code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _mature(subseq, absolute, c, size=33, total=5000):
"""Create mature sequences around start/end"""
reads = dict()
probs = [0.1, 0.2, 0.4, 0.2, 0.1]
end = 5 + size
error = [-2, -1, 0, 1, 2]
for error5 in error:
for error3 in error:
s = 5 - error5
e = end - erro... | Create mature sequences around start/end |
def ReadItem(self, document_link, options=None):
"""Reads a document.
:param str document_link:
The link to the document.
:param dict options:
The request options for the request.
:return:
The read Document.
:rtype:
dict
... | Reads a document.
:param str document_link:
The link to the document.
:param dict options:
The request options for the request.
:return:
The read Document.
:rtype:
dict |
def show_firmware_version_output_show_firmware_version_control_processor_memory(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show... | Auto Generated Code |
def set_folder(self, folder='assets'):
"""
Changes the file folder to look at
:param folder: str [images, assets]
:return: None
"""
folder = folder.replace('/', '.')
self._endpoint = 'files/{folder}'.format(folder=folder) | Changes the file folder to look at
:param folder: str [images, assets]
:return: None |
def team_billableInfo(self, **kwargs) -> SlackResponse:
"""Gets billable users information for the current team."""
self._validate_xoxp_token()
return self.api_call("team.billableInfo", http_verb="GET", params=kwargs) | Gets billable users information for the current team. |
def restore_from_snapshot(self, volume_id, snapshot_id):
"""Restores a specific volume from a snapshot
:param integer volume_id: The id of the volume
:param integer snapshot_id: The id of the restore point
:return: Returns whether succesfully restored or not
"""
return ... | Restores a specific volume from a snapshot
:param integer volume_id: The id of the volume
:param integer snapshot_id: The id of the restore point
:return: Returns whether succesfully restored or not |
def parallel_beam_geometry(space, num_angles=None, det_shape=None):
r"""Create default parallel beam geometry from ``space``.
This is intended for simple test cases where users do not need the full
flexibility of the geometries, but simply want a geometry that works.
This default geometry gives a full... | r"""Create default parallel beam geometry from ``space``.
This is intended for simple test cases where users do not need the full
flexibility of the geometries, but simply want a geometry that works.
This default geometry gives a fully sampled sinogram according to the
Nyquist criterion, which in gene... |
def handle_directive(self, words):
"""
handles directives: adds the reference and allocates space for the content
"""
refname = words[1]
logging.debug("Handling directive " + str(self.getdirective(words[0])))
logging.debug("First argument is " + str(words[1]))
if(self.getdirective(words[0]).isstatic()):... | handles directives: adds the reference and allocates space for the content |
def get_sub_dsp(self, nodes_bunch, edges_bunch=None):
"""
Returns the sub-dispatcher induced by given node and edge bunches.
The induced sub-dispatcher contains the available nodes in nodes_bunch
and edges between those nodes, excluding those that are in edges_bunch.
The availa... | Returns the sub-dispatcher induced by given node and edge bunches.
The induced sub-dispatcher contains the available nodes in nodes_bunch
and edges between those nodes, excluding those that are in edges_bunch.
The available nodes are non isolated nodes and function nodes that have
all ... |
def from_string(cls, constraint):
"""
:param str constraint: The string representation of a constraint
:rtype: :class:`MarathonConstraint`
"""
obj = constraint.split(':')
marathon_constraint = cls.from_json(obj)
if marathon_constraint:
return maratho... | :param str constraint: The string representation of a constraint
:rtype: :class:`MarathonConstraint` |
def eval_command(self, cmd):
"""
Thread func to allow restarting / stopping of threads, for example
when receiving a connection reset info message from the wss server.
:return:
"""
if cmd == 'restart':
self.restart(soft=True)
elif cmd == 'stop':
... | Thread func to allow restarting / stopping of threads, for example
when receiving a connection reset info message from the wss server.
:return: |
def _module_name(self) -> str:
"""Module name of the wrapped function."""
name = self.f.__module__
if name == '__main__':
return importer.main_module_name()
return name | Module name of the wrapped function. |
def mappedPolygon(self, polygon, path=None, percent=0.5):
"""
Maps the inputed polygon to the inputed path \
used when drawing items along the path. If no \
specific path is supplied, then this object's own \
path will be used. It will rotate and move the \
polygon acco... | Maps the inputed polygon to the inputed path \
used when drawing items along the path. If no \
specific path is supplied, then this object's own \
path will be used. It will rotate and move the \
polygon according to the inputed percentage.
:param polygon <QPo... |
def create_gallery_folder(self, folder_name, scope='content/write'):
"""
Create a new folder in the Mxit user's gallery
User authentication required with the following scope: 'content/write'
"""
return _post(
token=self.oauth.get_user_token(scope),
uri='/u... | Create a new folder in the Mxit user's gallery
User authentication required with the following scope: 'content/write' |
def accept(self):
"""Method invoked when OK button is clicked."""
self.save_state()
self.dock.show_busy()
# The order of the components are matter.
components = self.prepare_components()
error_code, message = self.impact_function.generate_report(
components,... | Method invoked when OK button is clicked. |
def _forward_pass(self, images):
""" Forward pass a list of images through the CNN """
# form image array
num_images = len(images)
if num_images == 0:
return None
for image in images:
if not isinstance(image, Image):
new_images = []
... | Forward pass a list of images through the CNN |
def _get_cifar(directory, url):
"""Download and extract CIFAR to directory unless it is there."""
filename = os.path.basename(url)
path = generator_utils.maybe_download(directory, filename, url)
tarfile.open(path, "r:gz").extractall(directory) | Download and extract CIFAR to directory unless it is there. |
def get_job(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Retrieves the specified job, whose status is OPEN or recently EXPIRED
within the last 90 days.
Examp... | Retrieves the specified job, whose status is OPEN or recently EXPIRED
within the last 90 days.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.JobServiceClient()
>>>
>>> name = client.job_path('[PROJECT]', ... |
def gen_table(self):
"""
This function generates the CRC table used for the table_driven CRC
algorithm. The Python version cannot handle tables of an index width
other than 8. See the generated C code for tables with different sizes
instead.
"""
table_length = 1... | This function generates the CRC table used for the table_driven CRC
algorithm. The Python version cannot handle tables of an index width
other than 8. See the generated C code for tables with different sizes
instead. |
def send(self):
"""Sends the broadcast message.
:returns: tuple of (:class:`adnpy.models.Message`, :class:`adnpy.models.APIMeta`)
"""
parse_links = self.parse_links or self.parse_markdown_links
message = {
'annotations': [],
'entities': {
... | Sends the broadcast message.
:returns: tuple of (:class:`adnpy.models.Message`, :class:`adnpy.models.APIMeta`) |
def is_expanded(request, key):
""" Examines request object to return boolean of whether
passed field is expanded.
"""
expand = request.query_params.get("expand", "")
expand_fields = []
for e in expand.split(","):
expand_fields.extend([e for e in e.split(".")])
return "~all" in ... | Examines request object to return boolean of whether
passed field is expanded. |
def _cache(self, response, key):
"""
Add a retrieved template to the cache for 304 checking
accepts a dict and key name, adds the retrieval time, and adds both
to self.templates as a new dict using the specified key
"""
# cache template and retrieval time for subsequent c... | Add a retrieved template to the cache for 304 checking
accepts a dict and key name, adds the retrieval time, and adds both
to self.templates as a new dict using the specified key |
def load_user():
"""Read user config file and return it as a dict."""
config_path = get_user_config_path()
config = {}
# TODO: This may be overkill and too slow just for reading a config file
with open(config_path) as f:
code = compile(f.read(), config_path, 'exec')
exec(code, config)
... | Read user config file and return it as a dict. |
async def Actions(self, entities):
'''
entities : typing.Sequence[~Entity]
Returns -> typing.Sequence[~ActionResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Action',
request='Actions',
version=2,
... | entities : typing.Sequence[~Entity]
Returns -> typing.Sequence[~ActionResult] |
def open_remote_url(urls, **kwargs):
"""Open the url and check that it stores a file.
Args:
:urls: Endpoint to take the file
"""
if isinstance(urls, str):
urls = [urls]
for url in urls:
try:
web_file = requests.get(url, stream=True, **kwargs)
if 'html'... | Open the url and check that it stores a file.
Args:
:urls: Endpoint to take the file |
def touch(self, edited=False):
"""Mark the node as dirty.
Args:
edited (bool): Whether to set the edited time.
"""
self._dirty = True
dt = datetime.datetime.utcnow()
self.timestamps.updated = dt
if edited:
self.timestamps.edited = dt | Mark the node as dirty.
Args:
edited (bool): Whether to set the edited time. |
def proc_request(self, req):
"""
Pre-process a request through all processors in the stack, in
order. If any processor's proc_request() method returns a
value other than None, that value is treated as a response and
post-processed through the proc_response() methods of the
... | Pre-process a request through all processors in the stack, in
order. If any processor's proc_request() method returns a
value other than None, that value is treated as a response and
post-processed through the proc_response() methods of the
processors preceding that processor in the sta... |
def retrieve_interval(self, start_time, end_time, compute_missing=False):
"""
Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to avoid recomputation.
:param start_time: A datetime for the beginning ... | Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to avoid recomputation.
:param start_time: A datetime for the beginning of the range,
aligned with `bucket_width`.
:param end_time: A datetime for the... |
def filter_threshold(self, inst_rc, threshold, num_occur=1):
'''
Filter the matrix rows or columns based on num_occur values being above a
threshold (in absolute value).
'''
inst_df = self.dat_to_df()
inst_df = run_filter.filter_threshold(inst_df, inst_rc, threshold,
num_occur)
self.... | Filter the matrix rows or columns based on num_occur values being above a
threshold (in absolute value). |
def validate_keys(self, *keys):
"""Validation helper to ensure that keys are present in data
This method makes sure that all of keys received here are
present in the data received from the caller.
It is better to call this method in the `validate()` method of
your event. Not in... | Validation helper to ensure that keys are present in data
This method makes sure that all of keys received here are
present in the data received from the caller.
It is better to call this method in the `validate()` method of
your event. Not in the `clean()` one, since the first will be... |
def is_marginable(self):
"""True if adding counts across this dimension axis is meaningful."""
return self.dimension_type not in {DT.CA, DT.MR, DT.MR_CAT, DT.LOGICAL} | True if adding counts across this dimension axis is meaningful. |
def put(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to PUT"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='PUT', **overrides) | Sets the acceptable HTTP method to PUT |
def are_ilx(self, ilx_ids):
''' Checks list of objects to see if they are usable ILX IDs '''
total_data = []
for ilx_id in ilx_ids:
ilx_id = ilx_id.replace('http', '').replace('.', '').replace('/', '')
data, success = self.get_data_from_ilx(ilx_id)
if success:... | Checks list of objects to see if they are usable ILX IDs |
def meanvR(self,R,t=0.,nsigma=None,deg=False,phi=0.,
epsrel=1.e-02,epsabs=1.e-05,
grid=None,gridpoints=101,returnGrid=False,
surfacemass=None,
hierarchgrid=False,nlevels=2,integrate_method='dopr54_c'):
"""
NAME:
meanvR
PURP... | NAME:
meanvR
PURPOSE:
calculate the mean vR of the velocity distribution at (R,phi)
INPUT:
R - radius at which to calculate the moment(/ro) (can be Quantity)
phi= azimuth (rad unless deg=True; can be Quantity)
t= time at which to evaluate the... |
def serialize(self, obj, level=0, objname=None, topLevelKeysToIgnore=None,
toBytes=True):
"""
Create a string representation of the given object.
Examples:
::
>>> serialize("str")
'str'
>>> serialize([1,2,3,4,5])
'1,2,3,4,5'
>>> ... | Create a string representation of the given object.
Examples:
::
>>> serialize("str")
'str'
>>> serialize([1,2,3,4,5])
'1,2,3,4,5'
>>> signing.serlize({1:'a', 2:'b'})
'1:a|2:b'
>>> signing.serlize({1:'a', 2:'b', 3:[1,{2:'k'}]})
'1:a|2:b|3:... |
def Pack(cls, obj, version):
"""Pack the given object using Ad Manager-specific logic.
Args:
obj: an object to be packed for SOAP using Ad Manager-specific logic, if
applicable.
version: the version of the current API, e.g. 'v201811'
Returns:
The given object packed with Ad Man... | Pack the given object using Ad Manager-specific logic.
Args:
obj: an object to be packed for SOAP using Ad Manager-specific logic, if
applicable.
version: the version of the current API, e.g. 'v201811'
Returns:
The given object packed with Ad Manager-specific logic for SOAP,
... |
def get_dataset(self, key, info):
"""Load a dataset."""
# Read bands
data = self.read_band(key, info)
# Convert to xarray
xdata = xr.DataArray(data, dims=['y', 'x'])
return xdata | Load a dataset. |
def set_expected_length(self, expected_length):
"""stub"""
if not self.my_osid_object_form._is_valid_integer(
expected_length, self.get_expected_length_metadata()):
raise InvalidArgument('expectedLength')
self.my_osid_object_form._my_map['expectedLength'] = expected_l... | stub |
def load_toolbar_item(import_path, *args, **kwargs):
"""
Load an item in the toolbar
:param import_path: the dotted python path to class or function.
:param args: For classes, any arguments to pass to the constructor.
:param kwargs: For classes, any keyword arguments to pass to the constructor.
... | Load an item in the toolbar
:param import_path: the dotted python path to class or function.
:param args: For classes, any arguments to pass to the constructor.
:param kwargs: For classes, any keyword arguments to pass to the constructor. |
async def send_command(self, command):
"""
Sends the given command to the server.
Args:
command (str): Command to send to the server.
Raises:
ConnectionResetError: If the connection with the server is lost.
(Shouldn't it raise BrokenPipeError too ?)
... | Sends the given command to the server.
Args:
command (str): Command to send to the server.
Raises:
ConnectionResetError: If the connection with the server is lost.
(Shouldn't it raise BrokenPipeError too ?) |
def stop(name, call=None):
'''
Stop a VM.
.. versionadded:: 2016.3.0
name
The name of the VM to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop my-vm
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called w... | Stop a VM.
.. versionadded:: 2016.3.0
name
The name of the VM to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop my-vm |
def get_value(record, key, default=None):
"""Return item as `dict.__getitem__` but using 'smart queries'.
.. note::
Accessing one value in a normal way, meaning d['a'], is almost as
fast as accessing a regular dictionary. But using the special
name convention is a bit slower than using... | Return item as `dict.__getitem__` but using 'smart queries'.
.. note::
Accessing one value in a normal way, meaning d['a'], is almost as
fast as accessing a regular dictionary. But using the special
name convention is a bit slower than using the regular access:
.. code-block:: pyth... |
def create_content_instance(content_plugin_class, page, placeholder_name='main', **kwargs):
"""
Creates a content instance from a content plugin class.
:param content_plugin_class: The class of the content plugin.
:param page: The fluent_page instance to create the content
instance one.
:param ... | Creates a content instance from a content plugin class.
:param content_plugin_class: The class of the content plugin.
:param page: The fluent_page instance to create the content
instance one.
:param placeholder_name: The placeholder name defined in the
template. [DEFAULT: main]
:param kwargs: A... |
def run_postdecode_hooks(decode_hook_args, dataset_split):
"""Run hooks after decodes have run."""
hooks = decode_hook_args.problem.decode_hooks
if not hooks:
return
global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir)
if global_step is None:
tf.logging.info(
"Skipping de... | Run hooks after decodes have run. |
def __deal_with_pagination(self, url, method, params, data):
"""
Perform multiple calls in order to have a full list of elements
when the API are "paginated". (content list is divided in more
than one page)
"""
all_data = data
while data.get("links", {... | Perform multiple calls in order to have a full list of elements
when the API are "paginated". (content list is divided in more
than one page) |
def param_texture_from_rasters(script, textName="TEMP3D.png", texsize=1024,
colorCorrection=True, colorCorrectionFilterSize=1,
useDistanceWeight=True, useImgBorderWeight=True,
useAlphaWeight=False, cleanIsolatedTriangles=True,
... | Set texture |
def is_valid(self, csdl):
""" Checks if the given CSDL is valid.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/validate
:param csdl: CSDL to validate
:type csdl: str
:returns: Boolean indicating the validity of the CSDL
:... | Checks if the given CSDL is valid.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/validate
:param csdl: CSDL to validate
:type csdl: str
:returns: Boolean indicating the validity of the CSDL
:rtype: bool
:raises: :clas... |
def ensure_dir_exists(directory):
"Creates local directories if they don't exist."
if directory.startswith('gs://'):
return
if not os.path.exists(directory):
dbg("Making dir {}".format(directory))
os.makedirs(directory, exist_ok=True) | Creates local directories if they don't exist. |
def save_facts(self, path, mode=SaveMode.LOCAL_SAVE):
"""Save the facts in the system to the specified file.
The Python equivalent of the CLIPS save-facts command.
"""
ret = lib.EnvSaveFacts(self._env, path.encode(), mode)
if ret == -1:
raise CLIPSError(self._env)
... | Save the facts in the system to the specified file.
The Python equivalent of the CLIPS save-facts command. |
def show_tooltip(self, title, text, color=_DEFAULT_TITLE_COLOR,
at_line=None, at_position=None, at_point=None):
"""
Show tooltip.
Tooltips will disappear if mouse hovers them. They are meant for quick
inspections.
"""
if text is not None and ... | Show tooltip.
Tooltips will disappear if mouse hovers them. They are meant for quick
inspections. |
def register(self, mimetype, processor):
"""Register passed `processor` for passed `mimetype`."""
if mimetype not in self or processor not in self[mimetype]:
self.setdefault(mimetype, []).append(processor) | Register passed `processor` for passed `mimetype`. |
def deserialize(cls, key, network="bitcoin_testnet"):
"""Load the ExtendedBip32Key from a hex key.
The key consists of
* 4 byte version bytes (network key)
* 1 byte depth:
- 0x00 for master nodes,
- 0x01 for level-1 descendants, ....
... | Load the ExtendedBip32Key from a hex key.
The key consists of
* 4 byte version bytes (network key)
* 1 byte depth:
- 0x00 for master nodes,
- 0x01 for level-1 descendants, ....
* 4 byte fingerprint of the parent's key (0x00000000 if master ke... |
def _lookup(self, fail_on_missing=False, fail_on_found=False, include_debug_header=True, **kwargs):
"""
=====API DOCS=====
Attempt to perform a lookup that is expected to return a single result, and return the record.
This method is a wrapper around `get` that strips out non-unique keys... | =====API DOCS=====
Attempt to perform a lookup that is expected to return a single result, and return the record.
This method is a wrapper around `get` that strips out non-unique keys, and is used internally by
`write` and `delete`.
:param fail_on_missing: Flag that raise exception if ... |
def _validate_key(self, key):
"""
Make sure the supplied key values are within the bounds
specified by the corresponding dimension range and soft_range.
"""
if key == () and len(self.kdims) == 0: return ()
key = util.wrap_tuple(key)
assert len(key) == len(self.kdi... | Make sure the supplied key values are within the bounds
specified by the corresponding dimension range and soft_range. |
def _write_standard(self, message, extra):
'''
Writes a standard log statement
@param message: The message to write
@param extra: The object to pull defaults from
'''
level = extra['level']
if self.include_extra:
del extra['timestamp']
del... | Writes a standard log statement
@param message: The message to write
@param extra: The object to pull defaults from |
def add_task(self, name=None, desc=None):
"""
Adds object to list of grindstone['tasks'].
"""
# A name is required to create a task
for k in self.get_tasks():
if name in keys_of(k):
raise ValueError('Task already exists')
if name is not None:
... | Adds object to list of grindstone['tasks']. |
def del_subkey(self,name):
"""Delete the named subkey, and any values or keys it contains."""
self.sam |= KEY_WRITE
subkey = self.get_subkey(name)
subkey.clear()
_winreg.DeleteKey(subkey.parent.hkey,subkey.name) | Delete the named subkey, and any values or keys it contains. |
def _CaptureRequestLogId(self):
"""Captures the request log id if possible.
The request log id is stored inside the breakpoint labels.
"""
# pylint: disable=not-callable
if callable(request_log_id_collector):
request_log_id = request_log_id_collector()
if request_log_id:
# We ha... | Captures the request log id if possible.
The request log id is stored inside the breakpoint labels. |
def inspect_config(app):
"""Inspect the Sphinx configuration and update for slide-linking.
If links from HTML to slides are enabled, make sure the sidebar
configuration includes the template and add the necessary theme
directory as a loader so the sidebar template can be located.
If the sidebar co... | Inspect the Sphinx configuration and update for slide-linking.
If links from HTML to slides are enabled, make sure the sidebar
configuration includes the template and add the necessary theme
directory as a loader so the sidebar template can be located.
If the sidebar configuration already includes ``s... |
def transform(self, jam):
'''Bypass transformations.
Parameters
----------
jam : pyjams.JAMS
A muda-enabled JAMS object
Yields
------
jam_out : pyjams.JAMS iterator
The first result is `jam` (unmodified), by reference
All subs... | Bypass transformations.
Parameters
----------
jam : pyjams.JAMS
A muda-enabled JAMS object
Yields
------
jam_out : pyjams.JAMS iterator
The first result is `jam` (unmodified), by reference
All subsequent results are generated by `tran... |
def clear(self, match="*", count=1000):
""" :see:meth:RedisMap.clear """
cursor = '0'
pipe = self._client.pipeline(transaction=False)
while cursor != 0:
cursor, keys = self.scan(cursor=cursor, match=match, count=count)
if keys:
pipe.delete(*keys)
... | :see:meth:RedisMap.clear |
def show_instance(instance_id, call=None, kwargs=None):
'''
Show the details from QingCloud concerning an instance.
CLI Examples:
.. code-block:: bash
salt-cloud -a show_instance i-2f733r5n
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance acti... | Show the details from QingCloud concerning an instance.
CLI Examples:
.. code-block:: bash
salt-cloud -a show_instance i-2f733r5n |
def remove_reader(self, fd):
" Remove read file descriptor from the event loop. "
fd = fd_to_int(fd)
if fd in self._read_fds:
del self._read_fds[fd]
self.selector.unregister(fd) | Remove read file descriptor from the event loop. |
def _build_prior(self, prior_tensors):
"""
Build a tf expression for the prior by summing all child-parameter priors.
"""
# TODO(@awav): What prior must represent empty list of parameters?
if not prior_tensors:
return tf.constant(0, dtype=settings.float_type)
... | Build a tf expression for the prior by summing all child-parameter priors. |
def _check_header_lines(self, header_lines):
"""Check header lines, in particular for starting file "##fileformat"
"""
if not header_lines:
raise exceptions.InvalidHeaderException(
"The VCF file did not contain any header lines!"
)
first = header_l... | Check header lines, in particular for starting file "##fileformat" |
def jdn_to_hdate(jdn):
"""Convert from the Julian day to the Hebrew day."""
# calculate Gregorian date
date = jdn_to_gdate(jdn)
# Guess Hebrew year is Gregorian year + 3760
year = date.year + 3760
jdn_tishrey1 = hdate_to_jdn(HebrewDate(year, 1, 1))
jdn_tishrey1_next_year = hdate_to_jdn(Heb... | Convert from the Julian day to the Hebrew day. |
def plot(self, sig_style='', title=None, figsize=None,
return_fig=False):
"""
Plot the comparison of two sets of annotations, possibly
overlaid on their original signal.
Parameters
----------
sig_style : str, optional
The matplotlib style of the ... | Plot the comparison of two sets of annotations, possibly
overlaid on their original signal.
Parameters
----------
sig_style : str, optional
The matplotlib style of the signal
title : str, optional
The title of the plot
figsize: tuple, optional
... |
def parametric_mean_function(max_iters=100, optimize=True, plot=True):
"""
A linear mean function with parameters that we'll learn alongside the kernel
"""
#create simple mean function
mf = GPy.core.Mapping(1,1)
mf.f = np.sin
X = np.linspace(0,10,50).reshape(-1,1)
Y = np.sin(X) + 0.5*n... | A linear mean function with parameters that we'll learn alongside the kernel |
def check_presence_of_mandatory_args(args, mandatory_args):
'''
Checks whether all mandatory arguments are passed.
This function aims at methods with many arguments
which are passed as kwargs so that the order
in which the are passed does not matter.
:args: The dictionary passed as arg... | Checks whether all mandatory arguments are passed.
This function aims at methods with many arguments
which are passed as kwargs so that the order
in which the are passed does not matter.
:args: The dictionary passed as args.
:mandatory_args: A list of keys that have to be
present i... |
def from_torch_layers(cls, module_graph, variable):
"""Recover something like neural net layers from PyTorch Module's and the
compute graph from a Variable.
Example output for a multi-layer RNN. We confusingly assign shared embedding values
to the encoder, but ordered next to the decode... | Recover something like neural net layers from PyTorch Module's and the
compute graph from a Variable.
Example output for a multi-layer RNN. We confusingly assign shared embedding values
to the encoder, but ordered next to the decoder.
rnns.0.linear.module.weight_raw rnns.0
rnns... |
def flatsize(obj, align=0, **opts):
'''Return the flat size of an object (in bytes),
optionally aligned to a given power of 2.
See function **basicsize** for a description of
the other options. See the documentation of
this module for the definition of flat size.
'''
v = _typed... | Return the flat size of an object (in bytes),
optionally aligned to a given power of 2.
See function **basicsize** for a description of
the other options. See the documentation of
this module for the definition of flat size. |
def delete_channel_cb(self, viewer, channel):
"""Called when a channel is deleted from the main interface.
Parameter is channel (a bunch)."""
chname_del = channel.name
# TODO: delete thumbs for this channel!
self.logger.debug("deleting thumbs for channel '%s'" % (chname_del))
... | Called when a channel is deleted from the main interface.
Parameter is channel (a bunch). |
def _load(target, **vars):
""" Fetch something from a module. The exact behaviour depends on the the
target string:
If the target is a valid python import path (e.g. `package.module`),
the rightmost part is returned as a module object.
If the target contains a colon (e.g. `package.m... | Fetch something from a module. The exact behaviour depends on the the
target string:
If the target is a valid python import path (e.g. `package.module`),
the rightmost part is returned as a module object.
If the target contains a colon (e.g. `package.module:var`) the module
vari... |
def add_errors(self, *errors: Union[BaseSchemaError, List[BaseSchemaError]]) -> None:
""" Adds errors to the error repository in schema loader """
self.schema_loader.add_errors(*errors) | Adds errors to the error repository in schema loader |
def check_dependencies():
"""Make sure virtualenv is in the path."""
print 'Checking dependencies...'
if not HAS_VIRTUALENV:
print 'Virtual environment not found.'
# Try installing it via easy_install...
if HAS_EASY_INSTALL:
print 'Installing virtualenv via easy_install.... | Make sure virtualenv is in the path. |
def first(args):
"""
%prog first N fastqfile(s)
Get first N reads from file.
"""
from jcvi.apps.base import need_update
p = OptionParser(first.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
N = int(args[0])
... | %prog first N fastqfile(s)
Get first N reads from file. |
def from_compressed_buffer(cls, compressed_buffer, point_format, count, laszip_vlr):
""" Construct the point record by reading and decompressing the points data from
the input buffer
"""
point_dtype = point_format.dtype
uncompressed = decompress_buffer(
compressed_bu... | Construct the point record by reading and decompressing the points data from
the input buffer |
def step(self, metrics):
""" EarlyStopping step on each epoch
Arguments:
metrics {float} -- metric value
"""
if self.best is None:
self.best = metrics
return False
if np.isnan(metrics):
return True
if self.is_better(metri... | EarlyStopping step on each epoch
Arguments:
metrics {float} -- metric value |
def vcfunpackinfo(table, *keys):
"""
Unpack the INFO field into separate fields. E.g.::
>>> import petl as etl
>>> # activate bio extensions
... import petlx.bio
>>> table1 = (
... etl
... .fromvcf('fixture/sample.vcf', samples=None)
... .vcfu... | Unpack the INFO field into separate fields. E.g.::
>>> import petl as etl
>>> # activate bio extensions
... import petlx.bio
>>> table1 = (
... etl
... .fromvcf('fixture/sample.vcf', samples=None)
... .vcfunpackinfo()
... )
>>> table1
... |
def add_action_rule(self, rule_config_name):
"""
Adds the given action rule to this ruleset's action rules
:param rule_config_name:
:return:
"""
self.logger.debug('Adding action rule {0}'.format(rule_config_name))
# Handle rules that are just a string, like 'stop-... | Adds the given action rule to this ruleset's action rules
:param rule_config_name:
:return: |
def _get_standalone_app_url(self, app_id, spark_master_address, requests_config, tags):
"""
Return the application URL from the app info page on the Spark master.
Due to a bug, we need to parse the HTML manually because we cannot
fetch JSON data from HTTP interface.
"""
a... | Return the application URL from the app info page on the Spark master.
Due to a bug, we need to parse the HTML manually because we cannot
fetch JSON data from HTTP interface. |
def check_for_input_len_diff(*args):
"""
Check for Input Length Difference.
This method checks if multiple data sets that are inputted are all the same
size. If they are not the same length an error is raised with a custom
message that informs the developer that the data set's lengths are not the
... | Check for Input Length Difference.
This method checks if multiple data sets that are inputted are all the same
size. If they are not the same length an error is raised with a custom
message that informs the developer that the data set's lengths are not the
same. |
def _replace_args_with_defaults(self, _args=None, **kwargs):
"""Internal method to fill absent values in the kwargs with the defaults.
Args:
_args: A list of arguments to replace if a subset is required. Name
chosen to prevent conflicts with kwargs.
**kwargs: The arguments to replace with ... | Internal method to fill absent values in the kwargs with the defaults.
Args:
_args: A list of arguments to replace if a subset is required. Name
chosen to prevent conflicts with kwargs.
**kwargs: The arguments to replace with defaults.
Returns:
A map with the same fields as kwargs, b... |
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)... | Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine |
def harmonic_mean(data):
"""Return the harmonic mean of data
"""
if not data:
raise StatisticsError('harmonic_mean requires at least one data point')
divisor = sum(map(lambda x: 1.0 / x if x else 0.0, data))
return len(data) / divisor if divisor else 0.0 | Return the harmonic mean of data |
def glob(self, pat):
"""`pat` can be an extended glob pattern, e.g. `'**/*.less'`
This code handles negations similarly to node.js' minimatch, i.e.
a leading `!` will negate the entire pattern.
"""
r = ""
negate = int(pat.startswith('!'))
i = negate
... | `pat` can be an extended glob pattern, e.g. `'**/*.less'`
This code handles negations similarly to node.js' minimatch, i.e.
a leading `!` will negate the entire pattern. |
def log_type(args_kw, ret, func, slf=False, prop_getter=False, clss=None, argspecs=None,
args_kw_type=None, ret_type = None):
"""Stores information of a function or method call into a cache, so pytypes can
create a PEP 484 stubfile from this information later on (see dump_cache).
"""
if args... | Stores information of a function or method call into a cache, so pytypes can
create a PEP 484 stubfile from this information later on (see dump_cache). |
def parse_args(mixed=None):
"""
Context manager to extract and apply environment related options from the provided argparser result.
A dictionnary with unknown options will be yielded, so the remaining options can be used by the caller.
:api: bonobo.patch_environ
:param mixed: ArgumentParser inst... | Context manager to extract and apply environment related options from the provided argparser result.
A dictionnary with unknown options will be yielded, so the remaining options can be used by the caller.
:api: bonobo.patch_environ
:param mixed: ArgumentParser instance, Namespace, or dict.
:return: |
def write(self, text, add_p_style=True, add_t_style=True):
"""
see mixed content
http://effbot.org/zone/element-infoset.htm#mixed-content
Writing is complicated by requirements of odp to ignore
duplicate spaces together. Deal with this by splitting on
white spaces then d... | see mixed content
http://effbot.org/zone/element-infoset.htm#mixed-content
Writing is complicated by requirements of odp to ignore
duplicate spaces together. Deal with this by splitting on
white spaces then dealing with the '' (empty strings) which
would be the extra spaces |
def build_filtered_queryset(self, query, **kwargs):
"""
Build and return the fully-filtered queryset
"""
# Take the basic queryset
qs = self.get_queryset()
# filter it via the query conditions
qs = qs.filter(self.get_queryset_filters(query))
return self.bu... | Build and return the fully-filtered queryset |
def _set_fcoe_fabric_map_fcmap(self, v, load=False):
"""
Setter method for fcoe_fabric_map_fcmap, mapped from YANG variable /fcoe/fcoe_fabric_map/fcoe_fabric_map_fcmap (fcoe-fcmap-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_fabric_map_fcmap is considered a... | Setter method for fcoe_fabric_map_fcmap, mapped from YANG variable /fcoe/fcoe_fabric_map/fcoe_fabric_map_fcmap (fcoe-fcmap-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_fabric_map_fcmap is considered as a private
method. Backends looking to populate this variabl... |
def get_linked_version(doi):
"""
Get the original link behind the DOI.
:param doi: A canonical DOI.
:returns: The canonical URL behind the DOI, or ``None``.
>>> get_linked_version('10.1209/0295-5075/111/40005')
'http://stacks.iop.org/0295-5075/111/i=4/a=40005?key=crossref.9ad851948a976ecdf216d... | Get the original link behind the DOI.
:param doi: A canonical DOI.
:returns: The canonical URL behind the DOI, or ``None``.
>>> get_linked_version('10.1209/0295-5075/111/40005')
'http://stacks.iop.org/0295-5075/111/i=4/a=40005?key=crossref.9ad851948a976ecdf216d4929b0b6f01' |
def perform_permissions_check(self, user, obj, perms):
""" Performs the permission check. """
return self.request.forum_permission_handler.can_vote_in_poll(obj, user) | Performs the permission check. |
def handle(self, *args, **options):
"""
This management command gets data for a given election date from
elex. Then, it loops through each row of the data and calls
`process_row`.
In order for this command to work, you must have bootstrapped all
of the dependent apps: en... | This management command gets data for a given election date from
elex. Then, it loops through each row of the data and calls
`process_row`.
In order for this command to work, you must have bootstrapped all
of the dependent apps: entity, geography, government, election, vote,
and... |
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... | 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. |
def updateDefaults(self, name, body, verbose=None):
"""
Updates the default values for the Visual Properties in the Visual Style specified by the `name` parameter.
Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.ucsd.e... | Updates the default values for the Visual Properties in the Visual Style specified by the `name` parameter.
Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.ucsd.edu/cytoscape-3.6.1/API/org/cytoscape/view/presentation/property/BasicVis... |
def main():
"""
iodp_samples_magic.py
OPTIONS:
-f FILE, input csv file
-Fsa FILE, output samples file for updating, default is to overwrite existing samples file
"""
if "-h" in sys.argv:
print(main.__doc__)
sys.exit()
dataframe = extractor.command_line_dataframe(... | iodp_samples_magic.py
OPTIONS:
-f FILE, input csv file
-Fsa FILE, output samples file for updating, default is to overwrite existing samples file |
def sine_psd(data, delta, number_of_tapers=None, number_of_iterations=2,
degree_of_smoothing=1.0, statistics=False, verbose=False):
"""
Wrapper method for the sine_psd subroutine in the library by German A.
Prieto.
The subroutine is in charge of estimating the adaptive sine multitaper as
... | Wrapper method for the sine_psd subroutine in the library by German A.
Prieto.
The subroutine is in charge of estimating the adaptive sine multitaper as
in Riedel and Sidorenko (1995). It outputs the power spectral density
(PSD).
This is done by performing a MSE adaptive estimation. First a pilot
... |
def p_expr_unary_op(p):
'''expr : PLUS expr
| MINUS expr
| NOT expr
| BOOLEAN_NOT expr'''
p[0] = ast.UnaryOp(p[1], p[2], lineno=p.lineno(1)) | expr : PLUS expr
| MINUS expr
| NOT expr
| BOOLEAN_NOT expr |
def convert(model, input_features, output_features):
"""Convert a _imputer model to the protobuf spec.
Parameters
----------
model: Imputer
A trained Imputer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Retur... | Convert a _imputer model to the protobuf spec.
Parameters
----------
model: Imputer
A trained Imputer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.