text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def list_cidr_ips(cidr):
'''
Get a list of IP addresses from a CIDR.
CLI example::
salt myminion netaddress.list_cidr_ips 192.168.0.0/20
'''
ips = netaddr.IPNetwork(cidr)
return [six.text_type(ip) for ip in list(ips)] | 0.003984 |
def get_existing_path(path, topmost_path=None):
"""Get the longest parent path in `path` that exists.
If `path` exists, it is returned.
Args:
path (str): Path to test
topmost_path (str): Do not test this path or above
Returns:
str: Existing path, or None if no path was found.
... | 0.00141 |
def positional_filter(positional_filters, title=''):
'''
a method to construct a conditional filter function to test positional arguments
:param positional_filters: dictionary or list of dictionaries with query criteria
:param title: string with name of function to use instead
:return: callab... | 0.006119 |
def calibrate_percentile_ranks(
self,
peptides=None,
num_peptides_per_length=int(1e5),
alleles=None,
bins=None):
"""
Compute the cumulative distribution of ic50 values for a set of alleles
over a large universe of random peptides, to en... | 0.00142 |
def get_report(self, ledger_id, report_id):
"""Get report info
Arguments:
ledger_id:
Id for ledger for report
report_id:
Report id assigned by mCASH
"""
return self.do_req('GET',
self.merchant_api_base_ur... | 0.004556 |
def class_in_progress(stack=None):
"""True if currently inside a class definition, else False."""
if stack is None:
stack = inspect.stack()
for frame in stack:
statement_list = frame[4]
if statement_list is None:
continue
if statement_list[0].strip().startswith('c... | 0.00271 |
def main(output):
"""
Generate a c7n-org subscriptions config file
"""
client = SubscriptionClient(Session().get_credentials())
subs = [sub.serialize(True) for sub in client.subscriptions.list()]
results = []
for sub in subs:
sub_info = {
'subscription_id': sub['subscrip... | 0.001828 |
def list_healthchecks(self, service_id, version_number):
"""List all of the healthchecks for a particular service and version."""
content = self._fetch("/service/%s/version/%d/healthcheck" % (service_id, version_number))
return map(lambda x: FastlyHealthCheck(self, x), content) | 0.021127 |
def update_time_login(u_name):
'''
Update the login time for user.
'''
entry = TabMember.update(
time_login=tools.timestamp()
).where(
TabMember.user_name == u_name
)
entry.execute() | 0.007634 |
def items(self):
"""D.items() -> a set-like object providing a view on D's items"""
keycol = self._keycol
for row in self.__iter__():
yield (row[keycol], dict(row)) | 0.01 |
def sync_update_price_info(self):
"""Update current price info."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.update_price_info())
loop.run_until_complete(task) | 0.009524 |
def __run_blast_select_loop(input_file, popens, fields):
'''
Run the select(2) loop to handle blast I/O to the given set of Popen
objects.
Yields records back that have been read from blast processes.
'''
def make_nonblocking(f):
fl = fcntl.fcntl(f.fileno(), fcntl.F_GETFL)
fl |... | 0.000677 |
def print_code_table(self, out=sys.stdout):
"""
Print code table overview
"""
out.write(u'bits code (value) symbol\n')
for symbol, (bitsize, value) in sorted(self._table.items()):
out.write(u'{b:4d} {c:10} ({v:5d}) {s!r}\n'.format(
b=bitsize,... | 0.007673 |
def plot1d(self, grid=None, size=64, limits=None, weight=None, figsize=None, f="identity", axes=None, xlabel=None, ylabel=None, **kwargs):
"""Plot the subspace using sane defaults to get a quick look at the data.
:param grid: A 2d numpy array with the counts, if None it will be calculated using limits ... | 0.005263 |
def get_virtual_transactions(blockchain_name, blockchain_opts, first_block_height, last_block_height, tx_filter=None, **hints):
"""
Get the sequence of virtualchain transactions from a particular blockchain over a given range of block heights.
Returns a list of tuples in the format of [(block height, [txs])... | 0.007345 |
def trim_join_unit(join_unit, length):
"""
Reduce join_unit's shape along item axis to length.
Extra items that didn't fit are returned as a separate block.
"""
if 0 not in join_unit.indexers:
extra_indexers = join_unit.indexers
if join_unit.block is None:
extra_block ... | 0.001059 |
def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None):
"""
Function to return a future timestep
"""
future = None
# Initialize variables to 0
dd, hh, mm, ss = [0 for i in range(4)]
if (in_days != None):
dd = dd + in_days
... | 0.010526 |
def _execute_command(cmd, at_time=None):
'''
Helper function to execute the command
:param str cmd: the command to run
:param str at_time: If passed, the cmd will be scheduled.
Returns: bool
'''
if at_time:
cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time))
return ... | 0.002653 |
def GetHostMemKernOvhdMB(self):
'''Undocumented.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetHostMemKernOvhdMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return counter.value | 0.014184 |
def get_params(self):
'''Get the parameters for this object. Returns as a dict.'''
out = {}
out['__class__'] = self.__class__
out['params'] = dict(steps=[])
for name, step in self.steps:
out['params']['steps'].append([name, step.get_params(deep=True)])
ret... | 0.006116 |
def _check_params(ignored_variables, ignored_interactions):
"""Helper for sample methods"""
if ignored_variables is None:
ignored_variables = set()
elif not isinstance(ignored_variables, abc.Container):
ignored_variables = set(ignored_variables)
if ignored_interactions is None:
... | 0.001923 |
def choose_coord_units(header):
"""Return the appropriate key code for the units value for the axes by
examining the FITS header.
"""
cunit = header['CUNIT1']
match = re.match(r'^deg\s*$', cunit)
if match:
return 'degree'
# raise WCSError("Don't understand units '%s'" % (cunit))
... | 0.002976 |
def is_in_expr(expr, find):
"""Returns True if `find` is a subtree of `expr`."""
return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find)) | 0.019108 |
def addTab(self, tab):
"""
Adds a new tab to this panel bar.
:param tab | <XViewPanelItem> || <str>
:return <int>
"""
if not isinstance(tab, XViewPanelItem):
tab = XViewPanelItem(tab, self)
tab.setFixedHeight(self.height())
inde... | 0.004505 |
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None):
"""Wraps Django's reverse to prepend the correct locale."""
prefixer = get_url_prefix()
if prefixer:
prefix = prefix or '/'
url = django_reverse(viewname, urlconf, args, kwargs, prefix)
if prefixer:
url = pref... | 0.002375 |
def sound_speed(self, value):
"""Sets the sound speed in m/s. Default is 1525.0. If this function is
called, `sound_speed_mode` will be set to fixed."""
if not self.sound_speed_mode:
self.sound_speed_mode = 1
self.pdx.SoundSpeed = float(value) | 0.006969 |
def remove_groups(self, group_list):
"""Remove groups from the model.
Members of each group are not removed
from the model (i.e. metabolites, reactions, and genes in the group
stay in the model after any groups containing them are removed).
Parameters
----------
... | 0.002242 |
def dump(self):
""" dump extracted data into a single hdf5file,
:return: None
:Example:
>>> # dump data into an hdf5 formated file
>>> datafields = ['s', 'Sx', 'Sy', 'enx', 'eny']
>>> datascript = 'sddsprintdata.sh'
>>> datapath = './tests/tracking'
>... | 0.002257 |
def ligas(self, query):
""" Retorna o resultado da busca ao Cartola por um determinado termo de pesquisa.
Args:
query (str): Termo para utilizar na busca.
Returns:
Uma lista de instâncias de cartolafc.Liga, uma para cada liga contento o termo utilizado na busca.
... | 0.007874 |
def gpg_profile_put_key( blockchain_id, key_id, key_name=None, immutable=True, txid=None, key_url=None, use_key_server=True, key_server=None, proxy=None, wallet_keys=None, gpghome=None ):
"""
Put a local GPG key into a blockchain ID's global account.
If the URL is not given, the key will be replicated to th... | 0.012833 |
def get_user_id(self, user_id, mount_point='app-id', wrap_ttl=None):
"""GET /auth/<mount_point>/map/user-id/<user_id>
:param user_id:
:type user_id:
:param mount_point:
:type mount_point:
:param wrap_ttl:
:type wrap_ttl:
:return:
:rtype:
"... | 0.004329 |
def _construct_message(self):
"""Build the message params."""
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.subject + "\n"
self.message["text"] += ... | 0.00554 |
def _set_interface_type(self, v, load=False):
"""
Setter method for interface_type, mapped from YANG variable /mpls_state/rsvp/interfaces/interface_type (dcm-interface-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_type is considered as a private
met... | 0.004052 |
def pitch(ax, ay, az):
'''Angle of x-axis relative to ground (theta)
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
pitch: ndarray
Pitch angle in radians
... | 0.002119 |
def logToFile(path, level=logging.INFO):
"""
Create a log handler that logs to the given file.
"""
logger = logging.getLogger()
logger.setLevel(level)
formatter = logging.Formatter(
'%(asctime)s %(name)s %(levelname)s %(message)s')
handler = logging.FileHandler(path)
handler.setF... | 0.002703 |
def h2o_median_absolute_error(y_actual, y_predicted):
"""
Median absolute error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:returns: median absolute error loss (best is 0.0)
"""
ModelBase._check_targets(y_actual, y_predi... | 0.00266 |
def ObjectModifiedEventHandler(obj, event):
"""Object has been modified
"""
# only snapshot supported objects
if not supports_snapshots(obj):
return
# take a new snapshot
take_snapshot(obj, action="edit")
# reindex the object in the auditlog catalog
reindex_object(obj) | 0.003205 |
def resize(image, x, y, stretch=False, top=None, left=None, mode='RGB',
resample=None):
"""Return an image resized."""
if x <= 0:
raise ValueError('x must be greater than zero')
if y <= 0:
raise ValueError('y must be greater than zero')
from PIL import Image
resample = I... | 0.001382 |
def bird(zenith, airmass_relative, aod380, aod500, precipitable_water,
ozone=0.3, pressure=101325., dni_extra=1364., asymmetry=0.85,
albedo=0.2):
"""
Bird Simple Clear Sky Broadband Solar Radiation Model
Based on NREL Excel implementation by Daryl R. Myers [1, 2].
Bird and Hulstrom d... | 0.000418 |
def growth_coefficients(start_date, end_date, ref_date, alpha, samples):
"""
Build a matrix of growth factors according to the CAGR formula y'=y0 (1+a)^(t'-t0).
a growth rate alpha
t0 start date
t' end date
y' output
y0 start value
"""
start_offset = 0
if ref_date < start_dat... | 0.003432 |
def update_items(self, ocean_backend, enrich_backend):
"""Retrieve the commits not present in the original repository and delete
the corresponding documents from the raw and enriched indexes"""
fltr = {
'name': 'origin',
'value': [self.perceval_backend.origin]
}
... | 0.004115 |
def _read_bytes_from_framed_body(self, b):
"""Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes
"""
plaintext = b""
final_frame = Fal... | 0.00468 |
def licenses(source=DEFAULT_LICENSE_FILE):
'''Feed the licenses from a JSON file'''
if source.startswith('http'):
json_licenses = requests.get(source).json()
else:
with open(source) as fp:
json_licenses = json.load(fp)
if len(json_licenses):
log.info('Dropping existi... | 0.000776 |
def from_name(cls, name):
"""Create an author by name, automatically populating the hash."""
return Author(name=name, sha512=cls.hash_name(name)) | 0.01227 |
def get_blocks_in_grimm_from_breakpoint_graph(bg):
"""
:param bg: a breakpoint graph, that contians all the information
:type bg: ``bg.breakpoint_graph.BreakpointGraph``
:return: list of strings, which represent genomes present in breakpoint graph as orders of blocks and is compatible wi... | 0.003846 |
def earningsTodayDF(token='', version=''):
'''Returns earnings that will be reported today as two arrays: before the open bto and after market close amc.
Each array contains an object with all keys from earnings, a quote object, and a headline key.
https://iexcloud.io/docs/api/#earnings-today
Updates a... | 0.00375 |
def update_discount_promotion_by_id(cls, discount_promotion_id, discount_promotion, **kwargs):
"""Update DiscountPromotion
Update attributes of DiscountPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
... | 0.006683 |
def get_package_version(self):
"""
Get the version of the package
:return:
"""
output = subprocess.check_output([
'{}'.format(self.python),
'setup.py',
'--version',
]).decode()
return output.rstrip() | 0.006873 |
def show(uuid):
'''
Show manifest of a given image
uuid : string
uuid of image
CLI Example:
.. code-block:: bash
salt '*' imgadm.show e42f8c84-bbea-11e2-b920-078fab2aab1f
salt '*' imgadm.show plexinc/pms-docker:plexpass
'''
ret = {}
if _is_uuid(uuid) or _is_d... | 0.001381 |
def _get_fstype_from_parser(self, fstype=None):
"""Load fstype information from the parser instance."""
if fstype:
self.fstype = fstype
elif self.index in self.disk.parser.fstypes:
self.fstype = self.disk.parser.fstypes[self.index]
elif '*' in self.disk.parser.fst... | 0.002712 |
def callback_save_indices():
'''Save index from bokeh textinput'''
import datetime
import os
import pylleo
import yamlord
if datadirs_select.value != 'None':
path_dir = os.path.join(parent_input.value, datadirs_select.value)
cal_yaml_path = os.path.join(path_dir, 'cal.yml')
... | 0.003094 |
def logs(self):
""" Returns the list of :class:`~explauto.experiment.log.ExperimentLog`.
.. note:: The logs will be returned as a vector if repeat was set as one in the :meth:`~explauto.experiment.pool.ExperimentPool.run` method else it will be a matrix where each rows represents the n repetitions of a... | 0.008666 |
def getSplits(self, login, tableName, maxSplits):
"""
Parameters:
- login
- tableName
- maxSplits
"""
self.send_getSplits(login, tableName, maxSplits)
return self.recv_getSplits() | 0.004673 |
def _convert_to_config(self):
"""self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
# remove subconfigs list from namespace before transforming the Namespace
if '_flags' in self.parsed_data:
subcs = self.parsed_data._flags
del self.parsed_data._... | 0.004184 |
def stream(self, date_created_from=values.unset, date_created_to=values.unset,
limit=None, page_size=None):
"""
Streams ExecutionInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
... | 0.008526 |
def get_widget(name):
"""
Give back a widget class according to his name.
"""
for widget in registry:
if widget.__name__ == name:
return widget
raise WidgetNotFound(
_('The widget %s has not been registered.') % name) | 0.003774 |
def noise_get_turbulence(
n: tcod.noise.Noise,
f: Sequence[float],
oc: float,
typ: int = NOISE_DEFAULT,
) -> float:
"""Return the turbulence noise sampled from the ``f`` coordinate.
Args:
n (Noise): A Noise instance.
f (Sequence[float]): The point to sample the noise from.
... | 0.001605 |
def readline(self, limit=-1):
"""Read and return a line from the stream.
If limit is specified, at most limit bytes will be read.
"""
if not self._universal and limit < 0:
# Shortcut common case - newline found in buffer.
i = self._readbuffer.find(b'\n', self._o... | 0.001155 |
def get_account_invitation(self, account_id, invitation_id, **kwargs): # noqa: E501
"""Details of a user invitation. # noqa: E501
An endpoint for retrieving the details of an active user invitation sent for a new or an existing user to join the account. **Example usage:** `curl https://api.us-east-... | 0.001439 |
def _words_by_salience_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None, least_to_most=False):
"""Return words in `vocab` ordered by saliency score."""
saliency = get_word_saliency(topic_word_distrib, doc_topic_distrib, doc_lengths)
return _words_by_score(vocab, saliency, least_to_mos... | 0.008798 |
def creation_date(self, value):
"""
The date on which the bond was issued.
:param creation_date:
:return:
"""
self._creation_date = parse(value).date() if isinstance(value, type_check) else value | 0.012346 |
def locate(self, pattern):
'''Find sequences matching a pattern.
:param pattern: Sequence for which to find matches.
:type pattern: str
:returns: Indices of pattern matches.
:rtype: list of ints
'''
if self.circular:
if len(pattern) >= 2 * len(self):... | 0.003205 |
def get_variables_by_attributes(self, **kwargs):
""" Returns variables that match specific conditions.
* Can pass in key=value parameters and variables are returned that
contain all of the matches. For example,
>>> # Get variables with x-axis attribute.
>>> vs = nc.get_variabl... | 0.003203 |
def add_to_fileswitcher(self, plugin, tabs, data, icon):
"""Add a plugin to the File Switcher."""
if self.fileswitcher is None:
from spyder.widgets.fileswitcher import FileSwitcher
self.fileswitcher = FileSwitcher(self, plugin, tabs, data, icon)
else:
se... | 0.004073 |
def show(format, full):
""" Print current allocation to the console. """
# load asset allocation
app = AppAggregate()
app.logger = logger
model = app.get_asset_allocation()
if format == "ascii":
formatter = AsciiFormatter()
elif format == "html":
formatter = HtmlFormatter
... | 0.001965 |
def save(self):
"""
Saves the object. If the object has not been saved before (i.e. it's
new), then a new object is created. Otherwise, any changes are
submitted to the API.
"""
if not self.id:
save_method = Panoptes.client().post
force_reload = F... | 0.002 |
def lookup_api_key_info():
"""Given a dbapi cursor, lookup all the api keys and their information."""
info = {}
with db_connect() as conn:
with conn.cursor() as cursor:
cursor.execute(ALL_KEY_INFO_SQL_STMT)
for row in cursor.fetchall():
id, key, name, groups =... | 0.001976 |
def hosted_number_orders(self):
"""
:rtype: twilio.rest.preview.hosted_numbers.hosted_number_order.HostedNumberOrderList
"""
if self._hosted_number_orders is None:
self._hosted_number_orders = HostedNumberOrderList(self)
return self._hosted_number_orders | 0.009804 |
def red(numbers):
"""Encode the deltas to reduce entropy."""
line = 0
deltas = []
for value in numbers:
deltas.append(value - line)
line = value
return b64encode(compress(b''.join(chr(i).encode('latin1') for i in deltas))).decode('latin1') | 0.059055 |
def main(_):
"""Run the sample attack"""
eps = FLAGS.max_epsilon / 255.0
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
with tf.Graph().as_default():
x_input = tf.placeholder(tf.float32, shape=batch_shape)
noisy_images = x_input + eps * tf.sign(tf.random_normal(batch_shape))... | 0.009615 |
def _sighash_anyone_can_pay(self, index, copy_tx, sighash_type):
'''
int, byte-like, Tx, int -> bytes
Applies SIGHASH_ANYONECANPAY procedure.
Should be called by another SIGHASH procedure.
Not on its own.
https://en.bitcoin.it/wiki/OP_CHECKSIG#Procedure_for_Hashtype_SIGHA... | 0.003226 |
def explore(node):
""" Given a node, explores on relatives, siblings and children
:param node: GraphNode from which to explore
:return: set of explored GraphNodes
"""
explored = set()
explored.add(node)
dfs(node, callback=lambda n: explored.add(n))
return explored | 0.003378 |
def noninteractive_changeset_update(self, fqn, template, old_parameters,
parameters, stack_policy, tags,
**kwargs):
"""Update a Cloudformation stack using a change set.
This is required for stacks with a defined Transform (... | 0.00242 |
def _returnPD(self, code, tablename, **kwargs):
"""
private function to take a sas code normally to create a table, generate pandas data frame and cleanup.
:param code: string of SAS code
:param tablename: the name of the SAS Data Set
:param kwargs:
:return: Pandas Data ... | 0.007593 |
def set_cfg_value(config, section, option, value):
"""Set configuration value."""
if isinstance(value, list):
value = '\n'.join(value)
config[section][option] = value | 0.005376 |
def get_command_line(self):
"""Returns the command line for the job."""
# In python 2, the command line is unicode, which needs to be converted to string before pickling;
# In python 3, the command line is bytes, which can be pickled directly
return loads(self.command_line) if isinstance(self.command_li... | 0.00813 |
def ma_fitplane(bma, gt=None, perc=(2,98), origmask=True):
"""Fit a plane to values in input array
"""
if gt is None:
gt = [0, 1, 0, 0, 0, -1]
#Filter, can be useful to remove outliers
if perc is not None:
from pygeotools.lib import filtlib
bma_f = filtlib.perc_fltr(bma, per... | 0.013757 |
def getCatalogFile(catalog_dir, mc_source_id):
"""
Inputs:
catalog_dir = string corresponding to directory containing the stellar catalog infiles
mc_source_id = integer corresponding the target MC_SOURCE_ID value
Outputs:
catalog_infile = string corresponding to filename of stellar c... | 0.006173 |
def get_items_of_reminder_per_page(self, reminder_id, per_page=1000, page=1):
"""
Get items of reminder per page
:param reminder_id: the reminder id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
... | 0.003914 |
def get_args(get_item):
"""Parse env, key, default out of input dict.
Args:
get_item: dict. contains keys env/key/default
Returns:
(env, key, has_default, default) tuple, where
env: str. env var name.
key: str. save env value to this context key.
has_def... | 0.000844 |
def is_orthogonal(dicoms, log_details=False):
"""
Validate that volume is orthonormal
:param dicoms: check that we have a volume without skewing
"""
first_image_orient1 = numpy.array(dicoms[0].ImageOrientationPatient)[0:3]
first_image_orient2 = numpy.array(dicoms[0].ImageOrientationPatient)[3:6... | 0.003956 |
def _on_loop_end(self, variables):
"""
performs on-loop-end actions like callbacks
variables contains local namespace variables.
Parameters
---------
variables : dict of available variables
Returns
-------
None
"""
for callback i... | 0.006383 |
def _cmp_date(self):
"""Returns Calendar date used for comparison.
Use the earliest date out of all CalendarDates in this instance,
or some date in the future if there are no CalendarDates (e.g.
when Date is a phrase).
"""
dates = sorted(val for val in self.kw.values()
... | 0.004032 |
def Downsampled(cls, stats, interval=None):
"""Constructs a copy of given stats but downsampled to given interval.
Args:
stats: A `ClientStats` instance.
interval: A downsampling interval.
Returns:
A downsampled `ClientStats` instance.
"""
interval = interval or cls.DEFAULT_SAMPL... | 0.001678 |
def ssgsea(data, gene_sets, outdir="ssGSEA_", sample_norm_method='rank', min_size=15, max_size=2000,
permutation_num=0, weighted_score_type=0.25, scale=True, ascending=False, processes=1,
figsize=(7,6), format='pdf', graph_num=20, no_plot=False, seed=None, verbose=False):
"""Run Gene Set Enric... | 0.008009 |
def queue(self, name, url=None, method=None, reservation_sid=None,
post_work_activity_sid=None, **kwargs):
"""
Create a <Queue> element
:param name: Queue name
:param url: Action URL
:param method: Action URL method
:param reservation_sid: TaskRouter Reserv... | 0.004178 |
def make_primitive_extrapolate_ends(cas_coords, smoothing_level=2):
"""Generates smoothed helix primitives and extrapolates lost ends.
Notes
-----
From an input list of CA coordinates, the running average is
calculated to form a primitive. The smoothing_level dictates how
many times to calculat... | 0.000476 |
def can_revert(self):
"""
Return True if we can revert the draft version of the document to the
currently published version.
"""
if self.can_publish:
with self.published_context():
return self.count(Q._uid == self._uid) > 0
return False | 0.006369 |
def bokehjssrcdir(self):
''' The absolute path of the BokehJS source code in the installed
Bokeh source tree.
'''
if self._is_dev or self.debugjs:
bokehjssrcdir = abspath(join(ROOT_DIR, '..', 'bokehjs', 'src'))
if isdir(bokehjssrcdir):
return bok... | 0.005698 |
def setDecel(self, vehID, decel):
"""setDecel(string, double) -> None
Sets the preferred maximal deceleration in m/s^2 for this vehicle.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_DECEL, vehID, decel) | 0.007273 |
def _validate_entries(self, processes, callback=None):
"""
Verify that the actual file contents match the recorded hashes stored in the manifest files
"""
errors = list()
if os.name == 'posix':
worker_init = posix_multiprocessing_worker_initializer
else:
... | 0.003396 |
def as_instruction(self, specification):
"""Convert the specification into an instruction
:param specification: a specification with a key
:data:`knittingpattern.Instruction.TYPE`
The instruction is not added.
.. seealso:: :meth:`add_instruction`
"""
instruct... | 0.00369 |
def _generate_provenance(self):
"""Function to generate provenance at the end of the IF."""
# noinspection PyTypeChecker
hazard = definition(
self._provenance['hazard_keywords']['hazard'])
exposures = [
definition(layer.keywords['exposure']) for layer in self.expo... | 0.00161 |
def get_results():
"""Parse all search result pages."""
base = "http://www.smackjeeves.com/search.php?submit=Search+for+Webcomics&search_mode=webcomics&comic_title=&special=all&last_update=3&style_all=on&genre_all=on&format_all=on&sort_by=2&start=%d"
session = requests.Session()
# store info in a dictio... | 0.004178 |
def update1(self, key: str, data: np.ndarray, size: int) -> None:
""" Update one entry in specific record in datastore """
print(data)
if key in self.get_keys():
self.data[key][data[0]] = data
else:
newdata = np.zeros((size, 6))
newdata[data[0]] = data... | 0.005602 |
def parse(
text = None,
humour = 75
):
"""
Parse input text using various triggers, some returning text and some for
engaging functions. If triggered, a trigger returns text or True if and if
not triggered, returns False. If no triggers are triggered, return False, if
one trigger is tr... | 0.027946 |
def get(self, endpoint, params=None):
"""Send an HTTP GET request to QuadrigaCX.
:param endpoint: API endpoint.
:type endpoint: str | unicode
:param params: URL parameters.
:type params: dict
:return: Response body from QuadrigaCX.
:rtype: dict
:raise qua... | 0.003419 |
def svd_to_stream(uvectors, stachans, k, sampling_rate):
"""
Convert the singular vectors output by SVD to streams.
One stream will be generated for each singular vector level,
for all channels. Useful for plotting, and aiding seismologists thinking
of waveforms!
:type svectors: list
:par... | 0.00063 |
def generate_random_sframe(num_rows, column_codes, random_seed = 0):
"""
Creates a random SFrame with `num_rows` rows and randomly
generated column types determined by `column_codes`. The output
SFrame is deterministic based on `random_seed`.
`column_types` is a string with each character denoti... | 0.006673 |
def readTupleQuotes(self, symbol, start, end):
''' read quotes as tuple '''
if end is None:
end=sys.maxint
session=self.getReadSession()()
try:
rows=session.query(Quote).filter(and_(Quote.symbol == symbol,
... | 0.015504 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.