code
stringlengths 51
2.38k
| docstring
stringlengths 4
15.2k
|
---|---|
def get_sym_eq_kpoints(self, kpoint, cartesian=False, tol=1e-2):
if not self.structure:
return None
sg = SpacegroupAnalyzer(self.structure)
symmops = sg.get_point_group_operations(cartesian=cartesian)
points = np.dot(kpoint, [m.rotation_matrix for m in symmops])
rm_list = []
for i in range(len(points) - 1):
for j in range(i + 1, len(points)):
if np.allclose(pbc_diff(points[i], points[j]), [0, 0, 0], tol):
rm_list.append(i)
break
return np.delete(points, rm_list, axis=0)
|
Returns a list of unique symmetrically equivalent k-points.
Args:
kpoint (1x3 array): coordinate of the k-point
cartesian (bool): kpoint is in cartesian or fractional coordinates
tol (float): tolerance below which coordinates are considered equal
Returns:
([1x3 array] or None): if structure is not available returns None
|
def CreateBlockDeviceMap(self, image_id, instance_type):
image = self.ec2.get_image(image_id)
block_device_map = image.block_device_mapping
assert(block_device_map)
ephemeral_device_names = ['/dev/sdb', '/dev/sdc', '/dev/sdd', '/dev/sde']
for i, device_name in enumerate(ephemeral_device_names):
name = 'ephemeral%d' % (i)
bdt = blockdevicemapping.BlockDeviceType(ephemeral_name = name)
block_device_map[device_name] = bdt
return block_device_map
|
If you launch without specifying a manual device block mapping, you may
not get all the ephemeral devices available to the given instance type.
This will build one that ensures all available ephemeral devices are
mapped.
|
def _configure_ebs_volume(self, vol_type, name, size, delete_on_termination):
root_dev = boto.ec2.blockdevicemapping.BlockDeviceType()
root_dev.delete_on_termination = delete_on_termination
root_dev.volume_type = vol_type
if size != 'default':
root_dev.size = size
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
bdm[name] = root_dev
return bdm
|
Sets the desired root EBS size, otherwise the default EC2 value is used.
:param vol_type: Type of EBS storage - gp2 (SSD), io1 or standard (magnetic)
:type vol_type: str
:param size: Desired root EBS size.
:type size: int
:param delete_on_termination: Toggle this flag to delete EBS volume on termination.
:type delete_on_termination: bool
:return: A BlockDeviceMapping object.
:rtype: object
|
def to_dict(self):
session = self._get_session()
snapshot = self._get_snapshot()
return {
"session_id": session._session_id,
"transaction_id": snapshot._transaction_id,
}
|
Return state as a dictionary.
Result can be used to serialize the instance and reconstitute
it later using :meth:`from_dict`.
:rtype: dict
|
def getopt(self, p, default=None):
for k, v in self.pairs:
if k == p:
return v
return default
|
Returns the first option value stored that matches p or default.
|
def _fetch_dataframe(self):
def reshape(training_summary):
out = {}
for k, v in training_summary['TunedHyperParameters'].items():
try:
v = float(v)
except (TypeError, ValueError):
pass
out[k] = v
out['TrainingJobName'] = training_summary['TrainingJobName']
out['TrainingJobStatus'] = training_summary['TrainingJobStatus']
out['FinalObjectiveValue'] = training_summary.get('FinalHyperParameterTuningJobObjectiveMetric',
{}).get('Value')
start_time = training_summary.get('TrainingStartTime', None)
end_time = training_summary.get('TrainingEndTime', None)
out['TrainingStartTime'] = start_time
out['TrainingEndTime'] = end_time
if start_time and end_time:
out['TrainingElapsedTimeSeconds'] = (end_time - start_time).total_seconds()
return out
df = pd.DataFrame([reshape(tjs) for tjs in self.training_job_summaries()])
return df
|
Return a pandas dataframe with all the training jobs, along with their
hyperparameters, results, and metadata. This also includes a column to indicate
if a training job was the best seen so far.
|
def export_modifications(self):
if self.__modified_data__ is not None:
return self.export_data()
result = {}
for key, value in enumerate(self.__original_data__):
try:
if not value.is_modified():
continue
modifications = value.export_modifications()
except AttributeError:
continue
try:
result.update({'{}.{}'.format(key, f): v for f, v in modifications.items()})
except AttributeError:
result[key] = modifications
return result
|
Returns list modifications.
|
def pop_fw_local(self, tenant_id, net_id, direc, node_ip):
net = self.get_network(net_id)
serv_obj = self.get_service_obj(tenant_id)
serv_obj.update_fw_local_cache(net_id, direc, node_ip)
if net is not None:
net_dict = self.fill_dcnm_net_info(tenant_id, direc, net.vlan,
net.segmentation_id)
serv_obj.store_dcnm_net_dict(net_dict, direc)
if direc == "in":
subnet = self.service_in_ip.get_subnet_by_netid(net_id)
else:
subnet = self.service_out_ip.get_subnet_by_netid(net_id)
if subnet is not None:
subnet_dict = self.fill_dcnm_subnet_info(
tenant_id, subnet,
self.get_start_ip(subnet), self.get_end_ip(subnet),
self.get_gateway(subnet), self.get_secondary_gateway(subnet),
direc)
serv_obj.store_dcnm_subnet_dict(subnet_dict, direc)
|
Populate the local cache.
Read the Network DB and populate the local cache.
Read the subnet from the Subnet DB, given the net_id and populate the
cache.
|
def set_pragmas(self, pragmas):
self.pragmas = pragmas
c = self.conn.cursor()
c.executescript(
';\n'.join(
['PRAGMA %s=%s' % i for i in self.pragmas.items()]
)
)
self.conn.commit()
|
Set pragmas for the current database connection.
Parameters
----------
pragmas : dict
Dictionary of pragmas; see constants.default_pragmas for a template
and http://www.sqlite.org/pragma.html for a full list.
|
def _admin_metadata_from_uri(uri, config_path):
uri = dtoolcore.utils.sanitise_uri(uri)
storage_broker = _get_storage_broker(uri, config_path)
admin_metadata = storage_broker.get_admin_metadata()
return admin_metadata
|
Helper function for getting admin metadata.
|
def declare_local_operator(self, type, raw_model=None):
onnx_name = self.get_unique_operator_name(str(type))
operator = Operator(onnx_name, self.name, type, raw_model, self.target_opset)
self.operators[onnx_name] = operator
return operator
|
This function is used to declare new local operator.
|
def sort(self, columnId, order=Qt.AscendingOrder):
self.layoutAboutToBeChanged.emit()
self.sortingAboutToStart.emit()
column = self._dataFrame.columns[columnId]
self._dataFrame.sort_values(column, ascending=not bool(order), inplace=True)
self.layoutChanged.emit()
self.sortingFinished.emit()
|
Sorts the model column
After sorting the data in ascending or descending order, a signal
`layoutChanged` is emitted.
:param: columnId (int)
the index of the column to sort on.
:param: order (Qt::SortOrder, optional)
descending(1) or ascending(0). defaults to Qt.AscendingOrder
|
def metadata(dataset, node, entityids, extended=False, api_key=None):
api_key = _get_api_key(api_key)
url = '{}/metadata'.format(USGS_API)
payload = {
"jsonRequest": payloads.metadata(dataset, node, entityids, api_key=api_key)
}
r = requests.post(url, payload)
response = r.json()
_check_for_usgs_error(response)
if extended:
metadata_urls = map(_get_metadata_url, response['data'])
results = _async_requests(metadata_urls)
data = map(lambda idx: _get_extended(response['data'][idx], results[idx]), range(len(response['data'])))
return response
|
Request metadata for a given scene in a USGS dataset.
:param dataset:
:param node:
:param entityids:
:param extended:
Send a second request to the metadata url to get extended metadata on the scene.
:param api_key:
|
def get_project(username, project, machine_name=None):
try:
account = Account.objects.get(
username=username,
date_deleted__isnull=True)
except Account.DoesNotExist:
return "Account '%s' not found" % username
if project is None:
project = account.default_project
else:
try:
project = Project.objects.get(pid=project)
except Project.DoesNotExist:
project = account.default_project
if project is None:
return "None"
if account.person not in project.group.members.all():
project = account.default_project
if project is None:
return "None"
if account.person not in project.group.members.all():
return "None"
return project.pid
|
Used in the submit filter to make sure user is in project
|
def _update_indexes_for_deleted_object(collection, obj):
for index in _db[collection].indexes.values():
_remove_from_index(index, obj)
|
If an object is deleted, it should no longer be
indexed so this removes the object from all indexes
on the given collection.
|
def get_random_node(graph,
node_blacklist: Set[BaseEntity],
invert_degrees: Optional[bool] = None,
) -> Optional[BaseEntity]:
try:
nodes, degrees = zip(*(
(node, degree)
for node, degree in sorted(graph.degree(), key=itemgetter(1))
if node not in node_blacklist
))
except ValueError:
return
if invert_degrees is None or invert_degrees:
degrees = [1 / degree for degree in degrees]
wrg = WeightedRandomGenerator(nodes, degrees)
return wrg.next()
|
Choose a node from the graph with probabilities based on their degrees.
:type graph: networkx.Graph
:param node_blacklist: Nodes to filter out
:param invert_degrees: Should the degrees be inverted? Defaults to true.
|
def body_as_str(self, encoding='UTF-8'):
data = self.body
try:
return "".join(b.decode(encoding) for b in data)
except TypeError:
return six.text_type(data)
except:
pass
try:
return data.decode(encoding)
except Exception as e:
raise TypeError("Message data is not compatible with string type: {}".format(e))
|
The body of the event data as a string if the data is of a
compatible type.
:param encoding: The encoding to use for decoding message data.
Default is 'UTF-8'
:rtype: str or unicode
|
def _restore_volume(self, fade):
self.device.mute = self.mute
if self.volume == 100:
fixed_vol = self.device.renderingControl.GetOutputFixed(
[('InstanceID', 0)])['CurrentFixed']
else:
fixed_vol = False
if not fixed_vol:
self.device.bass = self.bass
self.device.treble = self.treble
self.device.loudness = self.loudness
if fade:
self.device.volume = 0
self.device.ramp_to_volume(self.volume)
else:
self.device.volume = self.volume
|
Reinstate volume.
Args:
fade (bool): Whether volume should be faded up on restore.
|
def _ensure_extra_rows(self, term, N):
attrs = self.graph.node[term]
attrs['extra_rows'] = max(N, attrs.get('extra_rows', 0))
|
Ensure that we're going to compute at least N extra rows of `term`.
|
def ingest(self, **kwargs):
__name__ = '%s.ingest' % self.__class__.__name__
schema_dict = self.schema
path_to_root = '.'
valid_data = self._ingest_dict(kwargs, schema_dict, path_to_root)
return valid_data
|
a core method to ingest and validate arbitrary keyword data
**NOTE: data is always returned with this method**
for each key in the model, a value is returned according
to the following priority:
1. value in kwargs if field passes validation test
2. default value declared for the key in the model
3. empty value appropriate to datatype of key in the model
**NOTE: as long as a default value is provided for each key-
value, returned data will be model valid
**NOTE: if 'extra_fields' is True for a dictionary, the key-
value pair of all fields in kwargs which are not declared in
the model will also be added to the corresponding dictionary
data
**NOTE: if 'max_size' is declared for a list, method will
stop adding input to the list once it reaches max size
:param kwargs: key, value pairs
:return: dictionary with keys and value
|
def copy_neg(self):
result = mpfr.Mpfr_t.__new__(BigFloat)
mpfr.mpfr_init2(result, self.precision)
new_sign = not self._sign()
mpfr.mpfr_setsign(result, self, new_sign, ROUND_TIES_TO_EVEN)
return result
|
Return a copy of self with the opposite sign bit.
Unlike -self, this does not make use of the context: the result
has the same precision as the original.
|
def get_property_value_for_brok(self, prop, tab):
entry = tab[prop]
value = getattr(self, prop, entry.default)
pre_op = entry.brok_transformation
if pre_op is not None:
value = pre_op(self, value)
return value
|
Get the property of an object and brok_transformation if needed and return the value
:param prop: property name
:type prop: str
:param tab: object with all properties of an object
:type tab: object
:return: value of the property original or brok converted
:rtype: str
|
def _init_dict(self, data, index=None, dtype=None):
if data:
keys, values = zip(*data.items())
values = list(values)
elif index is not None:
values = na_value_for_dtype(dtype)
keys = index
else:
keys, values = [], []
s = Series(values, index=keys, dtype=dtype)
if data and index is not None:
s = s.reindex(index, copy=False)
elif not PY36 and not isinstance(data, OrderedDict) and data:
try:
s = s.sort_index()
except TypeError:
pass
return s._data, s.index
|
Derive the "_data" and "index" attributes of a new Series from a
dictionary input.
Parameters
----------
data : dict or dict-like
Data used to populate the new Series
index : Index or index-like, default None
index for the new Series: if None, use dict keys
dtype : dtype, default None
dtype for the new Series: if None, infer from data
Returns
-------
_data : BlockManager for the new Series
index : index for the new Series
|
def recall_score(y_true, y_pred, average='micro', suffix=False):
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_true = len(true_entities)
score = nb_correct / nb_true if nb_true > 0 else 0
return score
|
Compute the recall.
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives. The recall is
intuitively the ability of the classifier to find all the positive samples.
The best value is 1 and the worst value is 0.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
score : float.
Example:
>>> from seqeval.metrics import recall_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> recall_score(y_true, y_pred)
0.50
|
def _get_record(self, record_type):
if not self.has_record_type(record_type):
raise errors.Unsupported()
if str(record_type) not in self._records:
raise errors.Unimplemented()
return self._records[str(record_type)]
|
Get the record string type value given the record_type.
|
def _is_string(thing):
if _util._py3k: return isinstance(thing, str)
else: return isinstance(thing, basestring)
|
Python character arrays are a mess.
If Python2, check if **thing** is an :obj:`unicode` or a :obj:`str`.
If Python3, check if **thing** is a :obj:`str`.
:param thing: The thing to check.
:returns: ``True`` if **thing** is a string according to whichever version
of Python we're running in.
|
def read_index(self):
if not isinstance(self.tree, dict):
self.tree = dict()
self.tree.clear()
for path, metadata in self.read_index_iter():
self.tree[path] = metadata
|
Reads the index and populates the directory tree
|
def depth_february_average_ground_temperature(self, value=None):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
'value {} need to be of type float '
'for field `depth_february_average_ground_temperature`'.format(value))
self._depth_february_average_ground_temperature = value
|
Corresponds to IDD Field `depth_february_average_ground_temperature`
Args:
value (float): value for IDD Field `depth_february_average_ground_temperature`
Unit: C
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value
|
def _repair_row(self):
check_for_title = True
for row_index in range(self.start[0], self.end[0]):
table_row = self.table[row_index]
row_start = table_row[self.start[1]]
if check_for_title and is_empty_cell(row_start):
self._stringify_row(row_index)
elif (isinstance(row_start, basestring) and
re.search(allregex.year_regex, row_start)):
self._check_stringify_year_row(row_index)
else:
check_for_title = False
|
Searches for missing titles that can be inferred from the surrounding data and automatically
repairs those titles.
|
def _log_msg(self, msg, ok):
if self._config['color']:
CGREEN, CRED, CEND = '\033[92m', '\033[91m', '\033[0m'
else:
CGREEN = CRED = CEND = ''
LOG_LEVELS = {False: logging.ERROR, True: logging.INFO}
L.log(LOG_LEVELS[ok],
'%35s %s' + CEND, msg, CGREEN + 'PASS' if ok else CRED + 'FAIL')
|
Helper to log message to the right level
|
def update_url(self, url=None):
if not url:
raise ValueError("Neither a url or regex was provided to update_url.")
post_url = "%s%s" % (self.BASE_URL, url)
r = self.session.post(post_url)
return int(r.status_code) < 500
|
Accepts a fully-qualified url.
Returns True if successful, False if not successful.
|
def get_gpu_memory_usage(ctx: List[mx.context.Context]) -> Dict[int, Tuple[int, int]]:
if isinstance(ctx, mx.context.Context):
ctx = [ctx]
ctx = [c for c in ctx if c.device_type == 'gpu']
if not ctx:
return {}
if shutil.which("nvidia-smi") is None:
logger.warning("Couldn't find nvidia-smi, therefore we assume no GPUs are available.")
return {}
device_ids = [c.device_id for c in ctx]
mp_context = mp_utils.get_context()
result_queue = mp_context.Queue()
nvidia_smi_process = mp_context.Process(target=query_nvidia_smi, args=(device_ids, result_queue,))
nvidia_smi_process.start()
nvidia_smi_process.join()
memory_data = result_queue.get()
log_gpu_memory_usage(memory_data)
return memory_data
|
Returns used and total memory for GPUs identified by the given context list.
:param ctx: List of MXNet context devices.
:return: Dictionary of device id mapping to a tuple of (memory used, memory total).
|
def save(self, filename):
filename = pathlib.Path(filename)
out = []
keys = sorted(list(self.keys()))
for key in keys:
out.append("[{}]".format(key))
section = self[key]
ikeys = list(section.keys())
ikeys.sort()
for ikey in ikeys:
var, val = keyval_typ2str(ikey, section[ikey])
out.append("{} = {}".format(var, val))
out.append("")
with filename.open("w") as f:
for i in range(len(out)):
out[i] = out[i]+"\n"
f.writelines(out)
|
Save the configuration to a file
|
def zcr(data):
data = np.mean(data, axis=1)
count = len(data)
countZ = np.sum(np.abs(np.diff(np.sign(data)))) / 2
return (np.float64(countZ) / np.float64(count - 1.0))
|
Computes zero crossing rate of segment
|
def adjust_attributes_on_object(self, collection, name, things, values, how):
url = self._build_url("%s/%s" % (collection, name))
response = self._get(url)
logger.debug("before modification: %s", response.content)
build_json = response.json()
how(build_json['metadata'], things, values)
response = self._put(url, data=json.dumps(build_json), use_json=True)
check_response(response)
return response
|
adjust labels or annotations on object
labels have to match RE: (([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])? and
have at most 63 chars
:param collection: str, object collection e.g. 'builds'
:param name: str, name of object
:param things: str, 'labels' or 'annotations'
:param values: dict, values to set
:param how: callable, how to adjust the values e.g.
self._replace_metadata_things
:return:
|
def get_pixel_thresholds_from_calibration_array(gdacs, calibration_gdacs, threshold_calibration_array, bounds_error=True):
if len(calibration_gdacs) != threshold_calibration_array.shape[2]:
raise ValueError('Length of the provided pixel GDACs does not match the third dimension of the calibration array')
interpolation = interp1d(x=calibration_gdacs, y=threshold_calibration_array, kind='slinear', bounds_error=bounds_error)
return interpolation(gdacs)
|
Calculates the threshold for all pixels in threshold_calibration_array at the given GDAC settings via linear interpolation. The GDAC settings used during calibration have to be given.
Parameters
----------
gdacs : array like
The GDAC settings where the threshold should be determined from the calibration
calibration_gdacs : array like
GDAC settings used during calibration, needed to translate the index of the calibration array to a value.
threshold_calibration_array : numpy.array, shape=(80,336,# of GDACs during calibration)
The calibration array
Returns
-------
numpy.array, shape=(80,336,# gdacs given)
The threshold values for each pixel at gdacs.
|
def store(self, addr, length=1, non_temporal=False):
if non_temporal:
raise ValueError("non_temporal stores are not yet supported")
if addr is None:
return
elif not isinstance(addr, Iterable):
self.first_level.store(addr, length=length)
else:
self.first_level.iterstore(addr, length=length)
|
Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no write-allocate will be issued, but cacheline will be zeroed
|
def singleton(cls):
import inspect
instances = {}
if cls.__init__ is not object.__init__:
argspec = inspect.getfullargspec(cls.__init__)
if len(argspec.args) != 1 or argspec.varargs or argspec.varkw:
raise TypeError("Singleton classes cannot accept arguments to the constructor.")
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance
|
Decorator function that turns a class into a singleton.
|
def _plan_on_valid_line(self, at_line, final_line_count):
if at_line == 1 or at_line == final_line_count:
return True
after_version = (
self._lines_seen["version"]
and self._lines_seen["version"][0] == 1
and at_line == 2
)
if after_version:
return True
return False
|
Check if a plan is on a valid line.
|
def all(self, customer_id, data={}, **kwargs):
url = "{}/{}/tokens".format(self.base_url, customer_id)
return self.get_url(url, data, **kwargs)
|
Get all tokens for given customer Id
Args:
customer_id : Customer Id for which tokens have to be fetched
Returns:
Token dicts for given cutomer Id
|
def fit(self, p, x, y):
self.regression_model.fit(p, y)
ml_pred = self.regression_model.predict(p)
print('Finished learning regression model')
self.krige.fit(x=x, y=y - ml_pred)
print('Finished kriging residuals')
|
fit the regression method and also Krige the residual
Parameters
----------
p: ndarray
(Ns, d) array of predictor variables (Ns samples, d dimensions)
for regression
x: ndarray
ndarray of (x, y) points. Needs to be a (Ns, 2) array
corresponding to the lon/lat, for example 2d regression kriging.
array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging
y: ndarray
array of targets (Ns, )
|
def proxy_model(self):
if self.category != Category.MODEL:
raise IllegalArgumentError("Part {} is not a model, therefore it cannot have a proxy model".format(self))
if 'proxy' in self._json_data and self._json_data.get('proxy'):
catalog_model_id = self._json_data['proxy'].get('id')
return self._client.model(pk=catalog_model_id)
else:
raise NotFoundError("Part {} is not a proxy".format(self.name))
|
Retrieve the proxy model of this proxied `Part` as a `Part`.
Allows you to retrieve the model of a proxy. But trying to get the catalog model of a part that
has no proxy, will raise an :exc:`NotFoundError`. Only models can have a proxy.
:return: :class:`Part` with category `MODEL` and from which the current part is proxied
:raises NotFoundError: When no proxy model is found
Example
-------
>>> proxy_part = project.model('Proxy based on catalog model')
>>> catalog_model_of_proxy_part = proxy_part.proxy_model()
>>> proxied_material_of_the_bolt_model = project.model('Bolt Material')
>>> proxy_basis_for_the_material_model = proxied_material_of_the_bolt_model.proxy_model()
|
def kalman_filter(points, noise):
kalman = ikalman.filter(noise)
for point in points:
kalman.update_velocity2d(point.lat, point.lon, point.dt)
(lat, lon) = kalman.get_lat_long()
point.lat = lat
point.lon = lon
return points
|
Smooths points with kalman filter
See https://github.com/open-city/ikalman
Args:
points (:obj:`list` of :obj:`Point`): points to smooth
noise (float): expected noise
|
def sample_stats_prior_to_xarray(self):
data = self.sample_stats_prior
if not isinstance(data, dict):
raise TypeError("DictConverter.sample_stats_prior is not a dictionary")
return dict_to_dataset(data, library=None, coords=self.coords, dims=self.dims)
|
Convert sample_stats_prior samples to xarray.
|
def expand_short_options(self, argv):
new_argv = []
for arg in argv:
result = self.parse_multi_short_option(arg)
new_argv.extend(result)
return new_argv
|
Convert grouped short options like `-abc` to `-a, -b, -c`.
This is necessary because we set ``allow_abbrev=False`` on the
``ArgumentParser`` in :prop:`self.arg_parser`. The argparse docs
say ``allow_abbrev`` applies only to long options, but it also
affects whether short options grouped behind a single dash will
be parsed into multiple short options.
|
def add_commands(self):
self.parser.add_argument(
'-d',
action="count",
**self.config.default.debug.get_arg_parse_arguments())
|
You can override this method in order to add your command line
arguments to the argparse parser. The configuration file was
reloaded at this time.
|
def set_state_options(self, left_add_options=None, left_remove_options=None, right_add_options=None, right_remove_options=None):
s_right = self.project.factory.full_init_state(
add_options=right_add_options, remove_options=right_remove_options,
args=[],
)
s_left = self.project.factory.full_init_state(
add_options=left_add_options, remove_options=left_remove_options,
args=[],
)
return self.set_states(s_left, s_right)
|
Checks that the specified state options result in the same states over the next `depth` states.
|
def key(self, frame):
"Return the sort key for the given frame."
def keytuple(primary):
if frame.frameno is None:
return (primary, 1)
return (primary, 0, frame.frameno)
if type(frame) in self.frame_keys:
return keytuple(self.frame_keys[type(frame)])
if frame._in_version(2) and type(frame).__bases__[0] in self.frame_keys:
return keytuple(self.frame_keys[type(frame).__bases__[0]])
for (pattern, key) in self.re_keys:
if re.match(pattern, frame.frameid):
return keytuple(key)
return keytuple(self.unknown_key)
|
Return the sort key for the given frame.
|
def _validate_flushed(self) -> None:
journal_diff = self._journal_storage.diff()
if len(journal_diff) > 0:
raise ValidationError(
"StorageDB had a dirty journal when it needed to be clean: %r" % journal_diff
)
|
Will raise an exception if there are some changes made since the last persist.
|
def get_covariance_table(self, chain=0, parameters=None, caption="Parameter Covariance",
label="tab:parameter_covariance"):
parameters, cov = self.get_covariance(chain=chain, parameters=parameters)
return self._get_2d_latex_table(parameters, cov, caption, label)
|
Gets a LaTeX table of parameter covariance.
Parameters
----------
chain : int|str, optional
The chain index or name. Defaults to first chain.
parameters : list[str], optional
The list of parameters to compute correlations. Defaults to all parameters
for the given chain.
caption : str, optional
The LaTeX table caption.
label : str, optional
The LaTeX table label.
Returns
-------
str
The LaTeX table ready to go!
|
def combine(self, other, name=None):
return PhaseGroup(
setup=self.setup + other.setup,
main=self.main + other.main,
teardown=self.teardown + other.teardown,
name=name)
|
Combine with another PhaseGroup and return the result.
|
def reboot(self):
token = self.get_token()
self.bbox_auth.set_access(BboxConstant.AUTHENTICATION_LEVEL_PRIVATE, BboxConstant.AUTHENTICATION_LEVEL_PRIVATE)
url_suffix = "reboot?btoken={}".format(token)
self.bbox_url.set_api_name(BboxConstant.API_DEVICE, url_suffix)
api = BboxApiCall(self.bbox_url, BboxConstant.HTTP_METHOD_POST, None,
self.bbox_auth)
api.execute_api_request()
|
Reboot the device
Useful when trying to get xDSL sync
|
def get_temp_export_dir(timestamped_export_dir):
(dirname, basename) = os.path.split(timestamped_export_dir)
temp_export_dir = os.path.join(
tf.compat.as_bytes(dirname),
tf.compat.as_bytes("temp-{}".format(basename)))
return temp_export_dir
|
Builds a directory name based on the argument but starting with 'temp-'.
This relies on the fact that TensorFlow Serving ignores subdirectories of
the base directory that can't be parsed as integers.
Args:
timestamped_export_dir: the name of the eventual export directory, e.g.
/foo/bar/<timestamp>
Returns:
A sister directory prefixed with 'temp-', e.g. /foo/bar/temp-<timestamp>.
|
def setup(app):
app.add_config_value('sphinxmark_enable', False, 'html')
app.add_config_value('sphinxmark_div', 'default', 'html')
app.add_config_value('sphinxmark_border', None, 'html')
app.add_config_value('sphinxmark_repeat', True, 'html')
app.add_config_value('sphinxmark_fixed', False, 'html')
app.add_config_value('sphinxmark_image', 'default', 'html')
app.add_config_value('sphinxmark_text', 'default', 'html')
app.add_config_value('sphinxmark_text_color', (255, 0, 0), 'html')
app.add_config_value('sphinxmark_text_size', 100, 'html')
app.add_config_value('sphinxmark_text_width', 1000, 'html')
app.add_config_value('sphinxmark_text_opacity', 20, 'html')
app.add_config_value('sphinxmark_text_spacing', 400, 'html')
app.add_config_value('sphinxmark_text_rotation', 0, 'html')
app.connect('env-updated', watermark)
return {
'version': '0.1.18',
'parallel_read_safe': True,
'parallel_write_safe': True,
}
|
Configure setup for Sphinx extension.
:param app: Sphinx application context.
|
def _table_union(left, right, distinct=False):
op = ops.Union(left, right, distinct=distinct)
return op.to_expr()
|
Form the table set union of two table expressions having identical
schemas.
Parameters
----------
right : TableExpr
distinct : boolean, default False
Only union distinct rows not occurring in the calling table (this
can be very expensive, be careful)
Returns
-------
union : TableExpr
|
def publish_message(self, message, expire=None):
if expire is None:
expire = self._expire
if not isinstance(message, RedisMessage):
raise ValueError('message object is not of type RedisMessage')
for channel in self._publishers:
self._connection.publish(channel, message)
if expire > 0:
self._connection.setex(channel, expire, message)
|
Publish a ``message`` on the subscribed channel on the Redis datastore.
``expire`` sets the time in seconds, on how long the message shall additionally of being
published, also be persisted in the Redis datastore. If unset, it defaults to the
configuration settings ``WS4REDIS_EXPIRE``.
|
def fetch(opts):
resources = _load(opts.resources, opts.output_dir)
if opts.all:
opts.resource_names = ALL
reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name))
if opts.verbose:
backend.VERBOSE = True
_fetch(resources, opts.resource_names, opts.mirror_url, opts.force, reporthook)
return verify(opts)
|
Create a local mirror of one or more resources.
|
def can_claim_fifty_moves(self) -> bool:
if self.halfmove_clock >= 100:
if any(self.generate_legal_moves()):
return True
return False
|
Draw by the fifty-move rule can be claimed once the clock of halfmoves
since the last capture or pawn move becomes equal or greater to 100
and the side to move still has a legal move they can make.
|
def String(length=None, **kwargs):
return Property(
length=length,
types=stringy_types,
convert=to_string,
**kwargs
)
|
A string valued property with max. `length`.
|
def key(state, host, key=None, keyserver=None, keyid=None):
if key:
if urlparse(key).scheme:
yield 'wget -O- {0} | apt-key add -'.format(key)
else:
yield 'apt-key add {0}'.format(key)
if keyserver and keyid:
yield 'apt-key adv --keyserver {0} --recv-keys {1}'.format(keyserver, keyid)
|
Add apt gpg keys with ``apt-key``.
+ key: filename or URL
+ keyserver: URL of keyserver to fetch key from
+ keyid: key identifier when using keyserver
Note:
Always returns an add command, not state checking.
keyserver/id:
These must be provided together.
|
def _call_variants(example_dir, region_bed, data, out_file):
tf_out_file = "%s-tfrecord.gz" % utils.splitext_plus(out_file)[0]
if not utils.file_exists(tf_out_file):
with file_transaction(data, tf_out_file) as tx_out_file:
model = "wes" if strelka2.coverage_interval_from_bed(region_bed) == "targeted" else "wgs"
cmd = ["dv_call_variants.py", "--cores", dd.get_num_cores(data),
"--outfile", tx_out_file, "--examples", example_dir,
"--sample", dd.get_sample_name(data), "--model", model]
do.run(cmd, "DeepVariant call_variants %s" % dd.get_sample_name(data))
return tf_out_file
|
Call variants from prepared pileup examples, creating tensorflow record file.
|
def peak_generation(self, mode):
if mode == 'MV':
return sum([_.capacity for _ in self.grid.generators()])
elif mode == 'MVLV':
cum_mv_peak_generation = sum([_.capacity for _ in self.grid.generators()])
cum_lv_peak_generation = 0
for load_area in self.grid.grid_district.lv_load_areas():
cum_lv_peak_generation += load_area.peak_generation
return cum_mv_peak_generation + cum_lv_peak_generation
else:
raise ValueError('parameter \'mode\' is invalid!')
|
Calculates cumulative peak generation of generators connected to underlying grids
This is done instantaneously using bottom-up approach.
Parameters
----------
mode: str
determines which generators are included::
'MV': Only generation capacities of MV level are considered.
'MVLV': Generation capacities of MV and LV are considered
(= cumulative generation capacities in entire MVGD).
Returns
-------
float
Cumulative peak generation
|
def _untrack_tendril(self, tendril):
try:
del self.tendrils[tendril._tendril_key]
except KeyError:
pass
try:
del self._tendrils[tendril.proto][tendril._tendril_key]
except KeyError:
pass
|
Removes the tendril from the set of tracked tendrils.
|
def _get_predicton_csv_lines(data, headers, images):
if images:
data = copy.deepcopy(data)
for img_col in images:
for d, im in zip(data, images[img_col]):
if im == '':
continue
im = im.copy()
im.thumbnail((299, 299), Image.ANTIALIAS)
buf = BytesIO()
im.save(buf, "JPEG")
content = base64.urlsafe_b64encode(buf.getvalue()).decode('ascii')
d[img_col] = content
csv_lines = []
for d in data:
buf = six.StringIO()
writer = csv.DictWriter(buf, fieldnames=headers, lineterminator='')
writer.writerow(d)
csv_lines.append(buf.getvalue())
return csv_lines
|
Create CSV lines from list-of-dict data.
|
def decide(self, package):
if self._backtracking:
self._attempted_solutions += 1
self._backtracking = False
self._decisions[package.name] = package
self._assign(
Assignment.decision(package, self.decision_level, len(self._assignments))
)
|
Adds an assignment of package as a decision
and increments the decision level.
|
def _set_schedules(self):
self.schedules = ['ReturnHeader990x', ]
self.otherforms = []
for sked in self.raw_irs_dict['Return']['ReturnData'].keys():
if not sked.startswith("@"):
if sked in KNOWN_SCHEDULES:
self.schedules.append(sked)
else:
self.otherforms.append(sked)
|
Attach the known and unknown schedules
|
def chi_squareds(self, p=None):
if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None
if p is None: p = self.results[0]
rs = self.studentized_residuals(p)
if rs == None: return None
cs = []
for r in rs: cs.append(sum(r**2))
return cs
|
Returns a list of chi squared for each data set. Also uses ydata_massaged.
p=None means use the fit results
|
def AddXrefFrom(self, ref_kind, classobj, methodobj, offset):
self.xreffrom[classobj].add((ref_kind, methodobj, offset))
|
Creates a crossreference from this class.
XrefFrom means, that the current class is called by another class.
:param REF_TYPE ref_kind: type of call
:param classobj: :class:`ClassAnalysis` object to link
:param methodobj:
:param offset: Offset in the methods bytecode, where the call happens
:return:
|
def streaming_command(self, command, raw=False, timeout_ms=None):
if raw:
command = self._to_raw_command(command)
return self.adb_connection.streaming_command('shell', command, timeout_ms)
|
Run the given command and yield the output as we receive it.
|
def g_step(self, gen_frames, fake_logits_stop):
hparam_to_gen_loss = {
"least_squares": gan_losses.least_squares_generator_loss,
"cross_entropy": gan_losses.modified_generator_loss,
"wasserstein": gan_losses.wasserstein_generator_loss
}
fake_logits = self.discriminator(gen_frames)
mean_fake_logits = tf.reduce_mean(fake_logits)
tf.summary.scalar("mean_fake_logits", mean_fake_logits)
generator_loss_func = hparam_to_gen_loss[self.hparams.gan_loss]
gan_g_loss_pos_d = generator_loss_func(
discriminator_gen_outputs=fake_logits, add_summaries=True)
gan_g_loss_neg_d = -generator_loss_func(
discriminator_gen_outputs=fake_logits_stop, add_summaries=True)
return gan_g_loss_pos_d, gan_g_loss_neg_d
|
Performs the generator step in computing the GAN loss.
Args:
gen_frames: Generated frames
fake_logits_stop: Logits corresponding to the generated frames as per
the discriminator. Assumed to have a stop-gradient term.
Returns:
gan_g_loss_pos_d: Loss.
gan_g_loss_neg_d: -gan_g_loss_pos_d but with a stop gradient on generator.
|
def instagram_config(self, id, secret, scope=None, **_):
scope = scope if scope else 'basic'
token_params = dict(scope=scope)
config = dict(
access_token_url='/oauth/access_token/',
authorize_url='/oauth/authorize/',
base_url='https://api.instagram.com/',
consumer_key=id,
consumer_secret=secret,
request_token_params=token_params
)
return config
|
Get config dictionary for instagram oauth
|
def run_algorithm(start,
end,
initialize,
capital_base,
handle_data=None,
before_trading_start=None,
analyze=None,
data_frequency='daily',
bundle='quantopian-quandl',
bundle_timestamp=None,
trading_calendar=None,
metrics_set='default',
benchmark_returns=None,
default_extension=True,
extensions=(),
strict_extensions=True,
environ=os.environ,
blotter='default'):
load_extensions(default_extension, extensions, strict_extensions, environ)
return _run(
handle_data=handle_data,
initialize=initialize,
before_trading_start=before_trading_start,
analyze=analyze,
algofile=None,
algotext=None,
defines=(),
data_frequency=data_frequency,
capital_base=capital_base,
bundle=bundle,
bundle_timestamp=bundle_timestamp,
start=start,
end=end,
output=os.devnull,
trading_calendar=trading_calendar,
print_algo=False,
metrics_set=metrics_set,
local_namespace=False,
environ=environ,
blotter=blotter,
benchmark_returns=benchmark_returns,
)
|
Run a trading algorithm.
Parameters
----------
start : datetime
The start date of the backtest.
end : datetime
The end date of the backtest..
initialize : callable[context -> None]
The initialize function to use for the algorithm. This is called once
at the very begining of the backtest and should be used to set up
any state needed by the algorithm.
capital_base : float
The starting capital for the backtest.
handle_data : callable[(context, BarData) -> None], optional
The handle_data function to use for the algorithm. This is called
every minute when ``data_frequency == 'minute'`` or every day
when ``data_frequency == 'daily'``.
before_trading_start : callable[(context, BarData) -> None], optional
The before_trading_start function for the algorithm. This is called
once before each trading day (after initialize on the first day).
analyze : callable[(context, pd.DataFrame) -> None], optional
The analyze function to use for the algorithm. This function is called
once at the end of the backtest and is passed the context and the
performance data.
data_frequency : {'daily', 'minute'}, optional
The data frequency to run the algorithm at.
bundle : str, optional
The name of the data bundle to use to load the data to run the backtest
with. This defaults to 'quantopian-quandl'.
bundle_timestamp : datetime, optional
The datetime to lookup the bundle data for. This defaults to the
current time.
trading_calendar : TradingCalendar, optional
The trading calendar to use for your backtest.
metrics_set : iterable[Metric] or str, optional
The set of metrics to compute in the simulation. If a string is passed,
resolve the set with :func:`zipline.finance.metrics.load`.
default_extension : bool, optional
Should the default zipline extension be loaded. This is found at
``$ZIPLINE_ROOT/extension.py``
extensions : iterable[str], optional
The names of any other extensions to load. Each element may either be
a dotted module path like ``a.b.c`` or a path to a python file ending
in ``.py`` like ``a/b/c.py``.
strict_extensions : bool, optional
Should the run fail if any extensions fail to load. If this is false,
a warning will be raised instead.
environ : mapping[str -> str], optional
The os environment to use. Many extensions use this to get parameters.
This defaults to ``os.environ``.
blotter : str or zipline.finance.blotter.Blotter, optional
Blotter to use with this algorithm. If passed as a string, we look for
a blotter construction function registered with
``zipline.extensions.register`` and call it with no parameters.
Default is a :class:`zipline.finance.blotter.SimulationBlotter` that
never cancels orders.
Returns
-------
perf : pd.DataFrame
The daily performance of the algorithm.
See Also
--------
zipline.data.bundles.bundles : The available data bundles.
|
def change_type(self, cls):
target_type = cls._type
target = self._embedded.createInstance(target_type)
self._embedded.setDiagram(target)
return cls(target)
|
Change type of diagram in this chart.
Accepts one of classes which extend Diagram.
|
def join_channel(self, channel, key=None, tags=None):
params = [channel]
if key:
params.append(key)
self.send('JOIN', params=params, tags=tags)
|
Join the given channel.
|
def send(self, load, tries=None, timeout=None, raw=False):
if 'cmd' not in load:
log.error('Malformed request, no cmd: %s', load)
return {}
cmd = load['cmd'].lstrip('_')
if cmd in self.cmd_stub:
return self.cmd_stub[cmd]
if not hasattr(self.fs, cmd):
log.error('Malformed request, invalid cmd: %s', load)
return {}
return getattr(self.fs, cmd)(load)
|
Emulate the channel send method, the tries and timeout are not used
|
def construct_func_expr(n):
op = n[0]
if op.startswith('_') and op.endswith('_'):
op = op.strip('_')
if op == 'var':
return Var(str(n[1]))
elif op == 'literal':
if isinstance(n[1], basestring):
raise "not implemented"
return Constant(n[1])
elif op == 'cast':
raise "not implemented"
elif op in '+-/*':
return ArithErrFunc(op, *map(construct_func_expr,n[1:]))
else:
klass = __agg2f__.get(op, None)
if klass:
return klass(map(construct_func_expr, n[1:]))
raise "no klass"
|
construct the function expression
|
def wait(self, timeout=None):
us = -1 if timeout is None else int(timeout * 1000000)
return super(Reader, self).wait(us)
|
Wait for a change in the journal.
`timeout` is the maximum time in seconds to wait, or None which
means to wait forever.
Returns one of NOP (no change), APPEND (new entries have been added to
the end of the journal), or INVALIDATE (journal files have been added or
removed).
|
def _get_symmetry(self):
d = spglib.get_symmetry(self._cell, symprec=self._symprec,
angle_tolerance=self._angle_tol)
trans = []
for t in d["translations"]:
trans.append([float(Fraction.from_float(c).limit_denominator(1000))
for c in t])
trans = np.array(trans)
trans[np.abs(trans) == 1] = 0
return d["rotations"], trans
|
Get the symmetry operations associated with the structure.
Returns:
Symmetry operations as a tuple of two equal length sequences.
(rotations, translations). "rotations" is the numpy integer array
of the rotation matrices for scaled positions
"translations" gives the numpy float64 array of the translation
vectors in scaled positions.
|
def blit_2x(
self,
console: tcod.console.Console,
dest_x: int,
dest_y: int,
img_x: int = 0,
img_y: int = 0,
img_width: int = -1,
img_height: int = -1,
) -> None:
lib.TCOD_image_blit_2x(
self.image_c,
_console(console),
dest_x,
dest_y,
img_x,
img_y,
img_width,
img_height,
)
|
Blit onto a Console with double resolution.
Args:
console (Console): Blit destination Console.
dest_x (int): Console tile X position starting from the left at 0.
dest_y (int): Console tile Y position starting from the top at 0.
img_x (int): Left corner pixel of the Image to blit
img_y (int): Top corner pixel of the Image to blit
img_width (int): Width of the Image to blit.
Use -1 for the full Image width.
img_height (int): Height of the Image to blit.
Use -1 for the full Image height.
|
def lookup(self, key):
values = self.filter(lambda kv: kv[0] == key).values()
if self.partitioner is not None:
return self.ctx.runJob(values, lambda x: x, [self.partitioner(key)])
return values.collect()
|
Return the list of values in the RDD for key `key`. This operation
is done efficiently if the RDD has a known partitioner by only
searching the partition that the key maps to.
>>> l = range(1000)
>>> rdd = sc.parallelize(zip(l, l), 10)
>>> rdd.lookup(42) # slow
[42]
>>> sorted = rdd.sortByKey()
>>> sorted.lookup(42) # fast
[42]
>>> sorted.lookup(1024)
[]
>>> rdd2 = sc.parallelize([(('a', 'b'), 'c')]).groupByKey()
>>> list(rdd2.lookup(('a', 'b'))[0])
['c']
|
def anchor(self):
anchor = self._subtotal_dict["anchor"]
try:
anchor = int(anchor)
if anchor not in self.valid_elements.element_ids:
return "bottom"
return anchor
except (TypeError, ValueError):
return anchor.lower()
|
int or str indicating element under which to insert this subtotal.
An int anchor is the id of the dimension element (category or
subvariable) under which to place this subtotal. The return value can
also be one of 'top' or 'bottom'.
The return value defaults to 'bottom' for an anchor referring to an
element that is no longer present in the dimension or an element that
represents missing data.
|
def as_coeff_unit(self):
coeff, mul = self.expr.as_coeff_Mul()
coeff = float(coeff)
ret = Unit(
mul,
self.base_value / coeff,
self.base_offset,
self.dimensions,
self.registry,
)
return coeff, ret
|
Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient, returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit.
Example
-------
>>> import unyt as u
>>> unit = (u.m**2/u.cm).simplify()
>>> unit
100*m
>>> unit.as_coeff_unit()
(100.0, m)
|
def push(self, filename, data):
self._queue.put(Chunk(filename, data))
|
Push a chunk of a file to the streaming endpoint.
Args:
filename: Name of file that this is a chunk of.
chunk_id: TODO: change to 'offset'
chunk: File data.
|
def set_terminal_width(self, command="", delay_factor=1):
if not command:
return ""
delay_factor = self.select_delay_factor(delay_factor)
command = self.normalize_cmd(command)
self.write_channel(command)
output = self.read_until_prompt()
if self.ansi_escape_codes:
output = self.strip_ansi_escape_codes(output)
return output
|
CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:param command: Command string to send to the device
:type command: str
:param delay_factor: See __init__: global_delay_factor
:type delay_factor: int
|
def generate_string(self, initial_logits, initial_state, sequence_length):
current_logits = initial_logits
current_state = initial_state
generated_letters = []
for _ in range(sequence_length):
char_index = tf.squeeze(tf.multinomial(current_logits, 1))
char_one_hot = tf.one_hot(char_index, self._output_size, 1.0, 0.0)
generated_letters.append(char_one_hot)
gen_out_seq, current_state = self._core(
tf.nn.relu(self._embed_module(char_one_hot)),
current_state)
current_logits = self._output_module(gen_out_seq)
generated_string = tf.stack(generated_letters)
return generated_string
|
Builds sub-graph to generate a string, sampled from the model.
Args:
initial_logits: Starting logits to sample from.
initial_state: Starting state for the RNN core.
sequence_length: Number of characters to sample.
Returns:
A Tensor of characters, with dimensions `[sequence_length, batch_size,
output_size]`.
|
def threeprime_plot(self):
data = dict()
dict_to_add = dict()
for key in self.threepGtoAfreq_data:
pos = list(range(1,len(self.threepGtoAfreq_data.get(key))))
tmp = [i * 100.0 for i in self.threepGtoAfreq_data.get(key)]
tuples = list(zip(pos,tmp))
data = dict((x, y) for x, y in tuples)
dict_to_add[key] = data
config = {
'id': 'threeprime_misinc_plot',
'title': 'DamageProfiler: 3P G>A misincorporation plot',
'ylab': '% G to A substituted',
'xlab': 'Nucleotide position from 3\'',
'tt_label': '{point.y:.2f} % G>A misincorporations at nucleotide position {point.x}',
'ymin': 0,
'xmin': 1
}
return linegraph.plot(dict_to_add,config)
|
Generate a 3' G>A linegraph plot
|
def set_constants(self, *constants, verbose=True):
new = []
current = {c.expression: c for c in self._constants}
for expression in constants:
constant = current.get(expression, Constant(self, expression))
new.append(constant)
self._constants = new
for c in self._constants:
if c.units is None:
c.convert(c.variables[0].units)
self.flush()
self._on_constants_updated()
|
Set the constants associated with the data.
Parameters
----------
constants : str
Expressions for the new set of constants.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
transform
Similar method except for axes.
create_constant
Add an individual constant.
remove_constant
Remove an individual constant.
|
def _execute(self, worker):
self._assert_status_is(TaskStatus.RUNNING)
operation = worker.look_up(self.operation)
operation.invoke(self, [], worker=worker)
|
This method is ASSIGNED during the evaluation to control how to resume it once it has been paused
|
def _load_maps_by_type(map_type):
seq_maps = COLOR_MAPS[map_type]
loaded_maps = {}
for map_name in seq_maps:
loaded_maps[map_name] = {}
for num in seq_maps[map_name]:
inum = int(num)
colors = seq_maps[map_name][num]['Colors']
bmap = BrewerMap(map_name, map_type, colors)
loaded_maps[map_name][inum] = bmap
max_num = int(max(seq_maps[map_name].keys(), key=int))
loaded_maps[map_name]['max'] = loaded_maps[map_name][max_num]
return loaded_maps
|
Load all maps of a given type into a dictionary.
Color maps are loaded as BrewerMap objects. Dictionary is
keyed by map name and then integer numbers of defined
colors. There is an additional 'max' key that points to the
color map with the largest number of defined colors.
Parameters
----------
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Returns
-------
maps : dict of BrewerMap
|
def apply_args(self, **kwargs):
def apply_format(node):
if isinstance(node, PathParam):
return PathParam(node.name.format(**kwargs), node.type, node.type_args)
else:
return node
return UrlPath(*(apply_format(n) for n in self._nodes))
|
Apply formatting to each path node.
This is used to apply a name to nodes (used to apply key names) eg:
>>> a = UrlPath("foo", PathParam('{key_field}'), "bar")
>>> b = a.apply_args(id="item_id")
>>> b.format()
'foo/{item_id}/bar'
|
def update_refobj(self, old, new, reftrack):
if old:
del self._parentsearchdict[old]
if new:
self._parentsearchdict[new] = reftrack
|
Update the parent search dict so that the reftrack can be found
with the new refobj and delete the entry for the old refobj.
Old or new can also be None.
:param old: the old refobj of reftrack
:param new: the new refobj of reftrack
:param reftrack: The reftrack, which refobj was updated
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
|
def list_(name, add, match, stamp=False, prune=0):
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
if not isinstance(add, list):
add = add.split(',')
if name not in __reg__:
__reg__[name] = {}
__reg__[name]['val'] = []
for event in __events__:
try:
event_data = event['data']['data']
except KeyError:
event_data = event['data']
if salt.utils.stringutils.expr_match(event['tag'], match):
item = {}
for key in add:
if key in event_data:
item[key] = event_data[key]
if stamp is True:
item['time'] = event['data']['_stamp']
__reg__[name]['val'].append(item)
if prune > 0:
__reg__[name]['val'] = __reg__[name]['val'][:prune]
return ret
|
Add the specified values to the named list
If ``stamp`` is True, then the timestamp from the event will also be added
if ``prune`` is set to an integer higher than ``0``, then only the last
``prune`` values will be kept in the list.
USAGE:
.. code-block:: yaml
foo:
reg.list:
- add: bar
- match: my/custom/event
- stamp: True
|
def replacePassword(self, currentPassword, newPassword):
if unicode(currentPassword) != self.password:
return fail(BadCredentials())
return self.setPassword(newPassword)
|
Set this account's password if the current password matches.
@param currentPassword: The password to match against the current one.
@param newPassword: The new password.
@return: A deferred firing when the password has been changed.
@raise BadCredentials: If the current password did not match.
|
def splits(cls, exts, fields, root='.data',
train='train', validation='val', test='test2016', **kwargs):
if 'path' not in kwargs:
expected_folder = os.path.join(root, cls.name)
path = expected_folder if os.path.exists(expected_folder) else None
else:
path = kwargs['path']
del kwargs['path']
return super(Multi30k, cls).splits(
exts, fields, path, root, train, validation, test, **kwargs)
|
Create dataset objects for splits of the Multi30k dataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tuple containing the fields that will be used for data
in each language.
root: Root dataset storage directory. Default is '.data'.
train: The prefix of the train data. Default: 'train'.
validation: The prefix of the validation data. Default: 'val'.
test: The prefix of the test data. Default: 'test'.
Remaining keyword arguments: Passed to the splits method of
Dataset.
|
def cmd_signing_key(self, args):
if len(args) == 0:
print("usage: signing setup passphrase")
return
if not self.master.mavlink20():
print("You must be using MAVLink2 for signing")
return
passphrase = args[0]
key = self.passphrase_to_key(passphrase)
self.master.setup_signing(key, sign_outgoing=True, allow_unsigned_callback=self.allow_unsigned)
print("Setup signing key")
|
set signing key on connection
|
def extract_header_comment_key_value_tuples_from_file(file_descriptor):
file_data = file_descriptor.read()
findall_result = re.findall(HEADER_COMMENT_KEY_VALUE_TUPLES_REGEX, file_data, re.MULTILINE | re.DOTALL)
returned_list = []
for header_comment, _ignored, raw_comments, key, value in findall_result:
comments = re.findall("/\* (.*?) \*/", raw_comments)
if len(comments) == 0:
comments = [u""]
returned_list.append((header_comment, comments, key, value))
return returned_list
|
Extracts tuples representing comments and localization entries from strings file.
Args:
file_descriptor (file): The file to read the tuples from
Returns:
list : List of tuples representing the headers and localization entries.
|
def export_batch(self):
batch = self.batch_cls(
model=self.model, history_model=self.history_model, using=self.using
)
if batch.items:
try:
json_file = self.json_file_cls(batch=batch, path=self.path)
json_file.write()
except JSONDumpFileError as e:
raise TransactionExporterError(e)
batch.close()
return batch
return None
|
Returns a batch instance after exporting a batch of txs.
|
def nhapDaiHan(self, cucSo, gioiTinh):
for cung in self.thapNhiCung:
khoangCach = khoangCachCung(cung.cungSo, self.cungMenh, gioiTinh)
cung.daiHan(cucSo + khoangCach * 10)
return self
|
Nhap dai han
Args:
cucSo (TYPE): Description
gioiTinh (TYPE): Description
Returns:
TYPE: Description
|
def read(self) -> None:
try:
with netcdf4.Dataset(self.filepath, "r") as ncfile:
timegrid = query_timegrid(ncfile)
for variable in self.variables.values():
variable.read(ncfile, timegrid)
except BaseException:
objecttools.augment_excmessage(
f'While trying to read data from NetCDF file `{self.filepath}`')
|
Open an existing NetCDF file temporarily and call method
|NetCDFVariableDeep.read| of all handled |NetCDFVariableBase|
objects.
|
def _create_socket(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(s)
s.connect((self.host, self.__port))
s.settimeout(self.timeout)
return s
|
Creates ssl socket, connects to stream api and
sets timeout.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.