Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
4,700 | def add_section(self, section_name: str) -> None:
section_name = self._whitespace_re.sub(, section_name)
self._sections.append(section_name)
setattr(self, section_name, Section()) | Add a section to the :class:`SampleSheet`. |
4,701 | def load(self, options):
if options.autoblend:
self.autoblend()
for child in self.children:
child.build()
for child in self.children:
child.open_imports(options)
for child in self.children:
child.dereference()
log.debug(, s... | Load the schema objects for the root nodes.
- de-references schemas
- merge schemas
@param options: An options dictionary.
@type options: L{options.Options}
@return: The merged schema.
@rtype: L{Schema} |
4,702 | def _set_lookup_prop(self, result_data):
if self._lookup_prop:
return
if result_data.get("id"):
self._lookup_prop = "id"
elif result_data.get("title"):
self._lookup_prop = "name"
else:
return
logger.debug("Setting lookup ... | Set lookup property based on processed testcases if not configured. |
4,703 | def _compute(self, arrays, dates, assets, mask):
return masked_rankdata_2d(
arrays[0],
mask,
self.inputs[0].missing_value,
self._method,
self._ascending,
) | For each row in the input, compute a like-shaped array of per-row
ranks. |
4,704 | def _is_type(self, instance, type):
if type not in self._types:
raise UnknownType(type)
type = self._types[type]
if isinstance(instance, bool):
type = _flatten(type)
if int in type and bool not in type:
return False
r... | Check if an ``instance`` is of the provided (JSON Schema) ``type``. |
4,705 | def build(self):
if self._category_text_iter is None:
raise CategoryTextIterNotSetError()
nlp = self.get_nlp()
category_document_iter = (
(category, self._clean_function(raw_text))
for category, raw_text
in self._category_text_iter
... | Generate a TermDocMatrix from data in parameters.
Returns
----------
term_doc_matrix : TermDocMatrix
The object that this factory class builds. |
4,706 | def definition_name(cls):
outer_definition_name = cls.outer_definition_name()
if outer_definition_name is None:
return six.text_type(cls.__name__)
return u % (outer_definition_name, cls.__name__) | Helper method for creating definition name.
Names will be generated to include the classes package name,
scope (if the class is nested in another definition) and class
name.
By default, the package name for a definition is derived from
its module name. However, this value can b... |
4,707 | def __dfs(self, start, weights, depth_limit):
adj = self._adj
stack = [(start, depth_limit, iter(sorted(adj[start], key=weights)))]
visited = {start}
disconnected = defaultdict(list)
edges = defaultdict(list)
while stack:
parent, depth_now, children... | modified NX dfs |
4,708 | def bind_kernel(**kwargs):
from IPython.zmq.ipkernel import IPKernelApp
from IPython.parallel.apps.ipengineapp import IPEngineApp
if IPKernelApp.initialized() and isinstance(IPKernelApp._instance, IPKernelApp):
return
if IPEngineApp.initialized():
try:
... | Bind an Engine's Kernel to be used as a full IPython kernel.
This allows a running Engine to be used simultaneously as a full IPython kernel
with the QtConsole or other frontends.
This function returns immediately. |
4,709 | def predict_mhci_binding(job, peptfile, allele, peplen, univ_options, mhci_options):
work_dir = os.getcwd()
input_files = {
: peptfile}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
peptides = read_peptide_file(os.path.join(os.getcwd(), ))
if not peptid... | Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhci binding
prediction tool.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param str peplen: Length of peptides to process
:param dict univ_options: Dict... |
4,710 | def _set_current_page(self, current_page, last_page):
if not current_page:
current_page = self.resolve_current_page()
if current_page > last_page:
if last_page > 0:
return last_page
return 1
if not self._is_valid_page_number(current... | Get the current page for the request.
:param current_page: The current page of results
:type current_page: int
:param last_page: The last page of results
:type last_page: int
:rtype: int |
4,711 | def on_service_modify(self, svc_ref, old_properties):
with self._lock:
try:
service = self.services[svc_ref]
except KeyError:
return self.on_service_arrival(svc_ref)
else:
... | Called when a service has been modified in the framework
:param svc_ref: A service reference
:param old_properties: Previous properties values
:return: A tuple (added, (service, reference)) if the dependency has
been changed, else None |
4,712 | def cast_to_python(self, value):
if value is not None:
value = UserGroup(self._swimlane, value)
return value | Convert JSON definition to UserGroup object |
4,713 | def to_flat_dict(self, **kwargs):
if kwargs:
return self.filter(**kwargs).to_flat_dict()
return {param.uniquetwig: param for param in self._params} | Convert the :class:`ParameterSet` to a flat dictionary, with keys being
uniquetwigs to access the parameter and values being the :class:`Parameter`
objects themselves.
:return: dict of :class:`Parameter`s |
4,714 | def _file_path(self, uid):
file_name = % (uid)
return os.path.join(self.dayone_journal_path, file_name) | Create and return full file path for DayOne entry |
4,715 | def lambda_not_found_response(*args):
response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | Constructs a Flask Response for when a Lambda function is not found for an endpoint
:return: a Flask Response |
4,716 | def add_extensions(self, extensions):
for ext in extensions:
if not isinstance(ext, X509Extension):
raise ValueError("One of the elements is not an X509Extension")
add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
if not add_result:
... | Add extensions to the certificate.
:param extensions: The extensions to add.
:type extensions: An iterable of :py:class:`X509Extension` objects.
:return: ``None`` |
4,717 | def user_events(self, user_obj=None):
query = dict(user_id=user_obj[]) if user_obj else dict()
return self.event_collection.find(query) | Fetch all events by a specific user. |
4,718 | def getPrefixDirectories(self, engineRoot, delimiter=):
return delimiter.join(self.resolveRoot(self.prefixDirs, engineRoot)) | Returns the list of prefix directories for this library, joined using the specified delimiter |
4,719 | def configureCredentials(self, CAFilePath, KeyPath="", CertificatePath=""):
self._AWSIoTMQTTClient.configureCredentials(CAFilePath, KeyPath, CertificatePath) | **Description**
Used to configure the rootCA, private key and certificate files. Should be called before connect. This is a public
facing API inherited by application level public clients.
**Syntax**
.. code:: python
myShadowClient.clearLastWill("PATH/TO/ROOT_CA", "PATH/TO/... |
4,720 | def proto_IC_ramp_gain(abf=exampleABF):
standard_inspect(abf)
swhlab.ap.detect(abf)
swhlab.ap.check_AP_raw(abf)
swhlab.plot.save(abf,tag="01-raw",resize=False)
swhlab.ap.check_AP_deriv(abf)
swhlab.plot.save(abf,tag="02-deriv")
swhlab.ap.check_AP_phase(abf)
swhlab.plot.save(abf,t... | increasing ramps in (?) pA steps. |
4,721 | def nlargest(self, n=None):
if n is None:
return sorted(self.counts(), key=itemgetter(1), reverse=True)
else:
return heapq.nlargest(n, self.counts(), key=itemgetter(1)) | List the n most common elements and their counts.
List is from the most
common to the least. If n is None, the list all element counts.
Run time should be O(m log m) where m is len(self)
Args:
n (int): The number of elements to return |
4,722 | def _fset(self, name):
def fset(inst, value):
value = self.fparse(inst, value)
setattr(inst, name, value)
return fset | Build and returns the property's *fdel* method for the member defined by *name*. |
4,723 | def reverse(self):
enabled = self.lib.iperf_get_test_reverse(self._test)
if enabled:
self._reverse = True
else:
self._reverse = False
return self._reverse | Toggles direction of test
:rtype: bool |
4,724 | def write(self, __text: str) -> None:
if __text == os.linesep:
self.handle.write(__text)
else:
frame = inspect.currentframe()
if frame is None:
filename =
lineno = 0
else:
outer = frame.f_back
... | Write text to the debug stream.
Args:
__text: Text to write |
4,725 | def parse_safari (url_data):
from ..bookmarks.safari import parse_bookmark_data
for url, name in parse_bookmark_data(url_data.get_content()):
url_data.add_url(url, name=name) | Parse a Safari bookmark file. |
4,726 | def _add_q(self, q_object):
self._criteria = self._criteria._combine(q_object, q_object.connector) | Add a Q-object to the current filter. |
4,727 | def _self_event(self, event_name, cmd, *pargs, **kwargs):
if hasattr(self, event_name):
getattr(self, event_name)(cmd, *pargs, **kwargs) | Call self event |
4,728 | def t_BIN_STRING(self, t):
r[01]*\
value = t.value[1:-2]
while value and value[0] == and len(value) % 8:
value = value[1:]
return t | r'\'[01]*\'[bB] |
4,729 | def constructor(self, random, args):
self._use_ants = True
candidate = []
while len(candidate) < len(self.components):
feasible_components = []
if len(candidate) == 0:
feasible_components = self.components
else:
... | Return a candidate solution for an ant colony optimization. |
4,730 | def parse_int(value, base_unit=None):
convert = {
: {: 1, : 1024, : 1024 * 1024, : 1024 * 1024 * 1024},
: {: 1, : 1000, : 1000 * 60, : 1000 * 60 * 60, : 1000 * 60 * 60 * 24},
: {: -1000, : 1, : 60, : 60 * 60, : 60 * 60 * 24},
: {: -1000 * 60, : -60, : 1, : 60, : 60 * 24}
}
... | >>> parse_int('1') == 1
True
>>> parse_int(' 0x400 MB ', '16384kB') == 64
True
>>> parse_int('1MB', 'kB') == 1024
True
>>> parse_int('1000 ms', 's') == 1
True
>>> parse_int('1GB', 'MB') is None
True
>>> parse_int(0) == 0
True |
4,731 | def match_phase(qpi, model, n0, r0, c0=None, pha_offset=0,
fix_pha_offset=False, nrel=.10, rrel=.05, crel=.05,
stop_dn=.0005, stop_dr=.0010, stop_dc=1, min_iter=3,
max_iter=100, ret_center=False, ret_pha_offset=False,
ret_qpi=False, ret_num_iter=False, ret... | Fit a scattering model to a quantitative phase image
Parameters
----------
qpi: qpimage.QPImage
QPI data to fit (e.g. experimental data)
model: str
Name of the light-scattering model
(see :const:`qpsphere.models.available`)
n0: float
Initial refractive index of the s... |
4,732 | def resizeEvent(self, event):
if not self.isMaximized() and not self.fullscreen_flag:
self.window_size = self.size()
QMainWindow.resizeEvent(self, event)
self.sig_resized.emit(event) | Reimplement Qt method |
4,733 | def save_dtrajs(self, prefix=, output_dir=,
output_format=, extension=):
r
clustering = self._chain[-1]
reader = self._chain[0]
from pyemma.coordinates.clustering.interface import AbstractClustering
assert isinstance(clustering, AbstractClustering)
t... | r"""Saves calculated discrete trajectories. Filenames are taken from
given reader. If data comes from memory dtrajs are written to a default
filename.
Parameters
----------
prefix : str
prepend prefix to filenames.
output_dir : str (optional)
sav... |
4,734 | def geoid(self):
if self.valuetype_class.is_geoid():
return self
for c in self.table.columns:
if c.parent == self.name and c.valuetype_class.is_geoid():
return c | Return first child of the column, or self that is marked as a geographic identifier |
4,735 | def reset_namespace(self):
self.shellwidget.reset_namespace(warning=self.reset_warning,
message=True) | Resets the namespace by removing all names defined by the user |
4,736 | def export_true_table():
tester_list = [
("inspect.isroutine", lambda v: inspect.isroutine(v)),
("inspect.isfunction", lambda v: inspect.isfunction(v)),
("inspect.ismethod", lambda v: inspect.ismethod(v)),
("isinstance.property", lambda v: isinstance(v, property)),
("isi... | Export value, checker function output true table.
Help to organize thought.
klass.__dict__ 指的是在类定义中定义的, 从父类继承而来的不在此中。 |
4,737 | def keep_recent_datasets(max_dataset_history, info=None):
history = settings.value(, [])
if isinstance(history, str):
history = [history]
if info is not None and info.filename is not None:
new_dataset = info.filename
if new_dataset in history:
lg.debug(new_dataset ... | Keep track of the most recent recordings.
Parameters
----------
max_dataset_history : int
maximum number of datasets to remember
info : str, optional TODO
path to file
Returns
-------
list of str
paths to most recent datasets (only if you don't specify
new_d... |
4,738 | def set_referencepixel(self, pix):
assert len(pix) == len(self._coord["crpix"])
self._coord["crpix"] = pix[::-1] | Set the reference pixel of the given axis in this coordinate. |
4,739 | def get_default_gateway():
try:
with open("/proc/self/net/route") as routes:
for line in routes:
parts = line.split()
if == parts[1]:
hip = parts[2]
if hip is not None and len(hip) is 8:
... | Attempts to read /proc/self/net/route to determine the default gateway in use.
:return: String - the ip address of the default gateway or None if not found/possible/non-existant |
4,740 | def stats (self, antnames):
nbyant = np.zeros (self.nants, dtype=np.int)
sum = np.zeros (self.nants, dtype=np.complex)
sumsq = np.zeros (self.nants)
q = np.abs (self.normvis - 1)
for i in range (self.nsamps):
i1, i2 = self.blidxs[i]
nbyant[i1] +=... | XXX may be out of date. |
4,741 | def _finish_transaction_with_retry(self, command_name, explict_retry):
try:
return self._finish_transaction(command_name, explict_retry)
except ServerSelectionTimeoutError:
raise
except ConnectionFailure as exc:
try:
return se... | Run commit or abort with one retry after any retryable error.
:Parameters:
- `command_name`: Either "commitTransaction" or "abortTransaction".
- `explict_retry`: True when this is an explict commit retry attempt,
ie the application called session.commit_transaction() twice. |
4,742 | def get_label_at_address(self, address, offset = None):
if offset:
address = address + offset
module = self.get_name()
function = None
offset = address - self.get_base()
start = self.get_entry_point()
... | Creates a label from the given memory address.
If the address belongs to the module, the label is made relative to
it's base address.
@type address: int
@param address: Memory address.
@type offset: None or int
@param offset: (Optional) Offset value.
@rtype:... |
4,743 | def computeExpectations(self, A_n, output=, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False, useGeneral = False, state_dependent = False):
dims = len(np.shape(A_n))
N = self.N
K = self.K
if dims == 3:
print("e... | Compute the expectation of an observable of a phase space function.
Compute the expectation of an observable of phase space
function A(x) at all states where potentials are generated,
including states for which no samples were drawn.
We assume observables are not function of the state.... |
4,744 | def _trim_text(text, max_width):
width = get_cwidth(text)
if width > max_width:
if len(text) == width:
trimmed_text = (text[:max(1, max_width-3)] + )[:max_width]
return trimmed_text, len(trimmed_text)
else:
trimmed_text =... | Trim the text to `max_width`, append dots when the text is too long.
Returns (text, width) tuple. |
4,745 | def _close_list(self):
list_type = self.current_parent_element[][]
tag = LIST_TYPES[list_type]
html = .format(
t=tag
)
self.cleaned_html += html
self.current_parent_element[] =
self.current_parent_element[] = {} | Add an close list tag corresponding to the currently open
list found in current_parent_element. |
4,746 | def padding(self, px):
if not isinstance(px, list):
px = [px] * 4
x = max(0, self.x - px[3])
y = max(0, self.y - px[0])
x2 = self.x + self.width + px[1]
y2 = self.y + self.height + px[2]
return Box.from_xy(x, y, x2, y2) | Add padding around four sides of box
:param px: padding value in pixels.
Can be an array in the format of [top right bottom left] or single value.
:return: New padding added box |
4,747 | def prefix_keys(self, prefix, strip_prefix=False):
keys = self.keys(key_from=prefix)
start = 0
if strip_prefix:
start = len(prefix)
for key in keys:
if not key.startswith(prefix):
break
yield key[start:] | Get all keys that begin with ``prefix``.
:param prefix: Lexical prefix for keys to search.
:type prefix: bytes
:param strip_prefix: True to strip the prefix from yielded items.
:type strip_prefix: bool
:yields: All keys in the store that begin with ``prefix``. |
4,748 | def _validate_data(self):
msg = "Error! Expected {} timestamps, found {}.".format(
len(self._data_points), len(self._timestamps))
if len(self._data_points) != len(self._timestamps):
raise MonsoonError(msg) | Verifies that the data points contained in the class are valid. |
4,749 | def list_buckets(self):
method =
url = get_target_url(self._endpoint_url)
headers = {: self._user_agent}
region =
if self._region:
region = self._region
headers = sign_v4(method, url, region,
... | List all buckets owned by the user.
Example:
bucket_list = minio.list_buckets()
for bucket in bucket_list:
print(bucket.name, bucket.created_date)
:return: An iterator of buckets owned by the current user. |
4,750 | def transform_26_27(inst, new_inst, i, n, offset,
instructions, new_asm):
if inst.opname in (, ):
i += 1
assert i < n
assert instructions[i].opname ==
new_inst.offset = offset
new_inst.opname = (
if inst.opname == else
)
... | Change JUMP_IF_FALSE and JUMP_IF_TRUE to
POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE |
4,751 | def needs_confirmation(self):
if EMAIL_CONFIRMATION:
self.is_active = False
self.save()
return True
else:
return False | set is_active to False if needs email confirmation |
4,752 | def init(self, back=None):
back = self.backends(back)
for fsb in back:
fstr = .format(fsb)
if fstr in self.servers:
self.servers[fstr]() | Initialize the backend, only do so if the fs supports an init function |
4,753 | def symbolic_ref(cwd,
ref,
value=None,
opts=,
git_opts=,
user=None,
password=None,
ignore_retcode=False,
output_encoding=None):
FOOfooFOO--delete
cwd = _expand_path(cwd, user)
... | .. versionadded:: 2015.8.0
Interface to `git-symbolic-ref(1)`_
cwd
The path to the git checkout
ref
Symbolic ref to read/modify
value
If passed, then the symbolic ref will be set to this value and an empty
string will be returned.
If not passed, then the ref ... |
4,754 | def setData(self, index, value, role=QtCore.Qt.UserRole):
self._stim.overwriteComponent(value, index.row(), index.column())
self.samplerateChanged.emit(self.samplerate()) | Sets the component at *index* to *value* |
4,755 | def is_venv(directory, executable=):
path=os.path.join(directory, , executable)
return os.path.isfile(path) | :param directory: base directory of python environment |
4,756 | def _plotting(self, rank_metric, results, graph_num, outdir,
format, figsize, pheno_pos=, pheno_neg=):
if self._outdir is None: return
top_term = self.res2d.index[:graph_num]
pool = Pool(self._processes)
for gs in top_term:
... | Plotting API.
:param rank_metric: sorted pd.Series with rankings values.
:param results: self.results
:param data: preprocessed expression table |
4,757 | def _register_plotter(cls, identifier, module, plotter_name,
plotter_cls=None, summary=, prefer_list=False,
default_slice=None, default_dims={},
show_examples=True,
example_call="filename, name=[], ...",
... | Register a plotter for making plots
This class method registeres a plot function for the :class:`Project`
class under the name of the given `identifier`
Parameters
----------
%(Project._register_plotter.parameters)s
Other Parameters
----------------
pre... |
4,758 | def authenticate_user(self, response, **kwargs):
host = urlparse(response.url).hostname
try:
auth_header = self.generate_request_header(response, host)
except KerberosExchangeError:
return response
log.debug("authenticate_user(): Authoriza... | Handles user authentication with gssapi/kerberos |
4,759 | def partition_items(count, bin_size):
num_bins = int(math.ceil(count / float(bin_size)))
bins = [0] * num_bins
for i in range(count):
bins[i % num_bins] += 1
return bins | Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if you only have ten items, you'll have two gr... |
4,760 | def coef(self):
tbl = self._model_json["output"]["coefficients_table"]
if tbl is None:
return None
return {name: coef for name, coef in zip(tbl["names"], tbl["coefficients"])} | Return the coefficients which can be applied to the non-standardized data.
Note: standardize = True by default, if set to False then coef() return the coefficients which are fit directly. |
4,761 | def unified(old, new):
for diff in difflib.ndiff(old.splitlines(), new.splitlines()):
if diff[0] == " ":
yield diff
elif diff[0] == "?":
continue
else:
yield termcolor.colored(diff, "red" if diff[0] == "-" else "green",... | Returns a generator yielding a unified diff between `old` and `new`. |
4,762 | def brozzler_new_job(argv=None):
argv = argv or sys.argv
arg_parser = argparse.ArgumentParser(
prog=os.path.basename(argv[0]),
description=,
formatter_class=BetterArgumentDefaultsHelpFormatter)
arg_parser.add_argument(
, metavar=,
help=)
a... | Command line utility entry point for queuing a new brozzler job. Takes a
yaml brozzler job configuration file, creates job, sites, and pages objects
in rethinkdb, which brozzler-workers will look at and start crawling. |
4,763 | def create_temp_file(self, **mkstemp_kwargs) -> Tuple[int, str]:
kwargs = {**self.default_mkstemp_kwargs, **mkstemp_kwargs}
handle, location = tempfile.mkstemp(**kwargs)
self._temp_files.add(location)
return handle, location | Creates a temp file.
:param mkstemp_kwargs: named arguments to be passed to `tempfile.mkstemp`
:return: tuple where the first element is the file handle and the second is the location of the temp file |
4,764 | def pointlist(points, sr):
assert all(isinstance(pt, Point) or len(pt) == 2
for pt in points), "Point(s) not in [x, y] form"
return [coord if isinstance(coord, Point)
else Point(coord[0], coord[1], sr)
for coord in points] | Convert a list of the form [[x, y] ...] to a list of Point instances
with the given x, y coordinates. |
4,765 | def iter_contributors(self, anon=False, number=-1, etag=None):
url = self._build_url(, base_url=self._api)
params = {}
if anon:
params = {: True}
return self._iter(int(number), url, User, params, etag) | Iterate over the contributors to this repository.
:param bool anon: (optional), True lists anonymous contributors as
well
:param int number: (optional), number of contributors to return.
Default: -1 returns all contributors
:param str etag: (optional), ETag from a previo... |
4,766 | def add(self, child):
if isinstance(child, Case):
self.add_case(child)
else:
raise ModelError() | Adds a typed child object to the conditional derived variable.
@param child: Child object to be added. |
4,767 | def time_delay_from_earth_center(self, right_ascension, declination, t_gps):
return self.time_delay_from_location(np.array([0, 0, 0]),
right_ascension,
declination,
t_g... | Return the time delay from the earth center |
4,768 | def evals_get(self, service_staff_id, start_date, end_date, session):
request = TOPRequest()
request[] = service_staff_id
request[] = start_date
request[] = end_date
self.create(self.execute(request, session))
return self.staff_eval_details | taobao.wangwang.eservice.evals.get 获取评价详细
根据用户id查询用户对应的评价详细情况, 主账号id可以查询店铺内子账号的评价 组管理员可以查询组内账号的评价 非管理员的子账号可以查自己的评价 |
4,769 | def _should_fuzz_node(self, fuzz_node, stage):
if stage == ClientFuzzer.STAGE_ANY:
return True
if fuzz_node.name.lower() == stage.lower():
if self._index_in_path == len(self._fuzz_path) - 1:
return True
else:
return False | The matching stage is either the name of the last node, or ClientFuzzer.STAGE_ANY.
:return: True if we are in the correct model node |
4,770 | def get_state_machine(self):
if self.parent:
if self.is_root_state:
return self.parent
else:
return self.parent.get_state_machine()
return None | Get a reference of the state_machine the state belongs to
:rtype rafcon.core.state_machine.StateMachine
:return: respective state machine |
4,771 | def has_isotropic_cells(self):
return self.is_uniform and np.allclose(self.cell_sides[:-1],
self.cell_sides[1:]) | ``True`` if `grid` is uniform and `cell_sides` are all equal.
Always ``True`` for 1D partitions.
Examples
--------
>>> part = uniform_partition([0, -1], [1, 1], (5, 10))
>>> part.has_isotropic_cells
True
>>> part = uniform_partition([0, -1], [1, 1], (5, 5))
... |
4,772 | def search_google(self, query, *, max_results=100, **kwargs):
response = self._call(
mc_calls.Query,
query,
max_results=max_results,
**kwargs
)
clusters = response.body.get(, [])
results = defaultdict(list)
for cluster in clusters:
result_type = QueryResultType(cluster[][]).name
entri... | Search Google Music for content.
Parameters:
query (str): Search text.
max_results (int, Optional): Maximum number of results per type to retrieve.
Google only accepts values up to 100.
Default: ``100``
kwargs (bool, Optional): Any of ``albums``, ``artists``, ``genres``,
``playlists``, ``podcast... |
4,773 | def _approx_eq_(self, other: Any, atol: float) -> bool:
if not isinstance(other, type(self)):
return NotImplemented
if isinstance(other.value, sympy.Mod):
return self.value == other.value
if self.period != other.period:
ret... | Implementation of `SupportsApproximateEquality` protocol. |
4,774 | def sort(self):
self._matches.sort_values(
by=[constants.SIZE_FIELDNAME, constants.NGRAM_FIELDNAME,
constants.COUNT_FIELDNAME, constants.LABEL_FIELDNAME,
constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME],
ascending=[False, True, False, True, T... | Sorts all results rows.
Sorts by: size (descending), n-gram, count (descending), label,
text name, siglum. |
4,775 | def up(path, service_names=None):
[janus]
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
... | Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specif... |
4,776 | def _run_callback(self, callback):
try:
ret = callback()
if ret is not None:
from . import gen
try:
ret = gen.convert_yielded(ret)
except gen.B... | Runs a callback with error handling.
For use in subclasses. |
4,777 | def extract_single_dist_for_current_platform(self, reqs, dist_key):
distributions = self._resolve_distributions_by_platform(reqs, platforms=[])
try:
matched_dist = assert_single_element(list(
dist
for _, dists in distributions.items()
for dist in dists
if dist.key == d... | Resolve a specific distribution from a set of requirements matching the current platform.
:param list reqs: A list of :class:`PythonRequirement` to resolve.
:param str dist_key: The value of `distribution.key` to match for a `distribution` from the
resolved requirements.
:return: T... |
4,778 | def get_notes():
notes = {:{}, :{}}
notes[][] = 26.370
notes[][] = 31.929
notes[] = 0.500
notes[] = 437.000
notes[] = 35
notes[] = 19*2*12
notes[] = 12.000
notes[] = 26.000
notes[][] = 0.588
notes[][] = 0.612
... | By convention : D is a length of the element, d is a gap |
4,779 | def display_completions_like_readline(event):
b = event.current_buffer
if b.completer is None:
return
complete_event = CompleteEvent(completion_requested=True)
completions = list(b.completer.get_completions(b.document, complete_event))
common_suffix = get_common_complete_suff... | Key binding handler for readline-style tab completion.
This is meant to be as similar as possible to the way how readline displays
completions.
Generate the completions immediately (blocking) and display them above the
prompt in columns.
Usage::
# Call this handler when 'Tab' has been pre... |
4,780 | def wind_shear(shear: str, unit_alt: str = , unit_wind: str = , spoken: bool = False) -> str:
if not shear or not in shear or not in shear:
return
shear = shear[2:].rstrip(unit_wind.upper()).split()
wdir = core.spoken_number(shear[1][:3]) if spoken else shear[1][:3]
return f | Translate wind shear into a readable string
Ex: Wind shear 2000ft from 140 at 30kt |
4,781 | def most_likely_alpha(data, xmin, alpharange=(1.5,3.5), n_alpha=201):
alpha_vector = np.linspace(alpharange[0],alpharange[1],n_alpha)
return alpha_vector[discrete_max_likelihood_arg(data, xmin,
alpharange=alpharange,
... | Return the most likely alpha for the data given an xmin |
4,782 | def output_solution(self, fd, z, z_est, error_sqrsum):
col_width = 11
sep = ("=" * col_width + " ") * 4 + "\n"
fd.write("State Estimation\n")
fd.write("-" * 16 + "\n")
fd.write(sep)
fd.write("Type".center(col_width) + " ")
fd.write("Name".center(col_widt... | Prints comparison of measurements and their estimations. |
4,783 | def get_conversion_factor(self, new_unit):
uo_base, ofactor = self.as_base_units
un_base, nfactor = Unit(new_unit).as_base_units
units_new = sorted(un_base.items(),
key=lambda d: _UNAME2UTYPE[d[0]])
units_old = sorted(uo_base.items(),
... | Returns a conversion factor between this unit and a new unit.
Compound units are supported, but must have the same powers in each
unit type.
Args:
new_unit: The new unit. |
4,784 | def _create_flat_pointers(dct, key_stack=()):
for k in dct.keys():
current_key = key_stack + (k,)
if isinstance(dct[k], BaseMapping):
for flat_ptr in _create_flat_pointers(dct[k], current_key):
yield flat_ptr
else:
yield (current_key, dct, k) | Create a flattened dictionary of "key stacks" -> (value container, key) |
4,785 | async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
res = await self._set(
ns_k... | Stores the value in the given key with ttl if specified
:param key: str
:param value: obj
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory support float ttls
... |
4,786 | def refresh(self):
_logger().log(5, )
self.resize()
self._update(self.editor.contentsRect(), 0,
force_update_margins=True) | Refreshes the editor panels (resize and update margins) |
4,787 | def protein_statistics(self):
d = {}
d[] = self.id
d[] = [x.id for x in self.sequences]
d[] = self.num_sequences
if self.representative_sequence:
d[] = self.representative_sequence.id
d[] = self.representative_sequence.gene_name
... | Get a dictionary of basic statistics describing this protein |
4,788 | def buildElement(element, items, itemName):
def assertNonnegative(i,name):
if i < 0:
raise RuntimeError("Negative value %s reported for %s" %(i,name) )
else:
return float(i)
itemTimes = []
itemClocks = []
itemMemory = []
for item in items:
itemTi... | Create an element for output. |
4,789 | def _import_all_troposphere_modules(self):
dirname = os.path.join(os.path.dirname(__file__))
module_names = [
pkg_name
for importer, pkg_name, is_pkg in
pkgutil.walk_packages([dirname], prefix="troposphere.")
if not is_pkg and pkg_name not in self... | Imports all troposphere modules and returns them |
4,790 | def getFeatureID(self, location):
if not self.contains(location):
return self.EMPTY_FEATURE
return self.SPHERICAL_SURFACE | Returns the feature index associated with the provided location.
In the case of a sphere, it is always the same if the location is valid. |
4,791 | def add_unit(unit,**kwargs):
new_unit = Unit()
new_unit.dimension_id = unit["dimension_id"]
new_unit.name = unit[]
new_unit.abbreviation = unit[]
new_unit.description = unit[]
new_unit.lf = unit[]
new_unit.cf = unit[]
if ( in unit) ... | Add the unit defined into the object "unit" to the DB
If unit["project_id"] is None it means that the unit is global, otherwise is property of a project
If the unit exists emits an exception
A minimal example:
.. code-block:: python
new_unit = dict(
name ... |
4,792 | def calculate_dates(self, dt):
period_end = self.cal.open_and_close_for_session(
self.cal.minute_to_session_label(dt),
)[1]
self._period_end = self.cal.execution_time_from_close(period_end)
self._period_start = self._period_end - self.off... | Given a dt, find that day's close and period start (close - offset). |
4,793 | def get_zone_info(self, controller, zone, return_variable):
_LOGGER.debug("Begin - controller= %s, zone= %s, get status", controller, zone)
resp_msg_signature = self.create_response_signature("04 02 00 @zz 07", zone)
send_msg = self.create_send_message("F0 @... | Get all relevant info for the zone
When called with return_variable == 4, then the function returns a list with current
volume, source and ON/OFF status.
When called with 0, 1 or 2, it will return an integer with the Power, Source and Volume |
4,794 | def expand(self, percentage):
ex_h = math.ceil(self.height * percentage / 100)
ex_w = math.ceil(self.width * percentage / 100)
x = max(0, self.x - ex_w)
y = max(0, self.y - ex_h)
x2 = self.x + self.width + ex_w
y2 = self.y + self.height + ex_h
return Box... | Expands the box co-ordinates by given percentage on four sides. Ignores negative values.
:param percentage: Percentage to expand
:return: New expanded Box |
4,795 | def Offset(self, vtableOffset):
vtable = self.Pos - self.Get(N.SOffsetTFlags, self.Pos)
vtableEnd = self.Get(N.VOffsetTFlags, vtable)
if vtableOffset < vtableEnd:
return self.Get(N.VOffsetTFlags, vtable + vtableOffset)
return 0 | Offset provides access into the Table's vtable.
Deprecated fields are ignored by checking the vtable's length. |
4,796 | def shorter_name(key):
key_short = key
for sep in [, ]:
ind = key_short.rfind(sep)
if ind is not None:
key_short = key_short[ind+1:]
else:
key_short = key_short
return key_short.replace(, ).replace(, ) | Return a shorter name for an id.
Does this by only taking the last part of the URI,
after the last / and the last #. Also replaces - and . with _.
Parameters
----------
key: str
Some URI
Returns
-------
key_short: str
A shortened, but more ambiguous, identifier |
4,797 | def find(self, vid=None, pid=None, serial=None, interface=None, \
path=None, release_number=None, manufacturer=None,
product=None, usage=None, usage_page=None):
result = []
for dev in self.device_list:
if vid not in [0, None] and dev.vendor_id != vid:
... | Attempts to open a device in this `Enumeration` object. Optional
arguments can be provided to filter the resulting list based on various
parameters of the HID devices.
Args:
vid: filters by USB Vendor ID
pid: filters by USB Product ID
serial: filters by USB s... |
4,798 | def derivative(self, point):
r
point = self.domain.element(point)
norm = point.norm()
if norm == 0:
raise ValueError()
return InnerProductOperator(point / norm) | r"""Derivative of this operator in ``point``.
``NormOperator().derivative(y)(x) == (y / y.norm()).inner(x)``
This is only applicable in inner product spaces.
Parameters
----------
point : `domain` `element-like`
Point in which to take the derivative.
R... |
4,799 | def get_next_rngruns(self):
available_runs = [result[][] for result in
self.get_results()]
yield from DatabaseManager.get_next_values(available_runs) | Yield the next RngRun values that can be used in this campaign. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.