code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def ggnn_fast_dense(node_states,
adjacency_matrix,
num_edge_types,
total_value_depth,
name=None):
"""ggnn version of the MPNN from Gilmer et al.
Let B be the number of batches.
Let D be the size of the node hidden states.
Let K be ... | ggnn version of the MPNN from Gilmer et al.
Let B be the number of batches.
Let D be the size of the node hidden states.
Let K be the size of the attention keys/queries.
Let V be the size of the output of the ggnn.
Let T be the number of transforms / edge types.
Args:
node_states: The value Tensor of ... |
def shift_right_3d(x, pad_value=None):
"""Shift the second dimension of x right by one."""
if pad_value is None:
shifted_targets = tf.pad(x, [[0, 0], [1, 0], [0, 0]])[:, :-1, :]
else:
shifted_targets = tf.concat([pad_value, x], axis=1)[:, :-1, :]
return shifted_targets | Shift the second dimension of x right by one. |
def compute(self):
"""Compute and return the signature according to the given data."""
if "Signature" in self.params:
raise RuntimeError("Existing signature in parameters")
if self.signature_version is not None:
version = self.signature_version
else:
v... | Compute and return the signature according to the given data. |
def setTau(self, vehID, tau):
"""setTau(string, double) -> None
Sets the driver's tau-parameter (reaction time or anticipation time depending on the car-following model) in s for this vehicle.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_TAU, vehI... | setTau(string, double) -> None
Sets the driver's tau-parameter (reaction time or anticipation time depending on the car-following model) in s for this vehicle. |
def split_filename(pathname):
"""
@type pathname: str
@param pathname: Absolute path.
@rtype: tuple( str, str )
@return: Tuple containing the path to the file and the base filename.
"""
filepart = win32.PathFindFileName(pathname)
pathpart = win32.PathRe... | @type pathname: str
@param pathname: Absolute path.
@rtype: tuple( str, str )
@return: Tuple containing the path to the file and the base filename. |
def get_source_from_contracts_list(self, contracts):
"""
get the source data from the contracts list
:param contracts: the list of contracts
:return:
"""
if contracts is None or len(contracts) == 0:
return
if isinstance(contracts[0], SolidityContract):... | get the source data from the contracts list
:param contracts: the list of contracts
:return: |
def get_relationship_query_session_for_family(self, family_id=None, proxy=None):
"""Gets the ``OsidSession`` associated with the relationship query service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the family
arg: proxy (osid.proxy.Proxy): a proxy
return: (o... | Gets the ``OsidSession`` associated with the relationship query service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the family
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.relationship.RelationshipQuerySession) - a
``RelationshipQuerySession``
... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See documentation for method `GroundShakingIntensityModel` in
:class:~`openquake.hazardlib.gsim.base.GSIM`
"""
mean, stds = self._get_mean_and_stddevs(sites, rup, dists, imt,
... | See documentation for method `GroundShakingIntensityModel` in
:class:~`openquake.hazardlib.gsim.base.GSIM` |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._uuid is not None:
return False
if self._avatar is not None:
return False
if self._public_nick_name is not None:
return False
if self._display_name is not None:
... | :rtype: bool |
def _countOverlap(rep1, rep2):
"""
Return the overlap between two representations. rep1 and rep2 are lists of
non-zero indices.
"""
overlap = 0
for e in rep1:
if e in rep2:
overlap += 1
return overlap | Return the overlap between two representations. rep1 and rep2 are lists of
non-zero indices. |
def list_campaigns(self, **kwargs):
"""List all update campaigns.
:param int limit: number of campaigns to retrieve
:param str order: sort direction of campaigns when ordered by creation time (desc|asc)
:param str after: get campaigns after given campaign ID
:param dict filters:... | List all update campaigns.
:param int limit: number of campaigns to retrieve
:param str order: sort direction of campaigns when ordered by creation time (desc|asc)
:param str after: get campaigns after given campaign ID
:param dict filters: Dictionary of filters to apply
:return... |
def _iterbfs(self, start, end=None, forward=True):
"""
The forward parameter specifies whether it is a forward or backward
traversal. Returns a list of tuples where the first value is the hop
value the second value is the node id.
"""
queue, visited = deque([(start, 0)])... | The forward parameter specifies whether it is a forward or backward
traversal. Returns a list of tuples where the first value is the hop
value the second value is the node id. |
def moreData(ra,dec,box):
"""Search the CFHT archive for more images of this location"""
import cfhtCutout
cdata={'ra_deg': ra, 'dec_deg': dec, 'radius_deg': 0.2}
inter=cfhtCutout.find_images(cdata,0.2) | Search the CFHT archive for more images of this location |
def get(self, key):
'''
Get a value for a given key
:param key: entry's key
:return: corresponding value
'''
if key in self._data_fields:
return self._data_fields[key]
if key in self._sub_reports:
return self._sub_reports[key]
retu... | Get a value for a given key
:param key: entry's key
:return: corresponding value |
def _update_secrets(self):
'''update secrets will take a secrets credential file
either located at .sregistry or the environment variable
SREGISTRY_CLIENT_SECRETS and update the current client
secrets as well as the associated API base.
'''
self.secrets = read_client_sec... | update secrets will take a secrets credential file
either located at .sregistry or the environment variable
SREGISTRY_CLIENT_SECRETS and update the current client
secrets as well as the associated API base. |
def averageValues(self):
"""
return the averaged values in the grid
"""
assert self.opts['record_density'] and self.opts['method'] == 'sum'
# dont increase value of partly filled cells (density 0..1):
filled = self.density > 1
v = self.values.copy()
v[fill... | return the averaged values in the grid |
def pull_tar(url, name, verify=False):
'''
Execute a ``machinectl pull-raw`` to download a .tar container image,
and add it to /var/lib/machines as a new container.
.. note::
**Requires systemd >= 219**
url
URL from which to download the container
name
Name for the ne... | Execute a ``machinectl pull-raw`` to download a .tar container image,
and add it to /var/lib/machines as a new container.
.. note::
**Requires systemd >= 219**
url
URL from which to download the container
name
Name for the new container
verify : False
Perform sig... |
def _(f, x):
"""
fmap for dict like, not `f` should have signature `f::key->value->(key, value)`
"""
result = {}
for k, v in x.items():
k_, v_ = f(k, v)
result[k_] = v_
return result | fmap for dict like, not `f` should have signature `f::key->value->(key, value)` |
def _get_driver(self):
"""Get authenticated GCE driver."""
ComputeEngine = get_driver(Provider.GCE)
return ComputeEngine(
self.service_account_email,
self.service_account_file,
project=self.service_account_project
) | Get authenticated GCE driver. |
def create_weapon_layer(weapon, hashcode, isSecond=False):
"""Creates the layer for weapons."""
return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + weapon + '.pgn', hashcode, sym=False, invert=isSecond) | Creates the layer for weapons. |
def decimal(self, prompt, default=None, lower=None, upper=None):
"""Prompts user to input decimal, with optional default and bounds."""
prompt = prompt if prompt is not None else "Enter a decimal number"
prompt += " [{0}]: ".format(default) if default is not None else ': '
return self.in... | Prompts user to input decimal, with optional default and bounds. |
def exit_config_mode(self, exit_config="exit configuration-mode"):
"""Exit configuration mode."""
output = ""
if self.check_config_mode():
output = self.send_command_timing(
exit_config, strip_prompt=False, strip_command=False
)
# if 'Exit with... | Exit configuration mode. |
def insert(self, context, plan):
"""
Include an insert operation to the given plan.
:param execution.Context context:
Current execution context.
:param list plan:
List of :class:`execution.Operation` instances.
"""
op = execution.Insert(self.__comp_name, self.__comp())
if op not in plan ... | Include an insert operation to the given plan.
:param execution.Context context:
Current execution context.
:param list plan:
List of :class:`execution.Operation` instances. |
def run(**kwargs):
'''
Run a single module function or a range of module functions in a batch.
Supersedes ``module.run`` function, which requires ``m_`` prefix to
function-specific parameters.
:param returner:
Specify a common returner for the whole batch to send the return data
:param... | Run a single module function or a range of module functions in a batch.
Supersedes ``module.run`` function, which requires ``m_`` prefix to
function-specific parameters.
:param returner:
Specify a common returner for the whole batch to send the return data
:param kwargs:
Pass any argum... |
def rollback(self):
"""
It will rollback all changes and go to the *original_config*
"""
logger.info('Rolling back changes')
config_text = self.compare_config(other=self.original_config)
if len(config_text) > 0:
return self._commit(config_text, force=True, r... | It will rollback all changes and go to the *original_config* |
def set_default(self):
"""Set config to default."""
try:
os.makedirs(os.path.dirname(self._configfile))
except:
pass
self._config = configparser.RawConfigParser()
self._config.add_section('Settings')
for key, val in self.DEFAULTS.items():
... | Set config to default. |
def smooth(x0, rho, gamma, axis=0):
"""
Proximal operator for a smoothing function enforced via the discrete laplacian operator
Notes
-----
Currently only works with matrices (2-D arrays) as input
Parameters
----------
x0 : array_like
The starting or initial point used in the p... | Proximal operator for a smoothing function enforced via the discrete laplacian operator
Notes
-----
Currently only works with matrices (2-D arrays) as input
Parameters
----------
x0 : array_like
The starting or initial point used in the proximal update step
rho : float
Mom... |
def add_sign(xml, key, cert, debug=False, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1, digest_algorithm=OneLogin_Saml2_Constants.SHA1):
"""
Adds signature key and senders certificate to an element (Message or
Assertion).
:param xml: The element we should sign
:type: string ... | Adds signature key and senders certificate to an element (Message or
Assertion).
:param xml: The element we should sign
:type: string | Document
:param key: The private key
:type: string
:param cert: The public
:type: string
:param debug: Activate the ... |
def remove_functions(source, all_inline=False):
"""removes functions and returns new source, and 2 dicts.
first dict with removed hoisted(global) functions and second with replaced inline functions"""
global INLINE_COUNT
inline = {}
hoisted = {}
n = 0
limit = len(source) - 9 # 8 is leng... | removes functions and returns new source, and 2 dicts.
first dict with removed hoisted(global) functions and second with replaced inline functions |
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["params"] = ", ".join(self.parameters)
return result | A dict of members expressed in literals |
def loggers(self):
"""Return all the loggers that should be activated"""
ret = []
if self.logger_name:
if isinstance(self.logger_name, logging.Logger):
ret.append((self.logger_name.name, self.logger_name))
else:
ret.append((self.logger_name... | Return all the loggers that should be activated |
def _detach(cls, disk_id):
""" Detach a disk from a vm. """
disk = cls._info(disk_id)
opers = []
if disk.get('vms_id'):
for vm_id in disk['vms_id']:
cls.echo('The disk is still attached to the vm %s.' % vm_id)
cls.echo('Will detach it.')
... | Detach a disk from a vm. |
def sponsored(self, **kwargs):
"""Search containing any sponsored pieces of Content."""
eqs = self.search(**kwargs)
eqs = eqs.filter(AllSponsored())
published_offset = getattr(settings, "RECENT_SPONSORED_OFFSET_HOURS", None)
if published_offset:
now = timezone.now()
... | Search containing any sponsored pieces of Content. |
def downgrade():
"""Downgrade database."""
op.drop_constraint(op.f('fk_oauth2server_token_user_id_accounts_user'),
'oauth2server_token', type_='foreignkey')
op.drop_index(op.f('ix_oauth2server_token_user_id'),
table_name='oauth2server_token')
op.create_foreign_ke... | Downgrade database. |
def sub_symbols(pattern, code, symbol):
"""Substitutes symbols in CLDR number pattern."""
return pattern.replace('¤¤', code).replace('¤', symbol) | Substitutes symbols in CLDR number pattern. |
def albedo(self, value=999.0):
"""Corresponds to IDD Field `albedo`
Args:
value (float): value for IDD Field `albedo`
Missing value: 999.0
if `value` is None it will not be checked against the
specification and is assumed to be a missing value... | Corresponds to IDD Field `albedo`
Args:
value (float): value for IDD Field `albedo`
Missing value: 999.0
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: ... |
def get(self, request, uri):
"""
List uri revisions.
JSON Response:
[[uri, state], ...]
"""
uri = self.decode_uri(uri)
revisions = cio.revisions(uri)
revisions = [list(revision) for revision in revisions] # Convert tuples to lists
return self... | List uri revisions.
JSON Response:
[[uri, state], ...] |
def grant(self, lock, unit):
'''Maybe grant the lock to a unit.
The decision to grant the lock or not is made for $lock
by a corresponding method grant_$lock, which you may define
in a subclass. If no such method is defined, the default_grant
method is used. See Serial.default_g... | Maybe grant the lock to a unit.
The decision to grant the lock or not is made for $lock
by a corresponding method grant_$lock, which you may define
in a subclass. If no such method is defined, the default_grant
method is used. See Serial.default_grant() for details. |
def write_summary(self, global_step, delta_train_start, lesson_num=0):
"""
Saves training statistics to Tensorboard.
:param delta_train_start: Time elapsed since training started.
:param lesson_num: Current lesson number in curriculum.
:param global_step: The number of steps the... | Saves training statistics to Tensorboard.
:param delta_train_start: Time elapsed since training started.
:param lesson_num: Current lesson number in curriculum.
:param global_step: The number of steps the simulation has been going for |
def dump_service(self, sc):
"""Read all data blocks of a given service.
:meth:`dump_service` reads all data blocks from the service
with service code *sc* and returns a list of strings suitable
for printing. The number of strings returned does not
necessarily reflect the number ... | Read all data blocks of a given service.
:meth:`dump_service` reads all data blocks from the service
with service code *sc* and returns a list of strings suitable
for printing. The number of strings returned does not
necessarily reflect the number of data blocks because a range
... |
def get_historical_klines(symbol, interval, start_str, end_str=None):
"""Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
... | Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
:param symbol: Name of symbol pair e.g BNBBTC
:type symbol: str
:p... |
def get_profile_info(self, raw_token, profile_info_params={}):
"Fetch user profile information."
try:
response = self.request('get', self.provider.profile_url, token=raw_token, params=profile_info_params)
response.raise_for_status()
except RequestException as e:
... | Fetch user profile information. |
def add_cookie_header(self, request, referrer_host=None):
'''Wrapped ``add_cookie_header``.
Args:
request: An instance of :class:`.http.request.Request`.
referrer_host (str): An hostname or IP address of the referrer
URL.
'''
new_request = convert... | Wrapped ``add_cookie_header``.
Args:
request: An instance of :class:`.http.request.Request`.
referrer_host (str): An hostname or IP address of the referrer
URL. |
def get_issues_in_queue(self, service_desk_id, queue_id, start=0, limit=50):
"""
Returns a page of issues inside a queue for a given queue ID.
Only fields that the queue is configured to show are returned.
For example, if a queue is configured to show only Description and Due Date,
... | Returns a page of issues inside a queue for a given queue ID.
Only fields that the queue is configured to show are returned.
For example, if a queue is configured to show only Description and Due Date,
then only those two fields are returned for each issue in the queue.
Permissions: The... |
def check_auth(self, username, password):
"""Check if a username/password combination is valid."""
if username == self.args.username:
from glances.password import GlancesPassword
pwd = GlancesPassword()
return pwd.check_password(self.args.password, pwd.sha256_hash(pas... | Check if a username/password combination is valid. |
def list_load_areas(self, session, mv_districts):
"""list load_areas (load areas) peak load from database for a single MV grid_district
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
mv_districts:
List of MV districts
... | list load_areas (load areas) peak load from database for a single MV grid_district
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
mv_districts:
List of MV districts |
def json_files_serializer(objs, status=None):
"""JSON Files Serializer.
:parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`
instances.
:param status: A HTTP Status. (Default: ``None``)
:returns: A Flask response with JSON data.
:rtype: :py:class:`flask.Response`.
"""
... | JSON Files Serializer.
:parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`
instances.
:param status: A HTTP Status. (Default: ``None``)
:returns: A Flask response with JSON data.
:rtype: :py:class:`flask.Response`. |
def _validate_schema(self, schema, field, value):
""" {'type': ['dict', 'string'],
'anyof': [{'validator': 'schema'},
{'validator': 'bulk_schema'}]} """
if schema is None:
return
if isinstance(value, Sequence) and not isinstance(value, _str_type):... | {'type': ['dict', 'string'],
'anyof': [{'validator': 'schema'},
{'validator': 'bulk_schema'}]} |
def sun_ra_dec(utc_time):
"""Right ascension and declination of the sun at *utc_time*.
"""
jdate = jdays2000(utc_time) / 36525.0
eps = np.deg2rad(23.0 + 26.0 / 60.0 + 21.448 / 3600.0 -
(46.8150 * jdate + 0.00059 * jdate * jdate -
0.001813 * jdate * jdate * jdat... | Right ascension and declination of the sun at *utc_time*. |
def sort(self, col: str):
"""
Sorts the main dataframe according to the given column
:param col: column name
:type col: str
:example: ``ds.sort("Col 1")``
"""
try:
self.df = self.df.copy().sort_values(col)
except Exception as e:
s... | Sorts the main dataframe according to the given column
:param col: column name
:type col: str
:example: ``ds.sort("Col 1")`` |
def safe_dump(d, fname, *args, **kwargs):
"""
Savely dump `d` to `fname` using yaml
This method creates a copy of `fname` called ``fname + '~'`` before saving
`d` to `fname` using :func:`ordered_yaml_dump`
Parameters
----------
d: object
The object to dump
fname: str
Th... | Savely dump `d` to `fname` using yaml
This method creates a copy of `fname` called ``fname + '~'`` before saving
`d` to `fname` using :func:`ordered_yaml_dump`
Parameters
----------
d: object
The object to dump
fname: str
The path where to dump `d`
Other Parameters
---... |
def _getReader(self, filename, scoreClass):
"""
Obtain a JSON record reader for DIAMOND records.
@param filename: The C{str} file name holding the JSON.
@param scoreClass: A class to hold and compare scores (see scores.py).
"""
if filename.endswith('.json') or filename.e... | Obtain a JSON record reader for DIAMOND records.
@param filename: The C{str} file name holding the JSON.
@param scoreClass: A class to hold and compare scores (see scores.py). |
def _sentiment(self, distance=True):
"""Calculates the sentiment of an entity as it appears in text."""
sum_pos = 0
sum_neg = 0
text = self.parent
entity_positions = range(self.start, self.end)
non_entity_positions = set(range(len(text.words))).difference(entity_positions)
if not distance:
... | Calculates the sentiment of an entity as it appears in text. |
def filter_renderers(self, renderers, format):
"""
If there is a '.json' style format suffix, filter the renderers
so that we only negotiation against those that accept that format.
"""
renderers = [renderer for renderer in renderers
if renderer.format == for... | If there is a '.json' style format suffix, filter the renderers
so that we only negotiation against those that accept that format. |
def _adaptSegment(self, segUpdate):
"""
This function applies segment update information to a segment in a
cell.
Synapses on the active list get their permanence counts incremented by
permanenceInc. All other synapses get their permanence counts decremented
by permanenceDec.
We also increm... | This function applies segment update information to a segment in a
cell.
Synapses on the active list get their permanence counts incremented by
permanenceInc. All other synapses get their permanence counts decremented
by permanenceDec.
We also increment the positiveActivations count of the segment... |
def fit_transform(self, Z):
"""Learn the vocabulary dictionary and return term-document matrix.
This is equivalent to fit followed by transform, but more efficiently
implemented.
Parameters
----------
Z : iterable or DictRDD with column 'X'
An iterable of ra... | Learn the vocabulary dictionary and return term-document matrix.
This is equivalent to fit followed by transform, but more efficiently
implemented.
Parameters
----------
Z : iterable or DictRDD with column 'X'
An iterable of raw_documents which yields either str, un... |
def generate_description(dataset_name, local_cache_dir=None):
"""Generates desription for a given dataset in its README.md file in a dataset local_cache_dir file.
:param dataset_name: str
The name of the data set to load from PMLB.
:param local_cache_dir: str (required)
The directory on... | Generates desription for a given dataset in its README.md file in a dataset local_cache_dir file.
:param dataset_name: str
The name of the data set to load from PMLB.
:param local_cache_dir: str (required)
The directory on your local machine to store the data files.
If None, then th... |
def predict(self, Xnew, full_cov=False, kern=None, **kwargs):
"""
Predict the function(s) at the new point(s) Xnew. For Student-t processes, this method is equivalent to
predict_noiseless as no likelihood is included in the model.
"""
return self.predict_noiseless(Xnew, full_cov=... | Predict the function(s) at the new point(s) Xnew. For Student-t processes, this method is equivalent to
predict_noiseless as no likelihood is included in the model. |
def _get_encoding(encoding_or_label):
"""
Accept either an encoding object or label.
:param encoding: An :class:`Encoding` object or a label string.
:returns: An :class:`Encoding` object.
:raises: :exc:`~exceptions.LookupError` for an unknown label.
"""
if hasattr(encoding_or_label, 'codec... | Accept either an encoding object or label.
:param encoding: An :class:`Encoding` object or a label string.
:returns: An :class:`Encoding` object.
:raises: :exc:`~exceptions.LookupError` for an unknown label. |
def _piecewise(x, condlist, funclist, *args, **kw):
'''Fixed version of numpy.piecewise for 0-d arrays'''
x = asanyarray(x)
n2 = len(funclist)
if isscalar(condlist) or \
(isinstance(condlist, np.ndarray) and condlist.ndim == 0) or \
(x.ndim > 0 and condlist[0].ndim == 0):
... | Fixed version of numpy.piecewise for 0-d arrays |
def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
# If initial Y is non-zero, initial U is chosen so that
# the relevant dual optimality criterion (see (3.10) i... | Return initialiser for working variable U. |
def get_query_error(self,i):
"""Just get a single error characterization based on the index
:param i: list index
:type i: int
:returns: base-wise error
:rtype: HPA group description
"""
x = self._query_hpas[i]
h = x['hpa']
pos = x['pos']
prob = 0
be = BaseError('query')
... | Just get a single error characterization based on the index
:param i: list index
:type i: int
:returns: base-wise error
:rtype: HPA group description |
def executed_without_callbacks(self):
"""
Called when the task has been successfully executed
and the Taskmaster instance doesn't want to call
the Node's callback methods.
"""
T = self.tm.trace
if T: T.write(self.trace_message('Task.executed_without_callbacks()',
... | Called when the task has been successfully executed
and the Taskmaster instance doesn't want to call
the Node's callback methods. |
def keys(self):
"""
Returns a sorted list of keys
"""
keys = list()
for n in range(len(self)):
# only append the valid keys
key = self.get_value()
if not key in ['', None]: keys.append(key)
return keys | Returns a sorted list of keys |
def filter_trends(self, pattern=''):
"""
Filter available trends
"""
filtered_trends = {}
with open(self.abspath) as fobj:
for idx, line in enumerate(fobj):
variable_idx = idx-self._attributes['CATALOG']-1
if 'TIME SERIES' in li... | Filter available trends |
def check_output(self, cmd):
"""Wrapper for subprocess.check_output."""
ret, output = self._exec(cmd)
if not ret == 0:
raise CommandError(self)
return output | Wrapper for subprocess.check_output. |
def setdbo(self, bond1, bond2, dboval):
"""Set the double bond orientation for bond1 and bond2
based on this bond"""
# this bond must be a double bond
if self.bondtype != 2:
raise FrownsError("To set double bond order, center bond must be double!")
assert dboval in [D... | Set the double bond orientation for bond1 and bond2
based on this bond |
def update_tab_label(self, state_m):
"""Update all tab labels
:param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier not in self.tabs and state_identifier ... | Update all tab labels
:param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated |
def num_samples(input_filepath):
'''
Show number of samples (0 if unavailable).
Parameters
----------
input_filepath : str
Path to audio file.
Returns
-------
n_samples : int
total number of samples in audio file.
Returns 0 if empty or unavailable
'''
va... | Show number of samples (0 if unavailable).
Parameters
----------
input_filepath : str
Path to audio file.
Returns
-------
n_samples : int
total number of samples in audio file.
Returns 0 if empty or unavailable |
def reduce_multiline(string):
"""
reduces a multiline string to a single line of text.
args:
string: the text to reduce
"""
string = str(string)
return " ".join([item.strip()
for item in string.split("\n")
if item.strip()]) | reduces a multiline string to a single line of text.
args:
string: the text to reduce |
def _register_template(cls, template_bytes):
'''Registers the template for the widget and hooks init_template'''
# This implementation won't work if there are nested templates, but
# we can't do that anyways due to PyGObject limitations so it's ok
if not hasattr(cls, 'set_template'):
raise Typ... | Registers the template for the widget and hooks init_template |
def sanitize_for_archive(url, headers, payload):
"""Sanitize URL of a HTTP request by removing the token information
before storing/retrieving archived items
:param: url: HTTP url request
:param: headers: HTTP headers request
:param: payload: HTTP payload request
:retur... | Sanitize URL of a HTTP request by removing the token information
before storing/retrieving archived items
:param: url: HTTP url request
:param: headers: HTTP headers request
:param: payload: HTTP payload request
:returns the sanitized url, plus the headers and payload |
def _scope_and_enforce_robots(self, site, parent_page, outlinks):
'''
Returns tuple (
dict of {page_id: Page} of fresh `brozzler.Page` representing in
scope links accepted by robots policy,
set of in scope urls (canonicalized) blocked by robots policy,
... | Returns tuple (
dict of {page_id: Page} of fresh `brozzler.Page` representing in
scope links accepted by robots policy,
set of in scope urls (canonicalized) blocked by robots policy,
set of out-of-scope urls (canonicalized)). |
def pre_fork(self, process_manager):
'''
Pre-fork we need to create the zmq router device
:param func process_manager: An instance of salt.utils.process.ProcessManager
'''
salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
process_manager.add_pr... | Pre-fork we need to create the zmq router device
:param func process_manager: An instance of salt.utils.process.ProcessManager |
def get_reduced_assignment(
self,
original_assignment,
cluster_topology,
max_partition_movements,
max_leader_only_changes,
max_movement_size=DEFAULT_MAX_MOVEMENT_SIZE,
force_progress=False,
):
"""Reduce the assignment based on the total actions.
... | Reduce the assignment based on the total actions.
Actions represent actual partition movements
and/or changes in preferred leader.
Get the difference of original and proposed assignment
and take the subset of this plan for given limit.
Argument(s):
original_assignment: ... |
def request_token(self):
""" Returns url, request_token, request_secret"""
logging.debug("Getting request token from %s:%d",
self.server, self.port)
token, secret = self._token("/oauth/requestToken")
return "{}/oauth/authorize?oauth_token={}".format(self.host, token... | Returns url, request_token, request_secret |
def referencegenomefinder(self):
"""
Finds the closest reference genome to the profile of interest
"""
# Initialise dictionaries
referencematch = defaultdict(make_dict)
referencehits = defaultdict(make_dict)
# Set the name of the reference profile file
ref... | Finds the closest reference genome to the profile of interest |
def identical_dataset_and_algorithm_tuner(self, additional_parents=None):
"""Creates a new ``HyperparameterTuner`` by copying the request fields from the provided parent to the new
instance of ``HyperparameterTuner``. Followed by addition of warm start configuration with the type as
"IdenticalDa... | Creates a new ``HyperparameterTuner`` by copying the request fields from the provided parent to the new
instance of ``HyperparameterTuner``. Followed by addition of warm start configuration with the type as
"IdenticalDataAndAlgorithm" and parents as the union of provided list of ``additional_parents`` a... |
def sens_mppt_send(self, mppt_timestamp, mppt1_volt, mppt1_amp, mppt1_pwm, mppt1_status, mppt2_volt, mppt2_amp, mppt2_pwm, mppt2_status, mppt3_volt, mppt3_amp, mppt3_pwm, mppt3_status, force_mavlink1=False):
'''
Maximum Power Point Tracker (MPPT) sensor data for solar module power
... | Maximum Power Point Tracker (MPPT) sensor data for solar module power
performance tracking
mppt_timestamp : MPPT last timestamp (uint64_t)
mppt1_volt : MPPT1 voltage (float)
mppt1_amp : MPPT1 current (float)
... |
def get_ngrams(inputfile, n=1, use_transcript=False, use_vtt=False):
'''
Get ngrams from a text
Sourced from:
https://gist.github.com/dannguyen/93c2c43f4e65328b85af
'''
words = []
if use_transcript:
for s in audiogrep.convert_timestamps(inputfile):
for w in s['words']:
... | Get ngrams from a text
Sourced from:
https://gist.github.com/dannguyen/93c2c43f4e65328b85af |
def get_compositions_by_repository(self, repository_id):
"""Gets the list of ``Compositions`` associated with a ``Repository``.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.repository.CompositionList) - list of related
compositions
raise... | Gets the list of ``Compositions`` associated with a ``Repository``.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.repository.CompositionList) - list of related
compositions
raise: NotFound - ``repository_id`` is not found
raise: NullArg... |
def make_tarfile(output_filename, source_dir):
'''
Tar a directory
'''
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir)) | Tar a directory |
def status_favourite(self, id):
"""
Favourite a status.
Returns a `toot dict`_ with the favourited status.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/favourite'.format(str(id))
return self.__api_request('POST', url) | Favourite a status.
Returns a `toot dict`_ with the favourited status. |
def _open_ftp(self):
# type: () -> FTP
"""Open a new ftp object.
"""
_ftp = FTP()
_ftp.set_debuglevel(0)
with ftp_errors(self):
_ftp.connect(self.host, self.port, self.timeout)
_ftp.login(self.user, self.passwd, self.acct)
self._feature... | Open a new ftp object. |
def process(source, target, rdfsonly, base=None, logger=logging):
'''
Prepare a statement into a triple ready for rdflib graph
'''
for link in source.match():
s, p, o = link[:3]
#SKip docheader statements
if s == (base or '') + '@docheader': continue
if p in RESOURCE_MAP... | Prepare a statement into a triple ready for rdflib graph |
def mutate(self, row):
""" Add a row to the batch. If the current batch meets one of the size
limits, the batch is sent synchronously.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_batcher_mutate]
:end-before: [END bigtable_batcher_m... | Add a row to the batch. If the current batch meets one of the size
limits, the batch is sent synchronously.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_batcher_mutate]
:end-before: [END bigtable_batcher_mutate]
:type row: class
... |
def query(self, coords, **kwargs):
"""
Returns E(B-V), in mags, at the specified location(s) on the sky.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query.
Returns:
A float array of the reddening, in magnitudes of E(B-V), at the
... | Returns E(B-V), in mags, at the specified location(s) on the sky.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query.
Returns:
A float array of the reddening, in magnitudes of E(B-V), at the
selected coordinates. |
def write_config_file(self, parsed_namespace, output_file_paths, exit_after=False):
"""Write the given settings to output files.
Args:
parsed_namespace: namespace object created within parse_known_args()
output_file_paths: any number of file paths to write the config to
... | Write the given settings to output files.
Args:
parsed_namespace: namespace object created within parse_known_args()
output_file_paths: any number of file paths to write the config to
exit_after: whether to exit the program after writing the config files |
def find_threads_by_name(self, name, bExactMatch = True):
"""
Find threads by name, using different search methods.
@type name: str, None
@param name: Name to look for. Use C{None} to find nameless threads.
@type bExactMatch: bool
@param bExactMatch: C{True} if the na... | Find threads by name, using different search methods.
@type name: str, None
@param name: Name to look for. Use C{None} to find nameless threads.
@type bExactMatch: bool
@param bExactMatch: C{True} if the name must be
B{exactly} as given, C{False} if the name can be
... |
def main(self, c):
"""
:type c: Complex
:rtype: Sfix
"""
conj = self.conjugate.main(c)
mult = self.complex_mult.main(c, conj)
angle = self.angle.main(mult)
self.y = self.GAIN_SFIX * angle
return self.y | :type c: Complex
:rtype: Sfix |
def get_object(self):
"""
Get the object for publishing
Raises a http404 error if the object is not found.
"""
obj = super(PublishActionView, self).get_object()
if obj:
if not hasattr(obj, 'publish'):
raise http.Http404
return obj | Get the object for publishing
Raises a http404 error if the object is not found. |
def pset_field(item_type, optional=False, initial=()):
"""
Create checked ``PSet`` field.
:param item_type: The required type for the items in the set.
:param optional: If true, ``None`` can be used as a value for
this field.
:param initial: Initial value to pass to factory if no value is g... | Create checked ``PSet`` field.
:param item_type: The required type for the items in the set.
:param optional: If true, ``None`` can be used as a value for
this field.
:param initial: Initial value to pass to factory if no value is given
for the field.
:return: A ``field`` containing a ... |
def redirect_to():
"""302/3XX Redirects to the given URL.
---
tags:
- Redirects
produces:
- text/html
get:
parameters:
- in: query
name: url
type: string
required: true
- in: query
name: status_code
type: int
pos... | 302/3XX Redirects to the given URL.
---
tags:
- Redirects
produces:
- text/html
get:
parameters:
- in: query
name: url
type: string
required: true
- in: query
name: status_code
type: int
post:
consumes:
... |
def inspect_built_image(self):
"""
inspect built image
:return: dict
"""
logger.info("inspecting built image '%s'", self.image_id)
self.ensure_is_built()
# dict with lots of data, see man docker-inspect
inspect_data = self.tasker.inspect_image(self.image_... | inspect built image
:return: dict |
def get(self):
"""
Get a connection from the pool, to make and receive traffic.
If the connection fails for any reason (socket.error), it is dropped
and a new one is scheduled. Please use @retry as a way to automatically
retry whatever operation you were performing.
"""
... | Get a connection from the pool, to make and receive traffic.
If the connection fails for any reason (socket.error), it is dropped
and a new one is scheduled. Please use @retry as a way to automatically
retry whatever operation you were performing. |
def task(self, task_name):
"""
Returns an ENVI Py Engine Task object. See ENVI Py Engine Task for examples.
:param task_name: The name of the task to retrieve.
:return: An ENVI Py Engine Task object.
"""
return Task(uri=':'.join((self._engine_name, task_name)), cwd=self.... | Returns an ENVI Py Engine Task object. See ENVI Py Engine Task for examples.
:param task_name: The name of the task to retrieve.
:return: An ENVI Py Engine Task object. |
def apply(self, func, *args, **kwargs):
"""Apply the provided function and combine the results together in the
same way as apply from groupby in pandas.
This returns a DataFrame.
"""
self._prep_pandas_groupby()
def key_by_index(data):
"""Key each row by its ... | Apply the provided function and combine the results together in the
same way as apply from groupby in pandas.
This returns a DataFrame. |
def __bindings(self):
"""Binds events to handlers"""
self.textctrl.Bind(wx.EVT_TEXT, self.OnText)
self.fontbutton.Bind(wx.EVT_BUTTON, self.OnFont)
self.Bind(csel.EVT_COLOURSELECT, self.OnColor) | Binds events to handlers |
def get_grouped_translations(instances, **kwargs):
"""
Takes instances and returns grouped translations ready to
be set in cache.
"""
grouped_translations = collections.defaultdict(list)
if not instances:
return grouped_translations
if not isinstance(instances, collections.Iterable... | Takes instances and returns grouped translations ready to
be set in cache. |
def _scan_for_tokens(contents):
"""Scan a string for tokens and return immediate form tokens."""
# Regexes are in priority order. Changing the order may alter the
# behavior of the lexer
scanner = re.Scanner([
# Things inside quotes
(r"(?<![^\s\(])([\"\'])(?:(?=(\\?))\2.)*?\1(?![^\s\)])"... | Scan a string for tokens and return immediate form tokens. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.