text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def add_from_file(self, filename, handler_decorator=None):
"""
Wrapper around add() that reads the handlers from the
file with the given name. The file is a Python script containing
a list named 'commands' of tuples that map command names to
handlers.
:type filename: st... | 0.001925 |
def get_login_credentials(args):
"""
Gets the login credentials from the user, if not specified while invoking
the script.
@param args: arguments provided to the script.
"""
if not args.username:
args.username = raw_input("Enter Username: ")
if not args.password:
args.password = getpass.ge... | 0.011594 |
def load_bookmarks_without_file(filename):
"""Load all bookmarks but those from a specific file."""
bookmarks = _load_all_bookmarks()
return {k: v for k, v in bookmarks.items() if v[0] != filename} | 0.004785 |
def handle(client_message, handle_event_imap_invalidation=None, handle_event_imap_batch_invalidation=None, to_object=None):
""" Event handler """
message_type = client_message.get_message_type()
if message_type == EVENT_IMAPINVALIDATION and handle_event_imap_invalidation is not None:
key = None
... | 0.005 |
def add_flag_values(self, entry, flag):
''' Adds flag value to applicable compounds '''
if flag in self.flags:
self.flags[flag].append(entry) | 0.011834 |
def tuple_args(fn):
"""
args 파싱 유틸 function
fun(p1, p2, ...pn, **kwargs) or fun([p1, p2, ..], **kwargs)
ex) 샘플::
@tuple_arg
def f(args, **kwargs):
for d in args:
print d
f(1,2,3) => f([1,2,3])
:param function fn:
:return:
"""
@wraps(... | 0.001605 |
def Barr_1981(Re, eD):
r'''Calculates Darcy friction factor using the method in Barr (1981) [2]_
as shown in [1]_.
.. math::
\frac{1}{\sqrt{f_d}} = -2\log\left\{\frac{\epsilon}{3.7D} +
\frac{4.518\log(\frac{Re}{7})}{Re\left[1+\frac{Re^{0.52}}{29}
\left(\frac{\epsilon}{D}\right)^{0.7... | 0.001516 |
def count_markers_samples(prefix, file_type):
"""Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple).
"""
# The... | 0.000878 |
def _fake_modifyinstance(self, namespace, **params):
"""
Implements a server responder for
:meth:`~pywbem.WBEMConnection.CreateInstance`
Modify a CIM instance in the local repository.
Raises:
CIMError: CIM_ERR_ALREADY_EXISTS, CIM_ERR_INVALID_CLASS
"""
... | 0.000294 |
def get_name_by_preorder( self, preorder_hash ):
"""
Given a name preorder hash, get the associated name record.
(It may be expired or revoked)
"""
cur = self.db.cursor()
return namedb_get_name_by_preorder_hash( cur, preorder_hash ) | 0.021429 |
def putstats(pfile, handle, statdicts):
""" puts stats from pickles into a dictionary """
## load in stats
with open(pfile, 'r') as infile:
filestats, samplestats = pickle.load(infile)
## get dicts from statdicts tuple
perfile, fsamplehits, fbarhits, fmisses, fdbars = statdicts
## pul... | 0.009434 |
def build_schema(self, fields):
"""
Build the schema from fields.
:param fields: A list of fields in the index
:returns: list of dictionaries
Each dictionary has the keys
field_name: The name of the field index
type: what type of value it is
'multi_va... | 0.001141 |
def convert_dense(builder, layer, input_names, output_names, keras_layer):
"""Convert a dense layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output... | 0.030303 |
def layer_permutation(self, layer_partition, layout, qubit_subset):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on Sergey Bravyi's algorithm.
The layer_partitio... | 0.001139 |
def _EccZmaxRperiRap(self,*args,**kwargs):
"""
NAME:
EccZmaxRperiRap (_EccZmaxRperiRap)
PURPOSE:
evaluate the eccentricity, maximum height above the plane, peri- and apocenter in the Staeckel approximation
INPUT:
Either:
a) R,vR,vT,z,vz[,phi... | 0.025217 |
def access_token(self):
"""
Retrieve and cache an access token to authenticate API calls.
:return: An access token string.
"""
if self._cached_access_token is not None:
return self._cached_access_token
resp = self._request(endpoint='access_token', data={'grant... | 0.005556 |
def load_coef(filename):
"""Loads a file that was saved with save_coef."""
with open(filename) as f:
lines = f.readlines()
lst = lines[0].split(',')
nmax = int(lst[0])
mmax = int(lst[1])
L = (nmax + 1) + mmax * (2 * nmax - mmax + 1);
vec = np.zeros(L, dt... | 0.008636 |
def get_item_size(self, content):
"""
Get the max size (width and height) for the elements of a list of
strings as a QLabel.
"""
strings = []
if content:
for rich_text in content:
label = QLabel(rich_text)
label.setTextFormat(Qt... | 0.004049 |
def _datastore_api(self):
"""Getter for a wrapped API object."""
if self._datastore_api_internal is None:
if self._use_grpc:
self._datastore_api_internal = make_datastore_api(self)
else:
self._datastore_api_internal = HTTPDatastoreAPI(self)
... | 0.005618 |
def _compute_dynamic_properties(self, builder):
"""Update from the DatasetBuilder."""
# Fill other things by going over the dataset.
splits = self.splits
for split_info in utils.tqdm(
splits.values(), desc="Computing statistics...", unit=" split"):
try:
split_name = split_info.name... | 0.004615 |
def obfn_dfd(self):
r"""Compute data fidelity term :math:`(1/2) \| D X B - S \|_2^2`.
"""
DXBf = sl.dot(self.B, sl.inner(self.Df, self.obfn_fvarf(),
axis=self.cri.axisM),
axis=self.cri.axisC)
Ef = DXBf - self.Sf
retur... | 0.007916 |
def predict_y(self, xq, sigma=None, k=None, **kwargs):
"""Provide an prediction of xq in the output space
@param xq an array of float of length dim_x
"""
sigma = sigma or self.sigma
k = k or self.k
dists, index = self.dataset.nn_x(xq, k = k)
w = self._weights(di... | 0.016355 |
def set_identifiers(self, data):
"""
Sets the identifier(s) within the instance data.
The identifier name(s) is/are determined from the ``ResourceDetails``
instance hanging off the class itself.
:param data: The value(s) to be set.
:param data: dict
"""
... | 0.002564 |
def _to_bel_lines_footer(graph) -> Iterable[str]:
"""Iterate the lines of a BEL graph's corresponding BEL script's footer.
:param pybel.BELGraph graph: A BEL graph
"""
unqualified_edges_to_serialize = [
(u, v, d)
for u, v, d in graph.edges(data=True)
if d[RELATION] in UNQUALIFIE... | 0.000947 |
def origin_west_asia(origin):
"""\
Returns if the origin is located in Western Asia.
Holds true for the following countries:
* Armenia
* Azerbaijan
* Bahrain
* Cyprus
* Georgia
* Iraq
* Israel
* Jordan
* Kuwait
* Lebanon
... | 0.008318 |
def setAnimation(self,obj,animation,transition=None,force=False):
"""
Sets the animation to be used by the object.
See :py:meth:`Actor.setAnimation()` for more information.
"""
self.ensureModelData(obj)
data = obj._modeldata
# Validity check
... | 0.016048 |
def resolve_dependency_graph(self, target):
""" resolves the build order for interdependent build targets
Assumes no cyclic dependencies
"""
targets = self.deep_dependendants(target)
# print "deep dependants:", targets
return sorted(targets,
cmp... | 0.004008 |
def open(self, file_path):
"""
Open a SQLite database file.
:param str file_path: SQLite database file path to open.
"""
from simplesqlite import SimpleSQLite
if self.is_opened():
if self.stream.database_path == abspath(file_path):
self._log... | 0.005545 |
def verify(self):
'''Verifies the message data based on rules and restrictions defined
in the Postmark API docs. There can be no more than 20 recipients
in total. NOTE: This does not check that your attachments total less
than 10MB, you must do that yourself.
'''
if self... | 0.002361 |
def print_error(input, err, scanner):
"""This is a really dumb long function to print error messages nicely."""
p = err.pos
# Figure out the line number
line = input[:p].count('\n')
print err.msg + " on line " + repr(line + 1) + ":"
# Now try printing part of the line
text = input[max(p - 80... | 0.001965 |
def get_deep_focus(self, startfrom=None):
"""return the bottom most focussed widget of the widget tree"""
if not startfrom:
startfrom = self.current_buffer
if 'get_focus' in dir(startfrom):
focus = startfrom.get_focus()
if isinstance(focus, tuple):
... | 0.004219 |
def disable_dataset(self, dataset=None, **kwargs):
"""
Disable a 'dataset'. Datasets that are enabled will be computed
during :meth:`run_compute` and included in the cost function
during :meth:`run_fitting`.
If compute is not provided, the dataset will be disabled across all
... | 0.001894 |
def emulate(self, instruction):
"""
Emulate a single instruction.
"""
# The emulation might restart if Unicorn needs to bring in a memory map
# or bring a value from Manticore state.
while True:
self.reset()
# Establish Manticore state, potentia... | 0.001701 |
def _force_disconnect_action(self, action):
"""Forcibly disconnect a device.
Args:
action (ConnectionAction): the action object describing what we are
forcibly disconnecting
"""
conn_key = action.data['id']
if self._get_connection_state(conn_key) == ... | 0.002044 |
def list_all_payments(cls, **kwargs):
"""List Payments
Return a list of Payments
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_payments(async=True)
>>> result = thread.get()... | 0.002342 |
def write_summary(all_procs, summary_file):
"""
Write a summary of all run processes to summary_file in tab-delimited
format.
"""
if not summary_file:
return
with summary_file:
writer = csv.writer(summary_file, delimiter='\t', lineterminator='\n')
writer.writerow(('direc... | 0.003333 |
def export(self, **kwargs):
"""
Generate audio file from composition.
:param str. filename: Output filename (no extension)
:param str. filetype: Output file type (only .wav supported for now)
:param integer samplerate: Sample rate of output audio
:param integer channels:... | 0.004005 |
def verify(self, data):
r"""Does the given `data` hash to the digest in this `Multihash`?
>>> import hashlib
>>> data = b'foo'
>>> hash = hashlib.sha1(data)
>>> mh = Multihash.from_hash(hash)
>>> mh.verify(data)
True
>>> mh.verify(b'foobar')
False... | 0.003831 |
def run(self, *args):
"""Remove unique identities or identities from the registry.
By default, it removes the unique identity identified by <identifier>.
To remove an identity, set <identity> parameter.
"""
params = self.parser.parse_args(args)
identifier = params.ident... | 0.00464 |
def integrate_converge(self, crit=1e-4, verbose=True):
"""Integrates the model until model states are converging.
:param crit: exit criteria for difference of iterated
solutions [default: 0.0001]
:type crit: float
:param bool verbos... | 0.004484 |
def removeByIndex(self, index):
"""removes a user from the invitation list by position"""
if index < len(self._invites) -1 and \
index >=0:
self._invites.remove(index) | 0.019417 |
def validate_header(fields, # type: Sequence[FieldSpec]
column_names # type: Sequence[str]
):
# type: (...) -> None
""" Validate the `column_names` according to the specification in
`fields`.
:param fields: The `FieldSpec` objects forming the
... | 0.001053 |
def CIC(M, K):
"""
A functional form implementation of a cascade of integrator comb (CIC) filters.
Parameters
----------
M : Effective number of taps per section (typically the decimation factor).
K : The number of CIC sections cascaded (larger K gives the filter a wider image rejection bandwid... | 0.006635 |
def power_configuration(name, policy=None, delayType=None, delayValue=None):
'''
Ensures that the power configuration is configured on the system. This is
only available on some C-Series servers.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
policy(str): The act... | 0.001209 |
def version_object_and_next(string, retries=0): # type: (str, int) -> VersionThing
"""
Try three parsing strategies, favoring semver, then pep440, then whatev.
:param string:
:return:
"""
if retries > 2:
raise JiggleVersionException(
"Can't parse, ran out of retries: " + uni... | 0.004049 |
def _set_linecard(self, v, load=False):
"""
Setter method for linecard, mapped from YANG variable /global_lc_holder/linecard (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_linecard is considered as a private
method. Backends looking to populate this vari... | 0.00466 |
def set_boolean(self, option, value):
"""Set a boolean option.
Args:
option (str): name of option.
value (bool): value of the option.
Raises:
TypeError: Value must be a boolean.
"""
if not isinstance(value, bool):
... | 0.004728 |
def output_file_name(self):
"""Name of the file where plugin's output should be written to."""
safe_path = re.sub(r":|/", "_", self.source_urn.Path().lstrip("/"))
return "results_%s%s" % (safe_path, self.output_file_extension) | 0.004184 |
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
if n:
for i in xrange(0, len(l), n):
yield l[i:i + n] | 0.013793 |
def fitNull(self, init_method='emp_cov'):
""" fit null model """
self.null = self.mtSet1.fitNull(cache=False, factr=self.factr, init_method=init_method)
self.null['NLL'] = self.null['NLL0']
self.mtSet2.null = copy.copy(self.null)
return self.null | 0.01049 |
def get_probability_grammar(self):
"""
A method that returns probability grammar
"""
# Creating valid word expression for probability, it is of the format
# wor1 | var2 , var3 or var1 var2 var3 or simply var
word_expr = Word(alphanums + '-' + '_') + Suppress(Optional("|")... | 0.005976 |
def planner(self, *, resource=''):
""" Get an instance to read information from Microsoft planner """
if not isinstance(self.protocol, MSGraphProtocol):
# TODO: Custom protocol accessing OneDrive/Sharepoint Api fails here
raise RuntimeError(
'planner api only wor... | 0.007353 |
def modify_db_instance(DBInstanceIdentifier=None, AllocatedStorage=None, DBInstanceClass=None, DBSubnetGroupName=None, DBSecurityGroups=None, VpcSecurityGroupIds=None, ApplyImmediately=None, MasterUserPassword=None, DBParameterGroupName=None, BackupRetentionPeriod=None, PreferredBackupWindow=None, PreferredMaintenanceW... | 0.003689 |
def timelines(fig, y, xstart, xstop, color='b'):
"""Plot timelines at y from xstart to xstop with given color."""
fig.hlines(y, xstart, xstop, color, lw=4)
fig.vlines(xstart, y+0.03, y-0.03, color, lw=2)
fig.vlines(xstop, y+0.03, y-0.03, color, lw=2) | 0.003759 |
def decode_values(fct):
''' Decode base64 encoded responses from Consul storage '''
def inner(*args, **kwargs):
''' decorator '''
data = fct(*args, **kwargs)
if 'error' not in data:
for result in data:
result['Value'] = base64.b64decode(result['Value'])
... | 0.002857 |
def _write_bond_information(xml_file, structure, ref_distance, ref_energy):
"""Write the bonds in the system.
Parameters
----------
xml_file : file object
The file object of the hoomdxml file being written
structure : parmed.Structure
Parmed structure object
ref_distance : float... | 0.00138 |
def clear(self, domain=None, path=None, name=None):
"""Clear some cookies.
Invoking this method without arguments will clear all cookies. If
given a single argument, only cookies belonging to that domain will be
removed. If given two arguments, cookies belonging to the specified
... | 0.001817 |
def write(self):
"""
Writes the ``.sln`` file to disk.
"""
filters = {
'MSGUID': lambda x: ('{%s}' % x).upper(),
'relslnfile': lambda x: os.path.relpath(x, os.path.dirname(self.FileName))
}
context = {
'sln': self
}
retu... | 0.010204 |
def delete_ptr_records(self, device, ip_address=None):
"""
Deletes the PTR records for the specified device. If 'ip_address' is
supplied, only the PTR records with that IP address will be deleted.
"""
device_type = self._resolve_device_type(device)
href, svc_name = self._... | 0.00578 |
def _convert_ftp_time_to_iso(ftp_time):
"""
Convert datetime in the format 20160705042714 to a datetime object
:return: datetime object
"""
date_time = datetime(
int(ftp_time[:4]), int(ftp_time[4:6]), int(ftp_time[6:8]),
int(ftp_time[8:10]), int(ftp_time[... | 0.005333 |
def load(fnames, tag=None, sat_id=None, obs_long=0., obs_lat=0., obs_alt=0.,
TLE1=None, TLE2=None):
"""
Returns data and metadata in the format required by pysat. Finds position
of satellite in both ECI and ECEF co-ordinates.
Routine is directl... | 0.011161 |
def update(self):
"""Monolithic update method.
This method calls the following methods with the dynamic loss scaling.
1. solver.zerograd
2. feed data
3. loss.forward
4. loss.backward
5. comm.all_reduce (if it is specified)
6. solver.update
"""
... | 0.001157 |
def lp_tri(f, fb):
"""
Triangle spectral shape function used by :func:`lp_samp`.
Parameters
----------
f : ndarray containing frequency samples
fb : the bandwidth as a float constant
Returns
-------
x : ndarray of spectrum samples for a single triangle shape
Notes
----... | 0.003252 |
def ensure_node(self, tokens: ParseResults) -> BaseEntity:
"""Turn parsed tokens into canonical node name and makes sure its in the graph."""
if MODIFIER in tokens:
return self.ensure_node(tokens[TARGET])
node = parse_result_to_dsl(tokens)
self.graph.add_node_from_data(node)... | 0.008824 |
def print_details(self):
"""Print torrent details"""
print("Title:", self.title)
print("Category:", self.category)
print("Page: ", self.page)
print("Size: ", self.size)
print("Files: ", self.files)
print("Age: ", self.age)
print("Seeds:", self.seeders)
print("Leechers: ", self.leechers)
print("Magne... | 0.033898 |
def connect(self, server):
"Connects to a server and return a connection id."
if 'connections' not in session:
session['connections'] = {}
session.save()
conns = session['connections']
id = str(len(conns))
conn = Connection(server)
conns[... | 0.004773 |
def cli():
"""
Usage: sugartex [OPTIONS] [TO]
Reads from stdin and writes to stdout. Can have single argument/option only.
When no args or the arg is not from options then run Pandoc SugarTeX filter
that iterates over math blocks.
Options:
--kiwi Same as above but with kiwi flavo... | 0.005 |
def comment_thread(cls, backend, *args, **kwargs):
"""Create a comment thread for the desired backend.
:arg backend: String name of backend (e.g., 'file',
'github', 'redis', etc.).
:arg *args, **kwargs: Arguments to be passed to contructor
... | 0.002509 |
def identification_field_factory(label, error_required):
"""
A simple identification field factory which enable you to set the label.
:param label:
String containing the label for this field.
:param error_required:
String containing the error message if the field is left empty.
""... | 0.004637 |
def getBinary(self):
"""Returns the binary message (so far) with typetags."""
address = OSCArgument(self.address)[1]
typetags = OSCArgument(self.typetags)[1]
return address + typetags + self.message | 0.012987 |
def apmag_at_absmag(H, d, phi=1):
"""
Calculate the apparent magnitude of a TNO given its absolute magnitude H, for a given distance.
:param H: TNO absolute magnitude (unitless)
:param d: barycentric distance (AU)
:param phi: phase angle (0-1, always v close to 1 for TNOs)
:return: apparent mag... | 0.004673 |
def stratified_split(self, test_frac=0.2, seed=-1):
"""
Construct a column that can be used to perform a random stratified split.
:param float test_frac: The fraction of rows that will belong to the "test".
:param int seed: The seed for the random number generator.
:returns: an... | 0.006554 |
def logout(self):
"""Log out of the account."""
self._master_token = None
self._auth_token = None
self._email = None
self._android_id = None | 0.011111 |
def set_bulk_size(size):
"""Set size limit on bulk execution.
Bulk execution bundles many operators to run together.
This can improve performance when running a lot of small
operators sequentially.
Parameters
----------
size : int
Maximum number of operators that can be bundled in ... | 0.001873 |
def supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
"""
unsupported_platform = (sys.platform in ('win32', 'Pocket PC'))
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
if ... | 0.002538 |
def recreate_relationships(self, class_, attribute_name, key):
'''
Recreates one-to-many relationship
'''
iterable = self.record_keeper.foreign_to_many_foreign_map[key]
for foreign_page_id, foreign_page_id_list in iteritems(iterable):
# Assumption: local page has bee... | 0.001194 |
def find_lib_path():
"""Find MXNet dynamic library files.
Returns
-------
lib_path : list(string)
List of all found path to the libraries.
"""
lib_from_env = os.environ.get('MXNET_LIBRARY_PATH')
if lib_from_env:
if os.path.isfile(lib_from_env):
if not os.path.isa... | 0.004267 |
def execute_no_results(self, sock_info, generator):
"""Execute all operations, returning no results (w=0).
"""
if self.uses_collation:
raise ConfigurationError(
'Collation is unsupported for unacknowledged writes.')
if self.uses_array_filters:
rais... | 0.000995 |
def variant_to_list(obj):
"""
Return a list containing the descriptors in the given object.
The ``obj`` can be a list or a set of descriptor strings, or a Unicode string.
If ``obj`` is a Unicode string, it will be split using spaces as delimiters.
:param variant obj: the object to be parsed
... | 0.00813 |
def _handle_zeros_in_scale(scale, copy=True):
"""
Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features.
"""
# if we are fitting on 1D arrays, scale might be a scalar
if numpy.isscalar(scale):
if scale == .0:
... | 0.001821 |
def clips_value(self, dvalue):
"""Convert a Python type into CLIPS."""
try:
return VALUES[type(dvalue)](self._env, dvalue)
except KeyError:
if isinstance(dvalue, (list, tuple)):
return self.list_to_multifield(dvalue)
if isinstance(dvalue, (clip... | 0.004065 |
def __cost(self, params, phase, X):
"""Computes activation, cost function, and derivative."""
params = self.__roll(params)
a = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1) # This is a1
calculated_a = [a] # a1 is at index 0, a_n is at index n-1
calculated_z = [0] # There ... | 0.013655 |
def _field_controller_generator(self):
"""
Generates the methods called by the injected controller
"""
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
def get_value(self, name):
# pylint: disable=W0613
"""
... | 0.001736 |
def load(self, data):
""" Load a single row of data and convert it into entities and
relations. """
objs = {}
for mapper in self.entities:
objs[mapper.name] = mapper.load(self.loader, data)
for mapper in self.relations:
objs[mapper.name] = mapper.load(sel... | 0.005865 |
def _parse_new_contract_args(*args, **kwargs):
"""Parse argument for new_contract() function."""
# No arguments
if (not args) and (not kwargs):
return [
{
"name": "argument_invalid",
"msg": "Argument `*[argument_name]*` is not valid",
"type... | 0.002584 |
def make_sa():
"""
Factory to creates a SQLAlchemy queue store, pulling config values from the CoilMQ configuration.
"""
configuration = dict(config.items('coilmq'))
engine = engine_from_config(configuration, 'qstore.sqlalchemy.')
init_model(engine)
store = SAQueue()
return store | 0.00641 |
def function_info(self, functionKey):
"""Returns processed information about the function's name and file."""
node_type = 'function'
filename, line_number, function_name = functionKey
if function_name == '<module>':
modulePath, moduleName = osp.split(filename)
... | 0.003375 |
def receive_ack_requesting(self, pkt):
"""Receive ACK in REQUESTING state."""
logger.debug("C3. Received ACK?, in REQUESTING state.")
if self.process_received_ack(pkt):
logger.debug("C3: T. Received ACK, in REQUESTING state, "
"raise BOUND.")
rais... | 0.005988 |
def _construct_location_stack_entry(location, num_traverses):
"""Return a LocationStackEntry namedtuple with the specified parameters."""
if not isinstance(num_traverses, int) or num_traverses < 0:
raise AssertionError(u'Attempted to create a LocationStackEntry namedtuple with an invalid '
... | 0.005063 |
def lrange(self, key, start, stop):
"""Emulate lrange."""
redis_list = self._get_list(key, 'LRANGE')
start, stop = self._translate_range(len(redis_list), start, stop)
return redis_list[start:stop + 1] | 0.008621 |
def supports_py3(project_name):
"""Check with PyPI if a project supports Python 3."""
log = logging.getLogger("ciu")
log.info("Checking {} ...".format(project_name))
request = requests.get("https://pypi.org/pypi/{}/json".format(project_name))
if request.status_code >= 400:
log = logging.getL... | 0.003135 |
def isosurface_from_data(data, isolevel, origin, spacing):
"""Small wrapper to get directly vertices and faces to feed into programs
"""
spacing = np.array(extent/resolution)
if isolevel >= 0:
triangles = marching_cubes(data, isolevel)
else: # Wrong traingle unwinding roder -- god only knows... | 0.009449 |
def aggregate(self):
"""
Aggregate all reports of the same type into a master report
"""
for report in self.reportset:
printtime('Processing {}'.format(report.split('.')[0]), self.start)
# Initialise the header for each report - MLST is different, as the header is... | 0.003835 |
def parse(self, fo):
"""
Convert MEME output to motifs
Parameters
----------
fo : file-like
File object containing MEME output.
Returns
-------
motifs : list
List of Motif instances.
"""
motifs = []
... | 0.017618 |
def snapshot(self) -> Tuple[Hash32, UUID]:
"""
Perform a full snapshot of the current state.
Snapshots are a combination of the :attr:`~state_root` at the time of the
snapshot and the id of the changeset from the journaled DB.
"""
return self.state_root, self._account_db... | 0.009119 |
def _add_admin(self, app, **kwargs):
"""Add a Flask Admin interface to an application.
:param flask.Flask app: A Flask application
:param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`
:rtype: flask_admin.Admin
"""
from flask_admin import Admi... | 0.003501 |
def seek(self, offset, whence=os.SEEK_SET):
"""Seek to position in stream, see file.seek"""
pos = None
if whence == os.SEEK_SET:
pos = self.offset + offset
elif whence == os.SEEK_CUR:
pos = self.tell() + offset
elif whence == os.SEEK_END:
pos ... | 0.0033 |
def poly(self, return_coeffs=False):
"""returns the quadratic as a Polynomial object."""
p = self.bpoints()
coeffs = (p[0] - 2*p[1] + p[2], 2*(p[1] - p[0]), p[0])
if return_coeffs:
return coeffs
else:
return np.poly1d(coeffs) | 0.00692 |
def _element_charfix(self, element, charcount):
"""Updates the start and end attributes by charcount for the element."""
element.start += charcount
element.docstart += charcount
element.end += charcount
element.docend += charcount | 0.011111 |
def channeldir_node_to_row(self, path_tuple):
"""
Return a dict with keys corresponding to Content.csv columns.
"""
row = dict()
for key in CONTENT_INFO_HEADER:
row[key] = None
row[CONTENT_PATH_KEY] = "/".join(path_tuple) # use / in .csv on Windows and UNIX
... | 0.004902 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.