text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def execute(self, triple_map, output, **kwargs):
"""Execute """
subjects = []
if NS_MGR.ql.JSON.rdflib in \
triple_map.logicalSource.reference_formulations:
output_format = "json"
else:
output_format = "xml"
if 'limit' not in kwargs:
... | 0.002145 |
def map_init(interface, params):
"""Intialize random number generator with given seed `params.seed`."""
import numpy as np
import random
np.random.seed(params['seed'])
random.seed(params['seed'])
return params | 0.004292 |
def inverse_distance(xp, yp, variable, grid_x, grid_y, r, gamma=None, kappa=None,
min_neighbors=3, kind='cressman'):
"""Wrap inverse_distance_to_grid for deprecated inverse_distance function."""
return inverse_distance_to_grid(xp, yp, variable, grid_x, grid_y, r, gamma=gamma,
... | 0.01269 |
def order_target_percent(id_or_ins, percent, price=None, style=None):
"""
买入/卖出证券以自动调整该证券的仓位到占有一个目标价值。
加仓时,percent 代表证券已有持仓的价值加上即将花费的现金(包含税费)的总值占当前投资组合总价值的比例。
减仓时,percent 代表证券将被调整到的目标价至占当前投资组合总价值的比例。
其实我们需要计算一个position_to_adjust (即应该调整的仓位)
`position_to_adjust = target_position - current_posit... | 0.003231 |
def _convert_fancy(self, field):
"""Convert to a list (sep != None) and convert list elements."""
if self.sep is False:
x = self._convert_singlet(field)
else:
x = tuple([self._convert_singlet(s) for s in field.split(self.sep)])
if len(x) == 0:
... | 0.009132 |
def read(self):
"""Read the state of the GPIO.
Returns:
bool: ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
"""
# Read value
try:
buf = os.read(self._fd, 2)
except OSError ... | 0.00266 |
def _request(self, url, method = u"get", data = None, headers=None, **kwargs):
"""
does the request via requests
- oauth not implemented yet
- use basic auth please
"""
# if self.access_token:
# auth_header = {
# u"Authoriz... | 0.012299 |
def keep_alive_timeout_callback(self):
"""
Check if elapsed time since last response exceeds our configured
maximum keep alive timeout value and if so, close the transport
pipe and let the response writer handle the error.
:return: None
"""
time_elapsed = time() ... | 0.002656 |
def __doDownloadPage(self, *args, **kwargs):
"""Works like client.downloadPage(), but handle incoming headers
"""
logger.debug("download page: %r, %r", args, kwargs)
return self.__clientDefer(downloadPage(*args, **kwargs)) | 0.007843 |
def cache(self, con):
"""Put a connection back into the pool cache."""
try:
if self._reset == 2:
con.reset() # reset the connection completely
else:
if self._reset or con._transaction:
try:
con.rollback(... | 0.003263 |
def delete_list_members(self, list_, query_column, ids_to_delete):
""" Responsys.deleteListMembers call
Accepts:
InteractObject list_
string query_column
possible values: 'RIID'|'EMAIL_ADDRESS'|'CUSTOMER_ID'|'MOBILE_NUMBER'
list ids_to_delete
... | 0.006033 |
def set_config_variable(self, config_id, offset, value):
"""Set a chunk of the current config value's value."""
if self.initialized.is_set():
return [Error.STATE_CHANGE_AT_INVALID_TIME]
config = self._config_variables.get(config_id)
if config is None:
return [Er... | 0.004796 |
def Open(self):
"""Opens the storage writer.
Raises:
IOError: if the storage writer is already opened.
OSError: if the storage writer is already opened.
"""
if self._storage_file:
raise IOError('Storage writer already opened.')
self._storage_file = self._CreateStorageFile()
... | 0.005155 |
def binarycontent_sections(chunk):
'''Split a chunk of data into sections by start and end binary
content tags.'''
# using string split because it is significantly faster than regex.
# use common text of start and end tags to split the text
# (i.e. without < or </ tag beginning)
binary_content_... | 0.000856 |
def headerthreads(self):
"""
The contig ID must be twenty characters or fewer. The names of the headers created following SPAdes assembly
are usually far too long. This renames them as the sample name
"""
# Create and start threads
for i in range(self.cpus):
#... | 0.005365 |
def remove_child_gradebook(self, gradebook_id, child_id):
"""Removes a child from a gradebook.
arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: NotFound - ``gradebook_id`` not a parent of ``child_id``
... | 0.004167 |
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if name and name[0] != '<' and name[-1] != '>':
return os.path.basename(name) | 0.004739 |
def parse_query(cls, query):
"""return name=val&name2=val2 strings into {name: val} dict"""
if not query: return {}
d = {}
# https://docs.python.org/2/library/urlparse.html
for k, kv in urlparse.parse_qs(query, True, strict_parsing=True).items():
#k = k.rstrip("[]") ... | 0.010288 |
def _parse_normalizations(self, normalizations):
"""Returns a list of parsed normalizations.
Iterates over a list of normalizations, removing those
not correctly defined. It also transform complex items
to have a common format (list of tuples and strings).
Args:
nor... | 0.002275 |
def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20):
"""start joiner
Args:
strPSKd: Joiner's PSKd
Returns:
True: successful to start joiner
False: fail to start joiner
"""
print '%s call joinCommissioned' % self.port
se... | 0.004039 |
def simple_polygon_without_brush(layer, width='0.26', color=QColor('black')):
"""Simple style to apply a border line only to a polygon layer.
:param layer: The layer to style.
:type layer: QgsVectorLayer
:param color: Color to use for the line. Default to black.
:type color: QColor
:param wid... | 0.000914 |
def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = Fals... | 0.000973 |
def _zforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | 0.020581 |
def Ctrl_Fn(self, n, dl = 0):
"""Ctrl + Fn1~12 组合键
"""
self.Delay(dl)
self.keyboard.press_key(self.keyboard.control_key)
self.keyboard.tap_key(self.keyboard.function_keys[n])
self.keyboard.release_key(self.keyboard.control_key) | 0.014545 |
def add_deviation(self, dev, td=None):
"""
Add a deviation survey to this instance, and try to compute a position
log from it.
"""
self.deviation = dev
try:
self.compute_position_log(td=td)
except:
self.position = None
return | 0.009585 |
def abs_path_from_base(base_path, rel_path):
"""Join a base and a relative path and return an absolute path to the resulting
location.
Args:
base_path: str
Relative or absolute path to prepend to ``rel_path``.
rel_path: str
Path relative to the location of the module file from ... | 0.006319 |
def shutdown(self, timeout=None):
"""Cleanup DRMAA session and call shutdown of parent."""
try:
super(BaseDrmaaManager, self).shutdown(timeout)
except Exception:
pass
self.drmaa_session.close() | 0.008032 |
def _thread_body(self, request, callback):
"""
Private function. Send a request, wait for response and call the callback function.
:param request: the request to send
:param callback: the callback function
"""
self.protocol.send_message(request)
while not self.pr... | 0.007075 |
def get_props_from_doc(self, cls, id, doc):
"""
Pull out the properties from this document
Returns the class, the properties in a hash, and the id if provided as a tuple
:return: (cls, props, id)
"""
obj_node = doc.getElementsByTagName('object')[0]
if not cls:
... | 0.00453 |
def get_plugin_apps(self):
"""Obtains a mapping between routes and handlers. Stores the logdir.
Returns:
A mapping between routes and handlers (functions that respond to
requests).
"""
return {
'/infer': self._infer,
'/update_example': self._update_example,
'/example... | 0.001546 |
def log_transform(image):
'''Renormalize image intensities to log space
Returns a tuple of transformed image and a dictionary to be passed into
inverse_log_transform. The minimum and maximum from the dictionary
can be applied to an image by the inverse_log_transform to
convert it back to its f... | 0.005945 |
def dicts_to_dict(dictionaries, key_subfieldname):
"""Convert a list of dictionaries into a dictionary of dictionaries.
key_subfieldname must exist in each Record's subfields and have a value,
which will be used as the key for the new dictionary. If a key is duplicated,
the earlier value will be overwr... | 0.004598 |
def close(self):
""" Close the connection.
"""
if not self._closed:
if self.protocol_version >= 3:
log_debug("[#%04X] C: GOODBYE", self.local_port)
self._append(b"\x02", ())
try:
self.send()
except S... | 0.003425 |
def distributions(self, _args):
"""Lists all distributions currently available (i.e. that have already
been built)."""
ctx = self.ctx
dists = Distribution.get_distributions(ctx)
if dists:
print('{Style.BRIGHT}Distributions currently installed are:'
... | 0.003515 |
def absolute(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList and applies the mathematical abs
function to each datapoint transforming it to its absolute value.
Example::
&target=absolute(Server.instance01.threads.busy)
&target=absolute(Server.instance*.thread... | 0.001767 |
def get_undefined_namespaces(graph: BELGraph) -> Set[str]:
"""Get all namespaces that are used in the BEL graph aren't actually defined."""
return {
exc.namespace
for _, exc, _ in graph.warnings
if isinstance(exc, UndefinedNamespaceWarning)
} | 0.007194 |
def _advapi32_decrypt(cipher, key, data, iv, padding):
"""
Decrypts AES/RC4/RC2/3DES/DES ciphertext via CryptoAPI
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
"rc2", "rc4"
:param key:
The encryption key - a byte string 5-16 bytes long
... | 0.000599 |
def determine_indent(str):
"""
Figure out the character(s) used for indents in a given source code fragement.
Parameters
----------
str : string
source code starting at an indent of 0 and containing at least one indented block.
Returns
-------
string
The character(s) used f... | 0.006024 |
def parse_dates(d, default='today'):
""" Parses one or more dates from d """
if default == 'today':
default = datetime.datetime.today()
if d is None:
return default
elif isinstance(d, _parsed_date_types):
return d
elif is_number(d):
# Treat as milliseconds since 1... | 0.0012 |
def get_info(self):
"""
Helper method to get model info in a form of (app_label, model_name).
Avoid deprecation warnings and failures with different Django versions.
"""
if LooseVersion(django.get_version()) < LooseVersion('1.7.0'):
info = self.model._meta.app_label, ... | 0.004376 |
def run():
"""
Parse arguments and pass them into the main class
This is invoked from the `dnsyo` script
"""
# List all the possible options, defaults and help
options = [
['resolverlist', 'store',
'Location of the yaml resolvers list to download (http/https)',
'https... | 0.000215 |
def node_run(input_file, coords_only, bc_settings, bc_grid_weights):
"""Main function to process visibility data on Spark cluster nodes.
Args:
input_file (str):
RDD element containing filename to process.
coords_only (boolean):
If true, read only baseline coordinates to ... | 0.000292 |
def _fdopen(self, *args, **kwargs):
"""Redirector to open() builtin function.
Args:
*args: Pass through args.
**kwargs: Pass through kwargs.
Returns:
File object corresponding to file_des.
Raises:
TypeError: if file descriptor is not an ... | 0.004057 |
def clean_all(self, config_file, region=None, profile_name=None):
"""
Clean all provisioned artifacts from both the local file and the AWS
Greengrass service.
:param config_file: config file containing the group to clean
:param region: the region in which the group should be cle... | 0.001896 |
def remove_lvm_physical_volume(block_device):
'''
Remove LVM PV signatures from a given block device.
:param block_device: str: Full path of block device to scrub.
'''
p = Popen(['pvremove', '-ff', block_device],
stdin=PIPE)
p.communicate(input='y\n') | 0.003448 |
def frombase(path1, path2):
# type: (Text, Text) -> Text
"""Get the final path of ``path2`` that isn't in ``path1``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
str: the final part of ``path2``.
Example:
>>> frombase('foo/b... | 0.004024 |
def get(self, request, format=None):
""" get HTTP method """
action = request.query_params.get('action', 'unread')
# action can be only "unread" (default), "count" and "all"
action = action if action == 'count' or action == 'all' else 'unread'
# mark as read parameter, defaults t... | 0.004902 |
def inall_cmd(argv):
"""Run a command in each virtualenv."""
envs = lsenvs()
errors = False
for env in envs:
print("\n%s:" % env)
try:
inve(env, *argv)
except CalledProcessError as e:
errors = True
err(e)
sys.exit(errors) | 0.003322 |
def get(url, params={}):
"""Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary
"""
request_url = url
if len(params):... | 0.003063 |
def get_action(self, parent, undo_stack: QUndoStack, sel_range, groups,
view: int) -> QUndoCommand:
"""
:type parent: QTableView
:type undo_stack: QUndoStack
:type groups: list of ProtocolGroups
"""
raise NotImplementedError("Abstract Method.") | 0.009646 |
def load_keypair(keypair_file):
'''load a keypair from a keypair file. We add attributes key (the raw key)
and public_key (the url prepared public key) to the client.
Parameters
==========
keypair_file: the pem file to load.
'''
from Crypto.PublicKey import RSA
# Load key
... | 0.002114 |
def _save_assignment(self, node, name=None):
"""save assignement situation since node.parent is not available yet"""
if self._global_names and node.name in self._global_names[-1]:
node.root().set_local(node.name, node)
else:
node.parent.set_local(node.name, node) | 0.006431 |
def add_object(self,
name,
mesh,
transform=None):
"""
Add an object to the collision manager.
If an object with the given name is already in the manager,
replace it.
Parameters
----------
name : str
... | 0.003526 |
def load_data(self, pyramid):
"""
:param pyramid: hic pyramid
"""
import colorsys
logger.info("loading data from level = {}".format(self.level))
# self.im_init = np.array(pyramid.data[str(self.level)],
# dtype=np.int32)
# self.n_frags = self.im_init.shape... | 0.000205 |
def parse_requirements(
filename, # type: str
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
constraint=False, # type: bool
wheel_cache=None, # type: Optiona... | 0.000618 |
def _set_pvlan_tag(self, v, load=False):
"""
Setter method for pvlan_tag, mapped from YANG variable /interface/port_channel/switchport/private_vlan/trunk/pvlan_tag (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_pvlan_tag is considered as a private
method... | 0.005879 |
def _add_remover(self):
"""
Add a ``_remove_x()`` method to the element class for this child
element.
"""
def _remove_child(obj):
obj.remove_all(self._nsptagname)
_remove_child.__doc__ = (
'Remove all ``<%s>`` child elements.'
) % self._nsp... | 0.005063 |
def generate_html(self, jdoc, schema, schemas):
'''Generates html for a subset of jdoc records
describing objects of specific schema'''
params = {'functions': sorted([j for j in jdoc \
if (j.schema_name == schema.object_name and j.object_type \
in ['fun... | 0.010336 |
def get_indexed_slices(self, column_parent, index_clause, column_predicate, consistency_level):
"""
Returns the subset of columns specified in SlicePredicate for the rows matching the IndexClause
@deprecated use get_range_slices instead with range.row_filter specified
Parameters:
- column_parent
... | 0.006908 |
def create(self, url):
"""Create a bucket, directory, or empty file."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, ob... | 0.004695 |
def disconnect(self):
"""
Closes the connection.
"""
self.logger.debug('Close connection...')
self.auto_reconnect = False
if self.websocket is not None:
self.websocket.close() | 0.008439 |
def get_port_channel_detail_output_lacp_admin_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel_detail, "ou... | 0.003546 |
def _do_save_as(self, filename):
"""Saves spectrum back to FITS file."""
if len(self.spectrum.x) < 2:
raise RuntimeError("Spectrum must have at least two points")
if os.path.isfile(filename):
os.unlink(filename) # PyFITS does not overwrite file
hdu = self.spect... | 0.005405 |
def on_enter(self, *args):
"""Call the setter and blank myself out so that my hint text shows
up. It will be the same you just entered if everything's
working.
"""
if self.text == '':
return
self.setter(self.text)
self.text = ''
self.focus = F... | 0.006173 |
def propose(self, n=1):
"""Use the trained model to propose a new set of parameters.
Args:
n (int, optional): number of candidates to propose
Returns:
Mapping of tunable name to proposed value. If called with n>1 then proposal is a list
of dictionaries.
... | 0.001935 |
def check(self, text):
"""Yields bad words and suggested alternate spellings.
"""
for word, pos in self.tokenizer(text):
correct = self.dictionary.check(word)
if correct:
continue
yield word, self.dictionary.suggest(word) if self.suggest else [... | 0.005952 |
def copy(self, source_path, destination_path, threads=DEFAULT_THREADS, start_time=None, end_time=None,
part_size=DEFAULT_PART_SIZE, **kwargs):
"""
Copy object(s) from one S3 location to another. Works for individual keys or entire directories.
When files are larger than `part_size`,... | 0.009579 |
def delete_table_rate_rule_by_id(cls, table_rate_rule_id, **kwargs):
"""Delete TableRateRule
Delete an instance of TableRateRule by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.dele... | 0.006186 |
def _get_edge_sign(im, edge):
"""Get the polarity of the influence by examining the edge sign."""
edge_data = im[edge[0]][edge[1]]
# Handle possible multiple edges between nodes
signs = list(set([v['sign'] for v in edge_data.values()
if v.get('sign')]))
if len(signs... | 0.002786 |
def get_activating_mods(self):
"""Extract INDRA ActiveForm Statements with a single mod from BEL.
The SPARQL pattern used for extraction from BEL looks for a
ModifiedProteinAbundance as subject and an Activiy of a
ProteinAbundance as object.
Examples:
proteinAbunda... | 0.000861 |
def revdep_rebuild(lib=None):
'''
Fix up broken reverse dependencies
lib
Search for reverse dependencies for a particular library rather
than every library on the system. It can be a full path to a
library or basic regular expression.
CLI Example:
.. code-block:: bash
... | 0.001812 |
def remote_upload(self, picture_url, resize=None,
rotation=None, noexif=None):
"""
wraps remote_upload funktion
:param str picture_url: URL to picture allowd Protocols are: ftp,\
http, https
:param str resize: Aresolution in the folowing format: \
... | 0.004515 |
def main():
"""
Entry point.
"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
for arg in ARGUMENTS:
if "action" in arg:
if arg["short"] is not None:
parser.add_argument(arg["short"], arg["long"], action=arg["action"], help=arg["help"])
els... | 0.004941 |
def allocate(self):
"""Builds the context and the Hooks."""
self.logger.debug("Allocating environment.")
self._allocate()
self.logger.debug("Environment successfully allocated.") | 0.009524 |
def get_simplex_solution_graph(self):
'''
API:
get_simplex_solution_graph(self):
Description:
Assumes a feasible flow solution stored in 'flow' attribute's of
arcs. Returns the graph with arcs that have flow between 0 and
capacity.
Pre:
... | 0.004202 |
def get_port_profile_status_output_port_profile_mac_association_applied_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_status = ET.Element("get_port_profile_status")
config = get_port_profile_status
outp... | 0.002976 |
def add_aberration(position, velocity, light_time):
"""Correct a relative position vector for aberration of light.
Given the relative `position` [x,y,z] of an object (AU) from a
particular observer, the `velocity` [dx,dy,dz] at which the observer
is traveling (AU/day), and the light propagation delay `... | 0.001196 |
def connections_from_graph(env, G, edge_data=False):
"""Create connections for agents in the given environment from the given
NetworkX graph structure.
:param env:
Environment where the agents live. The environment should be derived
from :class:`~creamas.core.environment.Environment`,
... | 0.00041 |
def prep_ploidy(work_dir, sample, bam_file, cromwell_dir, sv_glob):
"""Create LOHHLA compatible input ploidy file from PureCN output.
"""
purecn_file = _get_cromwell_file(cromwell_dir, sv_glob, dict(sample=sample, method="purecn", ext="purecn.csv"))
work_dir = utils.safe_makedir(os.path.join(work_dir, s... | 0.004324 |
def pixy_set_brightness(self, brightness):
"""
Sends the setBrightness Pixy command.
This method sets the brightness (exposure) of Pixy's camera.
:param brightness: range between 0 and 255 with 255 being the
brightest setting
:returns: No return value... | 0.004386 |
def dump(self, dest_pattern="{id}.jpg", override=True, mask=False, alpha=False, bits=8,
zoom=None, max_size=None, increase_area=None, contrast=None, gamma=None, colormap=None, inverse=None):
"""
Download the annotation crop, with optional image modifications.
Parameters
---... | 0.004606 |
def checkUpdate(self, *args):
"""
Updates values after first checking instrument parameters are OK.
This is not integrated within update to prevent ifinite recursion
since update gets called from ipars.
"""
g = get_root(self).globals
if not self.check():
... | 0.003731 |
def _addLoggingOptions(addOptionFn):
"""
Adds logging options
"""
# BEFORE YOU ADD OR REMOVE OPTIONS TO THIS FUNCTION, KNOW THAT YOU MAY ONLY USE VARIABLES ACCEPTED BY BOTH
# optparse AND argparse FOR EXAMPLE, YOU MAY NOT USE default=%default OR default=%(default)s
defaultLogLevelName = logging.... | 0.00604 |
def get_sms_connection(backend=None, fail_silently=False, **kwds):
"""Load an sms backend and return an instance of it.
If backend is None (default) settings.SMS_BACKEND is used.
Both fail_silently and other keyword arguments are used in the
constructor of the backend.
https://github.com/django/django/blob/mast... | 0.019272 |
def get_filename_extensions(url='https://www.webopedia.com/quick_ref/fileextensionsfull.asp'):
""" Load a DataFrame of filename extensions from the indicated url
>>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html')
>>> df.head(2)
ext ... | 0.004658 |
def export_avg_losses(ekey, dstore):
"""
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
dskey = ekey[0]
oq = dstore['oqparam']
dt = oq.loss_dt()
name, value, tags = _get_data(dstore, dskey, oq.hazard_stats().items())
writer = writers.Csv... | 0.002841 |
def keep_tc_pos(func):
"""
Cache text cursor position and restore it when the wrapped
function exits.
This decorator can only be used on modes or panels.
:param func: wrapped function
"""
@functools.wraps(func)
def wrapper(editor, *args, **kwds):
""" Decorator """
sb = ... | 0.001497 |
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ser... | 0.001466 |
def basis_selector_oracle(qubits: List[int], bitstring: str) -> Program:
"""
Defines an oracle that selects the ith element of the computational basis.
Flips the sign of the state :math:`\\vert x\\rangle>`
if and only if x==bitstring and does nothing otherwise.
:param qubits: The qubits the oracle... | 0.002948 |
def _overlap(y,yr,psd):
""" returns the detector noise weighted inner product """
yyr = _inner_product(y,yr,psd)
yy = _inner_product(y,y,psd)
yryr = _inner_product(yr,yr,psd)
olap = yyr/np.sqrt(yy*yryr)
return olap | 0.045643 |
def close(self):
"""Close subscription.
"""
if self._S is not None:
# after .close() self._event should never be called
self._S.close()
# wait for Cancelled to be delivered
self._evt.wait()
self._S = None | 0.006944 |
def list_files(tag=None, sat_id=None, data_path=None, format_str=None,
supported_tags=None, fake_daily_files_from_monthly=False,
two_digit_year_break=None):
"""Return a Pandas Series of every file for chosen satellite data.
This routine is intended to be used by pysat instrume... | 0.005281 |
def get_field_type_from_schema(schema_type, field_name):
"""Return the type of the field in the given type, accounting for field name normalization."""
if field_name == '@class':
return GraphQLString
else:
if field_name not in schema_type.fields:
raise AssertionError(u'Field {} p... | 0.005329 |
def add_layer(self, tilemanager, opacity=1.0):
"""
Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing
"""
assert has_pil, _("Cannot blend layers without python PIL")
... | 0.006154 |
def mode(inlist):
"""
Returns a list of the modal (most common) score(s) in the passed
list. If there is more than one such score, all are returned. The
bin-count for the mode(s) is also returned.
Usage: lmode(inlist)
Returns: bin-count for mode(s), a list of modal value(s)
"""
scores = pstat.unique(inlis... | 0.001391 |
def get_card(self, index=-1, cache=True, remove=True):
"""
Retrieve a card any number of cards from the top. Returns a
``Card`` object loaded from a library if one is specified otherwise
just it will simply return its code.
If `index` is not set then the top card will be retrie... | 0.002317 |
def makemigrations(migrations_root):
"""等价于 django makemigrations 操作"""
from flask_migrate import (Migrate, init as migrate_init,
migrate as migrate_exec)
migrations_root = migrations_root or os.path.join(
os.environ.get('FANTASY_MIGRATION_PATH',
... | 0.00067 |
def set_cache_max(self, cache_name, maxsize, **kwargs):
"""
Sets the maxsize attribute of the named cache
"""
cache = self._get_cache(cache_name)
cache.set_maxsize(maxsize, **kwargs) | 0.009009 |
def random_str(n=20):
"""
随机生成一串密码
:param n: 密码的长度,默认为20
:return: 长度为n的随机字符串
"""
return ''.join(random.sample(string.ascii_letters + string.digits, n)) | 0.005714 |
def is_equal(self, other):
"""
The objects must be the same
- Same members (if enumerated)
- Or same structure (if not enumerated)
If the merge does not produce any new information (or contradiction)
then these are equal.
"""
print type(self.prototype... | 0.002861 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.