code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def parse_csr():
"""
Parse certificate signing request for domains
"""
LOGGER.info("Parsing CSR...")
cmd = [
'openssl', 'req',
'-in', os.path.join(gettempdir(), 'domain.csr'),
'-noout',
'-text'
]
devnull = open(os.devnull, 'wb')
out = subprocess.check_outp... | Parse certificate signing request for domains |
def appendRandomLenPadding(str, blocksize=AES_blocksize):
'ISO 10126 Padding (withdrawn, 2007): Pad with random bytes + last byte equal to the number of padding bytes'
pad_len = paddingLength(len(str), blocksize) - 1
from os import urandom
padding = urandom(pad_len)+chr(pad_len)
return str + padding | ISO 10126 Padding (withdrawn, 2007): Pad with random bytes + last byte equal to the number of padding bytes |
def render(self, *args, **kwargs):
'''
fun(uid_with_str)
fun(uid_with_str, slug = val1, glyph = val2)
'''
uid_with_str = args[0]
slug = kwargs.get('slug', False)
with_title = kwargs.get('with_title', False)
glyph = kwargs.get('glyph', '')
kwd ... | fun(uid_with_str)
fun(uid_with_str, slug = val1, glyph = val2) |
def _win32_is_hardlinked(fpath1, fpath2):
"""
Test if two hard links point to the same location
CommandLine:
python -m ubelt._win32_links _win32_is_hardlinked
Example:
>>> # xdoc: +REQUIRES(WIN32)
>>> import ubelt as ub
>>> root = ub.ensure_app_cache_dir('ubelt', 'win32... | Test if two hard links point to the same location
CommandLine:
python -m ubelt._win32_links _win32_is_hardlinked
Example:
>>> # xdoc: +REQUIRES(WIN32)
>>> import ubelt as ub
>>> root = ub.ensure_app_cache_dir('ubelt', 'win32_hardlink')
>>> ub.delete(root)
>>> ub... |
def cover(self):
"""
album cover as :class:`Picture` object
"""
if not self._cover:
self._cover = Picture(self._cover_url, self._connection)
return self._cover | album cover as :class:`Picture` object |
def build(self, recipe=None,
image=None,
isolated=False,
sandbox=False,
writable=False,
build_folder=None,
robot_name=False,
ext='simg',
sudo=True,
stream=False):
'''bui... | build a singularity image, optionally for an isolated build
(requires sudo). If you specify to stream, expect the image name
and an iterator to be returned.
image, builder = Client.build(...)
Parameters
==========
recipe: the path to the recipe file (or source to buil... |
def _expectation(p, mean1, none1, mean2, none2, nghp=None):
"""
Compute the expectation:
expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n)
- m1(.) :: Linear mean function
- m2(.) :: Identity mean function
:return: NxQxD
"""
with params_as_tensors_for(mean1):
N = tf.shape(p.mu)... | Compute the expectation:
expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n)
- m1(.) :: Linear mean function
- m2(.) :: Identity mean function
:return: NxQxD |
def _on_send_complete(self, handle, error):
"""Callback used with handle.send()."""
assert handle is self._handle
self._write_buffer_size -= 1
assert self._write_buffer_size >= 0
if self._error:
self._log.debug('ignore sendto status {} after error', error)
# S... | Callback used with handle.send(). |
def set_access_cookies(response, encoded_access_token, max_age=None):
"""
Takes a flask response object, and an encoded access token, and configures
the response to set in the access token in a cookie. If `JWT_CSRF_IN_COOKIES`
is `True` (see :ref:`Configuration Options`), this will also set the CSRF
... | Takes a flask response object, and an encoded access token, and configures
the response to set in the access token in a cookie. If `JWT_CSRF_IN_COOKIES`
is `True` (see :ref:`Configuration Options`), this will also set the CSRF
double submit values in a separate cookie.
:param response: The Flask respon... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'type') and self.type is not None:
_dict['type'] = self.type
if hasattr(self, 'credential_id') and self.credential_id is not None:
_dict['credential_id'] = self... | Return a json dictionary representing this model. |
def process(self, request, response, environ):
"""
Generates a new authorization token.
A form to authorize the access of the application can be displayed with
the help of `oauth2.web.SiteAdapter`.
"""
data = self.authorize(request, response, environ,
... | Generates a new authorization token.
A form to authorize the access of the application can be displayed with
the help of `oauth2.web.SiteAdapter`. |
def clone(self):
""" This method clones AttributeMap object.
Returns AttributeMap object that has the same values with the
original one.
"""
cloned_filters = [f.clone() for f in self.filters]
return self.__class__(cloned_filters, self.attr_type, self.attr_value) | This method clones AttributeMap object.
Returns AttributeMap object that has the same values with the
original one. |
def consul_fetch(client, path):
'''
Query consul for all keys/values within base path
'''
# Unless the root path is blank, it needs a trailing slash for
# the kv get from Consul to work as expected
return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True) | Query consul for all keys/values within base path |
def can_user_update_settings(request, view, obj=None):
""" Only staff can update shared settings, otherwise user has to be an owner of the settings."""
if obj is None:
return
# TODO [TM:3/21/17] clean it up after WAL-634. Clean up service settings update tests as well.
if ob... | Only staff can update shared settings, otherwise user has to be an owner of the settings. |
def attach(self, to_linode, config=None):
"""
Attaches this Volume to the given Linode
"""
result = self._client.post('{}/attach'.format(Volume.api_endpoint), model=self,
data={
"linode_id": to_linode.id if issubclass(type(to_linode), Base) else to_lin... | Attaches this Volume to the given Linode |
def raise_check_result(self):
"""Raise ACTIVE CHECK RESULT entry
Example : "ACTIVE HOST CHECK: server;DOWN;HARD;1;I don't know what to say..."
:return: None
"""
if not self.__class__.log_active_checks:
return
log_level = 'info'
if self.state == 'DOWN... | Raise ACTIVE CHECK RESULT entry
Example : "ACTIVE HOST CHECK: server;DOWN;HARD;1;I don't know what to say..."
:return: None |
def get_mask_from_prob(self, cloud_probs, threshold=None):
"""
Returns cloud mask by applying morphological operations -- convolution and dilation --
to input cloud probabilities.
:param cloud_probs: cloud probability map
:type cloud_probs: numpy array of cloud probabilities (sh... | Returns cloud mask by applying morphological operations -- convolution and dilation --
to input cloud probabilities.
:param cloud_probs: cloud probability map
:type cloud_probs: numpy array of cloud probabilities (shape n_images x n x m)
:param threshold: A float from [0,1] specifying t... |
def cancel_download_task(self, task_id, expires=None, **kwargs):
"""取消离线下载任务.
:param task_id: 要取消的任务ID号。
:type task_id: str
:param expires: 请求失效时间,如果有,则会校验。
:type expires: int
:return: requests.Response
"""
data = {
'expires': expires,
... | 取消离线下载任务.
:param task_id: 要取消的任务ID号。
:type task_id: str
:param expires: 请求失效时间,如果有,则会校验。
:type expires: int
:return: requests.Response |
def place2thing(self, name, location):
"""Turn a Place into a Thing with the given location.
It will keep all its attached Portals.
"""
self.engine._set_thing_loc(
self.name, name, location
)
if (self.name, name) in self.engine._node_objs:
... | Turn a Place into a Thing with the given location.
It will keep all its attached Portals. |
def _show_menu(self):
"""Show the overlay menu."""
# If the current widget in the TabbedWindowWidget has a menu,
# overlay it on the TabbedWindowWidget.
current_widget = self._tabbed_window.get_current_widget()
if hasattr(current_widget, 'get_menu_widget'):
menu_widge... | Show the overlay menu. |
def nvim_io_recover(self, io: NvimIORecover[A]) -> NvimIO[B]:
'''calls `map` to shift the recover execution to flat_map_nvim_io
'''
return eval_step(self.vim)(io.map(lambda a: a)) | calls `map` to shift the recover execution to flat_map_nvim_io |
def _get_adc_value(self, channel, average=None):
'''Read ADC
'''
conf = self.SCAN_OFF | self.SINGLE_ENDED | ((0x1e) & (channel << 1))
self._intf.write(self._base_addr + self.MAX_1239_ADD, array('B', pack('B', conf)))
def read_data():
ret = self._intf.read(self._base_... | Read ADC |
def furtherArgsProcessing(args):
"""
Converts args, and deals with incongruities that argparse couldn't handle
"""
if isinstance(args, str):
unprocessed = args.strip().split(' ')
if unprocessed[0] == 'cyther':
del unprocessed[0]
args = parser.parse_args(unprocessed)._... | Converts args, and deals with incongruities that argparse couldn't handle |
def _mutect_variant_stats(variant, sample_info):
"""Parse a single sample"s variant calling statistics based on Mutect"s (v1) VCF output
Parameters
----------
variant : varcode.Variant
sample_info : dict
Dictionary of Mutect-specific variant calling fields
Returns
-------
Varia... | Parse a single sample"s variant calling statistics based on Mutect"s (v1) VCF output
Parameters
----------
variant : varcode.Variant
sample_info : dict
Dictionary of Mutect-specific variant calling fields
Returns
-------
VariantStats |
def FromFile(cls, path, actions_dict, resources_dict, file_format="yaml", name=None):
"""Create a RecipeObject from a file.
The file should be a specially constructed yaml file that describes
the recipe as well as the actions that it performs.
Args:
path (str): The path to ... | Create a RecipeObject from a file.
The file should be a specially constructed yaml file that describes
the recipe as well as the actions that it performs.
Args:
path (str): The path to the recipe file that we wish to load
actions_dict (dict): A dictionary of named Recip... |
def link_page_filter(self, page, modelview_name):
"""
Arguments are passed like: page_<VIEW_NAME>=<PAGE_NUMBER>
"""
new_args = request.view_args.copy()
args = request.args.copy()
args["page_" + modelview_name] = page
return url_for(
request.endpoin... | Arguments are passed like: page_<VIEW_NAME>=<PAGE_NUMBER> |
def format_struct(struct_def):
'''Returns a cython struct from a :attr:`StructSpec` instance.
'''
text = []
text.append('cdef struct {}:'.format(struct_def.tp_name))
text.extend(
['{}{}'.format(tab, format_variable(var))
for var in struct_def.members]
)
for name i... | Returns a cython struct from a :attr:`StructSpec` instance. |
def read_memory(self):
"""
This function read mean value of target`d`
and input vector `x` from history
"""
if self.mem_empty == True:
if self.mem_idx == 0:
m_x = np.zeros(self.n)
m_d = 0
else:
m_x = np.mean(... | This function read mean value of target`d`
and input vector `x` from history |
def method(self, quote_id, payment_data, store_view=None):
"""
Allows you to set a payment method for a shopping cart (quote).
:param quote_id: Shopping cart ID (quote ID)
:param payment_data, dict of payment details, example
{
'po_number': '',
... | Allows you to set a payment method for a shopping cart (quote).
:param quote_id: Shopping cart ID (quote ID)
:param payment_data, dict of payment details, example
{
'po_number': '',
'method': 'checkmo',
'cc_cid': '',
'cc_owner'... |
def make_library(**kwargs):
"""Build and return a ModelManager object and fill the associated model library
"""
library_yaml = kwargs.pop('library', 'models/library.yaml')
comp_yaml = kwargs.pop('comp', 'config/binning.yaml')
basedir = kwargs.pop('basedir', os.path.abspath('.'))
model_man = kwa... | Build and return a ModelManager object and fill the associated model library |
def publish_proto_in_ipfs(self):
""" Publish proto files in ipfs and print hash """
ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs(self._get_ipfs_client(), self.args.protodir)
self._printout(ipfs_hash_base58) | Publish proto files in ipfs and print hash |
def parse_delete_zone(prs, conn):
"""Delete zone.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_zone_delete = prs.add_parser('zone_delete', help='delete zone')
prs_zone_delete.add_argument('--domain', action='store', required=True,
... | Delete zone.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information |
def AddMapping(self, filename, new_mapping):
"""Adds an entry to the list of known filenames.
Args:
filename: The filename whose mapping is being added.
new_mapping: A dictionary with the mapping to add. Must contain all
fields in _REQUIRED_MAPPING_FIELDS.
Raises:
Duplic... | Adds an entry to the list of known filenames.
Args:
filename: The filename whose mapping is being added.
new_mapping: A dictionary with the mapping to add. Must contain all
fields in _REQUIRED_MAPPING_FIELDS.
Raises:
DuplicateMapping if the filename already exists in the map... |
def replace_namespaced_pod(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_pod # noqa: E501
replace the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... | replace_namespaced_pod # noqa: E501
replace the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_pod(name, namespace, body, async_req=True)
>... |
def spin(self, use_thread=False):
'''call callback for all data forever (until \C-c)
:param use_thread: use thread for spin (do not block)
'''
if use_thread:
if self._thread is not None:
raise 'spin called twice'
self._thread = threading.Thread(ta... | call callback for all data forever (until \C-c)
:param use_thread: use thread for spin (do not block) |
def send(self):
"""
Send the message.
First, a message is constructed, then a session with the email
servers is created, finally the message is sent and the session
is stopped.
"""
self._generate_email()
if self.verbose:
print(
... | Send the message.
First, a message is constructed, then a session with the email
servers is created, finally the message is sent and the session
is stopped. |
def pretty_print(self):
"""
Pretty print representation of this fragment,
as ``(identifier, begin, end, text)``.
:rtype: string
.. versionadded:: 1.7.0
"""
return u"%s\t%.3f\t%.3f\t%s" % (
(self.identifier or u""),
(self.begin if self.beg... | Pretty print representation of this fragment,
as ``(identifier, begin, end, text)``.
:rtype: string
.. versionadded:: 1.7.0 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'content') and self.content is not None:
_dict['content'] = self.content
if hasattr(self, 'id') and self.id is not None:
_dict['id'] = self.id
if hasatt... | Return a json dictionary representing this model. |
def depth(self):
"""
Returns the number of ancestors of this directory.
"""
return len(self.path.rstrip(os.sep).split(os.sep)) | Returns the number of ancestors of this directory. |
def update(self, name, color):
"""Update this label.
:param str name: (required), new name of the label
:param str color: (required), color code, e.g., 626262, no leading '#'
:returns: bool
"""
json = None
if name and color:
if color[0] == '#':
... | Update this label.
:param str name: (required), new name of the label
:param str color: (required), color code, e.g., 626262, no leading '#'
:returns: bool |
def rename(self, container, name):
"""
Rename a container. Similar to the ``docker rename`` command.
Args:
container (str): ID of the container to rename
name (str): New name for the container
Raises:
:py:class:`docker.errors.APIError`
... | Rename a container. Similar to the ``docker rename`` command.
Args:
container (str): ID of the container to rename
name (str): New name for the container
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error. |
def min_base_size_mask(self, size, hs_dims=None, prune=False):
"""Returns MinBaseSizeMask object with correct row, col and table masks.
The returned object stores the necessary information about the base size, as
well as about the base values. It can create corresponding masks in teh row,
... | Returns MinBaseSizeMask object with correct row, col and table masks.
The returned object stores the necessary information about the base size, as
well as about the base values. It can create corresponding masks in teh row,
column, and table directions, based on the corresponding base values
... |
def check_bitdepth_rescale(
palette, bitdepth, transparent, alpha, greyscale):
"""
Returns (bitdepth, rescale) pair.
"""
if palette:
if len(bitdepth) != 1:
raise ProtocolError(
"with palette, only a single bitdepth may be used")
(bitdepth, ) = bitdept... | Returns (bitdepth, rescale) pair. |
def frompsl(args):
"""
%prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver>
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(frompsl.__doc__)
opts, args =... | %prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver> |
def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList'
) -> 'QubitOrder':
"""Converts a value into a basis.
Args:
val: An iterable or a basis.
Returns:
The basis implied by the value.
"""
if isinstance(val, collections.Iter... | Converts a value into a basis.
Args:
val: An iterable or a basis.
Returns:
The basis implied by the value. |
def add_double_proxy_for(self, label: str, shape: Collection[int] = None) -> Vertex:
"""
Creates a proxy vertex for the given label and adds to the sequence item
"""
if shape is None:
return Vertex._from_java_vertex(self.unwrap().addDoubleProxyFor(_VertexLabel(label).unwrap()... | Creates a proxy vertex for the given label and adds to the sequence item |
def get_object(cls, abbr):
'''
This particular model needs its own constructor in order to take
advantage of the metadata cache in billy.util, which would otherwise
return unwrapped objects.
'''
obj = get_metadata(abbr)
if obj is None:
msg = 'No metada... | This particular model needs its own constructor in order to take
advantage of the metadata cache in billy.util, which would otherwise
return unwrapped objects. |
def daemon_mode(self, args, options):
"""
Open a ControlWebSocket to SushiBar server and listend for remote commands.
Args:
args (dict): chef command line arguments
options (dict): additional compatibility mode options given on command line
"""
cws = Contr... | Open a ControlWebSocket to SushiBar server and listend for remote commands.
Args:
args (dict): chef command line arguments
options (dict): additional compatibility mode options given on command line |
def set_vcard(self, vcard):
"""
Store the vCard `vcard` for the connected entity.
:param vcard: the vCard to store.
.. note::
`vcard` should always be derived from the result of
`get_vcard` to preserve the elements of the vcard the
client does not modi... | Store the vCard `vcard` for the connected entity.
:param vcard: the vCard to store.
.. note::
`vcard` should always be derived from the result of
`get_vcard` to preserve the elements of the vcard the
client does not modify.
.. warning::
It is in t... |
def swapon(name, priority=None):
'''
Activate a swap disk
.. versionchanged:: 2016.3.2
CLI Example:
.. code-block:: bash
salt '*' mount.swapon /root/swapfile
'''
ret = {}
on_ = swaps()
if name in on_:
ret['stats'] = on_[name]
ret['new'] = False
ret... | Activate a swap disk
.. versionchanged:: 2016.3.2
CLI Example:
.. code-block:: bash
salt '*' mount.swapon /root/swapfile |
def destinations(stop):
"""Get destination information."""
from pyruter.api import Departures
async def get_destinations():
"""Get departure information."""
async with aiohttp.ClientSession() as session:
data = Departures(LOOP, stop, session=session)
result = await d... | Get destination information. |
def read_anchors(ac, qorder, sorder, minsize=0):
"""
anchors file are just (geneA, geneB) pairs (with possible deflines)
"""
all_anchors = defaultdict(list)
nanchors = 0
anchor_to_block = {}
for a, b, idx in ac.iter_pairs(minsize=minsize):
if a not in qorder or b not in sorder:
... | anchors file are just (geneA, geneB) pairs (with possible deflines) |
def jeffreys(logu, name=None):
"""The Jeffreys Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Jeffreys Csiszar-function is:
```none
f(u) = 0.5 ( u log(u) - log(u) )
= 0.5 kl_forward + 0.5 kl_reverse
= symmetrized_csiszar... | The Jeffreys Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Jeffreys Csiszar-function is:
```none
f(u) = 0.5 ( u log(u) - log(u) )
= 0.5 kl_forward + 0.5 kl_reverse
= symmetrized_csiszar_function(kl_reverse)
= symme... |
def dataset_search(q=None, type=None, keyword=None,
owningOrg=None, publishingOrg=None, hostingOrg=None, decade=None,
publishingCountry = None, facet = None, facetMincount=None,
facetMultiselect = None, hl = False, limit = 100, offset = None,
**kwargs):
'''
Full text search across all datasets. Results are ordere... | Full text search across all datasets. Results are ordered by relevance.
:param q: [str] Query term(s) for full text search. The value for this parameter
can be a simple word or a phrase. Wildcards can be added to the simple word
parameters only, e.g. ``q=*puma*``
:param type: [str] Type of dataset, options in... |
def hget(self, name, key):
"""
Returns the value stored in the field, None if the field doesn't exist.
:param name: str the name of the redis key
:param key: the member of the hash
:return: Future()
"""
with self.pipe as pipe:
f = Future()
... | Returns the value stored in the field, None if the field doesn't exist.
:param name: str the name of the redis key
:param key: the member of the hash
:return: Future() |
def init(self):
"""Init the connection to the ES server."""
if not self.export_enable:
return None
self.index='{}-{}'.format(self.index, datetime.utcnow().strftime("%Y.%m.%d"))
template_body = {
"mappings": {
"glances": {
"dynamic_templat... | Init the connection to the ES server. |
def apply_T8(word):
'''Split /ie/, /uo/, or /yö/ sequences in syllables that do not take
primary stress.'''
WORD = word
offset = 0
for vv in tail_diphthongs(WORD):
i = vv.start(1) + 1 + offset
WORD = WORD[:i] + '.' + WORD[i:]
offset += 1
RULE = ' T8' if word != WORD els... | Split /ie/, /uo/, or /yö/ sequences in syllables that do not take
primary stress. |
def _get_one_pending_job(self):
"""
Retrieve a pending job.
:return: A CFGJob instance or None
"""
pending_job_key, pending_job = self._pending_jobs.popitem()
pending_job_state = pending_job.state
pending_job_call_stack = pending_job.call_stack
pending_j... | Retrieve a pending job.
:return: A CFGJob instance or None |
def ensure_schema(self):
"""Create file and schema if it does not exist yet."""
self._ensure_filename()
if not os.path.isfile(self.filename):
self.create_schema() | Create file and schema if it does not exist yet. |
def regroup_commands(commands):
"""
Returns a list of tuples:
[(command_to_run, [list, of, commands])]
If the list of commands has a single item, the command was not grouped.
"""
grouped = []
pending = []
def group_pending():
if not pending:
return
new... | Returns a list of tuples:
[(command_to_run, [list, of, commands])]
If the list of commands has a single item, the command was not grouped. |
def straight_throat(target, throat_centroid='throat.centroid',
throat_vector='throat.vector',
throat_length='throat.length'):
r"""
Calculate the coordinates of throat endpoints given a central coordinate,
unit vector along the throat direction and a length.
Param... | r"""
Calculate the coordinates of throat endpoints given a central coordinate,
unit vector along the throat direction and a length.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and als... |
def get_par_css_dataframe(self):
""" get a dataframe of composite scaled sensitivities. Includes both
PEST-style and Hill-style.
Returns
-------
css : pandas.DataFrame
"""
assert self.jco is not None
assert self.pst is not None
jco = self.jco.t... | get a dataframe of composite scaled sensitivities. Includes both
PEST-style and Hill-style.
Returns
-------
css : pandas.DataFrame |
def clear(self):
"""T.clear() -> None. Remove all items from T."""
def _clear(node):
if node is not None:
_clear(node.left)
_clear(node.right)
node.free()
_clear(self._root)
self._count = 0
self._root = None | T.clear() -> None. Remove all items from T. |
def StatFSFromClient(args):
"""Call os.statvfs for a given list of paths.
Args:
args: An `rdf_client_action.StatFSRequest`.
Yields:
`rdf_client_fs.UnixVolume` instances.
Raises:
RuntimeError: if called on a Windows system.
"""
if platform.system() == "Windows":
raise RuntimeError("os.stat... | Call os.statvfs for a given list of paths.
Args:
args: An `rdf_client_action.StatFSRequest`.
Yields:
`rdf_client_fs.UnixVolume` instances.
Raises:
RuntimeError: if called on a Windows system. |
def show_vcs_output_vcs_guid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
vcs_guid = ET.SubElement(output, "vcs-guid")
vcs_guid.text... | Auto Generated Code |
def OpenFile(self, filepath):
"""open()-replacement that automatically handles zip files.
This assumes there is at most one .zip in the file path.
Args:
filepath: the path to the file to open.
Returns:
An open file-like object.
"""
archive = False
if '.zip/' in filepath:
a... | open()-replacement that automatically handles zip files.
This assumes there is at most one .zip in the file path.
Args:
filepath: the path to the file to open.
Returns:
An open file-like object. |
def udf_signature(input_type, pin, klass):
"""Compute the appropriate signature for a
:class:`~ibis.expr.operations.Node` from a list of input types
`input_type`.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of :class:`~ibis.expr.datatypes.DataType` insta... | Compute the appropriate signature for a
:class:`~ibis.expr.operations.Node` from a list of input types
`input_type`.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of :class:`~ibis.expr.datatypes.DataType` instances representing
the signature of a UDF/U... |
def down_ec2(instance_id, region, access_key_id, secret_access_key):
""" shutdown of an existing EC2 instance """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
# get the instance_id from the state file, and stop the instance
instance = conn.stop_instances(instance_ids=instance_id)[0]
... | shutdown of an existing EC2 instance |
def writecc (listoflists,file,writetype='w',extra=2):
"""
Writes a list of lists to a file in columns, customized by the max
size of items within the columns (max size of items in col, +2 characters)
to specified file. File-overwrite is the default.
Usage: writecc (listoflists,file,writetype='w',extra=2)
Return... | Writes a list of lists to a file in columns, customized by the max
size of items within the columns (max size of items in col, +2 characters)
to specified file. File-overwrite is the default.
Usage: writecc (listoflists,file,writetype='w',extra=2)
Returns: None |
def stringIO(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, ra... | Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
... |
def main():
"""
NAME
dir_redo.py
DESCRIPTION
converts the Cogne DIR format to PmagPy redo file
SYNTAX
dir_redo.py [-h] [command line options]
OPTIONS
-h: prints help message and quits
-f FILE: specify input file
-F FILE: specify output file, defaul... | NAME
dir_redo.py
DESCRIPTION
converts the Cogne DIR format to PmagPy redo file
SYNTAX
dir_redo.py [-h] [command line options]
OPTIONS
-h: prints help message and quits
-f FILE: specify input file
-F FILE: specify output file, default is 'zeq_redo' |
def cee_map_priority_table_map_cos4_pgid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name_key = ET.SubElement(cee_map, "name")
name_key.text = kwargs.pop... | Auto Generated Code |
def modify(self, current_modified_line, anchors, file_path, file_lines=None,
index=None):
"""
Removes the trailing AnchorHub tag from the end of the line being
examined.
:param current_modified_line: string representing the the line at
file_lines[index] _after... | Removes the trailing AnchorHub tag from the end of the line being
examined.
:param current_modified_line: string representing the the line at
file_lines[index] _after_ any previous modifications from other
WriterStrategy objects
:param anchors: Dictionary mapping string ... |
def setArg(self, namespace, key, value):
"""Set a single argument in this namespace"""
assert key is not None
assert value is not None
namespace = self._fixNS(namespace)
self.args[(namespace, key)] = value
if not (namespace is BARE_NS):
self.namespaces.add(nam... | Set a single argument in this namespace |
def create_token(self, request, refresh_token=False):
"""Create a JWT Token, using requestvalidator method."""
if callable(self.expires_in):
expires_in = self.expires_in(request)
else:
expires_in = self.expires_in
request.expires_in = expires_in
return ... | Create a JWT Token, using requestvalidator method. |
def remove_acl(cursor, uuid_, permissions):
"""Given a ``uuid`` and a set of permissions given as a tuple
of ``uid`` and ``permission``, remove these entries from the database.
"""
if not isinstance(permissions, (list, set, tuple,)):
raise TypeError("``permissions`` is an invalid type: {}"
... | Given a ``uuid`` and a set of permissions given as a tuple
of ``uid`` and ``permission``, remove these entries from the database. |
def sqlite_default():
'''
Prepend default scheme if none is specified. This helps provides backwards
compatibility with old versions of taxtastic where sqlite was the automatic
default database.
'''
def parse_url(url):
# TODO: need separate option for a config file
if url.endswit... | Prepend default scheme if none is specified. This helps provides backwards
compatibility with old versions of taxtastic where sqlite was the automatic
default database. |
def sin(duration: int, amp: complex, freq: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
"""Generates sine wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt. If `None` ... | Generates sine wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse. |
def datagram_handler(name, logname, host, port):
"""
A Bark logging handler logging output to a datagram (UDP) socket.
The server listening at the given 'host' and 'port' will be sent a
pickled dictionary.
Similar to logging.handlers.DatagramHandler.
"""
return wrap_log_handler(logging.han... | A Bark logging handler logging output to a datagram (UDP) socket.
The server listening at the given 'host' and 'port' will be sent a
pickled dictionary.
Similar to logging.handlers.DatagramHandler. |
def sanitize_ep(endpoint, plural=False):
"""
Sanitize an endpoint to a singular or plural form.
Used mostly for convenience in the `_parse` method to grab the raw
data from queried datasets.
XXX: this is el cheapo (no bastante bien)
"""
# if we need a plural end... | Sanitize an endpoint to a singular or plural form.
Used mostly for convenience in the `_parse` method to grab the raw
data from queried datasets.
XXX: this is el cheapo (no bastante bien) |
def manager(self, value):
"Set the manager object in the global _managers dict."
pid = current_process().ident
if _managers is None:
raise RuntimeError("Can not set the manager following a system exit.")
if pid not in _managers:
_managers[pid] = value
else... | Set the manager object in the global _managers dict. |
def muscle(sequences=None, alignment_file=None, fasta=None,
fmt='fasta', as_file=False, maxiters=None, diags=False,
gap_open=None, gap_extend=None, muscle_bin=None):
'''
Performs multiple sequence alignment with MUSCLE.
Args:
sequences (list): Sequences to be aligned. ``sequences`` can be ... | Performs multiple sequence alignment with MUSCLE.
Args:
sequences (list): Sequences to be aligned. ``sequences`` can be one of four things:
1. a FASTA-formatted string
2. a list of BioPython ``SeqRecord`` objects
3. a list of AbTools ``Sequence`` objects
... |
def make_bindings_type(filenames,color_input,colorkey,file_dictionary,sidebar,bounds):
# instantiating string the main string block for the javascript block of html code
string = ''
'''
# logic for instantiating variable colorkey input
if not colorkeyfields == False:
colorkey = 'selectedText'
'''
# iteratin... | # logic for instantiating variable colorkey input
if not colorkeyfields == False:
colorkey = 'selectedText' |
def proximal_quadratic_perturbation(prox_factory, a, u=None):
r"""Calculate the proximal of function F(x) + a * \|x\|^2 + <u,x>.
Parameters
----------
prox_factory : callable
A factory function that, when called with a step size, returns the
proximal operator of ``F``
a : non-negati... | r"""Calculate the proximal of function F(x) + a * \|x\|^2 + <u,x>.
Parameters
----------
prox_factory : callable
A factory function that, when called with a step size, returns the
proximal operator of ``F``
a : non-negative float
Scaling of the quadratic term
u : Element in ... |
def delete_field_value(self, name):
"""
Mark this field to be deleted
"""
name = self.get_real_name(name)
if name and self._can_write_field(name):
if name in self.__modified_data__:
self.__modified_data__.pop(name)
if name in self.__origi... | Mark this field to be deleted |
def values(self):
"""Return data in `self` as a numpy array.
If all columns are the same dtype, the resulting array
will have this dtype. If there are >1 dtypes in columns,
then the resulting array will have dtype `object`.
"""
dtypes = [col.dtype for col in self.columns... | Return data in `self` as a numpy array.
If all columns are the same dtype, the resulting array
will have this dtype. If there are >1 dtypes in columns,
then the resulting array will have dtype `object`. |
def plot(*args, ax=None, **kwargs):
"""
Plots but automatically resizes x axis.
.. versionadded:: 1.4
Parameters
----------
args
Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
The axis to plot to.
kwargs
Passed on to... | Plots but automatically resizes x axis.
.. versionadded:: 1.4
Parameters
----------
args
Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
The axis to plot to.
kwargs
Passed on to :meth:`matplotlib.axis.Axis.plot`. |
def _interactive_input_fn(hparams, decode_hp):
"""Generator that reads from the terminal and yields "interactive inputs".
Due to temporary limitations in tf.learn, if we don't want to reload the
whole graph, then we are stuck encoding all of the input as one fixed-size
numpy array.
We yield int32 arrays wit... | Generator that reads from the terminal and yields "interactive inputs".
Due to temporary limitations in tf.learn, if we don't want to reload the
whole graph, then we are stuck encoding all of the input as one fixed-size
numpy array.
We yield int32 arrays with shape [const_array_size]. The format is:
[num_s... |
def _validate_oneof(self, definitions, field, value):
""" {'type': 'list', 'logical': 'oneof'} """
valids, _errors = \
self.__validate_logical('oneof', definitions, field, value)
if valids != 1:
self._error(field, errors.ONEOF, _errors,
valids, len... | {'type': 'list', 'logical': 'oneof'} |
def set_change(name, change):
'''
Sets the time at which the password expires (in seconds since the UNIX
epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on
FreeBSD.
A value of ``0`` sets the password to never expire.
CLI Example:
.. code-block:: bash
salt '*' ... | Sets the time at which the password expires (in seconds since the UNIX
epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on
FreeBSD.
A value of ``0`` sets the password to never expire.
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 1419980400 |
def communicate(self, job_ids = None):
"""Communicates with the SGE grid (using qstat) to see if jobs are still running."""
self.lock()
# iterate over all jobs
jobs = self.get_jobs(job_ids)
for job in jobs:
job.refresh()
if job.status in ('queued', 'executing', 'waiting') and job.queue_n... | Communicates with the SGE grid (using qstat) to see if jobs are still running. |
def LinShuReductionFactor(axiPot,R,sigmar,nonaxiPot=None,
k=None,m=None,OmegaP=None):
"""
NAME:
LinShuReductionFactor
PURPOSE:
Calculate the Lin & Shu (1966) reduction factor: the reduced linear response of a kinematically-warm stellar disk to a perturbation
I... | NAME:
LinShuReductionFactor
PURPOSE:
Calculate the Lin & Shu (1966) reduction factor: the reduced linear response of a kinematically-warm stellar disk to a perturbation
INPUT:
axiPot - The background, axisymmetric potential
R - Cylindrical radius (can be Quantity)
... |
def register_command(self, namespace, command, method):
"""
Registers the given command to the shell.
The namespace can be None, empty or "default"
:param namespace: The command name space.
:param command: The shell name of the command
:param method: The method to call
... | Registers the given command to the shell.
The namespace can be None, empty or "default"
:param namespace: The command name space.
:param command: The shell name of the command
:param method: The method to call
:return: True if the method has been registered, False if it was
... |
def verify(self):
"""
## FOR DEBUGGING ONLY ##
Checks the table to ensure that the invariants are held.
"""
if self.all_intervals:
## top_node.all_children() == self.all_intervals
try:
assert self.top_node.all_children() == self.all_interva... | ## FOR DEBUGGING ONLY ##
Checks the table to ensure that the invariants are held. |
def to_table(result):
''' normalize raw result to table '''
max_count = 20
table, count = [], 0
for role, envs_topos in result.items():
for env, topos in envs_topos.items():
for topo in topos:
count += 1
if count > max_count:
continue
else:
table.append([rol... | normalize raw result to table |
def get_object_metadata(self, container, obj, prefix=None):
"""
Returns the metadata for the specified object as a dict.
"""
return self._manager.get_object_metadata(container, obj, prefix=prefix) | Returns the metadata for the specified object as a dict. |
def get(self, endpoint, params=None):
"""
Get items or item in alignak backend
If an error occurs, a BackendException is raised.
This method builds a response as a dictionary that always contains: _items and _status::
{
u'_items': [
...
... | Get items or item in alignak backend
If an error occurs, a BackendException is raised.
This method builds a response as a dictionary that always contains: _items and _status::
{
u'_items': [
...
],
u'_status': u'OK'
... |
def generate(self):
"""
:return: A new token
:rtype: str
"""
random_data = os.urandom(100)
hash_gen = hashlib.new("sha512")
hash_gen.update(random_data)
return hash_gen.hexdigest()[:self.token_length] | :return: A new token
:rtype: str |
def get_transfers(self, start=0, stop=None, inclusion_states=False):
# type: (int, Optional[int], bool) -> dict
"""
Returns all transfers associated with the seed.
:param start:
Starting key index.
:param stop:
Stop before this index.
Note t... | Returns all transfers associated with the seed.
:param start:
Starting key index.
:param stop:
Stop before this index.
Note that this parameter behaves like the ``stop`` attribute
in a :py:class:`slice` object; the stop index is *not*
includ... |
def _expand_list(names):
""" Do a wildchar name expansion of object names in a list and return expanded list.
The objects are expected to exist as this is used for copy sources or delete targets.
Currently we support wildchars in the key name only.
"""
if names is None:
names = []
elif isinstance(... | Do a wildchar name expansion of object names in a list and return expanded list.
The objects are expected to exist as this is used for copy sources or delete targets.
Currently we support wildchars in the key name only. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.