code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def setDocument(self, filename, empty=""):
"""Sets the HTML text to be displayed. """
self._source = QUrl.fromLocalFile(filename)
if os.path.exists(filename):
self.viewer.setSource(self._source)
else:
self.viewer.setText(empty) | Sets the HTML text to be displayed. |
def _native_size(self):
"""
A (width, height) 2-tuple representing the native dimensions of the
image in EMU, calculated based on the image DPI value, if present,
assuming 72 dpi as a default.
"""
EMU_PER_INCH = 914400
horz_dpi, vert_dpi = self._dpi
width_... | A (width, height) 2-tuple representing the native dimensions of the
image in EMU, calculated based on the image DPI value, if present,
assuming 72 dpi as a default. |
def dskcls(handle, optmiz=False):
"""
Close a DSK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskcls_c.html
:param handle: Handle assigned to the opened DSK file.
:type handle: int
:param optmiz: Flag indicating whether to segregate the DSK.
:type optmiz: bool
:... | Close a DSK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskcls_c.html
:param handle: Handle assigned to the opened DSK file.
:type handle: int
:param optmiz: Flag indicating whether to segregate the DSK.
:type optmiz: bool
:return: |
def execution_request(self, products, subjects):
"""Create and return an ExecutionRequest for the given products and subjects.
The resulting ExecutionRequest object will contain keys tied to this scheduler's product Graph,
and so it will not be directly usable with other scheduler instances without being r... | Create and return an ExecutionRequest for the given products and subjects.
The resulting ExecutionRequest object will contain keys tied to this scheduler's product Graph,
and so it will not be directly usable with other scheduler instances without being re-created.
NB: This method does a "cross product", ... |
def register_event(self, pattern, callback=None):
"""register an event. See :class:`~panoramisk.message.Message`:
.. code-block:: python
>>> def callback(manager, event):
... print(manager, event)
>>> manager = Manager()
>>> manager.register_event('M... | register an event. See :class:`~panoramisk.message.Message`:
.. code-block:: python
>>> def callback(manager, event):
... print(manager, event)
>>> manager = Manager()
>>> manager.register_event('Meetme*', callback)
<function callback at 0x...>
... |
def get_all_context_names(context_num):
"""Based on the nucleotide base context number, return
a list of strings representing each context.
Parameters
----------
context_num : int
number representing the amount of nucleotide base context to use.
Returns
-------
a list of st... | Based on the nucleotide base context number, return
a list of strings representing each context.
Parameters
----------
context_num : int
number representing the amount of nucleotide base context to use.
Returns
-------
a list of strings containing the names of the base contexts |
def best_match(self, matches):
"""
Find the most similar string to self.target.
Given a list of candidate strings find the closest match to
self.target, returning the best match with a score indicating closeness
of match.
:param matches: A list of candidate matches
... | Find the most similar string to self.target.
Given a list of candidate strings find the closest match to
self.target, returning the best match with a score indicating closeness
of match.
:param matches: A list of candidate matches
:returns: A tuple of (score, best_match) |
def maybe_convert_to_index_date_type(index, date):
"""Convert a datetime-like object to the index's date type.
Datetime indexing in xarray can be done using either a pandas
DatetimeIndex or a CFTimeIndex. Both support partial-datetime string
indexing regardless of the calendar type of the underlying d... | Convert a datetime-like object to the index's date type.
Datetime indexing in xarray can be done using either a pandas
DatetimeIndex or a CFTimeIndex. Both support partial-datetime string
indexing regardless of the calendar type of the underlying data;
therefore if a string is passed as a date, we ret... |
def waitUntilFinished(self):
"""
Processes the main thread until the loading process has finished. This
is a way to force the main thread to be synchronous in its execution.
"""
QtCore.QCoreApplication.processEvents()
while self.isLoading():
QtCore.QCo... | Processes the main thread until the loading process has finished. This
is a way to force the main thread to be synchronous in its execution. |
def close(self):
"""
Close the stream and the underlying XML stream (if any is connected).
This is essentially a way of saying "I do not want to use this stream
anymore" (until the next call to :meth:`start`). If the stream is
currently running, the XML stream is closed graceful... | Close the stream and the underlying XML stream (if any is connected).
This is essentially a way of saying "I do not want to use this stream
anymore" (until the next call to :meth:`start`). If the stream is
currently running, the XML stream is closed gracefully (potentially
sending an SM... |
def check_fare_attributes(
feed: "Feed", *, as_df: bool = False, include_warnings: bool = False
) -> List:
"""
Analog of :func:`check_agency` for ``feed.calendar_dates``.
"""
table = "fare_attributes"
problems = []
# Preliminary checks
if feed.fare_attributes is None:
return pro... | Analog of :func:`check_agency` for ``feed.calendar_dates``. |
def superable(cls) :
'''Provide .__super in python 2.x classes without having to specify the current
class name each time super is used (DRY principle).'''
name = cls.__name__
super_name = '_%s__super' % (name,)
setattr(cls,super_name,super(cls))
return cls | Provide .__super in python 2.x classes without having to specify the current
class name each time super is used (DRY principle). |
def _InternalUnpackAny(msg):
"""Unpacks Any message and returns the unpacked message.
This internal method is differnt from public Any Unpack method which takes
the target message as argument. _InternalUnpackAny method does not have
target message type and need to find the message type in descriptor pool.
A... | Unpacks Any message and returns the unpacked message.
This internal method is differnt from public Any Unpack method which takes
the target message as argument. _InternalUnpackAny method does not have
target message type and need to find the message type in descriptor pool.
Args:
msg: An Any message to be... |
def main():
"""Ideally we shouldn't lose the first second of events"""
with Input() as input_generator:
def extra_bytes_callback(string):
print('got extra bytes', repr(string))
print('type:', type(string))
input_generator.unget_bytes(string)
time.sleep(1)
... | Ideally we shouldn't lose the first second of events |
def is_enabled_path(path):
"""
Determine whether or not the path matches one or more paths
in the ENABLED_PATHS setting.
:param path: A string describing the path to be matched.
"""
for enabled_path in ENABLED_PATHS:
match = re.search(enabled_path, path[1:])
if match:
... | Determine whether or not the path matches one or more paths
in the ENABLED_PATHS setting.
:param path: A string describing the path to be matched. |
def num_extra_bytes(self):
""" Returns the number of extra bytes
"""
return sum(np.dtype(extra_dim[1]).itemsize for extra_dim in self.extra_dims) | Returns the number of extra bytes |
def generate_main(main, language):
'''
generate output code for main in `language`
`main` is a dict/Node or a list of dicts/Nodes with pseudo ast
e.g.
> print(generate_main({'type': 'int', 'value': 0, 'pseudo_type': 'Int'}, 'rb'))
2
> print(generate_main([pseudo.pseudo_tree.to_node('a'), p... | generate output code for main in `language`
`main` is a dict/Node or a list of dicts/Nodes with pseudo ast
e.g.
> print(generate_main({'type': 'int', 'value': 0, 'pseudo_type': 'Int'}, 'rb'))
2
> print(generate_main([pseudo.pseudo_tree.to_node('a'), pseudo.pseudo_tree.to_node(0)], 'js'))
'a';
... |
def dropEvent( self, event ):
"""
Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDropEvent>
"""
filt = self.dragDropFilter()
if ( filt and not filt(self, event) ):
return
su... | Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDropEvent> |
def timestamp(x):
"""Get a timestamp from a date in python 3 and python 2"""
if x.tzinfo is None:
# Naive dates to utc
x = x.replace(tzinfo=utc)
if hasattr(x, 'timestamp'):
return x.timestamp()
else:
return (x - datetime(1970, 1, 1, tzinfo=utc)).total_seconds() | Get a timestamp from a date in python 3 and python 2 |
def start(bt_device=''):
'''
Attributes:
device (string): BLE device (default hci0)
'''
# import ptyprocess here so as long as all implementations are in the same file, all will work
import ptyprocess
if not bt_device:
bt_device = 'hci0'
l... | Attributes:
device (string): BLE device (default hci0) |
def urls(cls):
"""Builds the URL configuration for this resource."""
return urls.patterns('', urls.url(
r'^{}(?:$|(?P<path>[/:(.].*))'.format(cls.meta.name),
cls.view,
name='armet-api-{}'.format(cls.meta.name),
kwargs={'resource': cls.meta.name})) | Builds the URL configuration for this resource. |
def add_inputs(self, private_key=None, address=None, amount='all', max_ins=None, password=None, services=None, **modes):
"""
Make call to external service to get inputs from an address and/or private_key.
`amount` is the amount of [currency] worth of inputs (in satoshis) to add from
this... | Make call to external service to get inputs from an address and/or private_key.
`amount` is the amount of [currency] worth of inputs (in satoshis) to add from
this address. Pass in 'all' (the default) to use *all* inputs found for this address.
Returned is the number of units (in satoshis) that... |
def inv_logistic(y: Union[float, np.ndarray],
k: float,
theta: float) -> Optional[float]:
r"""
Inverse standard logistic function:
.. math::
x = ( log( \frac {1} {y} - 1) / -k ) + \theta
Args:
y: :math:`y`
k: :math:`k`
theta: :math:`\t... | r"""
Inverse standard logistic function:
.. math::
x = ( log( \frac {1} {y} - 1) / -k ) + \theta
Args:
y: :math:`y`
k: :math:`k`
theta: :math:`\theta`
Returns:
:math:`x` |
def create_item(self, item_form):
"""Creates a new ``Item``.
arg: item_form (osid.assessment.ItemForm): the form for this
``Item``
return: (osid.assessment.Item) - the new ``Item``
raise: IllegalState - ``item_form`` already used in a create
transacti... | Creates a new ``Item``.
arg: item_form (osid.assessment.ItemForm): the form for this
``Item``
return: (osid.assessment.Item) - the new ``Item``
raise: IllegalState - ``item_form`` already used in a create
transaction
raise: InvalidArgument - one or m... |
def calc_wgtf_v1(self):
"""Calculate the potential snowmelt.
Required control parameters:
|NHRU|
|Lnk|
|GTF|
|TRefT|
|TRefN|
|RSchmelz|
|CPWasser|
Required flux sequence:
|TKor|
Calculated fluxes sequence:
|WGTF|
Basic equation:
:math:`... | Calculate the potential snowmelt.
Required control parameters:
|NHRU|
|Lnk|
|GTF|
|TRefT|
|TRefN|
|RSchmelz|
|CPWasser|
Required flux sequence:
|TKor|
Calculated fluxes sequence:
|WGTF|
Basic equation:
:math:`WGTF = max(GTF \\cdot (TKor - T... |
def create_footprints_gdf(polygon=None, north=None, south=None, east=None, west=None,
footprint_type='building', retain_invalid=False):
"""
Get footprint data from OSM then assemble it into a GeoDataFrame.
Parameters
----------
polygon : shapely Polygon or MultiPolygon
... | Get footprint data from OSM then assemble it into a GeoDataFrame.
Parameters
----------
polygon : shapely Polygon or MultiPolygon
geographic shape to fetch the footprints within
north : float
northern latitude of bounding box
south : float
southern latitude of bounding box
... |
def set_embedded_doc(self, document, form_key, current_key, remaining_key):
"""Get the existing embedded document if it exists, else created it."""
embedded_doc = getattr(document, current_key, False)
if not embedded_doc:
embedded_doc = document._fields[current_key].document_type_ob... | Get the existing embedded document if it exists, else created it. |
def num_gpus(): # type: () -> int
"""The number of gpus available in the current container.
Returns:
int: number of gpus available in the current container.
"""
try:
cmd = shlex.split('nvidia-smi --list-gpus')
output = subprocess.check_output(cmd).decode('utf-8')
return... | The number of gpus available in the current container.
Returns:
int: number of gpus available in the current container. |
def get_associated(self, klass_node, level):
"""return associated nodes of a class node"""
if level == 0:
return
for association_nodes in list(klass_node.instance_attrs_type.values()) + list(
klass_node.locals_type.values()
):
for node in association_n... | return associated nodes of a class node |
def update_file(self, value, relativePath, description=False,
dump=False, pull=False, raiseError=True, ntrials=3):
"""
Update the value of a file that is already in the Repository.\n
If file is not registered in repository, and error will be thrown.\n
If file is... | Update the value of a file that is already in the Repository.\n
If file is not registered in repository, and error will be thrown.\n
If file is missing in the system, it will be regenerated as dump method
is called.
Unlike dump_file, update_file won't block the whole repository but only
... |
def sync(sourcedir=None, exclude_gitignore_entries=None, exclude_regex_list=None):
""" Create and populate workdir.options.path, memoized so that it only runs once """
_set_log_level()
sourcedir = sourcedir or options.sync_sourcedir or os.getcwd()
if exclude_gitignore_entries is None:
exclude_gi... | Create and populate workdir.options.path, memoized so that it only runs once |
def install(name, minimum_version=None, required_version=None, scope=None,
repository=None):
'''
Install a Powershell module from powershell gallery on the system.
:param name: Name of a Powershell module
:type name: ``str``
:param minimum_version: The maximum version to install, e.g.... | Install a Powershell module from powershell gallery on the system.
:param name: Name of a Powershell module
:type name: ``str``
:param minimum_version: The maximum version to install, e.g. 1.23.2
:type minimum_version: ``str``
:param required_version: Install a specific version
:type requi... |
def invalidate_ip(self, ip):
"""
Invalidate httpBL cache for IP address
:param ip: ipv4 IP address
"""
if self._use_cache:
key = self._make_cache_key(ip)
self._cache.delete(key, version=self._cache_version) | Invalidate httpBL cache for IP address
:param ip: ipv4 IP address |
def doAction(self, w, action):
"""Perform the proper action
"""
#set environment for the UpperCaseFirst
U = self.upperCase1
return eval(self.actionList[action], locals()) | Perform the proper action |
def file_to_png(fp):
"""Convert an image to PNG format with Pillow.
:arg file-like fp: The image file.
:rtype: bytes
"""
import PIL.Image # pylint: disable=import-error
with io.BytesIO() as dest:
PIL.Image.open(fp).save(dest, "PNG", optimize=True)
return dest.getvalue() | Convert an image to PNG format with Pillow.
:arg file-like fp: The image file.
:rtype: bytes |
def mysql_to_dict(data, key):
'''
Convert MySQL-style output to a python dictionary
'''
ret = {}
headers = ['']
for line in data:
if not line:
continue
if line.startswith('+'):
continue
comps = line.split('|')
for comp in range(len(comps)):... | Convert MySQL-style output to a python dictionary |
def save_form(self, request, form, change):
"""
Set the object's owner as the logged in user.
"""
obj = form.save(commit=False)
if obj.user_id is None:
obj.user = request.user
return super(OwnableAdmin, self).save_form(request, form, change) | Set the object's owner as the logged in user. |
def check_language_data(self, qid, lang_data, lang, lang_data_type):
"""
Method to check if certain language data exists as a label, description or aliases
:param lang_data: list of string values to check
:type lang_data: list
:param lang: language code
:type lang: str
... | Method to check if certain language data exists as a label, description or aliases
:param lang_data: list of string values to check
:type lang_data: list
:param lang: language code
:type lang: str
:param lang_data_type: What kind of data is it? 'label', 'description' or 'aliases'... |
def update_config(new_config):
""" Update config options with the provided dictionary of options.
"""
flask_app.base_config.update(new_config)
# Check for changed working directory.
if new_config.has_key('working_directory'):
wd = os.path.abspath(new_config['working_directory'])
if ... | Update config options with the provided dictionary of options. |
def doi_uri_to_doi(value):
"Strip the uri schema from the start of DOI URL strings"
if value is None:
return value
replace_values = ['http://dx.doi.org/', 'https://dx.doi.org/',
'http://doi.org/', 'https://doi.org/']
for replace_value in replace_values:
value = valu... | Strip the uri schema from the start of DOI URL strings |
def start_stop_video(self):
"""Start and stop the video, and change the button.
"""
if self.parent.info.dataset is None:
self.parent.statusBar().showMessage('No Dataset Loaded')
return
# & is added automatically by PyQt, it seems
if 'Start' in self.idx_bu... | Start and stop the video, and change the button. |
def confidentiality_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if confidentiality (encryption) has been negotiated in this context, False otherwise.
If this property is True, you can use :meth:`wrap` with the `conf_req` param set to True t... | After :meth:`step` has been called, this property will be set to
True if confidentiality (encryption) has been negotiated in this context, False otherwise.
If this property is True, you can use :meth:`wrap` with the `conf_req` param set to True to
encrypt messages sent to the peer application. |
def kldiv_cs_model(prediction, fm):
"""
Computes Chao-Shen corrected KL-divergence between prediction
and fdm made from fixations in fm.
Parameters :
prediction : np.ndarray
a fixation density map
fm : FixMat object
"""
# compute histogram of fixations needed for Cha... | Computes Chao-Shen corrected KL-divergence between prediction
and fdm made from fixations in fm.
Parameters :
prediction : np.ndarray
a fixation density map
fm : FixMat object |
def _generate(num_particles, D, box, rs):
"""Generate a list of `Particle` objects."""
X0 = rs.rand(num_particles) * (box.x2 - box.x1) + box.x1
Y0 = rs.rand(num_particles) * (box.y2 - box.y1) + box.y1
Z0 = rs.rand(num_particles) * (box.z2 - box.z1) + box.z1
return [Particle(D=D, ... | Generate a list of `Particle` objects. |
def get(self, cluster, environ, topology):
'''
:param cluster:
:param environ:
:param topology:
:return:
'''
# pylint: disable=no-member
options = dict(
cluster=cluster,
environ=environ,
topology=topology,
active="topologies",
function=common.class... | :param cluster:
:param environ:
:param topology:
:return: |
def tbfuncs(frames):
'this takes the frames array returned by tbframes'
return ['%s:%s:%s'%(os.path.split(f.f_code.co_filename)[-1],f.f_code.co_name,f.f_lineno) for f in frames] | this takes the frames array returned by tbframes |
def strip_textpad(text):
"""
Attempt to intelligently strip excess whitespace from the output of a
curses textpad.
"""
if text is None:
return text
# Trivial case where the textbox is only one line long.
if '\n' not in text:
return text.r... | Attempt to intelligently strip excess whitespace from the output of a
curses textpad. |
def set_feedback_from_tpl(tpl_name, parameters, problem_id=None, append=False):
""" Parse a template, using the given parameters, and set it as the feedback message.
tpl_name must indicate a file. Given that XX_XX is the lang code of the current user ('en_US' or 'fr_FR', for example),
this function... | Parse a template, using the given parameters, and set it as the feedback message.
tpl_name must indicate a file. Given that XX_XX is the lang code of the current user ('en_US' or 'fr_FR', for example),
this function will search template file in different locations, in the following order:
- [cu... |
def directory(self):
"""str: Directory that the service is run in."""
if self._directory is None:
return self.service_group.hitch_dir.hitch_dir
else:
return self._directory | str: Directory that the service is run in. |
def format_json(item, **kwargs):
""" formats a datatype object to a json value """
try:
json.dumps(item.value)
return item.value
except TypeError:
if 'time' in item.class_type.lower() \
or 'date' in item.class_type.lower():
return item.value.isoformat()
... | formats a datatype object to a json value |
def allow_resource_access(self, resource_name, when=None):
"""
meterer.allow_resource_access(resource_name, when=None) -> bool
Indicate whether access to the specified resource should be allowed.
This checks the limit(s) for the pool associated with the resource and
records the ... | meterer.allow_resource_access(resource_name, when=None) -> bool
Indicate whether access to the specified resource should be allowed.
This checks the limit(s) for the pool associated with the resource and
records the attempt. If the attempt falls below the limit, the allowance
is also re... |
def impulse_deltav_general(v,y,b,w,pot):
"""
NAME:
impulse_deltav_general
PURPOSE:
calculate the delta velocity to due an encounter with a general spherical potential in the impulse approximation; allows for arbitrary velocity vectors, but y is input as the position along the stream
I... | NAME:
impulse_deltav_general
PURPOSE:
calculate the delta velocity to due an encounter with a general spherical potential in the impulse approximation; allows for arbitrary velocity vectors, but y is input as the position along the stream
INPUT:
v - velocity of the stream (nstar,3)
... |
def verify(self, token, **kwargs):
"""Validates authentication credentials for a registered Runner.
Args:
token (str): The runner's authentication token
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentic... | Validates authentication credentials for a registered Runner.
Args:
token (str): The runner's authentication token
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabVerifyE... |
def get_parsed_context(pipeline, context_in_string):
"""Execute get_parsed_context handler if specified.
Dynamically load the module specified by the context_parser key in pipeline
dict and execute the get_parsed_context function on that module.
Args:
pipeline: dict. Pipeline object.
c... | Execute get_parsed_context handler if specified.
Dynamically load the module specified by the context_parser key in pipeline
dict and execute the get_parsed_context function on that module.
Args:
pipeline: dict. Pipeline object.
context_in_string: string. Argument string used to initialize... |
def pkg_commit_hash(pkg_path):
"""Get short form of commit hash given directory `pkg_path`
We get the commit hash from (in order of preference):
* IPython.utils._sysinfo.commit
* git output, if we are in a git repository
If these fail, we return a not-found placeholder tuple
Parameters
-... | Get short form of commit hash given directory `pkg_path`
We get the commit hash from (in order of preference):
* IPython.utils._sysinfo.commit
* git output, if we are in a git repository
If these fail, we return a not-found placeholder tuple
Parameters
----------
pkg_path : str
di... |
def _load_11_6(self, **kwargs):
"""Must check if rule actually exists before proceeding with load."""
if self._check_existence_by_collection(self._meta_data['container'],
kwargs['name']):
return super(Protocol_Dns, self)._load(**kwargs)
... | Must check if rule actually exists before proceeding with load. |
def dset_copy(dset,to_dir):
'''robust way to copy a dataset (including AFNI briks)'''
if nl.is_afni(dset):
dset_strip = re.sub(r'\.(HEAD|BRIK)?(\.(gz|bz))?','',dset)
for dset_file in [dset_strip + '.HEAD'] + glob.glob(dset_strip + '.BRIK*'):
if os.path.exists(dset_file):
... | robust way to copy a dataset (including AFNI briks) |
def check_all(self) -> Generator[AAAError, None, None]:
"""
Run everything required for checking this function.
Returns:
A generator of errors.
Raises:
ValidationError: A non-recoverable linting error is found.
"""
# Function def
if funct... | Run everything required for checking this function.
Returns:
A generator of errors.
Raises:
ValidationError: A non-recoverable linting error is found. |
def check():
'''Check configuration for sanity.
'''
if config('server')['insecure']:
logger.warning('HTTPS CHECKS ARE TURNED OFF. A SECURE CONNECTION IS '
'NOT GUARANTEED')
if config('server')['certificate']:
# Ensure certificate exists and is readable
open... | Check configuration for sanity. |
def select_args(xmrs, nodeid=None, rargname=None, value=None):
"""
Return the list of matching (nodeid, role, value) triples in *xmrs*.
Predication arguments in *xmrs* match if the `nodeid` of the
:class:`~delphin.mrs.components.ElementaryPredication` they are
arguments of match *nodeid*, their rol... | Return the list of matching (nodeid, role, value) triples in *xmrs*.
Predication arguments in *xmrs* match if the `nodeid` of the
:class:`~delphin.mrs.components.ElementaryPredication` they are
arguments of match *nodeid*, their role matches *rargname*, and
their value matches *value*. The *nodeid*, *r... |
def add_transition(self, from_state_id, from_outcome, to_state_id, to_outcome, transition_id=None):
"""Adds a transition to the container state
Note: Either the toState or the toOutcome needs to be "None"
:param from_state_id: The source state of the transition
:param from_outcome: The... | Adds a transition to the container state
Note: Either the toState or the toOutcome needs to be "None"
:param from_state_id: The source state of the transition
:param from_outcome: The outcome id of the source state to connect the transition to
:param to_state_id: The target state of th... |
def ElementFactory(href, smcresult=None, raise_exc=None):
"""
Factory returns an object of type Element when only
the href is provided.
:param str href: string href to fetch
:param SMCResult smcresult: optional SMCResult. If provided,
the request fetch will be skipped
:param Excepti... | Factory returns an object of type Element when only
the href is provided.
:param str href: string href to fetch
:param SMCResult smcresult: optional SMCResult. If provided,
the request fetch will be skipped
:param Exception raise_exc: exception to raise if fetch
failed |
def extend(self, iterable, new_name=False):
"""
Add further arrays from an iterable to this list
Parameters
----------
iterable
Any iterable that contains :class:`InteractiveBase` instances
%(ArrayList.rename.parameters.new_name)s
Raises
----... | Add further arrays from an iterable to this list
Parameters
----------
iterable
Any iterable that contains :class:`InteractiveBase` instances
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
... |
def monitor_session_session_number(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
monitor = ET.SubElement(config, "monitor", xmlns="urn:brocade.com:mgmt:brocade-span")
session = ET.SubElement(monitor, "session")
session_number = ET.SubElement(se... | Auto Generated Code |
def round_to_specified_time(self, a_datetime, hour, minute, second, mode="lower"):
"""Round the given datetime to specified hour, minute and second.
:param mode: if 'lower', floor to. if 'upper', ceiling to.
**中文文档**
将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
"""
... | Round the given datetime to specified hour, minute and second.
:param mode: if 'lower', floor to. if 'upper', ceiling to.
**中文文档**
将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 |
def _do_batched_write_command(namespace, operation, command,
docs, check_keys, opts, ctx):
"""Execute a batch of insert, update, or delete commands.
"""
max_bson_size = ctx.max_bson_size
max_write_batch_size = ctx.max_write_batch_size
# Max BSON object size + 16k - 2 by... | Execute a batch of insert, update, or delete commands. |
def rms(x):
""""Root Mean Square"
Arguments:
x (seq of float): A sequence of numerical values
Returns:
The square root of the average of the squares of the values
math.sqrt(sum(x_i**2 for x_i in x) / len(x))
or
return (np.array(x) ** 2).mean() ** 0.5
>>> rms... | Root Mean Square"
Arguments:
x (seq of float): A sequence of numerical values
Returns:
The square root of the average of the squares of the values
math.sqrt(sum(x_i**2 for x_i in x) / len(x))
or
return (np.array(x) ** 2).mean() ** 0.5
>>> rms([0, 2, 4, 4])
3... |
def _iter_module_files():
"""This iterates over all relevant Python files. It goes through all
loaded files from modules, all files in folders of already loaded modules
as well as all files reachable through a package.
"""
# The list call is necessary on Python 3 in case the module
# dictionary... | This iterates over all relevant Python files. It goes through all
loaded files from modules, all files in folders of already loaded modules
as well as all files reachable through a package. |
def write_prepareref_fasta_file(outfile, gene_coords, genes_need_upstream, genes_non_upstream, upstream_before=100, upstream_after=100):
'''Writes fasta file to be used with -f option of prepareref'''
tmp_dict = {}
fasta_in = os.path.join(data_dir, 'NC_000962.3.fa.gz')
pyfastaq.tasks.file_to_dict(fasta_... | Writes fasta file to be used with -f option of prepareref |
def init_centers_widths(self, R):
"""Initialize prior of centers and widths
Returns
-------
centers : 2D array, with shape [K, n_dim]
Prior of factors' centers.
widths : 1D array, with shape [K, 1]
Prior of factors' widths.
"""
kmeans ... | Initialize prior of centers and widths
Returns
-------
centers : 2D array, with shape [K, n_dim]
Prior of factors' centers.
widths : 1D array, with shape [K, 1]
Prior of factors' widths. |
def remove_user_from_group(self, group_name, user_name):
"""
Remove a user from a group.
:type group_name: string
:param group_name: The name of the group
:type user_name: string
:param user_name: The user to remove from the group.
"""
params = {'GroupN... | Remove a user from a group.
:type group_name: string
:param group_name: The name of the group
:type user_name: string
:param user_name: The user to remove from the group. |
def _accumulate_props(dest_props, src_props):
"""
helper to accumulate a dict of properties
Mutates dest_props by adding the non None src_props and returns
the new size
"""
props_size = 0
if src_props:
for k, v in src_props.items():
if v is not None:
prop... | helper to accumulate a dict of properties
Mutates dest_props by adding the non None src_props and returns
the new size |
def treePopupWidget(self):
"""
Returns the popup widget for this record box when it is supposed to
be an ORB tree widget.
:return <XTreeWidget>
"""
edit = self.lineEdit()
if not self._treePopupWidget:
# create the treewidget
... | Returns the popup widget for this record box when it is supposed to
be an ORB tree widget.
:return <XTreeWidget> |
def from_range_strings(ranges, boundtype = int):
"""
Parse a list of ranges expressed as strings in the form "value" or
"first:last" into an equivalent pycbc_glue.segments.segmentlist. In the
latter case, an empty string for "first" and(or) "last" indicates a
(semi)infinite range. A typical use for this function... | Parse a list of ranges expressed as strings in the form "value" or
"first:last" into an equivalent pycbc_glue.segments.segmentlist. In the
latter case, an empty string for "first" and(or) "last" indicates a
(semi)infinite range. A typical use for this function is in
parsing command line options or entries in conf... |
def get_cluster_role_env_topologies(cluster, role, env):
'''
Get the list of topologies given a cluster submitted by a given role under a given environment
:param cluster:
:param role:
:param env:
:return:
'''
return _get_topologies(cluster, role=role, env=env) | Get the list of topologies given a cluster submitted by a given role under a given environment
:param cluster:
:param role:
:param env:
:return: |
def _match_parent(self, match, yield_parent):
"""
Handle a parent match
:param match:
:type match:
:param yield_parent:
:type yield_parent:
:return:
:rtype:
"""
ret = super(Chain, self)._match_parent(match, yield_parent)
original_ch... | Handle a parent match
:param match:
:type match:
:param yield_parent:
:type yield_parent:
:return:
:rtype: |
def headers_as_list(self):
"""
Does the same as 'headers' except it is returned as a list.
"""
headers = self.headers
headers_list = ['{}: {}'.format(key, value) for key, value in iteritems(headers)]
return headers_list | Does the same as 'headers' except it is returned as a list. |
def consume(self, queue_name, prefetch=1, timeout=5000):
"""Create a new consumer for a queue.
Parameters:
queue_name(str): The queue to consume.
prefetch(int): The number of messages to prefetch.
timeout(int): The idle timeout in milliseconds.
Returns:
... | Create a new consumer for a queue.
Parameters:
queue_name(str): The queue to consume.
prefetch(int): The number of messages to prefetch.
timeout(int): The idle timeout in milliseconds.
Returns:
Consumer: A consumer that retrieves messages from Redis. |
def bh_fdr(pval):
"""A python implementation of the Benjamani-Hochberg FDR method.
This code should always give precisely the same answer as using
p.adjust(pval, method="BH") in R.
Parameters
----------
pval : list or array
list/array of p-values
Returns
-------
pval_adj :... | A python implementation of the Benjamani-Hochberg FDR method.
This code should always give precisely the same answer as using
p.adjust(pval, method="BH") in R.
Parameters
----------
pval : list or array
list/array of p-values
Returns
-------
pval_adj : np.array
adjuste... |
def BasenamePath(self, path):
"""Determines the basename of the path.
Args:
path (str): path.
Returns:
str: basename of the path.
"""
if path.endswith(self.PATH_SEPARATOR):
path = path[:-1]
_, _, basename = path.rpartition(self.PATH_SEPARATOR)
return basename | Determines the basename of the path.
Args:
path (str): path.
Returns:
str: basename of the path. |
def from_filename(cls, filename, start_byte, chunk_size, callbacks=None,
enable_callbacks=True):
"""Convenience factory function to create from a filename.
:type start_byte: int
:param start_byte: The first byte from which to start reading.
:type chunk_size: int
... | Convenience factory function to create from a filename.
:type start_byte: int
:param start_byte: The first byte from which to start reading.
:type chunk_size: int
:param chunk_size: The max chunk size to read. Trying to read
pass the end of the chunk size will behave like ... |
def sample_ruptures(sources, srcfilter, param, monitor=Monitor()):
"""
:param sources:
a sequence of sources of the same group
:param srcfilter:
SourceFilter instance used also for bounding box post filtering
:param param:
a dictionary of additional parameters including
s... | :param sources:
a sequence of sources of the same group
:param srcfilter:
SourceFilter instance used also for bounding box post filtering
:param param:
a dictionary of additional parameters including
ses_per_logic_tree_path
:param monitor:
monitor instance
:yields... |
def save_replay(self, replay_data, replay_dir, prefix=None):
"""Save a replay to a directory, returning the path to the replay.
Args:
replay_data: The result of controller.save_replay(), ie the binary data.
replay_dir: Where to save the replay. This can be absolute or relative.
prefix: Option... | Save a replay to a directory, returning the path to the replay.
Args:
replay_data: The result of controller.save_replay(), ie the binary data.
replay_dir: Where to save the replay. This can be absolute or relative.
prefix: Optional prefix for the replay filename.
Returns:
The full path... |
def record_event(self, event: Event) -> None:
"""
Record the event async.
"""
from polyaxon.celery_api import celery_app
from polyaxon.settings import EventsCeleryTasks
if not event.ref_id:
event.ref_id = self.get_ref_id()
serialized_event = event.ser... | Record the event async. |
def semidetached(b, component, solve_for=None, **kwargs):
"""
Create a constraint to force requiv to be semidetached
"""
comp_ps = b.get_component(component=component)
requiv = comp_ps.get_parameter(qualifier='requiv')
requiv_critical = comp_ps.get_parameter(qualifier='requiv_max')
if solv... | Create a constraint to force requiv to be semidetached |
def vel_horizontal(HeightWaterCritical):
"""Return the horizontal velocity."""
#Checking input validity
ut.check_range([HeightWaterCritical, ">0", "Critical height of water"])
return np.sqrt(gravity.magnitude * HeightWaterCritical) | Return the horizontal velocity. |
def positive_float(string):
"""Convert string to positive float."""
error_msg = 'Positive float required, {string} given.'.format(string=string)
try:
value = float(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
... | Convert string to positive float. |
async def setup(self):
"""Setting up SQL table, if it not exists."""
try:
engine = await self.db
created = False
if not await engine.has_table(self.table_name):
# create table
logger.info("Creating SQL table [{}]".format(self.table_name... | Setting up SQL table, if it not exists. |
def generate_datasets_report(
self, catalogs, harvest='valid', report=None,
export_path=None, catalog_ids=None, catalog_homepages=None,
catalog_orgs=None
):
"""Genera un reporte sobre las condiciones de la metadata de los
datasets contenidos en uno o varios catálo... | Genera un reporte sobre las condiciones de la metadata de los
datasets contenidos en uno o varios catálogos.
Args:
catalogs (str, dict o list): Uno (str o dict) o varios (list de
strs y/o dicts) catálogos.
harvest (str): Criterio a utilizar para determinar el val... |
def write_sample_sheet(output_file, accessions, names, celfile_urls, sel=None):
"""Generate a sample sheet in tab-separated text format.
The columns contain the following sample attributes:
1) accession
2) name
3) CEL file name
4) CEL file URL
Parameters
----------
output_file: str... | Generate a sample sheet in tab-separated text format.
The columns contain the following sample attributes:
1) accession
2) name
3) CEL file name
4) CEL file URL
Parameters
----------
output_file: str
The path of the output file.
accessions: list or tuple of str
The ... |
def command_locate(options):
"""Command launched by CLI."""
matches = find_owners(options.file.name)
if matches:
print(*matches, sep='\n') | Command launched by CLI. |
def is_pid_healthy(pid):
'''
This is a health check that will confirm the PID is running
and executed by salt.
If pusutil is available:
* all architectures are checked
if psutil is not available:
* Linux/Solaris/etc: archs with `/proc/cmdline` available are checked
* AIX/Wi... | This is a health check that will confirm the PID is running
and executed by salt.
If pusutil is available:
* all architectures are checked
if psutil is not available:
* Linux/Solaris/etc: archs with `/proc/cmdline` available are checked
* AIX/Windows: assume PID is healhty and retu... |
def _make_line(self, uid, command=None):
"""
Prepares an IRC line in Herald's format
"""
if command:
return ":".join(("HRLD", command, uid))
else:
return ":".join(("HRLD", uid)) | Prepares an IRC line in Herald's format |
def apply_hyperparameter_renames(cls, hyperparameters):
"""
Handle hyperparameter renames.
Parameters
----------
hyperparameters : dict
Returns
-------
dict : updated hyperparameters
"""
for (from_name, to_name) in cls.hyperparameter_ren... | Handle hyperparameter renames.
Parameters
----------
hyperparameters : dict
Returns
-------
dict : updated hyperparameters |
def find_classes_in_module(module, clstypes):
"""Find classes of clstypes in module
"""
classes = []
for item in dir(module):
item = getattr(module, item)
try:
for cls in clstypes:
if issubclass(item, cls) and item != cls:
classes.append(it... | Find classes of clstypes in module |
def flatten_component_refs(
container: ast.Class,
expression: ast.Union[ast.ConnectClause, ast.AssignmentStatement, ast.ForStatement, ast.Symbol],
instance_prefix: str) -> ast.Union[ast.ConnectClause, ast.AssignmentStatement, ast.ForStatement, ast.Symbol]:
"""
Flattens component refs in ... | Flattens component refs in a tree
:param container: class
:param expression: original expression
:param instance_prefix: prefix for instance
:return: flattened expression |
def egg_link_path(dist):
# type: (Distribution) -> Optional[str]
"""
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site... | Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site_packages
3) in a yes-global virtualenv
try to find in site_packages, ... |
def run_tool_cmd(tool, cmd, args=None, properties=None, hadoop_conf_dir=None,
logger=None, keep_streams=True):
"""
Run a Hadoop command.
If ``keep_streams`` is set to :obj:`True` (the default), the
stdout and stderr of the command will be buffered in memory. If
the command succeed... | Run a Hadoop command.
If ``keep_streams`` is set to :obj:`True` (the default), the
stdout and stderr of the command will be buffered in memory. If
the command succeeds, the former will be returned; if it fails, a
``RunCmdError`` will be raised with the latter as the message.
This mode is appropria... |
def fetch_all_droplets(self, tag_name=None):
r"""
Returns a generator that yields all of the droplets belonging to the
account
.. versionchanged:: 0.2.0
``tag_name`` parameter added
:param tag_name: if non-`None`, only droplets with the given tag are
ret... | r"""
Returns a generator that yields all of the droplets belonging to the
account
.. versionchanged:: 0.2.0
``tag_name`` parameter added
:param tag_name: if non-`None`, only droplets with the given tag are
returned
:type tag_name: string or `Tag`
... |
def short_full_symbol(self):
"""Gets the full symbol excluding the character under the cursor."""
if self._short_full_symbol is None:
self._short_full_symbol = self._symbol_extract(cache.RE_FULL_CURSOR,
False, True)
return s... | Gets the full symbol excluding the character under the cursor. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.