text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'text') and self.text is not None:
_dict['text'] = self.text
return _dict | 0.00905 |
def clean_meta(rst_content):
"""remove moinmoin metada from the top of the file"""
rst = rst_content.split('\n')
for i, line in enumerate(rst):
if line.startswith('#'):
continue
break
return '\n'.join(rst[i:]) | 0.003937 |
def get_state_actions(self, state, **kwargs):
"""
For dependent items, inherits the behavior from :class:`dockermap.map.action.resume.ResumeActionGenerator`.
For other the main container, checks if containers exist, and depending on the ``remove_existing_before``
option either fails or r... | 0.005983 |
def WideResnetBlock(channels, strides=(1, 1), channel_mismatch=False):
"""WideResnet convolutational block."""
main = layers.Serial(layers.BatchNorm(), layers.Relu(),
layers.Conv(channels, (3, 3), strides, padding='SAME'),
layers.BatchNorm(), layers.Relu(),
... | 0.008319 |
def set_cancel_policy(self, cancel_policy):
"""Sets the order cancellation policy for the simulation.
Parameters
----------
cancel_policy : CancelPolicy
The cancellation policy to use.
See Also
--------
:class:`zipline.api.EODCancel`
:class:`... | 0.003436 |
def put(path, obj):
"""Write an object to file"""
try:
import cPickle as pickle
except:
import pickle
with open(path, 'wb') as file:
return pickle.dump(obj, file) | 0.009852 |
def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
lineterm="") | 0.003448 |
def child_added(self, child):
""" When a child is added, schedule a data changed notification """
super(AndroidViewPager, self).child_added(child)
self._notify_count += 1
self.get_context().timed_call(
self._notify_delay, self._notify_change) | 0.006993 |
def add(
self,
uri,
methods,
handler,
host=None,
strict_slashes=False,
version=None,
name=None,
):
"""Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
... | 0.00124 |
def _q_to_dcm(self, q):
"""
Create DCM from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: 3x3 dcm array
"""
assert(len(q) == 4)
assert(np.allclose(QuaternionBase.norm_array(q), 1))
dcm = np.zeros([3, 3])
a = q[0]
... | 0.002372 |
def rowlenselect(table, n, complement=False):
"""Select rows of length `n`."""
where = lambda row: len(row) == n
return select(table, where, complement=complement) | 0.011364 |
def separated(p, sep, mint, maxt=None, end=None):
'''Repeat a parser `p` separated by `s` between `mint` and `maxt` times.
When `end` is None, a trailing separator is optional.
When `end` is True, a trailing separator is required.
When `end` is False, a trailing separator is not allowed.
MATCHES AS ... | 0.000577 |
def create_raid(self, raid_config):
"""Create the raid configuration on the hardware.
:param raid_config: A dictionary containing target raid configuration
data. This data stucture should be as follows:
raid_config = {'logical_disks': [{'raid_leve... | 0.000983 |
def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument
'''
Frame the given message with our wire protocol for IPC
For IPC, we don't need to be backwards compatible, so
use the more efficient "use_bin_type=True" on Python 3.
'''
framed_msg = {}
if header is ... | 0.003591 |
def update_params(old_params, new_params, check=False):
"""Update old_params with new_params.
If check==False, this merely adds and overwrites the content of old_params.
If check==True, this only allows updating of parameters that are already
present in old_params.
Parameters
----------
o... | 0.001019 |
def with_read_hdf5(func):
"""Decorate an HDF5-reading function to open a filepath if needed
``func`` should be written to presume an `h5py.Group` as the first
positional argument.
"""
@wraps(func)
def decorated_func(fobj, *args, **kwargs):
# pylint: disable=missing-docstring
if ... | 0.001669 |
def run_send_all(*args):
'''
Send email to all user.
'''
for user_rec in MUser.query_all():
email_add = user_rec.user_email
send_mail([email_add],
"{0}|{1}".format(SMTP_CFG['name'], email_cfg['title']),
email_cfg['content']) | 0.003425 |
def get_sparql_dataframe( self ):
''' Iterates through the sparql table and condenses it into a Pandas DataFrame '''
self.result = self.g.query(self.query)
cols = set() # set(['qname'])
indx = set()
data = {}
curr_subj = None # place marker for first subj to be processed
... | 0.007357 |
def at(self, row, col):
"""Return the value at the given cell position.
Args:
row (int): zero-based row number
col (int): zero-based column number
Returns:
cell value
Raises:
TypeError: if ``row`` or ``col`` is not an ``int``
Ind... | 0.003906 |
def _truncated_normal(mean,
stddev,
seed=None,
normalize=True,
alpha=0.01):
''' Add noise with truncnorm from numpy.
Bounded (0.001,0.999)
'''
# within range ()
# provide entry to chose which adding noise way to ... | 0.001307 |
async def send_code_request(self, phone, *, force_sms=False):
"""
Sends a code request to the specified phone number.
Args:
phone (`str` | `int`):
The phone to which the code will be sent.
force_sms (`bool`, optional):
Whether to force se... | 0.001613 |
def auto_tweet(sender, instance, *args, **kwargs):
"""
Allows auto-tweeting newly created object to twitter
on accounts configured in settings.
You MUST create an app to allow oAuth authentication to work:
-- https://dev.twitter.com/apps/
You also must set the app to "Read and Write" access le... | 0.009834 |
def example_async_client(api_client):
"""Example async client.
"""
try:
pprint((yield from api_client.echo()))
except errors.RequestError as exc:
log.exception('Exception occurred: %s', exc)
yield gen.Task(lambda *args, **kwargs: ioloop.IOLoop.current().stop()) | 0.003344 |
def search(self, filepath=None, basedir=None, kind=None):
"""
Search for a settings file.
Keyword Arguments:
filepath (string): Path to a config file, either absolute or
relative. If absolute set its directory as basedir (omitting
given basedir argume... | 0.000939 |
def query_random(**kwargs):
'''
Return the random records of centain kind.
'''
if 'limit' in kwargs:
limit = kwargs['limit']
elif 'num' in kwargs:
limit = kwargs['num']
else:
limit = 10
kind = kwargs.get('kind', None)
... | 0.00267 |
def chimera(args):
"""
%prog chimera bedfile
Scan the bed file to break scaffolds that multi-maps.
"""
p = OptionParser(chimera.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bedfile, = args
bed = Bed(bedfile)
selected = select... | 0.002375 |
def get_all_for_build_configuration(self, configuration_id, **kwargs):
"""
Gets the Build Records linked to a specific Build Configuration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
t... | 0.004418 |
def Architecture_var(cls, v, serializerVars, extraTypes,
extraTypes_serialized, ctx, childCtx):
"""
:return: list of extra discovered processes
"""
v.name = ctx.scope.checkedName(v.name, v)
serializedVar = cls.SignalItem(v, childCtx, declaration=True)
... | 0.00831 |
def copy(self, zero=None):
"""
Returns a Poly instance with the same terms, but as a "T" (tee) copy
when they're Stream instances, allowing maths using a polynomial more
than once.
"""
return Poly(OrderedDict((k, v.copy() if isinstance(v, Stream) else v)
for k, v in i... | 0.0025 |
def _EndRecData(fpin):
"""Return data from the "End of Central Directory" record, or None.
The data is a list of the nine items in the ZIP "End of central dir"
record followed by a tenth item, the file seek offset of this record."""
# Determine file size
fpin.seek(0, 2)
filesize = fpin.tell()
... | 0.000843 |
def _get_token_from_query_string(self, request, refresh_token):
"""
Extract the token if present from the request args.
"""
if refresh_token:
query_string_token_name_key = "query_string_refresh_token_name"
else:
query_string_token_name_key = "query_string_... | 0.003929 |
def base_solution_linear(a: int, b: int, c: int) -> Iterator[Tuple[int, int]]:
r"""Yield solutions for a basic linear Diophantine equation of the form :math:`ax + by = c`.
First, the equation is normalized by dividing :math:`a, b, c` by their gcd.
Then, the extended Euclidean algorithm (:func:`extended_euc... | 0.003844 |
def from_array(array):
"""
Deserialize a new ShippingOption from a given dictionary.
:return: new ShippingOption instance.
:rtype: ShippingOption
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, paramet... | 0.006369 |
def download_repo(repo_url, destination, commit=None):
'''download_repo
:param repo_url: the url of the repo to clone from
:param destination: the full path to the destination for the repo
'''
command = "git clone %s %s" % (repo_url, destination)
os.system(command)
return destination | 0.003205 |
def pop_one(self, priority=None):
"""
NON-BLOCKING POP IN QUEUE, IF ANY
"""
with self.lock:
if not priority:
priority = self.highest_entry()
if self.closed:
return [THREAD_STOP]
elif not self.queue:
retur... | 0.007394 |
def write(
self,
mi_cmd_to_write,
timeout_sec=DEFAULT_GDB_TIMEOUT_SEC,
raise_error_on_timeout=True,
read_response=True,
):
"""Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec.
Args:
mi_cmd_to_write (str or ... | 0.003977 |
def from_any(cls, obj, bucket):
"""
Ensure the current object is an index. Always returns a new object
:param obj: string or IndexInfo object
:param bucket: The bucket name
:return: A new IndexInfo object
"""
if isinstance(obj, cls):
return cls(obj.raw... | 0.003914 |
def in_cache(self, objpath, metahash):
"""Returns true if object is cached.
Args:
objpath: Filename relative to buildroot.
metahash: hash object
"""
try:
self.path_in_cache(objpath, metahash)
return True
except CacheMiss:
r... | 0.006042 |
def _get_flag_file_lines(self, filename, parsed_file_stack=None):
"""Returns the useful (!=comments, etc) lines from a file with flags.
Args:
filename: str, the name of the flag file.
parsed_file_stack: [str], a list of the names of the files that we have
recursively encountered at the curr... | 0.006744 |
def _parseNetDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the NET directory.
@see: U{http://www.ntcore.com/files/dotnetformat.htm}
@type rva: int
@param rva: The RVA where the NET directory starts.
@type size: int
@param size: The... | 0.007678 |
def normalize_input(input,preferunicodeoverstring=False,nfconly=False):
'''
This looks dirty as crap, but the try/catch failure series goes in
the correct order and it's a lot easier to use this most of the
time, and it works for every situation I needed to use it in. That
said, I'm kind of hoping n... | 0.014555 |
def continuation(self, body=None, final=True):
'''return a `continuation` :class:`Frame`.'''
return self.encode(body, opcode=0, final=final) | 0.012821 |
def _getIndxChop(self, indx):
'''
A helper method for Type subclasses to use for a simple way to truncate
indx bytes.
'''
# cut down an index value to 256 bytes...
if len(indx) <= 256:
return indx
base = indx[:248]
sufx = xxhash.xxh64(indx).di... | 0.005666 |
def replace(self, pat, rep):
"""Replace first occurrence of pat with rep in each element.
Parameters
----------
pat : str
rep : str
Returns
-------
Series
"""
check_type(pat, str)
check_type(rep, str)
return _series_str_... | 0.005435 |
def push_pv(self, tokens):
""" Creates and Generator object, populates it with data, finds its Bus
and adds it.
"""
logger.debug("Pushing PV data: %s" % tokens)
bus = self.case.buses[tokens["bus_no"]-1]
g = Generator(bus)
g.p = tokens["p"]
g.q_max = toke... | 0.003929 |
def find_files(dir_path, extension="*"):
"""
From https://stackoverflow.com/a/2186565/610569
"""
if sys.version_info.major == 3 and sys.version_info.minor >= 5:
pattern = '/'.join([dir_path, '**', extension])
for filename in glob.iglob(pattern, recursive=True):
yield filename... | 0.001972 |
def _uint2farray(ftype, num, length=None):
"""Convert an unsigned integer to an farray."""
if num < 0:
raise ValueError("expected num >= 0")
else:
objs = _uint2objs(ftype, num, length)
return farray(objs) | 0.004167 |
def group_remove(groupname,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Removes a group from the Postgres server.
CLI Example:
.. code-block:: bash
s... | 0.001553 |
def check_stripe_api_host(app_configs=None, **kwargs):
"""
Check that STRIPE_API_HOST is not being used in production.
"""
from django.conf import settings
messages = []
if not settings.DEBUG and hasattr(settings, "STRIPE_API_HOST"):
messages.append(
checks.Warning(
"STRIPE_API_HOST should not be set i... | 0.033333 |
def export_verified_variants(aggregate_variants, unique_callers):
"""Create the lines for an excel file with verified variants for
an institute
Args:
aggregate_variants(list): a list of variants with aggregates case data
unique_callers(set): a unique list of available caller... | 0.008618 |
def _detect(env):
"""
Detect all the command line tools that we might need for creating
the requested output formats.
"""
global prefer_xsltproc
if env.get('DOCBOOK_PREFER_XSLTPROC',''):
prefer_xsltproc = True
if ((not has_libxml2 and not has_lxml) or (prefer_xsltproc))... | 0.012007 |
def lookup_discrete(x, xs, ys):
"""
Intermediate values take on the value associated with the next lower x-coordinate (also called a step-wise function). The last two points of a discrete graphical function must have the same y value.
Out-of-range values are the same as the closest endpoint (i.e, no extrapo... | 0.006012 |
def prepend_rez_path(self):
"""Prepend rez path to $PATH."""
if system.rez_bin_path:
self.env.PATH.prepend(system.rez_bin_path) | 0.012903 |
def auto_doc(tool, nco_self):
"""
Generate the __doc__ string of the decorated function by calling the nco help command
:param tool:
:param nco_self:
:return:
"""
def desc(func):
func.__doc__ = nco_self.call([tool, "--help"]).get("stdout")
return func
return desc | 0.006349 |
def depth_file_for_nir_file(video_filename, depth_file_list):
"""Returns the corresponding depth filename given a NIR filename"""
(root, filename) = os.path.split(video_filename)
needle_ts = int(filename.split('-')[2].split('.')[0])
haystack_ts_list = np.array(Kinect.timestamps_from_file... | 0.006 |
def from_fits_renormalized(cls, file_path, hdu, pixel_scale):
"""Loads a PSF from fits and renormalizes it
Parameters
----------
pixel_scale
file_path: String
The path to the file containing the PSF
hdu : int
The HDU the PSF is stored in the .fits... | 0.003552 |
def projects(accountable):
"""
List all projects.
"""
projects = accountable.metadata()['projects']
headers = sorted(['id', 'key', 'self'])
rows = [[v for k, v in sorted(p.items()) if k in headers] for p in projects]
rows.insert(0, headers)
print_table(SingleTable(rows)) | 0.006601 |
def _remove_remote_node_data_bag():
"""Removes generated 'node' data_bag from the remote node"""
node_data_bag_path = os.path.join(env.node_work_path, 'data_bags', 'node')
if exists(node_data_bag_path):
sudo("rm -rf {0}".format(node_data_bag_path)) | 0.003731 |
def upload_nginx_site_conf(site_name, template_name=None, context=None, enable=True):
"""Upload Nginx site configuration from a template."""
template_name = template_name or [u'nginx/%s.conf' % site_name, u'nginx/site.conf']
site_available = u'/etc/nginx/sites-available/%s' % site_name
upload_templ... | 0.011574 |
def Process(self, parser_mediator, **kwargs):
"""Evaluates if this is the correct plugin and processes data accordingly.
The purpose of the process function is to evaluate if this particular
plugin is the correct one for the particular data structure at hand.
This function accepts one value to use for ... | 0.001949 |
def load_app(config, **kwargs):
'''
Used to load a ``Pecan`` application and its environment based on passed
configuration.
:param config: Can be a dictionary containing configuration, a string which
represents a (relative) configuration filename
returns a pecan.Pecan object
... | 0.001181 |
def retry(*excepts):
'''A decorator to specify a bunch of exceptions that should be caught
and the job retried. It turns out this comes up with relative frequency'''
@decorator.decorator
def new_func(func, job):
'''No docstring'''
try:
func(job)
except tuple(excepts):... | 0.002747 |
def end_nodes(self):
"""
Yields `MatchVariable` instances for all the nodes having their end
position at the end of the input string.
"""
for varname, reg in self._nodes_to_regs():
# If this part goes until the end of the input string.
if reg[1] == len(sel... | 0.004193 |
def toggle_buttons(self):
"""Turn buttons on and off."""
all_time_on = self.all_time.get_value()
all_chan_on = self.all_chan.get_value()
self.times['beg'].setEnabled(not all_time_on)
self.times['end'].setEnabled(not all_time_on)
self.idx_chan.setEnabled(not all_chan_on) | 0.00627 |
def cloud_init(names, host=None, quiet=False, **kwargs):
'''
Wrapper for using lxc.init in saltcloud compatibility mode
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion to start the container on. Required.
path
pa... | 0.002646 |
def on_service_arrival(self, svc_ref):
"""
Called when a service has been registered in the framework
:param svc_ref: A service reference
"""
with self._lock:
new_ranking = svc_ref.get_property(SERVICE_RANKING)
if self._current_ranking is not None:
... | 0.001612 |
def walk(pathobj, topdown=True):
"""
os.walk like function to traverse the URI like a file system.
The only difference is that this function takes and returns Path objects
in places where original implementation will return strings
"""
dirs, nondirs = [], []
for child in pathobj:
re... | 0.001232 |
def mac_address_table_aging_time_conversational_time_out(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
mac_address_table = ET.SubElement(config, "mac-address-table", xmlns="urn:brocade.com:mgmt:brocade-mac-address-table")
aging_time = ET.SubElement(mac... | 0.006623 |
def __fetch_pre1_27(self, from_date=None):
"""Fetch the pages from the backend url.
The method retrieves, from a MediaWiki url, the
wiki pages.
:returns: a generator of pages
"""
def fetch_incremental_changes(namespaces_contents):
# Use recent changes API t... | 0.002921 |
def compute(
self, X: DataFrame, Y: Series=None,
column_types: Dict[str, str]=None, metafeature_ids: List=None,
exclude: List=None, sample_shape=None, seed=None, n_folds=2,
verbose=False, timeout=None
) -> dict:
"""
Parameters
----------
X: pandas.Data... | 0.003235 |
def getYadisXRD(xrd_tree):
"""Return the XRD element that should contain the Yadis services"""
xrd = None
# for the side-effect of assigning the last one in the list to the
# xrd variable
for xrd in xrd_tree.findall(xrd_tag):
pass
# There were no elements found, or else xrd would be se... | 0.002331 |
def tob32(val):
"""Return provided 32 bit value as a string of four bytes."""
ret = bytearray(4)
ret[0] = (val>>24)&M8
ret[1] = (val>>16)&M8
ret[2] = (val>>8)&M8
ret[3] = val&M8
return ret | 0.037037 |
def make_supercell(self, scaling_matrix, to_unit_cell=True):
"""
Create a supercell.
Args:
scaling_matrix: A scaling matrix for transforming the lattice
vectors. Has to be all integers. Several options are possible:
a. A full 3x3 scaling matrix defin... | 0.001669 |
def reorient_coordinates(self):
"""
Returns a modified .verts array with new coordinates for nodes.
This does not need to modify .edges. The order of nodes, and therefore
of verts rows is still the same because it is still based on the tree
branching order (ladderized usually). ... | 0.003019 |
def from_dict(input_dict, data=None):
"""
Instantiate an object of a derived class using the information
in input_dict (built by the to_dict method of the derived class).
More specifically, after reading the derived class from input_dict,
it calls the method _build_from_input_dic... | 0.002193 |
def locked(self, lock):
"""Locks or unlocks the thermostat."""
_LOGGER.debug("Setting the lock: %s", lock)
value = struct.pack('BB', PROP_LOCK, bool(lock))
self._conn.make_request(PROP_WRITE_HANDLE, value) | 0.008439 |
def get_clipboard(self):
"""Returns the clipboard content
If a bitmap is contained then it is returned.
Otherwise, the clipboard text is returned.
"""
bmpdata = wx.BitmapDataObject()
textdata = wx.TextDataObject()
if self.clipboard.Open():
is_bmp_p... | 0.003115 |
def select_spread(
list_of_elements = None,
number_of_elements = None
):
"""
This function returns the specified number of elements of a list spread
approximately evenly.
"""
if len(list_of_elements) <= number_of_elements:
return list_of_elements
if number_of_elements == 0:... | 0.015559 |
def update_parameter_group(name, parameters, apply_method="pending-reboot",
tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Update an RDS parameter group.
CLI example::
salt myminion boto_rds.update_parameter_group my-param-gro... | 0.001203 |
def node_is_upstream_leaf(graph: BELGraph, node: BaseEntity) -> bool:
"""Return if the node is an upstream leaf.
An upstream leaf is defined as a node that has no in-edges, and exactly 1 out-edge.
"""
return 0 == len(graph.predecessors(node)) and 1 == len(graph.successors(node)) | 0.010135 |
def featuretypes(self):
"""
Iterate over feature types found in the database.
Returns
-------
A generator object that yields featuretypes (as strings)
"""
c = self.conn.cursor()
c.execute(
'''
SELECT DISTINCT featuretype from featu... | 0.005249 |
def getThirdPartyLibCmakeFlags(self, libs):
"""
Retrieves the CMake invocation flags for building against the Unreal-bundled versions of the specified third-party libraries
"""
fmt = PrintingFormat.singleLine()
if libs[0] == '--multiline':
fmt = PrintingFormat.multiLine()
libs = libs[1:]
platformDe... | 0.036304 |
def instruction_addresses(self):
"""
Get all instruction addresses in the binary.
:return: A list of sorted instruction addresses.
:rtype: list
"""
addrs = [ ]
for b in sorted(self.blocks, key=lambda x: x.addr): # type: BasicBlock
addrs.extend(b.ins... | 0.007576 |
def _serve_experiment_runs(self, request):
"""Serve a JSON runs of an experiment, specified with query param
`experiment`, with their nested data, tag, populated. Runs returned are
ordered by started time (aka first event time) with empty times sorted last,
and then ties are broken by sorting on the run... | 0.005771 |
def node_created_handler(sender, **kwargs):
""" send notification when a new node is created according to users's settings """
if kwargs['created']:
obj = kwargs['instance']
queryset = exclude_owner_of_node(obj)
create_notifications.delay(**{
"users": queryset,
"n... | 0.004474 |
def SETUP(self):
"""Set up stream transport."""
message = "SETUP " + self.session.control_url + " RTSP/1.0\r\n"
message += self.sequence
message += self.authentication
message += self.user_agent
message += self.transport
message += '\r\n'
return message | 0.006309 |
def ExpandGroups(path):
"""Performs group expansion on a given path.
For example, given path `foo/{bar,baz}/{quux,norf}` this method will yield
`foo/bar/quux`, `foo/bar/norf`, `foo/baz/quux`, `foo/baz/norf`.
Args:
path: A path to expand.
Yields:
Paths that can be obtained from given path by expandi... | 0.011852 |
def get_plate_list(self, market, plate_class):
"""
获取板块集合下的子板块列表
:param market: 市场标识,注意这里不区分沪,深,输入沪或者深都会返回沪深市场的子板块(这个是和客户端保持一致的)参见Market
:param plate_class: 板块分类,参见Plate
:return: ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
... | 0.003273 |
def git_remote_resolve_reference(repo_dir, ref, remote='origin'):
"""Try to find a revision (commit hash) for the ref at 'remote' repo.
Once you have the revision (commit hash), you can check it out. Of
course, you may have to fetch it first.
Note: Borrowed these ideas from Chef
https://githu... | 0.001129 |
def _reset_errors(self, msg=None):
"""
Resets the logging throttle cache, so the next error is emitted
regardless of the value in `self.server_error_interval`
:param msg: if present, only this key is reset. Otherwise, the whole
cache is cleaned.
"""
if msg is... | 0.00463 |
def initialize(self, force=False):
"""
Initializes the view if it is visible or being loaded.
"""
if force or (self.isVisible() and \
not self.isInitialized() and \
not self.signalsBlocked()):
self._initialized = True
... | 0.014205 |
def export_ruptures_xml(ekey, dstore):
"""
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
fmt = ekey[-1]
oq = dstore['oqparam']
num_ses = oq.ses_per_logic_tree_path
mesh = get_mesh(dstore['sitecol'])
ruptures_by_grp = {}
for rgetter ... | 0.00142 |
def summarize_ranges(array):
"""
:type array: List[int]
:rtype: List[]
"""
res = []
if len(array) == 1:
return [str(array[0])]
i = 0
while i < len(array):
num = array[i]
while i + 1 < len(array) and array[i + 1] - array[i] == 1:
i += 1
if array... | 0.002222 |
def slugs_configuration_camera_send(self, target, idOrder, order, force_mavlink1=False):
'''
Control for camara.
target : The system setting the commands (uint8_t)
idOrder : ID 0: brightness 1: aperture 2: iris 3: ICR ... | 0.011864 |
def make_random_MLdataset(max_num_classes = 20,
min_class_size = 20,
max_class_size = 50,
max_dim = 100,
stratified = True):
"Generates a random MLDataset for use in testing."
smallest = min(min_class_size, ... | 0.01122 |
def mock_xray_client(f):
"""
Mocks the X-Ray sdk by pwning its evil singleton with our methods
The X-Ray SDK has normally been imported and `patched()` called long before we start mocking.
This means the Context() will be very unhappy if an env var isnt present, so we set that, save
the old context... | 0.002819 |
def get_seconds(self):
"""Gets seconds from raw time
:return: Seconds in time
"""
parsed = self.parse_hh_mm_ss() # get times
total_seconds = parsed.second
total_seconds += parsed.minute * 60.0
total_seconds += parsed.hour * 60.0 * 60.0
return total_secon... | 0.006211 |
def _enqueueIntoAllRemotes(self, msg: Any, signer: Signer) -> None:
"""
Enqueue the specified message into all the remotes in the nodestack.
:param msg: the message to enqueue
"""
for rid in self.remotes.keys():
self._enqueue(msg, rid, signer) | 0.006757 |
def get_sections_by_delegate_and_term(person,
term,
future_terms=0,
include_secondaries=True,
transcriptable_course='yes',
delete_... | 0.00093 |
def CreateChatWith(self, *Usernames):
"""Creates a chat with one or more users.
:Parameters:
Usernames : str
One or more Skypenames of the users.
:return: A chat object
:rtype: `Chat`
:see: `Chat.AddMembers`
"""
return Chat(self, chop(self... | 0.007895 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.