text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_matrix(theta, phi, psi, dx, dy, dz,
matrix=np.zeros((4, 4), dtype=DTYPE),
angles=np.zeros(3, dtype=DTYPE)):
"""
Build the rotation-translation matrix.
It has the form:
[ | dx ]
[ R | dy ]
[ | dz ]
... | 0.003742 |
def _pack(self, content):
"""pack the content using serializer and compressor"""
if self.serializer:
content = self.serializer.serialize(content)
if self.compressor:
content = self.compressor.compress(content)
return content | 0.007143 |
def is_valid_identifier(identifier):
"""Checks if the given identifier is valid or not. A valid
identifier may consists of the following characters with a
maximum length of 100 characters, minimum of 1 character.
Valid characters for an identifier,
- A to Z
- a to z
- 0 to 9
... | 0.00161 |
def audit(func):
"""
Record a Flask route function in the audit log.
Generates a JSON record in the Flask log for every request.
"""
@wraps(func)
def wrapper(*args, **kwargs):
options = AuditOptions(
include_request_body=DEFAULT_INCLUDE_REQUEST_BODY,
include_res... | 0.001773 |
def list_targets_by_instance(self, instance_id, target_list=None):
"""Returns a list of FloatingIpTarget objects of FIP association.
:param instance_id: ID of target VM instance
:param target_list: (optional) a list returned by list_targets().
If specified, looking up is done agains... | 0.001284 |
def evaluatePotentials(Pot,R,z,phi=None,t=0.,dR=0,dphi=0):
"""
NAME:
evaluatePotentials
PURPOSE:
convenience function to evaluate a possible sum of potentials
INPUT:
Pot - potential or list of potentials (dissipative forces in such a list are ignored)
R - cylindrical Ga... | 0.020243 |
def _set_strip_header(self, v, load=False):
"""
Setter method for strip_header, mapped from YANG variable /interface/ethernet/strip_header (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_strip_header is considered as a private
method. Backends looking t... | 0.004129 |
def compress_artifact_if_supported(artifact_path):
"""Compress artifacts with GZip if they're known to be supported.
This replaces the artifact given by a gzip binary.
Args:
artifact_path (str): the path to compress
Returns:
content_type, content_encoding (tuple): Type and encoding o... | 0.0036 |
def decode(self, query):
"""I transform query parameters into an L{OpenIDRequest}.
If the query does not seem to be an OpenID request at all, I return
C{None}.
@param query: The query parameters as a dictionary with each
key mapping to one value.
@type query: dict
... | 0.001441 |
def set_scale_limits(self, scale_min, scale_max):
"""Set scale limits.
Parameters
----------
scale_min, scale_max : float
Minimum and maximum scale limits, respectively.
"""
# TODO: force scale to within limits if already outside?
self.t_.set(scale_m... | 0.00565 |
def write(self, title, data, output=None):
'''
Add a data to the current opened section.
:return:
'''
if not isinstance(data, (dict, list, tuple)):
data = {'raw-content': str(data)}
output = output or self.__default_outputter
if output != 'null':
... | 0.002123 |
def update_database(adapter, variant_file=None, sv_file=None, family_file=None, family_type='ped',
skip_case_id=False, gq_treshold=None, case_id=None, max_window = 3000):
"""Update a case in the database
Args:
adapter: Connection to database
variant_file(str): Path t... | 0.005043 |
def backend():
"""
:return:
A unicode string of the backend being used: "openssl", "osx", "win",
"winlegacy"
"""
if _module_values['backend'] is not None:
return _module_values['backend']
with _backend_lock:
if _module_values['backend'] is not None:
retu... | 0.001242 |
def check_lazy_load_sectie(f):
'''
Decorator function to lazy load a :class:`Sectie`.
'''
def wrapper(self):
sectie = self
if (getattr(sectie, '_%s' % f.__name__, None) is None):
log.debug('Lazy loading Sectie %s in Afdeling %d', sectie.id, sectie.afdeling.id)
se... | 0.003339 |
def write(self,
features=None,
outfile=None,
format=0,
is_leaf_fn=None,
format_root_node=False,
dist_formatter=None,
support_formatter=None,
name_formatter=None):
"""
Returns the newick representation of current node. Several
... | 0.013514 |
def FloatGreaterThanEqualToZero(x):
"""If *x* is a float >= 0, returns it, otherwise raises and error.
>>> print('%.1f' % FloatGreaterThanEqualToZero('1.5'))
1.5
>>> print('%.1f' % FloatGreaterThanEqualToZero('-1.1'))
Traceback (most recent call last):
...
ValueError: -1.1 not float gre... | 0.003401 |
def run_parallel_map_providers_query(data, queue=None):
'''
This function will be called from another process when building the
providers map.
'''
salt.utils.crypt.reinit_crypto()
cloud = Cloud(data['opts'])
try:
with salt.utils.context.func_globals_inject(
cloud.clouds[... | 0.000991 |
def remove_input(urls, preserves, verbose = False):
"""
Attempt to delete all files identified by the URLs in urls except
any that are the same as the files in the preserves list.
"""
for path in map(url2path, urls):
if any(os.path.samefile(path, preserve) for preserve in preserves):
continue
if verbose:
... | 0.041162 |
def generate_contact_list(config, args):
"""TODO: Docstring for generate_contact_list.
:param config: the config object to use
:type config: config.Config
:param args: the command line arguments
:type args: argparse.Namespace
:returns: the contacts for further processing (TODO)
:rtype: list... | 0.000446 |
def get_order(tre):
"""
return tree order
"""
anode = tre.tree&">A"
sister = anode.get_sisters()[0]
sisters = (anode.name[1:], sister.name[1:])
others = [i for i in list("ABCD") if i not in sisters]
return sorted(sisters) + sorted(others) | 0.007407 |
def run_board(args):
"""
Run main entry for AutoMLBoard.
Args:
args: args parsed from command line
"""
init_config(args)
# backend service, should import after django settings initialized
from backend.collector import CollectorService
service = CollectorService(
args.l... | 0.001441 |
def finalize(self):
""" Is called before destruction (when closing).
Can be used to clean-up resources.
"""
logger.debug("Finalizing: {}".format(self))
# Disconnect signals
self.collector.sigContentsChanged.disconnect(self.collectorContentsChanged)
self._conf... | 0.008961 |
def transform(self, trajs_tuple, y=None):
"""Featurize a several trajectories.
Parameters
----------
traj_list : list(mdtraj.Trajectory)
Trajectories to be featurized.
Returns
-------
features : list(np.ndarray), length = len(traj_list)
T... | 0.00346 |
def build_self_reference(filename, clean_wcs=False):
""" This function creates a reference, undistorted WCS that can be used to
apply a correction to the WCS of the input file.
Parameters
----------
filename : str
Filename of image which will be corrected, and which will form the basis
... | 0.004018 |
def load(self, data, size=None):
"""Data is cffi array"""
self.bind()
if size is None:
# ffi's sizeof understands arrays
size = sizeof(data)
if size == self.buffer_size:
# same size - no need to allocate new buffer, just copy
glBufferSubDat... | 0.002625 |
def constant_fold(code, silent=True, ignore_errors=True):
"""Constant-folds simple expressions like 2 3 + to 5.
Args:
code: Code in non-native types.
silent: Flag that controls whether to print optimizations made.
ignore_errors: Whether to raise exceptions on found errors.
"""
#... | 0.004952 |
def plot_cells(cell_1, cell_2, cell_3):
"""Plots three cells"""
fig, ((ax1, ax2, ax3)) = plt.subplots(1, 3, figsize=(12, 5))
for ax in [ax1, ax2, ax3]:
ax.grid(False)
ax.set_xticks([])
ax.set_yticks([])
ax1.set_title("Type 1")
ax1.imshow(cell_1)
ax2.set_title("Type 2")
... | 0.002404 |
def open_external_editor(filename=None, sql=None):
"""Open external editor, wait for the user to type in their query, return
the query.
:return: list with one tuple, query as first element.
"""
message = None
filename = filename.strip().split(' ', 1)[0] if filename else None
sql = sql or '... | 0.000959 |
def to_bytes(self):
'''
Return packed byte representation of the TCP header.
'''
header = self._make_header(self._checksum)
return header + self._options.to_bytes() | 0.009804 |
def cmd(send, msg, args):
"""Gets previous nicks.
Syntax: {command} <nick>
"""
if not msg:
with args['handler'].data_lock:
users = list(args['handler'].channels[args['target']].users()) if args['target'] != 'private' else [args['nick']]
msg = choice(users)
chain = get_c... | 0.004415 |
def process_frames_face(self, frames):
"""
Preprocess from frames using face detector
"""
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(self.face_predictor_path)
mouth_frames = self.get_frames_mouth(detector, predictor, frames)
self.... | 0.004283 |
def _delete_membership(self, pipeline=None):
"""Removes the id of the object to the set of all objects of the
same class.
"""
Set(self._key['all'], pipeline=pipeline).remove(self.id) | 0.009346 |
def _log_exception(self, exception):
"""
Logs an exception.
:param Exception exception: The exception.
:rtype: None
"""
self._io.error(str(exception).strip().split(os.linesep)) | 0.00885 |
def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret | 0.003788 |
def sync_map_leaves(self, fragment_type=None):
"""
Return the list of non-empty leaves
in the sync map associated with the task.
If ``fragment_type`` has been specified,
return only leaves of that fragment type.
:param int fragment_type: type of fragment to return
... | 0.003676 |
def setDisabledPenColor(self, color):
"""
Sets the pen color to be used when drawing this node as disabled.
:param color | <QColor>
"""
color = QColor(color)
if self._palette is None:
self._palette = XNodePalette(self._scenePalette)
... | 0.008114 |
def build_on_event(self, runnable, regime, on_event):
"""
Build OnEvent event handler code.
@param on_event: OnEvent event handler object
@type on_event: lems.model.dynamics.OnEvent
@return: Generated OnEvent code
@rtype: list(string)
"""
on_event_code =... | 0.010152 |
def from_gpx(gpx_segment):
""" Creates a segment from a GPX format.
No preprocessing is done.
Arguments:
gpx_segment (:obj:`gpxpy.GPXTrackSegment`)
Return:
:obj:`Segment`
"""
points = []
for point in gpx_segment.points:
points... | 0.005249 |
async def stop_slaves(self, timeout=1):
"""Stop all the slaves by sending a stop-message to their managers.
:param int timeout:
Timeout for connecting to each manager. If a connection can not
be made before the timeout expires, the resulting error for that
particular... | 0.004464 |
def rows(self, csv=False):
"""
Returns each row based on the selected criteria.
"""
# Store the index of each field against its ID for building each
# entry row with columns in the correct order. Also store the IDs of
# fields with a type of FileField or Date-like for sp... | 0.000443 |
def _add_to_submit_args(s):
"""Adds string s to the PYSPARK_SUBMIT_ARGS env var"""
new_args = os.environ.get("PYSPARK_SUBMIT_ARGS", "") + (" %s" % s)
os.environ["PYSPARK_SUBMIT_ARGS"] = new_args
return new_args | 0.004425 |
def admin_print_styles_single(request):
""" Returns all books with any version of the given print style.
Returns the print_style, recipe type, num books using the print_style,
along with a dictionary of the book, author, revision date, recipe,
tag of the print_style, and a link to the content.
"""
... | 0.000235 |
def encodePathElement(element):
"""Encode a URL path element according to RFC3986."""
return urllib.parse.quote(
(
element.encode('utf-8')
if isinstance(element, str)
else str(element)
if isinstance(element, int)
else element
),
... | 0.002667 |
def p_expression_uxnor(self, p):
'expression : XNOR expression %prec UXNOR'
p[0] = Uxnor(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | 0.011976 |
def _find_from_file(full_doc, from_file_keyword):
"""
Finds a line in <full_doc> like
<from_file_keyword> <colon> <path>
and return path
"""
path = None
for line in full_doc.splitlines():
if from_file_keyword in line:
parts = line.strip().split(':')
if ... | 0.002188 |
def validate(mcs, bases, attributes):
"""Check attributes."""
if bases[0] is object:
return None
mcs.check_model_cls(attributes)
mcs.check_include_exclude(attributes)
mcs.check_properties(attributes) | 0.007968 |
def project_top_dir(self, *args) -> str:
""" Project top-level directory """
return os.path.join(self.project_dir, *args) | 0.014599 |
def add_dimension(cls, columns, dimension, dim_pos, values, vdim):
"""
Adding value dimensions not currently supported by iris interface.
Adding key dimensions not possible on dense interfaces.
"""
if not vdim:
raise Exception("Cannot add key dimension to a dense repr... | 0.008174 |
def perfect_platonic_per_pixel(N, R, scale=11, pos=None, zscale=1.0, returnpix=None):
"""
Create a perfect platonic sphere of a given radius R by supersampling by a
factor scale on a grid of size N. Scale must be odd.
We are able to perfectly position these particles up to 1/scale. Therefore,
let'... | 0.011505 |
def moveToReplayContext(self, r):
'set the sheet/row/col to the values in the replay row. return sheet'
if not r.sheet:
# assert not r.col and not r.row
return self # any old sheet should do, row/column don't matter
try:
sheetidx = int(r.sheet)
v... | 0.005734 |
def set_cache_buster(redis, path, hash):
"""Sets the cache buster value for a given file path"""
redis.hset("cache-buster:{}:v3".format(oz.settings["s3_bucket"]), path, hash) | 0.010989 |
def getftype(self, name):
"""Returns the python type for the specified field name. The field list is
cached so multiple calls do not invoke a getFields request each time.
@param name(string) The name of the SOLR field
@returns Python type of the field.
"""
fields = sel... | 0.003774 |
def demo(host, port):
"""Basic demo of the monitoring capabilities."""
# logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
stl = AsyncSatel(host,
port,
loop,
[1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15, 16, 17, 18, 19,
... | 0.001462 |
def read(self, vals):
"""Read values.
Args:
vals (list): list of strings representing values
"""
i = 0
if len(vals[i]) == 0:
self.ground_temperature_depth = None
else:
self.ground_temperature_depth = vals[i]
i += 1
if ... | 0.000654 |
def add_nodes(self, nodes, nesting=1):
"""
Adds edges showing dependencies between source files listed in
the nodes.
"""
hopNodes = set() # nodes in this hop
hopEdges = [] # edges in this hop
# get nodes and edges for this hop
for i, n in zip(range(le... | 0.002635 |
def _rfc3339_nanos_to_datetime(dt_str):
"""Convert a nanosecond-precision timestamp to a native datetime.
.. note::
Python datetimes do not support nanosecond precision; this function
therefore truncates such values to microseconds.
:type dt_str: str
:param dt_str: The string to conver... | 0.000878 |
def build_kernel(self):
"""Build the MNN kernel.
Build a mutual nearest neighbors kernel.
Returns
-------
K : kernel matrix, shape=[n_samples, n_samples]
symmetric matrix with ones down the diagonal
with no non-negative entries.
"""
taskl... | 0.000622 |
def handle(send, msg, args):
"""Get titles for urls.
Generate a short url. Get the page title.
"""
worker = args["handler"].workers
result = worker.run_pool(get_urls, [msg])
try:
urls = result.get(5)
except multiprocessing.TimeoutError:
worker.restart_pool()
send("U... | 0.003557 |
def _init_create_child(self):
"""
Initialize the base class :attr:`create_child` and
:attr:`create_child_args` according to whether we need a PTY or not.
"""
if self._requires_pty():
self.create_child = mitogen.parent.hybrid_tty_create_child
else:
... | 0.004376 |
def flatten4d3d(x):
"""Flatten a 4d-tensor into a 3d-tensor by joining width and height."""
xshape = shape_list(x)
result = tf.reshape(x, [xshape[0], xshape[1] * xshape[2], xshape[3]])
return result | 0.024272 |
def _upload_file(self, file_name, full_path, quiet, request, resources):
""" Helper function to upload a single file
Parameters
==========
file_name: name of the file to upload
full_path: path to the file to upload
request: the prepared request
... | 0.001115 |
def participants(self, **kwargs):
"""List the participants.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool... | 0.002304 |
def main():
""" Main function for command line usage """
usage = "usage: %(prog)s [options] "
description = "Merge a set of Fermi-LAT files."
parser = argparse.ArgumentParser(usage=usage, description=description)
parser.add_argument('-o', '--output', default=None, type=str,
... | 0.001821 |
def can_be_(self, state):
"""Check if machine can transit to given state."""
translator = self._meta['translator']
state = translator.translate(state)
if self._meta['complete']:
return True
if self.actual_state is None:
return True
transitions = self._meta['transitions'][self.... | 0.00274 |
def get_imported_namespaces(self,
must_have_imported_data_type=False,
consider_annotations=False,
consider_annotation_types=False):
# type: (bool, bool, bool) -> typing.List[ApiNamespace]
"""
Returns ... | 0.003962 |
def exportChatInviteLink(self, chat_id):
""" See: https://core.telegram.org/bots/api#exportchatinvitelink """
p = _strip(locals())
return self._api_request('exportChatInviteLink', _rectify(p)) | 0.009259 |
def _isDissipative(obj):
"""
NAME:
_isDissipative
PURPOSE:
Determine whether this combination of potentials and forces is Dissipative
INPUT:
obj - Potential/DissipativeForce instance or list of such instances
OUTPUT:
True or False depending on whether the object is... | 0.014265 |
def static_file(filename, root,
mimetype=True,
download=False,
charset='UTF-8',
etag=None):
""" Open a file in a safe way and return an instance of :exc:`HTTPResponse`
that can be sent back to the client.
:param filename: Name or path ... | 0.00196 |
def get_topic_for_path(channel, chan_path_tuple):
"""
Given channel (dict) that contains a hierary of TopicNode dicts, we use the
walk the path given in `chan_path_tuple` to find the corresponding TopicNode.
"""
assert chan_path_tuple[0] == channel['dirname'], 'Wrong channeldir'
chan_path_list =... | 0.004688 |
def get_process_parser(self, process_id_or_name):
"""
Returns the ProcessParser for the given process ID or name. It matches
by name first.
"""
if process_id_or_name in self.process_parsers_by_name:
return self.process_parsers_by_name[process_id_or_name]
else:... | 0.005263 |
def adjustButtons( self ):
"""
Adjusts the placement of the buttons for this line edit.
"""
y = 1
for btn in self.buttons():
btn.setIconSize(self.iconSize())
btn.setFixedSize(QSize(self.height() - 2, self.height() - 2))
# adju... | 0.013195 |
def get_batch_unlock_gain(
channel_state: NettingChannelState,
) -> UnlockGain:
"""Collect amounts for unlocked/unclaimed locks and onchain unlocked locks.
Note: this function does not check expiry, so the values make only sense during settlement.
Returns:
gain_from_partner_locks: locks amo... | 0.006052 |
def SetClipboardText(text: str) -> bool:
"""
Return bool, True if succeed otherwise False.
"""
if ctypes.windll.user32.OpenClipboard(0):
ctypes.windll.user32.EmptyClipboard()
textByteLen = (len(text) + 1) * 2
hClipboardData = ctypes.windll.kernel32.GlobalAlloc(0, textByteLen) # ... | 0.005411 |
def update_progress(self, progress, prefix=''):
"""
Print a progress bar for longer-running scripts.
The progress value is a value between 0.0 and 1.0. If a prefix is
present, it will be printed before the progress bar.
"""
total_length = 40
if progress == 1.:
... | 0.002522 |
def _async_raise(tid, exctype):
"""
raises the exception, performs cleanup if needed
参考: https://www.oschina.net/question/172446_2159505
"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.... | 0.003778 |
def _pfp__process_metadata(self):
"""Process the metadata once the entire struct has been
declared.
"""
if self._pfp__metadata_processor is None:
return
metadata_info = self._pfp__metadata_processor()
if isinstance(metadata_info, list):
for metada... | 0.002326 |
def contractString(self, contract, seperator="_"):
""" returns string from contract tuple """
localSymbol = ""
contractTuple = contract
if type(contract) != tuple:
localSymbol = contract.m_localSymbol
contractTuple = self.contract_to_tuple(contract)
# b... | 0.004812 |
def find_one(self, query):
"""Find one wrapper with conversion to dictionary
:param dict query: A Mongo query
"""
mongo_response = yield self.collection.find_one(query)
raise Return(self._obj_cursor_to_dictionary(mongo_response)) | 0.007407 |
def calculate_basic_cost(self, d1, d2):
"""
Calculates assignment cost between two cells.
"""
distance = euclidean_dist(d1.center, d2.center) / self.scale
area_change = 1 - min(d1.area, d2.area) / max(d1.area, d2.area)
return distance + self.parameters_cost_initial["are... | 0.008721 |
def delete_workflow(self, workflow_id):
"""
Delete a workflow from the database
:param workflow_id:
:return: None
"""
deleted = False
with switch_db(WorkflowDefinitionModel, "hyperstream"):
workflows = WorkflowDefinitionModel.objects(workflow_id=workf... | 0.004525 |
def download_satellite_image(self, metaimage, x=None, y=None, zoom=None, palette=None):
"""
Downloads the satellite image described by the provided metadata. In case the satellite image is a tile, then
tile coordinates and zoom must be provided. An optional palette ID can be provided, if support... | 0.004954 |
def version(self):
""" Return kernel and btrfs version. """
return dict(
buttersink=theVersion,
btrfs=self.butterStore.butter.btrfsVersion,
linux=platform.platform(),
) | 0.008772 |
def import_entities(self, entities):
"""Upload entity objects.
Args:
entities: iterable of firecloud.Entity objects.
"""
edata = Entity.create_payload(entities)
r = fapi.upload_entities(self.namespace, self.name,
edata, self.api_url)
... | 0.00554 |
def poly_to_power_basis(bezier_coeffs):
"""Convert a B |eacute| zier curve to polynomial in power basis.
.. note::
This assumes, but does not verify, that the "B |eacute| zier
degree" matches the true degree of the curve. Callers can
guarantee this by calling :func:`.full_reduce`.
Ar... | 0.000555 |
def _trj_store_meta_data(self, traj):
""" Stores general information about the trajectory in the hdf5file.
The `info` table will contain the name of the trajectory, it's timestamp, a comment,
the length (aka the number of single runs), and the current version number of pypet.
Also prep... | 0.004274 |
def trim_sparse(M, n_std=3, s_min=None, s_max=None):
"""Apply the trimming procedure to a sparse matrix.
"""
try:
from scipy.sparse import coo_matrix
except ImportError as e:
print(str(e))
print("I am peforming dense normalization by default.")
return trim_dense(M.todens... | 0.001125 |
def AgregarConceptosBasicosMercadoInterno(self, kg_produccion_gb, precio_por_kg_produccion_gb,
kg_produccion_pr, precio_por_kg_produccion_pr,
kg_crecimiento_gb, precio_por_kg_crecimiento_gb,
... | 0.017674 |
def split_code_and_text_blocks(source_file):
"""Return list with source file separated into code and text blocks.
Returns
-------
blocks : list of (label, content)
List where each element is a tuple with the label ('text' or 'code'),
and content string of block.
"""
docstring, r... | 0.000781 |
def import_users(self, users):
""" Import users, returns import result (http://confluence.jetbrains.net/display/YTD2/Import+Users)
Example: importUsers([{'login':'vadim', 'fullName':'vadim', 'email':'eee@ss.com', 'jabber':'fff@fff.com'},
{'login':'maxim', 'fullName'... | 0.006764 |
def actual_query(self):
"""Extract the actual query (not pattern) from operations."""
if not self._actual_query:
# trigger evaluation of operation
if (self.operation in ['query', 'getmore', 'update', 'remove'] or
self.command in ['count', 'findandmodify']):
... | 0.003273 |
def _nextJob(self, job, nextRound=True):
"""
Given a completed job, start the next job in the round, or return None
:param nextRound: whether to start jobs from the next round if the current round is completed.
:return: the newly started Job, or None if no job was started
"""
... | 0.002686 |
def list_views():
"""
List all registered views
"""
echo_header("List of registered views")
for view in current_app.appbuilder.baseviews:
click.echo(
"View:{0} | Route:{1} | Perms:{2}".format(
view.__class__.__name__, view.route_base, view.base_permissions
... | 0.002941 |
def cluster(x, cluster='KMeans', n_clusters=3, ndims=None, format_data=True):
"""
Performs clustering analysis and returns a list of cluster labels
Parameters
----------
x : A Numpy array, Pandas Dataframe or list of arrays/dfs
The data to be clustered. You can pass a single array/df or a ... | 0.004262 |
def find_tendril(cls, proto, addr):
"""
Finds the tendril corresponding to the protocol and address
tuple. Returns the Tendril object, or raises KeyError if the
tendril is not tracked.
The address tuple is the tuple of the local address and the
remote address for the te... | 0.004065 |
def set_joinstyle(self, js):
"""
Set the join style to be one of ('miter', 'round', 'bevel')
"""
DEBUG_MSG("set_joinstyle()", 1, self)
self.select()
GraphicsContextBase.set_joinstyle(self, js)
self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle])
se... | 0.005376 |
def upload(c, directory, index=None, sign=False, dry_run=False):
"""
Upload (potentially also signing) all artifacts in ``directory``.
:param str index:
Custom upload index/repository name.
By default, uses whatever the invoked ``pip`` is configured to use.
Modify your ``pypirc`` f... | 0.000419 |
def color_val(color):
"""Convert various input to color tuples.
Args:
color (:obj:`Color`/str/tuple/int/ndarray): Color inputs
Returns:
tuple[int]: A tuple of 3 integers indicating BGR channels.
"""
if is_str(color):
return Color[color].value
elif isinstance(color, Colo... | 0.001082 |
def _argspec(func):
""" For a callable, get the full argument spec
:type func: Callable
:rtype: list[data.ArgumentSpec]
"""
assert isinstance(func, collections.Callable), 'Argument must be a callable'
try: sp = inspect.getargspec(func) if six.PY2 else inspect.getfullargspec(func)
except T... | 0.005204 |
def _rewrite_where(self, q):
"""
Rewrite field names inside WHERE tree.
"""
if isinstance(q, Lookup):
self._rewrite_col(q.lhs)
if isinstance(q, Node):
for child in q.children:
self._rewrite_where(child) | 0.007092 |
def aghmean(nums):
"""Return arithmetic-geometric-harmonic mean.
Iterates over arithmetic, geometric, & harmonic means until they
converge to a single value (rounded to 12 digits), following the
method described in :cite:`Raissouli:2009`.
Parameters
----------
nums : list
A series ... | 0.000979 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.