code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def set_id(self,my_id):
"""
Sets the opinion identifier
@type my_id: string
@param my_id: the opinion identifier
"""
if self.type == 'NAF':
self.node.set('id',my_id)
elif self.type == 'KAF':
self.node.set('oid',my_id) | Sets the opinion identifier
@type my_id: string
@param my_id: the opinion identifier |
def save_global(self, obj, name=None, pack=struct.pack):
"""
Save a "global".
The name of this method is somewhat misleading: all types get
dispatched here.
"""
if obj is type(None):
return self.save_reduce(type, (None,), obj=obj)
elif obj is type(Ell... | Save a "global".
The name of this method is somewhat misleading: all types get
dispatched here. |
def Polygon(pos=(0, 0, 0), normal=(0, 0, 1), nsides=6, r=1, c="coral",
bc="darkgreen", lw=1, alpha=1, followcam=False):
"""
Build a 2D polygon of `nsides` of radius `r` oriented as `normal`.
:param followcam: if `True` the text will auto-orient itself to the active camera.
A ``vtkCamera... | Build a 2D polygon of `nsides` of radius `r` oriented as `normal`.
:param followcam: if `True` the text will auto-orient itself to the active camera.
A ``vtkCamera`` object can also be passed.
:type followcam: bool, vtkCamera
|Polygon| |
def _extended_lookup(
datastore_api,
project,
key_pbs,
missing=None,
deferred=None,
eventual=False,
transaction_id=None,
):
"""Repeat lookup until all keys found (unless stop requested).
Helper function for :meth:`Client.get_multi`.
:type datastore_api:
:class:`google.c... | Repeat lookup until all keys found (unless stop requested).
Helper function for :meth:`Client.get_multi`.
:type datastore_api:
:class:`google.cloud.datastore._http.HTTPDatastoreAPI`
or :class:`google.cloud.datastore_v1.gapic.DatastoreClient`
:param datastore_api: The datastore API object u... |
def _parse_volumes(volume_values: dict) -> str:
"""Parse volumes key.
Args:
volume_values (dict): volume configuration values
Returns:
string, volume specification with mount source and container path
"""
for v_values in volume_values:
for v... | Parse volumes key.
Args:
volume_values (dict): volume configuration values
Returns:
string, volume specification with mount source and container path |
def libvlc_media_get_user_data(p_md):
'''Get media descriptor's user_data. user_data is specialized data
accessed by the host application, VLC.framework uses it as a pointer to
an native object that references a L{Media} pointer.
@param p_md: media descriptor object.
'''
f = _Cfunctions.get('lib... | Get media descriptor's user_data. user_data is specialized data
accessed by the host application, VLC.framework uses it as a pointer to
an native object that references a L{Media} pointer.
@param p_md: media descriptor object. |
def _get_current_names(current, dsn, pc):
"""
Get the table name and variable name from the given time series entry
:param dict current: Time series entry
:param str pc: paleoData or chronData
:return str _table_name:
:return str _variable_name:
"""
_table_name = ""
_variable_name =... | Get the table name and variable name from the given time series entry
:param dict current: Time series entry
:param str pc: paleoData or chronData
:return str _table_name:
:return str _variable_name: |
def remove_content(self, *keys):
"""
Removes given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.remove_content("Luke", "John")
True
>>> cache
... | Removes given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.remove_content("Luke", "John")
True
>>> cache
{}
:param \*keys: Content to remove.
... |
def cg(output,
show,
verbose,
classname,
methodname,
descriptor,
accessflag,
no_isolated,
apk):
"""
Create a call graph and export it into a graph format.
classnames are found in the type "Lfoo/bar/bla;".
Example:
\b
$ androguard cg ... | Create a call graph and export it into a graph format.
classnames are found in the type "Lfoo/bar/bla;".
Example:
\b
$ androguard cg APK |
def delete_topic(self, project, topic, fail_if_not_exists=False):
"""Deletes a Pub/Sub topic if it exists.
:param project: the GCP project ID in which to delete the topic
:type project: str
:param topic: the Pub/Sub topic name to delete; do not
include the ``projects/{projec... | Deletes a Pub/Sub topic if it exists.
:param project: the GCP project ID in which to delete the topic
:type project: str
:param topic: the Pub/Sub topic name to delete; do not
include the ``projects/{project}/topics/`` prefix.
:type topic: str
:param fail_if_not_exis... |
def astra_cuda_bp_scaling_factor(proj_space, reco_space, geometry):
"""Volume scaling accounting for differing adjoint definitions.
ASTRA defines the adjoint operator in terms of a fully discrete
setting (transposed "projection matrix") without any relation to
physical dimensions, which makes a re-scal... | Volume scaling accounting for differing adjoint definitions.
ASTRA defines the adjoint operator in terms of a fully discrete
setting (transposed "projection matrix") without any relation to
physical dimensions, which makes a re-scaling necessary to
translate it to spaces with physical dimensions.
... |
def device_action(device_id, action_id):
""" Initiate device action via HTTP GET. """
success = False
if device_id in devices:
input_cmd = getattr(devices[device_id], action_id, None)
if callable(input_cmd):
input_cmd()
success = True
return jsonify(success=succes... | Initiate device action via HTTP GET. |
def close(self, response):
"""Close connection to database."""
LOGGER.info('Closing [%s]', os.getpid())
if not self.database.is_closed():
self.database.close()
return response | Close connection to database. |
def non_transactional(func, args, kwds, allow_existing=True):
"""A decorator that ensures a function is run outside a transaction.
If there is an existing transaction (and allow_existing=True), the
existing transaction is paused while the function is executed.
Args:
allow_existing: If false, throw an exce... | A decorator that ensures a function is run outside a transaction.
If there is an existing transaction (and allow_existing=True), the
existing transaction is paused while the function is executed.
Args:
allow_existing: If false, throw an exception if called from within
a transaction. If true, temporar... |
def set_interval(self, interval):
"""Set timer interval (ms)."""
self._interval = interval
if self.timer is not None:
self.timer.setInterval(interval) | Set timer interval (ms). |
def cmd_status(self, run, finished=False):
"""Given a :class:`~clusterjob.AsyncResult` instance, return a command
that queries the scheduler for the job status, as a list of command
arguments. If ``finished=True``, the scheduler is queried via
``sacct``. Otherwise, ``squeue`` is used.
... | Given a :class:`~clusterjob.AsyncResult` instance, return a command
that queries the scheduler for the job status, as a list of command
arguments. If ``finished=True``, the scheduler is queried via
``sacct``. Otherwise, ``squeue`` is used. |
def get_help(func):
"""Return usage information about a context or function.
For contexts, just return the context name and its docstring
For functions, return the function signature as well as its
argument types.
Args:
func (callable): An annotated callable function
Returns:
... | Return usage information about a context or function.
For contexts, just return the context name and its docstring
For functions, return the function signature as well as its
argument types.
Args:
func (callable): An annotated callable function
Returns:
str: The formatted help tex... |
def alter_partitions_with_environment_context(self, db_name, tbl_name, new_parts, environment_context):
"""
Parameters:
- db_name
- tbl_name
- new_parts
- environment_context
"""
self.send_alter_partitions_with_environment_context(db_name, tbl_name, new_parts, environment_context)
... | Parameters:
- db_name
- tbl_name
- new_parts
- environment_context |
def files(self):
""" Returns a list of all the files that match the given
input token.
"""
res = None
if not res:
res = glob.glob(self.path)
if not res and self.is_glob:
res = glob.glob(self.magic_path)
if not res:
res = glob.gl... | Returns a list of all the files that match the given
input token. |
def get_cluster_custom_object(self, group, version, plural, name, **kwargs): # noqa: E501
"""get_cluster_custom_object # noqa: E501
Returns a cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, pleas... | get_cluster_custom_object # noqa: E501
Returns a cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_cluster_custom_object(group, version, plural, name,... |
def generate_keywords(additional_keywords=None):
"""Generates gettext keywords list
:arg additional_keywords: dict of keyword -> value
:returns: dict of keyword -> values for Babel extraction
Here's what Babel has for DEFAULT_KEYWORDS::
DEFAULT_KEYWORDS = {
'_': None,
... | Generates gettext keywords list
:arg additional_keywords: dict of keyword -> value
:returns: dict of keyword -> values for Babel extraction
Here's what Babel has for DEFAULT_KEYWORDS::
DEFAULT_KEYWORDS = {
'_': None,
'gettext': None,
'ngettext': (1, 2),
... |
def engine(self):
"""return the SqlAlchemy engine for this database."""
if not self._engine:
if 'postgres' in self.driver:
if 'connect_args' not in self.engine_kwargs:
self.engine_kwargs['connect_args'] = {
'application_name': '{... | return the SqlAlchemy engine for this database. |
def _do_delete(self):
"""
HTTP Delete Request
"""
return requests.delete(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token)) | HTTP Delete Request |
def add_rules(self, rules: _RuleList) -> None:
"""Appends new rules to the router.
:arg rules: a list of Rule instances (or tuples of arguments, which are
passed to Rule constructor).
"""
for rule in rules:
if isinstance(rule, (tuple, list)):
asse... | Appends new rules to the router.
:arg rules: a list of Rule instances (or tuples of arguments, which are
passed to Rule constructor). |
def get_single_node(self) -> yaml.Node:
"""Hook used when loading a single document.
This is the hook we use to hook yatiml into ruamel.yaml. It is \
called by the yaml libray when the user uses load() to load a \
YAML document.
Returns:
A processed node representin... | Hook used when loading a single document.
This is the hook we use to hook yatiml into ruamel.yaml. It is \
called by the yaml libray when the user uses load() to load a \
YAML document.
Returns:
A processed node representing the document. |
def hmset(self, name, mapping):
"""
Sets or updates the fields with their corresponding values.
:param name: str the name of the redis key
:param mapping: a dict with keys and values
:return: Future()
"""
with self.pipe as pipe:
m_encode = self.me... | Sets or updates the fields with their corresponding values.
:param name: str the name of the redis key
:param mapping: a dict with keys and values
:return: Future() |
def service_command(name, command):
"""Run an init.d/upstart command."""
service_command_template = getattr(env, 'ARGYLE_SERVICE_COMMAND_TEMPLATE',
u'/etc/init.d/%(name)s %(command)s')
sudo(service_command_template % {'name': name,
... | Run an init.d/upstart command. |
def freader(filename, gz=False, bz=False):
""" Returns a filereader object that can handle gzipped input """
filecheck(filename)
if filename.endswith('.gz'):
gz = True
elif filename.endswith('.bz2'):
bz = True
if gz:
return gzip.open(filename, 'rb')
elif bz:
ret... | Returns a filereader object that can handle gzipped input |
def WriteTo(self, values):
"""Writes values to a byte stream.
Args:
values (tuple[object, ...]): values to copy to the byte stream.
Returns:
bytes: byte stream.
Raises:
IOError: if byte stream cannot be written.
OSError: if byte stream cannot be read.
"""
try:
re... | Writes values to a byte stream.
Args:
values (tuple[object, ...]): values to copy to the byte stream.
Returns:
bytes: byte stream.
Raises:
IOError: if byte stream cannot be written.
OSError: if byte stream cannot be read. |
def exit_with_error(message):
""" Display formatted error message and exit call """
click.secho(message, err=True, bg='red', fg='white')
sys.exit(0) | Display formatted error message and exit call |
def is_attr_private(attrname: str) -> Optional[Match[str]]:
"""Check that attribute name is private (at least two leading underscores,
at most one trailing underscore)
"""
regex = re.compile("^_{2,}.*[^_]+_?$")
return regex.match(attrname) | Check that attribute name is private (at least two leading underscores,
at most one trailing underscore) |
def extract_tmaster(self, topology):
"""
Returns the representation of tmaster that will
be returned from Tracker.
"""
tmasterLocation = {
"name": None,
"id": None,
"host": None,
"controller_port": None,
"master_port": None,
"stats_port": None,
}
... | Returns the representation of tmaster that will
be returned from Tracker. |
def img(self, **kwargs):
"""
Returns an XHTML <img/> tag of the chart
kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML
"""
safe = 'src="%s" ' % self.url.replace('&','&').replace('<... | Returns an XHTML <img/> tag of the chart
kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML |
def _read_channel(self):
"""Generic handler that will read all the data from an SSH or telnet channel."""
if self.protocol == "ssh":
output = ""
while True:
if self.remote_conn.recv_ready():
outbuf = self.remote_conn.recv(MAX_BUFFER)
... | Generic handler that will read all the data from an SSH or telnet channel. |
def write_np_dat(self, store_format='csv', delimiter=',', fmt='%.12g'):
"""
Write TDS data stored in `self.np_vars` to the output file
Parameters
----------
store_format : str
dump format in ('csv', 'txt', 'hdf5')
delimiter : str
delimiter for th... | Write TDS data stored in `self.np_vars` to the output file
Parameters
----------
store_format : str
dump format in ('csv', 'txt', 'hdf5')
delimiter : str
delimiter for the `csv` and `txt` format
fmt : str
output formatting template
... |
def binary_to_float(binary_list, lower_bound, upper_bound):
"""Return a floating point number between lower and upper bounds, from binary.
Args:
binary_list: list<int>; List of 0s and 1s.
The number of bits in this list determine the number of possible
values between lower and u... | Return a floating point number between lower and upper bounds, from binary.
Args:
binary_list: list<int>; List of 0s and 1s.
The number of bits in this list determine the number of possible
values between lower and upper bound.
Increase the size of binary_list for more p... |
def value_at_coord(dset,coords):
'''returns value at specified coordinate in ``dset``'''
return nl.numberize(nl.run(['3dmaskave','-q','-dbox'] + list(coords) + [dset],stderr=None).output) | returns value at specified coordinate in ``dset`` |
def get_power_all(self):
"""Returns the power in mW for all devices"""
power_dict = {}
for device in self.get_device_names().keys():
power_dict[device] = self.get_power_single(device)
return power_dict | Returns the power in mW for all devices |
def axes(self, axes):
'''Set the axes for this object's degrees of freedom.
Parameters
----------
axes : list of axes specifications
A list of axis values to set. This list must have the same number of
elements as the degrees of freedom of the underlying ODE obje... | Set the axes for this object's degrees of freedom.
Parameters
----------
axes : list of axes specifications
A list of axis values to set. This list must have the same number of
elements as the degrees of freedom of the underlying ODE object.
Each element can ... |
def _slugify_foreign_key(schema):
"""Slugify foreign key
"""
for foreign_key in schema.get('foreignKeys', []):
foreign_key['reference']['resource'] = _slugify_resource_name(
foreign_key['reference'].get('resource', ''))
return schema | Slugify foreign key |
def remove(self, id):
""" Remove pool.
"""
p = Pool.get(int(id))
p.remove()
redirect(url(controller = 'pool', action = 'list')) | Remove pool. |
def page(self, from_=values.unset, to=values.unset,
date_created_on_or_before=values.unset,
date_created_after=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of FaxInstance records from the API.
... | Retrieve a single page of FaxInstance records from the API.
Request is executed immediately
:param unicode from_: Retrieve only those faxes sent from this phone number
:param unicode to: Retrieve only those faxes sent to this phone number
:param datetime date_created_on_or_before: Retri... |
def create_dataset(self,
name,
x_img_size,
y_img_size,
z_img_size,
x_vox_res,
y_vox_res,
z_vox_res,
x_offset=0,
y... | Creates a dataset.
Arguments:
name (str): Name of dataset
x_img_size (int): max x coordinate of image size
y_img_size (int): max y coordinate of image size
z_img_size (int): max z coordinate of image size
x_vox_res (float): x voxel resolution
... |
def applet_validate_batch(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/validateBatch API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fapplet-xxxx%2FvalidateBatch
"""
return DXHTTPRe... | Invokes the /applet-xxxx/validateBatch API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fapplet-xxxx%2FvalidateBatch |
def close_shell(self, shell_id):
"""
Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool
"""
message_id = uuid.uui... | Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool |
def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None,
allow_redirects=False):
"""
Make an HTTP Request with parameters provided.
:param str method: The HTTP method to use
:param str url: The URL to request
:param dict param... | Make an HTTP Request with parameters provided.
:param str method: The HTTP method to use
:param str url: The URL to request
:param dict params: Query parameters to append to the URL
:param dict data: Parameters to go in the body of the HTTP request
:param dict headers: HTTP Head... |
def export_analytics_data_to_excel(data, output_file_name, result_info_key, identifier_keys):
"""Creates an Excel file containing data returned by the Analytics API
Args:
data: Analytics API data as a list of dicts
output_file_name: File name for output Excel file (use .xlsx extension).
""... | Creates an Excel file containing data returned by the Analytics API
Args:
data: Analytics API data as a list of dicts
output_file_name: File name for output Excel file (use .xlsx extension). |
def get_bandstructure_by_material_id(self, material_id, line_mode=True):
"""
Get a BandStructure corresponding to a material_id.
REST Endpoint: https://www.materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure or
https://www.materialsproject.org/rest/v2/materials/<mp-id>/vas... | Get a BandStructure corresponding to a material_id.
REST Endpoint: https://www.materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure or
https://www.materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure_uniform
Args:
material_id (str): Materials Project mater... |
async def message(self, recipient: str, text: str, notice: bool=False) -> None:
"""
Lower level messaging function used by User and Channel
"""
await self._send(cc.PRIVMSG if not notice else cc.NOTICE, recipient, rest=text) | Lower level messaging function used by User and Channel |
def eps(self):
"""Print the canvas to a postscript file"""
import tkFileDialog,tkMessageBox
filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=['eps','ps'])
if filename is None:
return
self.postscript(file=filename) | Print the canvas to a postscript file |
def from_fill_parent(cls, eg_fillProperties_parent):
"""
Return a |FillFormat| instance initialized to the settings contained
in *eg_fillProperties_parent*, which must be an element having
EG_FillProperties in its child element sequence in the XML schema.
"""
fill_elm = e... | Return a |FillFormat| instance initialized to the settings contained
in *eg_fillProperties_parent*, which must be an element having
EG_FillProperties in its child element sequence in the XML schema. |
def _do_classifyplot(df, out_file, title=None, size=None, samples=None, callers=None):
"""Plot using classification-based plot using seaborn.
"""
metric_labels = {"fdr": "False discovery rate",
"fnr": "False negative rate"}
metrics = [("fnr", "tpr"), ("fdr", "spc")]
is_mpl2 = Lo... | Plot using classification-based plot using seaborn. |
def _release_command_buffer(self, command_buffer):
"""This is called by the command buffer when it closes."""
if command_buffer.closed:
return
self._cb_poll.unregister(command_buffer.host_id)
self.connection_pool.release(command_buffer.connection)
command_buffer.conn... | This is called by the command buffer when it closes. |
def target_power(self):
"""Setting this to `True` will activate the power pins (4 and 6). If
set to `False` the power will be deactivated.
Raises an :exc:`IOError` if the hardware adapter does not support
the switchable power pins.
"""
ret = api.py_aa_target_power(self.h... | Setting this to `True` will activate the power pins (4 and 6). If
set to `False` the power will be deactivated.
Raises an :exc:`IOError` if the hardware adapter does not support
the switchable power pins. |
def execute_code_block(compiler, block, example_globals,
script_vars, gallery_conf):
"""Executes the code block of the example file"""
blabel, bcontent, lineno = block
# If example is not suitable to run, skip executing its blocks
if not script_vars['execute_script'] or blabel == ... | Executes the code block of the example file |
def save_blocks(self, id_env, blocks):
"""
Save blocks from environment
:param id_env: Environment id
:param blocks: Lists of blocks in order. Ex: ['content one', 'content two', ...]
:return: None
:raise AmbienteNaoExisteError: Ambiente não cadastrado.
:raise I... | Save blocks from environment
:param id_env: Environment id
:param blocks: Lists of blocks in order. Ex: ['content one', 'content two', ...]
:return: None
:raise AmbienteNaoExisteError: Ambiente não cadastrado.
:raise InvalidValueError: Invalid parameter.
:raise UserNot... |
def _work_chain_mod_time(self, worker_name):
""" Internal: We compute a modification time of a work chain.
Returns:
The newest modification time of any worker in the work chain.
"""
# Bottom out on sample, info or tags
if worker_name=='sample' or worker_name... | Internal: We compute a modification time of a work chain.
Returns:
The newest modification time of any worker in the work chain. |
def qteBindKeyGlobal(self, keysequence, macroName: str):
"""
Associate ``macroName`` with ``keysequence`` in all current
applets.
This method will bind ``macroName`` to ``keysequence`` in the
global key map and **all** local key maps. This also applies
for all applets (a... | Associate ``macroName`` with ``keysequence`` in all current
applets.
This method will bind ``macroName`` to ``keysequence`` in the
global key map and **all** local key maps. This also applies
for all applets (and their constituent widgets) yet to be
instantiated because they wil... |
def DbAddDevice(self, argin):
""" Add a Tango class device to a specific device server
:param argin: Str[0] = Full device server process name
Str[1] = Device name
Str[2] = Tango class name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid """
... | Add a Tango class device to a specific device server
:param argin: Str[0] = Full device server process name
Str[1] = Device name
Str[2] = Tango class name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid |
def ce(actual, predicted):
"""
Computes the classification error.
This function computes the classification error between two lists
Parameters
----------
actual : list
A list of the true classes
predicted : list
A list of the predicted classes
Returns
... | Computes the classification error.
This function computes the classification error between two lists
Parameters
----------
actual : list
A list of the true classes
predicted : list
A list of the predicted classes
Returns
-------
score : double
... |
def _set_matplotlib_default_backend():
"""
matplotlib will try to print to a display if it is available, but don't want
to run it in interactive mode. we tried setting the backend to 'Agg'' before
importing, but it was still resulting in issues. we replace the existing
backend with 'agg' in the defa... | matplotlib will try to print to a display if it is available, but don't want
to run it in interactive mode. we tried setting the backend to 'Agg'' before
importing, but it was still resulting in issues. we replace the existing
backend with 'agg' in the default matplotlibrc. This is a hack until we can
f... |
def normalize_bbox(coords, ymax, scaler=2):
"""
scales all coordinates and flip y axis due to different
origin coordinates (top left vs. bottom left)
"""
return [
coords[0] * scaler,
ymax - (coords[3] * scaler),
coords[2] * scaler,
ymax - (coords[1] * scaler),
] | scales all coordinates and flip y axis due to different
origin coordinates (top left vs. bottom left) |
def __parse_enrollments(self, user):
"""Parse user enrollments"""
enrollments = []
for company in user['companies']:
name = company['company_name']
org = self._organizations.get(name, None)
if not org:
org = Organization(name=name)
... | Parse user enrollments |
def read(self):
"""Read stdout and stdout pipes if process is no longer running."""
if self._process and self._process.poll() is not None:
ip = get_ipython()
err = ip.user_ns['error'].read().decode()
out = ip.user_ns['output'].read().decode()
else:
... | Read stdout and stdout pipes if process is no longer running. |
def unwrap(lines, max_wrap_lines, min_header_lines, min_quoted_lines):
"""
Returns a tuple of:
- Type ('forward', 'reply', 'headers', 'quoted')
- Range of the text at the top of the wrapped message (or None)
- Headers dict (or None)
- Range of the text of the wrapped message (or None)
- Rang... | Returns a tuple of:
- Type ('forward', 'reply', 'headers', 'quoted')
- Range of the text at the top of the wrapped message (or None)
- Headers dict (or None)
- Range of the text of the wrapped message (or None)
- Range of the text below the wrapped message (or None)
- Whether the wrapped text ne... |
def ensemble_simulations(
t, y0=None, volume=1.0, model=None, solver='ode',
is_netfree=False, species_list=None, without_reset=False,
return_type='matplotlib', opt_args=(), opt_kwargs=None,
structures=None, rndseed=None,
n=1, nproc=None, method=None, errorbar=True,
**kwargs):
"""
Run sim... | Run simulations multiple times and return its ensemble.
Arguments are almost same with ``ecell4.util.simulation.run_simulation``.
`observers` and `progressbar` is not available here.
Parameters
----------
n : int, optional
A number of runs. Default is 1.
nproc : int, optional
A ... |
def wait(self, pattern, seconds=None):
""" Searches for an image pattern in the given region, given a specified timeout period
Functionally identical to find(). If a number is passed instead of a pattern,
just waits the specified number of seconds.
Sikuli supports OCR search with a text... | Searches for an image pattern in the given region, given a specified timeout period
Functionally identical to find(). If a number is passed instead of a pattern,
just waits the specified number of seconds.
Sikuli supports OCR search with a text parameter. This does not (yet). |
def get_train_eval_files(input_dir):
"""Get preprocessed training and eval files."""
data_dir = _get_latest_data_dir(input_dir)
train_pattern = os.path.join(data_dir, 'train*.tfrecord.gz')
eval_pattern = os.path.join(data_dir, 'eval*.tfrecord.gz')
train_files = file_io.get_matching_files(train_pattern)
eval... | Get preprocessed training and eval files. |
def try_instance_init(self, instance, late_start=False):
"""Try to "initialize" the given module instance.
:param instance: instance to init
:type instance: object
:param late_start: If late_start, don't look for last_init_try
:type late_start: bool
:return: True on succ... | Try to "initialize" the given module instance.
:param instance: instance to init
:type instance: object
:param late_start: If late_start, don't look for last_init_try
:type late_start: bool
:return: True on successful init. False if instance init method raised any Exception.
... |
def register_post_execute(self, func):
"""Register a function for calling after code execution.
"""
if not callable(func):
raise ValueError('argument %s must be callable' % func)
self._post_execute[func] = True | Register a function for calling after code execution. |
def score(self, context, models, revids):
"""
Genetate scores for model applied to a sequence of revisions.
:Parameters:
context : str
The name of the context -- usually the database name of a wiki
models : `iterable`
The names of a models... | Genetate scores for model applied to a sequence of revisions.
:Parameters:
context : str
The name of the context -- usually the database name of a wiki
models : `iterable`
The names of a models to apply
revids : `iterable`
A se... |
def mysql(
self,
tableNamePrefix="TNS",
dirPath=None):
"""*Render the results as MySQL Insert statements*
**Key Arguments:**
- ``tableNamePrefix`` -- the prefix for the database table names to assign the insert statements to. Default *TNS*.
- ... | *Render the results as MySQL Insert statements*
**Key Arguments:**
- ``tableNamePrefix`` -- the prefix for the database table names to assign the insert statements to. Default *TNS*.
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Re... |
def _set_parameters(self, parameters):
"""Sort out the various possible parameter inputs and return a config
object (dict)
We have multiple input formats:
1) a list, tuple, or numpy.ndarray, containing the linear parameters
in the following order:
* for single term: rho... | Sort out the various possible parameter inputs and return a config
object (dict)
We have multiple input formats:
1) a list, tuple, or numpy.ndarray, containing the linear parameters
in the following order:
* for single term: rho0, m1, tau1, c1
* for multiple termss: rho... |
def viewbox_key_event(self, event):
"""ViewBox key event handler
Parameters
----------
event : instance of Event
The event.
"""
PerspectiveCamera.viewbox_key_event(self, event)
if event.handled or not self.interactive:
return
# E... | ViewBox key event handler
Parameters
----------
event : instance of Event
The event. |
def send_photo(self, *args, **kwargs):
"""See :func:`send_photo`"""
return send_photo(*args, **self._merge_overrides(**kwargs)).run() | See :func:`send_photo` |
def execute_update(args):
"""Execute the update based on command line args and returns a dictionary
with 'execution result, ''response code', 'response info' and
'process friendly message'.
"""
provider_class = getattr(dnsupdater,
dnsupdater.AVAILABLE_PLUGINS.get(args.p... | Execute the update based on command line args and returns a dictionary
with 'execution result, ''response code', 'response info' and
'process friendly message'. |
def to_sql(cls, qc, **kwargs):
"""Write records stored in a DataFrame to a SQL database.
Args:
qc: the query compiler of the DF that we want to run to_sql on
kwargs: parameters for pandas.to_sql(**kwargs)
"""
# we first insert an empty DF in order to create the fu... | Write records stored in a DataFrame to a SQL database.
Args:
qc: the query compiler of the DF that we want to run to_sql on
kwargs: parameters for pandas.to_sql(**kwargs) |
def summarise_file_as_html(fname):
"""
takes a large data file and produces a HTML summary as html
"""
txt = '<H1>' + fname + '</H1>'
num_lines = 0
print('Reading OpenCyc file - ', fname)
with open(ip_folder + os.sep + fname, 'r') as f:
txt += '<PRE>'
for line in f:
... | takes a large data file and produces a HTML summary as html |
def icasa(taskname, mult=None, clearstart=False, loadthese=[],**kw0):
"""
runs a CASA task given a list of options.
A given task can be run multiple times with a different options,
in this case the options must be parsed as a list/tuple of dictionaries via mult, e.g
icasa('exportfits',mul... | runs a CASA task given a list of options.
A given task can be run multiple times with a different options,
in this case the options must be parsed as a list/tuple of dictionaries via mult, e.g
icasa('exportfits',mult=[{'imagename':'img1.image','fitsimage':'image1.fits},{'imagename':'img2.image','fit... |
def validate_one_format(jupytext_format):
"""Validate extension and options for the given format"""
if not isinstance(jupytext_format, dict):
raise JupytextFormatError('Jupytext format should be a dictionary')
for key in jupytext_format:
if key not in _VALID_FORMAT_INFO + _VALID_FORMAT_OPTI... | Validate extension and options for the given format |
def init(self, game_info, static_data):
"""Take the game info and the static data needed to set up the game.
This must be called before render or get_actions for each game or restart.
Args:
game_info: A `sc_pb.ResponseGameInfo` object for this game.
static_data: A `StaticData` object for this ... | Take the game info and the static data needed to set up the game.
This must be called before render or get_actions for each game or restart.
Args:
game_info: A `sc_pb.ResponseGameInfo` object for this game.
static_data: A `StaticData` object for this game.
Raises:
ValueError: if there i... |
def auto(cls, func):
"""
The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.
.. note::
Please note, that most functions require the handle to continue being alive for future calls to data
retrieved from the function. In such cases, it's... | The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.
.. note::
Please note, that most functions require the handle to continue being alive for future calls to data
retrieved from the function. In such cases, it's advisable to use the `requires_refcount`... |
def get_functions_writing_to_variable(self, variable):
'''
Return the functions writting the variable
'''
return [f for f in self.functions if f.is_writing(variable)] | Return the functions writting the variable |
def reload(self):
"""
fonction de chargement automatique de la configuration
depuis le fichier extérieur
"""
# lecture du fichier de configuration en mode UTF-8
if self.config_filename != "":
try:
# content = open(self.config_filename).read()
self.config_content = codecs.open(self.config_filen... | fonction de chargement automatique de la configuration
depuis le fichier extérieur |
def _dumpArrayToFile(filelike, array):
"""Serializes a 1-dimensional ``numpy.array`` to bytes, writes the bytes to
the filelike object and returns a dictionary with metadata, necessary to
restore the ``numpy.array`` from the file.
:param filelike: can be a file or a file-like object that provides the
... | Serializes a 1-dimensional ``numpy.array`` to bytes, writes the bytes to
the filelike object and returns a dictionary with metadata, necessary to
restore the ``numpy.array`` from the file.
:param filelike: can be a file or a file-like object that provides the
methods ``.write()`` and ``.tell()``.
... |
def delete_record(self, domain, recordid, params=None):
''' /v1/dns/delete_record
POST - account
Deletes an individual DNS record
Link: https://www.vultr.com/api/#dns_delete_record
'''
params = update_params(params, {
'domain': domain,
'RECORDID':... | /v1/dns/delete_record
POST - account
Deletes an individual DNS record
Link: https://www.vultr.com/api/#dns_delete_record |
def _format(self, object, stream, indent, allowance, context, level):
"""
Recursive part of the formatting
"""
try:
PrettyPrinter._format(self, object, stream, indent, allowance, context, level)
except Exception as e:
stream.write(_format_exception(e)) | Recursive part of the formatting |
def has(self):
"""Whether the cache file exists in the file system."""
self._done = os.path.exists(self._cache_file)
return self._done or self._out is not None | Whether the cache file exists in the file system. |
def levenshtein_distance(word1, word2):
"""
Computes the Levenshtein distance.
[Reference]: https://en.wikipedia.org/wiki/Levenshtein_distance
[Article]: Levenshtein, Vladimir I. (February 1966). "Binary codes capable of correcting deletions,
insertions,and reversals". Soviet Physics Doklady 10... | Computes the Levenshtein distance.
[Reference]: https://en.wikipedia.org/wiki/Levenshtein_distance
[Article]: Levenshtein, Vladimir I. (February 1966). "Binary codes capable of correcting deletions,
insertions,and reversals". Soviet Physics Doklady 10 (8): 707–710.
[Implementation]: https://en.wiki... |
def inject2(module_name=None, module_prefix=None, DEBUG=False, module=None, N=1):
""" wrapper that depricates print_ and printDBG """
if module_prefix is None:
module_prefix = '[%s]' % (module_name,)
noinject(module_name, module_prefix, DEBUG, module, N=N)
module = _get_module(module_name, modul... | wrapper that depricates print_ and printDBG |
def to_dict(self):
"""Return the schema as a dict ready to be serialized.
"""
schema = super(Schema, self).to_dict()
schema['$schema'] = "http://json-schema.org/draft-04/schema#"
if self._id:
schema['id'] = self._id
if self._desc:
schema['descript... | Return the schema as a dict ready to be serialized. |
def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
... | Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum accep... |
def add_at(self, moment: float, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process':
"""
Adds a process to the simulation, which is made to start at the given exact time on the simulated clock. Note
that times in the past when compared to the current moment on the simulated clock are f... | Adds a process to the simulation, which is made to start at the given exact time on the simulated clock. Note
that times in the past when compared to the current moment on the simulated clock are forbidden.
See method add() for more details. |
def get(self, key):
""" Executes the callable registered at the specified key and returns
its value. Subsequent queries are cached internally.
`key`
String key for a previously stored callable.
"""
if not key in self._actions:
return None... | Executes the callable registered at the specified key and returns
its value. Subsequent queries are cached internally.
`key`
String key for a previously stored callable. |
def __set_date(self, value):
'''
Sets the invoice date.
@param value:datetime
'''
value = date_to_datetime(value)
if value > datetime.now() + timedelta(hours=14, minutes=1): #More or less 14 hours from now in case the submitted date was local
raise ValueError(... | Sets the invoice date.
@param value:datetime |
def unique_list(input_, key=lambda x:x):
"""Return the unique elements from the input, in order."""
seen = set()
output = []
for x in input_:
keyx = key(x)
if keyx not in seen:
seen.add(keyx)
output.append(x)
return output | Return the unique elements from the input, in order. |
def create_single_button_clone(self, submit_text='Submit', submit_css_class='btn-primary',
read_form_data=True, form_type=None):
"""
This will create a copy of this form, with all of inputs replaced with hidden inputs,
and with a single submit button. This all... | This will create a copy of this form, with all of inputs replaced with hidden inputs,
and with a single submit button. This allows you to easily create a "button" that
will submit a post request which is identical to the current state of the form.
You could then, if required, change some of the... |
def polygon(self, points, stroke=None, fill=None, stroke_width=1, disable_anti_aliasing=False):
"""
:param points: List of points
"""
self.put(' <polygon points="')
self.put(' '.join(['%s,%s' % p for p in points]))
self.put('" stroke-width="')
self.put(str(stroke_... | :param points: List of points |
def quote(code):
"""Returns quoted code if not already quoted and if possible
Parameters
----------
code: String
\tCode thta is quoted
"""
try:
code = code.rstrip()
except AttributeError:
# code is not a string, may be None --> There is no code to quote
retur... | Returns quoted code if not already quoted and if possible
Parameters
----------
code: String
\tCode thta is quoted |
def _extract_game_info(self, games):
"""
Parse game information from all boxscores.
Find the major game information for all boxscores listed on a
particular boxscores webpage and return the results in a list.
Parameters
----------
games : generator
A... | Parse game information from all boxscores.
Find the major game information for all boxscores listed on a
particular boxscores webpage and return the results in a list.
Parameters
----------
games : generator
A generator where each element points to a boxscore on the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.