Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
383,600 | def assign_rates(self, mu=1.0, pi=None, W=None):
n = len(self.alphabet)
self.mu = mu
if pi is not None and len(pi)==n:
Pi = np.array(pi)
else:
if pi is not None and len(pi)!=n:
self.logger("length of equilibrium frequency vector does not ... | Overwrite the GTR model given the provided data
Parameters
----------
mu : float
Substitution rate
W : nxn matrix
Substitution matrix
pi : n vector
Equilibrium frequencies |
383,601 | def deregister_entity_from_group(self, entity, group):
if entity in self._entities:
if entity in self._groups[group]:
self._groups[group].remove(entity)
else:
raise UnmanagedEntityError(entity) | Removes entity from group |
383,602 | def get_unique_schema_id(schema):
assert isinstance(schema, GraphQLSchema), (
"Must receive a GraphQLSchema as schema. Received {}"
).format(repr(schema))
if schema not in _cached_schemas:
_cached_schemas[schema] = sha1(str(schema).encode("utf-8")).hexdigest()
return _cached_s... | Get a unique id given a GraphQLSchema |
383,603 | def remove_child_objective_banks(self, objective_bank_id):
if self._catalog_session is not None:
return self._catalog_session.remove_child_catalogs(catalog_id=objective_bank_id)
return self._hierarchy_session.remove_children(id_=objective_bank_id) | Removes all children from an objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
raise: NotFound - ``objective_bank_id`` not in hierarchy
raise: NullArgument - ``objective_bank_id`` is ``null``
raise: OperationFailed - unable to com... |
383,604 | def updateColumnName(self, networkId, tableType, body, verbose=None):
response=api(url=self.___url++str(networkId)++str(tableType)+, method="PUT", body=body, verbose=verbose)
return response | Renames an existing column in the table specified by the `tableType` and `networkId` parameters.
:param networkId: SUID of the network containing the table
:param tableType: Table Type
:param body: Old and new column name
:param verbose: print more
:returns: default: successful... |
383,605 | def BE8(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
return UInt8(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) | 8-bit field, Big endian encoded |
383,606 | def from_dict(cls, d):
s = Structure.from_dict(d)
return cls(s, history=d["history"],
other_parameters=d.get("other_parameters", None)) | Creates a TransformedStructure from a dict. |
383,607 | def str_id(self):
"str: This key's string id."
id_or_name = self.id_or_name
if id_or_name is not None and isinstance(id_or_name, str):
return id_or_name
return None | str: This key's string id. |
383,608 | def determine_end_point(http_request, url):
if url.endswith() or url.endswith():
return
else:
return if is_detail_url(http_request, url) else | returns detail, list or aggregates |
383,609 | def On_close_criteria_box(self, dia):
criteria_list = list(self.acceptance_criteria.keys())
criteria_list.sort()
avg_by = dia.set_average_by_sample_or_site.GetValue()
if avg_by == :
for crit in [, , , , ]:
self.acc... | after criteria dialog window is closed.
Take the acceptance criteria values and update
self.acceptance_criteria |
383,610 | def open_stream(stream):
global stream_fd
try:
stream_fd = stream.open()
except StreamError as err:
raise StreamError("Could not open stream: {0}".format(err))
try:
log.debug("Pre-buffering 8192 bytes")
prebuffer = stream_fd.read(8192)
except IOE... | Opens a stream and reads 8192 bytes from it.
This is useful to check if a stream actually has data
before opening the output. |
383,611 | def result_to_components(self, result, model, island_data, isflags):
global_data = self.global_data
isle_num = island_data.isle_num
idata = island_data.i
xmin, xmax, ymin, ymax = island_data.offsets
box = slice(int(xmin), int(xmax)), slice(int(ymin), int(ymax)... | Convert fitting results into a set of components
Parameters
----------
result : lmfit.MinimizerResult
The fitting results.
model : lmfit.Parameters
The model that was fit.
island_data : :class:`AegeanTools.models.IslandFittingData`
Data abou... |
383,612 | def is_local(self):
local_repo = package_repository_manager.get_repository(
self.config.local_packages_path)
return (self.resource._repository.uid == local_repo.uid) | Returns True if the package is in the local package repository |
383,613 | def suspended_updates():
if getattr(local_storage, "bulk_queue", None) is None:
local_storage.bulk_queue = defaultdict(list)
try:
yield
finally:
for index, items in local_storage.bulk_queue.items():
index.bulk(chain(*items))
local_storage.bulk_queue = None | This allows you to postpone updates to all the search indexes inside of a with:
with suspended_updates():
model1.save()
model2.save()
model3.save()
model4.delete() |
383,614 | def recv_raw(self, x=MTU):
pkt, sa_ll = self.ins.recvfrom(x)
if self.outs and sa_ll[2] == socket.PACKET_OUTGOING:
return None, None, None
ts = get_last_packet_timestamp(self.ins)
return self.LL, pkt, ts | Receives a packet, then returns a tuple containing (cls, pkt_data, time) |
383,615 | def GET(self, token=None, **kwargs):
s event stream
.. http:get:: /ws/(token)
:query format_events: The event stream will undergo server-side
formatting if the ``format_events`` URL parameter is included
in the request. This can be useful to avoid formatting on the
... | Return a websocket connection of Salt's event stream
.. http:get:: /ws/(token)
:query format_events: The event stream will undergo server-side
formatting if the ``format_events`` URL parameter is included
in the request. This can be useful to avoid formatting on the
... |
383,616 | def uniq2orderipix(uniq):
order = ((np.log2(uniq//4)) // 2)
order = order.astype(int)
ipix = uniq - 4 * (4**order)
return order, ipix | convert a HEALPix pixel coded as a NUNIQ number
to a (norder, ipix) tuple |
383,617 | def reindex(clear: bool, progressive: bool, batch_size: int):
reindexer = Reindexer(clear, progressive, batch_size)
reindexer.reindex_all() | Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to process before writing to the
index. Unused in sin... |
383,618 | def create(name, url, backend, frequency=None, owner=None, org=None):
log.info(, name)
source = actions.create_source(name, url, backend,
frequency=frequency,
owner=owner,
organization=org)
log.info... | Create a new harvest source |
383,619 | def create_instance(self, body, project_id=None):
response = self.get_conn().instances().insert(
project=project_id,
body=body
).execute(num_retries=self.num_retries)
operation_name = response["name"]
self._wait_for_operation_to_complete(project_id=projec... | Creates a new Cloud SQL instance.
:param body: Body required by the Cloud SQL insert API, as described in
https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/insert#request-body.
:type body: dict
:param project_id: Project ID of the project that contains the instance... |
383,620 | def deltran(tree, feature):
ps_feature = get_personalized_feature_name(feature, PARS_STATES)
for node in tree.traverse():
if not node.is_root():
node_states = getattr(node, ps_feature)
parent_states = getattr(node.up, ps_feature)
state_intersection = node_states... | DELTRAN (delayed transformation) (Swofford & Maddison, 1987) aims at reducing the number of ambiguities
in the parsimonious result. DELTRAN makes the changes as close as possible to the leaves,
hence prioritizing parallel mutations. DELTRAN is performed after DOWNPASS.
if N is not a root:
P <- pare... |
383,621 | def linkify_h_by_hg(self, hostgroups):
for host in self:
new_hostgroups = []
if hasattr(host, ) and host.hostgroups != []:
hgs = [n.strip() for n in host.hostgroups if n.strip()]
for hg_name in hgs:
... | Link hosts with hostgroups
:param hostgroups: hostgroups object to link with
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: None |
383,622 | def transform_file_output(result):
from collections import OrderedDict
new_result = []
iterable = result if isinstance(result, list) else result.get(, result)
for item in iterable:
new_entry = OrderedDict()
entity_type = item[]
is_dir = entity_type ==
new_entry... | Transform to convert SDK file/dir list output to something that
more clearly distinguishes between files and directories. |
383,623 | def get_display(display):
modname = _display_mods.get(platform, _default_display_mod)
mod = _relative_import(modname)
return mod.get_display(display) | dname, protocol, host, dno, screen = get_display(display)
Parse DISPLAY into its components. If DISPLAY is None, use
the default display. The return values are:
DNAME -- the full display name (string)
PROTOCOL -- the protocol to use (None if automatic)
HOST -- the host name (string,... |
383,624 | def get_pstats(pstatfile, n):
with tempfile.TemporaryFile(mode=) as stream:
ps = pstats.Stats(pstatfile, stream=stream)
ps.sort_stats()
ps.print_stats(n)
stream.seek(0)
lines = list(stream)
for i, line in enumerate(lines):
if line.startswith():
br... | Return profiling information as an RST table.
:param pstatfile: path to a .pstat file
:param n: the maximum number of stats to retrieve |
383,625 | def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert):
return authenticate_with_certificate_chain(
reactor, base_url, [client_cert], client_key, ca_cert,
) | See ``authenticate_with_certificate_chain``.
:param pem.Certificate client_cert: The client certificate to use. |
383,626 | def sio(mag_file, dir_path=".", input_dir_path="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
samp_infile="", institution="", syn=False, syntype="", instrument="",
labfield=0, phi=0, theta=0, peakfiel... | converts Scripps Institution of Oceanography measurement files to MagIC data base model 3.0
Parameters
_________
magfile : input measurement file
dir_path : output directory path, default "."
input_dir_path : input file directory IF different from dir_path, default ""
meas_file : output file me... |
383,627 | def get_timerange_formatted(self, now):
later = now + datetime.timedelta(days=self.days)
return now.isoformat(), later.isoformat() | Return two ISO8601 formatted date strings, one for timeMin, the other for timeMax (to be consumed by get_events) |
383,628 | def list_traces(
self,
project_id,
view=None,
page_size=None,
start_time=None,
end_time=None,
filter_=None,
order_by=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None... | Returns of a list of traces that match the specified filter conditions.
Example:
>>> from google.cloud import trace_v1
>>>
>>> client = trace_v1.TraceServiceClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
... |
383,629 | def get_values(self, obj):
if is_exception(obj.node):
label = r"\fb\f09%s\fn" % obj.title
else:
label = r"\fb%s\fn" % obj.title
if obj.shape == "interface":
shape = "ellipse"
else:
shape = "box"
if not self.config.only_clas... | get label and shape for classes.
The label contains all attributes and methods |
383,630 | def flag_forgotten_entries(session, today=None):
today = date.today() if today is None else today
forgotten = (
session
.query(Entry)
.filter(Entry.time_out.is_(None))
.filter(Entry.forgot_sign_out.is_(False))
.filter(Entry.date < today)
)
for entry in for... | Flag any entries from previous days where users forgot to sign
out.
:param session: SQLAlchemy session through which to access the database.
:param today: (optional) The current date as a `datetime.date` object. Used for testing. |
383,631 | def step_forward_with_function(self, uv0fun, uv1fun, dt):
dx, dy = self._rk4_integrate(self.x, self.y, uv0fun, uv1fun, dt)
self.x = self._wrap_x(self.x + dx)
self.y = self._wrap_y(self.y + dy) | Advance particles using a function to determine u and v.
Parameters
----------
uv0fun : function
Called like ``uv0fun(x,y)``. Should return the velocity field
u, v at time t.
uv1fun(x,y) : function
Called like ``uv1fun(x,y)``. Should return th... |
383,632 | def scale_rows(A, v, copy=True):
v = np.ravel(v)
M, N = A.shape
if not isspmatrix(A):
raise ValueError()
if M != len(v):
raise ValueError()
if copy:
A = A.copy()
A.data = np.asarray(A.data, dtype=upcast(A.dtype, v.dtype))
else:
v = np.asarray(v, d... | Scale the sparse rows of a matrix.
Parameters
----------
A : sparse matrix
Sparse matrix with M rows
v : array_like
Array of M scales
copy : {True,False}
- If copy=True, then the matrix is copied to a new and different return
matrix (e.g. B=scale_rows(A,v))
... |
383,633 | def stack_memory(data, n_steps=2, delay=1, **kwargs):
if n_steps < 1:
raise ParameterError()
if delay == 0:
raise ParameterError()
data = np.atleast_2d(data)
t = data.shape[1]
kwargs.setdefault(, )
if kwargs[] == :
kwargs.setdefault(, [0])
if delay > 0... | Short-term history embedding: vertically concatenate a data
vector or matrix with delayed copies of itself.
Each column `data[:, i]` is mapped to::
data[:, i] -> [data[:, i],
data[:, i - delay],
...
data[:, i - (n_steps-1)*delay]... |
383,634 | def get_modscag_fn_list(dem_dt, tile_list=(, , , , ), pad_days=7):
import re
import requests
from bs4 import BeautifulSoup
auth = iolib.get_auth()
pad_days = timedelta(days=pad_days)
dt_list = timelib.dt_range(dem_dt-pad_days, dem_dt+pad_days+timedelta(1), timedelta(1)... | Function to fetch and process MODSCAG fractional snow cover products for input datetime
Products are tiled in MODIS sinusoidal projection
example url: https://snow-data.jpl.nasa.gov/modscag-historic/2015/001/MOD09GA.A2015001.h07v03.005.2015006001833.snow_fraction.tif |
383,635 | def get_user_profile_photos(self, user_id, offset=None, limit=None):
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(offset, None, int, parameter_name="offset")
assert_type_or_raise(limit, None, int, parameter_name="limit")
... | Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
https://core.telegram.org/bots/api#getuserprofilephotos
Parameters:
:param user_id: Unique identifier of the target user
:type user_id: int
Opt... |
383,636 | def synced(func):
def wrapper(self, *args, **kwargs):
task = DataManagerTask(func, *args, **kwargs)
self.submit_task(task)
return task.get_results()
return wrapper | Decorator for functions that should be called synchronously from another thread
:param func: function to call |
383,637 | def validate_bool(b):
if isinstance(b, six.string_types):
b = b.lower()
if b in (, , , , , , 1, True):
return True
elif b in (, , , , , , 0, False):
return False
else:
raise ValueError( % b) | Convert b to a boolean or raise |
383,638 | def trees_by_subpath(self, sub_path):
matches = (
self.path_db[tree_path].keys()
for tree_path in self.path_db.iterkeys()
if tree_path.startswith(sub_path)
)
return set(sum(matches, [])) | Search trees by `sub_path` using ``Tree.path.startswith(sub_path)``
comparison.
Args:
sub_path (str): Part of the :attr:`.Tree.path` property of
:class:`.Tree`.
Returns:
set: Set of matching :class:`Tree` instances. |
383,639 | def preprocess_source(base_dir=os.curdir):
source_path = os.path.join(base_dir, SOURCE_DIR)
destination_path = os.path.join(base_dir, PREPROCESSED_DIR)
shutil.rmtree(os.path.join(base_dir, ), ignore_errors=True)
shutil.rmtree(os.path.join(base_dir, ), ignore_errors=True)
... | A special method for convert all source files to compatible with current
python version during installation time.
The source directory layout must like this :
base_dir --+
|
+-- src (All sources are placed into this directory)
|
+-- prep... |
383,640 | def sync_imports( self, quiet = False ):
self.open()
return self._client[:].sync_imports(quiet = quiet) | Return a context manager to control imports onto all the engines
in the underlying cluster. This method is used within a ``with`` statement.
Any imports should be done with no experiments running, otherwise the
method will block until the cluster is quiet. Generally imports will be one
... |
383,641 | def gradient(self):
L = self.L
n = self.L.shape[0]
grad = {"Lu": zeros((n, n, n * self._L.shape[1]))}
for ii in range(self._L.shape[0] * self._L.shape[1]):
row = ii // self._L.shape[1]
col = ii % self._L.shape[1]
grad["Lu"][row, :, ii] = L[:, ... | Derivative of the covariance matrix over the lower triangular, flat part of L.
It is equal to
∂K/∂Lᵢⱼ = ALᵀ + LAᵀ,
where Aᵢⱼ is an n×m matrix of zeros except at [Aᵢⱼ]ᵢⱼ=1.
Returns
-------
Lu : ndarray
Derivative of K over the lower-triangular, flat par... |
383,642 | def clamp(inclusive_lower_bound: int,
inclusive_upper_bound: int,
value: int) -> int:
if value <= inclusive_lower_bound:
return inclusive_lower_bound
elif value >= inclusive_upper_bound:
return inclusive_upper_bound
else:
return value | Bound the given ``value`` between ``inclusive_lower_bound`` and
``inclusive_upper_bound``. |
383,643 | def init(filename=ConfigPath):
section, parts = "DEFAULT", filename.rsplit(":", 1)
if len(parts) > 1 and os.path.isfile(parts[0]): filename, section = parts
if not os.path.isfile(filename): return
vardict, parser = globals(), configparser.RawConfigParser()
parser.optionxform = str
... | Loads INI configuration into this module's attributes. |
383,644 | def createFromSource(cls, vs, name=None):
s faster.
Normally version will be empty, unless the original url was of the
form: or , which can be used
to grab a particular tagged version.
(Note that for github components we ignore the component name - it
... | returns a github component for any github url (including
git+ssh:// git+http:// etc. or None if this is not a Github URL.
For all of these we use the github api to grab a tarball, because
that's faster.
Normally version will be empty, unless the original url was of the
... |
383,645 | def _concat_reps(self, kpop, max_var_multiple, quiet, **kwargs):
outf = os.path.join(self.workdir,
"{}-K-{}.indfile".format(self.name, kpop))
excluded = 0
reps = []
with open(outf, ) as outfile:
repfiles = glob.glob(
os.path.join(self.workdir,
... | Combine structure replicates into a single indfile,
returns nreps, ninds. Excludes reps with too high of
variance (set with max_variance_multiplier) to exclude
runs that did not converge. |
383,646 | def correct_structure(self, atol=1e-8):
return np.allclose(self.structure.lattice.matrix,
self.prim.lattice.matrix, atol=atol) | Determine if the structure matches the standard primitive structure.
The standard primitive will be different between seekpath and pymatgen
high-symmetry paths, but this is handled by the specific subclasses.
Args:
atol (:obj:`float`, optional): Absolute tolerance used to compare
... |
383,647 | def _y_axis(self, draw_axes=True):
if not self._y_labels or not self.show_y_labels:
return
axis = self.svg.node(self.nodes[], class_="axis y web")
for label, r in reversed(self._y_labels):
major = r in self._y_labels_major
if not (self.show_minor_y_... | Override y axis to make it polar |
383,648 | def retrieve(cls, *args, **kwargs):
return super(BankAccount, cls).retrieve(*args, **kwargs) | Return parent method. |
383,649 | def transition_loop(n_states, prob):
s self-transition.
Returns
-------
transition : np.ndarray [shape=(n_states, n_states)]
The transition matrix
Examples
--------
>>> librosa.sequence.transition_loop(3, 0.5)
array([[0.5 , 0.25, 0.25],
[0.25, 0.5 , 0.25],
... | Construct a self-loop transition matrix over `n_states`.
The transition matrix will have the following properties:
- `transition[i, i] = p` for all i
- `transition[i, j] = (1 - p) / (n_states - 1)` for all `j != i`
This type of transition matrix is appropriate when states tend to be
local... |
383,650 | def split_string(self, string):
self.actions = []
start = 0
last_char = if len(string) > 0 and string[-1] == else None
string = string[:-1] if last_char is not None else string
for match in ANSI_OR_SPECIAL_PATTERN.finditer(string):
... | Yields substrings for which the same escape code applies. |
383,651 | def generate_api_key(self):
endpoint = .join((self.server_url, , , ))
resp = self.r_session.post(endpoint)
resp.raise_for_status()
return response_to_json_dict(resp) | Creates and returns a new API Key/pass pair.
:returns: API key/pass pair in JSON format |
383,652 | def resolveFilenameConflicts(self):
taken_names = set()
resolved = False
for item, dp in self.getItemDPList():
if dp.policy not in ["remove", "ignore", "banish"]:
name0 = str(item.text(self.ColRename))
name = _makeUniqueF... | Goes through list of DPs to make sure that their destination names
do not clash. Adjust names as needed. Returns True if some conflicts were resolved. |
383,653 | def list_active_vms(cwd=None):
*
vms = []
cmd =
reply = __salt__[](cmd, cwd=cwd)
log.info(, reply)
for line in reply.split():
tokens = line.strip().split()
if len(tokens) > 1:
if tokens[1] == :
vms.append(tokens[0])
return vms | Return a list of machine names for active virtual machine on the host,
which are defined in the Vagrantfile at the indicated path.
CLI Example:
.. code-block:: bash
salt '*' vagrant.list_active_vms cwd=/projects/project_1 |
383,654 | def rolling_restart(self, slave_batch_size=None,
slave_fail_count_threshold=None,
sleep_seconds=None,
stale_configs_only=None,
unupgraded_only=None,
restart_role_types=None,
restart_role_n... | Rolling restart the roles of a service. The sequence is:
1. Restart all the non-slave roles
2. If slaves are present restart them in batches of size specified
3. Perform any post-command needed after rolling restart
@param slave_batch_size: Number of slave roles to restart at a time
Mu... |
383,655 | def _calculate_gas(owners: List[str], safe_setup_data: bytes, payment_token: str) -> int:
base_gas = 205000
if payment_token != NULL_ADDRESS:
payment_token_gas = 55000
else:
payment_token_gas = 0
data_gas = 68 * len(safe_setup_data) ... | Calculate gas manually, based on tests of previosly deployed safes
:param owners: Safe owners
:param safe_setup_data: Data for proxy setup
:param payment_token: If payment token, we will need more gas to transfer and maybe storage if first time
:return: total gas needed for deployment |
383,656 | def configure_logger(logger, filename, folder, log_level):
fmt = logging.Formatter()
if folder is not None:
log_file = os.path.join(folder, filename)
hdl = logging.FileHandler(log_file)
hdl.setFormatter(fmt)
hdl.setLevel(log_level)
logger.addHandler(hdl)
shdl = l... | Configure logging behvior for the simulations. |
383,657 | def sh3(cmd):
p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True,
env=sub_environment())
out, err = p.communicate()
retcode = p.returncode
if retcode:
raise CalledProcessError(retcode, cmd)
else:
return out.rstrip(), err.rstrip() | Execute command in a subshell, return stdout, stderr
If anything appears in stderr, print it out to sys.stderr |
383,658 | def write_hash_file_for_path(path, recompute=False):
r
hash_fpath_list = []
for root, dname_list, fname_list in os.walk(path):
for fname in sorted(fname_list):
fpath = os.path.join(root, fname)
hash_fpath = write_hash_file(fpath, recompute=recompute)
... | r""" Creates a hash file for each file in a path
CommandLine:
python -m utool.util_hash --test-write_hash_file_for_path
Example:
>>> # DISABLE_DOCTEST
>>> import os
>>> import utool as ut
>>> from utool.util_hash import * # NOQA
>>> fpath = ut.grab_test_imgpath... |
383,659 | def _emit_message(cls, message):
sys.stdout.write(message)
sys.stdout.flush() | Print a message to STDOUT. |
383,660 | def get_path(filename):
path = abspath(filename) if os.path.isdir(filename) else dirname(abspath(filename))
return path | Get absolute path for filename.
:param filename: file
:return: path |
383,661 | def getISAAssay(assayNum, studyNum, pathToISATABFile):
from isatools import isatab
import copy
try:
isa = isatab.load(pathToISATABFile, skip_load_tables=True)
std = isa.studies[studyNum - 1]
return copy.deepcopy(std.assays[assayNum - 1])
except FileNotFoundError as err:
... | This function returns an Assay object given the assay and study numbers in an ISA file
Typically, you should use the exploreISA function to check the contents
of the ISA file and retrieve the assay and study numbers you are interested in!
:param assayNum: The Assay number (notice it's not zero-based index).... |
383,662 | def oidcCredentials(self, *args, **kwargs):
return self._makeApiCall(self.funcinfo["oidcCredentials"], *args, **kwargs) | Get Taskcluster credentials given a suitable `access_token`
Given an OIDC `access_token` from a trusted OpenID provider, return a
set of Taskcluster credentials for use on behalf of the identified
user.
This method is typically not called with a Taskcluster client library
and d... |
383,663 | def get_id(self):
if self._dxid is not None:
return self._dxid
else:
return + self._name + + self._alias | :returns: Object ID of associated app
:rtype: string
Returns the object ID of the app that the handler is currently
associated with. |
383,664 | def _render_having(having_conditions):
if not having_conditions:
return ""
rendered_conditions = []
for condition in having_conditions:
field = condition.get()
field_type = condition.get()
comparators = condition.get()
if None in (field, field_type, comparator... | Render the having part of a query.
Parameters
----------
having_conditions : list
A ``list`` of ``dict``s to filter the rows
Returns
-------
str
A string that represents the "having" part of a query.
See Also
--------
render_query : Further clarification of `condit... |
383,665 | def problem(self):
if self.api and self.problem_id:
return self.api._get_problem(self.problem_id) | | Comment: For tickets of type "incident", the ID of the problem the incident is linked to |
383,666 | def token_scan(cls, result_key, token):
def _scan(self):
return token in self
cls.scan(result_key, _scan) | Define a property that is set to true if the given token is found in
the log file. Uses the __contains__ method of the log file. |
383,667 | def n_executions(self):
pipeline = self.tiger.connection.pipeline()
pipeline.exists(self.tiger._key(, self.id))
pipeline.llen(self.tiger._key(, self.id, ))
exists, n_executions = pipeline.execute()
if not exists:
raise TaskNotFound(.format(
se... | Queries and returns the number of past task executions. |
383,668 | def resubmit(self, job_ids = None, also_success = False, running_jobs = False, new_command=None, verbosity=0, keep_logs=False, **kwargs):
self.lock()
jobs = self.get_jobs(job_ids)
if new_command is not None:
if len(jobs) == 1:
jobs[0].set_command_line(new_command)
else:
... | Re-submit jobs automatically |
383,669 | def make_display_lines(self):
self.screen_height, self.screen_width = self.linesnum()
display_lines = []
display_lines.append(self._title + )
top = self.topline
bottom = self.topline + self.screen_height - 3
for index, i in enumerate(self._lines[top:bottom])... | 生成输出行
注意: 多线程终端同时输出会有bug, 导致起始位置偏移, 需要在每行加\r |
383,670 | def _decrypt(private_key, ciphertext, padding):
if not isinstance(private_key, PrivateKey):
raise TypeError(pretty_message(
,
type_name(private_key)
))
if not isinstance(ciphertext, byte_cls):
raise TypeError(pretty_message(
,
type_n... | Decrypts RSA ciphertext using a private key
:param private_key:
A PrivateKey object
:param ciphertext:
The ciphertext - a byte string
:param padding:
The padding mode to use, specified as a kSecPadding*Key value
:raises:
ValueError - when any of the parameters contain... |
383,671 | def get_all_player_ids(ids="shots"):
url = "http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=0&LeagueID=00&Season=2015-16"
response = requests.get(url, headers=HEADERS)
response.raise_for_status()
headers = response.json()[][0][]
players = response.json()[][0... | Returns a pandas DataFrame containing the player IDs used in the
stats.nba.com API.
Parameters
----------
ids : { "shots" | "all_players" | "all_data" }, optional
Passing in "shots" returns a DataFrame that contains the player IDs of
all players have shot chart data. It is the default ... |
383,672 | def get_gtf_db(gtf, in_memory=False):
db_file = gtf + ".db"
if file_exists(db_file):
return gffutils.FeatureDB(db_file)
if not os.access(os.path.dirname(db_file), os.W_OK | os.X_OK):
in_memory = True
db_file = ":memory:" if in_memory else db_file
if in_memory or not file_exists(... | create a gffutils DB, in memory if we don't have write permissions |
383,673 | def X_less(self):
self.parent.value(,
self.parent.value() / 2)
self.parent.overview.update_position() | Zoom out on the x-axis. |
383,674 | def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=256):
cmap = get_cmap(cmap)
name = "%s-trunc-%.2g-%.2g" % (cmap.name, minval, maxval)
return colors.LinearSegmentedColormap.from_list(
name, cmap(np.linspace(minval, maxval, n))) | Truncates a colormap, such that the new colormap consists of
``cmap[minval:maxval]``.
If maxval is larger than minval, the truncated colormap will be reversed.
Args:
cmap (colormap): Colormap to be truncated
minval (float): Lower bound. Should be a float betwee 0 and 1.
maxval (float): U... |
383,675 | def GetPlaylists(self, start, max_count, order, reversed):
cv = convert2dbus
return self.iface.GetPlaylists(cv(start, ),
cv(max_count, ),
cv(order, ),
cv(reversed, )) | Gets a set of playlists.
:param int start: The index of the first playlist to be fetched
(according to the ordering).
:param int max_count: The maximum number of playlists to fetch.
:param str order: The ordering that should be used.
:param bool reversed: Whet... |
383,676 | def add(self, subj: Node, pred: URIRef, obj: Node) -> "FHIRResource":
self._g.add((subj, pred, obj))
return self | Shortcut to rdflib add function
:param subj:
:param pred:
:param obj:
:return: self for chaining |
383,677 | def _generate_ndarray_function_code(handle, name, func_name, signature_only=False):
real_name = ctypes.c_char_p()
desc = ctypes.c_char_p()
num_args = mx_uint()
arg_names = ctypes.POINTER(ctypes.c_char_p)()
arg_types = ctypes.POINTER(ctypes.c_char_p)()
arg_descs = ctypes.POINTER(ctypes.c_cha... | Generate function for ndarray op by handle and function name. |
383,678 | def sh2(cmd):
p = Popen(cmd, stdout=PIPE, shell=True, env=sub_environment())
out = p.communicate()[0]
retcode = p.returncode
if retcode:
raise CalledProcessError(retcode, cmd)
else:
return out.rstrip() | Execute command in a subshell, return stdout.
Stderr is unbuffered from the subshell.x |
383,679 | def deflections_from_grid(self, grid, tabulate_bins=1000):
@jit_integrand
def surface_density_integrand(x, kappa_radius, scale_radius, inner_slope):
return (3 - inner_slope) * (x + kappa_radius / scale_radius) ** (inner_slope - 4) * (1 - np.sqrt(1 - x * x))
def calculate_d... | Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
tabulate_bins : int
The number of bins to tabulate the... |
383,680 | def flag(val):
if val == 1:
return True
elif val == 0:
return False
val = str(val)
if len(val) > 5:
return False
return val.upper() in (, , , , , , , ) | Does the value look like an on/off flag? |
383,681 | def on_bindok(self, unused_frame):
self._logger.info()
while not self._stopping:
self.producer(self)
self._logger.info("producer done") | This method is invoked by pika when it receives the Queue.BindOk
response from RabbitMQ. |
383,682 | def get_traindata(self) -> np.ndarray:
traindata = None
for key, value in self.data.items():
if key not in [, , ]:
if traindata is None:
traindata = value[np.where(value[:, 4] != 0)]
else:
traindata = np.concate... | Pulls all available data and concatenates for model training
:return: 2d array of points |
383,683 | def get_class_name(self):
if self.class_idx_value is None:
self.class_idx_value = self.CM.get_type(self.class_idx)
return self.class_idx_value | Return the class name of the field
:rtype: string |
383,684 | def make_full_url(request, url):
urlparts = request.urlparts
return .format(
scheme=urlparts.scheme,
site=get_site_name(request),
url=url.lstrip(),
) | Get a relative URL and returns the absolute version.
Eg: “/foo/bar?q=is-open” ==> “http://example.com/foo/bar?q=is-open” |
383,685 | def _get_descriptors(self):
rlist = []
wlist = []
xlist = []
for socket, flags in self.sockets.items():
if isinstance(socket, zmq.Socket):
rlist.append(socket.getsockopt(zmq.FD))
continue
elif isinstance(socket, int):
... | Returns three elements tuple with socket descriptors ready
for gevent.select.select |
383,686 | def zip(self, *others):
args = [_unwrap(item) for item in (self,) + others]
ct = self.count()
if not all(len(arg) == ct for arg in args):
raise ValueError("Arguments are not all the same length")
return Collection(map(Wrapper.wrap, zip(*args))) | Zip the items of this collection with one or more
other sequences, and wrap the result.
Unlike Python's zip, all sequences must be the same length.
Parameters:
others: One or more iterables or Collections
Returns:
A new collection.
Examples:
... |
383,687 | def has_permission(self, request, view):
if view.suffix == :
return True
filter_and_actions = self._get_filter_and_actions(
request.query_params.get(),
view.action,
.format(
view.queryset.model._meta.app_label,
vie... | Check list and create permissions based on sign and filters. |
383,688 | def loop(self, timeout=1.0, max_packets=1):
if timeout < 0.0:
raise ValueError()
self._current_out_packet_mutex.acquire()
self._out_packet_mutex.acquire()
if self._current_out_packet is None and len(self._out_packet) > 0:
self._current_out_packet = self.... | Process network events.
This function must be called regularly to ensure communication with the
broker is carried out. It calls select() on the network socket to wait
for network events. If incoming data is present it will then be
processed. Outgoing commands, from e.g. publish(), are n... |
383,689 | def main():
cli = docker.from_env()
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "pcv", ["pretty", "compose"])
except getopt.GetoptError as _:
print("Usage: docker-parse [--pretty|-p|--compose|-c] [containers]")
sys.exit(2)
if len(args) == 0:
containers = cli... | main entry |
383,690 | def _get_args_contents(self):
return .join(
% (key, shlex_quote(str(self.args[key])))
for key in self.args
) + | Mimic the argument formatting behaviour of
ActionBase._execute_module(). |
383,691 | def area(self, chord_length=1e-4):
def area_without_arcs(path):
area_enclosed = 0
for seg in path:
x = real(seg.poly())
dy = imag(seg.poly()).deriv()
integrand = x*dy
integral = integrand.integ()
ar... | Find area enclosed by path.
Approximates any Arc segments in the Path with lines
approximately `chord_length` long, and returns the area enclosed
by the approximated Path. Default chord length is 0.01. If Arc
segments are included in path, to ensure accurate results, make
... |
383,692 | def modify(self, service_name, json, **kwargs):
return self._send(requests.put, service_name, json, **kwargs) | Modify an AppNexus object |
383,693 | def deserialize_profile(profile, key_prefix=, pop=False):
result = {}
if pop:
getter = profile.pop
else:
getter = profile.get
def prefixed(name):
return % (key_prefix, name)
for key in profile.keys():
val = ... | De-serialize user profile fields into concrete model fields. |
383,694 | async def presentProof(self, proofRequest: ProofRequest) -> FullProof:
claims, requestedProof = await self._findClaims(proofRequest)
proof = await self._prepareProof(claims, proofRequest.nonce, requestedProof)
return proof | Presents a proof to the verifier.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:return: a proof (both primary and non-revocation) and revealed attributes (initial non-encoded values) |
383,695 | def process_stats(self, stats, prefix, metric_categories, nested_tags, tags, recursion_level=0):
for child in stats:
if child.tag in metrics.METRIC_VALUE_FIELDS:
self.submit_metrics(child, prefix, tags)
elif child.tag in metrics.CATEGORY_FIELDS:
r... | The XML will have Stat Nodes and Nodes that contain the metrics themselves
This code recursively goes through each Stat Node to properly setup tags
where each Stat will have a different tag key depending on the context. |
383,696 | def depth(self, value):
for command in self.subcommands.values():
command.depth = value + 1
del command.argparser._defaults[self.arg_label_fmt % self._depth]
command.argparser._defaults[self.arg_label_fmt % value] = command
self._depth = value | Update ourself and any of our subcommands. |
383,697 | def _make_pheno_assoc(
self, graph, gene_id, disorder_num, disorder_label, phene_key
):
disorder_id = .join((, disorder_num))
rel_label =
rel_id = self.globaltt[rel_label]
if disorder_label.startswith():
rel_id = self.globaltt[]
... | From the docs:
Brackets, "[ ]", indicate "nondiseases," mainly genetic variations
that lead to apparently abnormal laboratory test values
(e.g., dysalbuminemic euthyroidal hyperthyroxinemia).
Braces, "{ }", indicate mutations that contribute to susceptibility
to multifactorial d... |
383,698 | def _recon_lcs(x, y):
i, j = len(x), len(y)
table = _lcs(x, y)
def _recon(i, j):
if i == 0 or j == 0:
return []
elif x[i - 1] == y[j - 1]:
return _recon(i - 1, j - 1) + [(x[i - 1], i)]
elif table[i - 1, j] > table[i, j - 1]:
return _... | Returns the Longest Subsequence between x and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns:
sequence: LCS of x and y |
383,699 | def get_instance(cls, dependencies=None):
assert cls is not ContractBase,
assert cls.CONTRACT_NAME,
return cls(cls.CONTRACT_NAME, dependencies) | Return an instance for a contract name.
:param dependencies:
:return: Contract base instance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.