text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def generate_security_data(self):
"""Generate a dict of security data for "initial" data."""
timestamp = int(time.time())
security_dict = {
'content_type': str(self.target_object._meta),
'object_pk': str(self.target_object._get_pk_val()),
'timestamp': str(time... | 0.004608 |
def clear_cache(self):
"""
Clears any cache associated with the serial model and the engines
seen by the direct view.
"""
self.underlying_model.clear_cache()
try:
logger.info('DirectView results has {} items. Clearing.'.format(
len(self._dv.res... | 0.005988 |
def remove_core_element(self, model):
"""Remove respective core element of handed scoped variable model
:param ScopedVariableModel model: Scoped variable model which core element should be removed
:return:
"""
assert model.scoped_variable.parent is self.model.state
gui_h... | 0.008 |
def load(self, **kwargs):
"""Custom load method to address issue in 11.6.0 Final,
where non existing objects would be True.
"""
if LooseVersion(self.tmos_ver) == LooseVersion('11.6.0'):
return self._load_11_6(**kwargs)
else:
return super(Rule, self)._load... | 0.006061 |
def sort_values(self, by, ascending=True):
"""Sort the DataFrame based on a column.
Unlike Pandas, one can sort by data from both index and regular columns.
Currently possible to sort only on a single column since Weld is missing multiple-column sort.
Note this is an expensive operatio... | 0.003968 |
def sync(self):
"""Sync a bucket.
Force all API calls to S3 and populate the database with the current state of S3.
"""
for key in mimicdb.backend.smembers(tpl.bucket % self.name):
mimicdb.backend.delete(tpl.key % (self.name, key))
mimicdb.backend.delete(tpl.bucket ... | 0.006547 |
def getStreamURL(self, **params):
""" Returns a stream url that may be used by external applications such as VLC.
Parameters:
**params (dict): optional parameters to manipulate the playback when accessing
the stream. A few known parameters include: maxVideoBitrat... | 0.005875 |
def reads_overlapping_variant(
samfile,
variant,
chromosome=None,
use_duplicate_reads=USE_DUPLICATE_READS,
use_secondary_alignments=USE_SECONDARY_ALIGNMENTS,
min_mapping_quality=MIN_READ_MAPPING_QUALITY):
"""
Find reads in the given SAM/BAM file which overlap the ... | 0.000936 |
def video_category(self):
"""doc: http://open.youku.com/docs/doc?id=90
"""
url = 'https://openapi.youku.com/v2/schemas/video/category.json'
r = requests.get(url)
check_error(r)
return r.json() | 0.008333 |
def add(self, component: Union[Component, Sequence[Component]]) -> None:
"""Add a widget to the grid in the next available cell.
Searches over columns then rows for available cells.
Parameters
----------
components : bowtie._Component
A Bowtie widget instance.
... | 0.003802 |
def recv(self, timeout=None):
"""Receive an ISOTP frame, blocking if none is available in the buffer
for at most 'timeout' seconds."""
try:
return self.rx_queue.get(timeout is None or timeout > 0, timeout)
except queue.Empty:
return None | 0.006803 |
def get_or_default_template_file_name(ctx, param, provided_value, include_build):
"""
Default value for the template file name option is more complex than what Click can handle.
This method either returns user provided file name or one of the two default options (template.yaml/template.yml)
depending on... | 0.005482 |
def tx_context_for_idx(self, tx_in_idx):
"""
solution_script: alleged solution to the puzzle_script
puzzle_script: the script protecting the coins
"""
tx_in = self.tx.txs_in[tx_in_idx]
tx_context = TxContext()
tx_context.lock_time = self.tx.lock_time
tx_c... | 0.004354 |
def close(self):
"""Close the queue, signalling that no more data can be put into the queue."""
self.read_queue.put(QueueClosed)
self.write_queue.put(QueueClosed) | 0.016129 |
def get_ad_info(self):
"""
Polls for basic AD information (needed for determine password usage characteristics!)
"""
logger.debug('Polling AD for basic info')
ldap_filter = r'(distinguishedName=%s)' % self._tree
attributes = MSADInfo.ATTRS
for entry in self.pagedsearch(ldap_filter, attributes):
self._l... | 0.031401 |
def add(lhs, rhs):
"""Returns element-wise sum of the input arrays with broadcasting.
Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and
``mx.nd.broadcast_plus(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
... | 0.001183 |
def render(self, flags: Flags) -> List[Text]:
"""
Returns a list of randomly chosen outcomes for each sentence of the
list.
"""
return [x.render(flags) for x in self.sentences] | 0.009259 |
def _get_char(self):
"""Read a character from input.
@rtype: string
"""
if self.ungotten_char is None:
if self.eof:
c = ''
else:
c = self.file.read(1)
if c == '':
self.eof = True
... | 0.004158 |
def _get_offset_front_id_after_onset_sample_idx(onset_sample_idx, offset_fronts):
"""
Returns the offset_front_id which corresponds to the offset front which occurs
first entirely after the given onset sample_idx.
"""
# get all the offset_front_ids
offset_front_ids = [i for i in np.unique(offset... | 0.005291 |
def list(context, sort, limit, where, verbose):
"""list(context, sort, limit, where, verbose)
List all products.
>>> dcictl product list
:param string sort: Field to apply sort
:param integer limit: Max number of rows to return
:param string where: An optional filter criteria
:param boole... | 0.002004 |
def _ram_buffer(self):
"""Setup the RAM buffer from the C++ code."""
# get the address of the RAM
address = _LIB.Memory(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(RAM_VECTOR)).contents
# create a Nu... | 0.005025 |
def sanitize_for_archive(url, headers, payload):
"""Sanitize URL of a HTTP request by removing the token information
before storing/retrieving archived items
:param: url: HTTP url request
:param: headers: HTTP headers request
:param: payload: HTTP payload request
:retur... | 0.004264 |
def t_BIN_STRING(self, t):
r'\'[01]*\'[bB]'
value = t.value[1:-2]
while value and value[0] == '0' and len(value) % 8:
value = value[1:]
# XXX raise in strict mode
# if len(value) % 8:
# raise error.PySmiLexerError("Number of 0s and 1s have to divide by... | 0.007732 |
def accepts(self, tp, converter):
''' Declare that other types may be converted to this property type.
Args:
tp (Property) :
A type that may be converted automatically to this property
type.
converter (callable) :
A function accep... | 0.003407 |
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based ... | 0.00029 |
def _frame_received(self, frame):
"""
Put the frame into the _rx_frames dict with a key of the frame_id.
"""
try:
self._rx_frames[frame["frame_id"]] = frame
except KeyError:
# Has no frame_id, ignore?
pass
_LOGGER.debug("Frame received:... | 0.004405 |
def get_plugin_actions(self):
"""Return a list of actions related to plugin"""
self.new_project_action = create_action(self,
_("New Project..."),
triggered=self.create_new_project)
self.open_project_action = create_acti... | 0.003132 |
def __callbacks(self, msg):
'''this method exists only to make profiling results easier to read'''
if self.callback:
self.callback(msg, *self.callback_args, **self.callback_kwargs) | 0.013636 |
def manage(commands, argv=None, delim=':'):
'''
Parses argv and runs neccessary command. Is to be used in manage.py file.
Accept a dict with digest name as keys and instances of
:class:`Cli<iktomi.management.commands.Cli>`
objects as values.
The format of command is the following::
./... | 0.002459 |
def _create_socket(self):
"""
Creates a new SSL enabled socket and sets its timeout.
"""
log.warning('No certificate check is performed for SSL connections')
s = super(SSL, self)._create_socket()
return wrap_socket(s) | 0.007547 |
def get_tags(name=None,
instance_id=None,
call=None,
location=None,
kwargs=None,
resource_id=None): # pylint: disable=W0613
'''
Retrieve tags for a resource. Normally a VM name or instance_id is passed
in, but a resource_id may be passed inst... | 0.000752 |
def get_edges(self):
"""Get the directed edges from GO term to GO term."""
edge_from_to = []
for parent, children in self.p_from_cs.items():
for child in children:
edge_from_to.append((child, parent))
for parent, children in self.c_from_ps.items():
... | 0.004717 |
def getString(self, config, relation=0):
"""
Return a representation of a Radix according to config.
:param DisplayConfig config: configuration
:param int relation: the relation of this value to actual value
"""
return String(config, self.base).xform(self, relation) | 0.006349 |
def _is_valid_part(self):
"""
Return True if the value of component in attribute "part" is valid,
and otherwise False.
:returns: True if value of component is valid, False otherwise
:rtype: boolean
"""
comp_str = self._encoded_value
# Check if value of ... | 0.004802 |
def start(self):
"""Start the component's event loop (thread-safe).
After the event loop is started the Qt thread calls the
component's :py:meth:`~Component.start_event` method, then calls
its :py:meth:`~Component.new_frame_event` and
:py:meth:`~Component.new_config_event` metho... | 0.002225 |
def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs):
"""
index = index of the locus the bootstrap sample corresponds to - only important if
using recalc=True in kwargs
"""
fit = np.empty((len(boot_collecti... | 0.007239 |
def find_latex_font_serif():
r'''
Find an available font to mimic LaTeX, and return its name.
'''
import os, re
import matplotlib.font_manager
name = lambda font: os.path.splitext(os.path.split(font)[-1])[0].split(' - ')[0]
fonts = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
... | 0.025597 |
def traverse_preorder(self, leaves=True, internal=True):
'''Perform a preorder traversal starting at this ``Node`` object
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`... | 0.009058 |
def _de_casteljau_one_round(nodes, degree, lambda1, lambda2, lambda3):
r"""Performs one "round" of the de Casteljau algorithm for surfaces.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
.. note::
This is a helper function, ... | 0.000466 |
def cli(variant_file, vep, split):
"""Parses a vcf file.\n
\n
Usage:\n
parser infile.vcf\n
If pipe:\n
parser -
"""
from datetime import datetime
from pprint import pprint as pp
if variant_file == '-':
my_parser = VCFParser(fsock=sys.stdin, spl... | 0.005926 |
def update(self, values):
""" Updates this row """
response = self.session.patch(self.build_url(''), data={'values': values})
if not response:
return False
data = response.json()
self.values = data.get('values', self.values)
return True | 0.010135 |
def _report_net_metrics(self, container, tags):
"""Find container network metrics by looking at /proc/$PID/net/dev of the container process."""
if self._disable_net_metrics:
self.log.debug("Network metrics are disabled. Skipping")
return
proc_net_file = os.path.join(cont... | 0.005973 |
def saveDirectory(alias):
"""save a directory to a certain alias/nickname"""
if not settings.platformCompatible():
return False
dataFile = open(settings.getDataFile(), "wb")
currentDirectory = os.path.abspath(".")
directory = {alias : currentDirectory}
pickle.dump(directory, dataFile)
speech.success(alias + " ... | 0.026667 |
def set_meta_all(self, props):
"""Set metadata values for collection.
``props`` a dict with values for properties.
"""
delta_props = self.get_meta()
for key in delta_props.keys():
if key not in props:
delta_props[key] = None
delta_props.updat... | 0.00551 |
def deltas(predicted_values, rewards, mask, gamma=0.99):
r"""Computes TD-residuals from V(s) and rewards.
Where a `delta`, i.e. a td-residual is defined as:
delta_{b,t} = r_{b,t} + \gamma * v_{b,t+1} - v_{b,t}.
Args:
predicted_values: ndarray of shape (B, T+1). NOTE: Expects axis 2 was
squeezed. Th... | 0.008314 |
def select_as_dict(self, table_name, columns=None, where=None, extra=None):
"""
Get data in the database and return fetched data as a
|OrderedDict| list.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_sel... | 0.003168 |
def en_dis_able_interrupts(self, mask):
"""
This callback might be used by a Register to enable/disable Interrupts.
``mask`` is an ``int``, the Interrupts are bits in this mask, the first registered interrupt
has the bit ``(1 << 0)``, the n-th Interrupt the bit ``(1 << (n - 1))``.
If the bit is cleared (``0`... | 0.027559 |
def attach_rconfiguration(context, id, name, topic_id, component_types, data):
"""attach_rconfiguration(context, name, topic_id, component_types, data):
Attach an rconfiguration to a Remote CI
>>> dcictl remoteci-attach-rconfiguration ID [OPTIONS]
:param string id: id of the remoteci
:param strin... | 0.001236 |
def tplot_restore(filename):
"""
This function will restore tplot variables that have been saved with the "tplot_save" command.
.. note::
This function is compatible with the IDL tplot_save routine.
If you have a ".tplot" file generated from IDL, this procedure will restore the data c... | 0.011762 |
def get_staking_leaderboard(self, round_num=0, tournament=1):
"""Retrieves the leaderboard of the staking competition for the given
round.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, option... | 0.001229 |
def withdraw(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#withdraw-funds"""
for required in ['payment_method', 'amount', 'currency']:
if required not in params:
raise ValueError("Missing required parameter: %s" % required)
response = self._po... | 0.006834 |
def mutate(self, mutation, timeout=None, metadata=None, credentials=None):
"""Runs mutate operation."""
return self.stub.Mutate(mutation, timeout=timeout, metadata=metadata,
credentials=credentials) | 0.00813 |
def set(self, item, value):
"""
Set new item in-place. Does not consolidate. Adds new Block if not
contained in the current set of items
"""
# FIXME: refactor, clearly separate broadcasting & zip-like assignment
# can prob also fix the various if tests for sparse/c... | 0.000429 |
def mixins(self, name):
""" Search mixins for name.
Allow '>' to be ignored. '.a .b()' == '.a > .b()'
Args:
name (string): Search term
Returns:
Mixin object list OR False
"""
m = self._smixins(name)
if m:
return m
return... | 0.005556 |
def get_text(self):
"""Return extended progress bar text"""
done_units = to_reasonable_unit(self.done, self.units)
current = round(self.current / done_units['multiplier'], 2)
percent = int(self.current * 100 / self.done)
return '{0:.2f} of {1:.2f} {2} ({3}%)'.format(current,
... | 0.003802 |
def xmlresponse(py_data):
"""
Generates an XML formatted method response for the given python
data.
:param py_data | <variant>
"""
xroot = ElementTree.Element('methodResponse')
xparams = ElementTree.SubElement(xroot, 'params')
xparam = ElementTree.SubElement(xparams, 'param')
... | 0.000769 |
def __dispatch_msg(self, message):
"""Verify the signature and update RequestEvents / perform callbacks
Note messages with an invalid wrapper, invalid hash, invalid sequence number or unexpected clientRef
will be sent to debug_bad callback.
"""
msg = self.__validate_decode_msg(m... | 0.004409 |
def query(input, representation, resolvers=None, **kwargs):
""" Get all results for resolving input to the specified output representation """
apiurl = API_BASE+'/%s/%s/xml' % (urlquote(input), representation)
if resolvers:
kwargs['resolver'] = ",".join(resolvers)
if kwargs:
apiurl+= '?%... | 0.006104 |
def format_to_json(data):
"""Converts `data` into json
If stdout is a tty it performs a pretty print.
"""
if sys.stdout.isatty():
return json.dumps(data, indent=4, separators=(',', ': '))
else:
return json.dumps(data) | 0.003953 |
def remove(name_or_path):
'''Remove an environment'''
click.echo()
try:
r = cpenv.resolve(name_or_path)
except cpenv.ResolveError as e:
click.echo(e)
return
obj = r.resolved[0]
if not isinstance(obj, cpenv.VirtualEnvironment):
click.echo('{} is a module. Use `cp... | 0.00125 |
def _do_east_asian(self):
"""Fetch and update east-asian tables."""
self._do_retrieve(self.EAW_URL, self.EAW_IN)
(version, date, values) = self._parse_east_asian(
fname=self.EAW_IN,
properties=(u'W', u'F',)
)
table = self._make_table(values)
self._... | 0.005236 |
def cint8_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):
return np.fromiter(cptr, dtype=np.int8, count=length)
else:
raise RuntimeError('Expected int pointer') | 0.003559 |
def _software_params_to_argparse(parameters):
"""
Converts a SoftwareParameterCollection into an ArgumentParser object.
Parameters
----------
parameters: SoftwareParameterCollection
The software parameters
Returns
-------
argparse: ArgumentParser
An initialized argument ... | 0.00335 |
def iter_options(grouped_choices, cutoff=None, cutoff_text=None):
"""
Helper function for options and option groups in templates.
"""
class StartOptionGroup(object):
start_option_group = True
end_option_group = False
def __init__(self, label):
self.label = label
... | 0.000702 |
def cif(self):
"""
https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal
:return: a random Spanish CIF
"""
first_chr = random.choice('ABCDEFGHJNPQRSUVW')
doi_body = str(random.randrange(0, 10000000)).zfill(7)
cif = first_chr + doi_body
r... | 0.005495 |
def fastaSubtract(fastaFiles):
"""
Given a list of open file descriptors, each with FASTA content,
remove the reads found in the 2nd, 3rd, etc files from the first file
in the list.
@param fastaFiles: a C{list} of FASTA filenames.
@raises IndexError: if passed an empty list.
@return: An ite... | 0.001129 |
def calc_synch_snu_ujy(b, ne, delta, sinth, width, elongation, dist, ghz, E0=1.):
"""Calculate a flux density from pure gyrosynchrotron emission.
This combines Dulk (1985) equations 40 and 41, which are fitting functions
assuming a power-law electron population, with standard radiative transfer
through... | 0.005036 |
def mirror(self, axes='x', inplace=False):
"""
Generates a symmetry of the Space respect global axes.
:param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'...
:type axes: str
:param inplace: If True, the new ``pyny.Space`` is copied and
added to the current ``... | 0.007715 |
def __do_parse(self, pattern_str):
"""
Parses the given pattern and returns the antlr parse tree.
:param pattern_str: The STIX pattern
:return: The parse tree
:raises ParseException: If there is a parse error
"""
in_ = antlr4.InputStream(pattern_str)
lexe... | 0.001042 |
def put(self, filename, data):
"""Create or update the specified file with the provided data.
"""
# Open the file for writing on the board and write chunks of data.
self._pyboard.enter_raw_repl()
self._pyboard.exec_("f = open('{0}', 'wb')".format(filename))
size = len(dat... | 0.004706 |
def _zoom(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom."
s = 1-1/scale
col_c = s * (2*col_pct - 1)
row_c = s * (2*row_pct - 1)
return _get_zoom_mat(1/scale, 1/scale, col_c, row_c) | 0.034843 |
def integer_decimation(data, decimation_factor):
"""
Downsampling by applying a simple integer decimation.
Make sure that no signal is present in frequency bands above the new
Nyquist frequency (samp_rate/2/decimation_factor), e.g. by applying a
lowpass filter beforehand!
New sampling rate is o... | 0.001211 |
def som_get_capture_objects(som_pointer):
"""!
@brief Returns list of indexes of captured objects by each neuron.
@param[in] som_pointer (c_pointer): pointer to object of self-organized map.
"""
ccore = ccore_library.get()
ccore.som_get_capture_objects.restype = POI... | 0.014583 |
def bytes2human(n, format="%(value).1f%(symbol)s"):
"""
>>> bytes2human(10000)
'9K'
>>> bytes2human(100001221)
'95M'
"""
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i + 1) * 10
for symbol in rev... | 0.001972 |
def _clean_data(api_response):
'''
Returns the DATA response from a Linode API query as a single pre-formatted dictionary
api_response
The query to be cleaned.
'''
data = {}
data.update(api_response['DATA'])
if not data:
response_data = api_response['DATA']
data.upd... | 0.005634 |
def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None):
"""
Extends the q-model loss via the dqfd large-margin loss.
"""
embedding = self.network.apply(x=states, internals=internals, update=update)
deltas = list()
for name in sorted(... | 0.005337 |
def _check_section_underline(cls, section_name, context, indentation):
"""D4{07,08,09,12}, D215: Section underline checks.
Check for correct formatting for docstring sections. Checks that:
* The line that follows the section name contains
dashes (D40{7,8}).
* The a... | 0.000773 |
def map(self, func, iterable, callback=None):
"""A wrapper around the built-in ``map()`` function to provide a
consistent interface with the other ``Pool`` classes.
Parameters
----------
worker : callable
A function or callable object that is executed on each element... | 0.00161 |
def executeTask(self,
inputs,
outSR=None,
processSR=None,
returnZ=False,
returnM=False,
f="json",
method="POST"
):
"""
performs the execute task... | 0.016713 |
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.body:
return '\n'.join(stmt.pretty_str(indent) for stmt in self.body)
else:
... | 0.00554 |
def translate(srcCol, matching, replace):
"""A function translate any character in the `srcCol` by a character in `matching`.
The characters in `replace` is corresponding to the characters in `matching`.
The translate will happen when any character in the string matching with the character
in the `match... | 0.009631 |
def lognormal(mu, sigma, random_state):
'''
mu: float or array_like of floats
sigma: float or array_like of floats
random_state: an object of numpy.random.RandomState
'''
return np.exp(normal(mu, sigma, random_state)) | 0.004149 |
def discharge_coefficient_to_K(D, Do, C):
r'''Converts a discharge coefficient to a standard loss coefficient,
for use in computation of the actual pressure drop of an orifice or other
device.
.. math::
K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2
Parameters
... | 0.004297 |
def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None):
"""Calcuate pct_change of each value to previous entry in group"""
# TODO: Remove this conditional when #23918 is fixed
if freq:
return self.apply(lambda x: x.pct_change(periods=periods,
... | 0.003008 |
def ufloatDict_nominal(self, ufloat_dict):
'This gives us a dictionary of nominal values from a dictionary of uncertainties'
return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.nominal_value, ufloat_dict.values()))) | 0.016736 |
def download(self, attr):
"""
Download an attribute attachment
(if type is malware-sample or attachment only)
:param attr: attribute (should be MispAttribute instance)
:returns: value of the attachment
"""
if attr.type not in ['malware-sample', 'attachment']:
... | 0.006237 |
def bartlett(timeseries, segmentlength, noverlap=None, window=None, plan=None):
# pylint: disable=unused-argument
"""Calculate an PSD of this `TimeSeries` using Bartlett's method
Parameters
----------
timeseries : `~gwpy.timeseries.TimeSeries`
input `TimeSeries` data.
segmentlength : `... | 0.001018 |
def clone_network(network_id, recipient_user_id=None, new_network_name=None, project_id=None, project_name=None, new_project=True, **kwargs):
"""
Create an exact clone of the specified network for the specified user.
If project_id is specified, put the new network in there.
Otherwise create a new ... | 0.00933 |
def log_pdf(self, y, mu, weights=None):
"""
computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights ... | 0.004292 |
def delete_job(job_id, connection=None):
"""Deletes a job.
:param job_id: unique identifier for this job
>>> delete_job('http://example.com/test')
"""
if connection is None:
connection = r
with connection.pipeline() as pipe:
pipe.delete(job_key(job_id))
pipe.zrem(REDIS_... | 0.002817 |
def rasterize(vectorobject, reference, outname=None, burn_values=1, expressions=None, nodata=0, append=False):
"""
rasterize a vector object
Parameters
----------
vectorobject: Vector
the vector object to be rasterized
reference: Raster
a reference Raster object to retrieve geo ... | 0.003813 |
def username_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa")
name_key = ET.SubElement(username, "name")
name_key.text = kwargs.pop('name')
enabl... | 0.00611 |
def run_MDR(n,stack_float,labels=None):
"""run utility function for MDR nodes."""
# need to check that tmp is categorical
x1 = stack_float.pop()
x2 = stack_float.pop()
# check data is categorical
if len(np.unique(x1))<=3 and len(np.unique(x2))<=3:
tmp = np.vstack((x1,x2)).transpose()
... | 0.021467 |
def connect(self):
"""Connect to host
"""
try:
self.client.connect(self.host, username=self.username,
password=self.password, port=self.port,
pkey=self.pkey, timeout=self.timeout)
except sock_gaierror, ex:
rais... | 0.006402 |
def _parallel_compare_helper(class_obj, pairs, x, x_link=None):
"""Internal function to overcome pickling problem in python2."""
return class_obj._compute(pairs, x, x_link) | 0.005556 |
def _needs_evaluation(self) -> bool:
"""
Returns True when:
1. Where clause is not specified
2. Where WHERE clause is specified and it evaluates to True
Returns false if a where clause is specified and it evaluates to False
"""
return self._schema.when is ... | 0.007895 |
def get_modifications(self):
"""Extract Modification INDRA Statements."""
# Find all event frames that are a type of protein modification
qstr = "$.events.frames[(@.type is 'protein-modification')]"
res = self.tree.execute(qstr)
if res is None:
return
# Extrac... | 0.000705 |
def is_valid_uid(uid):
"""
:return: True if it is a valid DHIS2 UID, False if not
"""
pattern = r'^[A-Za-z][A-Za-z0-9]{10}$'
if not isinstance(uid, string_types):
return False
return bool(re.compile(pattern).match(uid)) | 0.003984 |
def listAttachments(self, oid):
""" list attachements for a given OBJECT ID """
url = self._url + "/%s/attachments" % oid
params = {
"f":"json"
}
return self._get(url, params,
securityHandler=self._securityHandler,
... | 0.014778 |
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the servi... | 0.000946 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.