_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q22300 | _basis2name | train | def _basis2name(basis):
"""
converts the 'basis' into the proper name.
"""
component_name = (
'DC' if basis == 'diffmap'
else 'tSNE' if basis == 'tsne'
else 'UMAP' if basis == 'umap'
else 'PC' if basis == 'pca'
else basis.replace('draw_graph_', '').upper() if 'dr... | python | {
"resource": ""
} |
q22301 | dendrogram | train | def dendrogram(adata: AnnData, groupby: str,
n_pcs: Optional[int]=None,
use_rep: Optional[str]=None,
var_names: Optional[List[str]]=None,
use_raw: Optional[bool]=None,
cor_method: Optional[str]='pearson',
linkage_method: Optional[... | python | {
"resource": ""
} |
q22302 | paga_compare | train | def paga_compare(
adata,
basis=None,
edges=False,
color=None,
alpha=None,
groups=None,
components=None,
projection='2d',
legend_loc='on data',
legend_fontsize=None,
legend_fontweight='bold',
color_map=None,
palette=N... | python | {
"resource": ""
} |
q22303 | paga_adjacency | train | def paga_adjacency(
adata,
adjacency='connectivities',
adjacency_tree='connectivities_tree',
as_heatmap=True,
color_map=None,
show=None,
save=None):
"""Connectivity of paga groups.
"""
connectivity = adata.uns[adjacency].toarray()
connectivity_sele... | python | {
"resource": ""
} |
q22304 | clustermap | train | def clustermap(
adata, obs_keys=None, use_raw=None, show=None, save=None, **kwds):
"""\
Hierarchically-clustered heatmap.
Wraps `seaborn.clustermap
<https://seaborn.pydata.org/generated/seaborn.clustermap.html>`__ for
:class:`~anndata.AnnData`.
Parameters
----------
adata : :cl... | python | {
"resource": ""
} |
q22305 | dendrogram | train | def dendrogram(adata, groupby, dendrogram_key=None, orientation='top', remove_labels=False,
show=None, save=None):
"""Plots a dendrogram of the categories defined in `groupby`.
See :func:`~scanpy.tl.dendrogram`.
Parameters
----------
adata : :class:`~anndata.AnnData`
groupby : `... | python | {
"resource": ""
} |
q22306 | _prepare_dataframe | train | def _prepare_dataframe(adata, var_names, groupby=None, use_raw=None, log=False,
num_categories=7, layer=None, gene_symbols=None):
"""
Given the anndata object, prepares a data frame in which the row index are the categories
defined by group by and the columns correspond to var_names.
... | python | {
"resource": ""
} |
q22307 | _reorder_categories_after_dendrogram | train | def _reorder_categories_after_dendrogram(adata, groupby, dendrogram,
var_names=None,
var_group_labels=None,
var_group_positions=None):
"""
Function used by plotting functions that need to r... | python | {
"resource": ""
} |
q22308 | _plot_categories_as_colorblocks | train | def _plot_categories_as_colorblocks(groupby_ax, obs_tidy, colors=None, orientation='left', cmap_name='tab20'):
"""
Plots categories as colored blocks. If orientation is 'left', the categories are plotted vertically, otherwise
they are plotted horizontally.
Parameters
----------
groupby_ax : mat... | python | {
"resource": ""
} |
q22309 | DPT.branchings_segments | train | def branchings_segments(self):
"""Detect branchings and partition the data into corresponding segments.
Detect all branchings up to `n_branchings`.
Writes
------
segs : np.ndarray
Array of dimension (number of segments) × (number of data
points). Each ro... | python | {
"resource": ""
} |
q22310 | DPT.detect_branchings | train | def detect_branchings(self):
"""Detect all branchings up to `n_branchings`.
Writes Attributes
-----------------
segs : np.ndarray
List of integer index arrays.
segs_tips : np.ndarray
List of indices of the tips of segments.
"""
logg.m(' ... | python | {
"resource": ""
} |
q22311 | DPT.select_segment | train | def select_segment(self, segs, segs_tips, segs_undecided) -> Tuple[int, int]:
"""Out of a list of line segments, choose segment that has the most
distant second data point.
Assume the distance matrix Ddiff is sorted according to seg_idcs.
Compute all the distances.
Returns
... | python | {
"resource": ""
} |
q22312 | DPT.postprocess_segments | train | def postprocess_segments(self):
"""Convert the format of the segment class members."""
# make segs a list of mask arrays, it's easier to store
# as there is a hdf5 equivalent
for iseg, seg in enumerate(self.segs):
mask = np.zeros(self._adata.shape[0], dtype=bool)
... | python | {
"resource": ""
} |
q22313 | DPT.set_segs_names | train | def set_segs_names(self):
"""Return a single array that stores integer segment labels."""
segs_names = np.zeros(self._adata.shape[0], dtype=np.int8)
self.segs_names_unique = []
for iseg, seg in enumerate(self.segs):
segs_names[seg] = iseg
self.segs_names_unique.ap... | python | {
"resource": ""
} |
q22314 | DPT.order_pseudotime | train | def order_pseudotime(self):
"""Define indices that reflect segment and pseudotime order.
Writes
------
indices : np.ndarray
Index array of shape n, which stores an ordering of the data points
with respect to increasing segment index and increasing pseudotime.
... | python | {
"resource": ""
} |
q22315 | DPT.kendall_tau_split | train | def kendall_tau_split(self, a, b) -> int:
"""Return splitting index that maximizes correlation in the sequences.
Compute difference in Kendall tau for all splitted sequences.
For each splitting index i, compute the difference of the two
correlation measures kendalltau(a[:i], b[:i]) and... | python | {
"resource": ""
} |
q22316 | DPT._kendall_tau_diff | train | def _kendall_tau_diff(self, a: np.ndarray, b: np.ndarray, i) -> Tuple[int, int]:
"""Compute difference in concordance of pairs in split sequences.
Consider splitting a and b at index i.
Parameters
----------
a
?
b
?
Returns
-----... | python | {
"resource": ""
} |
q22317 | deprecated_arg_names | train | def deprecated_arg_names(arg_mapping):
"""
Decorator which marks a functions keyword arguments as deprecated. It will
result in a warning being emitted when the deprecated keyword argument is
used, and the function being called with the new argument.
Parameters
----------
arg_mapping : dict... | python | {
"resource": ""
} |
q22318 | doc_params | train | def doc_params(**kwds):
"""\
Docstrings should start with "\" in the first line for proper formatting.
"""
def dec(obj):
obj.__doc__ = dedent(obj.__doc__).format(**kwds)
return obj
return dec | python | {
"resource": ""
} |
q22319 | get_graph_tool_from_adjacency | train | def get_graph_tool_from_adjacency(adjacency, directed=None):
"""Get graph_tool graph from adjacency matrix."""
import graph_tool as gt
adjacency_edge_list = adjacency
if not directed:
from scipy.sparse import tril
adjacency_edge_list = tril(adjacency)
g = gt.Graph(directed=directed)
... | python | {
"resource": ""
} |
q22320 | get_igraph_from_adjacency | train | def get_igraph_from_adjacency(adjacency, directed=None):
"""Get igraph graph from adjacency matrix."""
import igraph as ig
sources, targets = adjacency.nonzero()
weights = adjacency[sources, targets]
if isinstance(weights, np.matrix):
weights = weights.A1
g = ig.Graph(directed=directed)
... | python | {
"resource": ""
} |
q22321 | compute_association_matrix_of_groups | train | def compute_association_matrix_of_groups(adata, prediction, reference,
normalization='prediction',
threshold=0.01, max_n_names=2):
"""Compute overlaps between groups.
See ``identify_groups`` for identifying the groups.
Param... | python | {
"resource": ""
} |
q22322 | compute_group_overlap_score | train | def compute_group_overlap_score(ref_labels, pred_labels,
threshold_overlap_pred=0.5,
threshold_overlap_ref=0.5):
"""How well do the pred_labels explain the ref_labels?
A predicted cluster explains a reference cluster if it is contained within the ... | python | {
"resource": ""
} |
q22323 | identify_groups | train | def identify_groups(ref_labels, pred_labels, return_overlaps=False):
"""Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this with ``compute_association_... | python | {
"resource": ""
} |
q22324 | unique_categories | train | def unique_categories(categories):
"""Pass array-like categories, return sorted cleaned unique categories."""
categories = np.unique(categories)
categories = np.setdiff1d(categories, np.array(settings.categories_to_ignore))
categories = np.array(natsorted(categories, key=lambda v: v.upper()))
return... | python | {
"resource": ""
} |
q22325 | fill_in_datakeys | train | def fill_in_datakeys(example_parameters, dexdata):
"""Update the 'examples dictionary' _examples.example_parameters.
If a datakey (key in 'datafile dictionary') is not present in the 'examples
dictionary' it is used to initialize an entry with that key.
If not specified otherwise, any 'exkey' (key in ... | python | {
"resource": ""
} |
q22326 | moving_average | train | def moving_average(a, n):
"""Moving average over one-dimensional array.
Parameters
----------
a : np.ndarray
One-dimensional array.
n : int
Number of entries to average over. n=2 means averaging over the currrent
the previous entry.
Returns
-------
An array view... | python | {
"resource": ""
} |
q22327 | update_params | train | def update_params(old_params, new_params, check=False):
"""Update old_params with new_params.
If check==False, this merely adds and overwrites the content of old_params.
If check==True, this only allows updating of parameters that are already
present in old_params.
Parameters
----------
o... | python | {
"resource": ""
} |
q22328 | read_args_tool | train | def read_args_tool(toolkey, example_parameters, tool_add_args=None):
"""Read args for single tool.
"""
import scanpy as sc
p = default_tool_argparser(help(toolkey), example_parameters)
if tool_add_args is None:
p = add_args(p)
else:
p = tool_add_args(p)
args = vars(p.parse_ar... | python | {
"resource": ""
} |
q22329 | default_tool_argparser | train | def default_tool_argparser(description, example_parameters):
"""Create default parser for single tools.
"""
import argparse
epilog = '\n'
for k, v in sorted(example_parameters.items()):
epilog += ' ' + k + '\n'
p = argparse.ArgumentParser(
description=description,
add_he... | python | {
"resource": ""
} |
q22330 | pretty_dict_string | train | def pretty_dict_string(d, indent=0):
"""Pretty output of nested dictionaries.
"""
s = ''
for key, value in sorted(d.items()):
s += ' ' * indent + str(key)
if isinstance(value, dict):
s += '\n' + pretty_dict_string(value, indent+1)
else:
s += '=' + str... | python | {
"resource": ""
} |
q22331 | merge_dicts | train | def merge_dicts(*ds):
"""Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
Notes
-----
http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression
"""
result = ds[0]
for d in ds... | python | {
"resource": ""
} |
q22332 | masks | train | def masks(list_of_index_lists, n):
"""Make an array in which rows store 1d mask arrays from list of index lists.
Parameters
----------
n : int
Maximal index / number of samples.
"""
# make a list of mask arrays, it's easier to store
# as there is a hdf5 equivalent
for il,l in en... | python | {
"resource": ""
} |
q22333 | warn_with_traceback | train | def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
"""Get full tracebacks when warning is raised by setting
warnings.showwarning = warn_with_traceback
See also
--------
http://stackoverflow.com/questions/22373927/get-traceback-of-warnings
"""
import traceba... | python | {
"resource": ""
} |
q22334 | subsample_n | train | def subsample_n(X, n=0, seed=0):
"""Subsample n samples from rows of array.
Parameters
----------
X : np.ndarray
Data array.
seed : int
Seed for sampling.
Returns
-------
Xsampled : np.ndarray
Subsampled X.
rows : np.ndarray
Indices of rows that are ... | python | {
"resource": ""
} |
q22335 | check_presence_download | train | def check_presence_download(filename, backup_url):
"""Check if file is present otherwise download."""
import os
filename = str(filename) # Throws error for Path on 3.5
if not os.path.exists(filename):
from .readwrite import download_progress
dr = os.path.dirname(filename)
try:
... | python | {
"resource": ""
} |
q22336 | hierarch_cluster | train | def hierarch_cluster(M):
"""Cluster matrix using hierarchical clustering.
Parameters
----------
M : np.ndarray
Matrix, for example, distance matrix.
Returns
-------
Mclus : np.ndarray
Clustered matrix.
indices : np.ndarray
Indices used to cluster the matrix.
... | python | {
"resource": ""
} |
q22337 | GetVersionNamespace | train | def GetVersionNamespace(version):
""" Get version namespace from version """
ns = nsMap[version]
if not ns:
ns = serviceNsMap[version]
versionId = versionIdMap[version]
if not versionId:
namespace = ns
else:
namespace = '%s/%s' % (ns, versionId)
return namespace | python | {
"resource": ""
} |
q22338 | GetWsdlMethod | train | def GetWsdlMethod(ns, wsdlName):
""" Get wsdl method from ns, wsdlName """
with _lazyLock:
method = _wsdlMethodMap[(ns, wsdlName)]
if isinstance(method, ManagedMethod):
# The type corresponding to the method is loaded,
# just return the method object
return method
elif... | python | {
"resource": ""
} |
q22339 | GetVmodlType | train | def GetVmodlType(name):
""" Get type from vmodl name """
# If the input is already a type, just return
if isinstance(name, type):
return name
# Try to get type from vmodl type names table
typ = vmodlTypes.get(name)
if typ:
return typ
# Else get the type from the _wsdlTypeMap
isArr... | python | {
"resource": ""
} |
q22340 | VmomiJSONEncoder.explode | train | def explode(self, obj):
""" Determine if the object should be exploded. """
if obj in self._done:
return False
result = False
for item in self._explode:
if hasattr(item, '_moId'):
# If it has a _moId it is an instance
if obj._moId =... | python | {
"resource": ""
} |
q22341 | main | train | def main():
"""
Simple command-line program for powering on virtual machines on a system.
"""
args = GetArgs()
if args.password:
password = args.password
else:
password = getpass.getpass(prompt='Enter password for host %s and user %s: ' % (args.host,args.user))
try:
vmnames = ar... | python | {
"resource": ""
} |
q22342 | PrintVmInfo | train | def PrintVmInfo(vm, depth=1):
"""
Print information for a particular virtual machine or recurse into a folder
or vApp with depth protection
"""
maxdepth = 10
# if this is a group it will have children. if it does, recurse into them
# and then return
if hasattr(vm, 'childEntity'):
if depth... | python | {
"resource": ""
} |
q22343 | main | train | def main():
"""
Simple command-line program for listing the virtual machines on a system.
"""
args = GetArgs()
if args.password:
password = args.password
else:
password = getpass.getpass(prompt='Enter password for host %s and '
'user %s: ' % (args.h... | python | {
"resource": ""
} |
q22344 | localSslFixup | train | def localSslFixup(host, sslContext):
"""
Connections to 'localhost' do not need SSL verification as a certificate
will never match. The OS provides security by only allowing root to bind
to low-numbered ports.
"""
if not sslContext and host in ['localhost', '127.0.0.1', '::1']:
import ss... | python | {
"resource": ""
} |
q22345 | Connect | train | def Connect(host='localhost', port=443, user='root', pwd='',
service="hostd", adapter="SOAP", namespace=None, path="/sdk",
connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC,
version=None, keyFile=None, certFile=None, thumbprint=None,
sslContext=None, b64token=None, m... | python | {
"resource": ""
} |
q22346 | ConnectNoSSL | train | def ConnectNoSSL(host='localhost', port=443, user='root', pwd='',
service="hostd", adapter="SOAP", namespace=None, path="/sdk",
version=None, keyFile=None, certFile=None, thumbprint=None,
b64token=None, mechanism='userpass'):
"""
Provides a standard method for co... | python | {
"resource": ""
} |
q22347 | __RetrieveContent | train | def __RetrieveContent(host, port, adapter, version, path, keyFile, certFile,
thumbprint, sslContext, connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC):
"""
Retrieve service instance for connection.
@param host: Which host to connect to.
@type host: string
@param port: Port
... | python | {
"resource": ""
} |
q22348 | __GetElementTree | train | def __GetElementTree(protocol, server, port, path, sslContext):
"""
Private method that returns a root from ElementTree for a remote XML document.
@param protocol: What protocol to use for the connection (e.g. https or http).
@type protocol: string
@param server: Which server to connect to.
@type s... | python | {
"resource": ""
} |
q22349 | __GetServiceVersionDescription | train | def __GetServiceVersionDescription(protocol, server, port, path, sslContext):
"""
Private method that returns a root from an ElementTree describing the API versions
supported by the specified server. The result will be vimServiceVersions.xml
if it exists, otherwise vimService.wsdl if it exists, otherwise N... | python | {
"resource": ""
} |
q22350 | __VersionIsSupported | train | def __VersionIsSupported(desiredVersion, serviceVersionDescription):
"""
Private method that returns true if the service version description document
indicates that the desired version is supported
@param desiredVersion: The version we want to see if the server supports
(eg. vim.v... | python | {
"resource": ""
} |
q22351 | __FindSupportedVersion | train | def __FindSupportedVersion(protocol, server, port, path, preferredApiVersions, sslContext):
"""
Private method that returns the most preferred API version supported by the
specified server,
@param protocol: What protocol to use for the connection (e.g. https or http).
@type protocol: string
@param s... | python | {
"resource": ""
} |
q22352 | SmartStubAdapter | train | def SmartStubAdapter(host='localhost', port=443, path='/sdk',
url=None, sock=None, poolSize=5,
certFile=None, certKeyFile=None,
httpProxyHost=None, httpProxyPort=80, sslProxyPath=None,
thumbprint=None, cacertsFile=None, preferredApiVers... | python | {
"resource": ""
} |
q22353 | SmartConnect | train | def SmartConnect(protocol='https', host='localhost', port=443, user='root', pwd='',
service="hostd", path="/sdk", connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC,
preferredApiVersions=None, keyFile=None, certFile=None,
thumbprint=None, sslContext=None, b64token=... | python | {
"resource": ""
} |
q22354 | SmartConnectNoSSL | train | def SmartConnectNoSSL(protocol='https', host='localhost', port=443, user='root', pwd='',
service="hostd", path="/sdk", connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC,
preferredApiVersions=None, keyFile=None, certFile=None,
thumbprint=None, b64tok... | python | {
"resource": ""
} |
q22355 | OpenUrlWithBasicAuth | train | def OpenUrlWithBasicAuth(url, user='root', pwd=''):
"""
Open the specified URL, using HTTP basic authentication to provide
the specified credentials to the server as part of the request.
Returns the response as a file-like object.
"""
return requests.get(url, auth=HTTPBasicAuth(user, pwd), verify=Fals... | python | {
"resource": ""
} |
q22356 | main | train | def main():
"""
Simple command-line program for dumping the contents of any managed object.
"""
args = GetArgs()
if args.password:
password = args.password
else:
password = getpass.getpass(prompt='Enter password for host %s and '
'user %s: ' % (args... | python | {
"resource": ""
} |
q22357 | SoapSerializer._NSPrefix | train | def _NSPrefix(self, ns):
""" Get xml ns prefix. self.nsMap must be set """
if ns == self.defaultNS:
return ''
prefix = self.nsMap[ns]
return prefix and prefix + ':' or '' | python | {
"resource": ""
} |
q22358 | SoapDeserializer.SplitTag | train | def SplitTag(self, tag):
""" Split tag into ns, name """
idx = tag.find(NS_SEP)
if idx >= 0:
return tag[:idx], tag[idx + 1:]
else:
return "", tag | python | {
"resource": ""
} |
q22359 | SoapDeserializer.LookupWsdlType | train | def LookupWsdlType(self, ns, name, allowManagedObjectReference=False):
""" Lookup wsdl type. Handle special case for some vmodl version """
try:
return GetWsdlType(ns, name)
except KeyError:
if allowManagedObjectReference:
if name.endswith('ManagedObjectReference') and ns... | python | {
"resource": ""
} |
q22360 | IsPrimitiveType | train | def IsPrimitiveType(obj):
"""See if the passed in type is a Primitive Type"""
return (isinstance(obj, types.bool) or isinstance(obj, types.byte) or
isinstance(obj, types.short) or isinstance(obj, six.integer_types) or
isinstance(obj, types.double) or isinstance(obj, types.float) or
isinstance(ob... | python | {
"resource": ""
} |
q22361 | DiffAnys | train | def DiffAnys(obj1, obj2, looseMatch=False, ignoreArrayOrder=True):
"""Diff any two objects. Objects can either be primitive type
or DataObjects"""
differ = Differ(looseMatch = looseMatch, ignoreArrayOrder = ignoreArrayOrder)
return differ.DiffAnyObjects(obj1, obj2) | python | {
"resource": ""
} |
q22362 | Differ.DiffAnyObjects | train | def DiffAnyObjects(self, oldObj, newObj, isObjLink=False):
"""Diff any two Objects"""
if oldObj == newObj:
return True
if not oldObj or not newObj:
__Log__.debug('DiffAnyObjects: One of the objects is unset.')
return self._looseMatch
oldObjInstance = oldObj
newOb... | python | {
"resource": ""
} |
q22363 | Differ.DiffDoArrays | train | def DiffDoArrays(self, oldObj, newObj, isElementLinks):
"""Diff two DataObject arrays"""
if len(oldObj) != len(newObj):
__Log__.debug('DiffDoArrays: Array lengths do not match %d != %d'
% (len(oldObj), len(newObj)))
return False
for i, j in zip(oldObj, newObj):
i... | python | {
"resource": ""
} |
q22364 | Differ.DiffAnyArrays | train | def DiffAnyArrays(self, oldObj, newObj, isElementLinks):
"""Diff two arrays which contain Any objects"""
if len(oldObj) != len(newObj):
__Log__.debug('DiffAnyArrays: Array lengths do not match. %d != %d'
% (len(oldObj), len(newObj)))
return False
for i, j in zip(oldObj, n... | python | {
"resource": ""
} |
q22365 | Differ.DiffPrimitiveArrays | train | def DiffPrimitiveArrays(self, oldObj, newObj):
"""Diff two primitive arrays"""
if len(oldObj) != len(newObj):
__Log__.debug('DiffDoArrays: Array lengths do not match %d != %d'
% (len(oldObj), len(newObj)))
return False
match = True
if self._ignoreArrayOrder:
... | python | {
"resource": ""
} |
q22366 | Differ.DiffArrayObjects | train | def DiffArrayObjects(self, oldObj, newObj, isElementLinks=False):
"""Method which deligates the diffing of arrays based on the type"""
if oldObj == newObj:
return True
if not oldObj or not newObj:
return False
if len(oldObj) != len(newObj):
__Log__.debug('DiffArrayObje... | python | {
"resource": ""
} |
q22367 | Differ.DiffDataObjects | train | def DiffDataObjects(self, oldObj, newObj):
"""Diff Data Objects"""
if oldObj == newObj:
return True
if not oldObj or not newObj:
__Log__.debug('DiffDataObjects: One of the objects in None')
return False
oldType = Type(oldObj)
newType = Type(newObj)
if oldTy... | python | {
"resource": ""
} |
q22368 | Cache | train | def Cache(fn):
""" Function cache decorator """
def fnCache(*args, **kwargs):
""" Cache function """
key = (args and tuple(args) or None,
kwargs and frozenset(kwargs.items()) or None)
if key not in fn.__cached__:
fn.__cached__[key] = cache = fn(*args, **kwargs)
else:
... | python | {
"resource": ""
} |
q22369 | DynamicTypeImporter.GetTypeManager | train | def GetTypeManager(self):
""" Get dynamic type manager """
dynTypeMgr = None
if self.hostSystem:
try:
dynTypeMgr = self.hostSystem.RetrieveDynamicTypeManager()
except vmodl.fault.MethodNotFound as err:
pass
if not dynTypeMgr:
# Older host not s... | python | {
"resource": ""
} |
q22370 | DynamicTypeImporter.ImportTypes | train | def ImportTypes(self, prefix=''):
""" Build dynamic types """
# Use QueryTypeInfo to get all types
dynTypeMgr = self.GetTypeManager()
filterSpec = None
if prefix != '':
filterSpec = vmodl.reflect.DynamicTypeManager.TypeFilterSpec(
... | python | {
"resource": ""
} |
q22371 | DynamicTypeConstructor.CreateTypes | train | def CreateTypes(self, allTypes):
"""
Create pyVmomi types from vmodl.reflect.DynamicTypeManager.AllTypeInfo
"""
enumTypes, dataTypes, managedTypes = self._ConvertAllTypes(allTypes)
self._CreateAllTypes(enumTypes, dataTypes, managedTypes) | python | {
"resource": ""
} |
q22372 | DynamicTypeConstructor._ConvertAllTypes | train | def _ConvertAllTypes(self, allTypes):
""" Convert all dynamic types to pyVmomi type definitions """
# Generate lists good for VmomiSupport.CreateXYZType
enumTypes = self._Filter(self._ConvertEnumType, allTypes.enumTypeInfo)
dataTypes = self._Filter(self._ConvertDataType, allTypes.dataTypeInfo)
... | python | {
"resource": ""
} |
q22373 | DynamicTypeConstructor._CreateAllTypes | train | def _CreateAllTypes(self, enumTypes, dataTypes, managedTypes):
""" Create pyVmomi types from pyVmomi type definitions """
# Create versions
for typeInfo in managedTypes:
name = typeInfo[0]
version = typeInfo[3]
VmomiSupport.AddVersion(version, '', '1.0', 0, name)
V... | python | {
"resource": ""
} |
q22374 | DynamicTypeConstructor._ConvertAnnotations | train | def _ConvertAnnotations(self, annotations):
""" Convert annotations to pyVmomi flags """
flags = 0
if annotations:
for annotation in annotations:
flags |= self._mapFlags.get(annotation.name, 0)
return flags | python | {
"resource": ""
} |
q22375 | DynamicTypeConstructor._ConvertParamType | train | def _ConvertParamType(self, paramType):
"""
Convert vmodl.reflect.DynamicTypeManager.ParamTypeInfo to pyVmomi param
definition
"""
if paramType:
name = paramType.name
version = paramType.version
aType = paramType.type
flags = self._ConvertAnnotations(par... | python | {
"resource": ""
} |
q22376 | DynamicTypeConstructor._ConvertMethodType | train | def _ConvertMethodType(self, methodType):
"""
Convert vmodl.reflect.DynamicTypeManager.MethodTypeInfo to pyVmomi method
definition
"""
if methodType:
name = methodType.name
wsdlName = methodType.wsdlName
version = methodType.version
params = self._Filter... | python | {
"resource": ""
} |
q22377 | DynamicTypeConstructor._ConvertManagedPropertyType | train | def _ConvertManagedPropertyType(self, propType):
"""
Convert vmodl.reflect.DynamicTypeManager.PropertyTypeInfo to pyVmomi
managed property definition
"""
if propType:
name = propType.name
version = propType.version
aType = propType.type
flags = self._Con... | python | {
"resource": ""
} |
q22378 | DynamicTypeConstructor._ConvertManagedType | train | def _ConvertManagedType(self, managedType):
"""
Convert vmodl.reflect.DynamicTypeManager.ManagedTypeInfo to pyVmomi
managed type definition
"""
if managedType:
vmodlName = managedType.name
wsdlName = managedType.wsdlName
version = managedType.version
par... | python | {
"resource": ""
} |
q22379 | DynamicTypeConstructor._ConvertDataPropertyType | train | def _ConvertDataPropertyType(self, propType):
"""
Convert vmodl.reflect.DynamicTypeManager.PropertyTypeInfo to pyVmomi
data property definition
"""
if propType:
name = propType.name
version = propType.version
aType = propType.type
flags = self._ConvertAn... | python | {
"resource": ""
} |
q22380 | DynamicTypeConstructor._ConvertDataType | train | def _ConvertDataType(self, dataType):
"""
Convert vmodl.reflect.DynamicTypeManager.DataTypeInfo to pyVmomi data
type definition
"""
if dataType:
vmodlName = dataType.name
wsdlName = dataType.wsdlName
version = dataType.version
parent = dataType.base[0]
... | python | {
"resource": ""
} |
q22381 | DynamicTypeConstructor._ConvertEnumType | train | def _ConvertEnumType(self, enumType):
"""
Convert vmodl.reflect.DynamicTypeManager.EnumTypeInfo to pyVmomi enum
type definition
"""
if enumType:
vmodlName = enumType.name
wsdlName = enumType.wsdlName
version = enumType.version
values = enumType.value
... | python | {
"resource": ""
} |
q22382 | WaitForTask | train | def WaitForTask(task,
raiseOnError=True,
si=None,
pc=None,
onProgressUpdate=None):
"""
Wait for task to complete.
@type raiseOnError : bool
@param raiseOnError : Any exception thrown is thrown up to the caller
... | python | {
"resource": ""
} |
q22383 | WaitForTasks | train | def WaitForTasks(tasks,
raiseOnError=True,
si=None,
pc=None,
onProgressUpdate=None,
results=None):
"""
Wait for mulitiple tasks to complete. Much faster than calling WaitForTask
N times
"""
if not tasks:
re... | python | {
"resource": ""
} |
q22384 | CreateTasksFilter | train | def CreateTasksFilter(pc, tasks):
""" Create property collector filter for tasks """
if not tasks:
return None
# First create the object specification as the task object.
objspecs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task)
for task in tasks]
# Next, create the pr... | python | {
"resource": ""
} |
q22385 | CheckForQuestionPending | train | def CheckForQuestionPending(task):
"""
Check to see if VM needs to ask a question, throw exception
"""
vm = task.info.entity
if vm is not None and isinstance(vm, vim.VirtualMachine):
qst = vm.runtime.question
if qst is not None:
raise TaskBlocked("Task blocked, User Inte... | python | {
"resource": ""
} |
q22386 | Adb.cmd | train | def cmd(self, *args, **kwargs):
'''adb command, add -s serial by default. return the subprocess.Popen object.'''
serial = self.device_serial()
if serial:
if " " in serial: # TODO how to include special chars on command line
serial = "'%s'" % serial
return... | python | {
"resource": ""
} |
q22387 | AutomatorServer.sdk_version | train | def sdk_version(self):
'''sdk version of connected device.'''
if self.__sdk == 0:
try:
self.__sdk = int(self.adb.cmd("shell", "getprop", "ro.build.version.sdk").communicate()[0].decode("utf-8").strip())
except:
pass
return self.__sdk | python | {
"resource": ""
} |
q22388 | AutomatorServer.stop | train | def stop(self):
'''Stop the rpc server.'''
if self.uiautomator_process and self.uiautomator_process.poll() is None:
res = None
try:
res = urllib2.urlopen(self.stop_uri)
self.uiautomator_process.wait()
except:
self.uiauto... | python | {
"resource": ""
} |
q22389 | AutomatorDevice.click | train | def click(self, x, y):
'''click at arbitrary coordinates.'''
return self.server.jsonrpc.click(x, y) | python | {
"resource": ""
} |
q22390 | AutomatorDevice.long_click | train | def long_click(self, x, y):
'''long click at arbitrary coordinates.'''
return self.swipe(x, y, x + 1, y + 1) | python | {
"resource": ""
} |
q22391 | AutomatorDevice.dump | train | def dump(self, filename=None, compressed=True, pretty=True):
'''dump device window and pull to local file.'''
content = self.server.jsonrpc.dumpWindowHierarchy(compressed, None)
if filename:
with open(filename, "wb") as f:
f.write(content.encode("utf-8"))
if p... | python | {
"resource": ""
} |
q22392 | AutomatorDevice.screenshot | train | def screenshot(self, filename, scale=1.0, quality=100):
'''take screenshot.'''
result = self.server.screenshot(filename, scale, quality)
if result:
return result
device_file = self.server.jsonrpc.takeScreenshot("screenshot.png",
... | python | {
"resource": ""
} |
q22393 | AutomatorDevice.orientation | train | def orientation(self, value):
'''setter of orientation property.'''
for values in self.__orientation:
if value in values:
# can not set upside-down until api level 18.
self.server.jsonrpc.setOrientation(values[1])
break
else:
... | python | {
"resource": ""
} |
q22394 | AutomatorDeviceUiObject.set_text | train | def set_text(self, text):
'''set the text field.'''
if text in [None, ""]:
return self.jsonrpc.clearTextField(self.selector) # TODO no return
else:
return self.jsonrpc.setText(self.selector, text) | python | {
"resource": ""
} |
q22395 | AutomatorDeviceObject.child | train | def child(self, **kwargs):
'''set childSelector.'''
return AutomatorDeviceObject(
self.device,
self.selector.clone().child(**kwargs)
) | python | {
"resource": ""
} |
q22396 | AutomatorDeviceObject.sibling | train | def sibling(self, **kwargs):
'''set fromParent selector.'''
return AutomatorDeviceObject(
self.device,
self.selector.clone().sibling(**kwargs)
) | python | {
"resource": ""
} |
q22397 | minimize | train | def minimize(model,
data,
algo,
max_evals,
trials,
functions=None,
rseed=1337,
notebook_name=None,
verbose=True,
eval_space=False,
return_space=False,
keep_temp=False):
"""
... | python | {
"resource": ""
} |
q22398 | with_line_numbers | train | def with_line_numbers(code):
"""
Adds line numbers to each line of a source code fragment
Parameters
----------
code : string
any multiline text, such as as (fragments) of source code
Returns
-------
str : string
The input with added <n>: for each line
Example
--... | python | {
"resource": ""
} |
q22399 | create_model | train | def create_model(x_train, y_train, x_test, y_test):
"""
Create your model...
"""
layer_1_size = {{quniform(12, 256, 4)}}
l1_dropout = {{uniform(0.001, 0.7)}}
params = {
'l1_size': layer_1_size,
'l1_dropout': l1_dropout
}
num_classes = 10
model = Sequential()
model... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.