text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def print_fn(results, niter, ncall, add_live_it=None,
dlogz=None, stop_val=None, nbatch=None,
logl_min=-np.inf, logl_max=np.inf):
"""
The default function used to print out results in real time.
Parameters
----------
results : tuple
Collection of variables output ... | [
"def",
"print_fn",
"(",
"results",
",",
"niter",
",",
"ncall",
",",
"add_live_it",
"=",
"None",
",",
"dlogz",
"=",
"None",
",",
"stop_val",
"=",
"None",
",",
"nbatch",
"=",
"None",
",",
"logl_min",
"=",
"-",
"np",
".",
"inf",
",",
"logl_max",
"=",
... | 36.441667 | 20.658333 |
def _setup_tunnel(
self):
"""
*setup ssh tunnel if required*
"""
from subprocess import Popen, PIPE, STDOUT
import pymysql as ms
# SETUP TUNNEL IF REQUIRED
if "ssh tunnel" in self.settings:
# TEST TUNNEL DOES NOT ALREADY EXIST
... | [
"def",
"_setup_tunnel",
"(",
"self",
")",
":",
"from",
"subprocess",
"import",
"Popen",
",",
"PIPE",
",",
"STDOUT",
"import",
"pymysql",
"as",
"ms",
"# SETUP TUNNEL IF REQUIRED",
"if",
"\"ssh tunnel\"",
"in",
"self",
".",
"settings",
":",
"# TEST TUNNEL DOES NOT A... | 39.978495 | 18.021505 |
def asList(self):
""" returns the value as the list object"""
return [self._red, self._green, self._blue, self._alpha] | [
"def",
"asList",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_red",
",",
"self",
".",
"_green",
",",
"self",
".",
"_blue",
",",
"self",
".",
"_alpha",
"]"
] | 44 | 15.666667 |
def mac_access_list_extended_hide_mac_acl_ext_seq_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
mac = ET.SubElement(config, "mac", xmlns="urn:brocade.com:mgmt:brocade-mac-access-list")
access_list = ET.SubElement(mac, "access-list")
exte... | [
"def",
"mac_access_list_extended_hide_mac_acl_ext_seq_action",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"mac",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"mac\"",
",",
"xmlns",
"=",... | 46.833333 | 14.777778 |
def start(self, hostname=None, port=None):
""" Spawns a new HTTP server, residing on defined hostname and port
:param hostname: the default hostname the server should listen on.
:param port: the default port of the server.
"""
if hostname is None:
hostname = settings.... | [
"def",
"start",
"(",
"self",
",",
"hostname",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"hostname",
"is",
"None",
":",
"hostname",
"=",
"settings",
".",
"settings",
"[",
"'mx_host'",
"]",
"if",
"port",
"is",
"None",
":",
"port",
"=",
"... | 60.617647 | 28.029412 |
def ignored_double_corner(
intersection, tangent_s, tangent_t, edge_nodes1, edge_nodes2
):
"""Check if an intersection is an "ignored" double corner.
.. note::
This is a helper used only by :func:`ignored_corner`, which in turn is
only used by :func:`classify_intersection`.
Helper for :... | [
"def",
"ignored_double_corner",
"(",
"intersection",
",",
"tangent_s",
",",
"tangent_t",
",",
"edge_nodes1",
",",
"edge_nodes2",
")",
":",
"# Compute the other edge for the ``s`` surface.",
"prev_index",
"=",
"(",
"intersection",
".",
"index_first",
"-",
"1",
")",
"%"... | 44.746988 | 22.493976 |
def generate_nucmer_commands(
filenames,
outdir=".",
nucmer_exe=pyani_config.NUCMER_DEFAULT,
filter_exe=pyani_config.FILTER_DEFAULT,
maxmatch=False,
):
"""Return a tuple of lists of NUCmer command-lines for ANIm
The first element is a list of NUCmer commands, the second a list
of delta_... | [
"def",
"generate_nucmer_commands",
"(",
"filenames",
",",
"outdir",
"=",
"\".\"",
",",
"nucmer_exe",
"=",
"pyani_config",
".",
"NUCMER_DEFAULT",
",",
"filter_exe",
"=",
"pyani_config",
".",
"FILTER_DEFAULT",
",",
"maxmatch",
"=",
"False",
",",
")",
":",
"nucmer_... | 38.387097 | 17.741935 |
def general_eq(a, b, attributes):
"""Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All other attributes are compared ... | [
"def",
"general_eq",
"(",
"a",
",",
"b",
",",
"attributes",
")",
":",
"try",
":",
"for",
"attr",
"in",
"attributes",
":",
"_a",
",",
"_b",
"=",
"getattr",
"(",
"a",
",",
"attr",
")",
",",
"getattr",
"(",
"b",
",",
"attr",
")",
"if",
"attr",
"in... | 36.807692 | 13.423077 |
def memoize(f):
""" Memoization decorator for a function taking one or more arguments. """
class memodict(dict):
def __getitem__(self, *key):
return dict.__getitem__(self, key)
def __missing__(self, key):
ret = self[key] = f(*key)
return ret
return memo... | [
"def",
"memoize",
"(",
"f",
")",
":",
"class",
"memodict",
"(",
"dict",
")",
":",
"def",
"__getitem__",
"(",
"self",
",",
"*",
"key",
")",
":",
"return",
"dict",
".",
"__getitem__",
"(",
"self",
",",
"key",
")",
"def",
"__missing__",
"(",
"self",
"... | 27.25 | 16.916667 |
def extract(self, *args):
"""
Extract a specific variable
"""
self.time = np.loadtxt(self.abspath,
skiprows=self._attributes['data_idx']+1,
unpack=True, usecols=(0,))
for variable_idx in args:
data ... | [
"def",
"extract",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"time",
"=",
"np",
".",
"loadtxt",
"(",
"self",
".",
"abspath",
",",
"skiprows",
"=",
"self",
".",
"_attributes",
"[",
"'data_idx'",
"]",
"+",
"1",
",",
"unpack",
"=",
"True",
... | 50.043478 | 16.478261 |
def lsm_var_to_grid(self, out_grid_file, lsm_data_var, gssha_convert_var, time_step=0, ascii_format='grass'):
"""This function takes array data and writes out a GSSHA ascii grid.
Parameters:
out_grid_file(str): Location of ASCII file to generate.
lsm_data_var(str or list): This ... | [
"def",
"lsm_var_to_grid",
"(",
"self",
",",
"out_grid_file",
",",
"lsm_data_var",
",",
"gssha_convert_var",
",",
"time_step",
"=",
"0",
",",
"ascii_format",
"=",
"'grass'",
")",
":",
"self",
".",
"_load_converted_gssha_data_from_lsm",
"(",
"gssha_convert_var",
",",
... | 51.596154 | 28.653846 |
def _get_merge_rules(properties, path=None):
"""
Yields merge rules as key-value pairs, in which the first element is a JSON path as a tuple, and the second element
is a list of merge properties whose values are `true`.
"""
if path is None:
path = ()
for key, value in properties.items()... | [
"def",
"_get_merge_rules",
"(",
"properties",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"(",
")",
"for",
"key",
",",
"value",
"in",
"properties",
".",
"items",
"(",
")",
":",
"new_path",
"=",
"path",
"+",
"("... | 55.030303 | 26.545455 |
def density_2d(self, x, y, Rs, rho0, r_trunc, center_x=0, center_y=0):
"""
projected two dimenstional NFW profile (kappa*Sigma_crit)
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization... | [
"def",
"density_2d",
"(",
"self",
",",
"x",
",",
"y",
",",
"Rs",
",",
"rho0",
",",
"r_trunc",
",",
"center_x",
"=",
"0",
",",
"center_y",
"=",
"0",
")",
":",
"x_",
"=",
"x",
"-",
"center_x",
"y_",
"=",
"y",
"-",
"center_y",
"R",
"=",
"np",
".... | 33.761905 | 12.904762 |
def cache_size(self, new_value):
'''
Set the cache size used to reduce the number of database
access operations.
'''
if type(new_value) == int and 0 < new_value:
if self._lemma_cache is not None:
self._lemma_cache = repoze.lru.LRUCache(new_value)
... | [
"def",
"cache_size",
"(",
"self",
",",
"new_value",
")",
":",
"if",
"type",
"(",
"new_value",
")",
"==",
"int",
"and",
"0",
"<",
"new_value",
":",
"if",
"self",
".",
"_lemma_cache",
"is",
"not",
"None",
":",
"self",
".",
"_lemma_cache",
"=",
"repoze",
... | 41.666667 | 19.444444 |
def reset(self):
"""
Resets the value of config item to its default value.
"""
old_value = self._value
old_raw_str_value = self.raw_str_value
self._value = not_set
self.raw_str_value = not_set
new_value = self._value
if old_value is not_set:
... | [
"def",
"reset",
"(",
"self",
")",
":",
"old_value",
"=",
"self",
".",
"_value",
"old_raw_str_value",
"=",
"self",
".",
"raw_str_value",
"self",
".",
"_value",
"=",
"not_set",
"self",
".",
"raw_str_value",
"=",
"not_set",
"new_value",
"=",
"self",
".",
"_va... | 27.48 | 15.48 |
def get_structdmtypes_for_python_typeorobject(typeorobj):
"""
Return structchar, dmtype for the python (or numpy)
type or object typeorobj.
For more complex types we only return the dm type
"""
# not isinstance is probably a bit more lenient than 'is'
# ie isinstance(x,str) is nicer than typ... | [
"def",
"get_structdmtypes_for_python_typeorobject",
"(",
"typeorobj",
")",
":",
"# not isinstance is probably a bit more lenient than 'is'",
"# ie isinstance(x,str) is nicer than type(x) is str.",
"# hence we use isinstance when available",
"if",
"isinstance",
"(",
"typeorobj",
",",
"typ... | 38.848485 | 17.212121 |
def deployed_resources(self, chalice_stage_name):
# type: (str) -> DeployedResources
"""Return resources associated with a given stage.
If a deployment to a given stage has never happened,
this method will return a value of None.
"""
# This is arguably the wrong level o... | [
"def",
"deployed_resources",
"(",
"self",
",",
"chalice_stage_name",
")",
":",
"# type: (str) -> DeployedResources",
"# This is arguably the wrong level of abstraction.",
"# We might be able to move this elsewhere.",
"deployed_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"s... | 44.714286 | 14.380952 |
def new_edge(self, node_a, node_b, cost=1):
"""Adds a new edge from node_a to node_b that has a cost.
Returns the edge id of the new edge."""
# Verify that both nodes exist in the graph
try:
self.nodes[node_a]
except KeyError:
raise NonexistentNodeError(n... | [
"def",
"new_edge",
"(",
"self",
",",
"node_a",
",",
"node_b",
",",
"cost",
"=",
"1",
")",
":",
"# Verify that both nodes exist in the graph",
"try",
":",
"self",
".",
"nodes",
"[",
"node_a",
"]",
"except",
"KeyError",
":",
"raise",
"NonexistentNodeError",
"(",... | 26.689655 | 17.37931 |
def set_attribute_mapping(resource_attr_a, resource_attr_b, **kwargs):
"""
Define one resource attribute from one network as being the same as
that from another network.
"""
user_id = kwargs.get('user_id')
ra_1 = get_resource_attribute(resource_attr_a)
ra_2 = get_resource_attribute(r... | [
"def",
"set_attribute_mapping",
"(",
"resource_attr_a",
",",
"resource_attr_b",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"ra_1",
"=",
"get_resource_attribute",
"(",
"resource_attr_a",
")",
"ra_2",
"=",
"ge... | 35.473684 | 22.105263 |
def main(): # pylint: disable-msg=R0912,R0915
"""Main."""
parser = optparse.OptionParser()
parser.usage = textwrap.dedent("""\
%prog {--run|--install_key|--dump_config} [options]
SSH command authenticator.
Used to restrict which commands can be run via trusted SSH keys.
""")
group = ... | [
"def",
"main",
"(",
")",
":",
"# pylint: disable-msg=R0912,R0915",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"usage",
"=",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\\\n %prog {--run|--install_key|--dump_config} [options]\n\n SSH command au... | 36.694215 | 15.85124 |
def get_pipeline(self, project, pipeline_id, revision=None):
"""GetPipeline.
[Preview API]
:param str project: Project ID or project name
:param int pipeline_id:
:param int revision:
:rtype: :class:`<Pipeline> <azure.devops.v5_1.pipelines.models.Pipeline>`
"""
... | [
"def",
"get_pipeline",
"(",
"self",
",",
"project",
",",
"pipeline_id",
",",
"revision",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize... | 49.545455 | 19.636364 |
def set_log_level(level):
"""
Sets the log level.
Lower log levels log more.
if level is 8, nothing is logged. If level is 0, everything is logged.
"""
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
return unity.set_log_level(level) | [
"def",
"set_log_level",
"(",
"level",
")",
":",
"from",
".",
".",
"_connect",
"import",
"main",
"as",
"_glconnect",
"unity",
"=",
"_glconnect",
".",
"get_unity",
"(",
")",
"return",
"unity",
".",
"set_log_level",
"(",
"level",
")"
] | 31.333333 | 10 |
def do_annealing_poly(start:Number, end:Number, pct:float, degree:Number)->Number:
"Helper function for `anneal_poly`."
return end + (start-end) * (1-pct)**degree | [
"def",
"do_annealing_poly",
"(",
"start",
":",
"Number",
",",
"end",
":",
"Number",
",",
"pct",
":",
"float",
",",
"degree",
":",
"Number",
")",
"->",
"Number",
":",
"return",
"end",
"+",
"(",
"start",
"-",
"end",
")",
"*",
"(",
"1",
"-",
"pct",
... | 56 | 16 |
def condensed_coords_within(pop, n):
"""Return indices into a condensed distance matrix for all
pairwise comparisons within the given population.
Parameters
----------
pop : array_like, int
Indices of samples or haplotypes within the population.
n : int
Size of the square matrix... | [
"def",
"condensed_coords_within",
"(",
"pop",
",",
"n",
")",
":",
"return",
"[",
"condensed_coords",
"(",
"i",
",",
"j",
",",
"n",
")",
"for",
"i",
",",
"j",
"in",
"itertools",
".",
"combinations",
"(",
"sorted",
"(",
"pop",
")",
",",
"2",
")",
"]"... | 26.578947 | 22.421053 |
def render_table(self, **kwargs):
"""Render the data as a html table"""
# Import here to avoid lxml import
try:
from pygal.table import Table
except ImportError:
raise ImportError('You must install lxml to use render table')
return Table(self).render(**kwa... | [
"def",
"render_table",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Import here to avoid lxml import",
"try",
":",
"from",
"pygal",
".",
"table",
"import",
"Table",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'You must install lxml to use rende... | 39.625 | 11 |
def find_data(folder):
""" Include everything in the folder """
for (path, directories, filenames) in os.walk(folder):
for filename in filenames:
yield os.path.join('..', path, filename) | [
"def",
"find_data",
"(",
"folder",
")",
":",
"for",
"(",
"path",
",",
"directories",
",",
"filenames",
")",
"in",
"os",
".",
"walk",
"(",
"folder",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"... | 42 | 10.8 |
def associate(self, model):
"""
Associate the model instance to the given parent.
:type model: orator.Model
:rtype: orator.Model
"""
self._parent.set_attribute(self._foreign_key, model.get_key())
self._parent.set_attribute(self._morph_type, model.get_morph_name(... | [
"def",
"associate",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"_parent",
".",
"set_attribute",
"(",
"self",
".",
"_foreign_key",
",",
"model",
".",
"get_key",
"(",
")",
")",
"self",
".",
"_parent",
".",
"set_attribute",
"(",
"self",
".",
"_morp... | 30.285714 | 20.571429 |
def find_cell_end(self, lines):
"""Return position of end of cell, and position
of first line after cell, and whether there was an
explicit end of cell marker"""
if self.cell_type == 'markdown':
# Empty cell "" or ''
if len(self.markdown_marker) <= 2:
... | [
"def",
"find_cell_end",
"(",
"self",
",",
"lines",
")",
":",
"if",
"self",
".",
"cell_type",
"==",
"'markdown'",
":",
"# Empty cell \"\" or ''",
"if",
"len",
"(",
"self",
".",
"markdown_marker",
")",
"<=",
"2",
":",
"if",
"len",
"(",
"lines",
")",
"==",
... | 43.87234 | 15.93617 |
def visual_callback_2d(background, fig=None):
"""
Returns a callback than can be passed as the argument `iter_callback`
of `morphological_geodesic_active_contour` and
`morphological_chan_vese` for visualizing the evolution
of the levelsets. Only works for 2D images.
Parameters
---------... | [
"def",
"visual_callback_2d",
"(",
"background",
",",
"fig",
"=",
"None",
")",
":",
"# Prepare the visual environment.",
"if",
"fig",
"is",
"None",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"fig",
".",
"clf",
"(",
")",
"ax1",
"=",
"fig",
".",
"ad... | 29.913043 | 19.391304 |
def exit_actor():
"""Intentionally exit the current actor.
This function is used to disconnect an actor and exit the worker.
Raises:
Exception: An exception is raised if this is a driver or this
worker is not an actor.
"""
worker = ray.worker.global_worker
if worker.mode ==... | [
"def",
"exit_actor",
"(",
")",
":",
"worker",
"=",
"ray",
".",
"worker",
".",
"global_worker",
"if",
"worker",
".",
"mode",
"==",
"ray",
".",
"WORKER_MODE",
"and",
"not",
"worker",
".",
"actor_id",
".",
"is_nil",
"(",
")",
":",
"# Disconnect the worker fro... | 38.409091 | 18.909091 |
def create_new_state_from_state_with_type(source_state, target_state_class):
"""The function duplicates/transforms a state to a new state type. If the source state type and the new state
type both are ContainerStates the new state will have not transitions to force the user to explicitly re-order
the logica... | [
"def",
"create_new_state_from_state_with_type",
"(",
"source_state",
",",
"target_state_class",
")",
":",
"current_state_is_container",
"=",
"isinstance",
"(",
"source_state",
",",
"ContainerState",
")",
"new_state_is_container",
"=",
"issubclass",
"(",
"target_state_class",
... | 54.297619 | 27.559524 |
def merge_split_adjustments_with_overwrites(
self,
pre,
post,
overwrites,
requested_split_adjusted_columns
):
"""
Merge split adjustments with the dict containing overwrites.
Parameters
----------
pre : dict[str -> dict[int -> list]]
... | [
"def",
"merge_split_adjustments_with_overwrites",
"(",
"self",
",",
"pre",
",",
"post",
",",
"overwrites",
",",
"requested_split_adjusted_columns",
")",
":",
"for",
"column_name",
"in",
"requested_split_adjusted_columns",
":",
"# We can do a merge here because the timestamps in... | 37.72093 | 15.72093 |
def infer_dm(self, m, s, ds):
"""Infer probable output from input x, y
"""
OptimizedInverseModel.infer_dm(self, ds)
if len(self.fmodel.dataset) == 0:
return [[0.0]*self.dim_out]
else:
_, index = self.fmodel.dataset.nn_dims(m, np.hstack((s, ds)), range(len(... | [
"def",
"infer_dm",
"(",
"self",
",",
"m",
",",
"s",
",",
"ds",
")",
":",
"OptimizedInverseModel",
".",
"infer_dm",
"(",
"self",
",",
"ds",
")",
"if",
"len",
"(",
"self",
".",
"fmodel",
".",
"dataset",
")",
"==",
"0",
":",
"return",
"[",
"[",
"0.0... | 44.304348 | 22.173913 |
def stop(self):
"""Stop subtasks and let run() finish."""
self._stop_event.set()
if self.select_greenlet is not None:
self.select_greenlet.kill()
self.select_greenlet.get()
gevent.sleep() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_stop_event",
".",
"set",
"(",
")",
"if",
"self",
".",
"select_greenlet",
"is",
"not",
"None",
":",
"self",
".",
"select_greenlet",
".",
"kill",
"(",
")",
"self",
".",
"select_greenlet",
".",
"get",
... | 34.428571 | 8 |
def unstack(self, column_names, new_column_name=None):
"""
Concatenate values from one or two columns into one column, grouping by
all other columns. The resulting column could be of type list, array or
dictionary. If ``column_names`` is a numeric column, the result will be of
a... | [
"def",
"unstack",
"(",
"self",
",",
"column_names",
",",
"new_column_name",
"=",
"None",
")",
":",
"if",
"(",
"type",
"(",
"column_names",
")",
"!=",
"str",
"and",
"len",
"(",
"column_names",
")",
"!=",
"2",
")",
":",
"raise",
"TypeError",
"(",
"\"'col... | 43.363636 | 25.090909 |
def registerAddon(cls, name, addon, force=False):
"""
Registers the inputted addon to the class.
:param name | <str>
addon | <variant>
"""
prop = '_{0}__addons'.format(cls.__name__)
cmds = getattr(cls, prop, {})
if name in c... | [
"def",
"registerAddon",
"(",
"cls",
",",
"name",
",",
"addon",
",",
"force",
"=",
"False",
")",
":",
"prop",
"=",
"'_{0}__addons'",
".",
"format",
"(",
"cls",
".",
"__name__",
")",
"cmds",
"=",
"getattr",
"(",
"cls",
",",
"prop",
",",
"{",
"}",
")"... | 29.52381 | 16.095238 |
def draw_geoscale(ax, minx=0, maxx=175):
"""
Draw geological epoch on million year ago (mya) scale.
"""
a, b = .1, .6 # Correspond to 200mya and 0mya
def cv(x): return b - (x - b) / (maxx - minx) * (b - a)
ax.plot((a, b), (.5, .5), "k-")
tick = .015
for mya in xrange(maxx - 25, 0, -25):... | [
"def",
"draw_geoscale",
"(",
"ax",
",",
"minx",
"=",
"0",
",",
"maxx",
"=",
"175",
")",
":",
"a",
",",
"b",
"=",
".1",
",",
".6",
"# Correspond to 200mya and 0mya",
"def",
"cv",
"(",
"x",
")",
":",
"return",
"b",
"-",
"(",
"x",
"-",
"b",
")",
"... | 40.166667 | 14.7 |
def create_factories(fs_provider, task_problem_types, hook_manager=None, course_class=Course, task_class=Task):
"""
Shorthand for creating Factories
:param fs_provider: A FileSystemProvider leading to the courses
:param hook_manager: an Hook Manager instance. If None, a new Hook Manager is created
:... | [
"def",
"create_factories",
"(",
"fs_provider",
",",
"task_problem_types",
",",
"hook_manager",
"=",
"None",
",",
"course_class",
"=",
"Course",
",",
"task_class",
"=",
"Task",
")",
":",
"if",
"hook_manager",
"is",
"None",
":",
"hook_manager",
"=",
"HookManager",... | 51.214286 | 29.357143 |
def nfa_to_dot(nfa: dict, name: str, path: str = './'):
""" Generates a DOT file and a relative SVG image in **path**
folder of the input NFA using graphviz library.
:param dict nfa: input NFA;
:param str name: string with the name of the output file;
:param str path: path where to save the DOT/SVG... | [
"def",
"nfa_to_dot",
"(",
"nfa",
":",
"dict",
",",
"name",
":",
"str",
",",
"path",
":",
"str",
"=",
"'./'",
")",
":",
"g",
"=",
"graphviz",
".",
"Digraph",
"(",
"format",
"=",
"'svg'",
")",
"fakes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(... | 37.166667 | 14.611111 |
def set_orders(self, object_pks):
"""
Perform a mass update of sort_orders across the full queryset.
Accepts a list, object_pks, of the intended order for the objects.
Works as follows:
- Compile a list of all sort orders in the queryset. Leave out anything that
isn't ... | [
"def",
"set_orders",
"(",
"self",
",",
"object_pks",
")",
":",
"objects_to_sort",
"=",
"self",
".",
"filter",
"(",
"pk__in",
"=",
"object_pks",
")",
"max_value",
"=",
"self",
".",
"model",
".",
"objects",
".",
"all",
"(",
")",
".",
"aggregate",
"(",
"m... | 51.044444 | 26.377778 |
def _process_thread(self, client):
"""Process a single client.
Args:
client: GRR client object to act on.
"""
file_list = self.files
if not file_list:
return
print('Filefinder to collect {0:d} items'.format(len(file_list)))
flow_action = flows_pb2.FileFinderAction(
acti... | [
"def",
"_process_thread",
"(",
"self",
",",
"client",
")",
":",
"file_list",
"=",
"self",
".",
"files",
"if",
"not",
"file_list",
":",
"return",
"print",
"(",
"'Filefinder to collect {0:d} items'",
".",
"format",
"(",
"len",
"(",
"file_list",
")",
")",
")",
... | 35.478261 | 16.608696 |
def _OpenFileObject(self, path_spec):
"""Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pysmraw.handle: a file-like object or None.
Raises:
PathSpecError: if the path specification is invalid.
"""
if not pat... | [
"def",
"_OpenFileObject",
"(",
"self",
",",
"path_spec",
")",
":",
"if",
"not",
"path_spec",
".",
"HasParent",
"(",
")",
":",
"raise",
"errors",
".",
"PathSpecError",
"(",
"'Unsupported path specification without parent.'",
")",
"parent_path_spec",
"=",
"path_spec",... | 33.926829 | 20.536585 |
def dict_matches_params_deep(params_dct, dct):
"""
Filters deeply by comparing dct to filter_dct's value at each depth. Whenever a mismatch occurs the whole
thing returns false
:param params_dct: dict matching any portion of dct. E.g. filter_dct = {foo: {bar: 1}} would allow
{foo: {bar: 1, car: 2}} ... | [
"def",
"dict_matches_params_deep",
"(",
"params_dct",
",",
"dct",
")",
":",
"def",
"recurse_if_param_exists",
"(",
"params",
",",
"key",
",",
"value",
")",
":",
"\"\"\"\n If a param[key] exists, recurse. Otherwise return True since there is no param to contest value\n ... | 40 | 23.178571 |
def _format_operation(operation, parameters=None):
"""Formats parameters in operation in way BigQuery expects.
:type: str
:param operation: A Google BigQuery query string.
:type: Mapping[str, Any] or Sequence[Any]
:param parameters: Optional parameter values.
:rtype: str
:returns: A forma... | [
"def",
"_format_operation",
"(",
"operation",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"return",
"operation",
"if",
"isinstance",
"(",
"parameters",
",",
"collections_abc",
".",
"Mapping",
")",
":",
"return",
"_format_op... | 32.681818 | 19.5 |
def htmIndex(ra,dec,htm_level=3):
"""Compute htm index of htm_level at position ra,dec"""
import re
if os.uname()[0] == "Linux": javabin = '/opt/java2/bin/java '
htm_level = htm_level
verc_htm_cmd = javabin+'-classpath /usr/cadc/misc/htm/htmIndex.jar edu.jhu.htm.app.lookup %s %s %s' % (htm_level, ra... | [
"def",
"htmIndex",
"(",
"ra",
",",
"dec",
",",
"htm_level",
"=",
"3",
")",
":",
"import",
"re",
"if",
"os",
".",
"uname",
"(",
")",
"[",
"0",
"]",
"==",
"\"Linux\"",
":",
"javabin",
"=",
"'/opt/java2/bin/java '",
"htm_level",
"=",
"htm_level",
"verc_ht... | 44.230769 | 20.153846 |
def main():
"""
The main() function handles command line arguments and maneuvers the cover
image generation.
"""
# Helper function.
def _draw_and_save(title, subtitle, author, filename):
"""
Draw a cover and write it to a file. Note that only PNG is supported.
"""
... | [
"def",
"main",
"(",
")",
":",
"# Helper function.",
"def",
"_draw_and_save",
"(",
"title",
",",
"subtitle",
",",
"author",
",",
"filename",
")",
":",
"\"\"\"\n Draw a cover and write it to a file. Note that only PNG is supported.\n \"\"\"",
"cover_image",
"=",
... | 42.945205 | 22.068493 |
def alphanumeric(text):
"""Make an ultra-safe, ASCII version a string.
For instance for use as a filename.
\w matches any alphanumeric character and the underscore."""
return "".join([c for c in text if re.match(r'\w', c)]) | [
"def",
"alphanumeric",
"(",
"text",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"text",
"if",
"re",
".",
"match",
"(",
"r'\\w'",
",",
"c",
")",
"]",
")"
] | 47 | 7.4 |
def transcribe(self, text, punctuation=True):
"""
Parameters:
:param text: str: The text to be transcribed
:param punctuation: bool: Retain punctuation
This module attempts to reconstruct the approximate phonology
of Old English.
The algorithm first trie... | [
"def",
"transcribe",
"(",
"self",
",",
"text",
",",
"punctuation",
"=",
"True",
")",
":",
"if",
"not",
"punctuation",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"[\\.\\\";\\,\\:\\[\\]\\(\\)!&?‘]\", ",
"\"",
", ",
"t",
"xt)",
"",
"text",
"=",
"text",
"."... | 38.381818 | 25 |
def fromFile(cls, filepath):
"""
Creates a proxy instance from the inputted registry file.
:param filepath | <str>
:return <PluginProxy> || None
"""
xdata = ElementTree.parse(nstr(filepath))
xroot = xdata.getroot()
# collect var... | [
"def",
"fromFile",
"(",
"cls",
",",
"filepath",
")",
":",
"xdata",
"=",
"ElementTree",
".",
"parse",
"(",
"nstr",
"(",
"filepath",
")",
")",
"xroot",
"=",
"xdata",
".",
"getroot",
"(",
")",
"# collect variable information",
"name",
"=",
"xroot",
".",
"ge... | 31.866667 | 14.711111 |
def _sparse_blockify(tuples, dtype=None):
""" return an array of blocks that potentially have different dtypes (and
are sparse)
"""
new_blocks = []
for i, names, array in tuples:
array = _maybe_to_sparse(array)
block = make_block(array, placement=[i])
new_blocks.append(block... | [
"def",
"_sparse_blockify",
"(",
"tuples",
",",
"dtype",
"=",
"None",
")",
":",
"new_blocks",
"=",
"[",
"]",
"for",
"i",
",",
"names",
",",
"array",
"in",
"tuples",
":",
"array",
"=",
"_maybe_to_sparse",
"(",
"array",
")",
"block",
"=",
"make_block",
"(... | 27.75 | 14.083333 |
def save(self, update_site=False, *args, **kwargs):
"""
Set the site to the current site when the record is first
created, or the ``update_site`` argument is explicitly set
to ``True``.
"""
if update_site or (self.id is None and self.site_id is None):
self.sit... | [
"def",
"save",
"(",
"self",
",",
"update_site",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"update_site",
"or",
"(",
"self",
".",
"id",
"is",
"None",
"and",
"self",
".",
"site_id",
"is",
"None",
")",
":",
"self",
"."... | 43.444444 | 14.333333 |
def __insert_action(self, revision):
"""
Handle the insert action type.
Creates new document to be created in this collection.
This allows you to stage a creation of an object
:param dict revision: The revision dictionary
"""
revision["patch"]["_id"] = ObjectI... | [
"def",
"__insert_action",
"(",
"self",
",",
"revision",
")",
":",
"revision",
"[",
"\"patch\"",
"]",
"[",
"\"_id\"",
"]",
"=",
"ObjectId",
"(",
"revision",
".",
"get",
"(",
"\"master_id\"",
")",
")",
"insert_response",
"=",
"yield",
"self",
".",
"collectio... | 30 | 22.352941 |
def poisson_random_measure(t, rate, rate_max):
"""A function that returns the arrival time of the next arrival for
a Poisson random measure.
Parameters
----------
t : float
The start time from which to simulate the next arrival time.
rate : function
The *intensity function* for ... | [
"def",
"poisson_random_measure",
"(",
"t",
",",
"rate",
",",
"rate_max",
")",
":",
"scale",
"=",
"1.0",
"/",
"rate_max",
"t",
"=",
"t",
"+",
"exponential",
"(",
"scale",
")",
"while",
"rate_max",
"*",
"uniform",
"(",
")",
">",
"rate",
"(",
"t",
")",
... | 32.253731 | 22.522388 |
def p_review_comment_1(self, p):
"""review_comment : REVIEW_COMMENT TEXT"""
try:
if six.PY2:
value = p[2].decode(encoding='utf-8')
else:
value = p[2]
self.builder.add_review_comment(self.document, value)
except CardinalityError:... | [
"def",
"p_review_comment_1",
"(",
"self",
",",
"p",
")",
":",
"try",
":",
"if",
"six",
".",
"PY2",
":",
"value",
"=",
"p",
"[",
"2",
"]",
".",
"decode",
"(",
"encoding",
"=",
"'utf-8'",
")",
"else",
":",
"value",
"=",
"p",
"[",
"2",
"]",
"self"... | 39.5 | 17 |
def get_activities(self, before=None, after=None, limit=None):
"""
Get activities for authenticated user sorted by newest first.
http://strava.github.io/api/v3/activities/
:param before: Result will start with activities whose start date is
before specified date... | [
"def",
"get_activities",
"(",
"self",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"before",
":",
"before",
"=",
"self",
".",
"_utc_datetime_to_epoch",
"(",
"before",
")",
"if",
"after",
":",
"after"... | 37.297297 | 23.351351 |
def GetPlatformRestrictions(campaign_feed):
"""Get the Platform Restrictions for a given Campaign Feed.
Args:
campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for.
Returns:
The Platform Restrictions for the given feed.
"""
platform_restrictions = None
if campaign_feed['matc... | [
"def",
"GetPlatformRestrictions",
"(",
"campaign_feed",
")",
":",
"platform_restrictions",
"=",
"None",
"if",
"campaign_feed",
"[",
"'matchingFunction'",
"]",
"[",
"'operator'",
"]",
"==",
"'AND'",
":",
"for",
"argument",
"in",
"campaign_feed",
"[",
"'matchingFuncti... | 38.347826 | 23.652174 |
def sample_conditional(self, y, t=None, size=None):
"""
Sample from the conditional (predictive) distribution
Note: this method scales as ``O(M^3)`` for large ``M``, where
``M == len(t)``.
Args:
y (array[n]): The observations at coordinates ``x`` from
... | [
"def",
"sample_conditional",
"(",
"self",
",",
"y",
",",
"t",
"=",
"None",
",",
"size",
"=",
"None",
")",
":",
"mu",
",",
"cov",
"=",
"self",
".",
"predict",
"(",
"y",
",",
"t",
",",
"return_cov",
"=",
"True",
")",
"return",
"np",
".",
"random",
... | 41.347826 | 24.130435 |
def results( self ):
"""Return a list of all the results currently available. This
excludes pending results. Results are returned as a single flat
list, so any repetition structure is lost.
:returns: a list of results"""
rs = []
for k in self._results.keys():
... | [
"def",
"results",
"(",
"self",
")",
":",
"rs",
"=",
"[",
"]",
"for",
"k",
"in",
"self",
".",
"_results",
".",
"keys",
"(",
")",
":",
"# filter out pending job ids, which can be anything except dicts",
"ars",
"=",
"[",
"res",
"for",
"res",
"in",
"self",
"."... | 41.5 | 19.916667 |
def parseArgv():
"""
Command line option parser.
"""
parser = OptionParser()
parser.usage = r""" cat <TEXT> | %prog [--unit <UNIT>] [--output <SA_FILE>]
Create the suffix array of TEXT with the processing UNIT and optionally store it in SA_FILE for subsequent use.
UNIT may be set to 'byte', 'charac... | [
"def",
"parseArgv",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
")",
"parser",
".",
"usage",
"=",
"r\"\"\" cat <TEXT> | %prog [--unit <UNIT>] [--output <SA_FILE>]\n\nCreate the suffix array of TEXT with the processing UNIT and optionally store it in SA_FILE for subsequent use.\nUN... | 52.350877 | 31.578947 |
def equals(series1, series2, ignore_order=False, ignore_index=False, all_close=False, _return_reason=False):
'''
Get whether 2 series are equal.
``NaN`` is considered equal to ``NaN`` and `None`.
Parameters
----------
series1 : pandas.Series
Series to compare.
series2 : pandas.Seri... | [
"def",
"equals",
"(",
"series1",
",",
"series2",
",",
"ignore_order",
"=",
"False",
",",
"ignore_index",
"=",
"False",
",",
"all_close",
"=",
"False",
",",
"_return_reason",
"=",
"False",
")",
":",
"result",
"=",
"_equals",
"(",
"series1",
",",
"series2",
... | 36.543478 | 27.456522 |
def _serialize_default(cls, obj):
"""
:type obj: int|str|bool|float|bytes|unicode|list|dict|object
:rtype: int|str|bool|list|dict
"""
if obj is None or cls._is_primitive(obj):
return obj
elif cls._is_bytes(obj):
return obj.decode()
elif t... | [
"def",
"_serialize_default",
"(",
"cls",
",",
"obj",
")",
":",
"if",
"obj",
"is",
"None",
"or",
"cls",
".",
"_is_primitive",
"(",
"obj",
")",
":",
"return",
"obj",
"elif",
"cls",
".",
"_is_bytes",
"(",
"obj",
")",
":",
"return",
"obj",
".",
"decode",... | 27.529412 | 14.470588 |
def to_csv(self):
"""
Renders a legend as a CSV string.
No arguments.
Returns:
str: The legend as a CSV.
"""
# We can't delegate this to Decor because we need to know the superset
# of all Decor properties. There may be lots of blanks.
header... | [
"def",
"to_csv",
"(",
"self",
")",
":",
"# We can't delegate this to Decor because we need to know the superset",
"# of all Decor properties. There may be lots of blanks.",
"header",
"=",
"[",
"]",
"component_header",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
":",
"for",
... | 33.347826 | 14.478261 |
def un(source, wrapper=list, error_bad_lines=True):
"""Parse a text stream to TSV
If the source is a string, it is converted to a line-iterable stream. If
it is a file handle or other object, we assume that we can iterate over
the lines in it.
The result is a generator, and what it contains depend... | [
"def",
"un",
"(",
"source",
",",
"wrapper",
"=",
"list",
",",
"error_bad_lines",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"six",
".",
"string_types",
")",
":",
"source",
"=",
"six",
".",
"StringIO",
"(",
"source",
")",
"# Prepare ... | 35.744186 | 22.069767 |
def transform_to_data_coordinates(obj, xdata, ydata):
"""The coordinates might not be in data coordinates, but could be sometimes in axes
coordinates. For example, the matplotlib command
axes.axvline(2)
will have the y coordinates set to 0 and 1, not to the limits. Therefore, a
two-stage transform... | [
"def",
"transform_to_data_coordinates",
"(",
"obj",
",",
"xdata",
",",
"ydata",
")",
":",
"if",
"obj",
".",
"axes",
"is",
"not",
"None",
"and",
"obj",
".",
"get_transform",
"(",
")",
"!=",
"obj",
".",
"axes",
".",
"transData",
":",
"points",
"=",
"nump... | 47.1875 | 15.9375 |
def get_ec_index(self, ec_handle):
'''Get the index of the execution context with the given handle.
@param ec_handle The handle of the execution context to look for.
@type ec_handle str
@return The index into the owned + participated arrays, suitable for
use in methods such as @... | [
"def",
"get_ec_index",
"(",
"self",
",",
"ec_handle",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"ii",
",",
"ec",
"in",
"enumerate",
"(",
"self",
".",
"owned_ecs",
")",
":",
"if",
"ec",
".",
"handle",
"==",
"ec_handle",
":",
"return",
"ii",... | 40.315789 | 19.789474 |
def write(self, buf, url):
"""Write buffer to storage at a given url"""
(store_name, path) = self._split_url(url)
adapter = self._create_adapter(store_name)
with adapter.open(path, 'wb') as f:
f.write(buf.encode()) | [
"def",
"write",
"(",
"self",
",",
"buf",
",",
"url",
")",
":",
"(",
"store_name",
",",
"path",
")",
"=",
"self",
".",
"_split_url",
"(",
"url",
")",
"adapter",
"=",
"self",
".",
"_create_adapter",
"(",
"store_name",
")",
"with",
"adapter",
".",
"open... | 42.166667 | 7.166667 |
def fit(self, X, y=None, input_type='data'):
"""
Fit the model from data in X.
Parameters
----------
input_type : string, one of: 'data', 'distance' or 'affinity'.
The values of input data X. (default = 'data')
X : array-like, shape (n_samples, n_features)
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"input_type",
"=",
"'data'",
")",
":",
"X",
"=",
"self",
".",
"_validate_input",
"(",
"X",
",",
"input_type",
")",
"self",
".",
"fit_geometry",
"(",
"X",
",",
"input_type",
")",
"rand... | 45.473684 | 22.947368 |
def write(self, data, debug_info=None):
"""
Write data to YHSM device.
"""
self.num_write_bytes += len(data)
if self.debug:
if not debug_info:
debug_info = str(len(data))
sys.stderr.write("%s: WRITE %s:\n%s\n" %(
self.__... | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"debug_info",
"=",
"None",
")",
":",
"self",
".",
"num_write_bytes",
"+=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"debug",
":",
"if",
"not",
"debug_info",
":",
"debug_info",
"=",
"str",
"(",
"len",
... | 32.857143 | 6.571429 |
def get_filelikeobject(filename: str = None,
blob: bytes = None) -> BinaryIO:
"""
Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob: for specifying via an in-memory ``bytes`` object
Retu... | [
"def",
"get_filelikeobject",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
")",
"->",
"BinaryIO",
":",
"if",
"not",
"filename",
"and",
"not",
"blob",
":",
"raise",
"ValueError",
"(",
"\"no filename and no blob\"",
")",
"... | 27.863636 | 17.045455 |
def load_pyproject_toml(
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
):
# type: (...) -> Optional[Tuple[List[str], str, List[str]]]
"""Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP ... | [
"def",
"load_pyproject_toml",
"(",
"use_pep517",
",",
"# type: Optional[bool]",
"pyproject_toml",
",",
"# type: str",
"setup_py",
",",
"# type: str",
"req_name",
"# type: str",
")",
":",
"# type: (...) -> Optional[Tuple[List[str], str, List[str]]]",
"has_pyproject",
"=",
"os",
... | 40.620438 | 20.948905 |
def from_client(cls, client):
"""
Constructs a configuration object from an existing client instance. If the client has already been created with
a configuration object, returns that instance.
:param client: Client object to derive the configuration from.
:type client: docker.cl... | [
"def",
"from_client",
"(",
"cls",
",",
"client",
")",
":",
"if",
"hasattr",
"(",
"client",
",",
"'client_configuration'",
")",
":",
"return",
"client",
".",
"client_configuration",
"kwargs",
"=",
"{",
"'client'",
":",
"client",
"}",
"for",
"attr",
"in",
"c... | 41.611111 | 13.611111 |
def set_contributor_details(self, contdetails):
""" Sets 'contributor_details' parameter used to enhance the \
contributors element of the status response to include \
the screen_name of the contributor. By default only \
the user_id of the contributor is included
:param contdet... | [
"def",
"set_contributor_details",
"(",
"self",
",",
"contdetails",
")",
":",
"if",
"not",
"isinstance",
"(",
"contdetails",
",",
"bool",
")",
":",
"raise",
"TwitterSearchException",
"(",
"1008",
")",
"self",
".",
"arguments",
".",
"update",
"(",
"{",
"'contr... | 46.8 | 17.533333 |
def map(self, key, value):
"""
Args:
key: Image name
value: Image as jpeg byte data
Yields:
A tuple in the form of (key, value)
key: Constant dummy value
value: (l2sqr_dist, value)
"""
try:
image = imfeat.re... | [
"def",
"map",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"try",
":",
"image",
"=",
"imfeat",
".",
"resize_image",
"(",
"imfeat",
".",
"image_fromstring",
"(",
"value",
",",
"{",
"'type'",
":",
"'numpy'",
",",
"'mode'",
":",
"'bgr'",
",",
"'dtyp... | 29.148148 | 17.666667 |
def send_mail(template_name, context, from_email, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
connection=None, **kwargs):
"""
Easy wrapper for sending a single email message to a recipient list using
django template system.
It works almost the sa... | [
"def",
"send_mail",
"(",
"template_name",
",",
"context",
",",
"from_email",
",",
"recipient_list",
",",
"fail_silently",
"=",
"False",
",",
"auth_user",
"=",
"None",
",",
"auth_password",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"*",
"*",
"kwargs",... | 34.234568 | 25.123457 |
def isTransiting(self):
""" Checks the the istransiting tag to see if the planet transits. Note that this only works as of catalogue
version ee12343381ae4106fd2db908e25ffc537a2ee98c (11th March 2014) where the istransiting tag was implemented
"""
try:
isTransiting = self.par... | [
"def",
"isTransiting",
"(",
"self",
")",
":",
"try",
":",
"isTransiting",
"=",
"self",
".",
"params",
"[",
"'istransiting'",
"]",
"except",
"KeyError",
":",
"return",
"False",
"if",
"isTransiting",
"==",
"'1'",
":",
"return",
"True",
"else",
":",
"return",... | 36.384615 | 21.384615 |
async def connect(self) -> Connection:
"""
Get or create a connection.
"""
if self._conn is None:
self._conn = await r.connect(host=self._host,
port=self._port,
db=self._db,
... | [
"async",
"def",
"connect",
"(",
"self",
")",
"->",
"Connection",
":",
"if",
"self",
".",
"_conn",
"is",
"None",
":",
"self",
".",
"_conn",
"=",
"await",
"r",
".",
"connect",
"(",
"host",
"=",
"self",
".",
"_host",
",",
"port",
"=",
"self",
".",
"... | 45.466667 | 13.6 |
def regional_maximum(image, mask = None, structure=None, ties_are_ok=False):
'''Return a binary mask containing only points that are regional maxima
image - image to be transformed
mask - mask of relevant pixels
structure - binary structure giving the neighborhood and connectivity
... | [
"def",
"regional_maximum",
"(",
"image",
",",
"mask",
"=",
"None",
",",
"structure",
"=",
"None",
",",
"ties_are_ok",
"=",
"False",
")",
":",
"global",
"eight_connect",
"if",
"not",
"ties_are_ok",
":",
"#",
"# Get an an initial pass with the ties.",
"#",
"result... | 47.218391 | 21.057471 |
def update(self, *args, **kw):
'''
Update the dictionary with items and names::
(items, names, **kw)
(dict, names, **kw)
(MIDict, names, **kw)
Optional positional argument ``names`` is only allowed when ``self.indices``
is empty (no indices are set y... | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
"and",
"self",
".",
"indices",
":",
"raise",
"ValueError",
"(",
"'Only one positional argument is allowed when the'",
"'index names are al... | 32.515152 | 20.818182 |
def read_config(cls, configparser):
"""Read configuration file options."""
config = dict()
section = cls.__name__
option = "prefixes"
if configparser.has_option(section, option):
value = configparser.get(section, option)
names = [x.strip().lower() for x in... | [
"def",
"read_config",
"(",
"cls",
",",
"configparser",
")",
":",
"config",
"=",
"dict",
"(",
")",
"section",
"=",
"cls",
".",
"__name__",
"option",
"=",
"\"prefixes\"",
"if",
"configparser",
".",
"has_option",
"(",
"section",
",",
"option",
")",
":",
"va... | 34.75 | 14.083333 |
def render(self, template, **kwargs):
"""Renders the template
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate`
and can also be modified by user accordingly.
... | [
"def",
"render",
"(",
"self",
",",
"template",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"temp",
"=",
"self",
".",
"environment",
".",
"get_template",
"(",
"template",
")",
"return",
"temp",
".",
"render",
"(",
"*",
"*",
"kwargs",
")",
"except",... | 37.512821 | 18.282051 |
def get_branch(self, i):
"""Gets a branch associated with leaf i. This will trace the tree
from the leaves down to the root, constructing a list of tuples that
represent the pairs of nodes all the way from leaf i to the root.
:param i: the leaf identifying the branch to retrieve
... | [
"def",
"get_branch",
"(",
"self",
",",
"i",
")",
":",
"branch",
"=",
"MerkleBranch",
"(",
"self",
".",
"order",
")",
"j",
"=",
"i",
"+",
"2",
"**",
"self",
".",
"order",
"-",
"1",
"for",
"k",
"in",
"range",
"(",
"0",
",",
"self",
".",
"order",
... | 37.888889 | 18.944444 |
def writeObject(self, obj, is_proxy=False):
"""
Writes an object to the stream.
"""
if self.use_proxies and not is_proxy:
self.writeProxy(obj)
return
self.stream.write(TYPE_OBJECT)
ref = self.context.getObjectReference(obj)
if ref != -1... | [
"def",
"writeObject",
"(",
"self",
",",
"obj",
",",
"is_proxy",
"=",
"False",
")",
":",
"if",
"self",
".",
"use_proxies",
"and",
"not",
"is_proxy",
":",
"self",
".",
"writeProxy",
"(",
"obj",
")",
"return",
"self",
".",
"stream",
".",
"write",
"(",
"... | 28.477778 | 20.9 |
def _other_to_lon(func):
"""Wrapper for casting Longitude operator arguments to Longitude"""
def func_other_to_lon(obj, other):
return func(obj, _maybe_cast_to_lon(other))
return func_other_to_lon | [
"def",
"_other_to_lon",
"(",
"func",
")",
":",
"def",
"func_other_to_lon",
"(",
"obj",
",",
"other",
")",
":",
"return",
"func",
"(",
"obj",
",",
"_maybe_cast_to_lon",
"(",
"other",
")",
")",
"return",
"func_other_to_lon"
] | 42.4 | 8.2 |
def get_top_war_clans(self, country_key='', **params: keys):
"""Get a list of top clans by war
location_id: Optional[str] = ''
A location ID or '' (global)
See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json
for a list of acceptable location ID... | [
"def",
"get_top_war_clans",
"(",
"self",
",",
"country_key",
"=",
"''",
",",
"*",
"*",
"params",
":",
"keys",
")",
":",
"url",
"=",
"self",
".",
"api",
".",
"TOP",
"+",
"'/war/'",
"+",
"str",
"(",
"country_key",
")",
"return",
"self",
".",
"_get_mode... | 42.521739 | 13.304348 |
def set_font_size(self, size):
"""Convenience method for just changing font size."""
if self.font.font_size == size:
pass
else:
self.font._set_size(size) | [
"def",
"set_font_size",
"(",
"self",
",",
"size",
")",
":",
"if",
"self",
".",
"font",
".",
"font_size",
"==",
"size",
":",
"pass",
"else",
":",
"self",
".",
"font",
".",
"_set_size",
"(",
"size",
")"
] | 33.5 | 10.166667 |
def _expectation(p, mean, none, kern, feat, nghp=None):
"""
Compute the expectation:
expectation[n] = <x_n K_{x_n, Z}>_p(x_n)
- K_{.,} :: Linear kernel
or the equivalent for MarkovGaussian
:return: NxDxM
"""
return tf.matrix_transpose(expectation(p, (kern, feat), mean)) | [
"def",
"_expectation",
"(",
"p",
",",
"mean",
",",
"none",
",",
"kern",
",",
"feat",
",",
"nghp",
"=",
"None",
")",
":",
"return",
"tf",
".",
"matrix_transpose",
"(",
"expectation",
"(",
"p",
",",
"(",
"kern",
",",
"feat",
")",
",",
"mean",
")",
... | 29.8 | 12.6 |
def set_items(self, items):
""" Defer until later so the view is only updated after all items
are added.
"""
self._pending_view_refreshes +=1
timed_call(self._pending_timeout, self._refresh_layout) | [
"def",
"set_items",
"(",
"self",
",",
"items",
")",
":",
"self",
".",
"_pending_view_refreshes",
"+=",
"1",
"timed_call",
"(",
"self",
".",
"_pending_timeout",
",",
"self",
".",
"_refresh_layout",
")"
] | 34.428571 | 12.714286 |
def _datapaths(self):
"""Returns a simple key-value map for easy access to data paths"""
paths = { }
try:
data = self._config['data']
for k in data:
paths[k] = data[k]['path']
except KeyError as e:
raise AitConfigMissing(e.message)
... | [
"def",
"_datapaths",
"(",
"self",
")",
":",
"paths",
"=",
"{",
"}",
"try",
":",
"data",
"=",
"self",
".",
"_config",
"[",
"'data'",
"]",
"for",
"k",
"in",
"data",
":",
"paths",
"[",
"k",
"]",
"=",
"data",
"[",
"k",
"]",
"[",
"'path'",
"]",
"e... | 32.692308 | 15.307692 |
def read_cell_array(fd, endian, header):
"""Read a cell array.
Returns an array with rows of the cell array.
"""
array = [list() for i in range(header['dims'][0])]
for row in range(header['dims'][0]):
for col in range(header['dims'][1]):
# read the matrix header and array
... | [
"def",
"read_cell_array",
"(",
"fd",
",",
"endian",
",",
"header",
")",
":",
"array",
"=",
"[",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"header",
"[",
"'dims'",
"]",
"[",
"0",
"]",
")",
"]",
"for",
"row",
"in",
"range",
"(",
"header",
... | 38.294118 | 8.294118 |
def notify_task(self, task_id, **kwargs):
"""
Notify PNC about a BPM task event. Accepts polymorphic JSON {\"eventType\": \"string\"} based on \"eventType\" field.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `cal... | [
"def",
"notify_task",
"(",
"self",
",",
"task_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"notify_task_with_http_info",
... | 43.28 | 19.84 |
def sodium_pad(s, blocksize):
"""
Pad the input bytearray ``s`` to a multiple of ``blocksize``
using the ISO/IEC 7816-4 algorithm
:param s: input bytes string
:type s: bytes
:param blocksize:
:type blocksize: int
:return: padded string
:rtype: bytes
"""
ensure(isinstance(s, ... | [
"def",
"sodium_pad",
"(",
"s",
",",
"blocksize",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"s",
",",
"bytes",
")",
",",
"raising",
"=",
"exc",
".",
"TypeError",
")",
"ensure",
"(",
"isinstance",
"(",
"blocksize",
",",
"integer_types",
")",
",",
"rais... | 30.653846 | 12.884615 |
def set_exc_info(self, exc_info):
"""Sets the exception information of a ``Future.``
Preserves tracebacks on Python 2.
.. versionadded:: 4.0
"""
self._exc_info = exc_info
self._log_traceback = True
if not _GC_CYCLE_FINALIZERS:
self._tb_logger = _Trac... | [
"def",
"set_exc_info",
"(",
"self",
",",
"exc_info",
")",
":",
"self",
".",
"_exc_info",
"=",
"exc_info",
"self",
".",
"_log_traceback",
"=",
"True",
"if",
"not",
"_GC_CYCLE_FINALIZERS",
":",
"self",
".",
"_tb_logger",
"=",
"_TracebackLogger",
"(",
"exc_info",... | 32.3 | 15.45 |
def smart_content_type_for_model(model):
"""
Returns the Django ContentType for a given model. If model is a proxy model, the proxy model's ContentType will
be returned. This differs from Django's standard behavior - the default behavior is to return the parent
ContentType for proxy models.
"""
... | [
"def",
"smart_content_type_for_model",
"(",
"model",
")",
":",
"try",
":",
"# noinspection PyPackageRequirements,PyUnresolvedReferences",
"from",
"django",
".",
"contrib",
".",
"contenttypes",
".",
"models",
"import",
"ContentType",
"except",
"ImportError",
":",
"print",
... | 43.5 | 25.944444 |
def lambda_handler(event, context):
'''Demonstrates a simple HTTP endpoint using API Gateway. You have full
access to the request and response payload, including headers and
status code.
TableName provided by template.yaml.
To scan a DynamoDB table, make a GET request with optional query string param... | [
"def",
"lambda_handler",
"(",
"event",
",",
"context",
")",
":",
"print",
"(",
"\"Received event: \"",
"+",
"json",
".",
"dumps",
"(",
"event",
",",
"indent",
"=",
"2",
")",
")",
"operations",
"=",
"{",
"'DELETE'",
":",
"lambda",
"dynamo",
",",
"x",
":... | 47 | 32.153846 |
def add_single_feature_methods(cls):
"""Custom decorator intended for :class:`~vision.helpers.VisionHelpers`.
This metaclass adds a `{feature}` method for every feature
defined on the Feature enum.
"""
# Sanity check: This only makes sense if we are building the GAPIC
# subclass and have enums ... | [
"def",
"add_single_feature_methods",
"(",
"cls",
")",
":",
"# Sanity check: This only makes sense if we are building the GAPIC",
"# subclass and have enums already attached.",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"\"enums\"",
")",
":",
"return",
"cls",
"# Add each single-fe... | 35.96875 | 19 |
def convert_to_xml(cls, value):
"""
Convert signed angle float like -42.42 to int 60000 per degree,
normalized to positive value.
"""
# modulo normalizes negative and >360 degree values
rot = int(round(value * cls.DEGREE_INCREMENTS)) % cls.THREE_SIXTY
return str(r... | [
"def",
"convert_to_xml",
"(",
"cls",
",",
"value",
")",
":",
"# modulo normalizes negative and >360 degree values",
"rot",
"=",
"int",
"(",
"round",
"(",
"value",
"*",
"cls",
".",
"DEGREE_INCREMENTS",
")",
")",
"%",
"cls",
".",
"THREE_SIXTY",
"return",
"str",
... | 39.5 | 14 |
def from_prefix(cls, container, prefix):
"""Create from prefix object."""
if prefix is None:
raise errors.NoObjectException
return cls(container,
name=prefix.name,
obj_type=cls.type_cls.SUBDIR) | [
"def",
"from_prefix",
"(",
"cls",
",",
"container",
",",
"prefix",
")",
":",
"if",
"prefix",
"is",
"None",
":",
"raise",
"errors",
".",
"NoObjectException",
"return",
"cls",
"(",
"container",
",",
"name",
"=",
"prefix",
".",
"name",
",",
"obj_type",
"=",... | 32.625 | 9.875 |
def get_token(self):
"""Get an authentication token."""
# Generate string formatted timestamps for not_before and not_after,
# for the lifetime specified in minutes.
now = datetime.datetime.utcnow()
# Start the not_before time x minutes in the past, to avoid clock skew
# ... | [
"def",
"get_token",
"(",
"self",
")",
":",
"# Generate string formatted timestamps for not_before and not_after,",
"# for the lifetime specified in minutes.",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"# Start the not_before time x minutes in the past, to av... | 44.536585 | 16.390244 |
def set_config_for_routing_entity(
self,
routing_entity: Union[web.Resource, web.StaticResource,
web.ResourceRoute],
config):
"""Record configuration for resource or it's route."""
if isinstance(routing_entity, (web.Resource, web.Sta... | [
"def",
"set_config_for_routing_entity",
"(",
"self",
",",
"routing_entity",
":",
"Union",
"[",
"web",
".",
"Resource",
",",
"web",
".",
"StaticResource",
",",
"web",
".",
"ResourceRoute",
"]",
",",
"config",
")",
":",
"if",
"isinstance",
"(",
"routing_entity",... | 40.478261 | 23.391304 |
def _add_document(self, doc_id, conn=None, nosave=False, score=1.0, payload=None,
replace=False, partial=False, language=None, **fields):
"""
Internal add_document used for both batch and single doc indexing
"""
if conn is None:
conn = self.redis
... | [
"def",
"_add_document",
"(",
"self",
",",
"doc_id",
",",
"conn",
"=",
"None",
",",
"nosave",
"=",
"False",
",",
"score",
"=",
"1.0",
",",
"payload",
"=",
"None",
",",
"replace",
"=",
"False",
",",
"partial",
"=",
"False",
",",
"language",
"=",
"None"... | 33.192308 | 16.230769 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.