Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
368,900 | def _updateModelDBResults(self):
metrics = self._getMetrics()
reportDict = dict([(k,metrics[k]) for k in self._reportMetricLabels])
metrics = self._getMetrics()
optimizeDict = dict()
if self._optimizeKeyPattern is not None:
optimizeDict[self._optimize... | Retrieves the current results and updates the model's record in
the Model database. |
368,901 | def sort_cyclic_graph_best_effort(graph, pick_first=):
ordered = []
visited = set()
if pick_first == :
fst_attr, snd_attr = (, )
else:
fst_attr, snd_attr = (, )
current = FIRST
while current is not None:
visited.add(current)
current = getattr(... | Fallback for cases in which the graph has cycles. |
368,902 | def download_manifest_v2(self, manifest, replica,
num_retries=10,
min_delay_seconds=0.25,
download_dir=):
fieldnames, rows = self._parse_manifest(manifest)
errors = 0
with concurrent.futures.ThreadPo... | Process the given manifest file in TSV (tab-separated values) format and download the files referenced by it.
The files are downloaded in the version 2 format.
This download format will serve as the main storage format for downloaded files. If a user specifies a different
format for download (c... |
368,903 | def edit(self, **args):
t require manual fetching of gistID of a gist
passing gistName will return edit the gist
descriptiondescriptionnameidnameidnamenameididGist Name/ID must be providedcontentcontentGist content can\)
if (self.gist_name == ):
self.gist_name = self.getgist(id=self.gist_id)
data = {"des... | Doesn't require manual fetching of gistID of a gist
passing gistName will return edit the gist |
368,904 | def change_selected(self,new_fit):
if len(self.fit_list)==0: return
if self.search_query and self.parent.current_fit not in [x[0] for x in self.fit_list]: return
if self.current_fit_index == None:
if not self.parent.current_fit: return
for i,(fit,specimen) in enu... | updates passed in fit or index as current fit for the editor (does not affect parent),
if no parameters are passed in it sets first fit as current
@param: new_fit -> fit object to highlight as selected |
368,905 | def has_false(self, e, extra_constraints=(), solver=None, model_callback=None):
return self._has_false(self.convert(e), extra_constraints=extra_constraints, solver=solver, model_callback=model_callback) | Should return False if `e` can possibly be False.
:param e: The AST.
:param extra_constraints: Extra constraints (as ASTs) to add to the solver for this solve.
:param solver: A solver, for backends that require it.
:param model_callback: a function ... |
368,906 | def _ansi_color(code, theme):
red = 170 if code & 1 else 0
green = 170 if code & 2 else 0
blue = 170 if code & 4 else 0
color = QtGui.QColor(red, green, blue)
if theme is not None:
mappings = {
: theme.red,
: theme.green,
: theme.yellow,
:... | Converts an ansi code to a QColor, taking the color scheme (theme) into account. |
368,907 | def many(parser):
results = []
terminate = object()
while local_ps.value:
result = optional(parser, terminate)
if result == terminate:
break
results.append(result)
return results | Applies the parser to input zero or more times.
Returns a list of parser results. |
368,908 | def size(self):
if self.id.endswith("/"):
subqueues = self.get_known_subqueues()
if len(subqueues) == 0:
return 0
else:
with context.connections.redis.pipeline(transaction=False) as pipe:
for subqueue in subqueues:... | Returns the total number of queued jobs on the queue |
368,909 | def process_event(self, event_id):
with db.session.begin_nested():
event = Event.query.get(event_id)
event._celery_task = self
event.receiver.run(event)
flag_modified(event, )
flag_modified(event, )
db.session.add(event)
db.session.commit() | Process event in Celery. |
368,910 | def _update_capacity(self, data):
if in data:
consumed = data[]
if not isinstance(consumed, list):
consumed = [consumed]
for cap in consumed:
self.capacity += cap.get(, 0)
self.table_capacity += cap.get(,
... | Update the consumed capacity metrics |
368,911 | def __valueKeyWithHeaderIndex(self, values):
machingIndexes = {}
for index, name in enumerate(self.header):
if name in values:
machingIndexes[index] = values[name]
return machingIndexes | This is hellper function, so that we can mach decision values with row index
as represented in header index.
Args:
values (dict): Normaly this will have dict of header values and values from decision
Return:
>>> return()
{
values[headerName] : int(headerName index in header array),
...
} |
368,912 | def swap(self, old_chunks, new_chunk):
indexes = [self.index(chunk) for chunk in old_chunks]
del self[indexes[0]:indexes[-1] + 1]
self.insert(indexes[0], new_chunk) | Swaps old consecutive chunks with new chunk.
Args:
old_chunks (:obj:`budou.chunk.ChunkList`): List of consecutive Chunks to
be removed.
new_chunk (:obj:`budou.chunk.Chunk`): A Chunk to be inserted. |
368,913 | def load(cls, primary_key, convert_key=True):
if convert_key:
primary_key = cls._query.get_primary_hash_key(primary_key)
if not cls.__database__.hash_exists(primary_key):
raise KeyError()
raw_data = cls.__database__.hgetall(primary_key)
if PY3:
... | Retrieve a model instance by primary key.
:param primary_key: The primary key of the model instance.
:returns: Corresponding :py:class:`Model` instance.
:raises: ``KeyError`` if object with given primary key does
not exist. |
368,914 | def read(self):
with open(self.default_file) as json_file:
try:
return json.load(json_file)
except Exception as e:
raise | read default csp settings from json file |
368,915 | def _init_settings(self):
self._show_whitespaces = False
self._tab_length = 4
self._use_spaces_instead_of_tabs = True
self.setTabStopWidth(self._tab_length *
self.fontMetrics().width(" "))
self._set_whitespaces_flags(self._show_whitespaces) | Init setting |
368,916 | def summary(self, raw):
taxonomies = list()
level =
namespace =
if self.service == :
summary = raw.get(, dict()).get(, dict())
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, , summary.get(, 0)),
self.b... | Use the Backscatter.io summary data to create a view. |
368,917 | def _handleAuthorizedEvents(self, component, action, data, user, client):
try:
if component == "debugger":
self.log(component, action, data, user, client, lvl=info)
if not user and component in self.authorized_events.keys():
self.log("Unknown cl... | Isolated communication link for authorized events. |
368,918 | def alphabetize_attributes(self):
self.attributes.sort(key=lambda name: (name == self.class_attr_name, name)) | Orders attributes names alphabetically, except for the class attribute, which is kept last. |
368,919 | def setup_and_check(self, data, title=, readonly=False,
xlabels=None, ylabels=None):
self.data = data
readonly = readonly or not self.data.flags.writeable
is_record_array = data.dtype.names is not None
is_masked_array = isinstance(data, np.ma.Masked... | Setup ArrayEditor:
return False if data is not supported, True otherwise |
368,920 | def linkify_sd_by_s(self, hosts, services):
to_del = []
errors = self.configuration_errors
warns = self.configuration_warnings
for servicedep in self:
try:
s_name = servicedep.dependent_service_description
hst_name = servicedep.depende... | Replace dependent_service_description and service_description
in service dependency by the real object
:param hosts: host list, used to look for a specific one
:type hosts: alignak.objects.host.Hosts
:param services: service list to look for a specific one
:type services: aligna... |
368,921 | def cluster(self, input_fasta_list, reverse_pipe):
output_fasta_list = []
for input_fasta in input_fasta_list:
output_path = input_fasta.replace(, )
cluster_dict = {}
logging.debug()
if os.path.exists(input_fasta):
reads=self.seq... | cluster - Clusters reads at 100% identity level and writes them to
file. Resets the input_fasta variable as the FASTA file containing the
clusters.
Parameters
----------
input_fasta_list : list
list of strings, each a path to input fasta files to be clustered.
... |
368,922 | def encrypt_file(file_path, sender, recipients):
"Returns encrypted binary file content if successful"
for recipient_key in recipients:
crypto.assert_type_and_length(, recipient_key, (str, crypto.UserLock))
crypto.assert_type_and_length("sender_key", sender, crypto.UserLock)
if (not os.path.exis... | Returns encrypted binary file content if successful |
368,923 | def hide_columns(self, subset):
subset = _non_reducing_slice(subset)
hidden_df = self.data.loc[subset]
self.hidden_columns = self.columns.get_indexer_for(hidden_df.columns)
return self | Hide columns from rendering.
.. versionadded:: 0.23.0
Parameters
----------
subset : IndexSlice
An argument to ``DataFrame.loc`` that identifies which columns
are hidden.
Returns
-------
self : Styler |
368,924 | def __read_frame(self):
if self.__frame_header_cache is None:
_logger.debug("Reading frame header.")
(length, frame_type) = struct.unpack(, self.__read(8))
self.__frame_header_cache = (length, frame_type)
else:
(length, frame_type) = self.__frame... | *Attempt* to read a frame. If we get an EAGAIN on the frame header,
it'll raise to our caller. If we get it *after* we already got the
header, wait-out the rest of the frame. |
368,925 | def image(self):
self._image = self.genImage()
self._image = funcs.rotateImage(self._image, self.direction)
return self._image | Generates the image using self.genImage(),
then rotates it to self.direction and returns it. |
368,926 | def grp_by_src(self):
smodels = []
grp_id = 0
for sm in self.source_models:
src_groups = []
smodel = sm.__class__(sm.names, sm.weight, sm.path, src_groups,
sm.num_gsim_paths, sm.ordinal, sm.samples)
for sg in sm.src_g... | :returns: a new CompositeSourceModel with one group per source |
368,927 | def set_default_by_index(self, index):
if index >= len(self._datasets):
raise DataInvalidIndex(.format(index))
self._default_index = index | Set the default dataset by its index.
After changing the default dataset, all calls without explicitly specifying the
dataset by index or alias will be redirected to this dataset.
Args:
index (int): The index of the dataset that should be made the default.
Raises:
... |
368,928 | def overall_error_rate(self):
substitution_rate = metric.substitution_rate(
Nref=self.overall[],
Nsubstitutions=self.overall[]
)
deletion_rate = metric.deletion_rate(
Nref=self.overall[],
Ndeletions=self.overall[]
)
inse... | Overall error rate metrics (error_rate, substitution_rate, deletion_rate, and insertion_rate)
Returns
-------
dict
results in a dictionary format |
368,929 | def _get_maxcov_downsample(data):
from bcbio.bam import ref
from bcbio.ngsalign import alignprep, bwa
from bcbio.variation import coverage
fastq_file = data["files"][0]
params = alignprep.get_downsample_params(data)
if params:
num_reads = alignprep.total_reads_from_grabix(fastq_file... | Calculate maximum coverage downsampling for whole genome samples.
Returns None if we're not doing downsampling. |
368,930 | def clean(inst):
if (inst.clean_level == ) | (inst.clean_level == ):
idx, = np.where(inst[] == 0)
inst.data = inst[idx, :]
return None | Routine to return VEFI data cleaned to the specified level
Parameters
-----------
inst : (pysat.Instrument)
Instrument class object, whose attribute clean_level is used to return
the desired level of data selectivity.
Returns
--------
Void : (NoneType)
data in inst is m... |
368,931 | def on_epoch_end(self, epoch, smooth_loss, last_metrics, **kwargs):
"Logs training loss, validation loss and custom metrics & log prediction samples & save model"
if self.save_model:
current = self.get_monitor_value()
if current is not None and self.operator(current... | Logs training loss, validation loss and custom metrics & log prediction samples & save model |
368,932 | def unpack(fmt, data):
formatdef, endianness, i = getmode(fmt)
j = 0
num = 0
result = []
length = calcsize(fmt)
if length != len(data):
raise StructError("unpack str size does not match format")
while i < len(fmt):
num, i = getNum(fmt, i)
cur = fmt[i]
i += 1
try:
format = form... | unpack(fmt, string) -> (v1, v2, ...)
Unpack the string, containing packed C structure data, according
to fmt. Requires len(string)==calcsize(fmt).
See struct.__doc__ for more on format strings. |
368,933 | def _make_plus_helper(obj, fields):
new_obj = {}
for key, value in obj.items():
if key in fields or key.startswith():
return new_obj | add a + prefix to any fields in obj that aren't in fields |
368,934 | def checkStock(self):
if not self.preferences:
logger.debug("no preferences")
return None
soup = BeautifulSoup(
self.xpath(path[])[0].html, "html.parser")
count = 0
for product in soup.select("div.tradebox"):
prod_name = p... | check stocks in preference |
368,935 | def run(self):
while not self._stoped:
self._tx_event.wait()
self._tx_event.clear()
try:
func = self._tx_queue.get_nowait()
if isinstance(func, str):
self._stoped = True
self._rx_queue.put()
... | 执行任务 |
368,936 | def localCitesOf(self, rec):
localCites = []
if isinstance(rec, Record):
recCite = rec.createCitation()
if isinstance(rec, str):
try:
recCite = self.getID(rec)
except ValueError:
try:
recCite = Citat... | Takes in a Record, WOS string, citation string or Citation and returns a RecordCollection of all records that cite it.
# Parameters
_rec_ : `Record, str or Citation`
> The object that is being cited
# Returns
`RecordCollection`
> A `RecordCollection` containing only... |
368,937 | def union_join(left, right, left_as=, right_as=):
attrs = {}
attrs.update(get_object_attrs(right))
attrs.update(get_object_attrs(left))
attrs[left_as] = left
attrs[right_as] = right
if isinstance(left, dict) and isinstance(right, dict):
return attrs
else:
joined_class = ... | Join function truest to the SQL style join. Merges both objects together in a sum-type,
saving references to each parent in ``left`` and ``right`` attributes.
>>> Dog = namedtuple('Dog', ['name', 'woof', 'weight'])
>>> dog = Dog('gatsby', 'Ruff!', 15)
>>> Cat = namedtuple('Cat', ['name', '... |
368,938 | def magic(adata,
name_list=None,
k=10,
a=15,
t=,
n_pca=100,
knn_dist=,
random_state=None,
n_jobs=None,
verbose=False,
copy=None,
**kwargs):
try:
from magic import MAGIC
except ImportError:... | Markov Affinity-based Graph Imputation of Cells (MAGIC) API [vanDijk18]_.
MAGIC is an algorithm for denoising and transcript recover of single cells
applied to single-cell sequencing data. MAGIC builds a graph from the data
and uses diffusion to smooth out noise and recover the data manifold.
More inf... |
368,939 | def _is_streaming_request(self):
arg2 = self.argstreams[1]
arg3 = self.argstreams[2]
return not (isinstance(arg2, InMemStream) and
isinstance(arg3, InMemStream) and
((arg2.auto_close and arg3.auto_close) or (
arg2.state == ... | check request is stream request or not |
368,940 | def DropLocation():
template = Template(template=PathDirs().cfg_file)
drop_loc = template.option(, )[1]
drop_loc = expanduser(drop_loc)
drop_loc = abspath(drop_loc)
return (True, drop_loc) | Get the directory that file drop is watching |
368,941 | def _prune_node(self, node):
if self.is_pruning:
prune_key, node_body = self._node_to_db_mapping(node)
should_prune = (node_body is not None)
else:
should_prune = False
yield
if should_prune:
del self.db[pru... | Prune the given node if context exits cleanly. |
368,942 | def dist_in_usersite(dist):
norm_path = normalize_path(dist_location(dist))
return norm_path.startswith(normalize_path(user_site)) | Return True if given Distribution is installed in user site. |
368,943 | def p_declarations(self, p):
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = [p[1]] | declarations : declarations declaration
| declaration |
368,944 | def namedb_get_preorder(cur, preorder_hash, current_block_number, include_expired=False, expiry_time=None):
select_query = None
args = None
if include_expired:
select_query = "SELECT * FROM preorders WHERE preorder_hash = ?;"
args = (preorder_hash,)
else:
assert expiry_... | Get a preorder record by hash.
If include_expired is set, then so must expiry_time
Return None if not found. |
368,945 | def lookup_expand(self, stmt, names):
if not names: return []
todo = [stmt]
while todo:
pst = todo.pop()
for sub in pst.substmts:
if sub.keyword in self.schema_nodes:
qname = self.qname(sub)
if qname in name... | Find schema nodes under `stmt`, also in used groupings.
`names` is a list with qualified names of the schema nodes to
look up. All 'uses'/'grouping' pairs between `stmt` and found
schema nodes are marked for expansion. |
368,946 | def _get_target_nearest(self):
reps_query = .format(
maxorigin=self.origins.index.max(),
origin_table=self.origin_table,
target_table=self.target_table
)
nearest_reps = self.context.query(
reps_query,
decode_geom=True
... | Get nearest target for each origin |
368,947 | def connectionLost(self, reason):
if self.connection is not None:
del self.factory.protocols[self.connection] | If we already have an AMP connection registered on the factory,
get rid of it. |
368,948 | def aggregate(self, **filters):
url = URL.aggregate.format(**locals())
return self.get_pages(url, **filters) | Conduct an aggregate query |
368,949 | def set(self, style={}):
_style = {}
for attr in style:
if attr in self.cmds and not style[attr] in self.cmds[attr]:
print +utfstr(style[attr])++utfstr(attr)
else:
self.stack[-1][attr] = self.enforce_type(attr, style[attr]) | overrides style values at the current stack level |
368,950 | def convert_result(converter):
def decorate(fn):
@inspection.wraps(fn)
def new_fn(*args, **kwargs):
return converter(fn(*args, **kwargs))
return new_fn
return decorate | Decorator that can convert the result of a function call. |
368,951 | def autoLayout( self,
padX = None,
padY = None,
direction = Qt.Horizontal,
layout = ,
animate = 0,
centerOn = None,
center = None,
debug=False ):
... | Automatically lays out all the nodes in the scene using the \
autoLayoutNodes method.
:param padX | <int> || None | default is 2 * cell width
padY | <int> || None | default is 2 * cell height
direction | <Qt.Direction>
layout | <s... |
368,952 | def add_usr_local_bin_to_path(log=False):
if log:
bookshelf2.logging_helpers.log_green()
with settings(hide(, , , ),
capture=True):
try:
sudo(
)
return True
except:
raise SystemExit(1) | adds /usr/local/bin to $PATH |
368,953 | def _write(self, f):
log.debug("writing ndef record at offset {0}".format(f.tell()))
record_type = self.type
record_name = self.name
record_data = self.data
if record_type == :
header_flags = 0; record_name = ; record_data =
elif record_typ... | Serialize an NDEF record to a file-like object. |
368,954 | def present(name=None,
table_name=None,
region=None,
key=None,
keyid=None,
profile=None,
read_capacity_units=None,
write_capacity_units=None,
alarms=None,
alarms_from_pillar="boto_dynamodb_alarms",
ha... | Ensure the DynamoDB table exists. Table throughput can be updated after
table creation.
Global secondary indexes (GSIs) are managed with some exceptions:
- If a GSI deletion is detected, a failure will occur (deletes should be
done manually in the AWS console).
- If multiple GSIs are added in a... |
368,955 | def remove_directory(self, directory_name, *args, **kwargs):
client = self.dav_client()
remote_path = self.join_path(self.session_path(), directory_name)
if client.is_dir(remote_path) is False:
raise ValueError()
client.clean(remote_path) | :meth:`.WNetworkClientProto.remove_directory` method implementation |
368,956 | def _get_metadata(network_id, user_id):
log.info("Getting Metadata")
dataset_qry = db.DBSession.query(
Dataset
).outerjoin(DatasetOwner, and_(DatasetOwner.dataset_id==Dataset.id, DatasetOwner.user_id==user_id)).filter(
or_(Dataset.hidden==, DatasetOwner.user_id != None),... | Get all the metadata in a network, across all scenarios
returns a dictionary of dict objects, keyed on dataset ID |
368,957 | def get_document(self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
if not in self._inner_api_calls:
self._inner_api_calls[
... | Retrieves the specified document.
Example:
>>> import dialogflow_v2beta1
>>>
>>> client = dialogflow_v2beta1.DocumentsClient()
>>>
>>> name = client.document_path('[PROJECT]', '[KNOWLEDGE_BASE]', '[DOCUMENT]')
>>>
>>> response ... |
368,958 | def write_word_at(self, index: int, value: Union[int, BitVec, bool, Bool]) -> None:
try:
if isinstance(value, bool):
_bytes = (
int(1).to_bytes(32, byteorder="big")
if value
else int(0).to_bytes(32, byt... | Writes a 32 byte word to memory at the specified index`
:param index: index to write to
:param value: the value to write to memory |
368,959 | def bit_flip(
p: Optional[float] = None
) -> Union[common_gates.XPowGate, BitFlipChannel]:
r
if p is None:
return pauli_gates.X
return _bit_flip(p) | r"""
Construct a BitFlipChannel that flips a qubit state
with probability of a flip given by p. If p is None, return
a guaranteed flip in the form of an X operation.
This channel evolves a density matrix via
$$
\rho \rightarrow M_0 \rho M_0^\dagger + M_1 \rho M_1^\dagger
$$
... |
368,960 | def enable_rm_ha(self, new_rm_host_id, zk_service_name=None):
args = dict(
newRmHostId = new_rm_host_id,
zkServiceName = zk_service_name
)
return self._cmd(, data=args) | Enable high availability for a YARN ResourceManager.
@param new_rm_host_id: id of the host where the second ResourceManager
will be added.
@param zk_service_name: Name of the ZooKeeper service to use for auto-failover.
If YARN service depends on a ZooKeeper service then th... |
368,961 | def _parse_args(self, args, known_only):
unparsed_names_and_args = []
undefok = set()
retired_flag_func = self.__dict__[]
flag_dict = self._flags()
args = iter(args)
for arg in args:
value = None
def get_value():
try:
return next(args) if value is ... | Helper function to do the main argument parsing.
This function goes through args and does the bulk of the flag parsing.
It will find the corresponding flag in our flag dictionary, and call its
.parse() method on the flag value.
Args:
args: [str], a list of strings with the arguments to parse.
... |
368,962 | def cmd_list(args):
for penlist in penStore.data:
puts(penlist + " (" + str(len(penStore.data[penlist])) + ")") | List all element in pen |
368,963 | def list_cameras():
ctx = lib.gp_context_new()
camlist_p = new_gp_object("CameraList")
port_list_p = new_gp_object("GPPortInfoList")
lib.gp_port_info_list_load(port_list_p)
abilities_list_p = new_gp_object("CameraAbilitiesList")
lib.gp_abilities_list_load(abilities_list_p, ctx)
lib.gp_a... | List all attached USB cameras that are supported by libgphoto2.
:return: All recognized cameras
:rtype: list of :py:class:`Camera` |
368,964 | def get(self, request, *args, **kwargs):
self.object = self.get_object()
return self.render(request, obj=self.object,
done_url=self.get_done_url()) | Method for handling GET requests. Passes the
following arguments to the context:
* **obj** - The object to publish
* **done_url** - The result of the `get_done_url` method |
368,965 | def items(self, prefix=None, delimiter=None):
return _item.Items(self._name, prefix, delimiter, context=self._context) | Get an iterator for the items within this bucket.
Args:
prefix: an optional prefix to match items.
delimiter: an optional string to simulate directory-like semantics. The returned items
will be those whose names do not contain the delimiter after the prefix. For
the remaining item... |
368,966 | def record(self):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
return struct.pack(self.FMT, self.flags, self.identifier, self.suffix) | A method to generate the string representing this UDF Entity ID.
Parameters:
None.
Returns:
A string representing this UDF Entity ID. |
368,967 | def log_conditional_likelihood(self, x):
T, D = self.T, self.D_latent
assert x.shape == (T, D)
ll = 0
for t in range(self.T):
ll += self.local_log_likelihood(x[t], self.data[t], self.inputs[t])
return ll | likelihood \sum_t log p(y_t | x_t)
Optionally override this in base classes |
368,968 | def _api_call(function):
@wraps(function)
def wrapper(*args, **kwargs):
try:
if not _webview_ready.wait(15):
raise Exception()
return function(*args, **kwargs)
except NameError:
raise Exception()
except KeyError as e:
t... | Decorator to call a pywebview API, checking for _webview_ready and raisings
appropriate Exceptions on failure. |
368,969 | def get_profile(profile, caller, runner):
profiles = profile.split()
data = {}
for profile in profiles:
if os.path.basename(profile) == profile:
profile = profile.split()[0]
profile_path = os.path.join(os.path.dirname(__file__), , profile + )
else:
... | Get profile.
:param profile:
:return: |
368,970 | def _position(self):
position = 0
if self.state != STATE_IDLE:
resp = self._player.query_position(_FORMAT_TIME)
position = resp[1] // _NANOSEC_MULT
return position | Get media position. |
368,971 | def get_handler_stats(self):
return {
address : stream_capturer[0].dump_all_handler_stats()
for address, stream_capturer in self._stream_capturers.iteritems()
} | Return handler read statistics
Returns a dictionary of managed handler data read statistics. The
format is primarily controlled by the
:func:`SocketStreamCapturer.dump_all_handler_stats` function::
{
<capture address>: <list of handler capture statistics>
... |
368,972 | def email_send(text_template, html_template, data, subject, emails, headers=None):
text = get_template(text_template)
html = get_template(html_template)
text_content = text.render(data)
html_content = html.render(data)
subject = settings.EMAIL_SUBJECT_PREFIX + subject
headers = {} if heade... | Send an HTML/Plaintext email with the following fields.
text_template: URL to a Django template for the text email's contents
html_template: URL to a Django tempalte for the HTML email's contents
data: The context to pass to the templates
subject: The subject of the email
emails: The addresses to s... |
368,973 | def build(self, builder):
builder.start("Protocol", {})
for child in self.study_event_refs:
child.build(builder)
for alias in self.aliases:
alias.build(builder)
builder.end("Protocol") | Build XML by appending to builder |
368,974 | def cmd_isn(ip, port, count, iface, graph, verbose):
conf.verb = False
if iface:
conf.iface = iface
isn_values = []
for _ in range(count):
pkt = IP(dst=ip)/TCP(sport=RandShort(), dport=port, flags="S")
ans = sr1(pkt, timeout=0.5)
if ans:
send(IP(dst=i... | Create TCP connections and print the TCP initial sequence
numbers for each one.
\b
$ sudo habu.isn -c 5 www.portantier.com
1962287220
1800895007
589617930
3393793979
469428558
Note: You can get a graphical representation (needs the matplotlib package)
using the '-g' option to b... |
368,975 | def _delete_port_profile_from_ucsm(self, handle, port_profile, ucsm_ip):
port_profile_dest = (const.PORT_PROFILESETDN + const.VNIC_PATH_PREFIX +
port_profile)
handle.StartTransaction()
p_profile = handle.GetManagedObject(
None,
... | Deletes Port Profile from UCS Manager. |
368,976 | def update(context, id, etag, name, country, parent_id, active, external):
result = team.update(context, id=id, etag=etag, name=name,
state=utils.active_string(active),
country=country, parent_id=parent_id,
external=external)
util... | update(context, id, etag, name, country, parent_id, active, external)
Update a team.
>>> dcictl team-update [OPTIONS]
:param string id: ID of the team to update [required]
:param string etag: Entity tag of the resource [required]
:param string name: Name of the team [required]
:param string c... |
368,977 | def _get_chrbands(self, limit, taxon):
model = Model(self.graph)
line_counter = 0
myfile = .join((self.rawdir, self.files[taxon][]))
LOG.info("Processing Chr bands from FILE: %s", myfile)
geno = Genotype(self.graph)
... | For the given taxon, it will fetch the chr band file.
We will not deal with the coordinate information with this parser.
Here, we only are concerned with building the partonomy.
:param limit:
:return: |
368,978 | def apply_u_umlaut(stem: str):
assert len(stem) > 0
s_stem = s.syllabify_ssp(stem.lower())
if len(s_stem) == 1:
last_syllable = OldNorseSyllable(s_stem[-1], VOWELS, CONSONANTS)
last_syllable.apply_u_umlaut()
return "".join(s_stem[:-1]) + str(last_syllable)
else:
pen... | Changes the vowel of the last syllable of the given stem if the vowel is affected by an u-umlaut.
>>> apply_u_umlaut("far")
'för'
>>> apply_u_umlaut("ör")
'ör'
>>> apply_u_umlaut("axl")
'öxl'
>>> apply_u_umlaut("hafn")
'höfn'
:param stem:
:return: |
368,979 | def process_form(self, instance, field, form, empty_marker = None,
emptyReturnsMarker = False):
bsc = getToolByName(instance, )
default = super(PartitionSetupWidget,self).process_form(
instance, field, form, empty_marker, emptyReturnsMarker)
if not defau... | Some special field handling for disabled fields, which don't
get submitted by the browser but still need to be written away. |
368,980 | def notes_to_positions(notes, root):
root_pos = note_to_val(root)
current_pos = root_pos
positions = []
for note in notes:
note_pos = note_to_val(note)
if note_pos < current_pos:
note_pos += 12 * ((current_pos - note_pos) // 12 + 1)
positions.append(note_pos - ro... | Get notes positions.
ex) notes_to_positions(["C", "E", "G"], "C") -> [0, 4, 7]
:param list[str] notes: list of notes
:param str root: the root note
:rtype: list[int]
:return: list of note positions |
368,981 | def current_git_dir():
path = os.path.abspath(os.curdir)
while path != :
if os.path.isdir(os.path.join(path, )):
return os.path.join(path, )
path = os.path.dirname(path)
return None | Locate the .git directory. |
368,982 | def _get_pos(self):
if self._h >= len(self._options):
return 0
else:
return self._start_line / (len(self._options) - self._h) | Get current position for scroll bar. |
368,983 | def getStrings(lang_dict):
field_list = []
kw = {}
try:
str_count = len(next(iter(lang_dict.values())))
except StopIteration:
str_count = 0
else:
for lang, string_list in lang_dict.items():
if len(string_list) != str_count:
raise ValueError()
... | Return a FunctionFS descriptor suitable for serialisation.
lang_dict (dict)
Key: language ID (ex: 0x0409 for en-us)
Value: list of unicode objects
All values must have the same number of items. |
368,984 | def rackconnect(vm_):
FalseTrue
return config.get_cloud_config_value(
, vm_, __opts__, default=False,
search_global=False
) | Determine if we should wait for rackconnect automation before running.
Either 'False' (default) or 'True'. |
368,985 | def update_helper_political_level(self):
current_country = self.country_comboBox.currentText()
index = self.admin_level_comboBox.currentIndex()
current_level = self.admin_level_comboBox.itemData(index)
content = None
try:
content = \
self.coun... | To update the helper about the country and the admin_level. |
368,986 | def ADOSC(frame, fast=3, slow=10, high_col=, low_col=, close_col=, vol_col=):
return _frame_to_series(frame, [high_col, low_col, close_col, vol_col], talib.ADOSC, fast, slow) | Chaikin A/D oscillator |
368,987 | def _max(self):
return (
self.range[1] if (self.range and self.range[1] is not None) else
(max(self._values) if self._values else None)
) | Getter for the maximum series value |
368,988 | def outputFieldMarkdown(self):
f, d = self.getFieldsColumnLengths()
fc, dc = self.printFieldsHeader(f, d)
f = max(fc, f)
d = max(dc, d)
self.printFields(f, d) | Sends the field definitions ot standard out |
368,989 | def switch_to_window(self, window, wait=None):
if len(self._scopes) > 1:
raise ScopeError(
"`switch_to_window` is not supposed to be invoked from "
"within `scope`s, `frame`s, or other `window`s.")
if isinstance(window, Window):
self.dri... | If ``window`` is a lambda, it switches to the first window for which ``window`` returns a
value other than False or None. If a window that matches can't be found, the window will be
switched back and :exc:`WindowError` will be raised.
Args:
window (Window | lambda): The window that ... |
368,990 | def _calc_traceback_limit(tb):
limit = 1
tb2 = tb
while not tb2.tb_next is None:
try:
maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2]
except IndexError:
maybe_pytypes = None
if maybe_pytypes == and not \
tb2.tb_n... | Calculates limit-parameter to strip away pytypes' internals when used
with API from traceback module. |
368,991 | def walker(top, names):
global packages, extensions
if any(exc in top for exc in excludes):
return
package = top[top.rfind():].replace(os.path.sep, )
packages.append(package)
for name in names:
ext = .join(name.split()[1:])
ext_str = % ext
if ext and ext not in ... | Walks a directory and records all packages and file extensions. |
368,992 | def deftypes(self):
for f in self.body:
if (hasattr(f, )
and (f._ctype._storage == Storages.TYPEDEF
or (f._name == and isinstance(f._ctype, ComposedType)))):
yield f | generator on all definition of type |
368,993 | def linearization_error(nodes):
r
_, num_nodes = nodes.shape
degree = num_nodes - 1
if degree == 1:
return 0.0
second_deriv = nodes[:, :-2] - 2.0 * nodes[:, 1:-1] + nodes[:, 2:]
worst_case = np.max(np.abs(second_deriv), axis=1)
multiplier = 0.125 * degree * (degree - 1)
... | r"""Compute the maximum error of a linear approximation.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
.. note::
This is a helper for :class:`.Linearization`, which is used during the
curve-curve intersection process.
... |
368,994 | def delete_user(self, email):
LOG.info("Deleting user %s", email)
user_obj = self.user_collection.delete_one({: email})
return user_obj | Delete a user from the database
Args:
email(str)
Returns:
user_obj(dict) |
368,995 | def random_color(dtype=np.uint8):
hue = np.random.random() + .61803
hue %= 1.0
color = np.array(colorsys.hsv_to_rgb(hue, .99, .99))
if np.dtype(dtype).kind in :
max_value = (2**(np.dtype(dtype).itemsize * 8)) - 1
color *= max_value
color = np.append(color, max_value).astype(dtyp... | Return a random RGB color using datatype specified.
Parameters
----------
dtype: numpy dtype of result
Returns
----------
color: (4,) dtype, random color that looks OK |
368,996 | def add_widget_to_content(self, widget):
self.__section_content_column.add_spacing(4)
self.__section_content_column.add(widget) | Subclasses should call this to add content in the section's top level column. |
368,997 | def initialize(self, stormconf, context):
self.terms = get_config()[][]
self.term_seq = itertools.cycle(self.terms) | Initialization steps:
1. Prepare sequence of terms based on config: TermCycleSpout/terms. |
368,998 | def _draw_image(self, ci):
img = img_adjust(ci.image, ci.opacity, tempdir=self.dir)
self.can.drawImage(img, x=ci.x, y=ci.y, width=ci.w, height=ci.h, mask=ci.mask,
preserveAspectRatio=ci.preserve_aspect_ratio, anchorAtXY=True) | Draw image object to reportlabs canvas.
:param ci: CanvasImage object |
368,999 | def timeout(seconds, error_message=None):
def decorated(func):
result = ""
def _handle_timeout(signum, frame):
errmsg = error_message or % func.__name__
global result
result = None
import inspect
stack_frame = inspect.stack()[4]
... | Timeout checking just for Linux-like platform, not working in Windows platform. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.