code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _filter_fields(self, filter_function):
"""
Utility to iterate through all fields (super types first) of a type.
:param filter: A function that takes in a Field object. If it returns
True, the field is part of the generated output. If False, it is
omitted.
"""... | Utility to iterate through all fields (super types first) of a type.
:param filter: A function that takes in a Field object. If it returns
True, the field is part of the generated output. If False, it is
omitted. |
def submit(self, stanza):
"""Adds keys to the current configuration stanza as a
dictionary of key-value pairs.
:param stanza: A dictionary of key-value pairs for the stanza.
:type stanza: ``dict``
:return: The :class:`Stanza` object.
"""
body = _encode(**stanza)
... | Adds keys to the current configuration stanza as a
dictionary of key-value pairs.
:param stanza: A dictionary of key-value pairs for the stanza.
:type stanza: ``dict``
:return: The :class:`Stanza` object. |
def remove_blocked_work_units(self, work_spec_name, work_unit_names):
'''Remove some work units in the blocked list.
If `work_unit_names` is :const:`None` (which must be passed
explicitly), all pending work units in `work_spec_name` are
removed; otherwise only the specific named work un... | Remove some work units in the blocked list.
If `work_unit_names` is :const:`None` (which must be passed
explicitly), all pending work units in `work_spec_name` are
removed; otherwise only the specific named work units will be.
Note that none of the "remove" functions will restart block... |
def _deposit_withdraw(self, type, amount, coinbase_account_id):
"""`<https://docs.exchange.coinbase.com/#depositwithdraw>`_"""
data = {
'type':type,
'amount':amount,
'coinbase_account_id':coinbase_account_id
}
return self._post('transfers', data=data) | `<https://docs.exchange.coinbase.com/#depositwithdraw>`_ |
def render_view(view_name, **args):
'''Process view and return root Node'''
try:
root_xml = get_view_root(view_name)
return render(root_xml, **args)
except CoreError as error:
error.add_view_info(ViewInfo(view_name, None))
raise
except:
info = exc_info()
e... | Process view and return root Node |
def restrict(self, point):
"""Apply the ``restrict`` method to all functions.
Returns a new farray.
"""
items = [f.restrict(point) for f in self._items]
return self.__class__(items, self.shape, self.ftype) | Apply the ``restrict`` method to all functions.
Returns a new farray. |
def stop(self, stop_I):
"""
Get all stop data as a pandas DataFrame for all stops, or an individual stop'
Parameters
----------
stop_I : int
stop index
Returns
-------
stop: pandas.DataFrame
"""
return pd.read_sql_query("SELEC... | Get all stop data as a pandas DataFrame for all stops, or an individual stop'
Parameters
----------
stop_I : int
stop index
Returns
-------
stop: pandas.DataFrame |
def _check_markers(task_ids, offset=10):
"""Returns a flag for markers being found for the task_ids. If all task ids
have markers True will be returned. Otherwise it will return False as soon
as a None result is hit.
"""
shuffle(task_ids)
has_errors = False
for index in xrange(0, len(task_... | Returns a flag for markers being found for the task_ids. If all task ids
have markers True will be returned. Otherwise it will return False as soon
as a None result is hit. |
def get_differentially_expressed_genes(self, diff_type: str) -> VertexSeq:
"""Get the differentially expressed genes based on diff_type.
:param str diff_type: Differential expression type chosen by the user; all, down, or up.
:return list: A list of differentially expressed genes.
"""
... | Get the differentially expressed genes based on diff_type.
:param str diff_type: Differential expression type chosen by the user; all, down, or up.
:return list: A list of differentially expressed genes. |
def stats(self):
""" shotcut to pull out useful info for interactive use """
printDebug("Classes.....: %d" % len(self.classes))
printDebug("Properties..: %d" % len(self.properties)) | shotcut to pull out useful info for interactive use |
def create_doc_jar(self, target, open_jar, version):
"""Returns a doc jar if either scala or java docs are available for the given target."""
javadoc = self._java_doc(target)
scaladoc = self._scala_doc(target)
if javadoc or scaladoc:
jar_path = self.artifact_path(open_jar, version, suffix='-javado... | Returns a doc jar if either scala or java docs are available for the given target. |
def find_last(fileobj, serial):
"""Find the last page of the stream 'serial'.
If the file is not multiplexed this function is fast. If it is,
it must read the whole the stream.
This finds the last page in the actual file object, or the last
page in the stream (with eos set), wh... | Find the last page of the stream 'serial'.
If the file is not multiplexed this function is fast. If it is,
it must read the whole the stream.
This finds the last page in the actual file object, or the last
page in the stream (with eos set), whichever comes first. |
def _verify_subnet_association(route_table_desc, subnet_id):
'''
Helper function verify a subnet's route table association
route_table_desc
the description of a route table, as returned from boto_vpc.describe_route_table
subnet_id
the subnet id to verify
.. versionadded:: 2016.11.... | Helper function verify a subnet's route table association
route_table_desc
the description of a route table, as returned from boto_vpc.describe_route_table
subnet_id
the subnet id to verify
.. versionadded:: 2016.11.0 |
def update_fluent_cached_urls(item, dry_run=False):
"""
Regenerate the cached URLs for an item's translations. This is a fiddly
business: we use "hidden" methods instead of the public ones to avoid
unnecessary and unwanted slug changes to ensure uniqueness, the logic for
which doesn't work with our ... | Regenerate the cached URLs for an item's translations. This is a fiddly
business: we use "hidden" methods instead of the public ones to avoid
unnecessary and unwanted slug changes to ensure uniqueness, the logic for
which doesn't work with our publishing. |
def get_all(self, name, failobj=None):
"""Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original
message, and may contain duplicates. Any fields deleted and
re-inserted are always appended to the header list.
If no ... | Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original
message, and may contain duplicates. Any fields deleted and
re-inserted are always appended to the header list.
If no such fields exist, failobj is returned (defaults t... |
def iteration(self):
"""
Runs the ipfn algorithm. Automatically detects of working with numpy ndarray or pandas dataframes.
"""
i = 0
conv = np.inf
old_conv = -np.inf
conv_list = []
m = self.original
# If the original data input is in pandas Data... | Runs the ipfn algorithm. Automatically detects of working with numpy ndarray or pandas dataframes. |
def content():
"""Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 4.0.0
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message
"""
# We will store a content... | Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 4.0.0
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message |
def patched(attrs, updates):
"""A context in which some attributes temporarily have a modified value."""
orig = patch(attrs, updates.items())
try:
yield orig
finally:
patch(attrs, orig.items()) | A context in which some attributes temporarily have a modified value. |
def add_cnt_64bit(self,oid,value,label=None):
"""Short helper to add a 64 bit counter value to the MIB subtree."""
# Truncate integer to 64bits ma,x
self.add_oid_entry(oid,'Counter64',int(value)%18446744073709551615,label=label) | Short helper to add a 64 bit counter value to the MIB subtree. |
def _write_jpy_config(target_dir=None, install_dir=None):
"""
Write out a well-formed jpyconfig.properties file for easier Java
integration in a given location.
"""
if not target_dir:
target_dir = _build_dir()
args = [sys.executable,
os.path.join(target_dir, 'jpyutil.py'... | Write out a well-formed jpyconfig.properties file for easier Java
integration in a given location. |
def _new_output_char(self, char):
""" insert in text field """
self.text.config(state=tkinter.NORMAL)
self.text.insert("end", char)
self.text.see("end")
self.text.config(state=tkinter.DISABLED) | insert in text field |
def process_upload(photo_list, form, parent_object, user, status=''):
"""
Helper function that actually processes and saves the upload(s).
Segregated out for readability.
"""
status += "beginning upload processing. Gathering and normalizing fields....<br>"
for upload_file in photo_list:
... | Helper function that actually processes and saves the upload(s).
Segregated out for readability. |
def get_urls(self):
"""
Content of field ``856u42``. Typically URL pointing to producers
homepage.
Returns:
list: List of URLs defined by producer.
"""
urls = self.get_subfields("856", "u", i1="4", i2="2")
return map(lambda x: x.replace("&", "&")... | Content of field ``856u42``. Typically URL pointing to producers
homepage.
Returns:
list: List of URLs defined by producer. |
def set_console(self, console):
"""
Sets the TCP console port.
:param console: console port (integer)
"""
self.console = console
yield from self._hypervisor.send('vm set_con_tcp_port "{name}" {console}'.format(name=self._name, console=self.console)) | Sets the TCP console port.
:param console: console port (integer) |
def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
"""
Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.... | Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. |
def switch_off(self, *args):
"""
Sets the state of the switch to False if off_check() returns True,
given the arguments provided in kwargs.
:param kwargs: variable length dictionary of key-pair arguments
:return: Boolean. Returns True if the operation is successful
"""
... | Sets the state of the switch to False if off_check() returns True,
given the arguments provided in kwargs.
:param kwargs: variable length dictionary of key-pair arguments
:return: Boolean. Returns True if the operation is successful |
def run_command(command):
"""
Runs command and returns stdout
"""
process = subprocess.Popen(
shlex.split(command),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
output, stderr = [stream.decode(sys.getdefaultencoding(), 'ignore')
... | Runs command and returns stdout |
def eventFilter( self, object, event ):
"""
Filters the object for particular events.
:param object | <QObject>
event | <QEvent>
:return <bool> | consumed
"""
if ( event.type() == event.KeyPress ):
if (... | Filters the object for particular events.
:param object | <QObject>
event | <QEvent>
:return <bool> | consumed |
def show_hydrophobic(self):
"""Visualizes hydrophobic contacts."""
hydroph = self.plcomplex.hydrophobic_contacts
if not len(hydroph.bs_ids) == 0:
self.select_by_ids('Hydrophobic-P', hydroph.bs_ids, restrict=self.protname)
self.select_by_ids('Hydrophobic-L', hydroph.lig_id... | Visualizes hydrophobic contacts. |
def changed(self, message=None, *args):
"""Marks the object as changed.
If a `parent` attribute is set, the `changed()` method on the parent
will be called, propagating the change notification up the chain.
The message (if provided) will be debug logged.
"""
if message ... | Marks the object as changed.
If a `parent` attribute is set, the `changed()` method on the parent
will be called, propagating the change notification up the chain.
The message (if provided) will be debug logged. |
def allreduce(self, x, mesh_axes, reduction_fn_string):
"""Grouped allreduce, (summed across the given dimensions).
Args:
x: a LaidOutTensor
mesh_axes: a list of integers
reduction_fn_string: "SUM"
Returns:
a LaidOutTensor
Raises:
ValueError: if the reduction is not yet im... | Grouped allreduce, (summed across the given dimensions).
Args:
x: a LaidOutTensor
mesh_axes: a list of integers
reduction_fn_string: "SUM"
Returns:
a LaidOutTensor
Raises:
ValueError: if the reduction is not yet implemented. |
def intersection(self, *args):
"""
Produce an array that contains every item shared between all the
passed-in arrays.
"""
if type(self.obj[0]) is int:
a = self.obj
else:
a = tuple(self.obj[0])
setobj = set(a)
for i, v in enumerate(a... | Produce an array that contains every item shared between all the
passed-in arrays. |
def sample_storage_size(self):
"""Get the storage size of the samples storage collection."""
try:
coll_stats = self.database.command('collStats', 'fs.chunks')
sample_storage_size = coll_stats['size']/1024.0/1024.0
return sample_storage_size
except pymongo.err... | Get the storage size of the samples storage collection. |
def place_oceans_at_map_borders(world):
"""
Lower the elevation near the border of the map
"""
ocean_border = int(min(30, max(world.width / 5, world.height / 5)))
def place_ocean(x, y, i):
world.layers['elevation'].data[y, x] = \
(world.layers['elevation'].data[y, x] * i) / oce... | Lower the elevation near the border of the map |
def move(self, source_path, destination_path):
"""
Rename/move an object from one GCS location to another.
"""
self.copy(source_path, destination_path)
self.remove(source_path) | Rename/move an object from one GCS location to another. |
def _get_dS2S(self, imt_per):
"""
Table 4 of 2013 report
"""
if imt_per == 0:
dS2S = 0.05
elif 0 < imt_per < 0.15:
dS2S = self._interp_function(-0.15, 0.05, 0.15, 0, imt_per)
elif 0.15 <= imt_per < 0.45:
dS2S = self._interp_function(0.4... | Table 4 of 2013 report |
def init_environment():
"""Allow variables assigned in .env available using
os.environ.get('VAR_NAME')"""
base_path = os.path.abspath(os.path.dirname(__file__))
env_path = '{0}/.env'.format(base_path)
if os.path.exists(env_path):
with open(env_path) as f:
... | Allow variables assigned in .env available using
os.environ.get('VAR_NAME') |
def one_thread_per_process():
"""Return a context manager where only one thread is allocated to a process.
This function is intended to be used as a with statement like::
>>> with process_per_thread():
... do_something() # one thread per process
Notes:
This function only works... | Return a context manager where only one thread is allocated to a process.
This function is intended to be used as a with statement like::
>>> with process_per_thread():
... do_something() # one thread per process
Notes:
This function only works when MKL (Intel Math Kernel Library)... |
def b_operator(self, P):
r"""
The B operator, mapping P into
.. math::
B(P) := R - \beta^2 A'PB(Q + \beta B'PB)^{-1}B'PA + \beta A'PA
and also returning
.. math::
F := (Q + \beta B'PB)^{-1} \beta B'PA
Parameters
----------
P :... | r"""
The B operator, mapping P into
.. math::
B(P) := R - \beta^2 A'PB(Q + \beta B'PB)^{-1}B'PA + \beta A'PA
and also returning
.. math::
F := (Q + \beta B'PB)^{-1} \beta B'PA
Parameters
----------
P : array_like(float, ndim=2)
... |
def is_ext_pack_usable(self, name):
"""Check if the given extension pack is loaded and usable.
in name of type str
The name of the extension pack to check for.
return usable of type bool
Is the given extension pack loaded and usable.
"""
if not isinstan... | Check if the given extension pack is loaded and usable.
in name of type str
The name of the extension pack to check for.
return usable of type bool
Is the given extension pack loaded and usable. |
def register_widgets():
"""
Register all collected widgets from settings
WIDGETS = [('mymodule.models.MyWidget', {'mykwargs': 'mykwarg'})]
WIDGETS = ['mymodule.models.MyWidget', MyClass]
"""
# special case
# register external apps
Page.create_content_type(
ApplicationWidget, APP... | Register all collected widgets from settings
WIDGETS = [('mymodule.models.MyWidget', {'mykwargs': 'mykwarg'})]
WIDGETS = ['mymodule.models.MyWidget', MyClass] |
def mkdir(self, req, parent, name, mode):
"""Create a directory
Valid replies:
reply_entry
reply_err
"""
self.reply_err(req, errno.EROFS) | Create a directory
Valid replies:
reply_entry
reply_err |
def addLayer(self,layer,z=-1):
"""
Adds a new layer to the stack, optionally at the specified z-value.
``layer`` must be an instance of Layer or subclasses.
``z`` can be used to override the index of the layer in the stack. Defaults to ``-1`` for appending.
"""
... | Adds a new layer to the stack, optionally at the specified z-value.
``layer`` must be an instance of Layer or subclasses.
``z`` can be used to override the index of the layer in the stack. Defaults to ``-1`` for appending. |
def future(self, rev=None):
"""Return a Mapping of items after the given revision.
Default revision is the last one looked up.
"""
if rev is not None:
self.seek(rev)
return WindowDictFutureView(self._future) | Return a Mapping of items after the given revision.
Default revision is the last one looked up. |
def get_design_run_results(self, data_view_id, run_uuid):
"""
Retrieves the results of an existing designrun
:param data_view_id: The ID number of the data view to which the
run belongs, as a string
:type data_view_id: str
:param run_uuid: The UUID of the design run ... | Retrieves the results of an existing designrun
:param data_view_id: The ID number of the data view to which the
run belongs, as a string
:type data_view_id: str
:param run_uuid: The UUID of the design run to retrieve results from
:type run_uuid: str
:return: A :class... |
def user_parse(data):
"""Parse information from the provider."""
user_ = data.get('user', {})
yield 'id', data.get('user_nsid') or user_.get('id')
yield 'username', user_.get('username', {}).get('_content')
first_name, _, last_name = data.get(
'fullname', {}).get('_co... | Parse information from the provider. |
def save_as_plt(self, fname, pixel_array=None, vmin=None, vmax=None,
cmap=None, format=None, origin=None):
""" This method saves the image from a numpy array using matplotlib
:param fname: Location and name of the image file to be saved.
:param pixel_array: Numpy pixel array, i.e. ``num... | This method saves the image from a numpy array using matplotlib
:param fname: Location and name of the image file to be saved.
:param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value
:param vmin: matplotlib vmin
:param vmax: matplotlib vmax
:param cmap: matplotlib c... |
def tell(self):
"""
:return: number of records processed from the original file
"""
if self._shifts:
t = self._file.tell()
if t == self._shifts[0]:
return 0
elif t == self._shifts[-1]:
return len(self._shifts) - 1
... | :return: number of records processed from the original file |
def identify_phase(T, P, Tm=None, Tb=None, Tc=None, Psat=None):
r'''Determines the phase of a one-species chemical system according to
basic rules, using whatever information is available. Considers only the
phases liquid, solid, and gas; does not consider two-phase
scenarios, as should occurs between p... | r'''Determines the phase of a one-species chemical system according to
basic rules, using whatever information is available. Considers only the
phases liquid, solid, and gas; does not consider two-phase
scenarios, as should occurs between phase boundaries.
* If the melting temperature is known and the ... |
def string(self):
r"""This is valid if and only if
1. the expression is a :class:`.TexCmd` AND
2. the command has only one argument.
:rtype: Union[None,str]
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''\textbf{Hello}''')
>>> soup.textbf.string
... | r"""This is valid if and only if
1. the expression is a :class:`.TexCmd` AND
2. the command has only one argument.
:rtype: Union[None,str]
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''\textbf{Hello}''')
>>> soup.textbf.string
'Hello'
>>> soup.... |
def reference_index(self, ref_id):
"""Return the first reference with this ID."""
try:
indexes = range(self.reference_count())
return next(i for i in indexes if self.reference_id(i) == ref_id)
except StopIteration as e:
raise ReferenceNotFoundError("ID: " + re... | Return the first reference with this ID. |
def untrace_class(cls):
"""
Untraces given class.
:param cls: Class to untrace.
:type cls: object
:return: Definition success.
:rtype: bool
"""
for name, method in inspect.getmembers(cls, inspect.ismethod):
untrace_method(cls, method)
for name, function in inspect.getmembe... | Untraces given class.
:param cls: Class to untrace.
:type cls: object
:return: Definition success.
:rtype: bool |
def _get_color(self, age):
"""Get the fill color depending on age.
Args:
age (int): The age of the branch/es
Returns:
tuple: (r, g, b)
"""
if age == self.tree.age:
return self.leaf_color
color = self.stem_color
tree = self.tre... | Get the fill color depending on age.
Args:
age (int): The age of the branch/es
Returns:
tuple: (r, g, b) |
def find_ge(self, dt):
'''Building block of all searches. Find the index
corresponding to the leftmost value greater or equal to *dt*.
If *dt* is greater than the
:func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.RightOutOfBound`
exception will raise.
*dt* must be a python datetime.date instance.'... | Building block of all searches. Find the index
corresponding to the leftmost value greater or equal to *dt*.
If *dt* is greater than the
:func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.RightOutOfBound`
exception will raise.
*dt* must be a python datetime.date instance. |
def get_refinement_options(self):
""" Returns possible specializations for the upper values in the taxonomy """
domain = self.get_domain()
for upper_value in self.upper:
for suc in domain.successors(upper_value):
yield suc | Returns possible specializations for the upper values in the taxonomy |
def data(self):
"""
Returns signed data if present in the message
"""
# Check if signatire is detached
if self.detached:
return None
bio = Membio()
if not libcrypto.CMS_verify(self.ptr, None, None, None, bio.bio,
Fla... | Returns signed data if present in the message |
def set_cpus(self, cpus=0):
"""
Add --cpus options to specify how many threads to use.
"""
from multiprocessing import cpu_count
max_cpus = cpu_count()
if not 0 < cpus < max_cpus:
cpus = max_cpus
self.add_option("--cpus", default=cpus, type="int",
... | Add --cpus options to specify how many threads to use. |
def xinfo_help(self):
"""Retrieve help regarding the ``XINFO`` sub-commands"""
fut = self.execute(b'XINFO', b'HELP')
return wait_convert(fut, lambda l: b'\n'.join(l)) | Retrieve help regarding the ``XINFO`` sub-commands |
def lists(self, uid=0, **kwargs):
"""
Returns a list of :class:`List` objects (lists which Contact belongs to) and a pager dict.
:Example:
lists, pager = client.contacts.lists(uid=1901010)
:param int uid: The unique id of the Contact to update. Required.
:param int p... | Returns a list of :class:`List` objects (lists which Contact belongs to) and a pager dict.
:Example:
lists, pager = client.contacts.lists(uid=1901010)
:param int uid: The unique id of the Contact to update. Required.
:param int page: Fetch specified results page. Default=1
... |
def device_from_request(request):
"""
Determine's the device name from the request by first looking for an
overridding cookie, and if not found then matching the user agent.
Used at both the template level for choosing the template to load and
also at the cache level as a cache key prefix.
"""
... | Determine's the device name from the request by first looking for an
overridding cookie, and if not found then matching the user agent.
Used at both the template level for choosing the template to load and
also at the cache level as a cache key prefix. |
def options_response(env):
"""Construct WbResponse for OPTIONS based on the WSGI env dictionary
:param dict env: The WSGI environment dictionary
:return: The WBResponse for the options request
:rtype: WbResponse
"""
status_headers = StatusAndHeaders('200 Ok', [
... | Construct WbResponse for OPTIONS based on the WSGI env dictionary
:param dict env: The WSGI environment dictionary
:return: The WBResponse for the options request
:rtype: WbResponse |
def _read_mode_acopt(self, size, kind):
"""Read Alternate Checksum Request option.
Positional arguments:
size - int, length of option
kind - int, 14 (Alt-Chksum Request)
Returns:
* dict -- extracted Alternate Checksum Request (CHKSUM-REQ) option
Str... | Read Alternate Checksum Request option.
Positional arguments:
size - int, length of option
kind - int, 14 (Alt-Chksum Request)
Returns:
* dict -- extracted Alternate Checksum Request (CHKSUM-REQ) option
Structure of TCP CHKSUM-REQ [RFC 1146][RFC 6247]:
... |
def is_known_type(self, type_name):
"""Check if type is known to the type system.
Returns:
bool: True if the type is a known instantiated simple type, False otherwise
"""
type_name = str(type_name)
if type_name in self.known_types:
return True
r... | Check if type is known to the type system.
Returns:
bool: True if the type is a known instantiated simple type, False otherwise |
def build_verified_certificate_chain(self, received_certificate_chain: List[Certificate]) -> List[Certificate]:
"""Try to figure out the verified chain by finding the anchor/root CA the received chain chains up to in the
trust store.
This will not clean the certificate chain if additional/inval... | Try to figure out the verified chain by finding the anchor/root CA the received chain chains up to in the
trust store.
This will not clean the certificate chain if additional/invalid certificates were sent and the signatures and
fields (notBefore, etc.) are not verified. |
def _multi_call(function, contentkey, *args, **kwargs):
'''
Retrieve full list of values for the contentkey from a boto3 ApiGateway
client function that may be paged via 'position'
'''
ret = function(*args, **kwargs)
position = ret.get('position')
while position:
more = function(*ar... | Retrieve full list of values for the contentkey from a boto3 ApiGateway
client function that may be paged via 'position' |
def render_search(self, ctx, data):
"""
Render some UI for performing searches, if we know about a search
aggregator.
"""
if self.username is None:
return ''
translator = self._getViewerPrivateApplication()
searchAggregator = translator.getPageComponen... | Render some UI for performing searches, if we know about a search
aggregator. |
def event_transition(self, event_cls, event_type,
ion_type=None, value=None, annotations=None, depth=None, whence=None):
"""Returns an ion event event_transition that yields to another co-routine.
If ``annotations`` is not specified, then the ``annotations`` are the annotations... | Returns an ion event event_transition that yields to another co-routine.
If ``annotations`` is not specified, then the ``annotations`` are the annotations of this
context.
If ``depth`` is not specified, then the ``depth`` is depth of this context.
If ``whence`` is not specified, then ``... |
def p_members(self, p):
"""members :
| members member VALUE_SEPARATOR
| members member"""
if len(p) == 1:
p[0] = list()
else:
p[1].append(p[2])
p[0] = p[1] | members :
| members member VALUE_SEPARATOR
| members member |
def top_charts(self):
"""Get a listing of the default top charts."""
response = self._call(mc_calls.BrowseTopChart)
top_charts = response.body
return top_charts | Get a listing of the default top charts. |
def get_db_mutations(mut_db_path, gene_list, res_stop_codons):
"""
This function opens the file resistenss-overview.txt, and reads the
content into a dict of dicts. The dict will contain information about
all known mutations given in the database. This dict is returned.
"""
# Open resistens-ove... | This function opens the file resistenss-overview.txt, and reads the
content into a dict of dicts. The dict will contain information about
all known mutations given in the database. This dict is returned. |
def com_google_fonts_check_metadata_canonical_filename(font_metadata,
canonical_filename,
is_variable_font):
"""METADATA.pb: Filename is set canonically?"""
if is_variable_font:
valid_varfont_suffixes ... | METADATA.pb: Filename is set canonically? |
def un_camel_case(text):
r"""
Splits apart words that are written in CamelCase.
Bugs:
- Non-ASCII characters are treated as lowercase letters, even if they are
actually capital letters.
Examples:
>>> un_camel_case('1984ZXSpectrumGames')
'1984 ZX Spectrum Games'
>>> un_camel_ca... | r"""
Splits apart words that are written in CamelCase.
Bugs:
- Non-ASCII characters are treated as lowercase letters, even if they are
actually capital letters.
Examples:
>>> un_camel_case('1984ZXSpectrumGames')
'1984 ZX Spectrum Games'
>>> un_camel_case('aaAa aaAaA 0aA AAAa!AAA'... |
def get_gravityspy_triggers(tablename, engine=None, **kwargs):
"""Fetch data into an `GravitySpyTable`
Parameters
----------
table : `str`,
The name of table you are attempting to receive triggers
from.
selection
other filters you would like to supply
underlying rea... | Fetch data into an `GravitySpyTable`
Parameters
----------
table : `str`,
The name of table you are attempting to receive triggers
from.
selection
other filters you would like to supply
underlying reader method for the given format
.. note::
For now it will... |
def count_genomic_region_plot(self):
""" Generate the SnpEff Counts by Genomic Region plot """
# Sort the keys based on the total counts
keys = self.snpeff_section_totals['# Count by genomic region']
sorted_keys = sorted(keys, reverse=True, key=keys.get)
# Make nicer label name... | Generate the SnpEff Counts by Genomic Region plot |
def sync(remote='origin', branch='master'):
"""git pull and push commit"""
pull(branch, remote)
push(branch, remote)
print(cyan("Git Synced!")) | git pull and push commit |
def save_files(self, selections) -> None:
"""Save the |Selection| objects contained in the given |Selections|
instance to separate network files."""
try:
currentpath = self.currentpath
selections = selectiontools.Selections(selections)
for selection in selecti... | Save the |Selection| objects contained in the given |Selections|
instance to separate network files. |
def get_apps_menu(self):
"""Temporal code, will change to apps.get_app_configs() for django 1.7
Generate a initial menu list using the AppsConfig registered
"""
menu = {}
for model, model_admin in self.admin_site._registry.items():
if hasattr(model_admin, 'app_config... | Temporal code, will change to apps.get_app_configs() for django 1.7
Generate a initial menu list using the AppsConfig registered |
def network_interfaces_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all network interfaces within a resource group.
:param resource_group: The resource group name to list network
interfaces within.
CLI Example:
.. code-block:: bash
salt-call azurearm_n... | .. versionadded:: 2019.2.0
List all network interfaces within a resource group.
:param resource_group: The resource group name to list network
interfaces within.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.network_interfaces_list testgroup |
def _build_crawlid_info(self, master, dict):
'''
Builds the crawlid info object
@param master: the master dict
@param dict: the dict object received
@return: the crawlid info object
'''
master['total_pending'] = 0
master['total_domains'] = 0
maste... | Builds the crawlid info object
@param master: the master dict
@param dict: the dict object received
@return: the crawlid info object |
def write_message(self, status=messages.INFO, message=None):
"""
Writes a message to django's messaging framework and
returns the written message.
:param status: The message status level. Defaults to \
messages.INFO.
:param message: The message to write. If not given, \
... | Writes a message to django's messaging framework and
returns the written message.
:param status: The message status level. Defaults to \
messages.INFO.
:param message: The message to write. If not given, \
defaults to appending 'saved' to the unicode representation \
of ... |
def bitwise_or(self, t):
"""
Binary operation: logical or
:param b: The other operand
:return: self | b
"""
"""
This implementation combines the approaches used by 'WYSINWYX: what you see is not what you execute'
paper and 'Signedness-Agnostic Program Ana... | Binary operation: logical or
:param b: The other operand
:return: self | b |
def format_latex(self, strng):
"""Format a string for latex inclusion."""
# Characters that need to be escaped for latex:
escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
# Magic command names as headers:
cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
... | Format a string for latex inclusion. |
def chain_sub_regexes(phrase, *regex_sub_pairs):
'''
Allow for a series of regex substitutions to occur
chain_sub_regexes('test ok', (' ', '_'), ('k$', 'oo'))
# => 'test_ooo'
'''
for regex, substitution in regex_sub_pairs:
if isinstance(regex, basestring):
regex = r... | Allow for a series of regex substitutions to occur
chain_sub_regexes('test ok', (' ', '_'), ('k$', 'oo'))
# => 'test_ooo' |
def do_write(self):
"""
Flushes as much pending data from the internal write buffer as possible.
"""
while True:
try:
written = 0
if hasattr(self.fd, 'send'):
written = self.fd.send(self.buffer)
else:
... | Flushes as much pending data from the internal write buffer as possible. |
def from_cli(opt, length, delta_f, low_frequency_cutoff,
strain=None, dyn_range_factor=1, precision=None):
"""Parses the CLI options related to the noise PSD and returns a
FrequencySeries with the corresponding PSD. If necessary, the PSD is
linearly interpolated to achieve the resolution specif... | Parses the CLI options related to the noise PSD and returns a
FrequencySeries with the corresponding PSD. If necessary, the PSD is
linearly interpolated to achieve the resolution specified in the CLI.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any obj... |
def reboot_adb_server():
""" execute 'adb devices' to start adb server """
_reboot_count = 0
_max_retry = 1
def _reboot():
nonlocal _reboot_count
if _reboot_count >= _max_retry:
raise RuntimeError('fail after retry {} times'.format(_max_retry))
_reboot_count += 1
... | execute 'adb devices' to start adb server |
def _square_batch_bcbio_variation(data, region, bam_files, vrn_files, out_file,
todo="square"):
"""Run squaring or merging analysis using bcbio.variation.recall.
"""
ref_file = tz.get_in(("reference", "fasta", "base"), data)
cores = tz.get_in(("config", "algorithm", "nu... | Run squaring or merging analysis using bcbio.variation.recall. |
def paste(self):
'''
Insert text from the clipboard at the cursor.
'''
try:
t = pygame.scrap.get(SCRAP_TEXT)
if t:
self.insert(t)
return True
except:
# pygame.scrap is experimental, allow for changes
... | Insert text from the clipboard at the cursor. |
def inall_cmd(argv):
"""Run a command in each virtualenv."""
envs = lsenvs()
errors = False
for env in envs:
print("\n%s:" % env)
try:
inve(env, *argv)
except CalledProcessError as e:
errors = True
err(e)
sys.exit(errors) | Run a command in each virtualenv. |
def log_error(self, msg, *args):
"""Log an error or print in stdout if no logger."""
if self._logger is not None:
self._logger.error(msg, *args)
else:
print(msg % args) | Log an error or print in stdout if no logger. |
def program_rtr_nwk_next_hop(self, rout_id, next_hop, cidr):
"""Program the next hop for all networks of a tenant. """
namespace = self.find_rtr_namespace(rout_id)
if namespace is None:
LOG.error("Unable to find namespace for router %s", rout_id)
return False
arg... | Program the next hop for all networks of a tenant. |
def to_html(sample, stats_object):
"""Generate a HTML report from summary statistics and a given sample.
Parameters
----------
sample : DataFrame
the sample you want to print
stats_object : dict
Summary statistics. Should be generated with an appropriate describe() function
Ret... | Generate a HTML report from summary statistics and a given sample.
Parameters
----------
sample : DataFrame
the sample you want to print
stats_object : dict
Summary statistics. Should be generated with an appropriate describe() function
Returns
-------
str
containin... |
def get_maya_envpath(self):
"""Return the PYTHONPATH neccessary for running mayapy
If you start native mayapy, it will setup these paths.
You might want to prepend this to your path if running from
an external intepreter.
:returns: the PYTHONPATH that is used for running mayapy... | Return the PYTHONPATH neccessary for running mayapy
If you start native mayapy, it will setup these paths.
You might want to prepend this to your path if running from
an external intepreter.
:returns: the PYTHONPATH that is used for running mayapy
:rtype: str
:raises: N... |
def reciprocal_space(space, axes=None, halfcomplex=False, shift=True,
**kwargs):
"""Return the range of the Fourier transform on ``space``.
Parameters
----------
space : `DiscreteLp`
Real space whose reciprocal is calculated. It must be
uniformly discretized.
ax... | Return the range of the Fourier transform on ``space``.
Parameters
----------
space : `DiscreteLp`
Real space whose reciprocal is calculated. It must be
uniformly discretized.
axes : sequence of ints, optional
Dimensions along which the Fourier transform is taken.
Defaul... |
def handle_get_reseller(self, req):
"""Handles the GET v2 call for getting general reseller information
(currently just a list of accounts). Can only be called by a
.reseller_admin.
On success, a JSON dictionary will be returned with a single `accounts`
key whose value is list o... | Handles the GET v2 call for getting general reseller information
(currently just a list of accounts). Can only be called by a
.reseller_admin.
On success, a JSON dictionary will be returned with a single `accounts`
key whose value is list of dicts. Each dict represents an account and
... |
def post_load(fn=None, pass_many=False, pass_original=False):
"""Register a method to invoke after deserializing an object. The method
receives the deserialized data and returns the processed data.
By default, receives a single datum at a time, transparently handling the ``many``
argument passed to the... | Register a method to invoke after deserializing an object. The method
receives the deserialized data and returns the processed data.
By default, receives a single datum at a time, transparently handling the ``many``
argument passed to the Schema. If ``pass_many=True``, the raw data
(which may be a coll... |
def get_commands():
"""
Returns a dictionary mapping command names to their callback applications.
This works by looking for a management.commands package in django.core, and
in each installed application -- if a commands package exists, all commands
in that package are registered.
Core comman... | Returns a dictionary mapping command names to their callback applications.
This works by looking for a management.commands package in django.core, and
in each installed application -- if a commands package exists, all commands
in that package are registered.
Core commands are always included. If a set... |
def read_transport_message(self, origin, message_type, timeout=15):
"""
Blocking read of a transport message that does not indicate a message from the Pebble.
Will block until a message is received, or it times out.
.. warning::
Avoid calling this method from an endpoint call... | Blocking read of a transport message that does not indicate a message from the Pebble.
Will block until a message is received, or it times out.
.. warning::
Avoid calling this method from an endpoint callback; doing so is likely to lead to deadlock.
:param origin: The type of :class... |
def add_dependency(self, depend):
"""Adds dependencies."""
try:
self._add_child(self.depends, self.depends_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = s... | Adds dependencies. |
def detach(self, force=False):
"""
Detach this EBS volume from an EC2 instance.
:type force: bool
:param force: Forces detachment if the previous detachment attempt did
not occur cleanly. This option can lead to data loss or
a corrupted file ... | Detach this EBS volume from an EC2 instance.
:type force: bool
:param force: Forces detachment if the previous detachment attempt did
not occur cleanly. This option can lead to data loss or
a corrupted file system. Use this option only as a last
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.