text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def main():
"""Main entry point for Glances.
Select the mode (standalone, client or server)
Run it...
"""
# Catch the CTRL-C signal
signal.signal(signal.SIGINT, __signal_handler)
# Log Glances and psutil version
logger.info('Start Glances {}'.format(__version__))
logger.info('{} {}... | 0.001397 |
def connect_to(self, joint, other_body, offset=(0, 0, 0), other_offset=(0, 0, 0),
**kwargs):
'''Move another body next to this one and join them together.
This method will move the ``other_body`` so that the anchor points for
the joint coincide. It then creates a joint to fas... | 0.003771 |
def _make_tuple(x):
"""TF has an obnoxious habit of being lenient with single vs tuple."""
if isinstance(x, prettytensor.PrettyTensor):
if x.is_sequence():
return tuple(x.sequence)
else:
return (x.tensor,)
elif isinstance(x, tuple):
return x
elif (isinstance(x, collections.Sequence) and
... | 0.01956 |
def marquee(txt='',width=78,mark='*'):
"""Return the input string centered in a 'marquee'.
:Examples:
In [16]: marquee('A test',40)
Out[16]: '**************** A test ****************'
In [17]: marquee('A test',40,'-')
Out[17]: '---------------- A test ----------------'
... | 0.011419 |
def _send_long(self,value):
"""
Convert a numerical value into an integer, then to a bytes object. Check
bounds for signed long.
"""
# Coerce to int. This will throw a ValueError if the value can't
# actually be converted.
if type(value) != int:
new_... | 0.013547 |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
ttype = args['ttype']
(targets_yaml, sim) = NAME_FACTORY.resolve_targetfile(
args, require_sim_name=True)
if targets_yaml is None:
return job_configs
... | 0.001078 |
def prepare_to_run(self, clock, period_count):
"""
Prepare the activity for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be... | 0.00161 |
def list_servers(self, nicknames=None):
"""
Iterate through the servers of the server group with the specified
nicknames, or the single server with the specified nickname, and yield
a `ServerDefinition` object for each server.
nicknames may be: None, string defining a nickname o... | 0.001546 |
def _gen_sample(self):
"""Generate a random captcha image sample
Returns
-------
(numpy.ndarray, str)
Tuple of image (numpy ndarray) and character string of digits used to generate the image
"""
num_str = self.get_rand(self.num_digit_min, self.num_digit_max)
... | 0.008108 |
def initialize_major_angle(self):
"""
Computes the major angle: 2pi radians / number of groups.
"""
num_groups = len(self.nodes.keys())
self.major_angle = 2 * np.pi / num_groups | 0.009217 |
def triangle_iteration(start, dim, stop=None):
"""
>>> list(triangle_iteration(1, 1, stop=3))
[(1,), (2,), (3,)]
>>> list(triangle_iteration(1, 2, stop=3))
[(1, 1), (1, 2), (2, 1), (1, 3), (3, 1), (2, 2)]
>>> list(triangle_iteration(1, 0, stop=3))
[]
"""
if not dim:
return
... | 0.001418 |
async def load_json_or_yaml_from_url(context, url, path, overwrite=True):
"""Retry a json/yaml file download, load it, then return its data.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to download
path (str): the path to download to
... | 0.001111 |
def _determine_notification_info(notification_arn,
notification_arn_from_pillar,
notification_types,
notification_types_from_pillar):
'''
helper method for present. ensure that notification_configs are set
''... | 0.002463 |
def text_index(self):
'''Returns the one-based index of the current text node.'''
# This is the number of text nodes we've seen so far.
# If we are currently in a text node, great; if not then add
# one for the text node that's about to begin.
i = self.tags.get(TextElement, 0)
... | 0.005025 |
def _read_newick_from_string(nw, root_node, matcher, formatcode):
""" Reads a newick string in the New Hampshire format. """
if nw.count('(') != nw.count(')'):
raise NewickError('Parentheses do not match. Broken tree structure?')
# white spaces and separators are removed
nw = re.sub("[\n\r\t]+"... | 0.005955 |
def created(self, data, schema=None, envelope=None):
"""
Gets a 201 response with the specified data.
:param data: The content value.
:param schema: The schema to serialize the data.
:param envelope: The key used to envelope the data.
:return: A Flask response object.
... | 0.004695 |
def get_calendars(self, calendar_id=None, body=None, params=None):
"""
`<>`_
:arg calendar_id: The ID of the calendar to fetch
:arg body: The from and size parameters optionally sent in the body
:arg from_: skips a number of calendars
:arg size: specifies a max number of... | 0.006061 |
def defrise_ellipses(ndim, nellipses=8, alternating=False):
"""Ellipses for the standard Defrise phantom in 2 or 3 dimensions.
Parameters
----------
ndim : {2, 3}
Dimension of the space for the ellipses/ellipsoids.
nellipses : int, optional
Number of ellipses. If more ellipses are u... | 0.000554 |
def set_privacy(self, state):
"""
:param state: True or False
:return: nothing
"""
values = {"desired_state": {"private": state}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | 0.00692 |
def serial_udb_extra_f15_send(self, sue_ID_VEHICLE_MODEL_NAME, sue_ID_VEHICLE_REGISTRATION, force_mavlink1=False):
'''
Backwards compatible version of SERIAL_UDB_EXTRA F15 and F16: format
sue_ID_VEHICLE_MODEL_NAME : Serial UDB Extra Model Name Of Vehicle (uint8_t)... | 0.01157 |
def get_table(table_name):
"""
Get a registered table.
Decorated functions will be converted to `DataFrameWrapper`.
Parameters
----------
table_name : str
Returns
-------
table : `DataFrameWrapper`
"""
table = get_raw_table(table_name)
if isinstance(table, TableFuncWr... | 0.002717 |
def _make_fits(self):
"""Generates the data fits for any variables set for fitting in the shell."""
a = self.tests[self.active]
args = self.curargs
#We need to generate a fit for the data if there are any fits specified.
if len(args["fits"]) > 0:
for fit in list(args[... | 0.013605 |
def minute(self, value=None):
"""Corresponds to IDD Field `minute`
Args:
value (int): value for IDD Field `minute`
value >= 0
value <= 60
if `value` is None it will not be checked against the
specification and is assumed to be ... | 0.002 |
def verify_psd_options_multi_ifo(opt, parser, ifos):
"""Parses the CLI options and verifies that they are consistent and
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_f... | 0.005967 |
def fetch_yeast_locus_sequence(locus_name, flanking_size=0):
'''Acquire a sequence from SGD http://www.yeastgenome.org.
:param locus_name: Common name or systematic name for the locus (e.g. ACT1
or YFL039C).
:type locus_name: str
:param flanking_size: The length of flanking DNA (... | 0.000289 |
def compile(self, prog, features=Features.ALL):
"""Currently this compiler simply returns an interpreter instead of compiling
TODO: Write this compiler to increase LPProg run speed and to prevent exceeding maximum recursion depth
Args:
prog (str): A string containing the program.
... | 0.011152 |
def enable(name, **kwargs):
'''
Enable the named service to start at boot.
flags : None
Set optional flags to run the service with.
service.flags can be used to change the default flags.
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
salt '*... | 0.001183 |
def ratio_and_percentage(current, total, time_remaining):
"""Returns the progress ratio and percentage."""
return "{} / {} ({}% completed)".format(current, total, int(current / total * 100)) | 0.010101 |
def _subprocessor(self, disabled_qubits):
"""Create a subprocessor by deleting a set of qubits. We assume
this removes all evil edges, and return an :class:`eden_processor`
instance.
"""
edgelist = [(p, q) for p, q in self._edgelist if
p not in disabled_qubit... | 0.006356 |
async def _send_plain_text(self, request: Request, stack: Stack):
"""
Sends plain text using `_send_text()`.
"""
await self._send_text(request, stack, None) | 0.010582 |
def depth(self, local: bool = True) -> int:
"""Return the circuit depth.
Args:
local: If True include local one-qubit gates in depth
calculation. Else return the multi-qubit gate depth.
"""
G = self.graph
if not local:
def remove_local(da... | 0.003236 |
def _diff_lists(old, new, comparator):
'''
Compare lists to extract the changes
:param old: old list
:param new: new list
:return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys
The sorted list is the union of unchanged and new lists, but keeping the original
ord... | 0.003218 |
def delete_record(self, name, recordid, username, password):
''' Delete record '''
#headers = {'key': username, 'secret': password}
req = requests.delete(self.api_server + '/api/' + name + '/' +
str(recordid), auth=(username, password))
return req | 0.009709 |
def get_vlan_brief_output_last_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
last_vlan_id = ET.SubElement(out... | 0.004115 |
def register(self, portstr, username, password, pfactory):
"""
Register a perspective factory PFACTORY to be executed when a PB
connection arrives on PORTSTR with USERNAME/PASSWORD. Returns a
Registration object which can be used to unregister later.
"""
# do some basic ... | 0.002545 |
def tz_to_utc(dt, tz, ignoretz=True):
"""Converts a datetime object from the specified timezone to a UTC datetime.
:param tz: the timezone the datetime is currently in. tz can be passed
as a string or as a timezone object. (i.e. 'US/Central' or
pytz.timezone('US/Central'), etc)
:param igno... | 0.003046 |
def addrecords(X, new):
"""
Append one or more records to the end of a numpy recarray or ndarray .
Can take a single record, void or tuple, or a list of records, voids or
tuples.
Implemented by the tabarray method
:func:`tabular.tab.tabarray.addrecords`.
**Parameters**
**X*... | 0.004766 |
def obj_to_mark_down(self, file_path=None, title_columns=False,
quote_numbers=True, quote_empty_str=False):
"""
This will return a str of a mark down table.
:param title_columns: bool if True will title all headers
:param file_path: str of the path to the... | 0.00524 |
def timed(name, tags=None):
"""Function decorator for tracking timing information
on a function's invocation.
>>> from statsdecor.decorators import timed
>>> @timed('my.metric')
>>> def my_func():
>>> pass
"""
def wrap(f):
@wraps(f)
def decorator(*args, **kwargs):
... | 0.002101 |
def get_filename(self, instance):
"""Get the filename
"""
filename = self.field.getFilename(instance)
if filename:
return filename
fieldname = self.get_field_name()
content_type = self.get_content_type(instance)
extension = mimetypes.guess_extension(c... | 0.005405 |
def getstruct(self, msgid, as_json=False, stream=sys.stdout):
"""Get and print the whole message.
as_json indicates whether to print the part list as JSON or not.
"""
parts = [part.get_content_type() for hdr, part in self._get(msgid)]
if as_json:
print(json.dumps(par... | 0.004796 |
def parsedate(data):
"""Convert a time string to a time tuple."""
t = parsedate_tz(data)
if isinstance(t, tuple):
return t[:9]
else:
return t | 0.00578 |
def compute_metrics_cv(self, X, y, **kwargs):
'''Compute cross-validated metrics.
Trains this model on data X with labels y.
Returns a list of dict with keys name, scoring_name, value.
Args:
X (Union[np.array, pd.DataFrame]): data
y (Union[np.array, pd.DataFrame, pd.Ser... | 0.004577 |
def _insertions(self, result, dimension, dimension_index):
"""Return list of (idx, sum) pairs representing subtotals.
*idx* is the int offset at which to insert the ndarray subtotal
in *sum*.
"""
def iter_insertions():
for anchor_idx, addend_idxs in dimension.hs_ind... | 0.002058 |
def __validate_arguments(self):
"""!
@brief Check input arguments of BANG algorithm and if one of them is not correct then appropriate exception
is thrown.
"""
if self.__levels <= 0:
raise ValueError("Incorrect amount of levels '%d'. Level value should... | 0.009023 |
def header(self, array):
"""Specify the header of the table
"""
self._check_row_size(array)
self._header = map(str, array) | 0.012903 |
def envget(var, default=None):
"""Get value of IRAF or OS environment variable."""
if 'pyraf' in sys.modules:
#ONLY if pyraf is already loaded, import iraf into the namespace
from pyraf import iraf
else:
# else set iraf to None so it knows to not use iraf's environment
iraf ... | 0.001825 |
def query_form_data(self):
"""
Get the formdata stored in the database for existing slice.
params: slice_id: integer
"""
form_data = {}
slice_id = request.args.get('slice_id')
if slice_id:
slc = db.session.query(models.Slice).filter_by(id=slice_id).one... | 0.006316 |
def concatenate(arrays, axis=0, always_copy=True):
"""DEPRECATED, use ``concat`` instead
Parameters
----------
arrays : list of `NDArray`
Arrays to be concatenate. They must have identical shape except
the first dimension. They also must have the same data type.
axis : int
T... | 0.000537 |
def fault_zone(self, zone, simulate_wire_problem=False):
"""
Faults a zone if we are emulating a zone expander.
:param zone: zone to fault
:type zone: int
:param simulate_wire_problem: Whether or not to simulate a wire fault
:type simulate_wire_problem: bool
"""
... | 0.002699 |
def upstream(self):
"""Get the remote name to use for upstream branches
Uses "upstream" if it exists, "origin" otherwise
"""
cmd = ["git", "remote", "get-url", "upstream"]
try:
subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
except subprocess.CalledPro... | 0.005208 |
def resolve_const_spec(self, name, lineno):
"""Finds and links the ConstSpec with the given name."""
if name in self.const_specs:
return self.const_specs[name].link(self)
if '.' in name:
include_name, component = name.split('.', 1)
if include_name in self.in... | 0.00313 |
def get_anonymization_salt(ts):
"""Get the anonymization salt based on the event timestamp's day."""
salt_key = 'stats:salt:{}'.format(ts.date().isoformat())
salt = current_cache.get(salt_key)
if not salt:
salt_bytes = os.urandom(32)
salt = b64encode(salt_bytes).decode('utf-8')
c... | 0.002564 |
def predict_type(self):
"""
Predict the type of the inst_ref, and make sure the property being
referenced is allowed
"""
inst_type = self.inst_ref.predict_type()
if self.prop_ref_type.allowed_inst_type != inst_type:
self.msg.fatal(
"'%s' is no... | 0.006494 |
def data2rst(table, spans=[[[0, 0]]], use_headers=True,
center_cells=False, center_headers=False):
"""
Convert a list of lists of str into a reStructuredText Grid Table
Parameters
----------
table : list of lists of str
spans : list of lists of lists of int, optional
These ... | 0.000656 |
def set_kg(self, kg):
"""Sets the Kg for the BMC to use
In RAKP, Kg is a BMC-specific integrity key that can be set. If not
set, Kuid is used for the integrity key
"""
try:
self.kg = kg.encode('utf-8')
except AttributeError:
self.kg = kg | 0.006431 |
def factorize_and_solve(self,A,b):
"""
Factorizes A and sovles Ax=b.
Parameters
----------
A : matrix
b : ndarray
Returns
-------
x : ndarray
"""
A = coo_matrix(A)
x = b.copy()
self.mumps.set_centralized_assemble... | 0.009662 |
def ae_latent_softmax(latents_pred, latents_discrete_hot, vocab_size, hparams):
"""Latent prediction and loss.
Args:
latents_pred: Tensor of shape [..., depth].
latents_discrete_hot: Tensor of shape [..., vocab_size].
vocab_size: an int representing the vocab size.
hparams: HParams.
Returns:
... | 0.003195 |
def _build_params(self):
''' método que constrói o dicionario com os parametros que serão usados
na requisição HTTP Post ao PagSeguro
Returns:
Um dicionário com os parametros definidos no objeto Payment.
'''
params = {}
params['email'] = self.email
... | 0.001731 |
def lazy_tag(tag, *args, **kwargs):
"""
Lazily loads a template tag after the page has loaded. Requires jQuery
(for now).
Usage:
{% load lazy_tags %}
{% lazy_tag 'tag_lib.tag_name' arg1 arg2 kw1='test' kw2='hello' %}
Args:
tag (str): the tag library and tag name separated ... | 0.001206 |
def set_user_access(uid, channel=14, callback=True, link_auth=True, ipmi_msg=True,
privilege_level='administrator', **kwargs):
'''
Set user access
:param uid: user number [1:16]
:param channel: number [1:7]
:param callback:
User Restricted to Callback
- False ... | 0.001902 |
def transform(self, X, y=None):
"""
Locally blur an image by applying a gradient anisotropic diffusion filter.
Arguments
---------
X : ANTsImage
image to transform
y : ANTsImage (optional)
another image to transform.
Example
----... | 0.004132 |
def update(self, data):
"""Update the object with new data."""
fields = [
'id',
'status',
'type',
'persistence',
'date_start',
'date_finish',
'date_created',
'date_modified',
'checksum',
... | 0.005376 |
def request(self, batch, attempt=0):
"""Attempt to upload the batch and retry before raising an error """
try:
q = self.api.new_queue()
for msg in batch:
q.add(msg['event'], msg['value'], source=msg['source'])
q.submit()
except:
if ... | 0.007353 |
def number_of_states(dtrajs):
r"""
Determine the number of states from a set of discrete trajectories
Parameters
----------
dtrajs : list of int-arrays
discrete trajectories
"""
# determine number of states n
nmax = 0
for dtraj in dtrajs:
nmax = max(nmax, np.max(dtra... | 0.002681 |
def get(self):
"""
this translates to 'get all token addresses we have channels open for'
"""
return self.rest_api.get_tokens_list(
self.rest_api.raiden_api.raiden.default_registry.address,
) | 0.00823 |
def wait(aws):
"""Waits for all of the awaitable objects (e.g. coroutines) in aws to finish.
All the awaitable objects are waited for, even if one of them raises an
exception. When one or more awaitable raises an exception, the exception from
the awaitable with the lowest index in the aws list will be reraised... | 0.008386 |
def set_position_target_global_int_encode(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate):
'''
Sets a desired vehicle position, velocity, and/or acceleration in a
global coo... | 0.005689 |
def restore(cls, data_dict):
"""
Restore from previously simplified data. Data is supposed to be valid,
no checks are performed!
"""
obj = cls.__new__(cls) # Avoid calling constructor
object.__setattr__(obj, '_simplified', data_dict)
object.__setattr__(obj, '_sto... | 0.005666 |
async def run(*cmd):
"""Run the given subprocess command in a coroutine.
Args:
*cmd: the command to run and its arguments.
Returns:
The output that the command wrote to stdout as a list of strings, one line
per element (stderr output is piped to stdout).
Raises:
RuntimeError: if the command r... | 0.01087 |
def lpad(s, N, char='\0'):
"""pads a string to the left with null-bytes or any other given character.
..note:: This is used by the :py:func:`xor` function.
:param s: the string
:param N: an integer of how much padding should be done
:returns: the original bytes
"""
assert isinstance(char, ... | 0.004831 |
def scopes(self, **kwargs):
"""Scopes associated to the team."""
return self._client.scopes(team=self.id, **kwargs) | 0.015267 |
def _tzinfome(tzinfo):
"""Gets a tzinfo object from a string.
Args:
tzinfo: A string (or string like) object, or a datetime.tzinfo object.
Returns:
An datetime.tzinfo object.
Raises:
UnknownTimeZoneError: If the timezone given can't be decoded.
"""
if not isinstance(tzinfo, datetime.tzinfo):
... | 0.013308 |
def visible(self):
"""
Read/write. |True| if axis is visible, |False| otherwise.
"""
delete = self._element.delete_
if delete is None:
return False
return False if delete.val else True | 0.008197 |
def create_with_virtualenv(self, interpreter, virtualenv_options):
"""Create a virtualenv using the virtualenv lib."""
args = ['virtualenv', '--python', interpreter, self.env_path]
args.extend(virtualenv_options)
if not self.pip_installed:
args.insert(3, '--no-pip')
t... | 0.003872 |
def setOutputHandler(self, outputhandler):
"""
Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands.
"""
class OutputHandlerInternal(amplpython.OutputHandler):
def output... | 0.003035 |
def get(img, light=False):
"""Get colorscheme."""
cols = gen_colors(img)
if len(cols) < 6:
logging.error("colorz failed to generate enough colors.")
logging.error("Try another backend or another image. (wal --backend)")
sys.exit(1)
return adjust(cols, light) | 0.003333 |
def chem_shifts_by_residue(self, amino_acids=None, atoms=None, amino_acids_and_atoms=None, nmrstar_version="3"):
"""Organize chemical shifts by amino acid residue.
:param list amino_acids: List of amino acids three-letter codes.
:param list atoms: List of BMRB atom type codes.
:param di... | 0.004607 |
def centerOnDateTime(self, dtime):
"""
Centers the view on a given datetime for the gantt widget.
:param dtime | <QDateTime>
"""
view = self.uiGanttVIEW
scene = view.scene()
point = view.mapToScene(0, 0)
x = scene.datetimeXPos(dtime)... | 0.008065 |
def dP_wedge_meter(D, H, P1, P2):
r'''Calculates the non-recoverable pressure drop of a wedge meter
based on the measured pressures before and at the wedge meter, and the
geometry of the wedge meter according to [1]_.
.. math::
\Delta \bar \omega = (1.09 - 0.79\beta)\Delta P
P... | 0.007529 |
def add_missing(C):
"""Add arrays with zeros for missing Wilson coefficient keys"""
C_out = C.copy()
for k in (set(WC_keys) - set(C.keys())):
C_out[k] = np.zeros(C_keys_shape[k])
return C_out | 0.004651 |
def store(self, obj):
""" Store
Store an object into the MongoDB storage for caching
Args:
obj (AtlasServiceBinding.Binding or AtlasServiceInstance.Instance): instance or binding
Returns:
ObjectId: MongoDB _id
Raise... | 0.017254 |
def superclass(self, klass):
"""True if the Class is a superclass of the given one."""
return bool(lib.EnvSuperclassP(self._env, self._cls, klass._cls)) | 0.011905 |
def module_getmtime(filename):
"""
Get the mtime associated with a module. If this is a .pyc or .pyo file and
a corresponding .py file exists, the time of the .py file is returned.
:param filename: filename of the module.
:returns: mtime or None if the file doesn"t exist.
"""
if os.path.sp... | 0.003704 |
def alg2keytype(alg):
"""
Go from algorithm name to key type.
:param alg: The algorithm name
:return: The key type
"""
if not alg or alg.lower() == "none":
return "none"
elif alg.startswith("RS") or alg.startswith("PS"):
return "RSA"
elif alg.startswith("HS") or alg.star... | 0.00216 |
def build_url_field(self, field_name, model_class):
"""
This is needed due to DRF's model serializer uses the queryset to build url name
# TODO: Move this to own serializer mixin or fix problem elsewhere?
"""
field, kwargs = super().build_url_field(field_name, model_class)
... | 0.006757 |
def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if not isinstance(x, basestring):
x = repr(x)
return x.zfill(width) | 0.003623 |
def scan_devices(fn, lfilter, iface=None):
"""Sniff packages
:param fn: callback on packet
:param lfilter: filter packages
:return: loop
"""
try:
sniff(prn=fn, store=0,
# filter="udp",
filter="arp or (udp and src port 68 and dst port 67 and src host 0.0.0.0)"... | 0.004662 |
def get_valid_statements_for_modeling(sts: List[Influence]) -> List[Influence]:
""" Select INDRA statements that can be used to construct a Delphi model
from a given list of statements. """
return [
s
for s in sts
if is_grounded_statement(s)
and (s.subj_delta["polarity"] is ... | 0.002597 |
def write_ds9(regions, filename, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to DS9 string and write to file.
Parameters
----------
regions : `list`
List of `regions.Region` objects
filename : `str`
Filename in which the string is to be ... | 0.000759 |
def _initialize_buffers(self, view_size):
""" Create the buffers to cache tile drawing
:param view_size: (int, int): size of the draw area
:return: None
"""
import math
from pygame import Rect
tw, th = self.data.tile_size
mw, mh = self.data.map_size
... | 0.002008 |
def _retrieve_problem(self, id_):
"""Resume polling for a problem previously submitted.
Args:
id_: Identification of the query.
Returns:
:obj: `Future`
"""
future = Future(self, id_, self.return_matrix, None)
self.client._poll(future)
ret... | 0.006061 |
def fake_shell(self, func, stdout=False):
"""
Execute a function and decorate its return value in the style of
_low_level_execute_command(). This produces a return value that looks
like some shell command was run, when really func() was implemented
entirely in Python.
If... | 0.002125 |
def OnButtonCell(self, event):
"""Button cell event handler"""
# The button text
text = event.text
with undo.group(_("Button")):
self.grid.actions.set_attr("button_cell", text)
self.grid.ForceRefresh()
self.grid.update_attribute_toolbar()
event.Sk... | 0.006173 |
def wait_for(self, new_state):
"""
Wait for an exact state `new_state` to be reached by the state
machine.
If the state is skipped, that is, if a state which is greater than
`new_state` is written to :attr:`state`, the coroutine raises
:class:`OrderedStateSkipped` except... | 0.002899 |
def output_sizes(self):
"""Returns a tuple of all output sizes of all the layers."""
return tuple([l() if callable(l) else l for l in self._output_sizes]) | 0.012346 |
def create(self, name, sources=None, destinations=None,
services=None, action='allow', log_options=None,
authentication_options=None, connection_tracking=None,
is_disabled=False, vpn_policy=None, mobile_vpn=False,
add_pos=None, after=None, before=None,
... | 0.007295 |
def trim1(l, proportiontocut, tail='right'):
"""
Slices off the passed proportion of items from ONE end of the passed
list (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost'
10% of scores). Slices off LESS if proportion results in a non-integer
slice index (i.e., conservatively slices off proporti... | 0.002972 |
def CopyFromDateTimeString(self, time_string):
"""Copies a POSIX timestamp from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can... | 0.001019 |
def inference(self, state_arr, limit=1000):
'''
Infernce.
Args:
state_arr: `np.ndarray` of state.
limit: The number of inferencing.
Returns:
`list of `np.ndarray` of an optimal route.
'''
self.__inferencing_f... | 0.002996 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.