Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
344,600 | def crop(self, height, width, center_i=None, center_j=None):
height = int(np.round(height))
width = int(np.round(width))
if center_i is None:
center_i = float(self.height) / 2
if center_j is None:
center_j = float(self.width) / 2
... | Crop the image centered around center_i, center_j.
Parameters
----------
height : int
The height of the desired image.
width : int
The width of the desired image.
center_i : int
The center height point at which to crop. If not specified, the... |
344,601 | def orient_to(self, other, index=None, inplace=False, scaling=False):
arr_self, arr_other = self._get_samples_shared_with(other, index=index)
if scaling:
raise NotImplementedError()
else:
self_mean = arr_self.mean(axis=0)
other_mean = arr_other.mean... | Orient this Projection to another dataset.
Orient this projection using reflection, rotation and translation to
match another projection using procrustes superimposition. Scaling is
optional.
Args:
other
(:py:class:`pymds.Projection` or :py:class:`pandas.Dat... |
344,602 | def _pwl1_to_poly(self, generators):
for g in generators:
if (g.pcost_model == PW_LINEAR) and (len(g.p_cost) == 2):
g.pwl_to_poly()
return generators | Converts single-block piecewise-linear costs into linear
polynomial. |
344,603 | def get_jobs_to_queue(self, with_times=False):
return self.get_jobs(to_unix(datetime.utcnow()), with_times=with_times) | Returns a list of job instances that should be queued
(score lower than current timestamp).
If with_times is True a list of tuples consisting of the job instance and
it's scheduled execution time is returned. |
344,604 | def getVentRequiredEnabled(self):
command =
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0004) | Returns True if enabled, False if disabled |
344,605 | def kde_gauss(events_x, events_y, xout=None, yout=None):
valid_combi = ((xout is None and yout is None) or
(xout is not None and yout is not None)
)
if not valid_combi:
raise ValueError("Both `xout` and `yout` must be (un)set.")
if yout is None and yout is... | Gaussian Kernel Density Estimation
Parameters
----------
events_x, events_y: 1D ndarray
The input points for kernel density estimation. Input
is flattened automatically.
xout, yout: ndarray
The coordinates at which the KDE should be computed.
If set to none, input coordi... |
344,606 | def connect_delete_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs):
kwargs[] = True
if kwargs.get():
return self.connect_delete_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs)
else:
(data) = self.connec... | connect DELETE requests to proxy of Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_service_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thr... |
344,607 | def sorteditems(self, multi=False):
for key in sorted(dict.keys(self)):
if multi:
for value in self.getlist(key):
yield key, value
else:
yield key, self[key] | Return an iterator of ``(key, value)`` pairs, sorted by key.
:param multi: If set to `True` the iterator returned will have a pair
for each value of each key. Otherwise it will only
contain pairs for the lasted added of each key. |
344,608 | def get_static(self, _, file_name=None):
content_type = {
: ,
: ,
}.get(file_name[-2:])
if not content_type:
raise HttpError(HTTPStatus.NOT_FOUND, 42)
return HttpResponse(self.load_static(file_name), headers={
: content_type,
... | Get static content for UI. |
344,609 | def chown(self, path, user=, group=):
_complain_ifclosed(self.closed)
return self.fs.chown(path, user, group) | Change file owner and group.
:type path: str
:param path: the path to the file or directory
:type user: str
:param user: Hadoop username. Set to '' if only setting group
:type group: str
:param group: Hadoop group name. Set to '' if only setting user
:raises: :ex... |
344,610 | def deregister(self, event, fn):
if event in self._handler_dict and fn in self._handler_dict[event]:
self._handler_dict[event].remove(fn) | Deregister the handler function from the given event. |
344,611 | def bend_miter(angle, Di=None, Re=None, roughness=0.0, L_unimpeded=None,
method=):
rRennelsCraneMillerBlevinsCraneMillerBlevinsRennelsMillerCraneBlevinsMiller
if method is None:
method =
if method == :
angle_rad = radians(angle)
sin_half_angle = sin(angle_rad*0.5)
... | r'''Returns loss coefficient for any single-joint miter bend in a pipe
of angle `angle`, diameter `Di`, Reynolds number `Re`, roughness
`roughness` unimpeded downstream length `L_unimpeded`, and using the
specified method. This calculation has four methods available.
The 'Rennels' method is based on a ... |
344,612 | def update_nodes(nodes,**kwargs):
user_id = kwargs.get()
updated_nodes = []
for n in nodes:
updated_node_i = update_node(n, flush=False, user_id=user_id)
updated_nodes.append(updated_node_i)
db.DBSession.flush()
return updated_nodes | Update multiple nodes.
If new attributes are present, they will be added to the node.
The non-presence of attributes does not remove them.
%TODO:merge this with the 'update_nodes' functionality in the 'update_netework'
function, so we're not duplicating functionality. D.R.Y!
returns: a list of upd... |
344,613 | def random_connection(self):
yield random.choice(
[conn for conn in self.connections() if conn.alive()]) | Pick a random living connection |
344,614 | def _get_all_containing(self, containing_contigs, name, exclude=None, max_depth=10):
contains_name = set()
if max_depth < 0:
return contains_name
if name in containing_contigs:
for containing_contig in containing_contigs[name]:
... | containing_contigs is a dict:
key=contig name. Value = set of contigs that contain the key.
Returns alls contigs called "name" that contain that contig |
344,615 | def write_assoc(self, assoc):
if assoc.get("header", False):
return
subj = assoc[]
db, db_object_id = self._split_prefix(subj)
rel = assoc[]
qualifier = rel[]
if assoc[]:
qualifier = + qualifier
goid = assoc[][]
ev = ... | Write a single association to a line in the output file |
344,616 | def cl_mutect(self, params, tmp_dir):
gatk_jar = self._get_jar("muTect", ["mutect"])
jvm_opts = config_utils.adjust_opts(self._jvm_opts,
{"algorithm": {"memory_adjust":
{"magnitude": ... | Define parameters to run the mutect paired algorithm. |
344,617 | def get(self, deviceUid, eventId):
if not isinstance(deviceUid, DeviceUid) and isinstance(deviceUid, dict):
deviceUid = DeviceUid(**deviceUid)
url = "api/v0002/device/types/%s/devices/%s/events/%s" % (deviceUid.typeId, deviceUid.deviceId, eventId)
r = self._apiClient.get(u... | Retrieves the last cached message for specified event from a specific device. |
344,618 | def _nix_collect_garbage():
nixhome = os.path.join(os.path.expanduser(.format(__opts__[])), )
return [os.path.join(nixhome, )] | Make sure we get the right nix-store, too. |
344,619 | def up(self,x,L_change = 12):
y = L_change*ssd.upsample(x,L_change)
y = signal.lfilter(self.b,[1],y)
return y | Upsample and filter the signal |
344,620 | def _load_start_paths(self):
" Start the Read-Eval-Print Loop. "
if self._startup_paths:
for path in self._startup_paths:
if os.path.exists(path):
with open(path, ) as f:
code = compile(f.read(), path, )
six.... | Start the Read-Eval-Print Loop. |
344,621 | def shift(self, count=1):
if self:
self._index = (self._index + count) % len(self)
else:
self._index = 0 | Shift the view a specified number of times.
:param count: The count of times to shift the view. |
344,622 | def build_schema(schema: Schema) -> Mapping[str, Any]:
builder = Schemas(build_parameter=build_parameter)
return builder.build(schema) | Build JSON schema from a marshmallow schema. |
344,623 | def and_return_result_of(self, return_value):
if not check_func_takes_args(return_value):
self._return_value = lambda *args, **kwargs: return_value()
else:
self._return_value = return_value
return self | Causes the double to return the result of calling the provided value.
:param return_value: A callable that will be invoked to determine the double's return value.
:type return_value: any callable object |
344,624 | def main():
log.setup_main_logger(console=True, file_logging=False)
log.log_sockeye_version(logger)
params = argparse.ArgumentParser(description="Rerank nbest lists of translations."
" Reranking sorts a list of hypotheses according"
... | Commandline interface to rerank nbest lists. |
344,625 | def get_comments_by_book(self, book_id):
mgr = self._get_provider_manager(, local=True)
lookup_session = mgr.get_comment_lookup_session_for_book(book_id, proxy=self._proxy)
lookup_session.use_isolated_book_view()
return lookup_session.get_comments() | Gets the list of ``Comments`` associated with a ``Book``.
arg: book_id (osid.id.Id): ``Id`` of a ``Book``
return: (osid.commenting.CommentList) - list of related comments
raise: NotFound - ``book_id`` is not found
raise: NullArgument - ``book_id`` is ``null``
raise: Operat... |
344,626 | def system_with_timeout(i):
import subprocess
import time
cmd=i[]
rc=0
to=i.get(,)
p=subprocess.Popen(cmd, shell=True)
if to != :
xto=float(to)
t0=time.time()
t=0
tx=float(i[])
while p.poll() == None and t<xto:
time.sleep(0.1)
... | Input: {
cmd - command line
(timeout) - timeout in seconds (granularity 0.01 sec) - may cause overheads ...
}
Output: {
return - return code = 0, if successful
> 0, if error
... |
344,627 | def close(self):
if self._subprocess is not None:
os.killpg(self._subprocess.pid, signal.SIGTERM)
self._subprocess = None | Close child subprocess |
344,628 | def get_color_data(self, condition):
if condition not in self.color_icons:
condition_lc = condition.lower()
if in condition_lc or in condition_lc:
if in condition_lc:
condition =
else:
condi... | Disambiguate similarly-named weather conditions, and return the icon
and color that match. |
344,629 | def retry(*dargs, **dkw):
if len(dargs) == 1 and callable(dargs[0]):
def wrap_simple(f):
@six.wraps(f)
def wrapped_f(*args, **kw):
return Retrying().call(f, *args, **kw)
return wrapped_f
return wrap_simple(dargs[0])
else:
... | Decorator function that instantiates the Retrying object
@param *dargs: positional arguments passed to Retrying object
@param **dkw: keyword arguments passed to the Retrying object |
344,630 | def map(self, f, preservesPartitioning=False):
return (
self
.mapPartitions(lambda p: (f(e) for e in p), preservesPartitioning)
.transform(lambda rdd:
rdd.setName(.format(rdd.prev.name(), f)))
) | Apply function f
:param f: mapping function
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2], [7]])
... |
344,631 | def is_break_tag(self, el):
name = el.name
return name in self.break_tags or name in self.user_break_tags | Check if tag is an element we should break on. |
344,632 | def formatDuration(self, duration):
days = duration.days
hours, remainder = divmod(duration.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
if days:
return .format(days, "s" if days > 1 else "",
hours, minutes,... | Format the duration.
This method could be overridden if really needed, as the duration format in gerrit
is an arbitrary string.
:param duration: duration in timedelta |
344,633 | def trigger_update(self, trigger_parent=True):
if not self.update_model() or (hasattr(self, "_in_init_") and self._in_init_):
return
self._trigger_params_changed(trigger_parent) | Update the model from the current state.
Make sure that updates are on, otherwise this
method will do nothing
:param bool trigger_parent: Whether to trigger the parent, after self has updated |
344,634 | def cat(f=None, o=None):
if f is None or o is None:
return
target = o
infiles = asiterable(f)
logger.debug("cat {0!s} > {1!s} ".format(" ".join(infiles), target))
with open(target, ) as out:
rc = subprocess.call([] + infiles, stdout=out)
if rc != 0:
msg = "faile... | Concatenate files *f*=[...] and write to *o* |
344,635 | def _read_as_int(self, addr, numBytes):
buf = self.read_register(addr, numBytes)
if len(buf) >= 4:
return struct.unpack_from("<i", buf)[0]
else:
rtn = 0
for i, byte in enumerate(buf):
rtn |= byte << 8 * i
return rtn | Convenience method. Oftentimes we need to read a range of
registers to represent an int. This method will automatically read
@numBytes registers starting at @addr and convert the array into an int. |
344,636 | def bound_symbols(self):
try:
lhs_syms = self.lhs.bound_symbols
except AttributeError:
lhs_syms = set()
try:
rhs_syms = self.rhs.bound_symbols
except AttributeError:
rhs_syms = set()
return lhs_syms | rhs_syms | Set of bound SymPy symbols contained within the equation. |
344,637 | def read_fits_region(filename, errors=):
regions = []
hdul = fits.open(filename)
for hdu in hdul:
if hdu.name == :
table = Table.read(hdu)
wcs = WCS(hdu.header, keysel=[, , ])
regions_list = FITSRegionParser(table, errors).shapes.to_regions()
fo... | Reads a FITS region file and scans for any fits regions table and
converts them into `Region` objects.
Parameters
----------
filename : str
The file path
errors : ``warn``, ``ignore``, ``strict``
The error handling scheme to use for handling parsing errors.
The default is 'stric... |
344,638 | def _create_filter_dsl(urlkwargs, definitions):
filters = []
for name, filter_factory in definitions.items():
values = request.values.getlist(name, type=text_type)
if values:
filters.append(filter_factory(values))
for v in values:
urlkwargs.add(name, ... | Create a filter DSL expression. |
344,639 | def Receive(self, replytype, **kw):
self.ReceiveSOAP(**kw)
ps = self.ps
tp = _find_type(ps.body_root)
isarray = ((type(tp) in (tuple,list) and tp[1] == ) or _find_arraytype(ps.body_root))
if self.typesmodule is None or isarray:
return _Binding.Receive(self, ... | Parse message, create Python object.
KeyWord data:
faults -- list of WSDL operation.fault typecodes
wsaction -- If using WS-Address, must specify Action value we expect to
receive. |
344,640 | def setup(self):
neb_dirs = self.neb_dirs
if self.backup:
for f in VASP_NEB_INPUT_FILES:
shutil.copy(f, "{}.orig".format(f))
for path in neb_dirs:
poscar = os.path.join(path, "POSCAR")
shutil.copy... | Performs initial setup for VaspNEBJob, including overriding any settings
and backing up. |
344,641 | def cmd_line(line, ctrl):
clients = ctrl.modules
if line == "update start":
for client in clients:
client.updating_start()
elif line == "update stop":
for client in clients:
client.updating_stop()
return line | :type: list[WrapperClient] |
344,642 | def find_autosummary_in_files(filenames):
documented = []
for filename in filenames:
f = open(filename, )
lines = f.read().splitlines()
documented.extend(find_autosummary_in_lines(lines, filename=filename))
f.close()
return documented | Find out what items are documented in source/*.rst.
See `find_autosummary_in_lines`. |
344,643 | def generate_mediation_matrix(dsm):
cat = dsm.categories
ent = dsm.entities
size = dsm.size[0]
if not cat:
cat = [] * size
packages = [e.split()[0] for e in ent]
mediation_matrix = [[0 for _ in range(size)]
for ... | Generate the mediation matrix of the given matrix.
Rules for mediation matrix generation:
Set -1 for items NOT to be considered
Set 0 for items which MUST NOT be present
Set 1 for items which MUST be present
Each module has optional dependencies to itself.
- Framework... |
344,644 | def display_context(doc):
from rowgenerators.exceptions import DownloadError
context = {s.name.lower(): s.as_dict() for s in doc if s.name.lower() != }
mandatory_sections = [, ]
deletes = []
for k,v in context.items():
try:
del v[]
except KeyError:... | Create a Jinja context for display |
344,645 | def set_title(self, s, delay_draw=False):
"set plot title"
self.conf.relabel(title=s, delay_draw=delay_draw) | set plot title |
344,646 | def find_config(test_file=None, defaults=None, root=os.curdir):
if defaults is None:
defaults = [".benchbuild.yml", ".benchbuild.yaml"]
def walk_rec(cur_path, root):
cur_path = local.path(root) / test_file
if cur_path.exists():
return cur_path
new_root = local.... | Find the path to the default config file.
We look at :root: for the :default: config file. If we can't find it
there we start looking at the parent directory recursively until we
find a file named :default: and return the absolute path to it.
If we can't find anything, we return None.
Args:
... |
344,647 | def overall_state_id(self):
overall_state = 0
if not self.monitored:
overall_state = 5
elif self.acknowledged:
overall_state = 1
elif self.downtimed:
overall_state = 2
elif self.state_type == :
if self.state == :
... | Get the service overall state.
The service overall state identifier is the service status including:
- the monitored state
- the acknowledged state
- the downtime state
The overall state is (prioritized):
- a service is not monitored (5)
- a service critical or ... |
344,648 | def indexFromItem(self, regItem, col=0):
sourceIndex = self.sourceModel().indexFromItem(regItem, col=col)
return self.mapFromSource(sourceIndex) | Gets the index (with column=0) for the row that contains the regItem
If col is negative, it is counted from the end |
344,649 | def _open_debug_interface(self, conn_id, callback, connection_string=None):
self._try_connect(connection_string)
callback(conn_id, self.id, True, None) | Enable debug interface for this IOTile device
Args:
conn_id (int): the unique identifier for the connection
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reason) |
344,650 | def precision(truth, recommend, k=None):
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k) | Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k. |
344,651 | def show_generic_keywords(self, layer):
keywords = KeywordIO(layer)
self.print_button.setEnabled(False)
try:
message = keywords.to_message()
send_static_message(self, message)
except InvalidMessageItemError:
pass
self.show... | Show the keywords defined for the active layer.
.. note:: The print button will be disabled if this method is called.
.. versionchanged:: 3.3 - changed parameter from keywords object
to a layer object so that we can show extra stuff like CRS and
data source in the keywords.
... |
344,652 | def _merge_slowly(self, other_trajectory, rename_dict):
for other_key in rename_dict:
new_key = rename_dict[other_key]
other_instance = other_trajectory.f_get(other_key)
if other_instance.f_is_empty():
with self._nn_interface._disab... | Merges trajectories by loading iteratively items of the other trajectory and
store it into the current trajectory.
:param rename_dict:
Dictionary containing mappings from the old result names in the `other_trajectory`
to the new names in the current trajectory. |
344,653 | def param_str(self, param, s):
param.pair = (self.value(s).strip(), str)
return True | Parse a str in parameter list |
344,654 | def insert(self,
entity_id,
property_uri,
value):
if not entity_id.startswith("http"):
entity_uri = urllib.parse.urljoin(self.base_url, entity_id)
else:
entity_uri = entity_id
if entity_uri.endswith("/"):
e... | Method inserts a new entity's property in Fedora4 Repository
Args:
entity_id(string): Unique ID of Fedora object
property_uri(string): URI of property
value: Value of the property, can be literal or URI reference
Returns:
boolean: True if successful chan... |
344,655 | def show_absolute_url(context, page, lang=None):
if not lang:
lang = context.get(, pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if not page:
return {: }
url = page.get_url_path(language=lang)
if url:
return {: url}
return {: } | Show the url of a page in the right language
Example ::
{% show_absolute_url page_object %}
You can also use the slug of a page::
{% show_absolute_url "my-page-slug" %}
Keyword arguments:
:param page: the page object, slug or id
:param lang: the wanted language \
(defaul... |
344,656 | def restart(self, hard=False, timeout=30, force=True):
body = dict()
body[] = {
: if hard else ,
: .format(timeout),
: if force else
}
path = .format(self.uuid)
self.cloud_manager.post_request(path, body)
object.__setattr__... | Restart the server. By default, issue a soft restart with a timeout of 30s
and a hard restart after the timeout.
After the a timeout a hard restart is performed if the server has not stopped.
Note: API responds immediately (unlike in start), with state: started.
This client will, howev... |
344,657 | def _beyond_unit_bound(self, loglstar):
if self.logl_first_update is None:
return loglstar >= self.logl_first_update | Check whether we should update our bound beyond the initial
unit cube. |
344,658 | def _set_ldp_rcv_label_silence_time(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={: []}, int_size=32), restriction_dict={: [u]}), default=RestrictedClassType(base_ty... | Setter method for ldp_rcv_label_silence_time, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/ldp/ldp_holder/ldp_rcv_label_silence_time (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_rcv_label_silence_time is considered as a private
method. ... |
344,659 | def _get_titles(self, limit):
raw = .join((self.rawdir, self.files[][]))
model = Model(self.graph)
col = [, , , ]
with open(raw, , encoding=) as csvfile:
filereader = csv.reader(csvfile, delimiter=, quotechar=)
header = next(filereader)
heade... | The file processed here is of the format:
#NBK_id GR_shortname OMIM
NBK1103 trimethylaminuria 136132
NBK1103 trimethylaminuria 602079
NBK1104 cdls 122470
Where each of the rows represents a mapping between
a gr id and an omim id. These are a 1:many relat... |
344,660 | def explain(self, entry):
d = self.get_explanation_dict(entry)
print("The uncorrected value of the energy of %s is %f eV" %
(entry.composition, d["uncorrected_energy"]))
print("The following corrections / screening are applied for %s:\n" %
d["compatibility"])... | Prints an explanation of the corrections that are being applied for a
given compatibility scheme. Inspired by the "explain" methods in many
database methodologies.
Args:
entry: A ComputedEntry. |
344,661 | def quality_comparator(video_data):
def parse_resolution(res: str) -> Tuple[int, ...]:
return tuple(map(int, res.split()))
raw_resolution = video_data[]
resolution = parse_resolution(raw_resolution)
return resolution | Custom comparator used to choose the right format based on the resolution. |
344,662 | def plot(self, figsize=None, rotation=45):
fig, ax = plt.subplots(figsize=figsize)
plt.imshow(self._cm, interpolation=, cmap=plt.cm.Blues, aspect=)
plt.title()
plt.colorbar()
tick_marks = np.arange(len(self._labels))
plt.xticks(tick_marks, self._labels, rotation=rotation)
plt.yticks(t... | Plot the confusion matrix.
Args:
figsize: tuple (x, y) of ints. Sets the size of the figure
rotation: the rotation angle of the labels on the x-axis. |
344,663 | def swaggerize_response(response, op):
response_spec = get_response_spec(response.status_int, op)
bravado_core.response.validate_response(
response_spec, op, PyramidSwaggerResponse(response)) | Delegate handling the Swagger concerns of the response to bravado-core.
:type response: :class:`pyramid.response.Response`
:type op: :class:`bravado_core.operation.Operation` |
344,664 | def _jit_update_fun(predict_fun, loss_fun, optimizer, lr_fun, num_devices):
if num_devices == 1:
def single_update(i, opt_state, batch, rng):
rng, subrng = jax_random.split(rng[0])
_, opt_update = optimizer(lr_fun)
params = trax_opt.get_params(opt_state)
return opt_update(i, backend.g... | Get jit-ed update function for loss, optimizer, learning rate function. |
344,665 | def pyminify(options, files):
global name_generator
if not is_iterable(files):
print(
"Error: The argument must be a list, tuple, etc of files. "
"Strings and bytes wont do anything else
prepend = None
if options.prepend:
try:
prepend = ope... | Given an *options* object (from `optparse.OptionParser` or similar),
performs minification and/or obfuscation on the given *files* (any iterable
containing file paths) based on said *options*.
All accepted options can be listed by running ``python __main__.py -h`` or
examining the :py:func:`__init__.ma... |
344,666 | def fetch_group_cached(group_id, failures=True, wait=0, count=None, broker=None):
if not broker:
broker = get_broker()
start = time()
if count:
while True:
if count_group_cached(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0:
break
... | Return a list of Tasks for a task group in the cache backend |
344,667 | def write(self, data):
if self.padded:
if len(self._bits) > 0:
self._flush_bits_to_stream()
self._stream.write(data)
else:
if len(data) == 0:
return
bits = bytes_to_bits(data)
... | Write data to the stream
:data: the data to write to the stream
:returns: None |
344,668 | def Process(self, request, context):
LOG.debug("Process called")
try:
metrics = self.plugin.process(
[Metric(pb=m) for m in request.Metrics],
ConfigMap(pb=request.Config)
)
return MetricsReply(metrics=[m.pb for m in metrics])
... | Dispatches the request to the plugins process method |
344,669 | def high_low(data, channels=None, high=None, low=None, full_output=False):
if channels is None:
data_ch = data
else:
data_ch = data[:,channels]
if data_ch.ndim == 1:
data_ch = data_ch.reshape((-1,1))
if high is None:
if hasattr(data_ch, ):
... | Gate out high and low values across all specified channels.
Gate out events in `data` with values in the specified channels which
are larger than or equal to `high` or less than or equal to `low`.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the nu... |
344,670 | def verbose_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS,
packet_size=PACKET_SIZE, path_finder=False):
signal.signal(signal.SIGINT, signal_handler)
if hasattr(signal, "SIGBREAK"):
signal.signal(signal.SIGBREAK, signal_handler)
myStats = MyStats()
m... | Send >count< ping to >destIP< with the given >timeout< and display
the result. |
344,671 | def pack_command(self, *args):
command = args[0]
if in command:
args = tuple([Token(s) for s in command.split()]) + args[1:]
else:
args = (Token(command),) + args[1:]
args_output = SYM_EMPTY.join([
... | Pack a series of arguments into a value SSDB command |
344,672 | def resize(self, newWidth = 0, newHeight = 0):
self.height = newHeight
self.width = newWidth | !
\~english
Resize width and height of rectangles
@param newWidth: new width value
@param newHeight: new height value
\~chinese
重新设定矩形高宽
@param newWidth: 新宽度
@param newHeight: 新高度 |
344,673 | def _cookiecutter_configs_have_changed(template, old_version, new_version):
temple.check.is_git_ssh_path(template)
repo_path = temple.utils.get_repo_path(template)
github_client = temple.utils.GithubClient()
api = .format(repo_path)
old_config_resp = github_client.get(api, params={: old_versio... | Given an old version and new version, check if the cookiecutter.json files have changed
When the cookiecutter.json files change, it means the user will need to be prompted for
new context
Args:
template (str): The git SSH path to the template
old_version (str): The git SHA of the old versi... |
344,674 | def update(self, series_list):
if not series_list:
self.series_notebook.AddPage(wx.Panel(self, -1), _("+"))
return
self.updating = True
self.series_notebook.DeleteAllPages()
for page, attrdict in enumerate(series_list):
... | Updates widget content from series_list
Parameters
----------
series_list: List of dict
\tList of dicts with data from all series |
344,675 | def listing(self):
"Return a list of filename entries currently in the archive"
return [.join([f,ext]) if ext else f for (f,ext) in self._files.keys()] | Return a list of filename entries currently in the archive |
344,676 | def create_table(self, data, table_name, error_if_exists = False, **kwargs):
t insert anything.You passed no sample values, or all the values you passed were null.IF NOT EXISTS
CREATE TABLE %s %s (
%s %s
);' % (if_not_exists, quote(table_name), quote(k), get_column_type(startdata[k])... | Create a table based on the data, but don\'t insert anything. |
344,677 | def setup_data(self):
data = self.data
if len(data) == 0:
return type(data)()
data = self.geom.setup_data(data)
check_required_aesthetics(
self.geom.REQUIRED_AES,
set(data.columns) | set(self.geom.aes_params),
self.geom.__class__... | Prepare/modify data for plotting |
344,678 | def sonify(annotation, sr=22050, duration=None, **kwargs):
length = None
if duration is None:
duration = annotation.duration
if duration is not None:
length = int(duration * sr)
if annotation.namespace in SONIFY_MAPPING:
ann = coerce_annotation(annotation, annotatio... | Sonify a jams annotation through mir_eval
Parameters
----------
annotation : jams.Annotation
The annotation to sonify
sr = : positive number
The sampling rate of the output waveform
duration : float (optional)
Optional length (in seconds) of the output waveform
kwargs... |
344,679 | def get_recurring_bill_by_client(self, *, customer_id, date_begin=None, date_final=None):
params = {
"customerId": customer_id,
}
if date_begin and date_final:
params[] = date_begin.strftime()
params[] = date_final.strftime()
return self.clien... | Consulta de las facturas que están pagadas o pendientes por pagar. Se puede consultar por cliente,
por suscripción o por rango de fechas.
Args:
customer_id:
date_begin:
date_final:
Returns: |
344,680 | def serialize_b58(self, private=True):
return ensure_str(
base58.b58encode_check(unhexlify(self.serialize(private)))) | Encode the serialized node in base58. |
344,681 | def ip_in_subnet(ip, subnet):
ipaddr = int(.join([ % int(x) for x in ip.split()]), 16)
netstr, bits = subnet.split()
netaddr = int(.join([ % int(x) for x in netstr.split()]), 16)
mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
return (ipaddr & mask) == (netaddr & mask) | Does IP exists in a given subnet utility. Returns a boolean |
344,682 | def _get_tough_method(self, method):
def tough_method(*args, **kwargs):
transaction = self._transaction
if not transaction:
try:
if not self._con.db.status:
raise AttributeError
if self._maxusage: ... | Return a "tough" version of a connection class method.
The tough version checks whether the connection is bad (lost)
and automatically and transparently tries to reset the connection
if this is the case (for instance, the database has been restarted). |
344,683 | def gcd2(a, b):
while a:
a, b = b%a, a
return b | Greatest common divisor using Euclid's algorithm. |
344,684 | def resize(image, width=None, height=None, crop=False, namespace="resized"):
return resize_lazy(image=image, width=width, height=height, crop=crop,
namespace=namespace, as_url=True) | Returns the url of the resized image |
344,685 | def generate(env):
link.generate(env)
env[] =
env[] =
env[] =
env[] = env[] +
env[] = SCons.Util.CLVar()
env[] = env[] +
env[] =
env[] =
env[] = SCons.Util.CLVar()
env[] = | Add Builders and construction variables for applelink to an
Environment. |
344,686 | def key(self) -> Tuple[int, int]:
return self._source.index, self._target.index | The unique identifier of the edge consisting of the indexes of its
source and target nodes. |
344,687 | def get_space_system(self, name):
url = .format(self._instance, name)
response = self._client.get_proto(url)
message = mdb_pb2.SpaceSystemInfo()
message.ParseFromString(response.content)
return SpaceSystem(message) | Gets a single space system by its unique name.
:param str name: A fully-qualified XTCE name
:rtype: .SpaceSystem |
344,688 | def generate_submit_array(templates, directories, **kwargs):
dirname = kwargs.setdefault(, os.path.curdir)
reldirs = [relpath(p, start=dirname) for p in asiterable(directories)]
missing = [p for p in (os.path.join(dirname, subdir) for subdir in reldirs)
if not os.path.exists(p)]
if l... | Generate a array job.
For each ``work_dir`` in *directories*, the array job will
1. cd into ``work_dir``
2. run the job as detailed in the template
It will use all the queuing system directives found in the
template. If more complicated set ups are required, then this
function cannot be used.... |
344,689 | def previous(task):
params = task.get_params()
previous_params = {}
previous_date_params = {}
for param_name, param_obj in params:
param_value = getattr(task, param_name)
if isinstance(param_obj, parameter.DateParameter):
previous_date_params[param_name] = param_value ... | Return a previous Task of the same family.
By default checks if this task family only has one non-global parameter and if
it is a DateParameter, DateHourParameter or DateIntervalParameter in which case
it returns with the time decremented by 1 (hour, day or interval) |
344,690 | def convert_string_value_to_type_value(string_value, data_type):
from ast import literal_eval
try:
if data_type in (str, type(None)):
converted_value = str(string_value)
elif data_type == int:
converted_value = int(string_value)
elif data_type == float:
... | Helper function to convert a given string to a given data type
:param str string_value: the string to convert
:param type data_type: the target data type
:return: the converted value |
344,691 | def iter_descendants_labels(self, ontology, iri, size=None, sleep=None):
for label in _help_iterate_labels(self.iter_descendants(ontology, iri, size=size, sleep=sleep)):
yield label | Iterates over the labels for the descendants of a given term
:param str ontology: The name of the ontology
:param str iri: The IRI of a term
:param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI.
:param int sleep: The amount of time to sleep be... |
344,692 | def dump(self):
reading = self.reading
if reading is not None:
reading = reading.asdict()
return {
u: str(self.selector),
u: reading
} | Serialize the state of this stream walker.
Returns:
dict: The serialized state. |
344,693 | def sampleset(self):
x1, x4 = self.bounding_box
dw = self.width * 0.5
x2 = self.x_0 - dw
x3 = self.x_0 + dw
if self._n_models == 1:
w = [x1, x2, x3, x4]
else:
w = list(zip(x1, x2, x3, x4))
return np.asarray(w) | Return ``x`` array that samples the feature. |
344,694 | def location_autosuggest(self, **params):
service_url = "{url}/{params_path}".format(
url=self.LOCATION_AUTOSUGGEST_URL,
params_path=self._construct_params(
params, self.LOCATION_AUTOSUGGEST_PARAMS)
)
return self.make_request(
service_... | Location Autosuggest Services
Doc URLs:
http://business.skyscanner.net/portal/en-GB/
Documentation/Autosuggest
http://business.skyscanner.net/portal/en-GB/
Documentation/CarHireAutoSuggest
http://business.skyscanner.net/portal/en-GB/
Doc... |
344,695 | def _parse_impute2_line(self, line):
row = line.rstrip("\r\n").split(" ")
prob = np.array(row[5:], dtype=float)
prob.shape = (prob.shape[0] // 3, 3)
dosage = 2 * prob[:, 2] + prob[:, 1]
if self.prob_t > 0:
dosage[~np.any(prob >= s... | Parses the current IMPUTE2 line (a single variant).
Args:
line (str): An IMPUTE2 line.
Returns:
Genotypes: The genotype in dosage format.
Warning
=======
By default, the genotypes object has multiallelic set to False. |
344,696 | def _cookie_expiration(self):
value = (datetime.datetime.utcnow() +
datetime.timedelta(seconds=self._session_duration))
LOGGER.debug(, value.isoformat())
return value | Return the expiration timestamp for the session cookie.
:rtype: datetime |
344,697 | def _verified_frame_length(frame_length, content_type):
if content_type == ContentType.FRAMED_DATA and frame_length > MAX_FRAME_SIZE:
raise SerializationError(
"Specified frame length larger than allowed maximum: {found} > {max}".format(
found=frame_length, max=MAX_FRAM... | Verify a frame length value for a message content type.
:param int frame_length: Frame length to verify
:param ContentType content_type: Message content type to verify against
:return: frame length
:rtype: int
:raises SerializationError: if frame length is too large
:raises SerializationError: ... |
344,698 | def determine_extended_chord6(chord, shorthand=False, no_inversions=False,
no_polychords=False):
if len(chord) != 6:
return False
def inversion_exhauster(
chord,
shorthand,
tries,
result,
polychords,
):
if ... | Determine the names of an 6 note chord. |
344,699 | def get_sortobj(self, goea_results, **kws):
nts_goea = MgrNtGOEAs(goea_results).get_goea_nts_prt(**kws)
goids = set(nt.GO for nt in nts_goea)
go2nt = {nt.GO:nt for nt in nts_goea}
grprobj = Grouper("GOEA", goids, self.hdrobj, self.grprdflt.gosubdag, go2nt=go2nt)
grprobj.... | Return a Grouper object, given a list of GOEnrichmentRecord. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.