code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def edit_user(self, id, user_avatar_token=None, user_avatar_url=None, user_email=None, user_locale=None, user_name=None, user_short_name=None, user_sortable_name=None, user_time_zone=None):
"""
Edit a user.
Modify an existing user. To modify a user's login, see the documentation for logins.... | Edit a user.
Modify an existing user. To modify a user's login, see the documentation for logins. |
def get_func_sourcecode(func):
"""
Try to get sourcecode using standard inspect.getsource().
If the function comes from a module which has been created dynamically
(not from the filesystem), then it tries to read the sourcecode on the
filesystem anyway.
WARNING: can do weird things if the filesy... | Try to get sourcecode using standard inspect.getsource().
If the function comes from a module which has been created dynamically
(not from the filesystem), then it tries to read the sourcecode on the
filesystem anyway.
WARNING: can do weird things if the filesystem code slightly differs from
... |
def get_public(self):
'''
Returns the public object or None if there is no such element
@return: the public object
@rtype: L{Cpublic}
'''
node = self.node.find('public')
if node is not None:
return Cpublic(node=node)
else:
return No... | Returns the public object or None if there is no such element
@return: the public object
@rtype: L{Cpublic} |
def _default_headers(self):
"""Set the default header for a Twilio SendGrid v3 API call"""
headers = {
"Authorization": 'Bearer {}'.format(self.api_key),
"User-agent": self.useragent,
"Accept": 'application/json'
}
if self.impersonate_subuser:
... | Set the default header for a Twilio SendGrid v3 API call |
def uncache(self, name):
"""Remove all created query engines that match `name` from
the cache (this disconnects from MongoDB, which is the point).
:param name: Name used for :meth:`add`, or pattern
:return: None
"""
delme = []
if self._is_pattern(name):
... | Remove all created query engines that match `name` from
the cache (this disconnects from MongoDB, which is the point).
:param name: Name used for :meth:`add`, or pattern
:return: None |
def traceroute_batch(input_list, results={}, method="udp", cmd_arguments=None,
delay_time=0.1, max_threads=100):
"""
This is a parallel version of the traceroute primitive.
:param input_list: the input is a list of domain names
:param method: the packet type used for traceroute, UD... | This is a parallel version of the traceroute primitive.
:param input_list: the input is a list of domain names
:param method: the packet type used for traceroute, UDP by default
:param cmd_arguments: the list of arguments that need to be passed
to traceroute.
:param delay_time: ... |
def deprecated(message): # pragma: no cover
"""
Raise a `DeprecationWarning` when wrapped function/method is called.
Borrowed from https://stackoverflow.com/a/48632082/866026
"""
def deprecated_decorator(func):
"""Deprecation decorator."""
@wraps(func)
def deprecated_func... | Raise a `DeprecationWarning` when wrapped function/method is called.
Borrowed from https://stackoverflow.com/a/48632082/866026 |
def alter_and_get(self, function):
"""
Alters the currently stored value by applying a function on it and gets the result.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializab... | Alters the currently stored value by applying a function on it and gets the result.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server side with... |
def GNN_instance(x, idx=0, device=None, nh=20, **kwargs):
"""Run an instance of GNN, testing causal direction.
:param m: data corresponding to the config : (N, 2) data, [:, 0] cause and [:, 1] effect
:param pair_idx: print purposes
:param run: numner of the run (for GPU dispatch)
:param device: dev... | Run an instance of GNN, testing causal direction.
:param m: data corresponding to the config : (N, 2) data, [:, 0] cause and [:, 1] effect
:param pair_idx: print purposes
:param run: numner of the run (for GPU dispatch)
:param device: device on with the algorithm is going to be run on.
:return: |
def getCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Creates a generator to perform SNMP GET query.
When iterator gets advanced by :py:mod:`asyncio` main loop,
SNMP GET request is send (:RFC:`1905#section-4.2.1`).
The iterator yields :py:class:`asyncio.Fut... | Creates a generator to perform SNMP GET query.
When iterator gets advanced by :py:mod:`asyncio` main loop,
SNMP GET request is send (:RFC:`1905#section-4.2.1`).
The iterator yields :py:class:`asyncio.Future` which gets done whenever
response arrives or error occurs.
Parameters
----------
s... |
def sequences(self):
"""Returns the sequence of each `Polymer` in the `Assembly` as a list.
Returns
-------
sequences : [str]
List of sequences.
"""
seqs = [x.sequence for x in self._molecules if hasattr(x, 'sequence')]
return seqs | Returns the sequence of each `Polymer` in the `Assembly` as a list.
Returns
-------
sequences : [str]
List of sequences. |
def get_ins_off(self, off):
"""
Get a particular instruction by using the address
:param off: address of the instruction
:type off: int
:rtype: an :class:`Instruction` object
"""
idx = 0
for i in self.get_instructions():
if idx == off:
... | Get a particular instruction by using the address
:param off: address of the instruction
:type off: int
:rtype: an :class:`Instruction` object |
def find(value):
"""
returns a dictionary of rdfclasses based on the a lowercase search
args:
value: the value to search by
"""
value = str(value).lower()
rtn_dict = RegistryDictionary()
for attr in dir(MODULE.rdfclass):
if value in attr.l... | returns a dictionary of rdfclasses based on the a lowercase search
args:
value: the value to search by |
def load_stl(file_obj, file_type=None, **kwargs):
"""
Load an STL file from a file object.
Parameters
----------
file_obj: open file- like object
file_type: not used
Returns
----------
loaded: kwargs for a Trimesh constructor with keys:
vertices: (n,3) float, vert... | Load an STL file from a file object.
Parameters
----------
file_obj: open file- like object
file_type: not used
Returns
----------
loaded: kwargs for a Trimesh constructor with keys:
vertices: (n,3) float, vertices
faces: (m,3) int, indexes of vertice... |
def is_valid(self):
"""
Validates single instance. Returns boolean value and store errors in self.errors
"""
self.errors = []
for field in self.get_all_field_names_declared_by_user():
getattr(type(self), field).is_valid(self, type(self), field)
field_erro... | Validates single instance. Returns boolean value and store errors in self.errors |
def absent(name, persist=False, comment=True, mods=None):
'''
Verify that the named kernel module is not loaded
name
The name of the kernel module to verify is not loaded
persist
Remove module from ``/etc/modules``
comment
Comment out module in ``/etc/modules`` rather than... | Verify that the named kernel module is not loaded
name
The name of the kernel module to verify is not loaded
persist
Remove module from ``/etc/modules``
comment
Comment out module in ``/etc/modules`` rather than remove it
mods
A list of modules to verify are unloaded.... |
def read_pdb(pdbfname, as_string=False):
"""Reads a given PDB file and returns a Pybel Molecule."""
pybel.ob.obErrorLog.StopLogging() # Suppress all OpenBabel warnings
if os.name != 'nt': # Resource module not available for Windows
maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1]
re... | Reads a given PDB file and returns a Pybel Molecule. |
def mksls(src, dst=None):
'''
Convert a preseed file to an SLS file
'''
ps_opts = {}
with salt.utils.files.fopen(src, 'r') as fh_:
for line in fh_:
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
if not line... | Convert a preseed file to an SLS file |
def plugins():
'''Display some details about the local plugins'''
plugins = current_app.config['PLUGINS']
for name, description in entrypoints.ENTRYPOINTS.items():
echo('{0} ({1})'.format(white(description), name))
if name == 'udata.themes':
actives = [current_app.config['THEME']... | Display some details about the local plugins |
def _exec_module(
self,
fullname: str,
loader_state: Mapping[str, str],
path_stats: Mapping[str, int],
module: types.ModuleType,
):
"""Load and execute a non-cached Basilisp module."""
filename = loader_state["filename"]
cache_filename = loader_state["... | Load and execute a non-cached Basilisp module. |
def ngram_similarity(samegrams, allgrams, warp=1.0):
"""Similarity for two sets of n-grams.
:note: ``similarity = (a**e - d**e)/a**e`` where `a` is \
"all n-grams", `d` is "different n-grams" and `e` is the warp.
:param samegrams: number of n-grams shared by the two strings.
:... | Similarity for two sets of n-grams.
:note: ``similarity = (a**e - d**e)/a**e`` where `a` is \
"all n-grams", `d` is "different n-grams" and `e` is the warp.
:param samegrams: number of n-grams shared by the two strings.
:param allgrams: total of the distinct n-grams across the two str... |
def hmac_sha256(key, msg):
"""
Adapted from rransom's tor-utils git repository. Returns the
digest (binary) of an HMAC with SHA256 over msg with key.
"""
return hmac.new(key, msg, hashlib.sha256).digest() | Adapted from rransom's tor-utils git repository. Returns the
digest (binary) of an HMAC with SHA256 over msg with key. |
def _explode_raster(raster, band_names=[]):
# type: (_Raster, Iterable[str]) -> List[_Raster]
"""Splits a raster into multiband rasters.
"""
# Using band_names=[] does no harm because we are not mutating it in place
# and it makes MyPy happy
if not band_names:
band_names = raster.band_n... | Splits a raster into multiband rasters. |
def getenv(name, **kwargs):
"""
Retrieves environment variable by name and casts the value to desired type.
If desired type is list or tuple - uses separator to split the value.
"""
default_value = kwargs.pop('default', None)
desired_type = kwargs.pop('type', str)
list_separator = kwargs.pop... | Retrieves environment variable by name and casts the value to desired type.
If desired type is list or tuple - uses separator to split the value. |
def getPos(self):
"""
Returns the absolute position and size of the layer.
This method is intended for use in vertex position calculation, as the border and offset have already been applied.
The returned value is a 4-tuple of ``(sx,sy,ex,ey)``\ .
The two values ... | Returns the absolute position and size of the layer.
This method is intended for use in vertex position calculation, as the border and offset have already been applied.
The returned value is a 4-tuple of ``(sx,sy,ex,ey)``\ .
The two values starting with an s are the "start" pos... |
def render_to_string(self, *args, **kwargs):
"""Load and render a template into a unicode string."""
try:
template_name, args = args[0], args[1:]
except IndexError:
raise TypeError('name of template required')
return self.get_template(template_name).render(*args, ... | Load and render a template into a unicode string. |
def json(self):
"""
:return: JSON formatted string with instructions & values from Dockerfile
"""
insndescs = [{insndesc['instruction']: insndesc['value']} for insndesc in self.structure]
return json.dumps(insndescs) | :return: JSON formatted string with instructions & values from Dockerfile |
def _get_non_tempy_contents(self):
"""Returns rendered Contents and non-DOMElement stuff inside this Tag."""
for thing in filter(
lambda x: not issubclass(x.__class__, DOMElement), self.childs
):
yield thing | Returns rendered Contents and non-DOMElement stuff inside this Tag. |
def partition_source(src):
"""Partitions source into a list of `CodePartition`s for import
refactoring.
"""
# In python2, ast.parse(text_string_with_encoding_pragma) raises
# SyntaxError: encoding declaration in Unicode string
ast_obj = ast.parse(src.encode('UTF-8'))
visitor = TopLevelImport... | Partitions source into a list of `CodePartition`s for import
refactoring. |
def _find_header_row(self):
"""
Evaluate all rows and determine header position, based on
greatest number of 'th' tagged elements
"""
th_max = 0
header_idx = 0
for idx, tr in enumerate(self._tr_nodes):
th_count = len(tr.contents.filter_tags(matches=fta... | Evaluate all rows and determine header position, based on
greatest number of 'th' tagged elements |
def set_signal_handler(self, sigs=None):
"""Set the signal handler to manage_signal (defined in this class)
Only set handlers for:
- signal.SIGTERM, signal.SIGINT
- signal.SIGUSR1, signal.SIGUSR2
- signal.SIGHUP
:return: None
"""
if sigs is None:
... | Set the signal handler to manage_signal (defined in this class)
Only set handlers for:
- signal.SIGTERM, signal.SIGINT
- signal.SIGUSR1, signal.SIGUSR2
- signal.SIGHUP
:return: None |
def get_soap_locals(obj, Hpos, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0):
"""Get the RBF basis SOAP output for the given positions in a finite system.
Args:
obj(ase.Atoms): Atomic structure for which the SOAP output is
calculated.
Hpos: Positio... | Get the RBF basis SOAP output for the given positions in a finite system.
Args:
obj(ase.Atoms): Atomic structure for which the SOAP output is
calculated.
Hpos: Positions at which to calculate SOAP
alp: Alphas
bet: Betas
rCut: Radial cutoff.
nMax: Maximum ... |
def isInNet(host, pattern, mask):
"""
Pattern and mask specification is done the same way as for SOCKS configuration.
:param str host: a DNS hostname, or IP address.
If a hostname is passed, it will be resolved into an IP address by this function.
:param str pattern: an IP address pattern in th... | Pattern and mask specification is done the same way as for SOCKS configuration.
:param str host: a DNS hostname, or IP address.
If a hostname is passed, it will be resolved into an IP address by this function.
:param str pattern: an IP address pattern in the dot-separated format
:param str mask: ma... |
def _parse_array_member_state(self, block):
"""
Parse the state of the the md array members.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
... | Parse the state of the the md array members.
>>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n'
>>> ' 100171776 blocks super 1.2 [2/2] [UU]\n'
>>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n'
>>> print _parse_array_member_state(block)
{
... |
def melt(table, key=None, variables=None, variablefield='variable',
valuefield='value'):
"""
Reshape a table, melting fields into data. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'gender', 'age'],
... [1, 'F', 12],
... [2, 'M', 17],
.... | Reshape a table, melting fields into data. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'gender', 'age'],
... [1, 'F', 12],
... [2, 'M', 17],
... [3, 'M', 16]]
>>> table2 = etl.melt(table1, 'id')
>>> table2.lookall()
+-... |
def checkout(self):
'''
Checkout the targeted branches/tags from the git_pillar remotes
'''
self.pillar_dirs = OrderedDict()
self.pillar_linked_dirs = []
for repo in self.remotes:
cachedir = self.do_checkout(repo)
if cachedir is not None:
... | Checkout the targeted branches/tags from the git_pillar remotes |
def create_cache(self, **kwargs):
"""
Creates an instance of the Cache Service.
"""
cache = predix.admin.cache.Cache(**kwargs)
cache.create(**kwargs)
cache.add_to_manifest(self)
return cache | Creates an instance of the Cache Service. |
def convert_map_type(cls, name, value):
"""
Converts a map to a repeated RECORD that contains two fields: 'key' and 'value',
each will be converted to its corresponding data type in BQ.
"""
converted_map = []
for k, v in zip(value.keys(), value.values()):
conv... | Converts a map to a repeated RECORD that contains two fields: 'key' and 'value',
each will be converted to its corresponding data type in BQ. |
def min(self):
"""Minimum value."""
if self._prop.fmin is None:
return -_INF
return self._prop.fmin(self._obj) | Minimum value. |
def mp_calc_stats(motifs, fg_fa, bg_fa, bg_name=None):
"""Parallel calculation of motif statistics."""
try:
stats = calc_stats(motifs, fg_fa, bg_fa, ncpus=1)
except Exception as e:
raise
sys.stderr.write("ERROR: {}\n".format(str(e)))
stats = {}
if not bg_name:
bg... | Parallel calculation of motif statistics. |
def _write(self, session, openFile, replaceParamFile):
"""
Write HMET WES to File Method
"""
## TODO: Ensure Other HMET Formats are supported
hmetRecords = self.hmetRecords
for record in hmetRecords:
openFile.write('%s\t%s\t%s\t%s\t%.3f\t%s\t%s\t%s\t%s\t%.2f\... | Write HMET WES to File Method |
def check_remove_particle(st, ind, im_change_frac=0.2, min_derr='3sig',
**kwargs):
"""
Checks whether to remove particle 'ind' from state 'st'. If removing the
particle increases the error by less than max( min_derr, change in image *
im_change_frac), then the particle is remov... | Checks whether to remove particle 'ind' from state 'st'. If removing the
particle increases the error by less than max( min_derr, change in image *
im_change_frac), then the particle is removed.
Parameters
----------
st : :class:`peri.states.State`
The state to check adding particles to.
... |
def is_valid_password(password):
"""
Check if a password is valid
"""
pattern = re.compile(r"^.{4,75}$")
return bool(pattern.match(password)) | Check if a password is valid |
def split_auth_from_netloc(netloc):
"""
Parse out and remove the auth information from a netloc.
Returns: (netloc, (username, password)).
"""
if '@' not in netloc:
return netloc, (None, None)
# Split from the right because that's how urllib.parse.urlsplit()
# behaves if more than o... | Parse out and remove the auth information from a netloc.
Returns: (netloc, (username, password)). |
def gen_enum_completions(self, arg_name):
""" generates dynamic enumeration completions """
try: # if enum completion
for choice in self.cmdtab[self.current_command].arguments[arg_name].choices:
if self.validate_completion(choice):
yield Completion(choice... | generates dynamic enumeration completions |
def input_data(self):
"""Function to extract data from files according to pid.
This function will read in the data with
:class:`bowie.plotutils.readdata.ReadInData`.
"""
ordererd = np.sort(np.asarray(list(self.plot_info.keys())).astype(int))
trans_cont_dict = OrderedDi... | Function to extract data from files according to pid.
This function will read in the data with
:class:`bowie.plotutils.readdata.ReadInData`. |
def _parse_object_header(self, header_line):
"""
:param header_line:
<hex_sha> type_string size_as_int
:return: (hex_sha, type_string, size_as_int)
:raise ValueError: if the header contains indication for an error due to
incorrect input sha"""
tokens = h... | :param header_line:
<hex_sha> type_string size_as_int
:return: (hex_sha, type_string, size_as_int)
:raise ValueError: if the header contains indication for an error due to
incorrect input sha |
def get(self, id):
"""
Return an instance based on the given primary key identifier,
or None if not found.
This returns a record whether active or not.
"""
ctx = self.context.copy()
ctx['active_test'] = False
results = self.rpc_model.search_read(
... | Return an instance based on the given primary key identifier,
or None if not found.
This returns a record whether active or not. |
def _init_metadata(self):
"""stub"""
self._start_timestamp_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'start_timestamp'),
'element_label': 'start timestamp',
... | stub |
def data_preprocess(data, size=None, min_axis=None, batch=False):
"""
Takes data and prepares it for sending to the api including
resizing and image data/structure standardizing.
"""
if batch:
return [data_preprocess(el, size=size, min_axis=min_axis, batch=False) for el in data]
if isin... | Takes data and prepares it for sending to the api including
resizing and image data/structure standardizing. |
def _parse_mode(self, mode, allowed=None, single=False):
r"""
This private method is for checking the \'mode\' used in the calling
method.
Parameters
----------
mode : string or list of strings
The mode(s) to be parsed
allowed : list of strings
... | r"""
This private method is for checking the \'mode\' used in the calling
method.
Parameters
----------
mode : string or list of strings
The mode(s) to be parsed
allowed : list of strings
A list containing the allowed modes. This list is defined... |
def parse_dereplicated_uc(dereplicated_uc_lines):
""" Return dict of seq ID:dereplicated seq IDs from dereplicated .uc lines
dereplicated_uc_lines: list of lines of .uc file from dereplicated seqs from
usearch61 (i.e. open file of abundance sorted .uc data)
"""
dereplicated_clusters = {}
see... | Return dict of seq ID:dereplicated seq IDs from dereplicated .uc lines
dereplicated_uc_lines: list of lines of .uc file from dereplicated seqs from
usearch61 (i.e. open file of abundance sorted .uc data) |
def get_client(self, client_id):
"""
Returns details about a specific client by the client_id.
"""
self.assert_has_permission('clients.read')
uri = self.uri + '/oauth/clients/' + client_id
headers = self.get_authorization_headers()
response = requests.get(uri, he... | Returns details about a specific client by the client_id. |
def sentences(self):
"""Iterate over all sentences (sentence_id, sentence) in the document, sentence is a list of 4-tuples (word,id,pos,lemma)"""
prevp = 0
prevs = 0
sentence = [];
sentence_id = ""
for word, id, pos, lemma in iter(self):
try:
d... | Iterate over all sentences (sentence_id, sentence) in the document, sentence is a list of 4-tuples (word,id,pos,lemma) |
def _latex_(self):
r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^... | r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^{3}' |
def add_page(self, route, target, link_name=None):
"""Add a new proxied page to the Web UI.
Parameters
----------
route : str
The route for the proxied page. Must be a valid path *segment* in a
url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique
... | Add a new proxied page to the Web UI.
Parameters
----------
route : str
The route for the proxied page. Must be a valid path *segment* in a
url (e.g. ``foo`` in ``/foo/bar/baz``). Routes must be unique
across the application.
target : str
... |
def bfd(self, **kwargs):
"""Configure BFD for Interface.
Args:
name (str): name of the interface to configure (230/0/1 etc)
int_type (str): interface type (gigabitethernet etc)
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
rx (str): BFD ... | Configure BFD for Interface.
Args:
name (str): name of the interface to configure (230/0/1 etc)
int_type (str): interface type (gigabitethernet etc)
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
rx (str): BFD receive interval in milliseconds (30... |
def set_model_doc_string(model, doc, override=False):
"""
Sets the doc string of the ONNX model.
:param model: instance of an ONNX model
:param doc: string containing the doc string that describes the model.
:param override: bool if true will always override the doc string with the new value
E... | Sets the doc string of the ONNX model.
:param model: instance of an ONNX model
:param doc: string containing the doc string that describes the model.
:param override: bool if true will always override the doc string with the new value
Example:
::
from onnxmltools.utils import set_model_do... |
def open(self, new=1):
"""
Open this viewer in a new browser window or tab.
(requires `webbrowser` module)
"""
import webbrowser
webbrowser.open(self.url, new=new) | Open this viewer in a new browser window or tab.
(requires `webbrowser` module) |
def _folder_to_dict(self, path):
"""
Recursively reads the files from the directory given by `path` and
writes their contents to a nested dictionary, which is then returned.
"""
res = {}
for key in os.listdir(path):
if key.startswith('.'):
cont... | Recursively reads the files from the directory given by `path` and
writes their contents to a nested dictionary, which is then returned. |
def registration_settings(request):
'''Expose selected settings to templates'''
context = {}
for setting in (
'WAFER_SSO',
'WAFER_HIDE_LOGIN',
'WAFER_REGISTRATION_OPEN',
'WAFER_REGISTRATION_MODE',
'WAFER_TALKS_OPEN',
'WAFER_VIDEO_LICENS... | Expose selected settings to templates |
def get_erasure_profile(service, name):
"""
:param service: six.string_types. The Ceph user name to run the command under
:param name:
:return:
"""
try:
out = check_output(['ceph', '--id', service,
'osd', 'erasure-code-profile', 'get',
... | :param service: six.string_types. The Ceph user name to run the command under
:param name:
:return: |
def raises(self, exc):
"""Set last call to raise an exception class or instance.
For example::
>>> import fudge
>>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert"))
>>> db.insert()
Traceback (most recent cal... | Set last call to raise an exception class or instance.
For example::
>>> import fudge
>>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert"))
>>> db.insert()
Traceback (most recent call last):
...
... |
def infer_location(
self,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
"""In-place location inferring
See infer_location function
Args:
Retu... | In-place location inferring
See infer_location function
Args:
Returns:
:obj:`Segment`: self |
def stop(self):
'cleans up and stops the discovery server'
self.clearRemoteServices()
self.clearLocalServices()
self._stopThreads()
self._serverStarted = False | cleans up and stops the discovery server |
def truncate_cwd(full_filename):
"""Remove the cwd from the full filename."""
if full_filename.startswith(os.getcwd()):
truncated_filename = full_filename.split(os.getcwd(), 1)[1]
truncated_filename = truncated_filename.split(os.sep, 1)[1]
else:
truncated_filename = full_filename
... | Remove the cwd from the full filename. |
def __create_event(self):
""" Create an SQLAlchemy event listening the 'set' in a particular column.
:rtype : object
"""
if not event.contains(self.field, 'set', self.__validate):
event.listen(self.field, 'set', self.__validate, retval=True) | Create an SQLAlchemy event listening the 'set' in a particular column.
:rtype : object |
def precise_matcher(text_log_error):
"""Query for TextLogErrorMatches identical to matches of the given TextLogError."""
failure_line = text_log_error.metadata.failure_line
logger.debug("Looking for test match in failure %d", failure_line.id)
if failure_line.action != "test_result" or failure_line.mess... | Query for TextLogErrorMatches identical to matches of the given TextLogError. |
def Tb(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[PSAT_DEFINITION]):
r'''This function handles the retrieval of a chemical's boiling
point. Lookup is based on CASRNs. Will automatically select a data
source to use if no Method is provided; returns None if the data is not
available.
... | r'''This function handles the retrieval of a chemical's boiling
point. Lookup is based on CASRNs. Will automatically select a data
source to use if no Method is provided; returns None if the data is not
available.
Prefered sources are 'CRC Physical Constants, organic' for organic
chemicals, and 'CR... |
def as_iframe(self, html_data):
"""Build the HTML representation for the mapviz."""
srcdoc = html_data.replace('"', "'")
return ('<iframe id="{div_id}", srcdoc="{srcdoc}" style="width: {width}; '
'height: {height};"></iframe>'.format(
div_id=self.div_id,
... | Build the HTML representation for the mapviz. |
def mcscanx(args):
"""
%prog mcscanx athaliana.athaliana.last athaliana.bed
Wrap around MCScanX.
"""
p = OptionParser(mcscanx.__doc__)
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
blastfile = args[0]
bedfiles = args[1:]
prefix = "_".jo... | %prog mcscanx athaliana.athaliana.last athaliana.bed
Wrap around MCScanX. |
def isEmpty(self):
"""
Is a given array, string, or object empty?
An "empty" object has no enumerable own-properties.
"""
if self.obj is None:
return True
if self._clean.isString():
ret = self.obj.strip() is ""
elif self._clean.isDict():
... | Is a given array, string, or object empty?
An "empty" object has no enumerable own-properties. |
def validate_overlap(self,force):
"""Validate that spectrum and bandpass overlap.
Warnings are stored in ``self.warnings``.
Parameters
----------
force : {'extrap', 'taper', `None`}
If `None`, it is required that the spectrum and bandpass fully
overlap. P... | Validate that spectrum and bandpass overlap.
Warnings are stored in ``self.warnings``.
Parameters
----------
force : {'extrap', 'taper', `None`}
If `None`, it is required that the spectrum and bandpass fully
overlap. Partial overlap is allowed if this is set to
... |
def run_r_script(r_script_filename, cwd = '.'):
'''This function was adapted from the covariation benchmark.'''
p = subprocess.Popen(["R", "CMD", "BATCH", r_script_filename], cwd = cwd)
while True:
time.sleep(0.3)
errcode = p.poll()
if errcode != None:
break
rout = "{... | This function was adapted from the covariation benchmark. |
def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Set header data"""
if role != Qt.DisplayRole:
return to_qvariant()
labels = self.xlabels if orientation == Qt.Horizontal else self.ylabels
if labels is None:
return to_qvariant(int(section))... | Set header data |
def config_mode(self, config_command="sudo su"):
"""Attempt to become root."""
delay_factor = self.select_delay_factor(delay_factor=1)
output = ""
if not self.check_config_mode():
output += self.send_command_timing(
config_command, strip_prompt=False, strip_co... | Attempt to become root. |
def set_temperature(self, temperature):
"""
Initializes the velocities based on Maxwell-Boltzmann distribution.
Removes linear, but not angular drift (same as VASP)
Scales the energies to the exact temperature (microcanonical ensemble)
Velocities are given in A/fs. This is the v... | Initializes the velocities based on Maxwell-Boltzmann distribution.
Removes linear, but not angular drift (same as VASP)
Scales the energies to the exact temperature (microcanonical ensemble)
Velocities are given in A/fs. This is the vasp default when
direct/cartesian is not specified (... |
def assert_sigfigs_equal(x, y, sigfigs=3):
"""
Tests if all elements in x and y
agree up to a certain number of
significant figures.
:param np.ndarray x: Array of numbers.
:param np.ndarray y: Array of numbers you want to
be equal to ``x``.
:param int sigfigs: How many significant
... | Tests if all elements in x and y
agree up to a certain number of
significant figures.
:param np.ndarray x: Array of numbers.
:param np.ndarray y: Array of numbers you want to
be equal to ``x``.
:param int sigfigs: How many significant
figures you demand that they share.
Defa... |
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
... | Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict |
def ignore_comments(iterator):
"""
Strips and filters empty or commented lines.
"""
for line in iterator:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield line | Strips and filters empty or commented lines. |
def solution(events, slots, objective_function=None, solver=None, **kwargs):
"""Compute a schedule in solution form
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
solver : pulp.s... | Compute a schedule in solution form
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
solver : pulp.solver
a pulp solver
objective_function: callable
from lp_problem... |
def html_color_to_rgba(html_colour, alpha):
"""
:param html_colour: Colour string like FF0088
:param alpha: Alpha value (opacity)
:return: RGBA semitransparent version of colour for use in css
"""
html_colour = html_colour.upper()
if html_colour[0] == '#':
html_colour = html_colour[1... | :param html_colour: Colour string like FF0088
:param alpha: Alpha value (opacity)
:return: RGBA semitransparent version of colour for use in css |
def detectEquilibration(A_t, fast=True, nskip=1):
"""Automatically detect equilibrated region of a dataset using a heuristic that maximizes number of effectively uncorrelated samples.
Parameters
----------
A_t : np.ndarray
timeseries
nskip : int, optional, default=1
number of sampl... | Automatically detect equilibrated region of a dataset using a heuristic that maximizes number of effectively uncorrelated samples.
Parameters
----------
A_t : np.ndarray
timeseries
nskip : int, optional, default=1
number of samples to sparsify data by in order to speed equilibration de... |
def build_row(row, left, center, right):
"""Combine single or multi-lined cells into a single row of list of lists including borders.
Row must already be padded and extended so each cell has the same number of lines.
Example return value:
[
['>', 'Left ', '|', 'Center', '|', 'Right', '<'],
... | Combine single or multi-lined cells into a single row of list of lists including borders.
Row must already be padded and extended so each cell has the same number of lines.
Example return value:
[
['>', 'Left ', '|', 'Center', '|', 'Right', '<'],
['>', 'Cell1', '|', 'Cell2 ', '|', 'Cell3',... |
def list_clients():
"""
List all the servers that are running.
"""
p = '%s/pymux.sock.%s.*' % (tempfile.gettempdir(), getpass.getuser())
for path in glob.glob(p):
try:
yield PosixClient(path)
except socket.error:
pass | List all the servers that are running. |
def is_full(cls, pid):
"""Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return cls._pools[pid].is_full | Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool |
def from_list(cls, values):
"""Construct a tree from a list with paths."""
self = cls()
for value in values:
self.add(value)
return self | Construct a tree from a list with paths. |
def matrix_product(mat1, mat2):
"""Compute the product of two Fortran contiguous matrices.
This is to avoid the overhead of NumPy converting to C-contiguous
before computing a matrix product.
Does so via ``A B = (B^T A^T)^T`` since ``B^T`` and ``A^T`` will be
C-contiguous without a copy, then the ... | Compute the product of two Fortran contiguous matrices.
This is to avoid the overhead of NumPy converting to C-contiguous
before computing a matrix product.
Does so via ``A B = (B^T A^T)^T`` since ``B^T`` and ``A^T`` will be
C-contiguous without a copy, then the product ``P = B^T A^T`` will
be C-c... |
def create_items(self):
"""
Create collidable items
"""
if not self.mode['items'] or len(self.mode['items']) == 0: return
# FIXME: Check if already contains
self.collman.add(self.player)
for k in self.mode['items']:
item = self.mode['items'][k]
... | Create collidable items |
def muscle_seqs(seqs,
add_seq_names=False,
out_filename=None,
input_handler=None,
params={},
WorkingDir=tempfile.gettempdir(),
SuppressStderr=None,
SuppressStdout=None):
"""Muscle align list of seq... | Muscle align list of sequences.
seqs: a list of sequences as strings or objects, you must set add_seq_names=True
or sequences in a multiline string, as read() from a fasta file
or sequences in a list of lines, as readlines() from a fasta file
or a fasta seq filename.
== for eg, testcode for guessi... |
def papermill_process(self, nb_man, resources):
"""
This function acts as a replacement for the grandparent's `preprocess`
method.
We are doing this for the following reasons:
1. Notebooks will stop executing when they encounter a failure but not
raise a `CellExcepti... | This function acts as a replacement for the grandparent's `preprocess`
method.
We are doing this for the following reasons:
1. Notebooks will stop executing when they encounter a failure but not
raise a `CellException`. This allows us to save the notebook with the
traceba... |
def _combined_items(self):
"""Returns a dictionary with this object's properties merged with all its parent's
properties.
The returned dictionary is all the available properties for this object (and their
associated values).
"""
result = dict(self._items)
par = s... | Returns a dictionary with this object's properties merged with all its parent's
properties.
The returned dictionary is all the available properties for this object (and their
associated values). |
def iter_encode(self, obj):
'''The iterative version of `arff.ArffEncoder.encode`.
This encodes iteratively a given object and return, one-by-one, the
lines of the ARFF file.
:param obj: the object containing the ARFF information.
:return: (yields) the ARFF file as unicode stri... | The iterative version of `arff.ArffEncoder.encode`.
This encodes iteratively a given object and return, one-by-one, the
lines of the ARFF file.
:param obj: the object containing the ARFF information.
:return: (yields) the ARFF file as unicode strings. |
def repeat(obj, times=None):
"""Make an iterator that returns object over and over again."""
if times is None:
return AsyncIterWrapper(sync_itertools.repeat(obj))
return AsyncIterWrapper(sync_itertools.repeat(obj, times)) | Make an iterator that returns object over and over again. |
def wrap_json(cls, json):
"""Create a Stream instance for the given json
:param json: the dict with the information of the stream
:type json: :class:`dict` | None
:returns: the new stream instance
:rtype: :class:`Stream` | None
:raises: None
"""
if json i... | Create a Stream instance for the given json
:param json: the dict with the information of the stream
:type json: :class:`dict` | None
:returns: the new stream instance
:rtype: :class:`Stream` | None
:raises: None |
def set_pkg_source_info(self, doc, text):
"""Sets the package's source information, if not already set.
text - Free form text.
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined.
SPDXValueError if text is not free form text.
"""... | Sets the package's source information, if not already set.
text - Free form text.
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined.
SPDXValueError if text is not free form text. |
def scale_and_crop_with_ranges(
im, size, size_range=None, crop=False, upscale=False, zoom=None, target=None, **kwargs):
"""
An easy_thumbnails processor that accepts a `size_range` tuple, which
indicates that one or both dimensions can give by a number of pixels in
order to minimize cropping.
"... | An easy_thumbnails processor that accepts a `size_range` tuple, which
indicates that one or both dimensions can give by a number of pixels in
order to minimize cropping. |
def add_rich_rule(zone, rule, permanent=True):
'''
Add a rich rule to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_rich_rule zone 'rule'
'''
cmd = "--zone={0} --add-rich-rule='{1}'".format(zone, rule)
if permanent:
cmd +... | Add a rich rule to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_rich_rule zone 'rule' |
def execute(self, input_data):
''' Execute Method '''
# View on all the meta data files in the sample
fields = ['filename', 'md5', 'length', 'customer', 'import_time', 'type_tag']
view = {key:input_data['meta'][key] for key in fields}
return view | Execute Method |
def unquote(text):
"""Replace all percent-encoded entities in text."""
while '%' in text:
newtext = url_unquote(text)
if newtext == text:
break
text = newtext
return text | Replace all percent-encoded entities in text. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.