text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def words_for_language(language_code):
"""
Return the math words for a language code.
The language_code should be an ISO 639-2 language code.
https://www.loc.gov/standards/iso639-2/php/code_list.php
"""
word_groups = word_groups_for_language(language_code)
words = []
for group in word_g... | 0.002551 |
def __init(self,code):
"""Initialize a `MucStatus` element from a status code.
:Parameters:
- `code`: the status code.
:Types:
- `code`: `int`
"""
code=int(code)
if code<0 or code>999:
raise ValueError("Bad status code")
self.c... | 0.021341 |
def _makepass(password, hasher='sha256'):
'''
Create a znc compatible hashed password
'''
# Setup the hasher
if hasher == 'sha256':
h = hashlib.sha256(password)
elif hasher == 'md5':
h = hashlib.md5(password)
else:
return NotImplemented
c = "abcdefghijklmnopqrstu... | 0.001618 |
def find_start_point(self):
"""
Find the first location in our array that is not empty
"""
for i, row in enumerate(self.data):
for j, _ in enumerate(row):
if self.data[i, j] != 0: # or not np.isfinite(self.data[i,j]):
return i, j | 0.006452 |
def value(self):
"""Read-only property containing data returned from function."""
if self.ready is True:
flag, load = self.__queue.get()
if flag:
return load
raise load | 0.008475 |
def write_section(self, name, features, info, f):
"""Provides formatting for one section (e.g. hydrogen bonds)"""
if not len(info) == 0:
f.write('\n\n### %s ###\n' % name)
f.write('%s\n' % '\t'.join(features))
for line in info:
f.write('%s\n' % '\t'.jo... | 0.0059 |
def login(self, username: str, password: str, course: int) -> requests.Response:
"""
登入課程
"""
try:
# 操作所需資訊
payload = {
'name': username,
'passwd': password,
'rdoCourse': course
}
# 回傳嘗試登入的回應
... | 0.005906 |
def keys_delete(cls, fqdn, key):
"""Delete a key for a domain."""
return cls.json_delete('%s/domains/%s/keys/%s' %
(cls.api_url, fqdn, key)) | 0.010695 |
def del_character(self, name):
"""Remove the Character from the database entirely.
This also deletes all its history. You'd better be sure.
"""
self.query.del_character(name)
self.del_graph(name)
del self.character[name] | 0.007407 |
def remove(self, *rules, _validate=True):
# type: (Iterable[Type[Rule]], bool) -> None
"""
Remove rules from the set.
:param rules: Rules to remove.
:param _validate: True if the rule should be validated before deleting.
This parameter is only for internal use.
:r... | 0.002846 |
def update_file(filename, items):
'''Edits the given file in place, replacing any instances of {key} with the
appropriate value from the provided items dict. If the given filename ends
with ".xml" values will be quoted and escaped for XML.
'''
# TODO: Implement something in the templates to denote w... | 0.001224 |
def parse(source, handler):
'''
Convert XML 1.0 to MicroXML
source - XML 1.0 input
handler - MicroXML events handler
Returns uxml, extras
uxml - MicroXML element extracted from the source
extras - information to be preserved but not part of MicroXML, e.g. namespaces
'''
h = expat_... | 0.003026 |
def recursive_xy_divide(elems, avg_font_size):
"""
Recursively group/divide the document by white stripes
by projecting elements onto alternating axes as intervals.
avg_font_size: the minimum gap size between elements below
which we consider interval continuous.
"""
log = logging.getLogger(... | 0.000504 |
def yaml_to_dict(yaml_str=None, str_or_buffer=None, ordered=False):
"""
Load YAML from a string, file, or buffer (an object with a .read method).
Parameters are mutually exclusive.
Parameters
----------
yaml_str : str, optional
A string of YAML.
str_or_buffer : str or file like, opt... | 0.001006 |
def decode(self, string, legacy=False):
"""
Decode a string according to the current alphabet into a UUID
Raises ValueError when encountering illegal characters
or a too-long string.
If string too short, fills leftmost (MSB) bits with 0.
Pass `legacy=True` if your UUID ... | 0.003906 |
def parse(readDataInstance):
"""
Returns a new L{TLSDirectory} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object containing data to create a new L{TLSDirectory} object.
@rtype: L{TLSDirectory}
@return: A new {TLSDi... | 0.007229 |
def perf_total(self, value):
"""The perf_total property.
Args:
value (string). the property value.
"""
if value == self._defaults['perfTotal'] and 'perfTotal' in self._values:
del self._values['perfTotal']
else:
self._values['perfTotal... | 0.012121 |
def clear_git_lock(role, remote=None, **kwargs):
'''
.. versionadded:: 2015.8.2
Remove the update locks for Salt components (gitfs, git_pillar, winrepo)
which use gitfs backend code from salt.utils.gitfs.
.. note::
Running :py:func:`cache.clear_all <salt.runners.cache.clear_all>` will
... | 0.000978 |
def get_labels(self, request_data, project=None, top=None, skip=None):
"""GetLabels.
Get a collection of shallow label references.
:param :class:`<TfvcLabelRequestData> <azure.devops.v5_0.tfvc.models.TfvcLabelRequestData>` request_data: labelScope, name, owner, and itemLabelFilter
:param... | 0.005116 |
def dependent_on_composite_state(self, job_record):
""" :return instance of <NodesCompositeState> """
assert isinstance(job_record, Job)
tree = self.get_tree(job_record.process_name)
node = tree.get_node(job_record.process_name, job_record.timeperiod)
return node.dependent_on_com... | 0.005988 |
def load_config(cls):
""" Load global and local configuration files and update if needed."""
config_file = os.path.expanduser(cls.home_config)
global_conf = cls.load(config_file, 'global')
cls.load(cls.local_config, 'local')
# update global configuration if needed
cls.upd... | 0.005618 |
def _handle_one(self):
"""
Handle one read/write cycle.
"""
ready_to_read, ready_to_write, in_error = select.select(
[self.request], [self.request], [self.request], 0.1)
if in_error:
raise self.Disconnect()
# Write any commands to the client
... | 0.003636 |
def create_date(past=False, max_years_future=10, max_years_past=10):
"""
Create a random valid date
If past, then dates can be in the past
If into the future, then no more than max_years into the future
If it's not, then it can't be any older than max_years_past
"""
if past:
start = ... | 0.004098 |
def asarray(self, key=None, series=None):
"""Return image data of multiple TIFF pages as numpy array.
By default the first image series is returned.
Parameters
----------
key : int, slice, or sequence of page indices
Defines which pages to return as array.
s... | 0.000962 |
def validate(self, size):
"""
Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match
"""
msg = 'scale and array size must match, ' \
'but were s... | 0.008734 |
def match_keyword(self, keyword, string_match_type=DEFAULT_STRING_MATCH_TYPE, match=True):
"""Adds a keyword to match.
Multiple keywords can be added to perform a boolean ``OR`` among
them. A keyword may be applied to any of the elements defined in
this object such as the display name, ... | 0.002104 |
def infer_domain(terms):
"""
Infer the domain from a collection of terms.
The algorithm for inferring domains is as follows:
- If all input terms have a domain of GENERIC, the result is GENERIC.
- If there is exactly one non-generic domain in the input terms, the result
is that domain.
... | 0.00085 |
def rsa_decrypt_base64_encoded_key(rsaprivatekey, enckey):
# type: (cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey,
# str) -> bytes
"""Decrypt an RSA encrypted key encoded as base64
:param rsaprivatekey: RSA private key
:type rsaprivatekey:
cryptography.hazmat.primitives.... | 0.001189 |
def _dens(self,R,z,phi=0.,t=0.):
"""
NAME:
_dens
PURPOSE:
evaluate the density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the densi... | 0.013015 |
def get_data(self, simulation_step=None, error_category=None):
"""
Parameters
----------
simulation_step: if not given, returns a raw report
error_category: if only one argument is specified, swaps dataframe report
"""
if simulation_step is None and error_category... | 0.004425 |
def upper2_for_ramp_wall(self) -> Set[Point2]:
""" Returns the 2 upper ramp points of the main base ramp required for the supply depot and barracks placement properties used in this file. """
if len(self.upper) > 5:
# NOTE: this was way too slow on large ramps
return set() # HAC... | 0.007067 |
def get_file_row_generator(file_path, separator, encoding=None):
"""
Reads an separated value file row by row.
Inputs: - file_path: The path of the separated value format file.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- encoding: The encoding used in the stored ... | 0.003436 |
def pretty_print (obj, indent=False):
"""
pretty print a JSON object
"""
if indent:
return json.dumps(obj, sort_keys=True, indent=2, separators=(',', ': '))
else:
return json.dumps(obj, sort_keys=True) | 0.012605 |
def _handle_auth_success(self, stream, success):
"""Handle successful authentication.
Send <success/> and mark the stream peer authenticated.
[receiver only]
"""
if not self._check_authorization(success.properties, stream):
element = ElementTree.Element(FAILURE_TAG)... | 0.002625 |
def _updateHiddenStateTrajectories(self):
"""Sample a new set of state trajectories from the conditional distribution P(S | T, E, O)
"""
self.model.hidden_state_trajectories = list()
for trajectory_index in range(self.nobs):
hidden_state_trajectory = self._sampleHiddenStateT... | 0.010823 |
def _event(self, event):
"""Converts a TraceEvent proto into a catapult trace event python value."""
result = dict(
pid=event.device_id,
tid=event.resource_id,
name=event.name,
ts=event.timestamp_ps / 1000000.0)
if event.duration_ps:
result['ph'] = _TYPE_COMPLETE
... | 0.011706 |
def hashsum(filename):
"""Return a hash of the file From <http://stackoverflow.com/a/7829658>"""
with open(filename, mode='rb') as f:
d = hashlib.sha1()
for buf in iter(partial(f.read, 2**20), b''):
d.update(buf)
return d.hexdigest() | 0.00365 |
def track_name_event(self, name):
"""Return the bytes for a track name meta event."""
l = self.int_to_varbyte(len(name))
return '\x00' + META_EVENT + TRACK_NAME + l + name | 0.015385 |
def add_columns(tree_view, df_py_dtypes, list_store):
'''
Add columns to a `gtk.TreeView` for the types listed in `df_py_dtypes`.
Args:
tree_view (gtk.TreeView) : Tree view to append columns to.
df_py_dtypes (pandas.DataFrame) : Data frame containing type
information for one or... | 0.000668 |
def tr(text, kword, color):
""" tr(text, keyword, color)
"""
return re.sub(kword, colorize(BgColor.Null, Base.Null, color, kword), text) | 0.006757 |
def to_png_file(self, fname: str):
"""
write a '.png' file.
"""
cmd = pipes.Template()
cmd.append('dot -Tpng > %s' % fname, '-.')
with cmd.open('pipefile', 'w') as f:
f.write(self.to_dot()) | 0.008032 |
def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False):
"""
Run Processor.
"""
g = ctx.obj
Processor = load_cls(None, None, processor_cls)
processor = Processor(projectdb=g.projectdb,
inqueue=g.fetcher2processor, status_queu... | 0.005814 |
def getStreamNetworkAsGeoJson(self, session, withNodes=True):
"""
Retrieve the stream network geometry in GeoJSON format.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database
withNodes (bool, optional): Includ... | 0.001341 |
def _get_section(self, section, count):
"""Read the next I{count} records from the wire data and add them to
the specified section.
@param section: the section of the message to which to add records
@type section: list of dns.rrset.RRset objects
@param count: the number of record... | 0.003104 |
def get_relevant_versions(self, package_name: str):
"""Return a tuple: (latest release, latest stable)
If there are different, it means the latest is not a stable
"""
versions = self.get_ordered_versions(package_name)
pre_releases = [version for version in versions if not version... | 0.007194 |
def define_frequencies(Ne, explicitly_antisymmetric=False):
u"""Define all frequencies omega_level, omega, gamma.
>>> from sympy import pprint
>>> pprint(define_frequencies(2), use_unicode=True)
⎛ ⎡ 0 ω₁₂⎤ ⎡ 0 γ₁₂⎤⎞
⎜[ω₁, ω₂], ⎢ ⎥, ⎢ ⎥⎟
⎝ ⎣ω₂₁ 0 ⎦ ⎣γ₂₁ ... | 0.001676 |
def _get_key_alias_from_cache(self, key_arn):
'''
Find a key's alias by looking up its key_arn in the KEY_METADATA
cache. This function will only work after a key has been lookedup by
its alias and is meant as a convenience function for turning an ARN
that's already been looked u... | 0.003868 |
def is_validated(self):
"""
Returns True if this instance is validated.
Note that resolving this property requires a DB query, so if you've a
very large amount of receipts you should prefetch (see django's
``select_related``) the ``validation`` field. Even so, a DB query *may*
... | 0.00241 |
def broadcast(self, gossip_message, message_type, exclude=None):
"""Broadcast gossip messages.
Broadcast the message to all peers unless they are in the excluded
list.
Args:
gossip_message: The message to be broadcast.
message_type: Type of the message.
... | 0.002116 |
def imageToColor(url: str, scale=200, mode='rgb'):
"""将 url 指向的图片提纯为一个颜色"""
from PIL import Image
import colorsys
if url:
response = urllib.request.urlopen(url)
img_buffer = io.BytesIO(response.read())
img = Image.open(img_buffer)
img = img... | 0.001451 |
def index(ref_file, out_dir, data):
"""Create a STAR index in the defined reference directory.
"""
(ref_dir, local_file) = os.path.split(ref_file)
gtf_file = dd.get_gtf_file(data)
if not utils.file_exists(gtf_file):
raise ValueError("%s not found, could not create a star index." % (gtf_file)... | 0.004484 |
def export(string, template=None, **extra):
"""
Decorator for registering view functions and adding
templates to it.
"""
def wrapped(f):
endpoint = (f.__module__ + "." + f.__name__)[16:]
if template is not None:
old_f = f
def f(**kwargs):
rv ... | 0.001543 |
def det_lognl(self, det):
"""Returns the log likelihood of the noise in the given detector.
Parameters
----------
det : str
The name of the detector.
Returns
-------
float :
The log likelihood of the noise in the requested detector.
... | 0.003413 |
def show(self, text):
"""
Write the text to the stream and flush immediately.
"""
self.stream.write(text)
self.stream.flush() | 0.011976 |
def context_exists(self, name):
"""Check if a given context exists."""
contexts = self.data['contexts']
for context in contexts:
if context['name'] == name:
return True
return False | 0.008299 |
def get_access_flags_string(self):
"""
Return the access flags string of the field
:rtype: string
"""
if self.access_flags_string == None:
self.access_flags_string = get_access_flags_string(
self.get_access_flags())
if self.access... | 0.006579 |
def zones(self):
"""
:class:`list` of :class:`stravalib.model.ActivityZone` objects for this activity.
"""
if self._zones is None:
self.assert_bind_client()
self._zones = self.bind_client.get_activity_zones(self.id)
return self._zones | 0.010067 |
def _call(self, x, out=None):
"""Calculate the spatial gradient of ``x``."""
if out is None:
out = self.range.element()
x_arr = x.asarray()
ndim = self.domain.ndim
dx = self.domain.cell_sides
for axis in range(ndim):
with writable_array(out[axis]... | 0.00346 |
def bitwise_xor(self, t):
"""
Operation xor
:param t: The other operand.
"""
# Using same variables as in paper
s = self
new_interval = (s.bitwise_not().bitwise_or(t)).bitwise_not().bitwise_or(s.bitwise_or(t.bitwise_not()).bitwise_not())
return new_int... | 0.008902 |
def get_xy_point_from_rgb(self, red_i, green_i, blue_i):
"""Returns an XYPoint object containing the closest available CIE 1931 x, y coordinates
based on the RGB input values."""
red = red_i / 255.0
green = green_i / 255.0
blue = blue_i / 255.0
r = ((red + 0.055) / (1.0... | 0.005597 |
def diversity(layer):
"""Encourage diversity between each batch element.
A neural net feature often responds to multiple things, but naive feature
visualization often only shows us one. If you optimize a batch of images,
this objective will encourage them all to be different.
In particular, it caculuates th... | 0.007993 |
def get_single_int_pk_colname(table_: Table) -> Optional[str]:
"""
If a table has a single-field (non-composite) integer PK, this will
return its database column name; otherwise, None.
Note that it is legitimate for a database table to have both a composite
primary key and a separate ``IDENTITY`` (... | 0.001414 |
def check_solver(self, kwargs_lens, kwargs_ps, kwargs_cosmo={}):
"""
test whether the image positions map back to the same source position
:param kwargs_lens:
:param kwargs_ps:
:return: Euclidean distance between the rayshooting of the image positions
"""
if self.... | 0.009119 |
def get_sitetree():
"""Returns SiteTree (thread-singleton) object, implementing utility methods.
:rtype: SiteTree
"""
sitetree = getattr(_THREAD_LOCAL, _THREAD_SITETREE, None)
if sitetree is None:
sitetree = SiteTree()
setattr(_THREAD_LOCAL, _THREAD_SITETREE, sitetree)
return ... | 0.006098 |
async def status_by_zip(self, zip_code: str) -> dict:
"""Get symptom data for the provided ZIP code."""
try:
location = next((
d for d in await self.user_reports()
if d['zip'] == zip_code))
except StopIteration:
return {}
return aw... | 0.004739 |
def is_country(self, text):
"""Check if a piece of text is in the list of countries"""
ct_list = self._just_cts.keys()
if text in ct_list:
return True
else:
return False | 0.008889 |
def _GetStat(self):
"""Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
"""
stat_object = super(APFSFileEntry, self)._GetStat()
# File data stat information.
stat_object.size = self._fsapfs_file_entry.size
# Ownership and permissions stat information.
... | 0.001299 |
def drop_pathlist(self, pathlist):
"""Drop path list"""
if pathlist:
files = ["r'%s'" % path for path in pathlist]
if len(files) == 1:
text = files[0]
else:
text = "[" + ", ".join(files) + "]"
if self.new_input_line:... | 0.004751 |
def query_params(*frb_fred_params):
"""
Decorator that pops all accepted parameters from method's kwargs and puts
them in the params argument. Modeled after elasticsearch-py client utils strategy.
See https://github.com/elastic/elasticsearch-py/blob/3400179153cc13b6ae2c26734337202569bdfd80/elasticsearch... | 0.007267 |
def handle_request(self, environ, start_response):
"""Retrieves the route handler and calls the handler returning its the response
:param dict environ: The WSGI environment dictionary for the request
:param start_response:
:return: The WbResponse for the request
:rtype: WbRespon... | 0.00423 |
def parse_for_simple_stems(output, skip_empty=False, skip_same_stems=True):
"""
Parses the output stem lines to produce a list with possible stems
for each word in the output.
:param skip_empty: set True to skip lines without stems (default is False)
:returns: a list of tuples, each containing an o... | 0.00203 |
def MeshViewers(
shape=(1, 1), titlebar="Mesh Viewers", keepalive=False,
window_width=1280, window_height=960
):
"""Allows subplot-style inspection of primitives in multiple subwindows.
Args:
shape: a tuple indicating the number of vertical and horizontal windows requested
Returns:... | 0.00311 |
def delta_encode(data, axis=-1, out=None):
"""Encode Delta."""
if isinstance(data, (bytes, bytearray)):
data = numpy.frombuffer(data, dtype='u1')
diff = numpy.diff(data, axis=0)
return numpy.insert(diff, 0, data[0]).tobytes()
dtype = data.dtype
if dtype.kind == 'f':
data... | 0.001704 |
def list_indexes(self):
"""Get a cursor over the index documents for this collection.
>>> for index in db.test.list_indexes():
... print(index)
...
SON([(u'v', 1), (u'key', SON([(u'_id', 1)])),
(u'name', u'_id_'), (u'ns', u'test.test')])
:Retu... | 0.000904 |
def r_dts_collection(self, objectId=None):
""" DTS Collection Metadata reply for given objectId
:param objectId: Collection Identifier
:return: JSON Format of DTS Collection
"""
try:
j = self.resolver.getMetadata(objectId=objectId).export(Mimetypes.JSON.DTS.Std)
... | 0.007813 |
def convert_table(shell_output, delimiter='\t|\s{2,}', output='dict'):
'''
a method to convert a STDOUT shell table into a python data structure
:param shell_output: string from STDOUT with headers
:param delimiter: string with regex pattern delimiting headers
:param output: string wit... | 0.005192 |
def insert(self, i, tab_index):
"""Insert the widget (at tab index) in the position i (index)."""
_id = id(self.editor.tabs.widget(tab_index))
self.history.insert(i, _id) | 0.010152 |
def shutdown(self):
'''Call the dbus proxy to start the shutdown.'''
if self._proxy:
os.sync()
self._proxy(*self._args) | 0.012579 |
def split_func(string):
"""
Take a string like 'requiredIf("arg_name")'
return the function name and the argument:
(requiredIf, arg_name)
"""
ind = string.index("(")
return string[:ind], string[ind+1:-1].strip('"') | 0.004132 |
def _makeResult(self):
"""Return a Result that doesn't print dots.
Nose's ResultProxy will wrap it, and other plugins can still print
stuff---but without smashing into our progress bar, care of
ProgressivePlugin's stderr/out wrapping.
"""
return ProgressiveResult(self._... | 0.004219 |
def subscribe(request):
"""
Takes POST data (``email`` and optional ``next`` fields), submitting the ``email`` field to
the newsletter provider for subscription to a mailing list, and redirecting the user to the value
of ``next`` (this can also be provided in the querystring), or the homepage if no foll... | 0.010828 |
def solvent_per_layer(self):
"""Determine the number of solvent molecules per single layer. """
if self._solvent_per_layer:
return self._solvent_per_layer
assert not (self.solvent_per_lipid is None and self.n_solvent is None)
if self.solvent_per_lipid is not None:
... | 0.004792 |
def evaluate(self, node, filename=None):
"""
Evaluate a source string or node, using ``filename`` when
displaying errors.
"""
if isinstance(node, string_types):
self.source = node
kwargs = {'mode': 'eval'}
if filename:
kwargs['f... | 0.00209 |
def destroy(self):
"""
destroy a client.
"""
logger.info("destroying snap7 client")
if self.library:
return self.library.Cli_Destroy(byref(self.pointer)) | 0.009756 |
def exp(vector):
"""
Computes a per-element exponent of the passed-in vector.
Args:
vector (TYPE): Description
"""
weld_type = None
if isinstance(vector, LazyOpResult):
weld_type = vector.weld_type
vector = vector.expr
elif isinstance(vector, np.ndarray):
wel... | 0.00207 |
def _disks_equal(disk1, disk2):
'''
Test if two disk elements should be considered like the same device
'''
target1 = disk1.find('target')
target2 = disk2.find('target')
source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None
source2 = ElementTree.t... | 0.004498 |
def map2set(data, relation):
"""
EXPECTING A is_data(relation) THAT MAPS VALUES TO lists
THE LISTS ARE EXPECTED TO POINT TO MEMBERS OF A SET
A set() IS RETURNED
"""
if data == None:
return Null
if isinstance(relation, Data):
Log.error("Does not accept a Data")
if is_data... | 0.002525 |
def get_queryset(self):
"""Only display unpublished content to authenticated users, filter by
query parameter if present."""
# Get base queryset from DispatchPublishableMixin
queryset = self.get_publishable_queryset()
queryset = queryset.order_by('-updated_at')
# Optio... | 0.004008 |
def local_attention_1d(q, k, v, block_length=128, filter_width=100, name=None):
"""Strided block local self-attention.
The sequence is divided into blocks of length block_length. Attention for a
given query position can see all memory positions in the corresponding block
and filter_width many positions to the ... | 0.003547 |
def proposals(ctx, account):
""" List proposals
"""
proposals = Proposals(account)
t = PrettyTable(
[
"id",
"expiration",
"proposer",
"required approvals",
"available approvals",
"review period time",
"proposal",... | 0.002092 |
def hkdf_extract(salt, input_key_material, hash=hashlib.sha512):
'''
Extract a pseudorandom key suitable for use with hkdf_expand
from the input_key_material and a salt using HMAC with the
provided hash (default SHA-512).
salt should be a random, application-specific byte string. If
salt is None or the empty str... | 0.025875 |
def setKeySequenceCounter(self, iKeySequenceValue):
""" set the Key sequence counter corresponding to Thread Network master key
Args:
iKeySequenceValue: key sequence value
Returns:
True: successful to set the key sequence
False: fail to set the key sequence
... | 0.006266 |
def get_obj_values(obj, translated_field_names):
"""
get the translated field values from translatable fields of an object
:param obj:
:param translated_field_names:
:return:
"""
# set of translated fields to list
fields = list(translated_field_names)
... | 0.00495 |
def exampleRand(S, A):
"""WARNING: This will delete a database with the same name as 'db'."""
db = "MDP-%sx%s.db" % (S, A)
if os.path.exists(db):
os.remove(db)
conn = sqlite3.connect(db)
with conn:
c = conn.cursor()
cmd = '''
CREATE TABLE info (name TEXT, value IN... | 0.002782 |
def training_loop(hparams, output_dir, report_fn=None, report_metric=None):
"""Run the main training loop."""
if report_fn:
assert report_metric is not None
# Directories
subdirectories = [
"data", "tmp", "world_model", ("world_model", "debug_videos"),
"policy", "eval_metrics"
]
directories... | 0.011438 |
def run(self):
"""Continuously read data from the source and attempt to parse a valid
message from the buffer of bytes. When a message is parsed, passes it
off to the callback if one is set.
"""
message_buffer = b""
while self.running:
try:
mes... | 0.003264 |
def redirect_to_terms_accept(current_path='/', slug='default'):
"""Redirect the user to the terms and conditions accept page."""
redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH))
if slug != 'default':
redirect_url_parts[2] += slug
querystring = QueryDict(redirect_url_parts[4], mutable=True)... | 0.002012 |
def getcombovalue(self, window_name, object_name):
"""
Get current selected combobox value
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, ... | 0.006443 |
def dev_from_index(self, if_index):
"""Return interface name from interface index"""
try:
if_index = int(if_index) # Backward compatibility
return next(iface for iface in six.itervalues(self)
if iface.win_index == if_index)
except (StopIteration, ... | 0.003017 |
def save(self, filename=None):
""" Saves a constructed Morse-Smale Complex in json file
@ In, filename, a filename for storing the hierarchical
merging of features and the base level partitions of the
data
"""
if filename is None:
filename = "morse... | 0.004796 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.