code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def key_release_event(self, event):
self.example.key_event(event.key(), self.keys.ACTION_RELEASE) | Process Qt key release events forwarding them to the example |
def guest_inspect_stats(self, userid_list):
if not isinstance(userid_list, list):
userid_list = [userid_list]
action = "get the statistics of guest '%s'" % str(userid_list)
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._monitor.inspect_stats(userid_list... | Get the statistics including cpu and mem of the guests
:param userid_list: a single userid string or a list of guest userids
:returns: dictionary describing the cpu statistics of the vm
in the form {'UID1':
{
'guest_cpus': xx,
'use... |
def set_metadata(self, metadata: MetaData) -> None:
self._parent.set_metadata(metadata)
self._child.set_metadata(metadata) | Sets the metadata for the parent and child tables. |
def tryload(self, cfgstr=None):
if cfgstr is None:
cfgstr = self.cfgstr
if cfgstr is None:
import warnings
warnings.warn('No cfgstr given in Cacher constructor or call')
cfgstr = ''
if not self.enabled:
if self.verbose > 0:
... | Like load, but returns None if the load fails |
def create_app(applet_id, applet_name, src_dir, publish=False, set_default=False, billTo=None, try_versions=None,
try_update=True, confirm=True, regional_options=None):
return _create_app(dict(applet=applet_id), applet_name, src_dir, publish=publish, set_default=set_default,
bi... | Creates a new app object from the specified applet.
.. deprecated:: 0.204.0
Use :func:`create_app_multi_region()` instead. |
def vertices(self):
if self._v_out is None:
output = qhalf('Fp', self.halfspaces, self.interior_point)
pts = []
for l in output[2:]:
pt = []
for c in l.split():
c = float(c)
if c != 10.101 and c != -10.10... | Returns the vertices of the halfspace intersection |
def add_vlan_to_interface(self, interface, vlan_id):
subif = '%s.%s' % (interface, vlan_id)
vlan_id = '%s' % vlan_id
cmd = ['ip', 'link', 'add', 'link', interface, 'name',
subif, 'type', 'vlan', 'id', vlan_id]
stdcode, stdout = agent_utils.execute(cmd, root=True)
i... | Add vlan interface.
ip link add link eth0 name eth0.10 type vlan id 10 |
def _sync_with_file(self):
self._records = []
i = -1
for i, line in self._enum_lines():
self._records.append(None)
self._last_synced_index = i | Clear in-memory structures so table is synced with the file. |
def verify(self):
if self._lock != 0:
return
id_new = self._id_function()
if id_new != self.id_current:
if len(self.cache) > 0:
log.debug('%d items cleared from cache: %s',
len(self.cache),
str(list(self.... | Verify that the cached values are still for the same
value of id_function and delete all stored items if
the value of id_function has changed. |
def _get_authentication_from_public_key_id(self, key_id):
for authentication in self._authentications:
if authentication.is_key_id(key_id):
return authentication
return None | Return the authentication based on it's id. |
def _HandleLegacy(self, args, token=None):
hunt_urn = args.hunt_id.ToURN()
hunt_obj = aff4.FACTORY.Open(
hunt_urn, aff4_type=implementation.GRRHunt, token=token)
clients_by_status = hunt_obj.GetClientsByStatus()
hunt_clients = clients_by_status[args.client_status.name]
total_count = len(hunt... | Retrieves the clients for a hunt. |
def ecg_find_peaks(signal, sampling_rate=1000):
rpeaks, = biosppy.ecg.hamilton_segmenter(np.array(signal), sampling_rate=sampling_rate)
rpeaks, = biosppy.ecg.correct_rpeaks(signal=np.array(signal), rpeaks=rpeaks, sampling_rate=sampling_rate, tol=0.05)
return(rpeaks) | Find R peaks indices on the ECG channel.
Parameters
----------
signal : list or ndarray
ECG signal (preferably filtered).
sampling_rate : int
Sampling rate (samples/second).
Returns
----------
rpeaks : list
List of R-peaks location indices.
Example
-------... |
def find_one(self, tname, where=None, where_not=None, columns=None, astype=None):
records = self.find(tname, where=where, where_not=where_not, columns=columns,
astype='dataframe')
return self._output(records, single=True, astype=astype) | Find a single record in the provided table from the database. If multiple match, return
the first one based on the internal order of the records. If no records are found, return
empty dictionary, string or series depending on the value of `astype`.
Parameters
----------
tname : ... |
def save_nk_object(obj, filename="file", path="", extension="nk", compress=False, compatibility=-1):
if compress is True:
with gzip.open(path + filename + "." + extension, 'wb') as name:
pickle.dump(obj, name, protocol=compatibility)
else:
with open(path + filename + "." + extension,... | Save whatever python object to a pickled file.
Parameters
----------
file : object
Whatever python thing (list, dict, ...).
filename : str
File's name.
path : str
File's path.
extension : str
File's extension. Default "nk" but can be whatever.
compress: bool
... |
def getAttributeName(self, index):
offset = self._get_attribute_offset(index)
name = self.m_attributes[offset + const.ATTRIBUTE_IX_NAME]
res = self.sb[name]
if not res:
attr = self.m_resourceIDs[name]
if attr in public.SYSTEM_RESOURCES['attributes']['inverse']:
... | Returns the String which represents the attribute name |
def add_swagger(app, json_route, html_route, **kwargs):
spec = getattr(app, SWAGGER_ATTR_NAME)
if spec:
spec = spec.swagger_definition(**kwargs)
else:
spec = {}
encoded_spec = json.dumps(spec).encode("UTF-8")
@app.route(json_route)
def swagger():
return Response(
... | add a swagger html page, and a swagger.json generated
from the routes added to the app. |
async def unmount(self):
self._data = await self._handler.unmount(
system_id=self.node.system_id, id=self.id) | Unmount this block device. |
def fit(self, X, y=None):
self.transformer_list = list(self.transformer_list)
self._validate_transformers()
with Pool(self.n_jobs) as pool:
transformers = pool.starmap(_fit_one_transformer,
((trans, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X, y)... | Fit all transformers using X.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data, used to fit transformers.
y : array-like, shape (n_samples, ...), optional
Targets for supervised learning.
Returns
-------
... |
def _get_attribute_tensors(onnx_model_proto):
for node in onnx_model_proto.graph.node:
for attribute in node.attribute:
if attribute.HasField("t"):
yield attribute.t
for tensor in attribute.tensors:
yield tensor | Create an iterator of tensors from node attributes of an ONNX model. |
def fix_size(self, content):
if content:
width, height = self.get_item_size(content)
parent = self.parent()
relative_width = parent.geometry().width() * 0.65
if relative_width > self.MAX_WIDTH:
relative_width = self.MAX_WIDTH
self.list.... | Adjusts the width and height of the file switcher
based on the relative size of the parent and content. |
def _get_record(self):
if not self.pk:
raise AJAXError(400, _('Invalid request for record.'))
try:
return self.model.objects.get(pk=self.pk)
except self.model.DoesNotExist:
raise AJAXError(404, _('%s with id of "%s" not found.') % (
self.model.... | Fetch a given record.
Handles fetching a record from the database along with throwing an
appropriate instance of ``AJAXError`. |
def register_tile(self, hw_type, api_major, api_minor, name, fw_major, fw_minor, fw_patch, exec_major, exec_minor, exec_patch, slot, unique_id):
api_info = (api_major, api_minor)
fw_info = (fw_major, fw_minor, fw_patch)
exec_info = (exec_major, exec_minor, exec_patch)
address = 10 + slot... | Register a tile with this controller.
This function adds the tile immediately to its internal cache of registered tiles
and queues RPCs to send all config variables and start tile rpcs back to the tile. |
def _construct(self):
self._acyclic_cfg = self._cfg.copy()
self._pre_process_cfg()
self._pd_construct()
self._graph = networkx.DiGraph()
rdf = compute_dominance_frontier(self._normalized_cfg, self._post_dom)
for y in self._cfg.graph.nodes():
if y not in rdf:
... | Construct a control dependence graph.
This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment
Form by Ron Cytron, etc. |
def exception(self, s):
self.error(s)
type, value, tb = sys.exc_info()
self.writelines(traceback.format_stack(), 1)
self.writelines(traceback.format_tb(tb)[1:], 1)
self.writelines(traceback.format_exception_only(type, value), 1) | Write error message with traceback info. |
def authenticated_session(username, password):
session = requests.Session()
session.headers.update(headers())
response = session.get(url())
login_path = path(response.text)
login_url = urljoin(response.url, login_path)
login_post_data = post_data(response.text, username, password)
response =... | Given username and password, return an authenticated Yahoo `requests`
session that can be used for further scraping requests.
Throw an AuthencationError if authentication fails. |
def _get_data_from_csv_files(self):
all_df = []
for file_name in self._input_csv_files:
with _util.open_local_or_gcs(file_name, mode='r') as f:
all_df.append(pd.read_csv(f, names=self._headers))
df = pd.concat(all_df, ignore_index=True)
return df | Get data from input csv files. |
def set_windows_env_var(key, value):
if not isinstance(key, text_type):
raise TypeError("%r not of type %r" % (key, text_type))
if not isinstance(value, text_type):
raise TypeError("%r not of type %r" % (value, text_type))
status = winapi.SetEnvironmentVariableW(key, value)
if status == ... | Set an env var.
Raises:
WindowsError |
def assign_role(backend, user, response, *args, **kwargs):
if backend.name is 'passthrough' and settings.DEMO is True and 'role' in kwargs['request'].session[passthrough.SESSION_VAR]:
role = kwargs['request'].session[passthrough.SESSION_VAR]['role']
if role == 'tutor':
make_tutor(user)
... | Part of the Python Social Auth Pipeline.
Checks if the created demo user should be pushed into some group. |
def _callback_new_block(self, latest_block: Dict):
with self.event_poll_lock:
latest_block_number = latest_block['number']
confirmed_block_number = max(
GENESIS_BLOCK_NUMBER,
latest_block_number - self.config['blockchain']['confirmation_blocks'],
... | Called once a new block is detected by the alarm task.
Note:
This should be called only once per block, otherwise there will be
duplicated `Block` state changes in the log.
Therefore this method should be called only once a new block is
mined with the correspond... |
def left_sections(self):
lines = self.text.split('\n')
sections = 0
for i in range(len(lines)):
if lines[i].startswith('+'):
sections += 1
sections -= 1
return sections | The number of sections that touch the left side.
During merging, the cell's text will grow to include other
cells. This property keeps track of the number of sections that
are touching the left side. For example::
+-----+-----+
section --> | foo | dog | <-- ... |
def get_vdp_failure_reason(self, reply):
try:
fail_reason = reply.partition(
"filter")[0].replace('\t', '').split('\n')[-2]
if len(fail_reason) == 0:
fail_reason = vdp_const.retrieve_failure_reason % (reply)
except Exception:
fail_reaso... | Parse the failure reason from VDP. |
def similarity(self, other):
if self.magnitude == 0 or other.magnitude == 0:
return 0
return self.dot(other) / self.magnitude | Calculates the cosine similarity between this vector and another
vector. |
def updateEditorGeometry(self, editor, option, index):
cti = index.model().getItem(index)
if cti.checkState is None:
displayRect = option.rect
else:
checkBoxRect = widgetSubCheckBoxRect(editor, option)
offset = checkBoxRect.x() + checkBoxRect.width()
... | Ensures that the editor is displayed correctly with respect to the item view. |
def compute_path(self, start_x, start_y, dest_x, dest_y,
diagonal_cost=_math.sqrt(2)):
return tcod.path.AStar(self, diagonal_cost).get_path(start_x, start_y,
dest_x, dest_y) | Get the shortest path between two points.
Args:
start_x (int): Starting x-position.
start_y (int): Starting y-position.
dest_x (int): Destination x-position.
dest_y (int): Destination y-position.
diagonal_cost (float): Multiplier for diagonal movement... |
def term_from_uri(uri):
if uri is None:
return None
if isinstance(uri, rdflib.Literal):
uri = str(uri.toPython())
patterns = ['http://www.openbel.org/bel/namespace//(.*)',
'http://www.openbel.org/vocabulary//(.*)',
'http://www.openbel.org/bel//(.*)',
... | Removes prepended URI information from terms. |
def _find_flats_edges(self, data, mag, direction):
i12 = np.arange(data.size).reshape(data.shape)
flat = mag == FLAT_ID_INT
flats, n = spndi.label(flat, structure=FLATS_KERNEL3)
objs = spndi.find_objects(flats)
f = flat.ravel()
d = data.ravel()
for i, _obj in enum... | Extend flats 1 square downstream
Flats on the downstream side of the flat might find a valid angle,
but that doesn't mean that it's a correct angle. We have to find
these and then set them equal to a flat |
def validate_valid_transition(enum, from_value, to_value):
validate_available_choice(enum, to_value)
if hasattr(enum, '_transitions') and not enum.is_valid_transition(from_value, to_value):
message = _(six.text_type('{enum} can not go from "{from_value}" to "{to_value}"'))
raise InvalidStatusOpe... | Validate that to_value is a valid choice and that to_value is a valid transition from from_value. |
def login(self):
_LOGGER.debug("Attempting to login to ZoneMinder")
login_post = {'view': 'console', 'action': 'login'}
if self._username:
login_post['username'] = self._username
if self._password:
login_post['password'] = self._password
req = requests.pos... | Login to the ZoneMinder API. |
def packets_to_flows(self):
for packet in self.input_stream:
flow_id = flow_utils.flow_tuple(packet)
self._flows[flow_id].add_packet(packet)
for flow in list(self._flows.values()):
if flow.ready():
flow_info = flow.get_flow()
... | Combine packets into flows |
def _new_device_id(self, key):
device_id = Id.SERVER + 1
if key in self._key2deviceId:
return self._key2deviceId[key]
while device_id in self._clients:
device_id += 1
return device_id | Generate a new device id or return existing device id for key
:param key: Key for device
:type key: unicode
:return: The device id
:rtype: int |
def plot(args):
from jcvi.graphics.base import savefig
p = OptionParser(plot.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="8x7", format="png")
if len(args) != 3:
sys.exit(not p.print_help())
workdir, sample_key, chrs = args
chrs = chrs.split(",")
hmm = CopyNumberHMM... | %prog plot workdir sample chr1,chr2
Plot some chromosomes for visual proof. Separate multiple chromosomes with
comma. Must contain folder workdir/sample-cn/. |
def psisloo(log_lik, **kwargs):
r
kwargs['overwrite_lw'] = True
lw = -log_lik
lw, ks = psislw(lw, **kwargs)
lw += log_lik
loos = sumlogs(lw, axis=0)
loo = loos.sum()
return loo, loos, ks | r"""PSIS leave-one-out log predictive densities.
Computes the log predictive densities given posterior samples of the log
likelihood terms :math:`p(y_i|\theta^s)` in input parameter `log_lik`.
Returns a sum of the leave-one-out log predictive densities `loo`,
individual leave-one-out log predictive den... |
def _verify_barycentric(lambda1, lambda2, lambda3):
weights_total = lambda1 + lambda2 + lambda3
if not np.allclose(weights_total, 1.0, atol=0.0):
raise ValueError(
"Weights do not sum to 1", lambda1, lambda2, lambda3
)
if lambda1 < 0.0 or lambda2 < 0.0 or ... | Verifies that weights are barycentric and on the reference triangle.
I.e., checks that they sum to one and are all non-negative.
Args:
lambda1 (float): Parameter along the reference triangle.
lambda2 (float): Parameter along the reference triangle.
lambda3 (float): ... |
def main(host='localhost', port=8086):
user = 'root'
password = 'root'
dbname = 'demo'
protocol = 'json'
client = DataFrameClient(host, port, user, password, dbname)
print("Create pandas DataFrame")
df = pd.DataFrame(data=list(range(30)),
index=pd.date_range(start='2014... | Instantiate the connection to the InfluxDB client. |
def _display_stream(normalized_data, stream):
try:
stream.write(normalized_data['stream'])
except UnicodeEncodeError:
stream.write(normalized_data['stream'].encode("utf-8")) | print stream message from docker-py stream. |
def create_ospf_area_with_message_digest_auth():
OSPFKeyChain.create(name='secure-keychain',
key_chain_entry=[{'key': 'fookey',
'key_id': 10,
'send_key': True}])
key_chain = OSPFKeyChain('secure-keychain'... | If you require message-digest authentication for your OSPFArea, you must
create an OSPF key chain configuration. |
def mnist(training):
if training:
data_filename = 'train-images-idx3-ubyte.gz'
labels_filename = 'train-labels-idx1-ubyte.gz'
count = 60000
else:
data_filename = 't10k-images-idx3-ubyte.gz'
labels_filename = 't10k-labels-idx1-ubyte.gz'
count = 10000
data_filename = maybe_download(MNIST_URL... | Downloads MNIST and loads it into numpy arrays. |
def _init_formats(self):
theme = self._color_scheme
fmt = QtGui.QTextCharFormat()
fmt.setForeground(theme.foreground)
fmt.setBackground(theme.background)
self._formats[OutputFormat.NormalMessageFormat] = fmt
fmt = QtGui.QTextCharFormat()
fmt.setForeground(theme.er... | Initialise default formats. |
def _do_denormalize (version_tuple):
version_parts_list = []
for parts_tuple in itertools.imap(None,*([iter(version_tuple)]*4)):
version_part = ''.join(fn(x) for fn, x in
zip(_denormalize_fn_list, parts_tuple))
if version_part:
version_parts_list.append... | separate action function to allow for the memoize decorator. Lists,
the most common thing passed in to the 'denormalize' below are not hashable. |
def _par_vector2dict(v, pars, dims, starts=None):
if starts is None:
starts = _calc_starts(dims)
d = OrderedDict()
for i in range(len(pars)):
l = int(np.prod(dims[i]))
start = starts[i]
end = start + l
y = np.asarray(v[start:end])
if len(dims[i]) > 1:
... | Turn a vector of samples into an OrderedDict according to param dims.
Parameters
----------
y : list of int or float
pars : list of str
parameter names
dims : list of list of int
list of dimensions of parameters
Returns
-------
d : dict
Examples
--------
>>... |
def set_off(self):
try:
request = requests.post(
'{}/{}/{}/'.format(self.resource, URI, self._mac),
data={'action': 'off'}, timeout=self.timeout)
if request.status_code == 200:
pass
except requests.exceptions.ConnectionError:
... | Turn the bulb off. |
def get_operator_output_port(self):
return OperatorOutputPort(self.rest_client.make_request(self.operatorOutputPort), self.rest_client) | Get the output port of this exported stream.
Returns:
OperatorOutputPort: Output port of this exported stream. |
def simple_write(self, s, frame, node=None):
self.start_write(frame, node)
self.write(s)
self.end_write(frame) | Simple shortcut for start_write + write + end_write. |
def write_array(self, obj):
classdesc = obj.get_class()
self._writeStruct(">B", 1, (self.TC_ARRAY,))
self.write_classdesc(classdesc)
self._writeStruct(">i", 1, (len(obj),))
self.references.append(obj)
logging.debug(
"*** Adding ref 0x%X for array []",
... | Writes a JavaArray
:param obj: A JavaArray object |
def get_base_branch():
base_branch = git.guess_base_branch()
if base_branch is None:
log.info("Can't guess the base branch, you have to pick one yourself:")
base_branch = choose_branch()
return base_branch | Return the base branch for the current branch.
This function will first try to guess the base branch and if it can't it
will let the user choose the branch from the list of all local branches.
Returns:
str: The name of the branch the current branch is based on. |
def run(command, verbose=False):
def do_nothing(*args, **kwargs):
return None
v_print = print if verbose else do_nothing
p = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
)
v_print("ru... | Run a shell command. Capture the stdout and stderr as a single stream.
Capture the status code.
If verbose=True, then print command and the output to the terminal as it
comes in. |
def _clear_stats(self):
for stat in (STAT_BYTES_RECEIVED,
STAT_BYTES_SENT,
STAT_MSG_RECEIVED,
STAT_MSG_SENT,
STAT_CLIENTS_MAXIMUM,
STAT_CLIENTS_CONNECTED,
STAT_CLIENTS_DISCONNECTED,
... | Initializes broker statistics data structures |
def discovery_mqtt(self):
self.context.install_bundle("pelix.remote.discovery.mqtt").start()
with use_waiting_list(self.context) as ipopo:
ipopo.add(
rs.FACTORY_DISCOVERY_MQTT,
"pelix-discovery-mqtt",
{
"application.id": "sa... | Installs the MQTT discovery bundles and instantiates components |
def first(self, callback=None, default=None):
if callback is not None:
for val in self.items:
if callback(val):
return val
return value(default)
if len(self.items) > 0:
return self.items[0]
else:
return default | Get the first item of the collection.
:param default: The default value
:type default: mixed |
def remove_user_from_group(uid, gid):
acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid))
try:
r = http.delete(acl_url)
assert r.status_code == 204
except dcos.errors.DCOSBadRequest:
pass | Removes a user from a group within DCOS Enterprise.
:param uid: user id
:type uid: str
:param gid: group id
:type gid: str |
def from_dict(cls, arr_dict, dtype=None, fillna=False, **kwargs):
if dtype is None:
names = sorted(list(arr_dict.keys()))
else:
dtype = np.dtype(dtype)
dt_names = [f for f in dtype.names]
dict_names = [k for k in arr_dict.keys()]
missing_names ... | Generate a table from a dictionary of arrays. |
def primary_key(self, hkey, rkey=None):
if isinstance(hkey, dict):
def decode(val):
if isinstance(val, Decimal):
return float(val)
return val
pkey = {self.hash_key.name: decode(hkey[self.hash_key.name])}
if self.range_key is... | Construct a primary key dictionary
You can either pass in a (hash_key[, range_key]) as the arguments, or
you may pass in an Item itself |
def data_from_techshop_ws(tws_url):
r = requests.get(tws_url)
if r.status_code == 200:
data = BeautifulSoup(r.text, "lxml")
else:
data = "There was an error while accessing data on techshop.ws."
return data | Scrapes data from techshop.ws. |
def create(self, name, plugin_name, hadoop_version, description=None,
cluster_configs=None, node_groups=None, anti_affinity=None,
net_id=None, default_image_id=None, use_autoconfig=None,
shares=None, is_public=None, is_protected=None,
domain_name=None):
... | Create a Cluster Template. |
def find_config(revision):
if not is_git_repo():
return None
cfg_path = f"{revision}:.cherry_picker.toml"
cmd = "git", "cat-file", "-t", cfg_path
try:
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
path_type = output.strip().decode("utf-8")
return cfg_pat... | Locate and return the default config for current revison. |
def process_result_value(self, value, dialect):
if value is not None:
with BytesIO(value) as stream:
with GzipFile(fileobj=stream, mode="rb") as file_handle:
value = json.loads(file_handle.read().decode("utf-8"))
return value | Convert a JSON encoded string to a dictionary structure. |
def _get_librato(ret=None):
_options = _get_options(ret)
conn = librato.connect(
_options.get('email'),
_options.get('api_token'),
sanitizer=librato.sanitize_metric_name,
hostname=_options.get('api_url'))
log.info("Connected to librato.")
return conn | Return a Librato connection object. |
def tensor_kraus_maps(k1, k2):
return [np.kron(k1j, k2l) for k1j in k1 for k2l in k2] | Generate the Kraus map corresponding to the composition
of two maps on different qubits.
:param list k1: The Kraus operators for the first qubit.
:param list k2: The Kraus operators for the second qubit.
:return: A list of tensored Kraus operators. |
def close(self):
self.out_stream.close()
if self.in_place:
shutil.move(self.temp_file.name, self.out) | Close the stream. Assumes stream has 'close' method. |
def unix_word_rubout(event, WORD=True):
buff = event.current_buffer
pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD)
if pos is None:
pos = - buff.cursor_position
if pos:
deleted = buff.delete_before_cursor(count=-pos)
if event.is_repeat:
del... | Kill the word behind point, using whitespace as a word boundary.
Usually bound to ControlW. |
def minimise(routing_table, target_length):
table, _ = ordered_covering(routing_table, target_length, no_raise=True)
return remove_default_routes(table, target_length) | Reduce the size of a routing table by merging together entries where
possible and by removing any remaining default routes.
.. warning::
The input routing table *must* also include entries which could be
removed and replaced by default routing.
.. warning::
It is assumed that the... |
def register_scf_task(self, *args, **kwargs):
kwargs["task_class"] = ScfTask
return self.register_task(*args, **kwargs) | Register a Scf task. |
def intersection(self, other):
ivs = set()
shorter, longer = sorted([self, other], key=len)
for iv in shorter:
if iv in longer:
ivs.add(iv)
return IntervalTree(ivs) | Returns a new tree of all intervals common to both self and
other. |
def _find_logs(self, compile_workunit):
for idx, workunit in enumerate(compile_workunit.children):
for output_name, outpath in workunit.output_paths().items():
if output_name in ('stdout', 'stderr'):
yield idx, workunit.name, output_name, outpath | Finds all logs under the given workunit. |
def SetUpperTimestamp(cls, timestamp):
if not hasattr(cls, '_upper'):
cls._upper = timestamp
return
if timestamp > cls._upper:
cls._upper = timestamp | Sets the upper bound timestamp. |
def reset_all(self):
for item in self.inputs:
setattr(self, "_%s" % item, None)
self.stack = [] | Resets all parameters to None |
def run_zone(self, minutes, zone=None):
if zone is None:
zone_cmd = 'runall'
relay_id = None
else:
if zone < 0 or zone > (len(self.relays) - 1):
return None
else:
zone_cmd = 'run'
relay_id = self.relays[zone]... | Run or stop a zone or all zones for an amount of time.
:param minutes: The number of minutes to run.
:type minutes: int
:param zone: The zone number to run. If no zone is specified then run
all zones.
:type zone: int or None
:returns: The response from set_z... |
def viewbox_key_event(self, event):
PerspectiveCamera.viewbox_key_event(self, event)
if event.handled or not self.interactive:
return
if not self._timer.running:
self._timer.start()
if event.key in self._keymap:
val_dims = self._keymap[event.key]
... | ViewBox key event handler
Parameters
----------
event : instance of Event
The event. |
def base_path(self):
path = self.request.path
base_path = path[:path.rfind("/")]
if not base_path.endswith("/command"):
raise BadRequestPathError(
"Json handlers should have /command path prefix")
return base_path[:base_path.rfind("/")] | Base path for all mapreduce-related urls.
JSON handlers are mapped to /base_path/command/command_name thus they
require special treatment.
Raises:
BadRequestPathError: if the path does not end with "/command".
Returns:
The base path. |
def encode (self):
byte = self.default
for bit, name, value0, value1, default in SeqCmdAttrs.Table:
if name in self.attrs:
value = self.attrs[name]
byte = setBit(byte, bit, value == value1)
return struct.pack('B', byte) | Encodes this SeqCmdAttrs to binary and returns a bytearray. |
def qt_at_least(needed_version, test_version=None):
major, minor, patch = needed_version.split('.')
needed_version = '0x0%s0%s0%s' % (major, minor, patch)
needed_version = int(needed_version, 0)
installed_version = Qt.QT_VERSION
if test_version is not None:
installed_version = test_version
... | Check if the installed Qt version is greater than the requested
:param needed_version: minimally needed Qt version in format like 4.8.4
:type needed_version: str
:param test_version: Qt version as returned from Qt.QT_VERSION. As in
0x040100 This is used only for tests
:type test_version: int
... |
def depth_first(problem, graph_search=False, viewer=None):
return _search(problem,
LifoList(),
graph_search=graph_search,
viewer=viewer) | Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. |
def get_permissions_for_registration(self):
qs = Permission.objects.none()
for instance in self.modeladmin_instances:
qs = qs | instance.get_permissions_for_registration()
return qs | Utilised by Wagtail's 'register_permissions' hook to allow permissions
for a all models grouped by this class to be assigned to Groups in
settings. |
def send_mail(to_list, sub, content, cc=None):
sender = SMTP_CFG['name'] + "<" + SMTP_CFG['user'] + ">"
msg = MIMEText(content, _subtype='html', _charset='utf-8')
msg['Subject'] = sub
msg['From'] = sender
msg['To'] = ";".join(to_list)
if cc:
msg['cc'] = ';'.join(cc)
try:
smtp... | Sending email via Python. |
def flush(self):
if self._num_outstanding_events == 0 or self._recordio_writer is None:
return
self._recordio_writer.flush()
if self._logger is not None:
self._logger.info('wrote %d %s to disk', self._num_outstanding_events,
'event' if self._... | Flushes the event file to disk. |
def _datetime_to_millis(dtm):
if dtm.utcoffset() is not None:
dtm = dtm - dtm.utcoffset()
return int(calendar.timegm(dtm.timetuple()) * 1000 +
dtm.microsecond // 1000) | Convert datetime to milliseconds since epoch UTC. |
def remove_all_timers(self):
with self.lock:
if self.rtimer is not None:
self.rtimer.cancel()
self.timers = {}
self.heap = []
self.rtimer = None
self.expiring = False | Remove all waiting timers and terminate any blocking threads. |
def make_tophat_ei (lower, upper):
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not np.isfinite (upper):
raise ValueError ('"upper" argument must be finite number; got %r' % upper)
def range_tophat_ei (x):
x = np.asarray (... | Return a ufunc-like tophat function on the defined range, left-exclusive
and right-inclusive. Returns 1 if lower < x <= upper, 0 otherwise. |
def pctile(self,pct,res=1000):
grid = np.linspace(self.minval,self.maxval,res)
return grid[np.argmin(np.absolute(pct-self.cdf(grid)))] | Returns the desired percentile of the distribution.
Will only work if properly normalized. Designed to mimic
the `ppf` method of the `scipy.stats` random variate objects.
Works by gridding the CDF at a given resolution and matching the nearest
point. NB, this is of course not as preci... |
async def fetch_wallet_search_next_records(wallet_handle: int,
wallet_search_handle: int,
count: int) -> str:
logger = logging.getLogger(__name__)
logger.debug("fetch_wallet_search_next_records: >>> wallet_handle: %r, wallet_s... | Fetch next records for wallet search.
:param wallet_handle: wallet handler (created by open_wallet).
:param wallet_search_handle: wallet wallet handle (created by open_wallet_search)
:param count: Count of records to fetch
:return: wallet records json:
{
totalCount: <str>, // present only i... |
def find_type(cls, val):
mt = ""
index = val.rfind(".")
if index == -1:
val = "fake.{}".format(val)
elif index == 0:
val = "fake{}".format(val)
mt = mimetypes.guess_type(val)[0]
if mt is None:
mt = ""
return mt | return the mimetype from the given string value
if value is a path, then the extension will be found, if val is an extension then
that will be used to find the mimetype |
def split(self, amount):
split_objs = list(self.all())
if not split_objs:
raise NoSplitsFoundForRecurringCost()
portions = [split_obj.portion for split_obj in split_objs]
split_amounts = ratio_split(amount, portions)
return [
(split_objs[i], split_amount)
... | Split the value given by amount according to the RecurringCostSplit's portions
Args:
amount (Decimal):
Returns:
list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decimal) |
def needs_label(model_field, field_name):
default_label = field_name.replace('_', ' ').capitalize()
return capfirst(model_field.verbose_name) != default_label | Returns `True` if the label based on the model's verbose name
is not equal to the default label it would have based on it's field name. |
def usearch61_chimera_check_denovo(abundance_fp,
uchime_denovo_fp,
minlen=64,
output_dir=".",
remove_usearch_logs=False,
uchime_denovo_log_fp="uc... | Does de novo, abundance based chimera checking with usearch61
abundance_fp: input consensus fasta file with abundance information for
each cluster.
uchime_denovo_fp: output uchime file for chimera results.
minlen: minimum sequence length for usearch input fasta seqs.
output_dir: output directory
... |
def parse_feed(content):
feed = feedparser.parse(content)
articles = []
for entry in feed['entries']:
article = {
'title': entry['title'],
'link': entry['link']
}
try:
article['media'] = entry['media_content'][0]... | utility function to parse feed |
def read_bytes(self):
global exit_flag
for self.i in range(0, self.length) :
self.bytes[self.i] = i_max[self.i]
self.maxbytes[self.i] = total_chunks[self.i]
self.progress[self.i]["maximum"] = total_chunks[self.i]
self.progress[self.i]["value"] = self.bytes[self.i]
self.str[self.i].set(file_name[self.... | reading bytes; update progress bar after 1 ms |
def textMD5(text):
m = hash_md5()
if isinstance(text, str):
m.update(text.encode())
else:
m.update(text)
return m.hexdigest() | Get md5 of a piece of text |
def get_contour(mask):
if isinstance(mask, np.ndarray) and len(mask.shape) == 2:
mask = [mask]
ret_list = False
else:
ret_list = True
contours = []
for mi in mask:
c0 = find_contours(mi.transpose(),
level=.9999,
positi... | Compute the image contour from a mask
The contour is computed in a very inefficient way using scikit-image
and a conversion of float coordinates to pixel coordinates.
Parameters
----------
mask: binary ndarray of shape (M,N) or (K,M,N)
The mask outlining the pixel positions of the event.
... |
def count(self):
"The number of items, pruned or otherwise, contained by this branch."
if getattr(self, '_count', None) is None:
self._count = getattr(self.node, 'count', 0)
return self._count | The number of items, pruned or otherwise, contained by this branch. |
def disconnect(self):
if self.connected:
self._socket.close()
self._socket = None
self.connected = False | Disconnect from deluge |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.