code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def stats(self) -> pd.DataFrame:
"""Statistics about flights contained in the structure.
Useful for a meaningful representation.
"""
cumul = []
for f in self:
info = {
"flight_id": f.flight_id,
"callsign": f.callsign,
"o... | Statistics about flights contained in the structure.
Useful for a meaningful representation. |
def get_suitable_slot_for_reference(self, reference):
"""Returns the suitable position for reference analyses, taking into
account if there is a WorksheetTemplate assigned to this worksheet.
By default, returns a new slot at the end of the worksheet unless there
is a slot defined for a ... | Returns the suitable position for reference analyses, taking into
account if there is a WorksheetTemplate assigned to this worksheet.
By default, returns a new slot at the end of the worksheet unless there
is a slot defined for a reference of the same type (blank or control)
in the work... |
def deliver_tx(self, raw_transaction):
"""Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction.
"""
self.abort_if_abci_chain_is_not_synced()
logger.debug('deliver_tx: %s', raw_transaction)
transaction = self.... | Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction. |
def computational_form(data):
"""
Input Series of numbers, Series, or DataFrames repackaged
for calculation.
Parameters
----------
data : pandas.Series
Series of numbers, Series, DataFrames
Returns
-------
pandas.Series, DataFrame, or Panel
repacked data, aligned by... | Input Series of numbers, Series, or DataFrames repackaged
for calculation.
Parameters
----------
data : pandas.Series
Series of numbers, Series, DataFrames
Returns
-------
pandas.Series, DataFrame, or Panel
repacked data, aligned by indices, ready for calculation |
def _convolve3_old(data, h, dev=None):
"""convolves 3d data with kernel h on the GPU Device dev
boundary conditions are clamping to edge.
h is converted to float32
if dev == None the default one is used
"""
if dev is None:
dev = get_device()
if dev is None:
raise ValueErro... | convolves 3d data with kernel h on the GPU Device dev
boundary conditions are clamping to edge.
h is converted to float32
if dev == None the default one is used |
def options(self):
"""
Reads all EMAIL_ options and set default values.
"""
config = self._config
o = {}
o.update(self._default_smtp_options)
o.update(self._default_message_options)
o.update(self._default_backend_options)
o.update(get_namespace(con... | Reads all EMAIL_ options and set default values. |
def update(ctx, no_restart, no_rebuild):
"""Update a HFOS node"""
# 0. (NOT YET! MAKE A BACKUP OF EVERYTHING)
# 1. update repository
# 2. update frontend repository
# 3. (Not yet: update venv)
# 4. rebuild frontend
# 5. restart service
instance = ctx.obj['instance']
log('Pulling g... | Update a HFOS node |
def token_is_valid(self,):
"""Check the validity of the token :3600s
"""
elapsed_time = time.time() - self.token_time
logger.debug("ELAPSED TIME : {0}".format(elapsed_time))
if elapsed_time > 3540: # 1 minute before it expires
logger.debug("TOKEN HAS EXPIRED")
... | Check the validity of the token :3600s |
def _check_len(self, pkt):
"""Check for odd packet length and pad according to Cisco spec.
This padding is only used for checksum computation. The original
packet should not be altered."""
if len(pkt) % 2:
last_chr = pkt[-1]
if last_chr <= b'\x80':
... | Check for odd packet length and pad according to Cisco spec.
This padding is only used for checksum computation. The original
packet should not be altered. |
def bsrchi(value, ndim, array):
"""
Do a binary search for a key value within an integer array,
assumed to be in increasing order. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchi_c.html
:param val... | Do a binary search for a key value within an integer array,
assumed to be in increasing order. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchi_c.html
:param value: Value to find in array.
:type value:... |
def load_config(self, filepath=None):
"""
checks if the file is a valid config file
Args:
filepath:
"""
# load config or default if invalid
def load_settings(filepath):
"""
loads a old_gui settings file (a json dictionary)
... | checks if the file is a valid config file
Args:
filepath: |
def exclude(self, target, operation, role, value):
"""Exclude a `role` of `value` at `target`
Arguments:
target (str): Destination proxy model
operation (str): "add" or "remove" exclusion
role (str): Role to exclude
value (str): Value of `role` to exclude... | Exclude a `role` of `value` at `target`
Arguments:
target (str): Destination proxy model
operation (str): "add" or "remove" exclusion
role (str): Role to exclude
value (str): Value of `role` to exclude |
def reshape(self, newshape, order='C'):
"""If axis 0 is unaffected by the reshape, then returns a Timeseries,
otherwise returns an ndarray. Preserves labels of axis j only if all
axes<=j are unaffected by the reshape.
See ``numpy.ndarray.reshape()`` for more information
"""
... | If axis 0 is unaffected by the reshape, then returns a Timeseries,
otherwise returns an ndarray. Preserves labels of axis j only if all
axes<=j are unaffected by the reshape.
See ``numpy.ndarray.reshape()`` for more information |
def update_variables(X, Z, U, prox_f, step_f, prox_g, step_g, L):
"""Update the primal and dual variables
Note: X, Z, U are updated inline
Returns: LX, R, S
"""
if not hasattr(prox_g, '__iter__'):
if prox_g is not None:
dX = step_f/step_g * L.T.dot(L.dot(X) - Z + U)
... | Update the primal and dual variables
Note: X, Z, U are updated inline
Returns: LX, R, S |
def getclientloansurl(idclient, *args, **kwargs):
"""Request Client loans URL.
How to use it? By default MambuLoan uses getloansurl as the urlfunc.
Override that behaviour by sending getclientloansurl (this function)
as the urlfunc to the constructor of MambuLoans (note the final 's')
and voila! yo... | Request Client loans URL.
How to use it? By default MambuLoan uses getloansurl as the urlfunc.
Override that behaviour by sending getclientloansurl (this function)
as the urlfunc to the constructor of MambuLoans (note the final 's')
and voila! you get the Loans just for a certain client.
If idclie... |
def input(msg="", default="", title="Lackey Input", hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInpu... | Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. |
def upload(self, timeout=None):
"""
Call ``upload()`` after :py:func:`adding <CommandSequence.add>` or :py:func:`clearing <CommandSequence.clear>` mission commands.
After the return from ``upload()`` any writes are guaranteed to have completed (or thrown an
exception) and future reads w... | Call ``upload()`` after :py:func:`adding <CommandSequence.add>` or :py:func:`clearing <CommandSequence.clear>` mission commands.
After the return from ``upload()`` any writes are guaranteed to have completed (or thrown an
exception) and future reads will see their effects.
:param int timeout: ... |
def _add_rule(self, state, rule):
"""Parse rule and add it to machine (for internal use)."""
if rule.strip() == "-":
parsed_rule = None
else:
parsed_rule = rule.split(',')
if (len(parsed_rule) != 3 or
parsed_rule[1] not in ['L', 'N', 'R'] or... | Parse rule and add it to machine (for internal use). |
def clear(self):
"""Clears the internal state of the bot.
After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed`
and :meth:`.is_ready` both return ``False`` along with the bot's internal
cache cleared.
"""
self._closed = False
self._ready.clea... | Clears the internal state of the bot.
After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed`
and :meth:`.is_ready` both return ``False`` along with the bot's internal
cache cleared. |
def check(self, metainfo, datapath, progress=None):
""" Check piece hashes of a metafile against the given datapath.
"""
if datapath:
self.datapath = datapath
def check_piece(filename, piece):
"Callback for new piece"
if piece != metainfo["info"]["pie... | Check piece hashes of a metafile against the given datapath. |
def connect(self):
"Initiate the connection to a proxying hub"
log.info("connecting")
# don't have the connection attempt reconnects, because when it goes
# down we are going to cycle to the next potential peer from the Client
self._peer = connection.Peer(
None, ... | Initiate the connection to a proxying hub |
def fill_translation_cache(instance):
"""
Fill the translation cache using information received in the
instance objects as extra fields.
You can not do this in post_init because the extra fields are
assigned by QuerySet.iterator after model initialization.
"""
if hasattr(instance, '_transl... | Fill the translation cache using information received in the
instance objects as extra fields.
You can not do this in post_init because the extra fields are
assigned by QuerySet.iterator after model initialization. |
def append_hdus(hdulist, srcmap_file, source_names, hpx_order):
"""Append HEALPix maps to a list
Parameters
----------
hdulist : list
The list being appended to
srcmap_file : str
Path to the file containing the HDUs
source_names : list of str
... | Append HEALPix maps to a list
Parameters
----------
hdulist : list
The list being appended to
srcmap_file : str
Path to the file containing the HDUs
source_names : list of str
Names of the sources to extract from srcmap_file
hpx_order... |
def _download_helper(url):
"""
Handle the download of an URL, using the proxy currently set in \
:mod:`socks`.
:param url: The URL to download.
:returns: A tuple of the raw content of the downloaded data and its \
associated content-type. Returns None if it was \
una... | Handle the download of an URL, using the proxy currently set in \
:mod:`socks`.
:param url: The URL to download.
:returns: A tuple of the raw content of the downloaded data and its \
associated content-type. Returns None if it was \
unable to download the document. |
def predict_proba(self, dataframe):
"""Predict probabilities using the model
:param dataframe: Dataframe against which to make predictions
"""
ret = numpy.ones((dataframe.shape[0], 2))
ret[:, 0] = (1 - self.mean)
ret[:, 1] = self.mean
return ret | Predict probabilities using the model
:param dataframe: Dataframe against which to make predictions |
def load_data(flist, drop_duplicates=False):
'''
Usage: set train, target, and test key and feature files.
FEATURE_LIST_stage2 = {
'train':(
TEMP_PATH + 'v1_stage1_all_fold.csv',
TEMP_PATH + 'v2_stage1_all_fold.csv',
... | Usage: set train, target, and test key and feature files.
FEATURE_LIST_stage2 = {
'train':(
TEMP_PATH + 'v1_stage1_all_fold.csv',
TEMP_PATH + 'v2_stage1_all_fold.csv',
TEMP_PATH + 'v3_stage1_all_fold.csv',
... |
def set_cache_buster(self, path, hash):
"""Sets the cache buster value for a given file path"""
oz.aws_cdn.set_cache_buster(self.redis(), path, hash) | Sets the cache buster value for a given file path |
def register(self, request, **cleaned_data):
"""
Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied to th... | Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied to that ``User``, containing the activation key which
will be ... |
def compute_hardwired_weights(rho,N_E,N_I,periodic, onlyI=False):
'''
%This function returns the synaptic weight matrices
%(G_I_EL,G_I_ER,G_EL_I,G_ER_I,G_I_I) and the suppressive envelope
%(A_env), based on:
%
% - the scale of the synaptic profiles (rho)
% - the size of the exctitatory and inhibitory pops... | %This function returns the synaptic weight matrices
%(G_I_EL,G_I_ER,G_EL_I,G_ER_I,G_I_I) and the suppressive envelope
%(A_env), based on:
%
% - the scale of the synaptic profiles (rho)
% - the size of the exctitatory and inhibitory pops (N_E, N_I)
% - the boundary conditions of the network (periodic=1 for p... |
def compare_names(first, second):
"""
Compare two names in complicated, but more error prone way.
Algorithm is using vector comparison.
Example:
>>> compare_names("Franta Putšálek", "ing. Franta Putšálek")
100.0
>>> compare_names("F. Putšálek", "ing. Franta Putšálek")
5... | Compare two names in complicated, but more error prone way.
Algorithm is using vector comparison.
Example:
>>> compare_names("Franta Putšálek", "ing. Franta Putšálek")
100.0
>>> compare_names("F. Putšálek", "ing. Franta Putšálek")
50.0
Args:
first (str): Fisst name... |
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
rotation parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
... | Transform an image using an Affine transform with
rotation parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image ... |
def setup(app):
"""Register domain and directive in Sphinx."""
app.add_domain(EverettDomain)
app.add_directive('autocomponent', AutoComponentDirective)
return {
'version': __version__,
'parallel_read_safe': True,
'parallel_write_safe': True
} | Register domain and directive in Sphinx. |
def fcoe_fcoe_map_fcoe_map_fabric_map_fcoe_map_fabric_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe")
fcoe_map = ET.SubElement(fcoe, "fcoe-map")
fcoe_map_nam... | Auto Generated Code |
def host_resolution_order(ifo, env='NDSSERVER', epoch='now',
lookback=14*86400):
"""Generate a logical ordering of NDS (host, port) tuples for this IFO
Parameters
----------
ifo : `str`
prefix for IFO of interest
env : `str`, optional
environment variable n... | Generate a logical ordering of NDS (host, port) tuples for this IFO
Parameters
----------
ifo : `str`
prefix for IFO of interest
env : `str`, optional
environment variable name to use for server order,
default ``'NDSSERVER'``. The contents of this variable should
be a co... |
def to_string(xml, **kwargs):
"""
Serialize an element to an encoded string representation of its XML tree.
:param xml: The root node
:type xml: str|bytes|xml.dom.minidom.Document|etree.Element
:returns: string representation of xml
:rtype: string
"""
if ... | Serialize an element to an encoded string representation of its XML tree.
:param xml: The root node
:type xml: str|bytes|xml.dom.minidom.Document|etree.Element
:returns: string representation of xml
:rtype: string |
def interval_timer(interval, func, *args, **kwargs):
'''Interval timer function.
Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708
'''
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is after interval
... | Interval timer function.
Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708 |
def _pack_with_tf_ops(dataset, keys, length):
"""Helper-function for packing a dataset which has already been batched.
See pack_dataset()
Uses tf.while_loop. Slow.
Args:
dataset: a dataset containing padded batches of examples.
keys: a list of strings
length: an integer
Returns:
a dataset... | Helper-function for packing a dataset which has already been batched.
See pack_dataset()
Uses tf.while_loop. Slow.
Args:
dataset: a dataset containing padded batches of examples.
keys: a list of strings
length: an integer
Returns:
a dataset. |
def unpackcFunc(self):
'''
"Unpacks" the consumption functions into their own field for easier access.
After the model has been solved, the consumption functions reside in the
attribute cFunc of each element of ConsumerType.solution. This method
creates a (time varying) attribut... | "Unpacks" the consumption functions into their own field for easier access.
After the model has been solved, the consumption functions reside in the
attribute cFunc of each element of ConsumerType.solution. This method
creates a (time varying) attribute cFunc that contains a list of consumption... |
def __geo_point(lat, lon, elev):
"""
GeoJSON standard:
Create a geoJson Point-type dictionary
:param list lat:
:param list lon:
:return dict:
"""
logger_noaa_lpd.info("enter geo_point")
coordinates = []
geo_dict = OrderedDict()
geom... | GeoJSON standard:
Create a geoJson Point-type dictionary
:param list lat:
:param list lon:
:return dict: |
def handle_signal(self, sig, frame):
"""Handles signals, surprisingly."""
if sig in [signal.SIGINT]:
log.warning("Ctrl-C pressed, shutting down...")
if sig in [signal.SIGTERM]:
log.warning("SIGTERM received, shutting down...")
self.cleanup()
sys.exit(-sig) | Handles signals, surprisingly. |
def write_to_file(self, file_path='', date=str(datetime.date.today()),
organization='N/A', members=0, teams=0):
"""
Writes the current organization information to file (csv).
"""
self.checkDir(file_path)
with open(file_path, 'w+') as output:
output.write('date... | Writes the current organization information to file (csv). |
def always_fails(
self,
work_dict):
"""always_fails
:param work_dict: dictionary for key/values
"""
label = "always_fails"
log.info(("task - {} - start "
"work_dict={}")
.format(label,
work_dict))
raise Exception(
wo... | always_fails
:param work_dict: dictionary for key/values |
def clone(local_root, new_root, remote, branch, rel_dest, exclude):
"""Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local ... | Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local path to git root directory.
:param str new_root: Local path empty direc... |
def default():
""" return default options, available options:
- max_name_length: maximum length of name for additionalProperties
- max_prop_count: maximum count of properties (count of fixed properties + additional properties)
- max_str_length: maximum length of string type
- max... | return default options, available options:
- max_name_length: maximum length of name for additionalProperties
- max_prop_count: maximum count of properties (count of fixed properties + additional properties)
- max_str_length: maximum length of string type
- max_byte_length: maximum lengt... |
def install(path, capture_error=False): # type: (str, bool) -> None
"""Install a Python module in the executing Python environment.
Args:
path (str): Real path location of the Python module.
capture_error (bool): Default false. If True, the running process captures the
stderr, and ... | Install a Python module in the executing Python environment.
Args:
path (str): Real path location of the Python module.
capture_error (bool): Default false. If True, the running process captures the
stderr, and appends it to the returned Exception message in case of errors. |
def subnet_distance(self):
"""
Specific subnet administrative distances
:return: list of tuple (subnet, distance)
"""
return [(Element.from_href(entry.get('subnet')), entry.get('distance'))
for entry in self.data.get('distance_entry')] | Specific subnet administrative distances
:return: list of tuple (subnet, distance) |
def is_complete(self, zmax=118):
"""
True if table is complete i.e. all elements with Z < zmax have at least on pseudopotential
"""
for z in range(1, zmax):
if not self[z]: return False
return True | True if table is complete i.e. all elements with Z < zmax have at least on pseudopotential |
def schema_delete_field(cls, key):
"""Deletes a field."""
root = '/'.join([API_ROOT, 'schemas', cls.__name__])
payload = {
'className': cls.__name__,
'fields': {
key: {
'__op': 'Delete'
}
}
}
... | Deletes a field. |
def _authenticate_x509(credentials, sock_info):
"""Authenticate using MONGODB-X509.
"""
query = SON([('authenticate', 1),
('mechanism', 'MONGODB-X509')])
if credentials.username is not None:
query['user'] = credentials.username
elif sock_info.max_wire_version < 5:
ra... | Authenticate using MONGODB-X509. |
def write(text, path):
"""Writer text to file with utf-8 encoding.
Usage::
>>> from angora.dataIO import textfile
or
>>> from angora.dataIO import *
>>> textfile.write("hello world!", "test.txt")
"""
with open(path, "wb") as f:
f.write(text.encode("utf-8")) | Writer text to file with utf-8 encoding.
Usage::
>>> from angora.dataIO import textfile
or
>>> from angora.dataIO import *
>>> textfile.write("hello world!", "test.txt") |
def generate_token(self):
"""Make request in API to generate a token."""
response = self._make_request()
self.auth = response
self.token = response['token'] | Make request in API to generate a token. |
def from_hex_key(cls, key, network=BitcoinMainNet):
"""Load the PublicKey from a compressed or uncompressed hex key.
This format is defined in PublicKey.get_key()
"""
if len(key) == 130 or len(key) == 66:
# It might be a hexlified byte array
try:
... | Load the PublicKey from a compressed or uncompressed hex key.
This format is defined in PublicKey.get_key() |
def get_directory(request):
"""Get API directory as a nested list of lists."""
def get_url(url):
return reverse(url, request=request) if url else url
def is_active_url(path, url):
return path.startswith(url) if url and path else False
path = request.path
directory_list = []
d... | Get API directory as a nested list of lists. |
def compute_dkl(fsamps, prior_fsamps, **kwargs):
"""
Compute the Kullback Leibler divergence for function samples for posterior
and prior pre-calculated at a range of x values.
Parameters
----------
fsamps: 2D numpy.array
Posterior function samples, as computed by
:func:`fgivenx... | Compute the Kullback Leibler divergence for function samples for posterior
and prior pre-calculated at a range of x values.
Parameters
----------
fsamps: 2D numpy.array
Posterior function samples, as computed by
:func:`fgivenx.compute_samples`
prior_fsamps: 2D numpy.array
P... |
def compute_score(markers, bonus, penalty):
"""
Compute chain score using dynamic programming. If a marker is the same
linkage group as a previous one, we add bonus; otherwise, we penalize the
chain switching.
"""
nmarkers = len(markers)
s = [bonus] * nmarkers # score
f = [-1] * nmarke... | Compute chain score using dynamic programming. If a marker is the same
linkage group as a previous one, we add bonus; otherwise, we penalize the
chain switching. |
def forProperty(instance,propertyName,useGetter=False):
"""
2-way binds to an instance property.
Parameters:
- instance -- the object instance
- propertyName -- the name of the property to bind to
- useGetter: when True, calls the getter method to obtain the value. When ... | 2-way binds to an instance property.
Parameters:
- instance -- the object instance
- propertyName -- the name of the property to bind to
- useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for the target setter. (default ... |
def set_inheritance(obj_name, enabled, obj_type='file', clear=False):
'''
Enable or disable an objects inheritance.
Args:
obj_name (str):
The name of the object
enabled (bool):
True to enable inheritance, False to disable
obj_type (Optional[str]):
... | Enable or disable an objects inheritance.
Args:
obj_name (str):
The name of the object
enabled (bool):
True to enable inheritance, False to disable
obj_type (Optional[str]):
The type of object. Only three objects allow inheritance. Valid
ob... |
def _import_public_names(module):
"Import public names from module into this module, like import *"
self = sys.modules[__name__]
for name in module.__all__:
if hasattr(self, name):
# don't overwrite existing names
continue
setattr(self, name, getattr(module, name)) | Import public names from module into this module, like import * |
def update(self, campaign_id, title, is_smooth, online_status, nick=None):
'''xxxxx.xxxxx.campaign.update
===================================
更新一个推广计划,可以设置推广计划名字、是否平滑消耗,只有在设置了日限额后平滑消耗才会产生作用。'''
request = TOPRequest('xxxxx.xxxxx.campaign.update')
request['campaign_id'] = campaign_... | xxxxx.xxxxx.campaign.update
===================================
更新一个推广计划,可以设置推广计划名字、是否平滑消耗,只有在设置了日限额后平滑消耗才会产生作用。 |
def _warning(code):
"""
Return a warning message of code 'code'.
If code = (cd, str) it returns the warning message of code 'cd' and appends
str at the end
"""
if isinstance(code, str):
return code
message = ''
if isinstance(code, tuple):
if isinstance(code[0], str):
... | Return a warning message of code 'code'.
If code = (cd, str) it returns the warning message of code 'cd' and appends
str at the end |
def expect(
self, re_strings='', timeout=None, output_callback=None, default_match_prefix='.*\n',
strip_ansi=True
):
"""
This function takes in a regular expression (or regular expressions)
that represent the last line of output from the server. The function
waits fo... | This function takes in a regular expression (or regular expressions)
that represent the last line of output from the server. The function
waits for one or more of the terms to be matched. The regexes are
matched using expression \n<regex>$ so you'll need to provide an
easygoing regex s... |
def launch_minecraft(port, installdir="MalmoPlatform", replaceable=False):
"""Launch Minecraft listening for malmoenv connections.
Args:
port: the TCP port to listen on.
installdir: the install dir name. Defaults to MalmoPlatform.
Must be same as given (or defaulted) in download call if... | Launch Minecraft listening for malmoenv connections.
Args:
port: the TCP port to listen on.
installdir: the install dir name. Defaults to MalmoPlatform.
Must be same as given (or defaulted) in download call if used.
replaceable: whether or not to automatically restart Minecraft (def... |
def alive(opts):
'''
Validate and return the connection status with the remote device.
.. versionadded:: 2018.3.0
'''
dev = conn()
thisproxy['conn'].connected = ping()
if not dev.connected:
__salt__['event.fire_master']({}, 'junos/proxy/{}/stop'.format(
opts['proxy'][... | Validate and return the connection status with the remote device.
.. versionadded:: 2018.3.0 |
def select_catalogue(self, selector, distance, selector_type='circle',
distance_metric='epicentral', point_depth=None,
upper_eq_depth=None, lower_eq_depth=None):
'''
Selects the catalogue associated to the point source.
Effectively a wrapper to t... | Selects the catalogue associated to the point source.
Effectively a wrapper to the two functions select catalogue within
a distance of the point and select catalogue within cell centred on
point
:param selector:
Populated instance of :class:
`openquake.hmtk.seism... |
def writePlistToString(rootObject):
'''Return 'rootObject' as a plist-formatted string.'''
plistData, error = (
NSPropertyListSerialization.
dataFromPropertyList_format_errorDescription_(
rootObject, NSPropertyListXMLFormat_v1_0, None))
if plistData is None:
if error:
... | Return 'rootObject' as a plist-formatted string. |
def template(page=None, layout=None, **kwargs):
"""
Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:fi... | Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:first arg or $layout: The layout to use for that view
... |
def _new_name(method, old_name):
"""Return a method with a deprecation warning."""
# Looks suspiciously like a decorator, but isn't!
@wraps(method)
def _method(*args, **kwargs):
warnings.warn(
"method '{}' has been deprecated, please rename to '{}'".format(
old_name,... | Return a method with a deprecation warning. |
def on_loss_begin(self, last_output:Tuple[Tensor,Tensor,Tensor], **kwargs):
"Save the extra outputs for later and only returns the true output."
self.raw_out,self.out = last_output[1],last_output[2]
return {'last_output': last_output[0]} | Save the extra outputs for later and only returns the true output. |
def serialize(self, keep_readonly=False):
"""Return the JSON that would be sent to azure from this model.
This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`.
:param bool keep_readonly: If you want to serialize the readonly attributes
:returns: A dict JSON ... | Return the JSON that would be sent to azure from this model.
This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`.
:param bool keep_readonly: If you want to serialize the readonly attributes
:returns: A dict JSON compatible object
:rtype: dict |
def is_standard(action):
""" actions which are general "store" instructions.
e.g. anything which has an argument style like:
$ script.py -f myfilename.txt
"""
boolean_actions = (
_StoreConstAction, _StoreFalseAction,
_StoreTrueAction
)
return (not action.choices
... | actions which are general "store" instructions.
e.g. anything which has an argument style like:
$ script.py -f myfilename.txt |
def update(self):
"""Retrieve latest state of the device."""
is_on = self._device.get_power_state()
if is_on:
self._state = STATE_ON
volume = self._device.get_current_volume()
if volume is not None:
self._volume_level = float(volume) / self._... | Retrieve latest state of the device. |
def name(self):
"""
Compact representation for the names
"""
names = self.names.split()
if len(names) == 1:
return names[0]
elif len(names) == 2:
return ' '.join(names)
else:
return ' '.join([names[0], '...', names[-1]]) | Compact representation for the names |
def get_annotated_list_qs(cls, qs):
"""
Gets an annotated list from a queryset.
"""
result, info = [], {}
start_depth, prev_depth = (None, None)
for node in qs:
depth = node.get_depth()
if start_depth is None:
start_depth = depth
... | Gets an annotated list from a queryset. |
def create_track_token(request):
"""Returns ``TrackToken``.
``TrackToken' contains request and user making changes.
It can be passed to ``TrackedModel.save`` instead of ``request``.
It is intended to be used when passing ``request`` is not possible
e.g. when ``TrackedModel.save`` will be called fro... | Returns ``TrackToken``.
``TrackToken' contains request and user making changes.
It can be passed to ``TrackedModel.save`` instead of ``request``.
It is intended to be used when passing ``request`` is not possible
e.g. when ``TrackedModel.save`` will be called from celery task. |
def simDeath(self):
'''
Randomly determine which consumers die, and distribute their wealth among the survivors.
This method only works if there is only one period in the cycle.
Parameters
----------
None
Returns
-------
who_dies : np.array(bool)... | Randomly determine which consumers die, and distribute their wealth among the survivors.
This method only works if there is only one period in the cycle.
Parameters
----------
None
Returns
-------
who_dies : np.array(bool)
Boolean array of size Agent... |
def getSubtotal(self):
""" Compute Subtotal """
if self.supplyorder_lineitems:
return sum(
[(Decimal(obj['Quantity']) * Decimal(obj['Price'])) for obj in self.supplyorder_lineitems])
return 0 | Compute Subtotal |
def create_table(
self,
impala_name,
kudu_name,
primary_keys=None,
obj=None,
schema=None,
database=None,
external=False,
force=False,
):
"""
Create an Kudu-backed table in the connected Impala cluster. For
non-external t... | Create an Kudu-backed table in the connected Impala cluster. For
non-external tables, this will create a Kudu table with a compatible
storage schema.
This function is patterned after the ImpalaClient.create_table function
designed for physical filesystems (like HDFS).
Parameter... |
def deserialize(cls, assoc_s):
"""
Parse an association as stored by serialize().
inverse of serialize
@param assoc_s: Association as serialized by serialize()
@type assoc_s: str
@return: instance of this class
"""
pairs = kvform.kvToSeq(assoc_s, str... | Parse an association as stored by serialize().
inverse of serialize
@param assoc_s: Association as serialized by serialize()
@type assoc_s: str
@return: instance of this class |
def render(self, name, value, attrs=None, renderer=None):
"""
Render the widget as an HTML string.
Overridden here to support Django < 1.11.
"""
if self.has_template_widget_rendering:
return super(ClearableFileInputWithImagePreview, self).render(
name... | Render the widget as an HTML string.
Overridden here to support Django < 1.11. |
def _validate(self, writing=False):
"""Validate internal correctness."""
if (((len(self.fragment_offset) != len(self.fragment_length)) or
(len(self.fragment_length) != len(self.data_reference)))):
msg = ("The lengths of the fragment offsets ({len_offsets}), "
... | Validate internal correctness. |
def _use_framework(module):
"""
Internal helper, to set this modules methods to a specified
framework helper-methods.
"""
import txaio
for method_name in __all__:
if method_name in ['use_twisted', 'use_asyncio']:
continue
setattr(txaio, method_name,
ge... | Internal helper, to set this modules methods to a specified
framework helper-methods. |
def _outer_values_update(self, full_values):
"""
Here you put the values, which were collected before in the right places.
E.g. set the gradients of parameters, etc.
"""
super(BayesianGPLVMMiniBatch, self)._outer_values_update(full_values)
if self.has_uncertain_inputs():
... | Here you put the values, which were collected before in the right places.
E.g. set the gradients of parameters, etc. |
def process_event(self, event_name: str, data: dict) -> None:
"""
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
... | Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
None |
def _nodeSatisfiesValue(cntxt: Context, n: Node, vsv: ShExJ.valueSetValue) -> bool:
"""
A term matches a valueSetValue if:
* vsv is an objectValue and n = vsv.
* vsv is a Language with langTag lt and n is a language-tagged string with a language tag l and l = lt.
* vsv is a IriStem, Lite... | A term matches a valueSetValue if:
* vsv is an objectValue and n = vsv.
* vsv is a Language with langTag lt and n is a language-tagged string with a language tag l and l = lt.
* vsv is a IriStem, LiteralStem or LanguageStem with stem st and nodeIn(n, st).
* vsv is a IriStemRange, Literal... |
def labels(self, hs_dims=None, prune=False):
"""Get labels for the cube slice, and perform pruning by slice."""
if self.ca_as_0th:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[1:]
else:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[-2:... | Get labels for the cube slice, and perform pruning by slice. |
def nextProperty(self, propuri):
"""Returns the next property in the list of properties. If it's the last one, returns the first one."""
if propuri == self.properties[-1].uri:
return self.properties[0]
flag = False
for x in self.properties:
if flag == True:
... | Returns the next property in the list of properties. If it's the last one, returns the first one. |
def sync_firmware(self):
"""Syncs the emulator's firmware version and the DLL's firmware.
This method is useful for ensuring that the firmware running on the
J-Link matches the firmware supported by the DLL.
Args:
self (JLink): the ``JLink`` instance
Returns:
... | Syncs the emulator's firmware version and the DLL's firmware.
This method is useful for ensuring that the firmware running on the
J-Link matches the firmware supported by the DLL.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None`` |
def wrap_text_in_a_box(body='', title='', style='double_star', **args):
r"""Return a nicely formatted text box.
e.g.
******************
** title **
**--------------**
** body **
******************
Indentation and newline are respected.
:param body... | r"""Return a nicely formatted text box.
e.g.
******************
** title **
**--------------**
** body **
******************
Indentation and newline are respected.
:param body: the main text
:param title: an optional title
:param style: the na... |
def x_forwarded_for(self):
"""X-Forwarded-For header value.
This is the amended header so that it contains the previous IP address
in the forwarding change.
"""
ip = self._request.META.get('REMOTE_ADDR')
current_xff = self.headers.get('X-Forwarded-For')
return ... | X-Forwarded-For header value.
This is the amended header so that it contains the previous IP address
in the forwarding change. |
def get_client_class(self, client_class_name):
"""Returns a specific client class details from CPNR server."""
request_url = self._build_url(['ClientClass', client_class_name])
return self._do_request('GET', request_url) | Returns a specific client class details from CPNR server. |
def get_template(template_dict, parameter_overrides=None):
"""
Given a SAM template dictionary, return a cleaned copy of the template where SAM plugins have been run
and parameter values have been substituted.
Parameters
----------
template_dict : dict
unproc... | Given a SAM template dictionary, return a cleaned copy of the template where SAM plugins have been run
and parameter values have been substituted.
Parameters
----------
template_dict : dict
unprocessed SAM template dictionary
parameter_overrides: dict
Op... |
def _get_username(self, username=None, use_config=True, config_filename=None):
"""Determine the username
If a username is given, this name is used. Otherwise the configuration
file will be consulted if `use_config` is set to True. The user is asked
for the username if the username is no... | Determine the username
If a username is given, this name is used. Otherwise the configuration
file will be consulted if `use_config` is set to True. The user is asked
for the username if the username is not available. Then the username is
stored in the configuration file.
:para... |
def IsOutOfLineMethodDefinition(clean_lines, linenum):
"""Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition... | Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition. |
def insert(self, var, value, index=None):
"""Insert at the index.
If the index is not provided appends to the end of the list.
"""
current = self.__get(var)
if not isinstance(current, list):
raise KeyError("%s: is not a list" % var)
if index is None:
... | Insert at the index.
If the index is not provided appends to the end of the list. |
def datafind_connection(server=None):
""" Return a connection to the datafind server
Parameters
-----------
server : {SERVER:PORT, string}, optional
A string representation of the server and port.
The port may be ommitted.
Returns
--------
connection
The open connecti... | Return a connection to the datafind server
Parameters
-----------
server : {SERVER:PORT, string}, optional
A string representation of the server and port.
The port may be ommitted.
Returns
--------
connection
The open connection to the datafind server. |
def get_source(self, environment, template):
'''
Salt-specific loader to find imported jinja files.
Jinja imports will be interpreted as originating from the top
of each of the directories in the searchpath when the template
name does not begin with './' or '../'. When a templa... | Salt-specific loader to find imported jinja files.
Jinja imports will be interpreted as originating from the top
of each of the directories in the searchpath when the template
name does not begin with './' or '../'. When a template name
begins with './' or '../' then the import will be... |
def add_section(self, section):
"""A block section of code to be used as substitutions
:param section: A block section of code to be used as substitutions
:type section: Section
"""
self._sections = self._ensure_append(section, self._sections) | A block section of code to be used as substitutions
:param section: A block section of code to be used as substitutions
:type section: Section |
def teetsv(table, source=None, encoding=None, errors='strict', write_header=True,
**csvargs):
"""
Convenience function, as :func:`petl.io.csv.teecsv` but with different
default dialect (tab delimited).
"""
csvargs.setdefault('dialect', 'excel-tab')
return teecsv(table, source=source... | Convenience function, as :func:`petl.io.csv.teecsv` but with different
default dialect (tab delimited). |
def fundrefxml2json(self, node):
"""Convert a FundRef 'skos:Concept' node into JSON."""
doi = FundRefDOIResolver.strip_doi_host(self.get_attrib(node,
'rdf:about'))
oaf_id = FundRefDOIResolver().resolve_by_doi(
"http://dx.doi.org/" + doi... | Convert a FundRef 'skos:Concept' node into JSON. |
def _summarize_o_mutation_type(model):
"""
This function create the actual mutation io summary corresponding to the model
"""
from nautilus.api.util import summarize_mutation_io
# compute the appropriate name for the object
object_type_name = get_model_string(model)
# return a mutation ... | This function create the actual mutation io summary corresponding to the model |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.