text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _cancel_http(api_request, operation_name):
"""Cancel an operation using a JSON/HTTP client.
Args:
api_request (Callable): A callable used to make an API request. This
should generally be
:meth:`google.cloud._http.Connection.api_request`.
operation_name (str): The nam... | [
"def",
"_cancel_http",
"(",
"api_request",
",",
"operation_name",
")",
":",
"path",
"=",
"\"operations/{}:cancel\"",
".",
"format",
"(",
"operation_name",
")",
"api_request",
"(",
"method",
"=",
"\"POST\"",
",",
"path",
"=",
"path",
")"
] | 39.636364 | 0.002242 |
def memoize(fun):
"""A simple memoize decorator for functions supporting (hashable)
positional arguments.
It also provides a cache_clear() function for clearing the cache:
>>> @memoize
... def foo()
... return 1
...
>>> foo()
1
>>> foo.cache_clear()
>>>
"""
@... | [
"def",
"memoize",
"(",
"fun",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fun",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"(",
"args",
",",
"frozenset",
"(",
"sorted",
"(",
"kwargs",
".",
"items",... | 23 | 0.001391 |
def get_or_create_in_transaction(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False):
'''
Uses the SQLAlchemy model to retrieve an existing record based on the supplied field values or, if there is no
existing re... | [
"def",
"get_or_create_in_transaction",
"(",
"tsession",
",",
"model",
",",
"values",
",",
"missing_columns",
"=",
"[",
"]",
",",
"variable_columns",
"=",
"[",
"]",
",",
"updatable_columns",
"=",
"[",
"]",
",",
"only_use_supplied_columns",
"=",
"False",
",",
"r... | 57.703125 | 0.00852 |
def distance_to_current_waypoint():
"""
Gets distance in metres to the current waypoint.
It returns None for the first waypoint (Home location).
"""
nextwaypoint = vehicle.commands.next
if nextwaypoint==0:
return None
missionitem=vehicle.commands[nextwaypoint-1] #commands are zero i... | [
"def",
"distance_to_current_waypoint",
"(",
")",
":",
"nextwaypoint",
"=",
"vehicle",
".",
"commands",
".",
"next",
"if",
"nextwaypoint",
"==",
"0",
":",
"return",
"None",
"missionitem",
"=",
"vehicle",
".",
"commands",
"[",
"nextwaypoint",
"-",
"1",
"]",
"#... | 38.2 | 0.015332 |
def deletable(self):
"""True if the MessageHandler can be deleted."""
return bool(lib.EnvIsDefmessageHandlerDeletable(
self._env, self._cls, self._idx)) | [
"def",
"deletable",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"lib",
".",
"EnvIsDefmessageHandlerDeletable",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_cls",
",",
"self",
".",
"_idx",
")",
")"
] | 44.25 | 0.011111 |
def _get_connection_info():
"""Return a string with the connection info."""
info = 'Connection: %s,' % CONN.url
if CONN.creds is not None:
info += ' userid=%s,' % CONN.creds[0]
else:
info += ' no creds,'
info += ' cacerts=%s,' % ('sys-default' if CONN.ca_certs is None
... | [
"def",
"_get_connection_info",
"(",
")",
":",
"info",
"=",
"'Connection: %s,'",
"%",
"CONN",
".",
"url",
"if",
"CONN",
".",
"creds",
"is",
"not",
"None",
":",
"info",
"+=",
"' userid=%s,'",
"%",
"CONN",
".",
"creds",
"[",
"0",
"]",
"else",
":",
"info",... | 30.457143 | 0.000909 |
def check_limit(self, varname, vmin=None, vmax=None):
"""
Check if the variable values are within the limits.
Return False if fails.
"""
retval = True
assert varname in self.__dict__
if varname in self._algebs:
val = self.system.dae.y[self.__dict__[... | [
"def",
"check_limit",
"(",
"self",
",",
"varname",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"retval",
"=",
"True",
"assert",
"varname",
"in",
"self",
".",
"__dict__",
"if",
"varname",
"in",
"self",
".",
"_algebs",
":",
"val",
"="... | 33.780488 | 0.001404 |
def build_alpha_part(ruleset, root_node):
"""
Given a set of already adapted rules, build the alpha part of
the RETE network starting at `root_node`.
"""
# Adds a dummy rule with InitialFact as LHS for always generate
# the alpha part matching InitialFact(). This is need... | [
"def",
"build_alpha_part",
"(",
"ruleset",
",",
"root_node",
")",
":",
"# Adds a dummy rule with InitialFact as LHS for always generate",
"# the alpha part matching InitialFact(). This is needed for the",
"# CE using InitialFact",
"ruleset",
"=",
"ruleset",
".",
"copy",
"(",
")",
... | 40.986667 | 0.000635 |
def send_queued(processes=1, log_level=None):
"""
Sends out all queued mails that has scheduled_time less than now or None
"""
queued_emails = get_queued()
total_sent, total_failed = 0, 0
total_email = len(queued_emails)
logger.info('Started sending %s emails with %s processes.' %
... | [
"def",
"send_queued",
"(",
"processes",
"=",
"1",
",",
"log_level",
"=",
"None",
")",
":",
"queued_emails",
"=",
"get_queued",
"(",
")",
"total_sent",
",",
"total_failed",
"=",
"0",
",",
"0",
"total_email",
"=",
"len",
"(",
"queued_emails",
")",
"logger",
... | 32.325 | 0.000751 |
def set_relation_many_to_many(self, obj, field_name, objs):
"Set a many-to-many field on an object"
relation = getattr(obj, field_name)
if hasattr(relation, 'set'):
relation.set(objs) # Django 2.x
else:
setattr(obj, field_name, objs) | [
"def",
"set_relation_many_to_many",
"(",
"self",
",",
"obj",
",",
"field_name",
",",
"objs",
")",
":",
"relation",
"=",
"getattr",
"(",
"obj",
",",
"field_name",
")",
"if",
"hasattr",
"(",
"relation",
",",
"'set'",
")",
":",
"relation",
".",
"set",
"(",
... | 40.428571 | 0.010381 |
def render(self, *args, **kwargs):
"""Render widget and register it in Django's cache."""
output = super(HeavySelect2Mixin, self).render(*args, **kwargs)
self.set_to_cache()
return output | [
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"output",
"=",
"super",
"(",
"HeavySelect2Mixin",
",",
"self",
")",
".",
"render",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"set_to_cache",
"(",
... | 43 | 0.009132 |
def map_providers(self, query='list_nodes', cached=False):
'''
Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs
'''
if cached is True and query in self.__cached_provider_queries:
retur... | [
"def",
"map_providers",
"(",
"self",
",",
"query",
"=",
"'list_nodes'",
",",
"cached",
"=",
"False",
")",
":",
"if",
"cached",
"is",
"True",
"and",
"query",
"in",
"self",
".",
"__cached_provider_queries",
":",
"return",
"self",
".",
"__cached_provider_queries"... | 44.371429 | 0.00189 |
def publish(context):
"""Saves changes and sends them to GitHub"""
header('Recording changes...')
run('git add -A')
header('Displaying changes...')
run('git -c color.status=always status')
if not click.confirm('\nContinue publishing'):
run('git reset HEAD --')
abort(context)
... | [
"def",
"publish",
"(",
"context",
")",
":",
"header",
"(",
"'Recording changes...'",
")",
"run",
"(",
"'git add -A'",
")",
"header",
"(",
"'Displaying changes...'",
")",
"run",
"(",
"'git -c color.status=always status'",
")",
"if",
"not",
"click",
".",
"confirm",
... | 27.451613 | 0.001135 |
def from_pickle(path: Union[str, BinaryIO], check_version: bool = True) -> BELGraph:
"""Read a graph from a pickle file.
:param path: File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed.
:param bool check_version: Checks if the graph was produced by this version of PyBEL
"""
... | [
"def",
"from_pickle",
"(",
"path",
":",
"Union",
"[",
"str",
",",
"BinaryIO",
"]",
",",
"check_version",
":",
"bool",
"=",
"True",
")",
"->",
"BELGraph",
":",
"graph",
"=",
"nx",
".",
"read_gpickle",
"(",
"path",
")",
"raise_for_not_bel",
"(",
"graph",
... | 34.307692 | 0.008734 |
def HowDoI():
'''
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - These buttons will cause the form to return with... | [
"def",
"HowDoI",
"(",
")",
":",
"# ------- Make a new Window ------- #",
"sg",
".",
"ChangeLookAndFeel",
"(",
"'GreenTan'",
")",
"# give our form a spiffy set of colors",
"layout",
"=",
"[",
"[",
"sg",
".",
"Text",
"(",
"'Ask and your answer will appear here....'",
",",... | 59.296296 | 0.008909 |
def is_relevant(self, action, subject):
"""
Matches both the subject and action, not necessarily the conditions.
"""
return self.matches_action(action) and self.matches_subject(subject) | [
"def",
"is_relevant",
"(",
"self",
",",
"action",
",",
"subject",
")",
":",
"return",
"self",
".",
"matches_action",
"(",
"action",
")",
"and",
"self",
".",
"matches_subject",
"(",
"subject",
")"
] | 42.6 | 0.009217 |
def tdbr2EOL(td):
"""convert the <br/> in <td> block into line ending (EOL = \n)"""
for br in td.find_all("br"):
br.replace_with("\n")
txt = six.text_type(td) # make it back into test
# would be unicode(id) in python2
soup = BeautifulSoup(txt, 'lxml') # read it as a ... | [
"def",
"tdbr2EOL",
"(",
"td",
")",
":",
"for",
"br",
"in",
"td",
".",
"find_all",
"(",
"\"br\"",
")",
":",
"br",
".",
"replace_with",
"(",
"\"\\n\"",
")",
"txt",
"=",
"six",
".",
"text_type",
"(",
"td",
")",
"# make it back into test ",
"# would be unico... | 48.4 | 0.018256 |
def emit_iana_rels(rels_url):
'''Fetches the IANA link relation registry'''
text = requests.get(rels_url).text.encode('ascii', 'ignore')
xml = objectify.fromstring(text)
iana_rels = {str(rec.value): str(rec.description)
for rec in xml.registry.record}
keys = sorted(iana_rels)
pr... | [
"def",
"emit_iana_rels",
"(",
"rels_url",
")",
":",
"text",
"=",
"requests",
".",
"get",
"(",
"rels_url",
")",
".",
"text",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"xml",
"=",
"objectify",
".",
"fromstring",
"(",
"text",
")",
"iana_rels",
... | 40.181818 | 0.001105 |
def do_access_control(self):
"""`before_request` handler to check if user should be redirected to
login page."""
from abilian.services import get_service
if current_app.testing and current_app.config.get("NO_LOGIN"):
# Special case for tests
user = User.query.get... | [
"def",
"do_access_control",
"(",
"self",
")",
":",
"from",
"abilian",
".",
"services",
"import",
"get_service",
"if",
"current_app",
".",
"testing",
"and",
"current_app",
".",
"config",
".",
"get",
"(",
"\"NO_LOGIN\"",
")",
":",
"# Special case for tests",
"user... | 35.956522 | 0.001766 |
def apply_chord(self, header, partial_args, group_id, body, **options):
u"""
Instantiate a linking ChordData object before executing subtasks.
Parameters
----------
header: a list of incomplete subtask signatures, with partial
different-per-instance arguments... | [
"def",
"apply_chord",
"(",
"self",
",",
"header",
",",
"partial_args",
",",
"group_id",
",",
"body",
",",
"*",
"*",
"options",
")",
":",
"callback_entry",
"=",
"TaskMeta",
".",
"objects",
".",
"create",
"(",
"task_id",
"=",
"body",
".",
"id",
")",
"cho... | 45.785714 | 0.001528 |
def _extract_gaussian_gradient_magnitude(image, mask = slice(None), sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `gaussian_gradient_magnitude`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# determine gaussian kernel... | [
"def",
"_extract_gaussian_gradient_magnitude",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"sigma",
"=",
"1",
",",
"voxelspacing",
"=",
"None",
")",
":",
"# set voxel spacing",
"if",
"voxelspacing",
"is",
"None",
":",
"voxelspacing",
"=",
... | 40.166667 | 0.022312 |
def doExperiment(cellDimensions,
cellCoordinateOffsets,
numObjects,
featuresPerObject,
objectWidth,
numFeatures,
useTrace,
noiseFactor,
moduleNoiseFactor,
anchoringMet... | [
"def",
"doExperiment",
"(",
"cellDimensions",
",",
"cellCoordinateOffsets",
",",
"numObjects",
",",
"featuresPerObject",
",",
"objectWidth",
",",
"numFeatures",
",",
"useTrace",
",",
"noiseFactor",
",",
"moduleNoiseFactor",
",",
"anchoringMethod",
"=",
"\"narrowing\"",
... | 34.809524 | 0.011173 |
def get_tilt(dec_geo, inc_geo, dec_tilt, inc_tilt):
"""
Function to return the dip direction and dip that would yield the tilt
corrected direction if applied to the uncorrected direction (geographic
coordinates)
Parameters
----------
dec_geo : declination in geographic coordinates
inc_g... | [
"def",
"get_tilt",
"(",
"dec_geo",
",",
"inc_geo",
",",
"dec_tilt",
",",
"inc_tilt",
")",
":",
"# strike is horizontal line equidistant from two input directions",
"SCart",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"# cartesian coordites of Strike",
"SCart",
"[",
"2",... | 39.560976 | 0.000602 |
def insert_data_frame(col, df, int_col=None, binary_col=None, minimal_size=5):
"""Insert ``pandas.DataFrame``.
:param col: :class:`pymongo.collection.Collection` instance.
:param df: :class:`pandas.DataFrame` instance.
:param int_col: list of integer-type column.
:param binary_col: list of binary-t... | [
"def",
"insert_data_frame",
"(",
"col",
",",
"df",
",",
"int_col",
"=",
"None",
",",
"binary_col",
"=",
"None",
",",
"minimal_size",
"=",
"5",
")",
":",
"data",
"=",
"transform",
".",
"to_dict_list_generic_type",
"(",
"df",
",",
"int_col",
"=",
"int_col",
... | 46.25 | 0.001767 |
def do_load(self, design, init=False):
# type: (str, bool) -> None
"""Load a design name, running the child LoadHooks.
Args:
design: Name of the design json file, without extension
init: Passed to the LoadHook to tell the children if this is being
run at ... | [
"def",
"do_load",
"(",
"self",
",",
"design",
",",
"init",
"=",
"False",
")",
":",
"# type: (str, bool) -> None",
"if",
"design",
":",
"filename",
"=",
"self",
".",
"_validated_config_filename",
"(",
"design",
")",
"with",
"open",
"(",
"filename",
",",
"\"r\... | 42.636364 | 0.001563 |
def tick_all(self, times):
"""
Tick all the EWMAs for the given number of times
"""
for i in range(times):
for avg in (self.m1, self.m5, self.m15, self.day):
avg.tick() | [
"def",
"tick_all",
"(",
"self",
",",
"times",
")",
":",
"for",
"i",
"in",
"range",
"(",
"times",
")",
":",
"for",
"avg",
"in",
"(",
"self",
".",
"m1",
",",
"self",
".",
"m5",
",",
"self",
".",
"m15",
",",
"self",
".",
"day",
")",
":",
"avg",
... | 27.75 | 0.008734 |
def limited_to(self, left: Set[TLeft], right: Set[TRight]) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
"""Returns the induced subgraph where only the nodes from the given sets are included."""
return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 in left and n2 in right) | [
"def",
"limited_to",
"(",
"self",
",",
"left",
":",
"Set",
"[",
"TLeft",
"]",
",",
"right",
":",
"Set",
"[",
"TRight",
"]",
")",
"->",
"'BipartiteGraph[TLeft, TRight, TEdgeValue]'",
":",
"return",
"BipartiteGraph",
"(",
"(",
"(",
"n1",
",",
"n2",
")",
",... | 105.333333 | 0.015723 |
def on_purchase_completed(self, mapping={'payload': 'payload','name':'name','status':'status','token':'token'}, convert={}, default={}):
"""Decorator routes an Connections.Response to the wrapped function.
Request is sent when Alexa completes the purchase flow.
See https://developer.amazon.co... | [
"def",
"on_purchase_completed",
"(",
"self",
",",
"mapping",
"=",
"{",
"'payload'",
":",
"'payload'",
",",
"'name'",
":",
"'name'",
",",
"'status'",
":",
"'status'",
",",
"'token'",
":",
"'token'",
"}",
",",
"convert",
"=",
"{",
"}",
",",
"default",
"=",... | 44.310345 | 0.012186 |
def context_by_id(self, context_id, via_id=None, create=True, name=None):
"""
Messy factory/lookup function to find a context by its ID, or construct
it. This will eventually be replaced by a more sensible interface.
"""
context = self._context_by_id.get(context_id)
if co... | [
"def",
"context_by_id",
"(",
"self",
",",
"context_id",
",",
"via_id",
"=",
"None",
",",
"create",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"context",
"=",
"self",
".",
"_context_by_id",
".",
"get",
"(",
"context_id",
")",
"if",
"context",
":",... | 33.84 | 0.002299 |
def out_name(stem, timestep=None):
"""Return StagPy out file name.
Args:
stem (str): short description of file content.
timestep (int): timestep if relevant.
Returns:
str: the output file name.
Other Parameters:
conf.core.outname (str): the generic name stem, defaults ... | [
"def",
"out_name",
"(",
"stem",
",",
"timestep",
"=",
"None",
")",
":",
"if",
"timestep",
"is",
"not",
"None",
":",
"stem",
"=",
"(",
"stem",
"+",
"INT_FMT",
")",
".",
"format",
"(",
"timestep",
")",
"return",
"conf",
".",
"core",
".",
"outname",
"... | 27.058824 | 0.002101 |
def linear_regression(X, y, add_intercept=True, coef_only=False, alpha=0.05,
as_dataframe=True, remove_na=False):
"""(Multiple) Linear regression.
Parameters
----------
X : np.array or list
Predictor(s). Shape = (n_samples, n_features) or (n_samples,).
y : np.array or ... | [
"def",
"linear_regression",
"(",
"X",
",",
"y",
",",
"add_intercept",
"=",
"True",
",",
"coef_only",
"=",
"False",
",",
"alpha",
"=",
"0.05",
",",
"as_dataframe",
"=",
"True",
",",
"remove_na",
"=",
"False",
")",
":",
"# Extract names if X is a Dataframe or Se... | 31.897196 | 0.000142 |
def to_np(v):
'''returns an np.array object given an input of np.array, list, tuple, torch variable or tensor.'''
if isinstance(v, float): return np.array(v)
if isinstance(v, (np.ndarray, np.generic)): return v
if isinstance(v, (list,tuple)): return [to_np(o) for o in v]
if isinstance(v, Variable): ... | [
"def",
"to_np",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"float",
")",
":",
"return",
"np",
".",
"array",
"(",
"v",
")",
"if",
"isinstance",
"(",
"v",
",",
"(",
"np",
".",
"ndarray",
",",
"np",
".",
"generic",
")",
")",
":",
"re... | 47.5 | 0.024793 |
def create(name, profile):
'''
Create the named vm
CLI Example:
.. code-block:: bash
salt <minion-id> saltcloud.create webserver rackspace_centos_512
'''
cmd = 'salt-cloud --out json -p {0} {1}'.format(profile, name)
out = __salt__['cmd.run_stdout'](cmd, python_shell=False)
tr... | [
"def",
"create",
"(",
"name",
",",
"profile",
")",
":",
"cmd",
"=",
"'salt-cloud --out json -p {0} {1}'",
".",
"format",
"(",
"profile",
",",
"name",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
... | 23.647059 | 0.002392 |
def to_dense_one_hot(labels, class_count):
"""Converts a vector that specified one-hot per batch into a dense version.
Args:
labels: The labels input.
class_count: The number of classes as an int.
Returns:
One dense vector for each item in the batch.
Raises:
ValueError: If labels is not rank 1.... | [
"def",
"to_dense_one_hot",
"(",
"labels",
",",
"class_count",
")",
":",
"if",
"not",
"isinstance",
"(",
"class_count",
",",
"tf",
".",
"compat",
".",
"integral_types",
")",
":",
"raise",
"TypeError",
"(",
"'class_count must be an integer type.'",
")",
"if",
"lab... | 36.075 | 0.011471 |
def get_facts(self):
"""Return a set of facts from the devices."""
# default values.
vendor = u'Cisco'
uptime = -1
serial_number, fqdn, os_version, hostname, domain_name = ('',) * 5
# obtain output from device
show_ver = self.device.send_command('show version')
... | [
"def",
"get_facts",
"(",
"self",
")",
":",
"# default values.",
"vendor",
"=",
"u'Cisco'",
"uptime",
"=",
"-",
"1",
"serial_number",
",",
"fqdn",
",",
"os_version",
",",
"hostname",
",",
"domain_name",
"=",
"(",
"''",
",",
")",
"*",
"5",
"# obtain output f... | 37.34375 | 0.001223 |
def discover_datasource_columns(datastore_str, datasource_id):
""" Loop through the datastore's datasources to find
the datasource identified by datasource_id, return
the matching datasource's columns. """
datastore = DataStore(datastore_str)
datasource = datastore.get_datasource(datasource_id)
... | [
"def",
"discover_datasource_columns",
"(",
"datastore_str",
",",
"datasource_id",
")",
":",
"datastore",
"=",
"DataStore",
"(",
"datastore_str",
")",
"datasource",
"=",
"datastore",
".",
"get_datasource",
"(",
"datasource_id",
")",
"if",
"datasource",
".",
"type",
... | 41.1 | 0.002381 |
def on_timeout(limit, handler=handler_func, hint=None):
"""
指定した実行時間に終了しなかった場合、handlerをhint/limitを引数にして呼び出します
@on_timeout(limit=3600, handler=notify_func, hint=u'長い計算')
def long_time_function():
"""
def notify_handler(signum, frame):
handler("'%s' is not finished in %d second(s)." % (hin... | [
"def",
"on_timeout",
"(",
"limit",
",",
"handler",
"=",
"handler_func",
",",
"hint",
"=",
"None",
")",
":",
"def",
"notify_handler",
"(",
"signum",
",",
"frame",
")",
":",
"handler",
"(",
"\"'%s' is not finished in %d second(s).\"",
"%",
"(",
"hint",
",",
"l... | 35.052632 | 0.001462 |
def pop():
"""Remove instance from instance list"""
pid = os.getpid()
thread = threading.current_thread()
Wdb._instances.pop((pid, thread)) | [
"def",
"pop",
"(",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"thread",
"=",
"threading",
".",
"current_thread",
"(",
")",
"Wdb",
".",
"_instances",
".",
"pop",
"(",
"(",
"pid",
",",
"thread",
")",
")"
] | 33.4 | 0.011696 |
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd... | [
"def",
"purge",
"(",
"name",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_uninstall",
"(",
"action",
"=",
"'purge'",
",",
"name",
"=",
"name",
",",
"pkgs",
"=",
"pkgs",
",",
"*",
"*",
"kwargs",
")"
] | 36.761905 | 0.001893 |
def _construct_schema(elements, nsmap):
"""Consruct fiona schema based on given elements
:param list Element: list of elements
:param dict nsmap: namespace map
:return dict: schema
"""
schema = {
'properties': {},
'geometry': None
}
schema_key = None
gml_key = Non... | [
"def",
"_construct_schema",
"(",
"elements",
",",
"nsmap",
")",
":",
"schema",
"=",
"{",
"'properties'",
":",
"{",
"}",
",",
"'geometry'",
":",
"None",
"}",
"schema_key",
"=",
"None",
"gml_key",
"=",
"None",
"# if nsmap is defined, use it",
"if",
"nsmap",
":... | 28.303571 | 0.00061 |
def get_expiration_seconds_v4(expiration):
"""Convert 'expiration' to a number of seconds offset from the current time.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration ... | [
"def",
"get_expiration_seconds_v4",
"(",
"expiration",
")",
":",
"if",
"not",
"isinstance",
"(",
"expiration",
",",
"_EXPIRATION_TYPES",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected an integer timestamp, datetime, or \"",
"\"timedelta. Got %s\"",
"%",
"type",
"(",
"... | 32.175 | 0.002262 |
def zero_d_graph_to_molecule_graph(bonded_structure, graph):
"""
Converts a zero-dimensional networkx Graph object into a MoleculeGraph.
Implements a similar breadth-first search to that in
calculate_dimensionality_of_site().
Args:
bonded_structure (StructureGraph): A structure with bonds,... | [
"def",
"zero_d_graph_to_molecule_graph",
"(",
"bonded_structure",
",",
"graph",
")",
":",
"import",
"networkx",
"as",
"nx",
"seen_indices",
"=",
"[",
"]",
"sites",
"=",
"[",
"]",
"start_index",
"=",
"list",
"(",
"graph",
".",
"nodes",
"(",
")",
")",
"[",
... | 38.163265 | 0.000521 |
def _array(fn, cls, genelist, **kwargs):
"""
Returns a "meta-feature" array, with len(genelist) rows and `bins`
cols. Each row contains the number of reads falling in each bin of
that row's modified feature.
"""
reader = cls(fn)
_local_coverage_func = cls.local_coverage
biglist = []
... | [
"def",
"_array",
"(",
"fn",
",",
"cls",
",",
"genelist",
",",
"*",
"*",
"kwargs",
")",
":",
"reader",
"=",
"cls",
"(",
"fn",
")",
"_local_coverage_func",
"=",
"cls",
".",
"local_coverage",
"biglist",
"=",
"[",
"]",
"if",
"'bins'",
"in",
"kwargs",
":"... | 32.9 | 0.001477 |
def read(cls, source, format=None, coalesce=False, **kwargs):
# pylint: disable=redefined-builtin
"""Read segments from file into a `SegmentList`
Parameters
----------
filename : `str`
path of file to read
format : `str`, optional
source format i... | [
"def",
"read",
"(",
"cls",
",",
"source",
",",
"format",
"=",
"None",
",",
"coalesce",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=redefined-builtin",
"def",
"combiner",
"(",
"listofseglists",
")",
":",
"\"\"\"Combine `SegmentList` from e... | 33.421053 | 0.002295 |
def AlternatesGroup(expressions, final_function, name=""):
""" Group expressions using the OR character ``|``
>>> from collections import namedtuple
>>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None)
>>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah')
>>> gro... | [
"def",
"AlternatesGroup",
"(",
"expressions",
",",
"final_function",
",",
"name",
"=",
"\"\"",
")",
":",
"inbetweens",
"=",
"[",
"\"|\"",
"]",
"*",
"(",
"len",
"(",
"expressions",
")",
"+",
"1",
")",
"inbetweens",
"[",
"0",
"]",
"=",
"\"\"",
"inbetween... | 41.214286 | 0.001695 |
def compile_intermediate_cpfs(self,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[Noise] = None) -> List[CPFPair]:
'''Compiles the intermediate fluent CPFs given the current ... | [
"def",
"compile_intermediate_cpfs",
"(",
"self",
",",
"scope",
":",
"Dict",
"[",
"str",
",",
"TensorFluent",
"]",
",",
"batch_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"noise",
":",
"Optional",
"[",
"Noise",
"]",
"=",
"None",
")",
"->"... | 42.310345 | 0.008765 |
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classe... | [
"def",
"get_context",
"(",
"app",
",",
"package",
",",
"module",
",",
"fullname",
")",
":",
"var",
"=",
"{",
"'package'",
":",
"package",
",",
"'module'",
":",
"module",
",",
"'fullname'",
":",
"fullname",
"}",
"logger",
".",
"debug",
"(",
"'Creating con... | 37.833333 | 0.001431 |
def power_off(self, timeout_sec=TIMEOUT_SEC):
"""Power off Bluetooth."""
# Turn off bluetooth.
self._powered_off.clear()
IOBluetoothPreferenceSetControllerPowerState(0)
if not self._powered_off.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting for adapte... | [
"def",
"power_off",
"(",
"self",
",",
"timeout_sec",
"=",
"TIMEOUT_SEC",
")",
":",
"# Turn off bluetooth.",
"self",
".",
"_powered_off",
".",
"clear",
"(",
")",
"IOBluetoothPreferenceSetControllerPowerState",
"(",
"0",
")",
"if",
"not",
"self",
".",
"_powered_off"... | 47.285714 | 0.008902 |
def get_raw_input(description, default=False):
"""Get user input from the command line via raw_input / input.
description (unicode): Text to display before prompt.
default (unicode or False/None): Default value to display with prompt.
RETURNS (unicode): User input.
"""
additional = ' (default: ... | [
"def",
"get_raw_input",
"(",
"description",
",",
"default",
"=",
"False",
")",
":",
"additional",
"=",
"' (default: %s)'",
"%",
"default",
"if",
"default",
"else",
"''",
"prompt",
"=",
"' %s%s: '",
"%",
"(",
"description",
",",
"additional",
")",
"user_inpu... | 41 | 0.002169 |
def terminate(self):
"""Terminate all connections in the pool."""
if self._closed:
return
self._check_init()
for ch in self._holders:
ch.terminate()
self._closed = True | [
"def",
"terminate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"self",
".",
"_check_init",
"(",
")",
"for",
"ch",
"in",
"self",
".",
"_holders",
":",
"ch",
".",
"terminate",
"(",
")",
"self",
".",
"_closed",
"=",
"True"
] | 28.125 | 0.008621 |
def bracket_split(source, brackets=('()', '{}', '[]'), strip=False):
"""DOES NOT RETURN EMPTY STRINGS (can only return empty bracket content if strip=True)"""
starts = [e[0] for e in brackets]
in_bracket = 0
n = 0
last = 0
while n < len(source):
e = source[n]
if not in_bracket an... | [
"def",
"bracket_split",
"(",
"source",
",",
"brackets",
"=",
"(",
"'()'",
",",
"'{}'",
",",
"'[]'",
")",
",",
"strip",
"=",
"False",
")",
":",
"starts",
"=",
"[",
"e",
"[",
"0",
"]",
"for",
"e",
"in",
"brackets",
"]",
"in_bracket",
"=",
"0",
"n",... | 33.92 | 0.002294 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkersRealTimeStatisticsContext for this WorkersRealTimeStatisticsInstance
:rtype: twilio.rest.t... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"WorkersRealTimeStatisticsContext",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_si... | 45.928571 | 0.009146 |
def create_list(list_type):
"""
Based on the passed in list_type create a list objects (ol/ul). In the
future this function will also deal with what the numbering of an ordered
list should look like.
"""
list_types = {
'bullet': 'ul',
}
el = etree.Element(list_types.get(list_type... | [
"def",
"create_list",
"(",
"list_type",
")",
":",
"list_types",
"=",
"{",
"'bullet'",
":",
"'ul'",
",",
"}",
"el",
"=",
"etree",
".",
"Element",
"(",
"list_types",
".",
"get",
"(",
"list_type",
",",
"'ol'",
")",
")",
"# These are the supported list style typ... | 35.535714 | 0.000978 |
def wrap_json(cls, json):
"""Create a Channel instance for the given json
:param json: the dict with the information of the channel
:type json: :class:`dict`
:returns: the new channel instance
:rtype: :class:`Channel`
:raises: None
"""
c = Channel(name=js... | [
"def",
"wrap_json",
"(",
"cls",
",",
"json",
")",
":",
"c",
"=",
"Channel",
"(",
"name",
"=",
"json",
".",
"get",
"(",
"'name'",
")",
",",
"status",
"=",
"json",
".",
"get",
"(",
"'status'",
")",
",",
"displayname",
"=",
"json",
".",
"get",
"(",
... | 41.12 | 0.001901 |
def gnuplot_2d(x, y, filename, title='', x_label='', y_label=''):
'''
Function to produce a general 2D plot.
Args:
x (list): x points.
y (list): y points.
filename (str): Filename of the output image.
title (str): Title of the plot. Default is '' (no title).
x_label... | [
"def",
"gnuplot_2d",
"(",
"x",
",",
"y",
",",
"filename",
",",
"title",
"=",
"''",
",",
"x_label",
"=",
"''",
",",
"y_label",
"=",
"''",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
"!="... | 23.860465 | 0.001873 |
def save(self, request):
"""
Saves a new comment and sends any notification emails.
"""
comment = self.get_comment_object()
obj = comment.content_object
if request.user.is_authenticated():
comment.user = request.user
comment.by_author = request.user ==... | [
"def",
"save",
"(",
"self",
",",
"request",
")",
":",
"comment",
"=",
"self",
".",
"get_comment_object",
"(",
")",
"obj",
"=",
"comment",
".",
"content_object",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"comment",
".",
"user",... | 42.404762 | 0.001098 |
def draw_tree(t, df, size=10, ratio=0.6, precision=0):
""" Draws a representation of a random forest in IPython.
Parameters:
-----------
t: The tree you wish to draw
df: The data used to train the tree. This is used to get the names of the features.
"""
s=export_graphviz(t, out_file=None, fe... | [
"def",
"draw_tree",
"(",
"t",
",",
"df",
",",
"size",
"=",
"10",
",",
"ratio",
"=",
"0.6",
",",
"precision",
"=",
"0",
")",
":",
"s",
"=",
"export_graphviz",
"(",
"t",
",",
"out_file",
"=",
"None",
",",
"feature_names",
"=",
"df",
".",
"columns",
... | 49 | 0.009107 |
def _spec(self, name):
"Return the named spec."
for s in self._framespec:
if s.name == name:
return s
raise ValueError("Unknown spec: " + name) | [
"def",
"_spec",
"(",
"self",
",",
"name",
")",
":",
"for",
"s",
"in",
"self",
".",
"_framespec",
":",
"if",
"s",
".",
"name",
"==",
"name",
":",
"return",
"s",
"raise",
"ValueError",
"(",
"\"Unknown spec: \"",
"+",
"name",
")"
] | 31.666667 | 0.010256 |
def possible_params(self):
""" Used when assuming params is a list. """
return self.params if isinstance(self.params, list) else [self.params] | [
"def",
"possible_params",
"(",
"self",
")",
":",
"return",
"self",
".",
"params",
"if",
"isinstance",
"(",
"self",
".",
"params",
",",
"list",
")",
"else",
"[",
"self",
".",
"params",
"]"
] | 52 | 0.012658 |
def plot_word(self,position):
'''Blits a rendered word on to the main display surface'''
posrectangle = pygame.Rect(position,self.word_size)
self.used_pos.append(posrectangle)
self.cloud.blit(self.rendered_word,position) | [
"def",
"plot_word",
"(",
"self",
",",
"position",
")",
":",
"posrectangle",
"=",
"pygame",
".",
"Rect",
"(",
"position",
",",
"self",
".",
"word_size",
")",
"self",
".",
"used_pos",
".",
"append",
"(",
"posrectangle",
")",
"self",
".",
"cloud",
".",
"b... | 49.6 | 0.019841 |
def execute_greenlet_async(func, *args, **kwargs):
"""
Executes `func` in a separate greenlet in the same process. Memory and other
resources are available (e.g. TCP connections etc.) `args` and `kwargs` are
passed to `func`.
"""
global _GREENLET_EXECUTOR
if _GREENLET_EXECUTOR is None:
_GREENLET_EXECU... | [
"def",
"execute_greenlet_async",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_GREENLET_EXECUTOR",
"if",
"_GREENLET_EXECUTOR",
"is",
"None",
":",
"_GREENLET_EXECUTOR",
"=",
"GreenletExecutor",
"(",
"num_greenlets",
"=",
"settings",
... | 40.454545 | 0.010989 |
def simulate(s0, transmat, steps=1):
"""Simulate the next state
Parameters
----------
s0 : ndarray
Vector with state variables at t=0
transmat : ndarray
The estimated transition/stochastic matrix.
steps : int
(Default: 1) The number of steps to simulate model outputs a... | [
"def",
"simulate",
"(",
"s0",
",",
"transmat",
",",
"steps",
"=",
"1",
")",
":",
"# Single-Step simulation",
"if",
"steps",
"==",
"1",
":",
"return",
"np",
".",
"dot",
"(",
"s0",
",",
"transmat",
")",
"# Multi-Step simulation",
"out",
"=",
"np",
".",
"... | 26.361111 | 0.001016 |
def recache(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
o=i.get('out','')
# Listing all repos
r=ck.access({'action'... | [
"def",
"recache",
"(",
"i",
")",
":",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"# Listing all repos",
"r",
"=",
"ck",
".",
"access",
"(",
"{",
"'action'",
":",
"'list'",
",",
"'module_uoa'",
":",
"ck",
".",
"cfg",
"[",
"'repo_name'"... | 31.175439 | 0.036815 |
def auth_stage2(self,stanza):
"""Handle the first stage authentication response (result of the <iq
type="get"/>).
[client only]"""
self.lock.acquire()
try:
self.__logger.debug("Procesing auth response...")
self.available_auth_methods=[]
if (st... | [
"def",
"auth_stage2",
"(",
"self",
",",
"stanza",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"Procesing auth response...\"",
")",
"self",
".",
"available_auth_methods",
"=",
"[",
"]",
... | 41.529412 | 0.015235 |
def read_bytes(self, count):
"""Read count number of bytes."""
if self.pos + count > self.remaining_length:
return NC.ERR_PROTOCOL, None
ba = bytearray(count)
for x in xrange(0, count):
ba[x] = self.payload[self.pos]
self.pos += 1
... | [
"def",
"read_bytes",
"(",
"self",
",",
"count",
")",
":",
"if",
"self",
".",
"pos",
"+",
"count",
">",
"self",
".",
"remaining_length",
":",
"return",
"NC",
".",
"ERR_PROTOCOL",
",",
"None",
"ba",
"=",
"bytearray",
"(",
"count",
")",
"for",
"x",
"in"... | 30.909091 | 0.011429 |
def not_empty(_object):
"""
Validates the given input (has to be a valid data structure) is empty.
Input *has* to be one of: `list`, `dict`, or `string`.
It is specially useful when most of the validators being created are
dealing with data structures that should not be empty.
"""
if is_cal... | [
"def",
"not_empty",
"(",
"_object",
")",
":",
"if",
"is_callable",
"(",
"_object",
")",
":",
"_validator",
"=",
"_object",
"@",
"wraps",
"(",
"_validator",
")",
"@",
"instance_of",
"(",
")",
"def",
"decorated",
"(",
"value",
")",
":",
"ensure",
"(",
"v... | 34.142857 | 0.001357 |
def enable(self, msgid, scope="package", line=None, ignore_unknown=False):
"""reenable message of the given id"""
self._set_msg_status(
msgid, enable=True, scope=scope, line=line, ignore_unknown=ignore_unknown
)
self._register_by_id_managed_msg(msgid, line, is_disabled=False) | [
"def",
"enable",
"(",
"self",
",",
"msgid",
",",
"scope",
"=",
"\"package\"",
",",
"line",
"=",
"None",
",",
"ignore_unknown",
"=",
"False",
")",
":",
"self",
".",
"_set_msg_status",
"(",
"msgid",
",",
"enable",
"=",
"True",
",",
"scope",
"=",
"scope",... | 52.5 | 0.009375 |
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 | 0.002193 |
def __dumptable(self, table):
""" Dumps table on screen
for debugging purposes
"""
for x in table.table.keys():
sys.stdout.write("{0}\t<--- {1} {2}".format(x, table[x], type(table[x])))
if isinstance(table[x], ID):
sys.stdout(" {0}".format(table[x]... | [
"def",
"__dumptable",
"(",
"self",
",",
"table",
")",
":",
"for",
"x",
"in",
"table",
".",
"table",
".",
"keys",
"(",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"{0}\\t<--- {1} {2}\"",
".",
"format",
"(",
"x",
",",
"table",
"[",
"x",
"]",... | 39.555556 | 0.008242 |
def popular(self, period=DAILY):
'''
Get popular songs.
:param period: time period
:rtype: a generator generates :class:`Song` objects
Time periods:
+---------------------------------+-----------------------------------+
| Constant | Mean... | [
"def",
"popular",
"(",
"self",
",",
"period",
"=",
"DAILY",
")",
":",
"songs",
"=",
"self",
".",
"connection",
".",
"request",
"(",
"'popularGetSongs'",
",",
"{",
"'type'",
":",
"period",
"}",
",",
"self",
".",
"connection",
".",
"header",
"(",
"'popul... | 44.909091 | 0.001982 |
def returnFalseNegatives(kw, noisePct, n, theta):
"""
Generate a weight vector W, with kw non-zero components. Generate 1000
noisy versions of W and return the match statistics. Noisy version of W is
generated by randomly setting noisePct of the non-zero components to zero.
:param kw: k for the weight vector... | [
"def",
"returnFalseNegatives",
"(",
"kw",
",",
"noisePct",
",",
"n",
",",
"theta",
")",
":",
"W",
"=",
"getSparseTensor",
"(",
"kw",
",",
"n",
",",
"1",
",",
"fixedRange",
"=",
"1.0",
"/",
"kw",
")",
"# Get permuted versions of W and see how many match",
"m2... | 34.56 | 0.011261 |
def lookup(self, key_name, headers=None, callback=None):
"""
Deprecated: Please use get_key method.
:type key_name: string
:param key_name: The name of the key to retrieve
:rtype: :class:`boto.s3.key.Key`
:returns: A Key object from this bucket.
... | [
"def",
"lookup",
"(",
"self",
",",
"key_name",
",",
"headers",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_key",
"(",
"key_name",
",",
"headers",
"=",
"headers",
",",
"callback",
"=",
"callback",
")"
] | 35.181818 | 0.010076 |
def serialize(self, data):
""" Determine & invoke the proper serializer method
If data is a list then the serialize_datas method will
be run otherwise serialize_data.
"""
super(Serializer, self).serialize(data)
body = {
'jsonapi': {
'version... | [
"def",
"serialize",
"(",
"self",
",",
"data",
")",
":",
"super",
"(",
"Serializer",
",",
"self",
")",
".",
"serialize",
"(",
"data",
")",
"body",
"=",
"{",
"'jsonapi'",
":",
"{",
"'version'",
":",
"goldman",
".",
"config",
".",
"JSONAPI_VERSION",
",",
... | 30.825 | 0.001572 |
def trace_pars(mname):
"""Define trace parameters."""
pickle_fname = os.path.join(os.path.dirname(__file__), "{0}.pkl".format(mname))
ddir = os.path.dirname(os.path.dirname(__file__))
moddb_fname = os.path.join(ddir, "moddb.json")
in_callables_fname = moddb_fname if os.path.exists(moddb_fname) else ... | [
"def",
"trace_pars",
"(",
"mname",
")",
":",
"pickle_fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"{0}.pkl\"",
".",
"format",
"(",
"mname",
")",
")",
"ddir",
"=",
"os",
".",
"path... | 36.045455 | 0.002457 |
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
conf):
'''
Check etcd for all data
'''
comps = conf.split()
profile = None
if comps[0]:
profile = comps[0]
client = salt.utils.etcd_util.get_conn(__opts__, profile)
path = '/'
if len(co... | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"# pylint: disable=W0613",
"conf",
")",
":",
"comps",
"=",
"conf",
".",
"split",
"(",
")",
"profile",
"=",
"None",
"if",
"comps",
"[",
"0",
"]",
":",
"profile",
"=",
"comps",
"[",
"0",
"]",
"... | 23.448276 | 0.001412 |
def initOptions(self, options):
"""
Initializes the edit with the inputed options data set.
:param options | <XScintillaEditOptions>
"""
self.setAutoIndent( options.value('autoIndent'))
self.setIndentationsUseTabs( options.value('indentationsU... | [
"def",
"initOptions",
"(",
"self",
",",
"options",
")",
":",
"self",
".",
"setAutoIndent",
"(",
"options",
".",
"value",
"(",
"'autoIndent'",
")",
")",
"self",
".",
"setIndentationsUseTabs",
"(",
"options",
".",
"value",
"(",
"'indentationsUseTabs'",
")",
")... | 40.058824 | 0.009556 |
def extractInfo(self, otherInfoObject):
"""
>>> from fontMath.test.test_mathInfo import _TestInfoObject, _testData
>>> from fontMath.mathFunctions import _roundNumber
>>> info1 = MathInfo(_TestInfoObject())
>>> info2 = info1 * 2.5
>>> info3 = _TestInfoObject()
>>>... | [
"def",
"extractInfo",
"(",
"self",
",",
"otherInfoObject",
")",
":",
"for",
"attr",
",",
"(",
"formatter",
",",
"factorIndex",
")",
"in",
"_infoAttrs",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"attr",
")",
":",
"v",
"=",
"getat... | 42 | 0.00141 |
def error_perturbation(C, S):
r"""Error perturbation for given sensitivity matrix.
Parameters
----------
C : (M, M) ndarray
Count matrix
S : (M, M) ndarray or (K, M, M) ndarray
Sensitivity matrix (for scalar observable) or sensitivity
tensor for vector observable
Return... | [
"def",
"error_perturbation",
"(",
"C",
",",
"S",
")",
":",
"if",
"len",
"(",
"S",
".",
"shape",
")",
"==",
"2",
":",
"# Scalar observable",
"return",
"error_perturbation_single",
"(",
"C",
",",
"S",
")",
"elif",
"len",
"(",
"S",
".",
"shape",
")",
"=... | 30.666667 | 0.001318 |
def rev_regs(self) -> list:
"""
Return list of revocation registry identifiers for which HolderProver has tails files.
:return: list of revocation registry identifiers for which HolderProver has tails files
"""
LOGGER.debug('HolderProver.rev_regs >>>')
rv = [basename(f... | [
"def",
"rev_regs",
"(",
"self",
")",
"->",
"list",
":",
"LOGGER",
".",
"debug",
"(",
"'HolderProver.rev_regs >>>'",
")",
"rv",
"=",
"[",
"basename",
"(",
"f",
")",
"for",
"f",
"in",
"Tails",
".",
"links",
"(",
"self",
".",
"_dir_tails",
")",
"]",
"LO... | 35.333333 | 0.009195 |
def savedocx(
document, coreprops, appprops, contenttypes, websettings,
wordrelationships, output, imagefiledict=None):
"""
Save a modified document
"""
if imagefiledict is None:
warn(
'Using savedocx() without imagefiledict parameter will be deprec'
'ated... | [
"def",
"savedocx",
"(",
"document",
",",
"coreprops",
",",
"appprops",
",",
"contenttypes",
",",
"websettings",
",",
"wordrelationships",
",",
"output",
",",
"imagefiledict",
"=",
"None",
")",
":",
"if",
"imagefiledict",
"is",
"None",
":",
"warn",
"(",
"'Usi... | 36.785714 | 0.000473 |
def build_ordered_cliques(cliques, next_cliques):
"""Order the new cliques based on the order of their ancestors in the
previous iteration."""
def sort_key(clique):
return -len(clique[1])
if not cliques:
return list(sorted(
list(next_cliques.values())[0].items(),
... | [
"def",
"build_ordered_cliques",
"(",
"cliques",
",",
"next_cliques",
")",
":",
"def",
"sort_key",
"(",
"clique",
")",
":",
"return",
"-",
"len",
"(",
"clique",
"[",
"1",
"]",
")",
"if",
"not",
"cliques",
":",
"return",
"list",
"(",
"sorted",
"(",
"list... | 30.52 | 0.001271 |
def show_mode_indicator(viewer, tf, corner='ur'):
"""Show a keyboard mode indicator in one of the corners.
Parameters
----------
viewer : an ImageView subclass instance
If True, show the color bar; else remove it if present.
tf : bool
If True, show the mark; else remove it if prese... | [
"def",
"show_mode_indicator",
"(",
"viewer",
",",
"tf",
",",
"corner",
"=",
"'ur'",
")",
":",
"tag",
"=",
"'_$mode_indicator'",
"canvas",
"=",
"viewer",
".",
"get_private_canvas",
"(",
")",
"try",
":",
"indic",
"=",
"canvas",
".",
"get_object_by_tag",
"(",
... | 28.052632 | 0.000907 |
def split_cli_ids_arg(value):
"""
Split ids given in the command line
Possible formats are:
* 1
* 1,2,3,4
* 1-5,20,30,40
Returns respectively
* set([1])
* set([1,2,3,4])
* set([1,2,3,4,5,20,30,40])
"""
def parse(el):
el = el.strip()
if not el:
... | [
"def",
"split_cli_ids_arg",
"(",
"value",
")",
":",
"def",
"parse",
"(",
"el",
")",
":",
"el",
"=",
"el",
".",
"strip",
"(",
")",
"if",
"not",
"el",
":",
"ret",
"=",
"[",
"]",
"elif",
"'-'",
"in",
"el",
":",
"start",
",",
"end",
"=",
"el",
".... | 24.26087 | 0.001724 |
def start(views,
center=[37.7792, -122.2191],
zoom=11,
shape_json='data/zones.json',
geom_name='ZONE_ID', # from JSON file
join_name='zone_id', # from data frames
precision=8,
port=8765,
host='localhost',
testing=False):
"""... | [
"def",
"start",
"(",
"views",
",",
"center",
"=",
"[",
"37.7792",
",",
"-",
"122.2191",
"]",
",",
"zoom",
"=",
"11",
",",
"shape_json",
"=",
"'data/zones.json'",
",",
"geom_name",
"=",
"'ZONE_ID'",
",",
"# from JSON file",
"join_name",
"=",
"'zone_id'",
",... | 31.486842 | 0.000405 |
def add_library_path(path: str) -> bool:
"""
Adds the path to the Python system path if not already added and the path
exists.
:param path:
The path to add to the system paths
:return:
Whether or not the path was added. Only returns False if the path was
not added because it... | [
"def",
"add_library_path",
"(",
"path",
":",
"str",
")",
"->",
"bool",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"False",
"if",
"path",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"app... | 24 | 0.00211 |
def generate_df(js_dict, naming, value="value"):
"""Decode JSON-stat dict into pandas.DataFrame object. Helper method \
that should be called inside from_json_stat().
Args:
js_dict(OrderedDict): OrderedDict with data in JSON-stat format, \
previously deserialized into a... | [
"def",
"generate_df",
"(",
"js_dict",
",",
"naming",
",",
"value",
"=",
"\"value\"",
")",
":",
"values",
"=",
"[",
"]",
"dimensions",
",",
"dim_names",
"=",
"get_dimensions",
"(",
"js_dict",
",",
"naming",
")",
"values",
"=",
"get_values",
"(",
"js_dict",
... | 40.56 | 0.000963 |
def to_fits(self, filename, wavelengths=None, flux_unit=None, area=None,
vegaspec=None, **kwargs):
"""Write the spectrum to a FITS file.
Parameters
----------
filename : str
Output filename.
wavelengths : array-like, `~astropy.units.quantity.Quantity... | [
"def",
"to_fits",
"(",
"self",
",",
"filename",
",",
"wavelengths",
"=",
"None",
",",
"flux_unit",
"=",
"None",
",",
"area",
"=",
"None",
",",
"vegaspec",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"w",
",",
"y",
"=",
"self",
".",
"_get_arrays... | 33.878049 | 0.002099 |
def off(self, name, callback, once=False):
"""
Removes callback to the event specified by name
"""
if name not in self.event_listeners:
return
self.event_listeners[name].remove((callback, once)) | [
"def",
"off",
"(",
"self",
",",
"name",
",",
"callback",
",",
"once",
"=",
"False",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"event_listeners",
":",
"return",
"self",
".",
"event_listeners",
"[",
"name",
"]",
".",
"remove",
"(",
"(",
"callba... | 26.666667 | 0.008065 |
def process_incoming(self):
"""
process incoming messages
data is a dict with several arrays
"""
model = self.model
sockets = self.sockets
# Check for new messages
if not sockets:
return
# unpack sockets
poller = sockets['pol... | [
"def",
"process_incoming",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"model",
"sockets",
"=",
"self",
".",
"sockets",
"# Check for new messages",
"if",
"not",
"sockets",
":",
"return",
"# unpack sockets",
"poller",
"=",
"sockets",
"[",
"'poller'",
"]",... | 44.922535 | 0.000767 |
def simxSetFloatSignal(clientID, signalName, signalValue, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
if (sys.version_info[0] == 3) and (type(signalName) is str):
signalName=signalName.encode('utf-8')
return c_SetFloatSignal(... | [
"def",
"simxSetFloatSignal",
"(",
"clientID",
",",
"signalName",
",",
"signalValue",
",",
"operationMode",
")",
":",
"if",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
")",
"and",
"(",
"type",
"(",
"signalName",
")",
"is",
"str",
")",
":"... | 45.25 | 0.00813 |
def get_assets_by_ids(self, asset_ids):
"""Gets an ``AssetList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the assets
specified in the ``Id`` list, in the order of the list,
including duplicates, or an error results if an ``Id`` in the
... | [
"def",
"get_assets_by_ids",
"(",
"self",
",",
"asset_ids",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources_by_ids",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'repositor... | 46.785714 | 0.001994 |
def load_events(filename, delimiter=r'\s+'):
r"""Import time-stamp events from an annotation file. The file should
consist of a single column of numeric values corresponding to the event
times. This is primarily useful for processing events which lack duration,
such as beats or onsets.
Parameters
... | [
"def",
"load_events",
"(",
"filename",
",",
"delimiter",
"=",
"r'\\s+'",
")",
":",
"# Use our universal function to load in the events",
"events",
"=",
"load_delimited",
"(",
"filename",
",",
"[",
"float",
"]",
",",
"delimiter",
")",
"events",
"=",
"np",
".",
"a... | 30.866667 | 0.001047 |
def get_batch(data_source, i, seq_len=None):
"""Get mini-batches of the dataset.
Parameters
----------
data_source : NDArray
The dataset is evaluated on.
i : int
The index of the batch, starting from 0.
seq_len : int
The length of each sample in the batch.
Returns
... | [
"def",
"get_batch",
"(",
"data_source",
",",
"i",
",",
"seq_len",
"=",
"None",
")",
":",
"seq_len",
"=",
"min",
"(",
"seq_len",
"if",
"seq_len",
"else",
"args",
".",
"bptt",
",",
"len",
"(",
"data_source",
")",
"-",
"1",
"-",
"i",
")",
"data",
"=",... | 25.391304 | 0.00165 |
def small_ftk_image_recognition():
"""!
@brief Trains network using letters 'F', 'T', 'K' and recognize each of them with and without noise.
"""
images = [];
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_F;
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_T;
images += IMAGE... | [
"def",
"small_ftk_image_recognition",
"(",
")",
":",
"images",
"=",
"[",
"]",
"images",
"+=",
"IMAGE_SYMBOL_SAMPLES",
".",
"LIST_IMAGES_SYMBOL_F",
"images",
"+=",
"IMAGE_SYMBOL_SAMPLES",
".",
"LIST_IMAGES_SYMBOL_T",
"images",
"+=",
"IMAGE_SYMBOL_SAMPLES",
".",
"LIST_IMA... | 37.090909 | 0.021531 |
def getRawIdent(self, node):
"""
Get the identifier for a node object
"""
if node is self:
return node
ident = getattr(node, 'graphident', None)
return ident | [
"def",
"getRawIdent",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"is",
"self",
":",
"return",
"node",
"ident",
"=",
"getattr",
"(",
"node",
",",
"'graphident'",
",",
"None",
")",
"return",
"ident"
] | 26.25 | 0.009217 |
def get_setting(name):
'''
Get the current configuration for the named audit setting
Args:
name (str): The name of the setting to retrieve
Returns:
str: The current configuration for the named setting
Raises:
KeyError: On invalid setting name
CommandExecutionError:... | [
"def",
"get_setting",
"(",
"name",
")",
":",
"current_settings",
"=",
"get_settings",
"(",
"category",
"=",
"'All'",
")",
"for",
"setting",
"in",
"current_settings",
":",
"if",
"name",
".",
"lower",
"(",
")",
"==",
"setting",
".",
"lower",
"(",
")",
":",... | 29.107143 | 0.002375 |
def getTickTock(self, vals):
'''
Get a tick, tock time pair.
Args:
vals (list): A pair of values to norm.
Returns:
(int, int): A ordered pair of integers.
'''
val0, val1 = vals
try:
_tick = self._getLiftValu(val0)
exc... | [
"def",
"getTickTock",
"(",
"self",
",",
"vals",
")",
":",
"val0",
",",
"val1",
"=",
"vals",
"try",
":",
"_tick",
"=",
"self",
".",
"_getLiftValu",
"(",
"val0",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"s_exc",
".",
"BadTypeValu",
"(",
"n... | 30.075 | 0.002415 |
def phiforce(self,R,phi=0.,t=0.):
"""
NAME:
phiforce
PURPOSE:
evaluate the phi force
INPUT:
R - Cylindrical radius (can be Quantity)
phi= azimuth (optional; can be Quantity)
t= time (optional; can be Quantity)
OUTPUT:... | [
"def",
"phiforce",
"(",
"self",
",",
"R",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"return",
"self",
".",
"_phiforce_nodecorator",
"(",
"R",
",",
"phi",
"=",
"phi",
",",
"t",
"=",
"t",
")"
] | 16.321429 | 0.014463 |
def update(self, cls, rid, partialrecord, user='undefined'):
"""Update existing record
>>> s = teststore()
>>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})
>>> r = s.get('tstoretest', '1')
>>> r['age']
>>> s.update('tstoretest', '1', {'age': 25})
>>> r = s... | [
"def",
"update",
"(",
"self",
",",
"cls",
",",
"rid",
",",
"partialrecord",
",",
"user",
"=",
"'undefined'",
")",
":",
"self",
".",
"validate_partial_record",
"(",
"cls",
",",
"partialrecord",
")",
"partialrecord",
"[",
"UPDATE_DATE",
"]",
"=",
"self",
"."... | 41.68 | 0.000938 |
def read(fname,**kw):
'''
Reads an lsp output file and returns a raw dump of data,
sectioned into quantities either as an dictionary or a typed numpy array.
Parameters:
-----------
fname -- filename of thing to read
Keyword Arguments:
------------------
vprint -- Verbose p... | [
"def",
"read",
"(",
"fname",
",",
"*",
"*",
"kw",
")",
":",
"if",
"test",
"(",
"kw",
",",
"'gzip'",
")",
"and",
"kw",
"[",
"'gzip'",
"]",
"==",
"'guess'",
":",
"kw",
"[",
"'gzip'",
"]",
"=",
"re",
".",
"search",
"(",
"r'\\.gz$'",
",",
"fname",
... | 40.325843 | 0.011694 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.