text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def estimateAbsoluteMagnitude(spectralType):
"""Uses the spectral type to lookup an approximate absolute magnitude for
the star.
"""
from .astroclasses import SpectralType
specType = SpectralType(spectralType)
if specType.classLetter == '':
return np.nan
elif specType.classNumber ... | [
"def",
"estimateAbsoluteMagnitude",
"(",
"spectralType",
")",
":",
"from",
".",
"astroclasses",
"import",
"SpectralType",
"specType",
"=",
"SpectralType",
"(",
"spectralType",
")",
"if",
"specType",
".",
"classLetter",
"==",
"''",
":",
"return",
"np",
".",
"nan"... | 33.03125 | 0.000919 |
def holtWintersConfidenceArea(requestContext, seriesList, delta=3):
"""
Performs a Holt-Winters forecast using the series as input data and plots
the area between the upper and lower bands of the predicted forecast
deviations.
"""
bands = holtWintersConfidenceBands(requestContext, seriesList, de... | [
"def",
"holtWintersConfidenceArea",
"(",
"requestContext",
",",
"seriesList",
",",
"delta",
"=",
"3",
")",
":",
"bands",
"=",
"holtWintersConfidenceBands",
"(",
"requestContext",
",",
"seriesList",
",",
"delta",
")",
"results",
"=",
"areaBetween",
"(",
"requestCon... | 44.666667 | 0.001828 |
def _generate_contents(self, tar):
"""
Adds configuration files to tarfile instance.
:param tar: tarfile instance
:returns: None
"""
text = self.render(files=False)
# create a list with all the packages (and remove empty entries)
vpn_instances = vpn_patte... | [
"def",
"_generate_contents",
"(",
"self",
",",
"tar",
")",
":",
"text",
"=",
"self",
".",
"render",
"(",
"files",
"=",
"False",
")",
"# create a list with all the packages (and remove empty entries)",
"vpn_instances",
"=",
"vpn_pattern",
".",
"split",
"(",
"text",
... | 38.043478 | 0.00223 |
def exists(self, **kwargs):
r"""Check for the existence of the ASM object on the BIG-IP
Sends an HTTP GET to the URI of the ASM object and if it fails with
a :exc:~requests.HTTPError` exception it checks the exception for
status code of 404 and returns :obj:`False` in that case.
... | [
"def",
"exists",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"requests_params",
"=",
"self",
".",
"_handle_requests_params",
"(",
"kwargs",
")",
"self",
".",
"_check_load_parameters",
"(",
"*",
"*",
"kwargs",
")",
"kwargs",
"[",
"'uri_as_parts'",
"]",
... | 38.395349 | 0.002363 |
def colorize(target, color, use_escape=True):
''' Colorize target string. Set use_escape to false when text will not be
interpreted by readline, such as in intro message.'''
def escape(code):
''' Escape character '''
return '\001%s\002' % code
if color == 'purple':
color_c... | [
"def",
"colorize",
"(",
"target",
",",
"color",
",",
"use_escape",
"=",
"True",
")",
":",
"def",
"escape",
"(",
"code",
")",
":",
"''' Escape character '''",
"return",
"'\\001%s\\002'",
"%",
"code",
"if",
"color",
"==",
"'purple'",
":",
"color_code",
"=",
... | 32.28125 | 0.00094 |
def fire(data, tag, timeout=None):
'''
Fire an event on the local minion event bus. Data must be formed as a dict.
CLI Example:
.. code-block:: bash
salt '*' event.fire '{"data":"my event data"}' 'tag'
'''
if timeout is None:
timeout = 60000
else:
timeout = timeout... | [
"def",
"fire",
"(",
"data",
",",
"tag",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"60000",
"else",
":",
"timeout",
"=",
"timeout",
"*",
"1000",
"try",
":",
"event",
"=",
"salt",
".",
"utils",
".",
... | 34.928571 | 0.000995 |
def init_argparser_build_dir(
self, argparser, help=(
'the build directory, where all sources will be copied to '
'as part of the build process; if left unspecified, the '
'default behavior is to create a new temporary directory '
'that will be... | [
"def",
"init_argparser_build_dir",
"(",
"self",
",",
"argparser",
",",
"help",
"=",
"(",
"'the build directory, where all sources will be copied to '",
"'as part of the build process; if left unspecified, the '",
"'default behavior is to create a new temporary directory '",
"'that will be ... | 44.055556 | 0.002469 |
def human(value):
"If val>=1000 return val/1024+KiB, etc."
if value >= 1073741824000:
return '{:.1f} T'.format(value / 1099511627776.0)
if value >= 1048576000:
return '{:.1f} G'.format(value / 1073741824.0)
if value >= 1024000:
return '{:.1f} M'.format(value / 1048576.0)
if v... | [
"def",
"human",
"(",
"value",
")",
":",
"if",
"value",
">=",
"1073741824000",
":",
"return",
"'{:.1f} T'",
".",
"format",
"(",
"value",
"/",
"1099511627776.0",
")",
"if",
"value",
">=",
"1048576000",
":",
"return",
"'{:.1f} G'",
".",
"format",
"(",
"value"... | 36.909091 | 0.002404 |
def delete(self):
""" Delete this Dagobah instance from the Backend. """
logger.debug('Deleting Dagobah instance with ID {0}'.format(self.dagobah_id))
self.jobs = []
self.created_jobs = 0
self.backend.delete_dagobah(self.dagobah_id) | [
"def",
"delete",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Deleting Dagobah instance with ID {0}'",
".",
"format",
"(",
"self",
".",
"dagobah_id",
")",
")",
"self",
".",
"jobs",
"=",
"[",
"]",
"self",
".",
"created_jobs",
"=",
"0",
"self",
".... | 44.5 | 0.011029 |
def investment_term(self, investment_term):
""" This investment term is in months. This might change to a relative delta."""
try:
if isinstance(investment_term, (str, int)):
self._investment_term = int(investment_term)
except Exception:
raise ValueError('... | [
"def",
"investment_term",
"(",
"self",
",",
"investment_term",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"investment_term",
",",
"(",
"str",
",",
"int",
")",
")",
":",
"self",
".",
"_investment_term",
"=",
"int",
"(",
"investment_term",
")",
"except",... | 53.5 | 0.009195 |
def trace_filter (patterns):
"""Add given patterns to trace filter set or clear set if patterns is
None."""
if patterns is None:
_trace_filter.clear()
else:
_trace_filter.update(re.compile(pat) for pat in patterns) | [
"def",
"trace_filter",
"(",
"patterns",
")",
":",
"if",
"patterns",
"is",
"None",
":",
"_trace_filter",
".",
"clear",
"(",
")",
"else",
":",
"_trace_filter",
".",
"update",
"(",
"re",
".",
"compile",
"(",
"pat",
")",
"for",
"pat",
"in",
"patterns",
")"... | 34.285714 | 0.00813 |
def load_text(self, text, verbose):
"""
:param text:
:param rdf_format_opts:
:param verbose:
:return:
"""
if verbose: printDebug("----------")
if verbose: printDebug("Reading: '%s ...'" % text[:10])
success = False
for f in self.rd... | [
"def",
"load_text",
"(",
"self",
",",
"text",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"printDebug",
"(",
"\"----------\"",
")",
"if",
"verbose",
":",
"printDebug",
"(",
"\"Reading: '%s ...'\"",
"%",
"text",
"[",
":",
"10",
"]",
")",
"success",
"=... | 35.08 | 0.011099 |
def validate(self):
"""
Verify that the contents of the PublicKey object are valid.
Raises:
TypeError: if the types of any PublicKey attributes are invalid.
"""
if not isinstance(self.value, bytes):
raise TypeError("key value must be bytes")
elif ... | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"value",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"key value must be bytes\"",
")",
"elif",
"not",
"isinstance",
"(",
"self",
".",
"cryptographic_algorithm",
"... | 45.5 | 0.001076 |
def shouts(self, group, format, *args):
"""
Send formatted string to a named group
"""
return lib.zyre_shouts(self._as_parameter_, group, format, *args) | [
"def",
"shouts",
"(",
"self",
",",
"group",
",",
"format",
",",
"*",
"args",
")",
":",
"return",
"lib",
".",
"zyre_shouts",
"(",
"self",
".",
"_as_parameter_",
",",
"group",
",",
"format",
",",
"*",
"args",
")"
] | 36 | 0.01087 |
def get_period_uncertainty(self, fx, fy, jmax, fx_width=100):
"""
Get uncertainty of a period.
The uncertainty is defined as the half width of the frequencies
around the peak, that becomes lower than average + standard deviation
of the power spectrum.
Since we may not h... | [
"def",
"get_period_uncertainty",
"(",
"self",
",",
"fx",
",",
"fy",
",",
"jmax",
",",
"fx_width",
"=",
"100",
")",
":",
"# Get subset",
"start_index",
"=",
"jmax",
"-",
"fx_width",
"end_index",
"=",
"jmax",
"+",
"fx_width",
"if",
"start_index",
"<",
"0",
... | 31.469697 | 0.000934 |
def put_item(self, table_name, item,
condition_expression=None,
expression_attribute_names=None,
expression_attribute_values=None,
return_consumed_capacity=None,
return_item_collection_metrics=None,
return_values=None)... | [
"def",
"put_item",
"(",
"self",
",",
"table_name",
",",
"item",
",",
"condition_expression",
"=",
"None",
",",
"expression_attribute_names",
"=",
"None",
",",
"expression_attribute_values",
"=",
"None",
",",
"return_consumed_capacity",
"=",
"None",
",",
"return_item... | 57.12 | 0.001836 |
def _find_only_column_of_type(sframe, target_type, type_name, col_name):
"""
Finds the only column in `SFrame` with a type specified by `target_type`.
If there are zero or more than one such columns, an exception will be
raised. The name and type of the target column should be provided as
strings fo... | [
"def",
"_find_only_column_of_type",
"(",
"sframe",
",",
"target_type",
",",
"type_name",
",",
"col_name",
")",
":",
"image_column_name",
"=",
"None",
"if",
"type",
"(",
"target_type",
")",
"!=",
"list",
":",
"target_type",
"=",
"[",
"target_type",
"]",
"for",
... | 54.111111 | 0.002018 |
def run(self):
"""Starts the blotter
Connects to the TWS/GW, processes and logs market data,
and broadcast it over TCP via ZeroMQ (which algo subscribe to)
"""
self._check_unique_blotter()
# connect to mysql
self.mysql_connect()
self.context = zmq.Cont... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_check_unique_blotter",
"(",
")",
"# connect to mysql",
"self",
".",
"mysql_connect",
"(",
")",
"self",
".",
"context",
"=",
"zmq",
".",
"Context",
"(",
"zmq",
".",
"REP",
")",
"self",
".",
"socket",
"... | 42.15942 | 0.002015 |
def plot(self, agebins=50, p=(2.5, 97.5), ax=None):
"""Age-depth plot"""
if ax is None:
ax = plt.gca()
ax.hist2d(np.repeat(self.depth, self.age_ensemble.shape[1]), self.age_ensemble.flatten(),
(len(self.depth), agebins), cmin=1)
ax.step(self.depth, self.age... | [
"def",
"plot",
"(",
"self",
",",
"agebins",
"=",
"50",
",",
"p",
"=",
"(",
"2.5",
",",
"97.5",
")",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"ax",
".",
"hist2d",
"(",
"np",
"... | 50.230769 | 0.009023 |
def calc_geo_dist_matrix_vincenty(nodes_pos):
""" Calculates the geodesic distance between all nodes in `nodes_pos` incorporating the detour factor in config_calc.cfg.
For every two points/coord it uses geopy's vincenty function (formula devised by Thaddeus Vincenty,
with an accurate ellipsoidal m... | [
"def",
"calc_geo_dist_matrix_vincenty",
"(",
"nodes_pos",
")",
":",
"branch_detour_factor",
"=",
"cfg_ding0",
".",
"get",
"(",
"'assumptions'",
",",
"'branch_detour_factor'",
")",
"matrix",
"=",
"{",
"}",
"for",
"i",
"in",
"nodes_pos",
":",
"pos_origin",
"=",
"t... | 32.367347 | 0.010404 |
def get_pkg_info(
package_name, additional=("pip", "flit", "pbr", "setuptools", "wheel")
):
"""Return build and package dependencies as a dict."""
dist_index = build_dist_index(pkg_resources.working_set)
root = dist_index[package_name]
tree = construct_tree(dist_index)
dependencies = {pkg.name: ... | [
"def",
"get_pkg_info",
"(",
"package_name",
",",
"additional",
"=",
"(",
"\"pip\"",
",",
"\"flit\"",
",",
"\"pbr\"",
",",
"\"setuptools\"",
",",
"\"wheel\"",
")",
")",
":",
"dist_index",
"=",
"build_dist_index",
"(",
"pkg_resources",
".",
"working_set",
")",
"... | 40.157895 | 0.00128 |
def add(self, name, parents=None):
"""
add a node to the graph.
Raises an exception if the node cannot be added (i.e., if a node
that name already exists, or if it would create a cycle.
NOTE: A node can be added before its parents are added.
name: The name of the node ... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"parents",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"Hashable",
")",
":",
"raise",
"TypeError",
"(",
"name",
")",
"parents",
"=",
"set",
"(",
"parents",
"or",
"(",
")",
")",
... | 30.603448 | 0.001092 |
def _get_rhos(X, indices, Ks, max_K, save_all_Ks, min_dist):
"Gets within-bag distances for each bag."
logger.info("Getting within-bag distances...")
if max_K >= X.n_pts.min():
msg = "asked for K = {}, but there's a bag with only {} points"
raise ValueError(msg.format(max_K, X.n_pts.min()))... | [
"def",
"_get_rhos",
"(",
"X",
",",
"indices",
",",
"Ks",
",",
"max_K",
",",
"save_all_Ks",
",",
"min_dist",
")",
":",
"logger",
".",
"info",
"(",
"\"Getting within-bag distances...\"",
")",
"if",
"max_K",
">=",
"X",
".",
"n_pts",
".",
"min",
"(",
")",
... | 40.368421 | 0.001274 |
def seriesflow(self, dae):
"""
Compute the flow through the line after solving PF.
Compute terminal injections, line losses
"""
# Vm = dae.y[self.v]
# Va = dae.y[self.a]
# V1 = polar(Vm[self.a1], Va[self.a1])
# V2 = polar(Vm[self.a2], Va[self.a2])
... | [
"def",
"seriesflow",
"(",
"self",
",",
"dae",
")",
":",
"# Vm = dae.y[self.v]",
"# Va = dae.y[self.a]",
"# V1 = polar(Vm[self.a1], Va[self.a1])",
"# V2 = polar(Vm[self.a2], Va[self.a2])",
"I1",
"=",
"mul",
"(",
"self",
".",
"v1",
",",
"div",
"(",
"self",
".",
"y12",
... | 31.52381 | 0.001465 |
def separate_globs(globs):
"""Separate include and exclude globs."""
exclude = []
include = []
for path in globs:
if path.startswith("!"):
exclude.append(path[1:])
else:
include.append(path)
return (exclude, include) | [
"def",
"separate_globs",
"(",
"globs",
")",
":",
"exclude",
"=",
"[",
"]",
"include",
"=",
"[",
"]",
"for",
"path",
"in",
"globs",
":",
"if",
"path",
".",
"startswith",
"(",
"\"!\"",
")",
":",
"exclude",
".",
"append",
"(",
"path",
"[",
"1",
":",
... | 18.5 | 0.042918 |
def _currentResponse(self, debugInfo):
"""
Pull the current response off the queue.
"""
bd = b''.join(self._bufferedData)
self._bufferedData = []
return AssuanResponse(bd, debugInfo) | [
"def",
"_currentResponse",
"(",
"self",
",",
"debugInfo",
")",
":",
"bd",
"=",
"b''",
".",
"join",
"(",
"self",
".",
"_bufferedData",
")",
"self",
".",
"_bufferedData",
"=",
"[",
"]",
"return",
"AssuanResponse",
"(",
"bd",
",",
"debugInfo",
")"
] | 32 | 0.008696 |
def comments(self, ticket, include_inline_images=False):
"""
Retrieve the comments for a ticket.
:param ticket: Ticket object or id
:param include_inline_images: Boolean. If `True`, inline image attachments will be
returned in each comments' `attachments` field alongside non... | [
"def",
"comments",
"(",
"self",
",",
"ticket",
",",
"include_inline_images",
"=",
"False",
")",
":",
"return",
"self",
".",
"_query_zendesk",
"(",
"self",
".",
"endpoint",
".",
"comments",
",",
"'comment'",
",",
"id",
"=",
"ticket",
",",
"include_inline_imag... | 53.666667 | 0.010183 |
def remove(self, item):
"""Remove an item from the list.
"""
self.items.pop(item)
self._remove_dep(item)
self.order = None
self.changed(code_changed=True) | [
"def",
"remove",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"items",
".",
"pop",
"(",
"item",
")",
"self",
".",
"_remove_dep",
"(",
"item",
")",
"self",
".",
"order",
"=",
"None",
"self",
".",
"changed",
"(",
"code_changed",
"=",
"True",
")"
... | 28 | 0.009901 |
def reverse_pivot_to_fact(self, staging_table, piv_column, piv_list, from_column, meas_names, meas_values, new_line):
"""
For each column in the piv_list, append ALL from_column's using the group_list
e.g.
Input Table
YEAR Person Q1 Q2
2010 Fre... | [
"def",
"reverse_pivot_to_fact",
"(",
"self",
",",
"staging_table",
",",
"piv_column",
",",
"piv_list",
",",
"from_column",
",",
"meas_names",
",",
"meas_values",
",",
"new_line",
")",
":",
"self",
".",
"sql_text",
"+=",
"'\\n-----------------------------\\n--Reverse P... | 42.802469 | 0.008176 |
def update_sql(table, filter, updates):
'''
>>> update_sql('tbl', {'foo': 'a', 'bar': 1}, {'bar': 2, 'baz': 'b'})
('UPDATE tbl SET bar=$1, baz=$2 WHERE bar=$3 AND foo=$4', [2, 'b', 1, 'a'])
'''
where_keys, where_vals = _split_dict(filter)
up_keys, up_vals = _split_dict(updates)
changes = _pa... | [
"def",
"update_sql",
"(",
"table",
",",
"filter",
",",
"updates",
")",
":",
"where_keys",
",",
"where_vals",
"=",
"_split_dict",
"(",
"filter",
")",
"up_keys",
",",
"up_vals",
"=",
"_split_dict",
"(",
"updates",
")",
"changes",
"=",
"_pairs",
"(",
"up_keys... | 41.666667 | 0.001957 |
def xpointerEval(self, str):
"""Evaluate the XPath Location Path in the given context. """
ret = libxml2mod.xmlXPtrEval(str, self._o)
if ret is None:raise treeError('xmlXPtrEval() failed')
return xpathObjectRet(ret) | [
"def",
"xpointerEval",
"(",
"self",
",",
"str",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPtrEval",
"(",
"str",
",",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlXPtrEval() failed'",
")",
"return",
"xpathObj... | 48.6 | 0.016194 |
def authenticate(self,
connection_certificate=None,
connection_info=None,
request_credentials=None):
"""
Query the configured SLUGS service with the provided credentials.
Args:
connection_certificate (cryptography.x509.C... | [
"def",
"authenticate",
"(",
"self",
",",
"connection_certificate",
"=",
"None",
",",
"connection_info",
"=",
"None",
",",
"request_credentials",
"=",
"None",
")",
":",
"if",
"(",
"self",
".",
"users_url",
"is",
"None",
")",
"or",
"(",
"self",
".",
"groups_... | 42.829787 | 0.002428 |
def _autodiscover(self):
"""Discovers panels to register from the current dashboard module."""
if getattr(self, "_autodiscover_complete", False):
return
panels_to_discover = []
panel_groups = []
# If we have a flat iterable of panel names, wrap it again so
# ... | [
"def",
"_autodiscover",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"\"_autodiscover_complete\"",
",",
"False",
")",
":",
"return",
"panels_to_discover",
"=",
"[",
"]",
"panel_groups",
"=",
"[",
"]",
"# If we have a flat iterable of panel names, wrap i... | 43.416667 | 0.000939 |
def _get_property_columns(tabletype, columns):
"""Returns list of GPS columns required to read gpsproperties for a table
Examples
--------
>>> _get_property_columns(lsctables.SnglBurstTable, ['peak'])
['peak_time', 'peak_time_ns']
"""
from ligo.lw.lsctables import gpsproperty as GpsProperty... | [
"def",
"_get_property_columns",
"(",
"tabletype",
",",
"columns",
")",
":",
"from",
"ligo",
".",
"lw",
".",
"lsctables",
"import",
"gpsproperty",
"as",
"GpsProperty",
"# get properties for row object",
"rowvars",
"=",
"vars",
"(",
"tabletype",
".",
"RowType",
")",... | 34.833333 | 0.001553 |
def AsDict(self, dt=True):
"""
A dict representation of this User instance.
The return value uses the same key names as the JSON representation.
Args:
dt (bool): If True, return dates as python datetime objects. If
False, return dates as ISO strings.
Re... | [
"def",
"AsDict",
"(",
"self",
",",
"dt",
"=",
"True",
")",
":",
"data",
"=",
"{",
"}",
"if",
"self",
".",
"name",
":",
"data",
"[",
"'name'",
"]",
"=",
"self",
".",
"name",
"data",
"[",
"'mlkshk_url'",
"]",
"=",
"self",
".",
"mlkshk_url",
"if",
... | 32.068966 | 0.002088 |
def arcs_missing(self):
"""Returns a sorted list of the arcs in the code not executed."""
possible = self.arc_possibilities()
executed = self.arcs_executed()
missing = [
p for p in possible
if p not in executed
and p[0] not in self.no_branc... | [
"def",
"arcs_missing",
"(",
"self",
")",
":",
"possible",
"=",
"self",
".",
"arc_possibilities",
"(",
")",
"executed",
"=",
"self",
".",
"arcs_executed",
"(",
")",
"missing",
"=",
"[",
"p",
"for",
"p",
"in",
"possible",
"if",
"p",
"not",
"in",
"execute... | 35.7 | 0.010929 |
def center_at(self, x, y):
"""Center the menu at x, y"""
self.x = x - (self.width / 2)
self.y = y - (self.height / 2) | [
"def",
"center_at",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"x",
"=",
"x",
"-",
"(",
"self",
".",
"width",
"/",
"2",
")",
"self",
".",
"y",
"=",
"y",
"-",
"(",
"self",
".",
"height",
"/",
"2",
")"
] | 27.6 | 0.014085 |
def _html_to_img_tuples(html:str, format:str='jpg', n_images:int=10) -> list:
"Parse the google images html to img tuples containining `(fname, url)`"
bs = BeautifulSoup(html, 'html.parser')
img_tags = bs.find_all('div', {'class': 'rg_meta'})
metadata_dicts = (json.loads(e.text) for e in img_tags)
... | [
"def",
"_html_to_img_tuples",
"(",
"html",
":",
"str",
",",
"format",
":",
"str",
"=",
"'jpg'",
",",
"n_images",
":",
"int",
"=",
"10",
")",
"->",
"list",
":",
"bs",
"=",
"BeautifulSoup",
"(",
"html",
",",
"'html.parser'",
")",
"img_tags",
"=",
"bs",
... | 66.285714 | 0.021277 |
def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None):
"""
Random truncated normal variates.
"""
sigma = 1. / np.sqrt(tau)
na = utils.normcdf((a - mu) / sigma)
nb = utils.normcdf((b - mu) / sigma)
# Use the inverse CDF generation method.
U = np.random.mtrand.uniform(size=size)... | [
"def",
"rtruncated_normal",
"(",
"mu",
",",
"tau",
",",
"a",
"=",
"-",
"np",
".",
"inf",
",",
"b",
"=",
"np",
".",
"inf",
",",
"size",
"=",
"None",
")",
":",
"sigma",
"=",
"1.",
"/",
"np",
".",
"sqrt",
"(",
"tau",
")",
"na",
"=",
"utils",
"... | 25.25 | 0.002387 |
def upload_files(self, dataset_key, files, files_metadata={}, **kwargs):
"""Upload dataset files
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param files: The list of names/paths for files stored in the
local filesystem
:type fi... | [
"def",
"upload_files",
"(",
"self",
",",
"dataset_key",
",",
"files",
",",
"files_metadata",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"owner_id",
",",
"dataset_id",
"=",
"parse_dataset_key",
"(",
"dataset_key",
")",
"try",
":",
"self",
".",
"_up... | 42.575758 | 0.001392 |
def excess_sharpe(returns, factor_returns, out=None):
"""
Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_retu... | [
"def",
"excess_sharpe",
"(",
"returns",
",",
"factor_returns",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"returns",
".",
"shape",
"[",
"1",
":",
... | 26.617021 | 0.000771 |
def _handle_tag_definefontalignzones(self):
"""Handle the DefineFontAlignZones tag."""
obj = _make_object("DefineFontAlignZones")
obj.FontId = unpack_ui16(self._src)
bc = BitConsumer(self._src)
obj.CSMTableHint = bc.u_get(2)
obj.Reserved = bc.u_get(6)
obj.ZoneTab... | [
"def",
"_handle_tag_definefontalignzones",
"(",
"self",
")",
":",
"obj",
"=",
"_make_object",
"(",
"\"DefineFontAlignZones\"",
")",
"obj",
".",
"FontId",
"=",
"unpack_ui16",
"(",
"self",
".",
"_src",
")",
"bc",
"=",
"BitConsumer",
"(",
"self",
".",
"_src",
"... | 44.576923 | 0.001689 |
def addIndexOnAttribute(self, attributeName):
'''
addIndexOnAttribute - Add an index for an arbitrary attribute. This will be used by the getElementsByAttr function.
You should do this prior to parsing, or call reindex. Otherwise it will be blank. "name" and "id" will have no effect.... | [
"def",
"addIndexOnAttribute",
"(",
"self",
",",
"attributeName",
")",
":",
"attributeName",
"=",
"attributeName",
".",
"lower",
"(",
")",
"self",
".",
"_otherAttributeIndexes",
"[",
"attributeName",
"]",
"=",
"{",
"}",
"def",
"_otherIndexFunction",
"(",
"self",
... | 52.421053 | 0.009862 |
def _validate_indexers(self, key):
""" Make sanity checks """
for dim, k in zip(self.dims, key):
if isinstance(k, BASIC_INDEXING_TYPES):
pass
else:
if not isinstance(k, Variable):
k = np.asarray(k)
if k.ndim ... | [
"def",
"_validate_indexers",
"(",
"self",
",",
"key",
")",
":",
"for",
"dim",
",",
"k",
"in",
"zip",
"(",
"self",
".",
"dims",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"k",
",",
"BASIC_INDEXING_TYPES",
")",
":",
"pass",
"else",
":",
"if",
"no... | 52.777778 | 0.001378 |
def _create_storer(self, group, format=None, value=None, append=False,
**kwargs):
""" return a suitable class to operate """
def error(t):
raise TypeError(
"cannot properly create the storer for: [{t}] [group->"
"{group},value->{value},... | [
"def",
"_create_storer",
"(",
"self",
",",
"group",
",",
"format",
"=",
"None",
",",
"value",
"=",
"None",
",",
"append",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"error",
"(",
"t",
")",
":",
"raise",
"TypeError",
"(",
"\"cannot proper... | 36.604651 | 0.000928 |
def calc_timestep_statistic(self, statistic, time):
"""
Calculate statistics from the primary attribute of the StObject.
Args:
statistic: statistic being calculated
time: Timestep being investigated
Returns:
Value of the statistic
"""
... | [
"def",
"calc_timestep_statistic",
"(",
"self",
",",
"statistic",
",",
"time",
")",
":",
"ti",
"=",
"np",
".",
"where",
"(",
"self",
".",
"times",
"==",
"time",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"ma",
"=",
"np",
".",
"where",
"(",
"self",
".",
... | 37.933333 | 0.001714 |
def writePlist(dataObject, filepath):
'''
Write 'rootObject' as a plist to filepath.
'''
plistData, error = (
NSPropertyListSerialization.
dataFromPropertyList_format_errorDescription_(
dataObject, NSPropertyListXMLFormat_v1_0, None))
if plistData is None:
if erro... | [
"def",
"writePlist",
"(",
"dataObject",
",",
"filepath",
")",
":",
"plistData",
",",
"error",
"=",
"(",
"NSPropertyListSerialization",
".",
"dataFromPropertyList_format_errorDescription_",
"(",
"dataObject",
",",
"NSPropertyListXMLFormat_v1_0",
",",
"None",
")",
")",
... | 33.95 | 0.001433 |
def setMetadata(self, remote, address, key, value):
"""Set metadata of device"""
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].setMetadata(address, key, value)
except Exception as err:
LOG.debug("ServerThread.setMetadata: Exception: %s" % str(err)) | [
"def",
"setMetadata",
"(",
"self",
",",
"remote",
",",
"address",
",",
"key",
",",
"value",
")",
":",
"try",
":",
"return",
"self",
".",
"proxies",
"[",
"\"%s-%s\"",
"%",
"(",
"self",
".",
"_interface_id",
",",
"remote",
")",
"]",
".",
"setMetadata",
... | 51.666667 | 0.009524 |
def certify_enum_value(value, kind=None, required=True):
"""
Certifier for enum values.
:param value:
The value to be certified.
:param kind:
The enum type that value should be an instance of.
:param bool required:
Whether the value can be `None`. Defaults to True.
:rais... | [
"def",
"certify_enum_value",
"(",
"value",
",",
"kind",
"=",
"None",
",",
"required",
"=",
"True",
")",
":",
"if",
"certify_required",
"(",
"value",
"=",
"value",
",",
"required",
"=",
"required",
",",
")",
":",
"return",
"try",
":",
"kind",
"(",
"valu... | 26 | 0.001325 |
def resize_image_with_crop_or_pad(image, target_height, target_width,
dynamic_shape=False):
"""Crops and/or pads an image to a target width and height.
Resizes an image to a target width and height by either centrally
cropping the image or padding it evenly with zeros.
If `wi... | [
"def",
"resize_image_with_crop_or_pad",
"(",
"image",
",",
"target_height",
",",
"target_width",
",",
"dynamic_shape",
"=",
"False",
")",
":",
"image",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"image",
",",
"name",
"=",
"'image'",
")",
"_Check3DImage",
"(",
... | 38.4 | 0.009068 |
def visitExponentExpression(self, ctx):
"""
expression: expression EXPONENT expression
"""
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_decimal(self.visit(ctx.expression(1)), self._eval_context)
return conversions.... | [
"def",
"visitExponentExpression",
"(",
"self",
",",
"ctx",
")",
":",
"arg1",
"=",
"conversions",
".",
"to_decimal",
"(",
"self",
".",
"visit",
"(",
"ctx",
".",
"expression",
"(",
"0",
")",
")",
",",
"self",
".",
"_eval_context",
")",
"arg2",
"=",
"conv... | 50.571429 | 0.011111 |
def _bisearch(ucs, table):
"""
Auxiliary function for binary search in interval table.
:arg int ucs: Ordinal value of unicode character.
:arg list table: List of starting and ending ranges of ordinal values,
in form of ``[(start, end), ...]``.
:rtype: int
:returns: 1 if ordinal value uc... | [
"def",
"_bisearch",
"(",
"ucs",
",",
"table",
")",
":",
"lbound",
"=",
"0",
"ubound",
"=",
"len",
"(",
"table",
")",
"-",
"1",
"if",
"ucs",
"<",
"table",
"[",
"0",
"]",
"[",
"0",
"]",
"or",
"ucs",
">",
"table",
"[",
"ubound",
"]",
"[",
"1",
... | 27.76 | 0.001393 |
async def delete_record(type_: str, id: str):
"""
Delete a record from the storage wallet.
:param type_:
:param id:
Example:
await Wallet.add_record({
'id': 'RecordId',
'tags': json.dumps({
'tag1': 'unencrypted value1',
... | [
"async",
"def",
"delete_record",
"(",
"type_",
":",
"str",
",",
"id",
":",
"str",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"not",
"hasattr",
"(",
"Wallet",
".",
"delete_record",
",",
"\"cb\"",
")",
":",
"logger"... | 33.6 | 0.002479 |
def _cache_provider_details(conn=None):
'''
Provide a place to hang onto results of --list-[locations|sizes|images]
so we don't have to go out to the API and get them every time.
'''
DETAILS['avail_locations'] = {}
DETAILS['avail_sizes'] = {}
DETAILS['avail_images'] = {}
locations = avai... | [
"def",
"_cache_provider_details",
"(",
"conn",
"=",
"None",
")",
":",
"DETAILS",
"[",
"'avail_locations'",
"]",
"=",
"{",
"}",
"DETAILS",
"[",
"'avail_sizes'",
"]",
"=",
"{",
"}",
"DETAILS",
"[",
"'avail_images'",
"]",
"=",
"{",
"}",
"locations",
"=",
"a... | 36.565217 | 0.001159 |
def _compose_mro(cls, types): # noqa
"""Calculates the method resolution order for a given class *cls*.
Includes relevant abstract base classes (with their respective bases) from
the *types* iterable. Uses a modified C3 linearization algorithm.
"""
bases = set(cls.__mro__)
# Remove entries w... | [
"def",
"_compose_mro",
"(",
"cls",
",",
"types",
")",
":",
"# noqa",
"bases",
"=",
"set",
"(",
"cls",
".",
"__mro__",
")",
"# Remove entries which are already present in the __mro__ or unrelated.",
"def",
"is_related",
"(",
"_type",
")",
":",
"return",
"(",
"# :of... | 34.085106 | 0.000607 |
def syllabify(self, words: str) -> List[str]:
"""
Parse a Latin word into a list of syllable strings.
:param words: a string containing one latin word or many words separated by spaces.
:return: list of string, each representing a syllable.
>>> syllabifier = Syllabifier()
... | [
"def",
"syllabify",
"(",
"self",
",",
"words",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"cleaned",
"=",
"words",
".",
"translate",
"(",
"self",
".",
"remove_punct_map",
")",
"cleaned",
"=",
"cleaned",
".",
"replace",
"(",
"\"qu\"",
",",
"... | 37.736434 | 0.000801 |
def get_repository_filter_raw(self, term=False):
""" Returns the filter to be used in queries in a repository items """
perceval_backend_name = self.get_connector_name()
filter_ = get_repository_filter(self.perceval_backend, perceval_backend_name, term)
return filter_ | [
"def",
"get_repository_filter_raw",
"(",
"self",
",",
"term",
"=",
"False",
")",
":",
"perceval_backend_name",
"=",
"self",
".",
"get_connector_name",
"(",
")",
"filter_",
"=",
"get_repository_filter",
"(",
"self",
".",
"perceval_backend",
",",
"perceval_backend_nam... | 59.2 | 0.01 |
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
"==",
"''",
"and",
"self",
".",
"details",
"!=",
"None",
"and",
"'name'",
"in",
"self",
".",
"details",
":",
"self",
".",
"_name",
"=",
"self",
".",
"details",
"[",
"'name'",
"]",
... | 44.8 | 0.017544 |
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
... | [
"def",
"vm_profiles_config",
"(",
"path",
",",
"providers",
",",
"env_var",
"=",
"'SALT_CLOUDVM_CONFIG'",
",",
"defaults",
"=",
"None",
")",
":",
"if",
"defaults",
"is",
"None",
":",
"defaults",
"=",
"VM_CONFIG_DEFAULTS",
"overrides",
"=",
"salt",
".",
"config... | 30.115385 | 0.001238 |
def parse_html_dict(dictionary, prefix=''):
"""
Used to support dictionary values in HTML forms.
{
'profile.username': 'example',
'profile.email': 'example@example.com',
}
-->
{
'profile': {
'username': 'example',
'email': 'example@example.com... | [
"def",
"parse_html_dict",
"(",
"dictionary",
",",
"prefix",
"=",
"''",
")",
":",
"ret",
"=",
"MultiValueDict",
"(",
")",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'^%s\\.(.+)$'",
"%",
"re",
".",
"escape",
"(",
"prefix",
")",
")",
"for",
"field",
",",
... | 24 | 0.001603 |
def paintEvent(self, event):
"""Qt Override.
Include a validation icon to the left of the line edit.
"""
super(IconLineEdit, self).paintEvent(event)
painter = QPainter(self)
rect = self.geometry()
space = int((rect.height())/6)
h = rect.height() - space
... | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"IconLineEdit",
",",
"self",
")",
".",
"paintEvent",
"(",
"event",
")",
"painter",
"=",
"QPainter",
"(",
"self",
")",
"rect",
"=",
"self",
".",
"geometry",
"(",
")",
"space",
"="... | 32.1875 | 0.001885 |
def accept(self):
"""Method invoked when OK button is clicked."""
self.save_state()
self.dock.show_busy()
# The order of the components are matter.
components = self.prepare_components()
error_code, message = self.impact_function.generate_report(
components,... | [
"def",
"accept",
"(",
"self",
")",
":",
"self",
".",
"save_state",
"(",
")",
"self",
".",
"dock",
".",
"show_busy",
"(",
")",
"# The order of the components are matter.",
"components",
"=",
"self",
".",
"prepare_components",
"(",
")",
"error_code",
",",
"messa... | 32.030303 | 0.001837 |
def GetDeviceIntProperty(dev_ref, key):
"""Reads int property from the HID device."""
cf_key = CFStr(key)
type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key)
cf.CFRelease(cf_key)
if not type_ref:
return None
if cf.CFGetTypeID(type_ref) != cf.CFNumberGetTypeID():
raise errors.OsHidError('Expect... | [
"def",
"GetDeviceIntProperty",
"(",
"dev_ref",
",",
"key",
")",
":",
"cf_key",
"=",
"CFStr",
"(",
"key",
")",
"type_ref",
"=",
"iokit",
".",
"IOHIDDeviceGetProperty",
"(",
"dev_ref",
",",
"cf_key",
")",
"cf",
".",
"CFRelease",
"(",
"cf_key",
")",
"if",
"... | 29.157895 | 0.019231 |
def are_debian_packages_installed(packages: List[str]) -> Dict[str, bool]:
"""
Check which of a list of Debian packages are installed, via ``dpkg-query``.
Args:
packages: list of Debian package names
Returns:
dict: mapping from package name to boolean ("present?")
"""
assert l... | [
"def",
"are_debian_packages_installed",
"(",
"packages",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"bool",
"]",
":",
"assert",
"len",
"(",
"packages",
")",
">=",
"1",
"require_executable",
"(",
"DPKG_QUERY",
")",
"args",
"=",
"[",... | 36 | 0.00066 |
def _do_batched_op_msg(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Create the next batched insert, update, or delete operation
using OP_MSG.
"""
command['$db'] = namespace.split('.', 1)[0]
if 'writeConcern' in command:
ack = bool(command['writeConcern'].get('w', ... | [
"def",
"_do_batched_op_msg",
"(",
"namespace",
",",
"operation",
",",
"command",
",",
"docs",
",",
"check_keys",
",",
"opts",
",",
"ctx",
")",
":",
"command",
"[",
"'$db'",
"]",
"=",
"namespace",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]"... | 38.6 | 0.001686 |
def send_command_w_enter(self, *args, **kwargs):
"""
For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message
Even though pagination is disabled
show run-config also has excessive delays in the output which requires special
handling.
Arguments are the s... | [
"def",
"send_command_w_enter",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"Must pass in delay_factor as keyword argument\"",
")",
"# If no delay_factor use 1 for def... | 38.784314 | 0.001972 |
def create_labels(da, labels, locations, direction):
"""
Return an OffsetBox with label texts
"""
# The box dimensions are determined by the size of
# the text objects. We put two dummy children at
# either end to gaurantee that when center packed
# the labels in the labels_box matchup with ... | [
"def",
"create_labels",
"(",
"da",
",",
"labels",
",",
"locations",
",",
"direction",
")",
":",
"# The box dimensions are determined by the size of",
"# the text objects. We put two dummy children at",
"# either end to gaurantee that when center packed",
"# the labels in the labels_box... | 34.605263 | 0.00074 |
def save(cls, network=None, phases=[], filename='', delim=' | '):
r"""
Save all the pore and throat property data on the Network (and
optionally on any Phases objects) to CSV files.
Parameters
----------
network : OpenPNM Network
The Network containing the da... | [
"def",
"save",
"(",
"cls",
",",
"network",
"=",
"None",
",",
"phases",
"=",
"[",
"]",
",",
"filename",
"=",
"''",
",",
"delim",
"=",
"' | '",
")",
":",
"project",
",",
"network",
",",
"phases",
"=",
"cls",
".",
"_parse_args",
"(",
"network",
"=",
... | 34.548387 | 0.001817 |
def generate_params(n_items, interval=5.0, ordered=False):
r"""Generate random model parameters.
This function samples a parameter independently and uniformly for each
item. ``interval`` defines the width of the uniform distribution.
Parameters
----------
n_items : int
Number of distin... | [
"def",
"generate_params",
"(",
"n_items",
",",
"interval",
"=",
"5.0",
",",
"ordered",
"=",
"False",
")",
":",
"params",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"low",
"=",
"0",
",",
"high",
"=",
"interval",
",",
"size",
"=",
"n_items",
")",
... | 28.125 | 0.001433 |
def get_variable_scope_name(value):
"""Returns the name of the variable scope indicated by the given value.
Args:
value: String, variable scope, or object with `variable_scope` attribute
(e.g., Sonnet module).
Returns:
The name (a string) of the corresponding variable scope.
Raises:
ValueErro... | [
"def",
"get_variable_scope_name",
"(",
"value",
")",
":",
"# If the object has a \"variable_scope\" property, use it.",
"value",
"=",
"getattr",
"(",
"value",
",",
"\"variable_scope\"",
",",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"tf",
".",
"VariableScop... | 31.428571 | 0.010294 |
def set_duration(self, duration):
""" Android for whatever stupid reason doesn't let you set the time
it only allows 1-long or 0-short. So we have to repeatedly call show
until the duration expires, hence this method does nothing see
`set_show`.
"""
if duration ... | [
"def",
"set_duration",
"(",
"self",
",",
"duration",
")",
":",
"if",
"duration",
"==",
"0",
":",
"self",
".",
"widget",
".",
"setDuration",
"(",
"-",
"2",
")",
"#: Infinite",
"else",
":",
"self",
".",
"widget",
".",
"setDuration",
"(",
"0",
")"
] | 38.181818 | 0.011628 |
def add_put(self, path: str, handler: _WebHandler,
**kwargs: Any) -> AbstractRoute:
"""
Shortcut for add_route with method PUT
"""
return self.add_route(hdrs.METH_PUT, path, handler, **kwargs) | [
"def",
"add_put",
"(",
"self",
",",
"path",
":",
"str",
",",
"handler",
":",
"_WebHandler",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"AbstractRoute",
":",
"return",
"self",
".",
"add_route",
"(",
"hdrs",
".",
"METH_PUT",
",",
"path",
",",
"han... | 39.166667 | 0.0125 |
def fixup_version(destination, version):
"""Newer releases of the SDK do not have the version number set correctly
in the VERSION file. Fix it up."""
version_path = os.path.join(
destination, 'google_appengine', 'VERSION')
with open(version_path, 'r') as f:
version_data = f.read()
... | [
"def",
"fixup_version",
"(",
"destination",
",",
"version",
")",
":",
"version_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination",
",",
"'google_appengine'",
",",
"'VERSION'",
")",
"with",
"open",
"(",
"version_path",
",",
"'r'",
")",
"as",
"f"... | 33.8 | 0.001919 |
def rn_boundary(af, b_hi):
"""
R(n) ratio boundary for selecting between [b_hi-1, b_hi]
alpha = b + 2
"""
return np.sqrt( rn_theory(af, b)*rn_theory(af, b-1) ) | [
"def",
"rn_boundary",
"(",
"af",
",",
"b_hi",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"rn_theory",
"(",
"af",
",",
"b",
")",
"*",
"rn_theory",
"(",
"af",
",",
"b",
"-",
"1",
")",
")"
] | 25.428571 | 0.021739 |
def get_representation(self, prefix="", suffix="\n"):
"""return the string representation of the current object."""
res = prefix + "Section " + self.get_section_name().upper() + suffix
return res | [
"def",
"get_representation",
"(",
"self",
",",
"prefix",
"=",
"\"\"",
",",
"suffix",
"=",
"\"\\n\"",
")",
":",
"res",
"=",
"prefix",
"+",
"\"Section \"",
"+",
"self",
".",
"get_section_name",
"(",
")",
".",
"upper",
"(",
")",
"+",
"suffix",
"return",
"... | 54 | 0.009132 |
def _evalAndDer(self,x):
'''
Returns the level and first derivative of the function at each value in
x. Only called internally by HARKinterpolator1D.eval_and_der.
'''
m = len(x)
fx = np.zeros((m,self.funcCount))
for j in range(self.funcCount):
fx[:,j]... | [
"def",
"_evalAndDer",
"(",
"self",
",",
"x",
")",
":",
"m",
"=",
"len",
"(",
"x",
")",
"fx",
"=",
"np",
".",
"zeros",
"(",
"(",
"m",
",",
"self",
".",
"funcCount",
")",
")",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"funcCount",
")",
":",
... | 35.235294 | 0.013008 |
def com_google_fonts_check_varfont_generate_static(ttFont):
""" Check a static ttf can be generated from a variable font. """
import tempfile
from fontTools.varLib import mutator
try:
loc = {k.axisTag: float((k.maxValue + k.minValue) / 2)
for k in ttFont['fvar'].axes}
with tempfile.Temporary... | [
"def",
"com_google_fonts_check_varfont_generate_static",
"(",
"ttFont",
")",
":",
"import",
"tempfile",
"from",
"fontTools",
".",
"varLib",
"import",
"mutator",
"try",
":",
"loc",
"=",
"{",
"k",
".",
"axisTag",
":",
"float",
"(",
"(",
"k",
".",
"maxValue",
"... | 41.4375 | 0.013274 |
def weighted_choice(choices):
"""Returns a value from choices chosen by weighted random selection
choices should be a list of (value, weight) tuples.
eg. weighted_choice([('val1', 5), ('val2', 0.3), ('val3', 1)])
"""
values, weights = zip(*choices)
total = 0
cum_weights = []
for w in ... | [
"def",
"weighted_choice",
"(",
"choices",
")",
":",
"values",
",",
"weights",
"=",
"zip",
"(",
"*",
"choices",
")",
"total",
"=",
"0",
"cum_weights",
"=",
"[",
"]",
"for",
"w",
"in",
"weights",
":",
"total",
"+=",
"w",
"cum_weights",
".",
"append",
"... | 26.882353 | 0.002114 |
def deserialize(self):
"""
Based on a text based representation of an RSA key this method
instantiates a
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance
"""
# first look for the public parts of a RSA key
if self.n and... | [
"def",
"deserialize",
"(",
"self",
")",
":",
"# first look for the public parts of a RSA key",
"if",
"self",
".",
"n",
"and",
"self",
".",
"e",
":",
"try",
":",
"numbers",
"=",
"{",
"}",
"# loop over all the parameters that define a RSA key",
"for",
"param",
"in",
... | 36.540984 | 0.000874 |
def copy_abiext(self, inext, outext):
"""Copy the Abinit file with extension inext to a new file withw extension outext"""
infile = self.has_abiext(inext)
if not infile:
raise RuntimeError('no file with extension %s in %s' % (inext, self))
for i in range(len(infile) - 1, -1,... | [
"def",
"copy_abiext",
"(",
"self",
",",
"inext",
",",
"outext",
")",
":",
"infile",
"=",
"self",
".",
"has_abiext",
"(",
"inext",
")",
"if",
"not",
"infile",
":",
"raise",
"RuntimeError",
"(",
"'no file with extension %s in %s'",
"%",
"(",
"inext",
",",
"s... | 38.466667 | 0.00846 |
def export(self, passphrase=None, iter=2048, maciter=1):
"""
Dump a PKCS12 object as a string.
For more information, see the :c:func:`PKCS12_create` man page.
:param passphrase: The passphrase used to encrypt the structure. Unlike
some other passphrase arguments, this *must... | [
"def",
"export",
"(",
"self",
",",
"passphrase",
"=",
"None",
",",
"iter",
"=",
"2048",
",",
"maciter",
"=",
"1",
")",
":",
"passphrase",
"=",
"_text_to_bytes_and_warn",
"(",
"\"passphrase\"",
",",
"passphrase",
")",
"if",
"self",
".",
"_cacerts",
"is",
... | 31.694915 | 0.001037 |
def create_parser():
"""Creat a commandline parser for epubcheck
:return Argumentparser:
"""
parser = ArgumentParser(
prog='epubcheck',
description="EpubCheck v%s - Validate your ebooks" % __version__
)
# Arguments
parser.add_argument(
'path',
nargs='?',
... | [
"def",
"create_parser",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"'epubcheck'",
",",
"description",
"=",
"\"EpubCheck v%s - Validate your ebooks\"",
"%",
"__version__",
")",
"# Arguments",
"parser",
".",
"add_argument",
"(",
"'path'",
",",
... | 24.5 | 0.000981 |
async def request(self, value: Any) -> Any:
"""\
Sends a command to and receives the reply from the task.
"""
await self.send(value)
return await self.recv() | [
"async",
"def",
"request",
"(",
"self",
",",
"value",
":",
"Any",
")",
"->",
"Any",
":",
"await",
"self",
".",
"send",
"(",
"value",
")",
"return",
"await",
"self",
".",
"recv",
"(",
")"
] | 32 | 0.010152 |
def cache(self):
"""Caches the result of loader(filename) to cachename."""
msg = 'Saving updates from more recent "%s" to "%s"'
log.info(msg, self.filename, self.cachename)
with open(self.cachename, 'wb') as output:
cPickle.dump(self._dict, output, -1) | [
"def",
"cache",
"(",
"self",
")",
":",
"msg",
"=",
"'Saving updates from more recent \"%s\" to \"%s\"'",
"log",
".",
"info",
"(",
"msg",
",",
"self",
".",
"filename",
",",
"self",
".",
"cachename",
")",
"with",
"open",
"(",
"self",
".",
"cachename",
",",
"... | 46.833333 | 0.024476 |
def get_source(self, id, **kwargs): # noqa: E501
"""Get a specific source for a customer # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_source(id, async_... | [
"def",
"get_source",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"get_source_with_h... | 40.142857 | 0.002317 |
async def findArtifactFromTask(self, *args, **kwargs):
"""
Get Artifact From Indexed Task
Find a task by index path and redirect to the artifact on the most recent
run with the given `name`.
Note that multiple calls to this endpoint may return artifacts from differen tasks
... | [
"async",
"def",
"findArtifactFromTask",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"findArtifactFromTask\"",
"]",
",",
"*",
"args",
",",
"*",
"*",... | 51.782609 | 0.009893 |
def update_scalars(self, scalars, mesh=None, render=True):
"""
Updates scalars of the an object in the plotter.
Parameters
----------
scalars : np.ndarray
Scalars to replace existing scalars.
mesh : vtk.PolyData or vtk.UnstructuredGrid, optional
... | [
"def",
"update_scalars",
"(",
"self",
",",
"scalars",
",",
"mesh",
"=",
"None",
",",
"render",
"=",
"True",
")",
":",
"if",
"mesh",
"is",
"None",
":",
"mesh",
"=",
"self",
".",
"mesh",
"if",
"isinstance",
"(",
"mesh",
",",
"(",
"collections",
".",
... | 30.932203 | 0.001593 |
def fromfile(self, path_to_file, mimetype=None):
"""
load blob content from file in StorageBlobModel instance. Parameters are:
- path_to_file (required): path to a local file
- mimetype (optional): set a mimetype. azurestoragewrap will guess it if not given
"""
if os.... | [
"def",
"fromfile",
"(",
"self",
",",
"path_to_file",
",",
"mimetype",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path_to_file",
")",
":",
"# Load file into self.__content__",
"self",
".",
"filename",
"=",
"os",
".",
"path",
".",
... | 40.666667 | 0.009608 |
def _add_play_button(self, image_url, image_path):
"""Try to add a play button to the screenshot."""
try:
from PIL import Image
from tempfile import NamedTemporaryFile
import urllib
try:
urlretrieve = urllib.request.urlretrieve
... | [
"def",
"_add_play_button",
"(",
"self",
",",
"image_url",
",",
"image_path",
")",
":",
"try",
":",
"from",
"PIL",
"import",
"Image",
"from",
"tempfile",
"import",
"NamedTemporaryFile",
"import",
"urllib",
"try",
":",
"urlretrieve",
"=",
"urllib",
".",
"request... | 42.870968 | 0.001472 |
def bipart(func, seq):
r"""Like a partitioning version of `filter`. Returns
``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``.
Example:
>>> bipart(bool, [1,None,2,3,0,[],[0]])
[[None, 0, []], [1, 2, 3, [0]]]
"""
if func is None: func = bool
res = [[],[]]
for i in... | [
"def",
"bipart",
"(",
"func",
",",
"seq",
")",
":",
"if",
"func",
"is",
"None",
":",
"func",
"=",
"bool",
"res",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"for",
"i",
"in",
"seq",
":",
"res",
"[",
"not",
"not",
"func",
"(",
"i",
")",
"]",
"... | 25.571429 | 0.010782 |
def buckets(bucket=None, account=None, matched=False, kdenied=False,
errors=False, dbpath=None, size=None, denied=False,
format=None, incomplete=False, oversize=False, region=(),
not_region=(), inventory=None, output=None, config=None, sort=None,
tagprefix=None, not_bucke... | [
"def",
"buckets",
"(",
"bucket",
"=",
"None",
",",
"account",
"=",
"None",
",",
"matched",
"=",
"False",
",",
"kdenied",
"=",
"False",
",",
"errors",
"=",
"False",
",",
"dbpath",
"=",
"None",
",",
"size",
"=",
"None",
",",
"denied",
"=",
"False",
"... | 34.966102 | 0.000471 |
def get_item(self, url):
"""
Returned item should have specific interface. See module docstring.
"""
_hash = self.build_hash(url)
query = {'_id': _hash}
return self.dbase.cache.find_one(query) | [
"def",
"get_item",
"(",
"self",
",",
"url",
")",
":",
"_hash",
"=",
"self",
".",
"build_hash",
"(",
"url",
")",
"query",
"=",
"{",
"'_id'",
":",
"_hash",
"}",
"return",
"self",
".",
"dbase",
".",
"cache",
".",
"find_one",
"(",
"query",
")"
] | 29.25 | 0.008299 |
def find_TPs_and_DUPs(self, percent=5., makefig=False):
"""
Function which finds TPs and uses the calc_DUP_parameter
function. To calculate DUP parameter evolution dependent of
the star or core mass.
Parameters
----------
fig : integer
Figure number ... | [
"def",
"find_TPs_and_DUPs",
"(",
"self",
",",
"percent",
"=",
"5.",
",",
"makefig",
"=",
"False",
")",
":",
"t0_model",
"=",
"self",
".",
"find_first_TP",
"(",
")",
"t0_idx",
"=",
"(",
"t0_model",
"-",
"self",
".",
"get",
"(",
"\"model_number\"",
")",
... | 37.149533 | 0.011027 |
def update_doc(input, **params):
"""
Updates document with value from another document
:param input:
:param params:
:return:
"""
PARAM_SOURCE = 'source'
SOURCE_COL = 'src.col'
SOURCE_FIELD = 'src.field'
PARAM_RESULT = 'result'
res = input[params.get(PARAM_RESULT)]
for sr... | [
"def",
"update_doc",
"(",
"input",
",",
"*",
"*",
"params",
")",
":",
"PARAM_SOURCE",
"=",
"'source'",
"SOURCE_COL",
"=",
"'src.col'",
"SOURCE_FIELD",
"=",
"'src.field'",
"PARAM_RESULT",
"=",
"'result'",
"res",
"=",
"input",
"[",
"params",
".",
"get",
"(",
... | 26.5625 | 0.002273 |
def help(handler):
"""
Returns a Markdown document that describes this handler and
it's operations.
"""
data = {'operation': 'describe'}
response = handler.invoke(data, raw=True)
description = response.data
lines = []
lines.append('# {}'.format(handler.lambda_fn))
lines.append('#... | [
"def",
"help",
"(",
"handler",
")",
":",
"data",
"=",
"{",
"'operation'",
":",
"'describe'",
"}",
"response",
"=",
"handler",
".",
"invoke",
"(",
"data",
",",
"raw",
"=",
"True",
")",
"description",
"=",
"response",
".",
"data",
"lines",
"=",
"[",
"]... | 33.170732 | 0.000714 |
def update(self, obj, set_fields = None, unset_fields = None, update_obj = True):
"""
We return the result of the save method (updates are not yet implemented here).
"""
if set_fields:
if isinstance(set_fields,(list,tuple)):
set_attributes = {}
... | [
"def",
"update",
"(",
"self",
",",
"obj",
",",
"set_fields",
"=",
"None",
",",
"unset_fields",
"=",
"None",
",",
"update_obj",
"=",
"True",
")",
":",
"if",
"set_fields",
":",
"if",
"isinstance",
"(",
"set_fields",
",",
"(",
"list",
",",
"tuple",
")",
... | 33.933333 | 0.021968 |
def reset(self):
"""
Clear the active cells.
"""
self.activePhases = np.empty((0,2), dtype="float")
self.phaseDisplacement = np.empty((0,2), dtype="float")
self.cellsForActivePhases = np.empty(0, dtype="int")
self.activeCells = np.empty(0, dtype="int")
self.sensoryAssociatedCells = np.em... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"activePhases",
"=",
"np",
".",
"empty",
"(",
"(",
"0",
",",
"2",
")",
",",
"dtype",
"=",
"\"float\"",
")",
"self",
".",
"phaseDisplacement",
"=",
"np",
".",
"empty",
"(",
"(",
"0",
",",
"2",
... | 36.777778 | 0.00885 |
def _apply_axes_mapping(self, target, inverse=False):
"""
Apply the transposition to the target iterable.
Parameters
----------
target - iterable
The iterable to transpose. This would be suitable for things
such as a shape as well as a list of ``__getitem... | [
"def",
"_apply_axes_mapping",
"(",
"self",
",",
"target",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"len",
"(",
"target",
")",
"!=",
"self",
".",
"ndim",
":",
"raise",
"ValueError",
"(",
"'The target iterable is of length {}, but '",
"'should be of length {}.'... | 35.181818 | 0.001676 |
def arc_data(self):
"""Return the map from filenames to lists of line number pairs."""
return dict(
[(f, sorted(amap.keys())) for f, amap in iitems(self.arcs)]
) | [
"def",
"arc_data",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"f",
",",
"sorted",
"(",
"amap",
".",
"keys",
"(",
")",
")",
")",
"for",
"f",
",",
"amap",
"in",
"iitems",
"(",
"self",
".",
"arcs",
")",
"]",
")"
] | 39.4 | 0.00995 |
def create(context, name, password, team_id, active, email, fullname):
"""create(context, name, password, team_id, active, email, fullname)
Create a user.
>>> dcictl user-create [OPTIONS]
:param string name: Name of the user [required]
:param string password: Password for the user [required]
... | [
"def",
"create",
"(",
"context",
",",
"name",
",",
"password",
",",
"team_id",
",",
"active",
",",
"email",
",",
"fullname",
")",
":",
"team_id",
"=",
"team_id",
"or",
"identity",
".",
"my_team_id",
"(",
"context",
")",
"fullname",
"=",
"fullname",
"or",... | 44.55 | 0.001099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.