code stringlengths 70 11.9k | docstring stringlengths 4 7.08k | text stringlengths 128 15k |
|---|---|---|
def _to_numeric(val):
if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):
return val
return float(val) | Helper function for conversion of various data types into numeric representation. | ### Input:
Helper function for conversion of various data types into numeric representation.
### Response:
def _to_numeric(val):
if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):
return val
return float(val) |
def GC_partial(portion):
sequence_count = collections.Counter(portion)
gc = ((sum([sequence_count[i] for i in ]) +
sum([sequence_count[i] for i in ]) / 3.0 +
2 * sum([sequence_count[i] for i in ]) / 3.0 +
sum([sequence_count[i] for i in ]) / 2.0) / len(portion))
return 0 or 100 * gc | Manually compute GC content percentage in a DNA string, taking
ambiguous values into account (according to standard IUPAC notation). | ### Input:
Manually compute GC content percentage in a DNA string, taking
ambiguous values into account (according to standard IUPAC notation).
### Response:
def GC_partial(portion):
sequence_count = collections.Counter(portion)
gc = ((sum([sequence_count[i] for i in ]) +
sum([sequence_count[i] for i in ]) / 3.0 +
2 * sum([sequence_count[i] for i in ]) / 3.0 +
sum([sequence_count[i] for i in ]) / 2.0) / len(portion))
return 0 or 100 * gc |
def _get_taxon(taxon):
if not taxon:
return None
sep = taxon.find()
taxid = taxon[sep + 1:]
assert taxid.isdigit(), "UNEXPECTED TAXON({T})".format(T=taxid)
return int(taxid) | Return Interacting taxon ID | optional | 0 or 1 | gaf column 13. | ### Input:
Return Interacting taxon ID | optional | 0 or 1 | gaf column 13.
### Response:
def _get_taxon(taxon):
if not taxon:
return None
sep = taxon.find()
taxid = taxon[sep + 1:]
assert taxid.isdigit(), "UNEXPECTED TAXON({T})".format(T=taxid)
return int(taxid) |
def hurst_compare_nvals(data, nvals=None):
import matplotlib.pyplot as plt
data = np.asarray(data)
n_all = np.arange(2,len(data)+1)
dd_all = nolds.hurst_rs(data, nvals=n_all, debug_data=True, fit="poly")
dd_def = nolds.hurst_rs(data, debug_data=True, fit="poly")
n_def = np.round(np.exp(dd_def[1][0])).astype("int32")
n_div = n_all[np.where(len(data) % n_all[:-1] == 0)]
dd_div = nolds.hurst_rs(data, nvals=n_div, debug_data=True, fit="poly")
def corr(nvals):
return [np.log(nolds.expected_rs(n)) for n in nvals]
l_all = plt.plot(dd_all[1][0], dd_all[1][1] - corr(n_all), "o")
l_def = plt.plot(dd_def[1][0], dd_def[1][1] - corr(n_def), "o")
l_div = plt.plot(dd_div[1][0], dd_div[1][1] - corr(n_div), "o")
l_cst = []
t_cst = []
if nvals is not None:
dd_cst = nolds.hurst_rs(data, nvals=nvals, debug_data=True, fit="poly")
l_cst = plt.plot(dd_cst[1][0], dd_cst[1][1] - corr(nvals), "o")
l_cst = l_cst
t_cst = ["custom"]
plt.xlabel("log(n)")
plt.ylabel("log((R/S)_n - E[(R/S)_n])")
plt.legend(l_all + l_def + l_div + l_cst, ["all", "default", "divisors"] + t_cst)
labeled_data = zip([dd_all[0], dd_def[0], dd_div[0]], ["all", "def", "div"])
for data, label in labeled_data:
print("%s: %.3f" % (label, data))
if nvals is not None:
print("custom: %.3f" % dd_cst[0])
plt.show() | Creates a plot that compares the results of different choices for nvals
for the function hurst_rs.
Args:
data (array-like of float):
the input data from which the hurst exponent should be estimated
Kwargs:
nvals (array of int):
a manually selected value for the nvals parameter that should be plotted
in comparison to the default choices | ### Input:
Creates a plot that compares the results of different choices for nvals
for the function hurst_rs.
Args:
data (array-like of float):
the input data from which the hurst exponent should be estimated
Kwargs:
nvals (array of int):
a manually selected value for the nvals parameter that should be plotted
in comparison to the default choices
### Response:
def hurst_compare_nvals(data, nvals=None):
import matplotlib.pyplot as plt
data = np.asarray(data)
n_all = np.arange(2,len(data)+1)
dd_all = nolds.hurst_rs(data, nvals=n_all, debug_data=True, fit="poly")
dd_def = nolds.hurst_rs(data, debug_data=True, fit="poly")
n_def = np.round(np.exp(dd_def[1][0])).astype("int32")
n_div = n_all[np.where(len(data) % n_all[:-1] == 0)]
dd_div = nolds.hurst_rs(data, nvals=n_div, debug_data=True, fit="poly")
def corr(nvals):
return [np.log(nolds.expected_rs(n)) for n in nvals]
l_all = plt.plot(dd_all[1][0], dd_all[1][1] - corr(n_all), "o")
l_def = plt.plot(dd_def[1][0], dd_def[1][1] - corr(n_def), "o")
l_div = plt.plot(dd_div[1][0], dd_div[1][1] - corr(n_div), "o")
l_cst = []
t_cst = []
if nvals is not None:
dd_cst = nolds.hurst_rs(data, nvals=nvals, debug_data=True, fit="poly")
l_cst = plt.plot(dd_cst[1][0], dd_cst[1][1] - corr(nvals), "o")
l_cst = l_cst
t_cst = ["custom"]
plt.xlabel("log(n)")
plt.ylabel("log((R/S)_n - E[(R/S)_n])")
plt.legend(l_all + l_def + l_div + l_cst, ["all", "default", "divisors"] + t_cst)
labeled_data = zip([dd_all[0], dd_def[0], dd_div[0]], ["all", "def", "div"])
for data, label in labeled_data:
print("%s: %.3f" % (label, data))
if nvals is not None:
print("custom: %.3f" % dd_cst[0])
plt.show() |
def pauli_single(cls, num_qubits, index, pauli_label):
tmp = Pauli.from_label(pauli_label)
z = np.zeros(num_qubits, dtype=np.bool)
x = np.zeros(num_qubits, dtype=np.bool)
z[index] = tmp.z[0]
x[index] = tmp.x[0]
return cls(z, x) | Generate single qubit pauli at index with pauli_label with length num_qubits.
Args:
num_qubits (int): the length of pauli
index (int): the qubit index to insert the single qubii
pauli_label (str): pauli
Returns:
Pauli: single qubit pauli | ### Input:
Generate single qubit pauli at index with pauli_label with length num_qubits.
Args:
num_qubits (int): the length of pauli
index (int): the qubit index to insert the single qubii
pauli_label (str): pauli
Returns:
Pauli: single qubit pauli
### Response:
def pauli_single(cls, num_qubits, index, pauli_label):
tmp = Pauli.from_label(pauli_label)
z = np.zeros(num_qubits, dtype=np.bool)
x = np.zeros(num_qubits, dtype=np.bool)
z[index] = tmp.z[0]
x[index] = tmp.x[0]
return cls(z, x) |
def update_buffer_with_value( self, value, buffer, parent=None ):
assert common.is_bytes( buffer )
self.validate( value, parent )
return | Write a Python object into a byte array, using the field definition.
value
Input Python object to process.
buffer
Output byte array to encode value into.
parent
Parent block object where this Field is defined. Used for e.g.
evaluating Refs. | ### Input:
Write a Python object into a byte array, using the field definition.
value
Input Python object to process.
buffer
Output byte array to encode value into.
parent
Parent block object where this Field is defined. Used for e.g.
evaluating Refs.
### Response:
def update_buffer_with_value( self, value, buffer, parent=None ):
assert common.is_bytes( buffer )
self.validate( value, parent )
return |
def parse_targets(filename):
base,ext = os.path.splitext(filename)
if (ext==):
import fitsio
data = fitsio.read(filename)
elif (ext==):
from numpy.lib import NumpyVersion
if NumpyVersion(np.__version__) < :
data = np.genfromtxt(filename,names=True,dtype=None)
else:
data = np.genfromtxt(filename,names=True,dtype=None,encoding=None)
elif (ext==):
import yaml
data = [(k,v[][][],v[][][],0.5,) for k,v in yaml.load(open(filename)).items()]
data = np.rec.fromrecords(data,names=[,,,,])
else:
msg = "Unrecognized file type: %s"%filename
raise IOError(msg)
data = np.atleast_1d(data)
data.dtype.names = list(map(str.lower,data.dtype.names))
names = data[]
out = data[[,,]].copy()
coord = np.char.lower(data[])
gal = (coord==)
cel = (coord==)
hpx = (coord==)
if cel.any():
glon,glat = cel2gal(data[][cel],data[][cel])
out[][cel] = glon
out[][cel] = glat
if hpx.any():
glon,glat = pix2ang(data[][hpx],data[][hpx])
out[][hpx] = glon
out[][hpx] = glat
return names,out.view(np.ndarray) | Load a text file with target coordinates. Returns
an array of target locations in Galactic coordinates.
File description:
[NAME] [LON] [LAT] [RADIUS] [COORD]
The values of LON and LAT will depend on COORD:
COORD = [GAL | CEL | HPX ],
LON = [GLON | RA | NSIDE]
LAT = [GLAT | DEC | PIX ] | ### Input:
Load a text file with target coordinates. Returns
an array of target locations in Galactic coordinates.
File description:
[NAME] [LON] [LAT] [RADIUS] [COORD]
The values of LON and LAT will depend on COORD:
COORD = [GAL | CEL | HPX ],
LON = [GLON | RA | NSIDE]
LAT = [GLAT | DEC | PIX ]
### Response:
def parse_targets(filename):
base,ext = os.path.splitext(filename)
if (ext==):
import fitsio
data = fitsio.read(filename)
elif (ext==):
from numpy.lib import NumpyVersion
if NumpyVersion(np.__version__) < :
data = np.genfromtxt(filename,names=True,dtype=None)
else:
data = np.genfromtxt(filename,names=True,dtype=None,encoding=None)
elif (ext==):
import yaml
data = [(k,v[][][],v[][][],0.5,) for k,v in yaml.load(open(filename)).items()]
data = np.rec.fromrecords(data,names=[,,,,])
else:
msg = "Unrecognized file type: %s"%filename
raise IOError(msg)
data = np.atleast_1d(data)
data.dtype.names = list(map(str.lower,data.dtype.names))
names = data[]
out = data[[,,]].copy()
coord = np.char.lower(data[])
gal = (coord==)
cel = (coord==)
hpx = (coord==)
if cel.any():
glon,glat = cel2gal(data[][cel],data[][cel])
out[][cel] = glon
out[][cel] = glat
if hpx.any():
glon,glat = pix2ang(data[][hpx],data[][hpx])
out[][hpx] = glon
out[][hpx] = glat
return names,out.view(np.ndarray) |
def _change_volume(self, increase):
sign = "+" if increase else "-"
delta = "%d%%%s" % (self.volume_tick, sign)
self._run(["amixer", "-q", "sset", "Master", delta]) | Change volume using amixer | ### Input:
Change volume using amixer
### Response:
def _change_volume(self, increase):
sign = "+" if increase else "-"
delta = "%d%%%s" % (self.volume_tick, sign)
self._run(["amixer", "-q", "sset", "Master", delta]) |
def setup(addr, user, remote_path, local_key=None):
port = find_port(addr, user)
if not port or not is_alive(addr, user):
port = new_port()
scp(addr, user, __file__, , local_key)
ssh_call = [, % port,
, ,
, % port,
, ,
% (user, addr,), , ,
, remote_path]
if local_key:
ssh_call.insert(1, local_key)
ssh_call.insert(1, )
subprocess.call(ssh_call)
time.sleep(1)
return port | Setup the tunnel | ### Input:
Setup the tunnel
### Response:
def setup(addr, user, remote_path, local_key=None):
port = find_port(addr, user)
if not port or not is_alive(addr, user):
port = new_port()
scp(addr, user, __file__, , local_key)
ssh_call = [, % port,
, ,
, % port,
, ,
% (user, addr,), , ,
, remote_path]
if local_key:
ssh_call.insert(1, local_key)
ssh_call.insert(1, )
subprocess.call(ssh_call)
time.sleep(1)
return port |
def emd(prediction, ground_truth):
import opencv
if not (prediction.shape == ground_truth.shape):
raise RuntimeError( +
%(str(prediction.shape), str(ground_truth.shape)))
(x, y) = np.meshgrid(list(range(0, prediction.shape[1])),
list(range(0, prediction.shape[0])))
s1 = np.array([x.flatten(), y.flatten(), prediction.flatten()]).T
s2 = np.array([x.flatten(), y.flatten(), ground_truth.flatten()]).T
s1m = opencv.cvCreateMat(s1.shape[0], s2.shape[1], opencv.CV_32FC1)
s2m = opencv.cvCreateMat(s1.shape[0], s2.shape[1], opencv.CV_32FC1)
for r in range(0, s1.shape[0]):
for c in range(0, s1.shape[1]):
s1m[r, c] = float(s1[r, c])
s2m[r, c] = float(s2[r, c])
d = opencv.cvCalcEMD2(s1m, s2m, opencv.CV_DIST_L2)
return d | Compute the Eart Movers Distance between prediction and model.
This implementation uses opencv for doing the actual work.
Unfortunately, at the time of implementation only the SWIG
bindings werer available and the numpy arrays have to
converted by hand. This changes with opencv 2.1. | ### Input:
Compute the Eart Movers Distance between prediction and model.
This implementation uses opencv for doing the actual work.
Unfortunately, at the time of implementation only the SWIG
bindings werer available and the numpy arrays have to
converted by hand. This changes with opencv 2.1.
### Response:
def emd(prediction, ground_truth):
import opencv
if not (prediction.shape == ground_truth.shape):
raise RuntimeError( +
%(str(prediction.shape), str(ground_truth.shape)))
(x, y) = np.meshgrid(list(range(0, prediction.shape[1])),
list(range(0, prediction.shape[0])))
s1 = np.array([x.flatten(), y.flatten(), prediction.flatten()]).T
s2 = np.array([x.flatten(), y.flatten(), ground_truth.flatten()]).T
s1m = opencv.cvCreateMat(s1.shape[0], s2.shape[1], opencv.CV_32FC1)
s2m = opencv.cvCreateMat(s1.shape[0], s2.shape[1], opencv.CV_32FC1)
for r in range(0, s1.shape[0]):
for c in range(0, s1.shape[1]):
s1m[r, c] = float(s1[r, c])
s2m[r, c] = float(s2[r, c])
d = opencv.cvCalcEMD2(s1m, s2m, opencv.CV_DIST_L2)
return d |
def resize(self, shape, format=None, internalformat=None):
return self._resize(shape, format, internalformat) | Set the texture size and format
Parameters
----------
shape : tuple of integers
New texture shape in zyx order. Optionally, an extra dimention
may be specified to indicate the number of color channels.
format : str | enum | None
The format of the texture: 'luminance', 'alpha',
'luminance_alpha', 'rgb', or 'rgba'. If not given the format
is chosen automatically based on the number of channels.
When the data has one channel, 'luminance' is assumed.
internalformat : str | enum | None
The internal (storage) format of the texture: 'luminance',
'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha',
'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16',
'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f',
'rgba32f'. If None, the internalformat is chosen
automatically based on the number of channels. This is a
hint which may be ignored by the OpenGL implementation. | ### Input:
Set the texture size and format
Parameters
----------
shape : tuple of integers
New texture shape in zyx order. Optionally, an extra dimention
may be specified to indicate the number of color channels.
format : str | enum | None
The format of the texture: 'luminance', 'alpha',
'luminance_alpha', 'rgb', or 'rgba'. If not given the format
is chosen automatically based on the number of channels.
When the data has one channel, 'luminance' is assumed.
internalformat : str | enum | None
The internal (storage) format of the texture: 'luminance',
'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha',
'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16',
'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f',
'rgba32f'. If None, the internalformat is chosen
automatically based on the number of channels. This is a
hint which may be ignored by the OpenGL implementation.
### Response:
def resize(self, shape, format=None, internalformat=None):
return self._resize(shape, format, internalformat) |
def _write_header(self):
for line in self.header.lines:
print(line.serialize(), file=self.stream)
if self.header.samples.names:
print(
"\t".join(list(parser.REQUIRE_SAMPLE_HEADER) + self.header.samples.names),
file=self.stream,
)
else:
print("\t".join(parser.REQUIRE_NO_SAMPLE_HEADER), file=self.stream) | Write out the header | ### Input:
Write out the header
### Response:
def _write_header(self):
for line in self.header.lines:
print(line.serialize(), file=self.stream)
if self.header.samples.names:
print(
"\t".join(list(parser.REQUIRE_SAMPLE_HEADER) + self.header.samples.names),
file=self.stream,
)
else:
print("\t".join(parser.REQUIRE_NO_SAMPLE_HEADER), file=self.stream) |
def get_status(self, instance):
status_key, status = self._get_status(instance)
if status[] in [, ]:
cache.delete(status_key)
return status | Retrives a status of a field from cache. Fields in state 'error' and
'complete' will not retain the status after the call. | ### Input:
Retrives a status of a field from cache. Fields in state 'error' and
'complete' will not retain the status after the call.
### Response:
def get_status(self, instance):
status_key, status = self._get_status(instance)
if status[] in [, ]:
cache.delete(status_key)
return status |
def get_cf_distribution_class():
if LooseVersion(troposphere.__version__) == LooseVersion():
cf_dist = cloudfront.Distribution
cf_dist.props[] = (DistributionConfig, True)
return cf_dist
return cloudfront.Distribution | Return the correct troposphere CF distribution class. | ### Input:
Return the correct troposphere CF distribution class.
### Response:
def get_cf_distribution_class():
if LooseVersion(troposphere.__version__) == LooseVersion():
cf_dist = cloudfront.Distribution
cf_dist.props[] = (DistributionConfig, True)
return cf_dist
return cloudfront.Distribution |
def delete(self, filename=None, delete_v1=True, delete_v2=True):
if filename is None:
filename = self.filename
delete(filename, delete_v1, delete_v2)
self.clear() | Remove tags from a file.
If no filename is given, the one most recently loaded is used.
Keyword arguments:
* delete_v1 -- delete any ID3v1 tag
* delete_v2 -- delete any ID3v2 tag | ### Input:
Remove tags from a file.
If no filename is given, the one most recently loaded is used.
Keyword arguments:
* delete_v1 -- delete any ID3v1 tag
* delete_v2 -- delete any ID3v2 tag
### Response:
def delete(self, filename=None, delete_v1=True, delete_v2=True):
if filename is None:
filename = self.filename
delete(filename, delete_v1, delete_v2)
self.clear() |
def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng):
membs = np.empty(shape=X.shape[0], dtype=int)
centers = kmeans._kmeans_init(X, n_clusters, method=, rng=rng)
sse_last = 9999.9
n_iter = 0
for it in range(1,max_iter):
membs = kmeans._assign_clusters(X, centers)
centers,sse_arr = _update_centers(X, membs, n_clusters, distance)
sse_total = np.sum(sse_arr)
if np.abs(sse_total - sse_last) < tol:
n_iter = it
break
sse_last = sse_total
return(centers, membs, sse_total, sse_arr, n_iter) | Run a single trial of k-medoids clustering
on dataset X, and given number of clusters | ### Input:
Run a single trial of k-medoids clustering
on dataset X, and given number of clusters
### Response:
def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng):
membs = np.empty(shape=X.shape[0], dtype=int)
centers = kmeans._kmeans_init(X, n_clusters, method=, rng=rng)
sse_last = 9999.9
n_iter = 0
for it in range(1,max_iter):
membs = kmeans._assign_clusters(X, centers)
centers,sse_arr = _update_centers(X, membs, n_clusters, distance)
sse_total = np.sum(sse_arr)
if np.abs(sse_total - sse_last) < tol:
n_iter = it
break
sse_last = sse_total
return(centers, membs, sse_total, sse_arr, n_iter) |
def pattern_logic_aeidon():
if Config.options.pattern_files:
return prep_patterns(Config.options.pattern_files)
elif Config.options.regex:
return Config.REGEX
else:
return Config.TERMS | Return patterns to be used for searching subtitles via aeidon. | ### Input:
Return patterns to be used for searching subtitles via aeidon.
### Response:
def pattern_logic_aeidon():
if Config.options.pattern_files:
return prep_patterns(Config.options.pattern_files)
elif Config.options.regex:
return Config.REGEX
else:
return Config.TERMS |
def neighbor_update(self, address, conf_type, conf_value):
assert conf_type == MULTI_EXIT_DISC or conf_type == CONNECT_MODE
func_name =
attribute_param = {}
if conf_type == MULTI_EXIT_DISC:
attribute_param = {neighbors.MULTI_EXIT_DISC: conf_value}
elif conf_type == CONNECT_MODE:
attribute_param = {neighbors.CONNECT_MODE: conf_value}
param = {neighbors.IP_ADDRESS: address,
neighbors.CHANGES: attribute_param}
call(func_name, **param) | This method changes the neighbor configuration.
``address`` specifies the IP address of the peer.
``conf_type`` specifies configuration type which you want to change.
Currently ryu.services.protocols.bgp.bgpspeaker.MULTI_EXIT_DISC
can be specified.
``conf_value`` specifies value for the configuration type. | ### Input:
This method changes the neighbor configuration.
``address`` specifies the IP address of the peer.
``conf_type`` specifies configuration type which you want to change.
Currently ryu.services.protocols.bgp.bgpspeaker.MULTI_EXIT_DISC
can be specified.
``conf_value`` specifies value for the configuration type.
### Response:
def neighbor_update(self, address, conf_type, conf_value):
assert conf_type == MULTI_EXIT_DISC or conf_type == CONNECT_MODE
func_name =
attribute_param = {}
if conf_type == MULTI_EXIT_DISC:
attribute_param = {neighbors.MULTI_EXIT_DISC: conf_value}
elif conf_type == CONNECT_MODE:
attribute_param = {neighbors.CONNECT_MODE: conf_value}
param = {neighbors.IP_ADDRESS: address,
neighbors.CHANGES: attribute_param}
call(func_name, **param) |
def remove_blocked_work_units(self, work_spec_name, work_unit_names):
return self._remove_some_work_units(
work_spec_name, work_unit_names, suffix=_BLOCKED) | Remove some work units in the blocked list.
If `work_unit_names` is :const:`None` (which must be passed
explicitly), all pending work units in `work_spec_name` are
removed; otherwise only the specific named work units will be.
Note that none of the "remove" functions will restart blocked
work units, so if you have called
e.g. :meth:`remove_available_work_units` for a predecessor
job, you may need to also call this method for its successor.
:param str work_spec_name: name of the work spec
:param list work_unit_names: names of the work units, or
:const:`None` for all in `work_spec_name`
:return: number of work units removed | ### Input:
Remove some work units in the blocked list.
If `work_unit_names` is :const:`None` (which must be passed
explicitly), all pending work units in `work_spec_name` are
removed; otherwise only the specific named work units will be.
Note that none of the "remove" functions will restart blocked
work units, so if you have called
e.g. :meth:`remove_available_work_units` for a predecessor
job, you may need to also call this method for its successor.
:param str work_spec_name: name of the work spec
:param list work_unit_names: names of the work units, or
:const:`None` for all in `work_spec_name`
:return: number of work units removed
### Response:
def remove_blocked_work_units(self, work_spec_name, work_unit_names):
return self._remove_some_work_units(
work_spec_name, work_unit_names, suffix=_BLOCKED) |
def dxlink(object_id, project_id=None, field=None):
job$dnanexus_linkjobfield$dnanexus_linkprojectid
if is_dxlink(object_id):
return object_id
if isinstance(object_id, DXDataObject):
object_id = object_id.get_id()
if not any((project_id, field)):
return {: object_id}
elif field:
dxpy.verify_string_dxid(object_id, "job")
return {: {: object_id, : field}}
else:
return {: {: project_id, : object_id}} | :param object_id: Object ID or the object handler itself
:type object_id: string or :class:`~dxpy.bindings.DXDataObject`
:param project_id: A project ID, if creating a cross-project DXLink
:type project_id: string
:param field: A field name, if creating a job-based object reference
:type field: string
:returns: A dict formatted as a symbolic DNAnexus object reference
:rtype: dict
Creates a DXLink to the specified object.
If `object_id` is already a link, it is returned without modification.
If `object_id is a `~dxpy.bindings.DXDataObject`, the object ID is
retrieved via its `get_id()` method.
If `field` is not `None`, `object_id` is expected to be of class 'job'
and the link created is a Job Based Object Reference (JBOR), which is
of the form::
{'$dnanexus_link': {'job': object_id, 'field': field}}
If `field` is `None` and `project_id` is not `None`, the link created
is a project-specific link of the form::
{'$dnanexus_link': {'project': project_id, 'id': object_id}} | ### Input:
:param object_id: Object ID or the object handler itself
:type object_id: string or :class:`~dxpy.bindings.DXDataObject`
:param project_id: A project ID, if creating a cross-project DXLink
:type project_id: string
:param field: A field name, if creating a job-based object reference
:type field: string
:returns: A dict formatted as a symbolic DNAnexus object reference
:rtype: dict
Creates a DXLink to the specified object.
If `object_id` is already a link, it is returned without modification.
If `object_id is a `~dxpy.bindings.DXDataObject`, the object ID is
retrieved via its `get_id()` method.
If `field` is not `None`, `object_id` is expected to be of class 'job'
and the link created is a Job Based Object Reference (JBOR), which is
of the form::
{'$dnanexus_link': {'job': object_id, 'field': field}}
If `field` is `None` and `project_id` is not `None`, the link created
is a project-specific link of the form::
{'$dnanexus_link': {'project': project_id, 'id': object_id}}
### Response:
def dxlink(object_id, project_id=None, field=None):
job$dnanexus_linkjobfield$dnanexus_linkprojectid
if is_dxlink(object_id):
return object_id
if isinstance(object_id, DXDataObject):
object_id = object_id.get_id()
if not any((project_id, field)):
return {: object_id}
elif field:
dxpy.verify_string_dxid(object_id, "job")
return {: {: object_id, : field}}
else:
return {: {: project_id, : object_id}} |
def browse(self):
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open( + path) | Save response in temporary file and open it in GUI browser. | ### Input:
Save response in temporary file and open it in GUI browser.
### Response:
def browse(self):
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open( + path) |
def delete_function(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Qualifier:
conn.delete_function(
FunctionName=FunctionName, Qualifier=Qualifier)
else:
conn.delete_function(FunctionName=FunctionName)
return {: True}
except ClientError as e:
return {: False, : __utils__[](e)} | Given a function name and optional version qualifier, delete it.
Returns {deleted: true} if the function was deleted and returns
{deleted: false} if the function was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.delete_function myfunction | ### Input:
Given a function name and optional version qualifier, delete it.
Returns {deleted: true} if the function was deleted and returns
{deleted: false} if the function was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.delete_function myfunction
### Response:
def delete_function(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Qualifier:
conn.delete_function(
FunctionName=FunctionName, Qualifier=Qualifier)
else:
conn.delete_function(FunctionName=FunctionName)
return {: True}
except ClientError as e:
return {: False, : __utils__[](e)} |
def can_create_gradebook_column_with_record_types(self, gradebook_column_record_types):
if self._catalog_session is not None:
return self._catalog_session.can_create_catalog_with_record_types(catalog_record_types=gradebook_column_record_types)
return True | Tests if this user can create a single ``GradebookColumn`` using the desired record types.
While ``GradingManager.getGradebookColumnRecordTypes()`` can be
used to examine which records are supported, this method tests
which record(s) are required for creating a specific
``GradebookColumn``. Providing an empty array tests if a
``GradebookColumn`` can be created with no records.
arg: gradebook_column_record_types (osid.type.Type[]): array
of gradebook column record types
return: (boolean) - ``true`` if ``GradebookColumn`` creation
using the specified record ``Types`` is supported,
``false`` otherwise
raise: NullArgument - ``gradebook_column_record_types`` is
``null``
*compliance: mandatory -- This method must be implemented.* | ### Input:
Tests if this user can create a single ``GradebookColumn`` using the desired record types.
While ``GradingManager.getGradebookColumnRecordTypes()`` can be
used to examine which records are supported, this method tests
which record(s) are required for creating a specific
``GradebookColumn``. Providing an empty array tests if a
``GradebookColumn`` can be created with no records.
arg: gradebook_column_record_types (osid.type.Type[]): array
of gradebook column record types
return: (boolean) - ``true`` if ``GradebookColumn`` creation
using the specified record ``Types`` is supported,
``false`` otherwise
raise: NullArgument - ``gradebook_column_record_types`` is
``null``
*compliance: mandatory -- This method must be implemented.*
### Response:
def can_create_gradebook_column_with_record_types(self, gradebook_column_record_types):
if self._catalog_session is not None:
return self._catalog_session.can_create_catalog_with_record_types(catalog_record_types=gradebook_column_record_types)
return True |
def handle(self, key, value):
master = {}
master[] = value
master[] = 0
master[] = int(self.get_current_time())
elements = key.split(":")
dict = {}
dict[] = elements[1]
dict[] = elements[2]
extras = self.get_log_dict(, dict[],
dict[], master[])
if len(elements) == 4:
dict[] = elements[3]
extras = self.get_log_dict(, dict[],
dict[], master[],
elements[3])
self.logger.info(, extra=extras)
if in dict:
master = self._build_crawlid_info(master, dict)
else:
master = self._build_appid_info(master, dict)
if self._send_to_kafka(master):
extras[] = True
self.logger.info(, extra=extras)
else:
extras[] = False
self.logger.error(,
extra=extras) | Processes a vaild action info request
@param key: The key that matched the request
@param value: The value associated with the key | ### Input:
Processes a vaild action info request
@param key: The key that matched the request
@param value: The value associated with the key
### Response:
def handle(self, key, value):
master = {}
master[] = value
master[] = 0
master[] = int(self.get_current_time())
elements = key.split(":")
dict = {}
dict[] = elements[1]
dict[] = elements[2]
extras = self.get_log_dict(, dict[],
dict[], master[])
if len(elements) == 4:
dict[] = elements[3]
extras = self.get_log_dict(, dict[],
dict[], master[],
elements[3])
self.logger.info(, extra=extras)
if in dict:
master = self._build_crawlid_info(master, dict)
else:
master = self._build_appid_info(master, dict)
if self._send_to_kafka(master):
extras[] = True
self.logger.info(, extra=extras)
else:
extras[] = False
self.logger.error(,
extra=extras) |
def update(self, uid):
if self.userinfo.role[0] > :
pass
else:
return False
post_data = self.get_post_data()
post_data[] = self.userinfo.user_name if self.userinfo else
cur_info = MWiki.get_by_uid(uid)
MWikiHist.create_wiki_history(cur_info)
MWiki.update_cnt(uid, post_data)
if cur_info.kind == :
self.redirect(.format(cur_info.title))
elif cur_info.kind == :
self.redirect(.format(cur_info.uid)) | Update the post via ID. | ### Input:
Update the post via ID.
### Response:
def update(self, uid):
if self.userinfo.role[0] > :
pass
else:
return False
post_data = self.get_post_data()
post_data[] = self.userinfo.user_name if self.userinfo else
cur_info = MWiki.get_by_uid(uid)
MWikiHist.create_wiki_history(cur_info)
MWiki.update_cnt(uid, post_data)
if cur_info.kind == :
self.redirect(.format(cur_info.title))
elif cur_info.kind == :
self.redirect(.format(cur_info.uid)) |
def load_medium(self, model):
media = self.config.get("medium")
if media is None:
return
definitions = media.get("definitions")
if definitions is None or len(definitions) == 0:
return
path = self.get_path(media, join("data", "experimental", "media"))
for medium_id, medium in iteritems(definitions):
if medium is None:
medium = dict()
filename = medium.get("filename")
if filename is None:
filename = join(path, "{}.csv".format(medium_id))
elif not isabs(filename):
filename = join(path, filename)
tmp = Medium(identifier=medium_id, obj=medium, filename=filename)
tmp.load()
tmp.validate(model)
self.media[medium_id] = tmp | Load and validate all media. | ### Input:
Load and validate all media.
### Response:
def load_medium(self, model):
media = self.config.get("medium")
if media is None:
return
definitions = media.get("definitions")
if definitions is None or len(definitions) == 0:
return
path = self.get_path(media, join("data", "experimental", "media"))
for medium_id, medium in iteritems(definitions):
if medium is None:
medium = dict()
filename = medium.get("filename")
if filename is None:
filename = join(path, "{}.csv".format(medium_id))
elif not isabs(filename):
filename = join(path, filename)
tmp = Medium(identifier=medium_id, obj=medium, filename=filename)
tmp.load()
tmp.validate(model)
self.media[medium_id] = tmp |
def auth_key_send(self, key, force_mavlink1=False):
return self.send(self.auth_key_encode(key), force_mavlink1=force_mavlink1) | Emit an encrypted signature / key identifying this system. PLEASE
NOTE: This protocol has been kept simple, so
transmitting the key requires an encrypted channel for
true safety.
key : key (char) | ### Input:
Emit an encrypted signature / key identifying this system. PLEASE
NOTE: This protocol has been kept simple, so
transmitting the key requires an encrypted channel for
true safety.
key : key (char)
### Response:
def auth_key_send(self, key, force_mavlink1=False):
return self.send(self.auth_key_encode(key), force_mavlink1=force_mavlink1) |
def set_all_attribute_values(self, value):
for attribute_name, type_instance in inspect.getmembers(self):
if attribute_name.startswith() or inspect.ismethod(type_instance):
continue
if isinstance(type_instance, bool):
self.__dict__[attribute_name] = value
elif isinstance(type_instance, self.__class__):
type_instance.set_all_attribute_values(value) | sets all the attribute values to the value and propagate to any children | ### Input:
sets all the attribute values to the value and propagate to any children
### Response:
def set_all_attribute_values(self, value):
for attribute_name, type_instance in inspect.getmembers(self):
if attribute_name.startswith() or inspect.ismethod(type_instance):
continue
if isinstance(type_instance, bool):
self.__dict__[attribute_name] = value
elif isinstance(type_instance, self.__class__):
type_instance.set_all_attribute_values(value) |
def _to_edit(self, infoid):
postinfo = MPost.get_by_uid(infoid)
if postinfo:
pass
else:
return self.show404()
if in postinfo.extinfo:
catid = postinfo.extinfo[]
elif in postinfo.extinfo:
catid = postinfo.extinfo[]
else:
catid =
if len(catid) == 4:
pass
else:
catid =
catinfo = None
p_catinfo = None
post2catinfo = MPost2Catalog.get_first_category(postinfo.uid)
if post2catinfo:
catid = post2catinfo.tag_id
catinfo = MCategory.get_by_uid(catid)
if catinfo:
p_catinfo = MCategory.get_by_uid(catinfo.pid)
kwd = {
: catid,
: ,
: ,
: MCategory.get_parent_list(),
: self.request.remote_ip,
: json.dumps(postinfo.extinfo, indent=2, ensure_ascii=False),
}
if self.filter_view:
tmpl = .format(catid)
else:
tmpl = .format(self.kind)
logger.info(.format(tmpl))
self.render(
tmpl,
kwd=kwd,
postinfo=postinfo,
catinfo=catinfo,
pcatinfo=p_catinfo,
userinfo=self.userinfo,
cat_enum=MCategory.get_qian2(catid[:2]),
tag_infos=MCategory.query_all(by_order=True, kind=self.kind),
tag_infos2=MCategory.query_all(by_order=True, kind=self.kind),
app2tag_info=MPost2Catalog.query_by_entity_uid(infoid, kind=self.kind).objects(),
app2label_info=MPost2Label.get_by_uid(infoid).objects()
) | render the HTML page for post editing. | ### Input:
render the HTML page for post editing.
### Response:
def _to_edit(self, infoid):
postinfo = MPost.get_by_uid(infoid)
if postinfo:
pass
else:
return self.show404()
if in postinfo.extinfo:
catid = postinfo.extinfo[]
elif in postinfo.extinfo:
catid = postinfo.extinfo[]
else:
catid =
if len(catid) == 4:
pass
else:
catid =
catinfo = None
p_catinfo = None
post2catinfo = MPost2Catalog.get_first_category(postinfo.uid)
if post2catinfo:
catid = post2catinfo.tag_id
catinfo = MCategory.get_by_uid(catid)
if catinfo:
p_catinfo = MCategory.get_by_uid(catinfo.pid)
kwd = {
: catid,
: ,
: ,
: MCategory.get_parent_list(),
: self.request.remote_ip,
: json.dumps(postinfo.extinfo, indent=2, ensure_ascii=False),
}
if self.filter_view:
tmpl = .format(catid)
else:
tmpl = .format(self.kind)
logger.info(.format(tmpl))
self.render(
tmpl,
kwd=kwd,
postinfo=postinfo,
catinfo=catinfo,
pcatinfo=p_catinfo,
userinfo=self.userinfo,
cat_enum=MCategory.get_qian2(catid[:2]),
tag_infos=MCategory.query_all(by_order=True, kind=self.kind),
tag_infos2=MCategory.query_all(by_order=True, kind=self.kind),
app2tag_info=MPost2Catalog.query_by_entity_uid(infoid, kind=self.kind).objects(),
app2label_info=MPost2Label.get_by_uid(infoid).objects()
) |
def update(uid=None):
app.logger.info("PUT /sync route with id: %s" % uid)
try:
user = Participant.query.\
filter(Participant.uniqueid == uid).\
one()
except exc.SQLAlchemyError:
app.logger.error("DB error: Unique user not found.")
if hasattr(request, ):
user.datastring = request.data.decode().encode(
,
)
db_session.add(user)
db_session.commit()
try:
data = json.loads(user.datastring)
except:
data = {}
trial = data.get("currenttrial", None)
app.logger.info("saved data for %s (current trial: %s)", uid, trial)
resp = {"status": "user data saved"}
return jsonify(**resp) | Save experiment data, which should be a JSON object and will be stored
after converting to string. | ### Input:
Save experiment data, which should be a JSON object and will be stored
after converting to string.
### Response:
def update(uid=None):
app.logger.info("PUT /sync route with id: %s" % uid)
try:
user = Participant.query.\
filter(Participant.uniqueid == uid).\
one()
except exc.SQLAlchemyError:
app.logger.error("DB error: Unique user not found.")
if hasattr(request, ):
user.datastring = request.data.decode().encode(
,
)
db_session.add(user)
db_session.commit()
try:
data = json.loads(user.datastring)
except:
data = {}
trial = data.get("currenttrial", None)
app.logger.info("saved data for %s (current trial: %s)", uid, trial)
resp = {"status": "user data saved"}
return jsonify(**resp) |
def parse(cls, headers):
h = cls()
for line in headers.splitlines():
if line:
h.parse_line(line)
return h | Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.iteritems())
[('Content-Length', '42'), ('Content-Type', 'text/html')] | ### Input:
Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.iteritems())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
### Response:
def parse(cls, headers):
h = cls()
for line in headers.splitlines():
if line:
h.parse_line(line)
return h |
def make_process_header(self, slug, typ, version, source_uri, description, inputs):
node = addnodes.desc()
signode = addnodes.desc_signature(slug, )
node.append(signode)
node[] = node[] = typ
signode += addnodes.desc_annotation(typ, typ, classes=[])
signode += addnodes.desc_addname(, )
signode += addnodes.desc_name(slug + , slug + )
paramlist = addnodes.desc_parameterlist()
for field_schema, _, _ in iterate_schema({}, inputs, ):
field_type = field_schema[]
field_name = field_schema[]
field_default = field_schema.get(, None)
field_default = if field_default is None else .format(field_default)
param = addnodes.desc_parameter(, , noemph=True)
param += nodes.emphasis(field_type, field_type, classes=[])
param += nodes.strong(text= + field_name)
paramlist += param
signode += paramlist
signode += nodes.reference(, nodes.Text(.format(version)),
refuri=source_uri, classes=[])
desc = nodes.paragraph()
desc += nodes.Text(description, description)
return [node, desc] | Generate a process definition header.
:param str slug: process' slug
:param str typ: process' type
:param str version: process' version
:param str source_uri: url to the process definition
:param str description: process' description
:param dict inputs: process' inputs | ### Input:
Generate a process definition header.
:param str slug: process' slug
:param str typ: process' type
:param str version: process' version
:param str source_uri: url to the process definition
:param str description: process' description
:param dict inputs: process' inputs
### Response:
def make_process_header(self, slug, typ, version, source_uri, description, inputs):
node = addnodes.desc()
signode = addnodes.desc_signature(slug, )
node.append(signode)
node[] = node[] = typ
signode += addnodes.desc_annotation(typ, typ, classes=[])
signode += addnodes.desc_addname(, )
signode += addnodes.desc_name(slug + , slug + )
paramlist = addnodes.desc_parameterlist()
for field_schema, _, _ in iterate_schema({}, inputs, ):
field_type = field_schema[]
field_name = field_schema[]
field_default = field_schema.get(, None)
field_default = if field_default is None else .format(field_default)
param = addnodes.desc_parameter(, , noemph=True)
param += nodes.emphasis(field_type, field_type, classes=[])
param += nodes.strong(text= + field_name)
paramlist += param
signode += paramlist
signode += nodes.reference(, nodes.Text(.format(version)),
refuri=source_uri, classes=[])
desc = nodes.paragraph()
desc += nodes.Text(description, description)
return [node, desc] |
def get_quoted_foreign_columns(self, platform):
columns = []
for column in self._foreign_column_names.values():
columns.append(column.get_quoted_name(platform))
return columns | Returns the quoted representation of the referenced table column names
the foreign key constraint is associated with.
But only if they were defined with one or the referenced table column name
is a keyword reserved by the platform.
Otherwise the plain unquoted value as inserted is returned.
:param platform: The platform to use for quotation.
:type platform: Platform
:rtype: list | ### Input:
Returns the quoted representation of the referenced table column names
the foreign key constraint is associated with.
But only if they were defined with one or the referenced table column name
is a keyword reserved by the platform.
Otherwise the plain unquoted value as inserted is returned.
:param platform: The platform to use for quotation.
:type platform: Platform
:rtype: list
### Response:
def get_quoted_foreign_columns(self, platform):
columns = []
for column in self._foreign_column_names.values():
columns.append(column.get_quoted_name(platform))
return columns |
def _recursiveSetNodePath(self, nodePath):
self._nodePath = nodePath
for childItem in self.childItems:
childItem._recursiveSetNodePath(nodePath + + childItem.nodeName) | Sets the nodePath property and updates it for all children. | ### Input:
Sets the nodePath property and updates it for all children.
### Response:
def _recursiveSetNodePath(self, nodePath):
self._nodePath = nodePath
for childItem in self.childItems:
childItem._recursiveSetNodePath(nodePath + + childItem.nodeName) |
def _common(s1, s2, i1, i2):
c = len(set(s1).intersection(s2))
t = min(len(s1), len(s2))
pct = 1.0 * c / t * t
is_gt = up_threshold(pct, t * 1.0, parameters.similar)
logger.debug("_common: pct %s of clusters:%s %s = %s" % (1.0 * c / t, i1, i2, is_gt))
if pct < parameters.similar and is_gt and pct > 0:
pct = parameters.similar
return pct / t | calculate the common % percentage of sequences | ### Input:
calculate the common % percentage of sequences
### Response:
def _common(s1, s2, i1, i2):
c = len(set(s1).intersection(s2))
t = min(len(s1), len(s2))
pct = 1.0 * c / t * t
is_gt = up_threshold(pct, t * 1.0, parameters.similar)
logger.debug("_common: pct %s of clusters:%s %s = %s" % (1.0 * c / t, i1, i2, is_gt))
if pct < parameters.similar and is_gt and pct > 0:
pct = parameters.similar
return pct / t |
def split_type(cls, type_name):
if cls.matches_type(type_name):
basename = type_name[:-1]
cardinality = cls.from_char_map[type_name[-1]]
else:
cardinality = Cardinality.one
basename = type_name
return (basename, cardinality) | Split type of a type name with CardinalityField suffix into its parts.
:param type_name: Type name (as string).
:return: Tuple (type_basename, cardinality) | ### Input:
Split type of a type name with CardinalityField suffix into its parts.
:param type_name: Type name (as string).
:return: Tuple (type_basename, cardinality)
### Response:
def split_type(cls, type_name):
if cls.matches_type(type_name):
basename = type_name[:-1]
cardinality = cls.from_char_map[type_name[-1]]
else:
cardinality = Cardinality.one
basename = type_name
return (basename, cardinality) |
def load_gltf(file_obj=None,
resolver=None,
**mesh_kwargs):
try:
kwargs = _read_buffers(header=tree,
buffers=buffers,
mesh_kwargs=mesh_kwargs)
return kwargs | Load a GLTF file, which consists of a directory structure
with multiple files.
Parameters
-------------
file_obj : None or file-like
Object containing header JSON, or None
resolver : trimesh.visual.Resolver
Object which can be used to load other files by name
**mesh_kwargs : dict
Passed to mesh constructor
Returns
--------------
kwargs : dict
Arguments to create scene | ### Input:
Load a GLTF file, which consists of a directory structure
with multiple files.
Parameters
-------------
file_obj : None or file-like
Object containing header JSON, or None
resolver : trimesh.visual.Resolver
Object which can be used to load other files by name
**mesh_kwargs : dict
Passed to mesh constructor
Returns
--------------
kwargs : dict
Arguments to create scene
### Response:
def load_gltf(file_obj=None,
resolver=None,
**mesh_kwargs):
try:
kwargs = _read_buffers(header=tree,
buffers=buffers,
mesh_kwargs=mesh_kwargs)
return kwargs |
def step_command_output_should_not_contain_log_records(context):
assert context.table, "REQUIRE: context.table"
context.table.require_columns(["category", "level", "message"])
format = getattr(context, "log_record_format", context.config.logging_format)
for row in context.table.rows:
output = LogRecordTable.make_output_for_row(row, format)
context.execute_steps(u.format(expected_output=output)) | Verifies that the command output contains the specified log records
(in any order).
.. code-block: gherkin
Then the command output should contain the following log records:
| category | level | message |
| bar | CURRENT | xxx | | ### Input:
Verifies that the command output contains the specified log records
(in any order).
.. code-block: gherkin
Then the command output should contain the following log records:
| category | level | message |
| bar | CURRENT | xxx |
### Response:
def step_command_output_should_not_contain_log_records(context):
assert context.table, "REQUIRE: context.table"
context.table.require_columns(["category", "level", "message"])
format = getattr(context, "log_record_format", context.config.logging_format)
for row in context.table.rows:
output = LogRecordTable.make_output_for_row(row, format)
context.execute_steps(u.format(expected_output=output)) |
def GetFilename(self):
if not self._file_entry:
return None
data_stream = getattr(self._file_entry.path_spec, , None)
if data_stream:
return .format(self._file_entry.name, data_stream)
return self._file_entry.name | Retrieves the name of the active file entry.
Returns:
str: name of the active file entry or None. | ### Input:
Retrieves the name of the active file entry.
Returns:
str: name of the active file entry or None.
### Response:
def GetFilename(self):
if not self._file_entry:
return None
data_stream = getattr(self._file_entry.path_spec, , None)
if data_stream:
return .format(self._file_entry.name, data_stream)
return self._file_entry.name |
def isect_polygon__naive(points):
isect = []
n = len(points)
if Real is float:
pass
else:
points = [(Real(p[0]), Real(p[1])) for p in points]
for i in range(n):
a0, a1 = points[i], points[(i + 1) % n]
for j in range(i + 1, n):
b0, b1 = points[j], points[(j + 1) % n]
if a0 not in (b0, b1) and a1 not in (b0, b1):
ix = isect_seg_seg_v2_point(a0, a1, b0, b1)
if ix is not None:
if USE_IGNORE_SEGMENT_ENDINGS:
if ((len_squared_v2v2(ix, a0) < NUM_EPS_SQ or
len_squared_v2v2(ix, a1) < NUM_EPS_SQ) and
(len_squared_v2v2(ix, b0) < NUM_EPS_SQ or
len_squared_v2v2(ix, b1) < NUM_EPS_SQ)):
continue
isect.append(ix)
return isect | Brute force O(n2) version of ``isect_polygon`` for test validation. | ### Input:
Brute force O(n2) version of ``isect_polygon`` for test validation.
### Response:
def isect_polygon__naive(points):
isect = []
n = len(points)
if Real is float:
pass
else:
points = [(Real(p[0]), Real(p[1])) for p in points]
for i in range(n):
a0, a1 = points[i], points[(i + 1) % n]
for j in range(i + 1, n):
b0, b1 = points[j], points[(j + 1) % n]
if a0 not in (b0, b1) and a1 not in (b0, b1):
ix = isect_seg_seg_v2_point(a0, a1, b0, b1)
if ix is not None:
if USE_IGNORE_SEGMENT_ENDINGS:
if ((len_squared_v2v2(ix, a0) < NUM_EPS_SQ or
len_squared_v2v2(ix, a1) < NUM_EPS_SQ) and
(len_squared_v2v2(ix, b0) < NUM_EPS_SQ or
len_squared_v2v2(ix, b1) < NUM_EPS_SQ)):
continue
isect.append(ix)
return isect |
def _last_bookmark(b0, b1):
n = [None, None]
_, _, n[0] = b0.rpartition(":")
_, _, n[1] = b1.rpartition(":")
for i in range(2):
try:
n[i] = int(n[i])
except ValueError:
raise ValueError("Invalid bookmark: {}".format(b0))
return b0 if n[0] > n[1] else b1 | Return the latest of two bookmarks by looking for the maximum
integer value following the last colon in the bookmark string. | ### Input:
Return the latest of two bookmarks by looking for the maximum
integer value following the last colon in the bookmark string.
### Response:
def _last_bookmark(b0, b1):
n = [None, None]
_, _, n[0] = b0.rpartition(":")
_, _, n[1] = b1.rpartition(":")
for i in range(2):
try:
n[i] = int(n[i])
except ValueError:
raise ValueError("Invalid bookmark: {}".format(b0))
return b0 if n[0] > n[1] else b1 |
def init_app(self, app):
host = app.config.get(, )
port = app.config.get(, 27017)
dbname = app.config[]
log.info("connecting to database: %s:%s/%s", host, port, dbname)
self.setup(app.config[]) | Setup via Flask. | ### Input:
Setup via Flask.
### Response:
def init_app(self, app):
host = app.config.get(, )
port = app.config.get(, 27017)
dbname = app.config[]
log.info("connecting to database: %s:%s/%s", host, port, dbname)
self.setup(app.config[]) |
def download_file(self, filename, timeout=5):
path_file = os.path.join(self.output_directory, DOWNLOADS_PATH, self.session_id[-8:], filename)
file_url = .format(self.server_url, self.session_id, filename)
if self.browser_remote:
self.__download_file(file_url, path_file, timeout)
return path_file
return None | download a file from remote selenoid and removing the file in the server.
request: http://<username>:<password>@<ggr_host>:<ggr_port>/download/<ggr_session_id>/<filename>
:param filename: file name with extension to download
:param timeout: threshold until the video file is downloaded
:return: downloaded file path or None | ### Input:
download a file from remote selenoid and removing the file in the server.
request: http://<username>:<password>@<ggr_host>:<ggr_port>/download/<ggr_session_id>/<filename>
:param filename: file name with extension to download
:param timeout: threshold until the video file is downloaded
:return: downloaded file path or None
### Response:
def download_file(self, filename, timeout=5):
path_file = os.path.join(self.output_directory, DOWNLOADS_PATH, self.session_id[-8:], filename)
file_url = .format(self.server_url, self.session_id, filename)
if self.browser_remote:
self.__download_file(file_url, path_file, timeout)
return path_file
return None |
def walk(self, node):
"Walk a parse tree, calling visit for each node."
node = self.visit(node)
if node is None:
return None
if isinstance(node, parso.tree.BaseNode):
walked = map(self.walk, node.children)
node.children = [child for child in walked if child is not None]
return node | Walk a parse tree, calling visit for each node. | ### Input:
Walk a parse tree, calling visit for each node.
### Response:
def walk(self, node):
"Walk a parse tree, calling visit for each node."
node = self.visit(node)
if node is None:
return None
if isinstance(node, parso.tree.BaseNode):
walked = map(self.walk, node.children)
node.children = [child for child in walked if child is not None]
return node |
def list_regions(self):
url = .format(self.host)
return http._get_with_qiniu_mac(url, None, self.auth) | 获得账号可见的区域的信息
列出当前用户所有可使用的区域。
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回区域列表,失败返回None
- ResponseInfo 请求的Response信息 | ### Input:
获得账号可见的区域的信息
列出当前用户所有可使用的区域。
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回区域列表,失败返回None
- ResponseInfo 请求的Response信息
### Response:
def list_regions(self):
url = .format(self.host)
return http._get_with_qiniu_mac(url, None, self.auth) |
def ParsePartitionsTable(
self, parser_mediator, database=None, table=None, **unused_kwargs):
if database is None:
raise ValueError()
if table is None:
raise ValueError()
for esedb_record in table.records:
if parser_mediator.abort:
break
record_values = self._GetRecordValues(
parser_mediator, table.name, esedb_record)
event_data = MsieWebCachePartitionsEventData()
event_data.directory = record_values.get(, None)
event_data.partition_identifier = record_values.get(, None)
event_data.partition_type = record_values.get(, None)
event_data.table_identifier = record_values.get(, None)
timestamp = record_values.get(, None)
if timestamp:
date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)
event = time_events.DateTimeValuesEvent(
date_time, )
parser_mediator.ProduceEventWithEventData(event, event_data) | Parses the Partitions table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
database (Optional[pyesedb.file]): ESE database.
table (Optional[pyesedb.table]): table.
Raises:
ValueError: if the database or table value is missing. | ### Input:
Parses the Partitions table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
database (Optional[pyesedb.file]): ESE database.
table (Optional[pyesedb.table]): table.
Raises:
ValueError: if the database or table value is missing.
### Response:
def ParsePartitionsTable(
self, parser_mediator, database=None, table=None, **unused_kwargs):
if database is None:
raise ValueError()
if table is None:
raise ValueError()
for esedb_record in table.records:
if parser_mediator.abort:
break
record_values = self._GetRecordValues(
parser_mediator, table.name, esedb_record)
event_data = MsieWebCachePartitionsEventData()
event_data.directory = record_values.get(, None)
event_data.partition_identifier = record_values.get(, None)
event_data.partition_type = record_values.get(, None)
event_data.table_identifier = record_values.get(, None)
timestamp = record_values.get(, None)
if timestamp:
date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)
event = time_events.DateTimeValuesEvent(
date_time, )
parser_mediator.ProduceEventWithEventData(event, event_data) |
def create(source, ids, force, pid_minter=None):
records_deprecation_warning()
from .api import Record
from .models import RecordMetadata
pid_minter = [process_minter(minter) for minter in pid_minter or []]
data = json.load(source)
if isinstance(data, dict):
data = [data]
if ids:
assert len(ids) == len(data),
for record, id_ in zip_longest(data, ids):
id_ = id_ or uuid.uuid4()
try:
for minter in pid_minter:
minter(id_, record)
click.echo(Record.create(record, id_=id_).id)
except exc.IntegrityError:
if force:
current_app.logger.warning(
"Trying to force insert: {0}".format(id_))
vm = current_app.extensions[].versioning_manager
uow = vm.unit_of_work(db.session)
uow.create_transaction(db.session)
model = RecordMetadata.query.get(id_)
rec = Record(record, model=model).commit()
current_app.logger.info("Created new revision {0}".format(
rec.revision_id))
click.echo(rec.id)
else:
raise click.BadParameter(
.format(id_),
param_hint=,
)
db.session.flush()
db.session.commit() | Create new bibliographic record(s). | ### Input:
Create new bibliographic record(s).
### Response:
def create(source, ids, force, pid_minter=None):
records_deprecation_warning()
from .api import Record
from .models import RecordMetadata
pid_minter = [process_minter(minter) for minter in pid_minter or []]
data = json.load(source)
if isinstance(data, dict):
data = [data]
if ids:
assert len(ids) == len(data),
for record, id_ in zip_longest(data, ids):
id_ = id_ or uuid.uuid4()
try:
for minter in pid_minter:
minter(id_, record)
click.echo(Record.create(record, id_=id_).id)
except exc.IntegrityError:
if force:
current_app.logger.warning(
"Trying to force insert: {0}".format(id_))
vm = current_app.extensions[].versioning_manager
uow = vm.unit_of_work(db.session)
uow.create_transaction(db.session)
model = RecordMetadata.query.get(id_)
rec = Record(record, model=model).commit()
current_app.logger.info("Created new revision {0}".format(
rec.revision_id))
click.echo(rec.id)
else:
raise click.BadParameter(
.format(id_),
param_hint=,
)
db.session.flush()
db.session.commit() |
def add_observer(self, observer):
if not isinstance(observer, PowerManagementObserver):
raise TypeError("observer MUST conform to power.PowerManagementObserver")
self._weak_observers.append(weakref.ref(observer)) | Adds weak ref to an observer.
@param observer: Instance of class registered with PowerManagementObserver
@raise TypeError: If observer is not registered with PowerManagementObserver abstract class | ### Input:
Adds weak ref to an observer.
@param observer: Instance of class registered with PowerManagementObserver
@raise TypeError: If observer is not registered with PowerManagementObserver abstract class
### Response:
def add_observer(self, observer):
if not isinstance(observer, PowerManagementObserver):
raise TypeError("observer MUST conform to power.PowerManagementObserver")
self._weak_observers.append(weakref.ref(observer)) |
async def debug(self, client_id, conn_string, command, args):
conn_id = self._client_info(client_id, )[conn_string]
return await self.adapter.debug(conn_id, command, args) | Send a debug command to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_script`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
command (str): The name of the debug command to run.
args (dict): Any command arguments.
Returns:
object: The response to the debug command.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had a protocol issue sending the debug
command. | ### Input:
Send a debug command to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_script`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
command (str): The name of the debug command to run.
args (dict): Any command arguments.
Returns:
object: The response to the debug command.
Raises:
DeviceServerError: There is an issue with your client_id such
as not being connected to the device.
DeviceAdapterError: The adapter had a protocol issue sending the debug
command.
### Response:
async def debug(self, client_id, conn_string, command, args):
conn_id = self._client_info(client_id, )[conn_string]
return await self.adapter.debug(conn_id, command, args) |
def clear(self):
self.mutex.acquire()
self.queue.clear()
self.mutex.release() | Remove all queue entries. | ### Input:
Remove all queue entries.
### Response:
def clear(self):
self.mutex.acquire()
self.queue.clear()
self.mutex.release() |
def include_sqlalchemy_models(nc, Base):
from sqlalchemy.ext.declarative.clsregistry import _ModuleMarker
for name, klass in Base._decl_class_registry.items():
print(name, klass)
if isinstance(klass, _ModuleMarker):
continue
add_script(nc, get_import_statement(klass))
add_greeting(nc, "* **{}** - {}".format(klass.__name__, get_dotted_path(klass))) | Include all SQLAlchemy models in the script context.
:param nc: notebook_context dictionary
:param Base: SQLAlchemy model Base class from where the all models inherit. | ### Input:
Include all SQLAlchemy models in the script context.
:param nc: notebook_context dictionary
:param Base: SQLAlchemy model Base class from where the all models inherit.
### Response:
def include_sqlalchemy_models(nc, Base):
from sqlalchemy.ext.declarative.clsregistry import _ModuleMarker
for name, klass in Base._decl_class_registry.items():
print(name, klass)
if isinstance(klass, _ModuleMarker):
continue
add_script(nc, get_import_statement(klass))
add_greeting(nc, "* **{}** - {}".format(klass.__name__, get_dotted_path(klass))) |
def action(inner_rule, loc=None):
def decorator(mapper):
@llrule(loc, inner_rule.expected)
def outer_rule(parser):
result = inner_rule(parser)
if result is unmatched:
return result
if isinstance(result, tuple):
return mapper(parser, *result)
else:
return mapper(parser, result)
return outer_rule
return decorator | A decorator returning a function that first runs ``inner_rule`` and then, if its
return value is not None, maps that value using ``mapper``.
If the value being mapped is a tuple, it is expanded into multiple arguments.
Similar to attaching semantic actions to rules in traditional parser generators. | ### Input:
A decorator returning a function that first runs ``inner_rule`` and then, if its
return value is not None, maps that value using ``mapper``.
If the value being mapped is a tuple, it is expanded into multiple arguments.
Similar to attaching semantic actions to rules in traditional parser generators.
### Response:
def action(inner_rule, loc=None):
def decorator(mapper):
@llrule(loc, inner_rule.expected)
def outer_rule(parser):
result = inner_rule(parser)
if result is unmatched:
return result
if isinstance(result, tuple):
return mapper(parser, *result)
else:
return mapper(parser, result)
return outer_rule
return decorator |
def postponed_to(self):
toDate = getLocalDate(self.date, self.time_from, self.tz)
return dateFormat(toDate) | Date that the event was postponed to (in the local time zone). | ### Input:
Date that the event was postponed to (in the local time zone).
### Response:
def postponed_to(self):
toDate = getLocalDate(self.date, self.time_from, self.tz)
return dateFormat(toDate) |
def detect(self, source, description):
if source == "guid" and description in self.guids:
return {self: 100}
description = description.lower()
if description == self.type:
return {self: 100}
elif re.search(r"\b" + self.type + r"\b", description):
return {self: 80}
elif any((re.search(r"\b" + alias + r"\b", description) for alias in self.aliases)):
return {self: 70}
return {} | Detects the type of a volume based on the provided information. It returns the plausibility for all
file system types as a dict. Although it is only responsible for returning its own plausibility, it is possible
that one type of filesystem is more likely than another, e.g. when NTFS detects it is likely to be NTFS, it
can also update the plausibility of exFAT to indicate it is less likely.
All scores a cumulative. When multiple sources are used, it is also cumulative. For instance, if run 1 is 25
certain, and run 2 is 25 certain as well, it will become 50 certain.
:meth:`Volume.detect_fs_type` will return immediately if the score is higher than 50 and there is only 1
FS type with the highest score. Otherwise, it will continue with the next run. If at the end of all runs no
viable FS type was found, it will return the highest scoring FS type (if it is > 0), otherwise it will return
the FS type fallback.
:param source: The source of the description
:param description: The description to detect with
:return: Dict with mapping of FsType() objects to scores | ### Input:
Detects the type of a volume based on the provided information. It returns the plausibility for all
file system types as a dict. Although it is only responsible for returning its own plausibility, it is possible
that one type of filesystem is more likely than another, e.g. when NTFS detects it is likely to be NTFS, it
can also update the plausibility of exFAT to indicate it is less likely.
All scores a cumulative. When multiple sources are used, it is also cumulative. For instance, if run 1 is 25
certain, and run 2 is 25 certain as well, it will become 50 certain.
:meth:`Volume.detect_fs_type` will return immediately if the score is higher than 50 and there is only 1
FS type with the highest score. Otherwise, it will continue with the next run. If at the end of all runs no
viable FS type was found, it will return the highest scoring FS type (if it is > 0), otherwise it will return
the FS type fallback.
:param source: The source of the description
:param description: The description to detect with
:return: Dict with mapping of FsType() objects to scores
### Response:
def detect(self, source, description):
if source == "guid" and description in self.guids:
return {self: 100}
description = description.lower()
if description == self.type:
return {self: 100}
elif re.search(r"\b" + self.type + r"\b", description):
return {self: 80}
elif any((re.search(r"\b" + alias + r"\b", description) for alias in self.aliases)):
return {self: 70}
return {} |
def _print_registers(self, registers):
for reg, value in registers.items():
print(" %s : 0x%08x (%d)" % (reg, value, value)) | Print registers. | ### Input:
Print registers.
### Response:
def _print_registers(self, registers):
for reg, value in registers.items():
print(" %s : 0x%08x (%d)" % (reg, value, value)) |
def legacy(**kwargs):
params = []
params += [BoolParameter(qualifier=, copy_for={: , : [, , ], : }, dataset=, value=kwargs.get(, True), description=)]
params += [ChoiceParameter(copy_for = {: [], : }, component=, qualifier=, value=kwargs.get(, ), choices=[, ], description=)]
params += [IntParameter(copy_for={: [], : }, component=, qualifier=, value=kwargs.get(, 60), limits=(10,None), description=)]
params += [ChoiceParameter(qualifier=, value=kwargs.get(, ), choices=[, ], description=)]
params += [IntParameter(visible_if=, qualifier=, value=kwargs.get(, 1), limits=(0,None), description=)]
params += [BoolParameter(qualifier=, value=kwargs.get(, False), description=)]
return ParameterSet(params) | Compute options for using the PHOEBE 1.0 legacy backend (must be
installed).
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.legacy` for a list of sources to
cite when using this backend.
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s | ### Input:
Compute options for using the PHOEBE 1.0 legacy backend (must be
installed).
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_compute`
Please see :func:`phoebe.backend.backends.legacy` for a list of sources to
cite when using this backend.
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Parameter`s
### Response:
def legacy(**kwargs):
params = []
params += [BoolParameter(qualifier=, copy_for={: , : [, , ], : }, dataset=, value=kwargs.get(, True), description=)]
params += [ChoiceParameter(copy_for = {: [], : }, component=, qualifier=, value=kwargs.get(, ), choices=[, ], description=)]
params += [IntParameter(copy_for={: [], : }, component=, qualifier=, value=kwargs.get(, 60), limits=(10,None), description=)]
params += [ChoiceParameter(qualifier=, value=kwargs.get(, ), choices=[, ], description=)]
params += [IntParameter(visible_if=, qualifier=, value=kwargs.get(, 1), limits=(0,None), description=)]
params += [BoolParameter(qualifier=, value=kwargs.get(, False), description=)]
return ParameterSet(params) |
def normalize_rust_function(self, function, line):
function = drop_prefix_and_return_type(function)
function = collapse(
function,
open_string=,
close_string=,
replacement=,
exceptions=(,)
)
if self.collapse_arguments:
function = collapse(
function,
open_string=,
close_string=,
replacement=
)
if self.signatures_with_line_numbers_re.match(function):
function = .format(function, line)
function = self.fixup_space.sub(, function)
function = self.fixup_comma.sub(, function)
function = self.fixup_hash.sub(, function)
return function | Normalizes a single rust frame with a function | ### Input:
Normalizes a single rust frame with a function
### Response:
def normalize_rust_function(self, function, line):
function = drop_prefix_and_return_type(function)
function = collapse(
function,
open_string=,
close_string=,
replacement=,
exceptions=(,)
)
if self.collapse_arguments:
function = collapse(
function,
open_string=,
close_string=,
replacement=
)
if self.signatures_with_line_numbers_re.match(function):
function = .format(function, line)
function = self.fixup_space.sub(, function)
function = self.fixup_comma.sub(, function)
function = self.fixup_hash.sub(, function)
return function |
def imsiDetachIndication():
a = TpPd(pd=0x5)
b = MessageType(mesType=0x1)
c = MobileStationClassmark1()
d = MobileId()
packet = a / b / c / d
return packet | IMSI DETACH INDICATION Section 9.2.12 | ### Input:
IMSI DETACH INDICATION Section 9.2.12
### Response:
def imsiDetachIndication():
a = TpPd(pd=0x5)
b = MessageType(mesType=0x1)
c = MobileStationClassmark1()
d = MobileId()
packet = a / b / c / d
return packet |
def dallinger_package_path():
dist = get_distribution("dallinger")
src_base = os.path.join(dist.location, dist.project_name)
return src_base | Return the absolute path of the root directory of the installed
Dallinger package:
>>> utils.dallinger_package_location()
'/Users/janedoe/projects/Dallinger3/dallinger' | ### Input:
Return the absolute path of the root directory of the installed
Dallinger package:
>>> utils.dallinger_package_location()
'/Users/janedoe/projects/Dallinger3/dallinger'
### Response:
def dallinger_package_path():
dist = get_distribution("dallinger")
src_base = os.path.join(dist.location, dist.project_name)
return src_base |
def data_to_tfrecord(images, labels, filename):
if os.path.isfile(filename):
print("%s exists" % filename)
return
print("Converting data into %s ..." % filename)
writer = tf.python_io.TFRecordWriter(filename)
for index, img in enumerate(images):
img_raw = img.tobytes()
label = int(labels[index])
example = tf.train.Example(
features=tf.train.Features(
feature={
"label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),
: tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),
}
)
)
writer.write(example.SerializeToString())
writer.close() | Save data into TFRecord. | ### Input:
Save data into TFRecord.
### Response:
def data_to_tfrecord(images, labels, filename):
if os.path.isfile(filename):
print("%s exists" % filename)
return
print("Converting data into %s ..." % filename)
writer = tf.python_io.TFRecordWriter(filename)
for index, img in enumerate(images):
img_raw = img.tobytes()
label = int(labels[index])
example = tf.train.Example(
features=tf.train.Features(
feature={
"label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),
: tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),
}
)
)
writer.write(example.SerializeToString())
writer.close() |
def _activate_stream(self, idx):
re not sampling "with_replacement", the distribution for this
chosen streamer is set to 0, causing the streamer not to be available
until it is exhausted.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
re sampling without replacement, zero this one out
if self.mode != "with_replacement":
self.distribution_[idx] = 0.0
if (self.distribution_ > 0).any():
self.distribution_[:] /= np.sum(self.distribution_)
return streamer, weight | Randomly select and create a stream.
StochasticMux adds mode handling to _activate_stream, making it so that
if we're not sampling "with_replacement", the distribution for this
chosen streamer is set to 0, causing the streamer not to be available
until it is exhausted.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace | ### Input:
Randomly select and create a stream.
StochasticMux adds mode handling to _activate_stream, making it so that
if we're not sampling "with_replacement", the distribution for this
chosen streamer is set to 0, causing the streamer not to be available
until it is exhausted.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
### Response:
def _activate_stream(self, idx):
re not sampling "with_replacement", the distribution for this
chosen streamer is set to 0, causing the streamer not to be available
until it is exhausted.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
re sampling without replacement, zero this one out
if self.mode != "with_replacement":
self.distribution_[idx] = 0.0
if (self.distribution_ > 0).any():
self.distribution_[:] /= np.sum(self.distribution_)
return streamer, weight |
def diffuse_advanced(self, heatColumnName=None, time=None, verbose=False):
PARAMS=set_param(["heatColumnName","time"],[heatColumnName,time])
response=api(url=self.__url+"/diffuse_advanced", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | Diffusion will send the selected network view and its selected nodes to
a web-based REST service to calculate network propagation. Results are
returned and represented by columns in the node table.
Columns are created for each execution of Diffusion and their names are
returned in the response.
:param heatColumnName (string, optional): A node column name intended
to override the default table column 'diffusion_input'. This represents
the query vector and corresponds to h in the diffusion equation. =
['HEKScore', 'JurkatScore', '(Use selected nodes)']
:param time (string, optional): The extent of spread over the network.
This corresponds to t in the diffusion equation.
:param verbose: print more | ### Input:
Diffusion will send the selected network view and its selected nodes to
a web-based REST service to calculate network propagation. Results are
returned and represented by columns in the node table.
Columns are created for each execution of Diffusion and their names are
returned in the response.
:param heatColumnName (string, optional): A node column name intended
to override the default table column 'diffusion_input'. This represents
the query vector and corresponds to h in the diffusion equation. =
['HEKScore', 'JurkatScore', '(Use selected nodes)']
:param time (string, optional): The extent of spread over the network.
This corresponds to t in the diffusion equation.
:param verbose: print more
### Response:
def diffuse_advanced(self, heatColumnName=None, time=None, verbose=False):
PARAMS=set_param(["heatColumnName","time"],[heatColumnName,time])
response=api(url=self.__url+"/diffuse_advanced", PARAMS=PARAMS, method="POST", verbose=verbose)
return response |
def add_creg(self, creg):
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j)) | Add all wires in a classical register. | ### Input:
Add all wires in a classical register.
### Response:
def add_creg(self, creg):
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j)) |
def drop_user(self, name):
statement = ddl.DropUser(name)
self._execute(statement) | Drop an MapD user
Parameters
----------
name : string
Database name | ### Input:
Drop an MapD user
Parameters
----------
name : string
Database name
### Response:
def drop_user(self, name):
statement = ddl.DropUser(name)
self._execute(statement) |
def _expand_parameters(circuits, run_config):
parameter_binds = run_config.parameter_binds
if parameter_binds or \
any(circuit.parameters for circuit in circuits):
all_bind_parameters = [bind.keys()
for bind in parameter_binds]
all_circuit_parameters = [circuit.parameters for circuit in circuits]
unique_parameters = set(param
for param_list in all_bind_parameters + all_circuit_parameters
for param in param_list)
if not all_bind_parameters \
or not all_circuit_parameters \
or any(unique_parameters != bind_params for bind_params in all_bind_parameters) \
or any(unique_parameters != parameters for parameters in all_circuit_parameters):
raise QiskitError(
( +
+
).format(all_bind_parameters, all_circuit_parameters))
circuits = [circuit.bind_parameters(binds)
for circuit in circuits
for binds in parameter_binds]
run_config = copy.deepcopy(run_config)
run_config.parameter_binds = []
return circuits, run_config | Verifies that there is a single common set of parameters shared between
all circuits and all parameter binds in the run_config. Returns an expanded
list of circuits (if parameterized) with all parameters bound, and a copy of
the run_config with parameter_binds cleared.
If neither the circuits nor the run_config specify parameters, the two are
returned unmodified.
Raises:
QiskitError: if run_config parameters are not compatible with circuit parameters
Returns:
Tuple(List[QuantumCircuit], RunConfig):
- List of input circuits expanded and with parameters bound
- RunConfig with parameter_binds removed | ### Input:
Verifies that there is a single common set of parameters shared between
all circuits and all parameter binds in the run_config. Returns an expanded
list of circuits (if parameterized) with all parameters bound, and a copy of
the run_config with parameter_binds cleared.
If neither the circuits nor the run_config specify parameters, the two are
returned unmodified.
Raises:
QiskitError: if run_config parameters are not compatible with circuit parameters
Returns:
Tuple(List[QuantumCircuit], RunConfig):
- List of input circuits expanded and with parameters bound
- RunConfig with parameter_binds removed
### Response:
def _expand_parameters(circuits, run_config):
parameter_binds = run_config.parameter_binds
if parameter_binds or \
any(circuit.parameters for circuit in circuits):
all_bind_parameters = [bind.keys()
for bind in parameter_binds]
all_circuit_parameters = [circuit.parameters for circuit in circuits]
unique_parameters = set(param
for param_list in all_bind_parameters + all_circuit_parameters
for param in param_list)
if not all_bind_parameters \
or not all_circuit_parameters \
or any(unique_parameters != bind_params for bind_params in all_bind_parameters) \
or any(unique_parameters != parameters for parameters in all_circuit_parameters):
raise QiskitError(
( +
+
).format(all_bind_parameters, all_circuit_parameters))
circuits = [circuit.bind_parameters(binds)
for circuit in circuits
for binds in parameter_binds]
run_config = copy.deepcopy(run_config)
run_config.parameter_binds = []
return circuits, run_config |
def get_all_code_styles():
result = dict((name, style_from_pygments_cls(get_style_by_name(name))) for name in get_all_styles())
result[] = Style.from_dict(win32_code_style)
return result | Return a mapping from style names to their classes. | ### Input:
Return a mapping from style names to their classes.
### Response:
def get_all_code_styles():
result = dict((name, style_from_pygments_cls(get_style_by_name(name))) for name in get_all_styles())
result[] = Style.from_dict(win32_code_style)
return result |
def get_local_tzone():
if localtime().tm_isdst:
if altzone < 0:
tzone = + \
str(int(float(altzone) / 60 // 60)).rjust(2,
) + \
str(int(float(
altzone) / 60 % 60)).ljust(2, )
else:
tzone = + \
str(int(float(altzone) / 60 // 60)).rjust(2,
) + \
str(int(float(
altzone) / 60 % 60)).ljust(2, )
else:
if altzone < 0:
tzone = \
+ str(int(float(timezone) / 60 // 60)).rjust(2,
) + \
str(int(float(
timezone) / 60 % 60)).ljust(2, )
else:
tzone = \
+ str(int(float(timezone) / 60 // 60)).rjust(2,
) + \
str(int(float(
timezone) / 60 % 60)).ljust(2, )
return tzone | Get the current time zone on the local host | ### Input:
Get the current time zone on the local host
### Response:
def get_local_tzone():
if localtime().tm_isdst:
if altzone < 0:
tzone = + \
str(int(float(altzone) / 60 // 60)).rjust(2,
) + \
str(int(float(
altzone) / 60 % 60)).ljust(2, )
else:
tzone = + \
str(int(float(altzone) / 60 // 60)).rjust(2,
) + \
str(int(float(
altzone) / 60 % 60)).ljust(2, )
else:
if altzone < 0:
tzone = \
+ str(int(float(timezone) / 60 // 60)).rjust(2,
) + \
str(int(float(
timezone) / 60 % 60)).ljust(2, )
else:
tzone = \
+ str(int(float(timezone) / 60 // 60)).rjust(2,
) + \
str(int(float(
timezone) / 60 % 60)).ljust(2, )
return tzone |
def _get_current_names(current, dsn, pc):
_table_name = ""
_variable_name = ""
try:
_table_name = current[.format(pc)]
_variable_name = current[.format(pc)]
except Exception as e:
print("Error: Unable to collapse time series: {}, {}".format(dsn, e))
logger_ts.error("get_current: {}, {}".format(dsn, e))
return _table_name, _variable_name | Get the table name and variable name from the given time series entry
:param dict current: Time series entry
:param str pc: paleoData or chronData
:return str _table_name:
:return str _variable_name: | ### Input:
Get the table name and variable name from the given time series entry
:param dict current: Time series entry
:param str pc: paleoData or chronData
:return str _table_name:
:return str _variable_name:
### Response:
def _get_current_names(current, dsn, pc):
_table_name = ""
_variable_name = ""
try:
_table_name = current[.format(pc)]
_variable_name = current[.format(pc)]
except Exception as e:
print("Error: Unable to collapse time series: {}, {}".format(dsn, e))
logger_ts.error("get_current: {}, {}".format(dsn, e))
return _table_name, _variable_name |
async def setex(self, name, time, value):
if isinstance(time, datetime.timedelta):
time = time.seconds + time.days * 24 * 3600
return await self.execute_command(, name, time, value) | Set the value of key ``name`` to ``value`` that expires in ``time``
seconds. ``time`` can be represented by an integer or a Python
timedelta object. | ### Input:
Set the value of key ``name`` to ``value`` that expires in ``time``
seconds. ``time`` can be represented by an integer or a Python
timedelta object.
### Response:
async def setex(self, name, time, value):
if isinstance(time, datetime.timedelta):
time = time.seconds + time.days * 24 * 3600
return await self.execute_command(, name, time, value) |
def _set_origin(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=origin.origin, is_container=, presence=False, yang_name="origin", rest_name="origin", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u: u, u: None}}, namespace=, defining_module=, yang_type=, is_config=True)
except (TypeError, ValueError):
raise ValueError({
: ,
: "container",
: ,
})
self.__origin = t
if hasattr(self, ):
self._set() | Setter method for origin, mapped from YANG variable /routing_system/route_map/content/set/origin (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_origin is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_origin() directly.
YANG Description: BGP origin code | ### Input:
Setter method for origin, mapped from YANG variable /routing_system/route_map/content/set/origin (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_origin is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_origin() directly.
YANG Description: BGP origin code
### Response:
def _set_origin(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=origin.origin, is_container=, presence=False, yang_name="origin", rest_name="origin", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u: u, u: None}}, namespace=, defining_module=, yang_type=, is_config=True)
except (TypeError, ValueError):
raise ValueError({
: ,
: "container",
: ,
})
self.__origin = t
if hasattr(self, ):
self._set() |
def opt_top1(n_items, data, alpha=1e-6, method="Newton-CG",
initial_params=None, max_iter=None, tol=1e-5):
fcts = Top1Fcts(data, alpha)
return _opt(n_items, fcts, method, initial_params, max_iter, tol) | Compute the ML estimate of model parameters using ``scipy.optimize``.
This function computes the maximum-likelihood estimate of model parameters
given top-1 data (see :ref:`data-top1`), using optimizers provided by the
``scipy.optimize`` module.
If ``alpha > 0``, the function returns the maximum a-posteriori (MAP)
estimate under an isotropic Gaussian prior with variance ``1 / alpha``. See
:ref:`regularization` for details.
Parameters
----------
n_items : int
Number of distinct items.
data : list of lists
Top-1 data.
alpha : float, optional
Regularization strength.
method : str, optional
Optimization method. Either "BFGS" or "Newton-CG".
initial_params : array_like, optional
Parameters used to initialize the iterative procedure.
max_iter : int, optional
Maximum number of iterations allowed.
tol : float, optional
Tolerance for termination (method-specific).
Returns
-------
params : numpy.ndarray
The (penalized) ML estimate of model parameters.
Raises
------
ValueError
If the method is not "BFGS" or "Newton-CG". | ### Input:
Compute the ML estimate of model parameters using ``scipy.optimize``.
This function computes the maximum-likelihood estimate of model parameters
given top-1 data (see :ref:`data-top1`), using optimizers provided by the
``scipy.optimize`` module.
If ``alpha > 0``, the function returns the maximum a-posteriori (MAP)
estimate under an isotropic Gaussian prior with variance ``1 / alpha``. See
:ref:`regularization` for details.
Parameters
----------
n_items : int
Number of distinct items.
data : list of lists
Top-1 data.
alpha : float, optional
Regularization strength.
method : str, optional
Optimization method. Either "BFGS" or "Newton-CG".
initial_params : array_like, optional
Parameters used to initialize the iterative procedure.
max_iter : int, optional
Maximum number of iterations allowed.
tol : float, optional
Tolerance for termination (method-specific).
Returns
-------
params : numpy.ndarray
The (penalized) ML estimate of model parameters.
Raises
------
ValueError
If the method is not "BFGS" or "Newton-CG".
### Response:
def opt_top1(n_items, data, alpha=1e-6, method="Newton-CG",
initial_params=None, max_iter=None, tol=1e-5):
fcts = Top1Fcts(data, alpha)
return _opt(n_items, fcts, method, initial_params, max_iter, tol) |
def readline(self, size=-1):
if size == 0:
return self.string_type()
index = self.expect([self.crlf, self.delimiter])
if index == 0:
return self.before + self.crlf
else:
return self.before | This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
this is what the pseudotty device returns. So contrary to what you may
expect you will receive newlines as \\r\\n.
If the size argument is 0 then an empty string is returned. In all
other cases the size argument is ignored, which is not standard
behavior for a file-like object. | ### Input:
This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
this is what the pseudotty device returns. So contrary to what you may
expect you will receive newlines as \\r\\n.
If the size argument is 0 then an empty string is returned. In all
other cases the size argument is ignored, which is not standard
behavior for a file-like object.
### Response:
def readline(self, size=-1):
if size == 0:
return self.string_type()
index = self.expect([self.crlf, self.delimiter])
if index == 0:
return self.before + self.crlf
else:
return self.before |
def GetArtifactsInProperOrder(self):
artifact_list = []
while self.reachable_nodes:
node_name = self.reachable_nodes.pop()
node = self.graph[node_name]
if node.is_artifact:
artifact_list.append(node_name)
for next_node_name in node.outgoing:
if next_node_name not in self.graph:
continue
next_node = self.graph[next_node_name]
if next_node.is_provided:
continue
next_node.incoming.remove(node_name)
if not (next_node.is_artifact and next_node.incoming):
next_node.is_provided = True
self.reachable_nodes.add(next_node_name)
return artifact_list | Bring the artifacts in a linear order that resolves dependencies.
This method obtains a linear ordering of the nodes and then returns the list
of artifact names.
Returns:
A list of `ArtifactName` instances such that if they are collected in the
given order their dependencies are resolved. | ### Input:
Bring the artifacts in a linear order that resolves dependencies.
This method obtains a linear ordering of the nodes and then returns the list
of artifact names.
Returns:
A list of `ArtifactName` instances such that if they are collected in the
given order their dependencies are resolved.
### Response:
def GetArtifactsInProperOrder(self):
artifact_list = []
while self.reachable_nodes:
node_name = self.reachable_nodes.pop()
node = self.graph[node_name]
if node.is_artifact:
artifact_list.append(node_name)
for next_node_name in node.outgoing:
if next_node_name not in self.graph:
continue
next_node = self.graph[next_node_name]
if next_node.is_provided:
continue
next_node.incoming.remove(node_name)
if not (next_node.is_artifact and next_node.incoming):
next_node.is_provided = True
self.reachable_nodes.add(next_node_name)
return artifact_list |
def file_fingerprint(fullpath):
stat = os.stat(fullpath)
return .join([str(value) for value in [stat.st_ino, stat.st_mtime, stat.st_size] if value]) | Get a metadata fingerprint for a file | ### Input:
Get a metadata fingerprint for a file
### Response:
def file_fingerprint(fullpath):
stat = os.stat(fullpath)
return .join([str(value) for value in [stat.st_ino, stat.st_mtime, stat.st_size] if value]) |
def get_ip_interface_output_interface_ip_address_ipv4(self, **kwargs):
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop()
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop()
ip_address = ET.SubElement(interface, "ip-address")
ipv4 = ET.SubElement(ip_address, "ipv4")
ipv4.text = kwargs.pop()
callback = kwargs.pop(, self._callback)
return callback(config) | Auto Generated Code | ### Input:
Auto Generated Code
### Response:
def get_ip_interface_output_interface_ip_address_ipv4(self, **kwargs):
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop()
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop()
ip_address = ET.SubElement(interface, "ip-address")
ipv4 = ET.SubElement(ip_address, "ipv4")
ipv4.text = kwargs.pop()
callback = kwargs.pop(, self._callback)
return callback(config) |
def do_DELETE(self):
self.do_initial_operations()
coap_response = self.client.delete(self.coap_uri.path)
self.client.stop()
logger.debug("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | Perform a DELETE request | ### Input:
Perform a DELETE request
### Response:
def do_DELETE(self):
self.do_initial_operations()
coap_response = self.client.delete(self.coap_uri.path)
self.client.stop()
logger.debug("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) |
def wait_for_tasks(self, tasks):
property_collector = self.service_instance.RetrieveContent().propertyCollector
task_list = [str(task) for task in tasks]
obj_specs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task)
for task in tasks]
property_spec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,
pathSet=[],
all=True)
filter_spec = vmodl.query.PropertyCollector.FilterSpec()
filter_spec.objectSet = obj_specs
filter_spec.propSet = [property_spec]
pcfilter = property_collector.CreateFilter(filter_spec, True)
try:
version, state = None, None
while len(task_list):
update = property_collector.WaitForUpdates(version)
for filter_set in update.filterSet:
for obj_set in filter_set.objectSet:
task = obj_set.obj
for change in obj_set.changeSet:
if change.name == :
state = change.val.state
elif change.name == :
state = change.val
else:
continue
if not str(task) in task_list:
continue
if state == vim.TaskInfo.State.success:
task_list.remove(str(task))
elif state == vim.TaskInfo.State.error:
raise task.info.error
version = update.version
finally:
if pcfilter:
pcfilter.Destroy() | Given the service instance si and tasks, it returns after all the
tasks are complete | ### Input:
Given the service instance si and tasks, it returns after all the
tasks are complete
### Response:
def wait_for_tasks(self, tasks):
property_collector = self.service_instance.RetrieveContent().propertyCollector
task_list = [str(task) for task in tasks]
obj_specs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task)
for task in tasks]
property_spec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,
pathSet=[],
all=True)
filter_spec = vmodl.query.PropertyCollector.FilterSpec()
filter_spec.objectSet = obj_specs
filter_spec.propSet = [property_spec]
pcfilter = property_collector.CreateFilter(filter_spec, True)
try:
version, state = None, None
while len(task_list):
update = property_collector.WaitForUpdates(version)
for filter_set in update.filterSet:
for obj_set in filter_set.objectSet:
task = obj_set.obj
for change in obj_set.changeSet:
if change.name == :
state = change.val.state
elif change.name == :
state = change.val
else:
continue
if not str(task) in task_list:
continue
if state == vim.TaskInfo.State.success:
task_list.remove(str(task))
elif state == vim.TaskInfo.State.error:
raise task.info.error
version = update.version
finally:
if pcfilter:
pcfilter.Destroy() |
def select(self, element):
self._field.validate_value(element)
self._elements.add(element)
self._sync_field() | Add an element to the set of selected elements
Proxy to internal set.add and sync field | ### Input:
Add an element to the set of selected elements
Proxy to internal set.add and sync field
### Response:
def select(self, element):
self._field.validate_value(element)
self._elements.add(element)
self._sync_field() |
def sortrows(a, i=0, index_out=False, recurse=True):
I = np.argsort(a[:, i])
a = a[I, :]
if recurse & (len(a[0]) > i + 1):
for b in np.unique(a[:, i]):
ids = a[:, i] == b
colids = range(i) + range(i+1, len(a[0]))
a[np.ix_(ids, colids)], I2 = sortrows(a[np.ix_(ids, colids)],
0, True, True)
I[ids] = I[np.nonzero(ids)[0][I2]]
if index_out:
return a, I
else:
return a | Sorts array "a" by columns i
Parameters
------------
a : np.ndarray
array to be sorted
i : int (optional)
column to be sorted by, taken as 0 by default
index_out : bool (optional)
return the index I such that a(I) = sortrows(a,i). Default = False
recurse : bool (optional)
recursively sort by each of the columns. i.e.
once column i is sort, we sort the smallest column number
etc. True by default.
Returns
--------
a : np.ndarray
The array 'a' sorted in descending order by column i
I : np.ndarray (optional)
The index such that a[I, :] = sortrows(a, i). Only return if
index_out = True
Examples
---------
>>> a = array([[1,2],[3,1],[2,3]])
>>> b = sortrows(a,0)
>>> b
array([[1, 2],
[2, 3],
[3, 1]])
c, I = sortrows(a,1,True)
>>> c
array([[3, 1],
[1, 2],
[2, 3]])
>>> I
array([1, 0, 2])
>>> a[I,:] - c
array([[0, 0],
[0, 0],
[0, 0]]) | ### Input:
Sorts array "a" by columns i
Parameters
------------
a : np.ndarray
array to be sorted
i : int (optional)
column to be sorted by, taken as 0 by default
index_out : bool (optional)
return the index I such that a(I) = sortrows(a,i). Default = False
recurse : bool (optional)
recursively sort by each of the columns. i.e.
once column i is sort, we sort the smallest column number
etc. True by default.
Returns
--------
a : np.ndarray
The array 'a' sorted in descending order by column i
I : np.ndarray (optional)
The index such that a[I, :] = sortrows(a, i). Only return if
index_out = True
Examples
---------
>>> a = array([[1,2],[3,1],[2,3]])
>>> b = sortrows(a,0)
>>> b
array([[1, 2],
[2, 3],
[3, 1]])
c, I = sortrows(a,1,True)
>>> c
array([[3, 1],
[1, 2],
[2, 3]])
>>> I
array([1, 0, 2])
>>> a[I,:] - c
array([[0, 0],
[0, 0],
[0, 0]])
### Response:
def sortrows(a, i=0, index_out=False, recurse=True):
I = np.argsort(a[:, i])
a = a[I, :]
if recurse & (len(a[0]) > i + 1):
for b in np.unique(a[:, i]):
ids = a[:, i] == b
colids = range(i) + range(i+1, len(a[0]))
a[np.ix_(ids, colids)], I2 = sortrows(a[np.ix_(ids, colids)],
0, True, True)
I[ids] = I[np.nonzero(ids)[0][I2]]
if index_out:
return a, I
else:
return a |
def setPoint(self, x, group, y):
if x == -1:
self.plot([0],[y], symbol=)
else:
yindex = self.groups.index(group)
xdata, ydata = self.lines[yindex].getData()
if ydata is None:
xdata = [x]
ydata = [y]
else:
xdata = np.append(xdata, x)
ydata = np.append(ydata, y)
self.lines[yindex].setData(xdata, ydata) | Sets the given point, connects line to previous point in group
:param x: x value of point
:type x: float
:param group: group which plot point for
:type group: float
:param y: y value of point
:type y: float | ### Input:
Sets the given point, connects line to previous point in group
:param x: x value of point
:type x: float
:param group: group which plot point for
:type group: float
:param y: y value of point
:type y: float
### Response:
def setPoint(self, x, group, y):
if x == -1:
self.plot([0],[y], symbol=)
else:
yindex = self.groups.index(group)
xdata, ydata = self.lines[yindex].getData()
if ydata is None:
xdata = [x]
ydata = [y]
else:
xdata = np.append(xdata, x)
ydata = np.append(ydata, y)
self.lines[yindex].setData(xdata, ydata) |
def setdict(self, D=None):
if D is not None:
self.D = np.asarray(D, dtype=self.dtype)
self.Df = sl.rfftn(self.D, self.cri.Nv, self.cri.axisN)
self.DSf = np.conj(self.Df) * self.Sf
if self.cri.Cd > 1:
self.DSf = np.sum(self.DSf, axis=self.cri.axisC, keepdims=True)
if self.opt[] and self.cri.Cd == 1:
self.c = sl.solvedbd_sm_c(
self.Df, np.conj(self.Df), self.mu*self.GHGf + self.rho,
self.cri.axisM)
else:
self.c = None | Set dictionary array. | ### Input:
Set dictionary array.
### Response:
def setdict(self, D=None):
if D is not None:
self.D = np.asarray(D, dtype=self.dtype)
self.Df = sl.rfftn(self.D, self.cri.Nv, self.cri.axisN)
self.DSf = np.conj(self.Df) * self.Sf
if self.cri.Cd > 1:
self.DSf = np.sum(self.DSf, axis=self.cri.axisC, keepdims=True)
if self.opt[] and self.cri.Cd == 1:
self.c = sl.solvedbd_sm_c(
self.Df, np.conj(self.Df), self.mu*self.GHGf + self.rho,
self.cri.axisM)
else:
self.c = None |
def C_dict2array(C):
return np.hstack([np.asarray(C[k]).ravel() for k in C_keys]) | Convert an OrderedDict containing C values to a 1D array. | ### Input:
Convert an OrderedDict containing C values to a 1D array.
### Response:
def C_dict2array(C):
return np.hstack([np.asarray(C[k]).ravel() for k in C_keys]) |
def run(self, depth=None):
if len(self.simgr.right) != 1 or len(self.simgr.left) != 1:
self._report_incongruency("Single path in pg.left and pg.right required.")
return False
if "UNICORN" in self.simgr.one_right.options and depth is not None:
self.simgr.one_right.unicorn.max_steps = depth
if "UNICORN" in self.simgr.one_left.options and depth is not None:
self.simgr.one_left.unicorn.max_steps = depth
l.debug("Performing initial path comparison.")
if not self.compare_paths(self.simgr.left[0], self.simgr.right[0]):
self._report_incongruency("Initial path comparison check failed.")
return False
while len(self.simgr.left) > 0 and len(self.simgr.right) > 0:
if depth is not None:
self._update_progress(100. * float(self.simgr.one_left.history.block_count) / depth)
if len(self.simgr.deadended) != 0:
self._report_incongruency("Unexpected deadended paths before step.")
return False
if len(self.simgr.right) == 0 and len(self.simgr.left) == 0:
l.debug("All done!")
return True
if len(self.simgr.right) != 1 or len(self.simgr.left) != 1:
self._report_incongruency("Different numbers of paths in left and right stash..")
return False
l.debug(
"Stepping right path with weighted length %d/%d",
self.simgr.right[0].history.block_count,
depth
)
self.prev_pg = self.simgr.copy()
self.simgr.step(stash=)
CongruencyCheck._sync_steps(self.simgr)
if len(self.simgr.errored) != 0:
self._report_incongruency("Unexpected errored paths.")
return False
try:
if not self.compare_path_group(self.simgr) and self._validate_incongruency():
self._report_incongruency("Path group comparison failed.")
return False
except AngrIncongruencyError:
if self._validate_incongruency():
raise
if depth is not None:
self.simgr.drop(stash=, filter_func=lambda p: p.history.block_count >= depth)
self.simgr.drop(stash=, filter_func=lambda p: p.history.block_count >= depth)
self.simgr.right.sort(key=lambda p: p.addr)
self.simgr.left.sort(key=lambda p: p.addr)
self.simgr.stashed_right[:] = self.simgr.stashed_right[::-1]
self.simgr.stashed_left[:] = self.simgr.stashed_left[::-1]
self.simgr.move(, )
self.simgr.move(, )
if len(self.simgr.left) > 1:
self.simgr.split(from_stash=, limit=1, to_stash=)
self.simgr.split(from_stash=, limit=1, to_stash=) | Checks that the paths in the specified path group stay the same over the next
`depth` bytes.
The path group should have a "left" and a "right" stash, each with a single
path. | ### Input:
Checks that the paths in the specified path group stay the same over the next
`depth` bytes.
The path group should have a "left" and a "right" stash, each with a single
path.
### Response:
def run(self, depth=None):
if len(self.simgr.right) != 1 or len(self.simgr.left) != 1:
self._report_incongruency("Single path in pg.left and pg.right required.")
return False
if "UNICORN" in self.simgr.one_right.options and depth is not None:
self.simgr.one_right.unicorn.max_steps = depth
if "UNICORN" in self.simgr.one_left.options and depth is not None:
self.simgr.one_left.unicorn.max_steps = depth
l.debug("Performing initial path comparison.")
if not self.compare_paths(self.simgr.left[0], self.simgr.right[0]):
self._report_incongruency("Initial path comparison check failed.")
return False
while len(self.simgr.left) > 0 and len(self.simgr.right) > 0:
if depth is not None:
self._update_progress(100. * float(self.simgr.one_left.history.block_count) / depth)
if len(self.simgr.deadended) != 0:
self._report_incongruency("Unexpected deadended paths before step.")
return False
if len(self.simgr.right) == 0 and len(self.simgr.left) == 0:
l.debug("All done!")
return True
if len(self.simgr.right) != 1 or len(self.simgr.left) != 1:
self._report_incongruency("Different numbers of paths in left and right stash..")
return False
l.debug(
"Stepping right path with weighted length %d/%d",
self.simgr.right[0].history.block_count,
depth
)
self.prev_pg = self.simgr.copy()
self.simgr.step(stash=)
CongruencyCheck._sync_steps(self.simgr)
if len(self.simgr.errored) != 0:
self._report_incongruency("Unexpected errored paths.")
return False
try:
if not self.compare_path_group(self.simgr) and self._validate_incongruency():
self._report_incongruency("Path group comparison failed.")
return False
except AngrIncongruencyError:
if self._validate_incongruency():
raise
if depth is not None:
self.simgr.drop(stash=, filter_func=lambda p: p.history.block_count >= depth)
self.simgr.drop(stash=, filter_func=lambda p: p.history.block_count >= depth)
self.simgr.right.sort(key=lambda p: p.addr)
self.simgr.left.sort(key=lambda p: p.addr)
self.simgr.stashed_right[:] = self.simgr.stashed_right[::-1]
self.simgr.stashed_left[:] = self.simgr.stashed_left[::-1]
self.simgr.move(, )
self.simgr.move(, )
if len(self.simgr.left) > 1:
self.simgr.split(from_stash=, limit=1, to_stash=)
self.simgr.split(from_stash=, limit=1, to_stash=) |
def _decode_exp(self, access_token=None):
c = self.get_credentials()
jwt = access_token or c.access_token
x = self.decode_jwt_payload(jwt)
if in x:
try:
exp = int(x[])
except ValueError:
raise PanCloudError(
"Expiration time (exp) must be an integer")
else:
self.jwt_exp = exp
return exp
else:
raise PanCloudError("No exp field found in payload") | Extract exp field from access token.
Args:
access_token (str): Access token to decode. Defaults to ``None``.
Returns:
int: JWT expiration in epoch seconds. | ### Input:
Extract exp field from access token.
Args:
access_token (str): Access token to decode. Defaults to ``None``.
Returns:
int: JWT expiration in epoch seconds.
### Response:
def _decode_exp(self, access_token=None):
c = self.get_credentials()
jwt = access_token or c.access_token
x = self.decode_jwt_payload(jwt)
if in x:
try:
exp = int(x[])
except ValueError:
raise PanCloudError(
"Expiration time (exp) must be an integer")
else:
self.jwt_exp = exp
return exp
else:
raise PanCloudError("No exp field found in payload") |
def intersects_first(self,
ray_origins,
ray_directions):
ray_origins = np.asanyarray(deepcopy(ray_origins))
ray_directions = np.asanyarray(ray_directions)
triangle_index = self._scene.run(ray_origins,
ray_directions)
return triangle_index | Find the index of the first triangle a ray hits.
Parameters
----------
ray_origins: (n,3) float, origins of rays
ray_directions: (n,3) float, direction (vector) of rays
Returns
----------
triangle_index: (n,) int, index of triangle ray hit, or -1 if not hit | ### Input:
Find the index of the first triangle a ray hits.
Parameters
----------
ray_origins: (n,3) float, origins of rays
ray_directions: (n,3) float, direction (vector) of rays
Returns
----------
triangle_index: (n,) int, index of triangle ray hit, or -1 if not hit
### Response:
def intersects_first(self,
ray_origins,
ray_directions):
ray_origins = np.asanyarray(deepcopy(ray_origins))
ray_directions = np.asanyarray(ray_directions)
triangle_index = self._scene.run(ray_origins,
ray_directions)
return triangle_index |
async def _previous(self, ctx):
player = self.bot.lavalink.players.get(ctx.guild.id)
try:
await player.play_previous()
except lavalink.NoPreviousTrack:
await ctx.send() | Plays the previous song. | ### Input:
Plays the previous song.
### Response:
async def _previous(self, ctx):
player = self.bot.lavalink.players.get(ctx.guild.id)
try:
await player.play_previous()
except lavalink.NoPreviousTrack:
await ctx.send() |
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
self.logger.error(f) | Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised | ### Input:
Callback for receiving errors from the websocket connection
Args:
ws: websocket connection
error: exception raised
### Response:
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
self.logger.error(f) |
def _update_database_helper_table(
self):
self.log.debug()
tableName = self.dbTableName
sqlQuery = u % locals()
writequery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
)
self.log.debug(
)
return None | *Update the sherlock catalogues database helper table with the time-stamp of when this catlogue was last updated*
**Usage:**
.. code-block:: python
self._update_database_helper_table() | ### Input:
*Update the sherlock catalogues database helper table with the time-stamp of when this catlogue was last updated*
**Usage:**
.. code-block:: python
self._update_database_helper_table()
### Response:
def _update_database_helper_table(
self):
self.log.debug()
tableName = self.dbTableName
sqlQuery = u % locals()
writequery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
)
self.log.debug(
)
return None |
def get_jump_targets(code, opc):
offsets = []
for offset, op, arg in unpack_opargs_wordcode(code, opc):
if arg is not None:
if op in opc.JREL_OPS:
jump_offset = offset + 2 + arg
elif op in opc.JABS_OPS:
jump_offset = arg
else:
continue
if jump_offset not in offsets:
offsets.append(jump_offset)
return offsets | Returns a list of instruction offsets in the supplied bytecode
which are the targets of some sort of jump instruction. | ### Input:
Returns a list of instruction offsets in the supplied bytecode
which are the targets of some sort of jump instruction.
### Response:
def get_jump_targets(code, opc):
offsets = []
for offset, op, arg in unpack_opargs_wordcode(code, opc):
if arg is not None:
if op in opc.JREL_OPS:
jump_offset = offset + 2 + arg
elif op in opc.JABS_OPS:
jump_offset = arg
else:
continue
if jump_offset not in offsets:
offsets.append(jump_offset)
return offsets |
def find_child_reference(self, name):
name = name.upper()
element = self.structure_by_name.get(name, None) or self.structure_by_longname.get(name, None)
if element is None:
if self.allow_infinite_children and _valid_child_name(name, self.name):
if _valid_z_field_name(name):
datatype =
else:
datatype =
element = {: Field, : name, : (, None, datatype, None, None, -1)}
else:
element = find_reference(name, self.child_classes.values(), self.version)
if element:
raise ChildNotValid(name, self)
else:
raise ChildNotFound(name)
return element | Override the corresponding :class`Element <hl7apy.core.Element>`'s method. This is done for segments
that allow children other than the ones expected in the HL7 structure: the ones with the last known
field of type `varies` and the Z-Segments.
The :class:`Field <hl7apy.core.Field>` will be created although it is not found in the HL7 structures,
but only if its match the pattern `<SegmentName>_<index>`.
In this case the method returns a reference for a :class:`Field <hl7apy.core.Field>` of type `None`
in case of Z-Segment and `varies` otherwise.
An example of a segment with the last field of type ``varies`` is the `QPD` in the version 2.5,
whose last field is QPD_3.
That means that it allows fields with name QPD_4, QPD_5,...QPD_n. | ### Input:
Override the corresponding :class`Element <hl7apy.core.Element>`'s method. This is done for segments
that allow children other than the ones expected in the HL7 structure: the ones with the last known
field of type `varies` and the Z-Segments.
The :class:`Field <hl7apy.core.Field>` will be created although it is not found in the HL7 structures,
but only if its match the pattern `<SegmentName>_<index>`.
In this case the method returns a reference for a :class:`Field <hl7apy.core.Field>` of type `None`
in case of Z-Segment and `varies` otherwise.
An example of a segment with the last field of type ``varies`` is the `QPD` in the version 2.5,
whose last field is QPD_3.
That means that it allows fields with name QPD_4, QPD_5,...QPD_n.
### Response:
def find_child_reference(self, name):
name = name.upper()
element = self.structure_by_name.get(name, None) or self.structure_by_longname.get(name, None)
if element is None:
if self.allow_infinite_children and _valid_child_name(name, self.name):
if _valid_z_field_name(name):
datatype =
else:
datatype =
element = {: Field, : name, : (, None, datatype, None, None, -1)}
else:
element = find_reference(name, self.child_classes.values(), self.version)
if element:
raise ChildNotValid(name, self)
else:
raise ChildNotFound(name)
return element |
def calc_geo_branches_in_buffer(node, mv_grid, radius, radius_inc, proj):
branches = []
while not branches:
node_shp = transform(proj, node.geo_data)
buffer_zone_shp = node_shp.buffer(radius)
for branch in mv_grid.graph_edges():
nodes = branch[]
branch_shp = transform(proj, LineString([nodes[0].geo_data, nodes[1].geo_data]))
if buffer_zone_shp.intersects(branch_shp):
branches.append(branch)
radius += radius_inc
return branches | Determines branches in nodes' associated graph that are at least partly
within buffer of `radius` from `node`.
If there are no nodes, the buffer is successively extended by `radius_inc`
until nodes are found.
Parameters
----------
node : LVStationDing0, GeneratorDing0, or CableDistributorDing0
origin node (e.g. LVStationDing0 object) with associated shapely object
(attribute `geo_data`) in any CRS (e.g. WGS84)
radius : float
buffer radius in m
radius_inc : float
radius increment in m
proj : int
pyproj projection object: nodes' CRS to equidistant CRS
(e.g. WGS84 -> ETRS)
Returns
-------
:any:`list` of :networkx:`NetworkX Graph Obj< >`
List of branches (NetworkX branch objects) | ### Input:
Determines branches in nodes' associated graph that are at least partly
within buffer of `radius` from `node`.
If there are no nodes, the buffer is successively extended by `radius_inc`
until nodes are found.
Parameters
----------
node : LVStationDing0, GeneratorDing0, or CableDistributorDing0
origin node (e.g. LVStationDing0 object) with associated shapely object
(attribute `geo_data`) in any CRS (e.g. WGS84)
radius : float
buffer radius in m
radius_inc : float
radius increment in m
proj : int
pyproj projection object: nodes' CRS to equidistant CRS
(e.g. WGS84 -> ETRS)
Returns
-------
:any:`list` of :networkx:`NetworkX Graph Obj< >`
List of branches (NetworkX branch objects)
### Response:
def calc_geo_branches_in_buffer(node, mv_grid, radius, radius_inc, proj):
branches = []
while not branches:
node_shp = transform(proj, node.geo_data)
buffer_zone_shp = node_shp.buffer(radius)
for branch in mv_grid.graph_edges():
nodes = branch[]
branch_shp = transform(proj, LineString([nodes[0].geo_data, nodes[1].geo_data]))
if buffer_zone_shp.intersects(branch_shp):
branches.append(branch)
radius += radius_inc
return branches |
def supervisor_command(parser_args):
import logging
from synergy.supervisor.supervisor_configurator import SupervisorConfigurator, set_box_id
if parser_args.boxid:
set_box_id(logging, parser_args.argument)
return
sc = SupervisorConfigurator()
if parser_args.reset:
sc.reset_db()
elif parser_args.start:
sc.mark_for_start(parser_args.argument)
elif parser_args.stop:
sc.mark_for_stop(parser_args.argument)
elif parser_args.query:
sc.query() | Supervisor-related commands | ### Input:
Supervisor-related commands
### Response:
def supervisor_command(parser_args):
import logging
from synergy.supervisor.supervisor_configurator import SupervisorConfigurator, set_box_id
if parser_args.boxid:
set_box_id(logging, parser_args.argument)
return
sc = SupervisorConfigurator()
if parser_args.reset:
sc.reset_db()
elif parser_args.start:
sc.mark_for_start(parser_args.argument)
elif parser_args.stop:
sc.mark_for_stop(parser_args.argument)
elif parser_args.query:
sc.query() |
def create_snapshot(self, repository, snapshot, body, params={}, callback=None, **kwargs):
query_params = (, ,)
params = self._filter_params(query_params, params)
url = self.mk_url(*[, repository, snapshot], **params)
self.client.fetch(
self.mk_req(url, body=body, method=, **kwargs),
callback = callback
) | Create a snapshot in repository
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html>`_
:arg repository: A repository name
:arg snapshot: A snapshot name
:arg body: The snapshot definition
:arg master_timeout: Explicit operation timeout for connection to master
node
:arg wait_for_completion: Should this request wait until the operation
has completed before returning, default False | ### Input:
Create a snapshot in repository
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html>`_
:arg repository: A repository name
:arg snapshot: A snapshot name
:arg body: The snapshot definition
:arg master_timeout: Explicit operation timeout for connection to master
node
:arg wait_for_completion: Should this request wait until the operation
has completed before returning, default False
### Response:
def create_snapshot(self, repository, snapshot, body, params={}, callback=None, **kwargs):
query_params = (, ,)
params = self._filter_params(query_params, params)
url = self.mk_url(*[, repository, snapshot], **params)
self.client.fetch(
self.mk_req(url, body=body, method=, **kwargs),
callback = callback
) |
def is_file_url(url):
from .misc import to_text
if not url:
return False
if not isinstance(url, six.string_types):
try:
url = getattr(url, "url")
except AttributeError:
raise ValueError("Cannot parse url from unknown type: {0!r}".format(url))
url = to_text(url, encoding="utf-8")
return urllib_parse.urlparse(url.lower()).scheme == "file" | Returns true if the given url is a file url | ### Input:
Returns true if the given url is a file url
### Response:
def is_file_url(url):
from .misc import to_text
if not url:
return False
if not isinstance(url, six.string_types):
try:
url = getattr(url, "url")
except AttributeError:
raise ValueError("Cannot parse url from unknown type: {0!r}".format(url))
url = to_text(url, encoding="utf-8")
return urllib_parse.urlparse(url.lower()).scheme == "file" |
def avail_images(call=None):
if call == :
raise SaltCloudException(
)
ret = {}
vm_ = get_configured_provider()
manager = packet.Manager(auth_token=vm_[])
ret = {}
for os_system in manager.list_operating_systems():
ret[os_system.name] = os_system.__dict__
return ret | Return available Packet os images.
CLI Example:
.. code-block:: bash
salt-cloud --list-images packet-provider
salt-cloud -f avail_images packet-provider | ### Input:
Return available Packet os images.
CLI Example:
.. code-block:: bash
salt-cloud --list-images packet-provider
salt-cloud -f avail_images packet-provider
### Response:
def avail_images(call=None):
if call == :
raise SaltCloudException(
)
ret = {}
vm_ = get_configured_provider()
manager = packet.Manager(auth_token=vm_[])
ret = {}
for os_system in manager.list_operating_systems():
ret[os_system.name] = os_system.__dict__
return ret |
def perez(surface_tilt, surface_azimuth, dhi, dni, dni_extra,
solar_zenith, solar_azimuth, airmass,
model=, return_components=False):
s model coefficient sets.
Parameters
----------
surface_tilt : numeric
Surface tilt angles in decimal degrees. surface_tilt must be >=0
and <=180. The tilt angle is defined as degrees from horizontal
(e.g. surface facing up = 0, surface facing horizon = 90)
surface_azimuth : numeric
Surface azimuth angles in decimal degrees. surface_azimuth must
be >=0 and <=360. The azimuth convention is defined as degrees
east of north (e.g. North = 0, South=180 East = 90, West = 270).
dhi : numeric
Diffuse horizontal irradiance in W/m^2. DHI must be >=0.
dni : numeric
Direct normal irradiance in W/m^2. DNI must be >=0.
dni_extra : numeric
Extraterrestrial normal irradiance in W/m^2.
solar_zenith : numeric
apparent (refraction-corrected) zenith angles in decimal
degrees. solar_zenith must be >=0 and <=180.
solar_azimuth : numeric
Sun azimuth angles in decimal degrees. solar_azimuth must be >=0
and <=360. The azimuth convention is defined as degrees east of
north (e.g. North = 0, East = 90, West = 270).
airmass : numeric
Relative (not pressure-corrected) airmass values. If AM is a
DataFrame it must be of the same size as all other DataFrame
inputs. AM must be >=0 (careful using the 1/sec(z) model of AM
generation)
model : string (optional, default=)
A string which selects the desired set of Perez coefficients. If
model is not provided as an input, the default, will be
used. All possible model selections are:
*
* (same as )
*
*
*
*
*
*
*
*
*
*
return_components: bool (optional, default=False)
Flag used to decide whether to return the calculated diffuse components
or not.
Returns
--------
numeric, OrderedDict, or DataFrame
Return type controlled by `return_components` argument.
If ``return_components=False``, `sky_diffuse` is returned.
If ``return_components=True``, `diffuse_components` is returned.
sky_diffuse : numeric
The sky diffuse component of the solar radiation on a tilted
surface.
diffuse_components : OrderedDict (array input) or DataFrame (Series input)
Keys/columns are:
* sky_diffuse: Total sky diffuse
* isotropic
* circumsolar
* horizon
References
----------
[1] Loutzenhiser P.G. et. al. "Empirical validation of models to
compute solar irradiance on inclined surfaces for building energy
simulation" 2007, Solar Energy vol. 81. pp. 254-267
[2] Perez, R., Seals, R., Ineichen, P., Stewart, R., Menicucci, D.,
1987. A new simplified version of the Perez diffuse irradiance model
for tilted surfaces. Solar Energy 39(3), 221-232.
[3] Perez, R., Ineichen, P., Seals, R., Michalsky, J., Stewart, R.,
1990. Modeling daylight availability and irradiance components from
direct and global irradiance. Solar Energy 44 (5), 271-289.
[4] Perez, R. et. al 1988. "The Development and Verification of the
Perez Diffuse Radiation Model". SAND88-7030
s "brightness"
delta = dhi * airmass / dni_extra
mask = sky_diffuse == 0
if isinstance(sky_diffuse, pd.Series):
diffuse_components = pd.DataFrame(diffuse_components)
diffuse_components.loc[mask] = 0
else:
diffuse_components = {k: np.where(mask, 0, v) for k, v in
diffuse_components.items()}
return diffuse_components
else:
return sky_diffuse | Determine diffuse irradiance from the sky on a tilted surface using
one of the Perez models.
Perez models determine the diffuse irradiance from the sky (ground
reflected irradiance is not included in this algorithm) on a tilted
surface using the surface tilt angle, surface azimuth angle, diffuse
horizontal irradiance, direct normal irradiance, extraterrestrial
irradiance, sun zenith angle, sun azimuth angle, and relative (not
pressure-corrected) airmass. Optionally a selector may be used to
use any of Perez's model coefficient sets.
Parameters
----------
surface_tilt : numeric
Surface tilt angles in decimal degrees. surface_tilt must be >=0
and <=180. The tilt angle is defined as degrees from horizontal
(e.g. surface facing up = 0, surface facing horizon = 90)
surface_azimuth : numeric
Surface azimuth angles in decimal degrees. surface_azimuth must
be >=0 and <=360. The azimuth convention is defined as degrees
east of north (e.g. North = 0, South=180 East = 90, West = 270).
dhi : numeric
Diffuse horizontal irradiance in W/m^2. DHI must be >=0.
dni : numeric
Direct normal irradiance in W/m^2. DNI must be >=0.
dni_extra : numeric
Extraterrestrial normal irradiance in W/m^2.
solar_zenith : numeric
apparent (refraction-corrected) zenith angles in decimal
degrees. solar_zenith must be >=0 and <=180.
solar_azimuth : numeric
Sun azimuth angles in decimal degrees. solar_azimuth must be >=0
and <=360. The azimuth convention is defined as degrees east of
north (e.g. North = 0, East = 90, West = 270).
airmass : numeric
Relative (not pressure-corrected) airmass values. If AM is a
DataFrame it must be of the same size as all other DataFrame
inputs. AM must be >=0 (careful using the 1/sec(z) model of AM
generation)
model : string (optional, default='allsitescomposite1990')
A string which selects the desired set of Perez coefficients. If
model is not provided as an input, the default, '1990' will be
used. All possible model selections are:
* '1990'
* 'allsitescomposite1990' (same as '1990')
* 'allsitescomposite1988'
* 'sandiacomposite1988'
* 'usacomposite1988'
* 'france1988'
* 'phoenix1988'
* 'elmonte1988'
* 'osage1988'
* 'albuquerque1988'
* 'capecanaveral1988'
* 'albany1988'
return_components: bool (optional, default=False)
Flag used to decide whether to return the calculated diffuse components
or not.
Returns
--------
numeric, OrderedDict, or DataFrame
Return type controlled by `return_components` argument.
If ``return_components=False``, `sky_diffuse` is returned.
If ``return_components=True``, `diffuse_components` is returned.
sky_diffuse : numeric
The sky diffuse component of the solar radiation on a tilted
surface.
diffuse_components : OrderedDict (array input) or DataFrame (Series input)
Keys/columns are:
* sky_diffuse: Total sky diffuse
* isotropic
* circumsolar
* horizon
References
----------
[1] Loutzenhiser P.G. et. al. "Empirical validation of models to
compute solar irradiance on inclined surfaces for building energy
simulation" 2007, Solar Energy vol. 81. pp. 254-267
[2] Perez, R., Seals, R., Ineichen, P., Stewart, R., Menicucci, D.,
1987. A new simplified version of the Perez diffuse irradiance model
for tilted surfaces. Solar Energy 39(3), 221-232.
[3] Perez, R., Ineichen, P., Seals, R., Michalsky, J., Stewart, R.,
1990. Modeling daylight availability and irradiance components from
direct and global irradiance. Solar Energy 44 (5), 271-289.
[4] Perez, R. et. al 1988. "The Development and Verification of the
Perez Diffuse Radiation Model". SAND88-7030 | ### Input:
Determine diffuse irradiance from the sky on a tilted surface using
one of the Perez models.
Perez models determine the diffuse irradiance from the sky (ground
reflected irradiance is not included in this algorithm) on a tilted
surface using the surface tilt angle, surface azimuth angle, diffuse
horizontal irradiance, direct normal irradiance, extraterrestrial
irradiance, sun zenith angle, sun azimuth angle, and relative (not
pressure-corrected) airmass. Optionally a selector may be used to
use any of Perez's model coefficient sets.
Parameters
----------
surface_tilt : numeric
Surface tilt angles in decimal degrees. surface_tilt must be >=0
and <=180. The tilt angle is defined as degrees from horizontal
(e.g. surface facing up = 0, surface facing horizon = 90)
surface_azimuth : numeric
Surface azimuth angles in decimal degrees. surface_azimuth must
be >=0 and <=360. The azimuth convention is defined as degrees
east of north (e.g. North = 0, South=180 East = 90, West = 270).
dhi : numeric
Diffuse horizontal irradiance in W/m^2. DHI must be >=0.
dni : numeric
Direct normal irradiance in W/m^2. DNI must be >=0.
dni_extra : numeric
Extraterrestrial normal irradiance in W/m^2.
solar_zenith : numeric
apparent (refraction-corrected) zenith angles in decimal
degrees. solar_zenith must be >=0 and <=180.
solar_azimuth : numeric
Sun azimuth angles in decimal degrees. solar_azimuth must be >=0
and <=360. The azimuth convention is defined as degrees east of
north (e.g. North = 0, East = 90, West = 270).
airmass : numeric
Relative (not pressure-corrected) airmass values. If AM is a
DataFrame it must be of the same size as all other DataFrame
inputs. AM must be >=0 (careful using the 1/sec(z) model of AM
generation)
model : string (optional, default='allsitescomposite1990')
A string which selects the desired set of Perez coefficients. If
model is not provided as an input, the default, '1990' will be
used. All possible model selections are:
* '1990'
* 'allsitescomposite1990' (same as '1990')
* 'allsitescomposite1988'
* 'sandiacomposite1988'
* 'usacomposite1988'
* 'france1988'
* 'phoenix1988'
* 'elmonte1988'
* 'osage1988'
* 'albuquerque1988'
* 'capecanaveral1988'
* 'albany1988'
return_components: bool (optional, default=False)
Flag used to decide whether to return the calculated diffuse components
or not.
Returns
--------
numeric, OrderedDict, or DataFrame
Return type controlled by `return_components` argument.
If ``return_components=False``, `sky_diffuse` is returned.
If ``return_components=True``, `diffuse_components` is returned.
sky_diffuse : numeric
The sky diffuse component of the solar radiation on a tilted
surface.
diffuse_components : OrderedDict (array input) or DataFrame (Series input)
Keys/columns are:
* sky_diffuse: Total sky diffuse
* isotropic
* circumsolar
* horizon
References
----------
[1] Loutzenhiser P.G. et. al. "Empirical validation of models to
compute solar irradiance on inclined surfaces for building energy
simulation" 2007, Solar Energy vol. 81. pp. 254-267
[2] Perez, R., Seals, R., Ineichen, P., Stewart, R., Menicucci, D.,
1987. A new simplified version of the Perez diffuse irradiance model
for tilted surfaces. Solar Energy 39(3), 221-232.
[3] Perez, R., Ineichen, P., Seals, R., Michalsky, J., Stewart, R.,
1990. Modeling daylight availability and irradiance components from
direct and global irradiance. Solar Energy 44 (5), 271-289.
[4] Perez, R. et. al 1988. "The Development and Verification of the
Perez Diffuse Radiation Model". SAND88-7030
### Response:
def perez(surface_tilt, surface_azimuth, dhi, dni, dni_extra,
solar_zenith, solar_azimuth, airmass,
model=, return_components=False):
s model coefficient sets.
Parameters
----------
surface_tilt : numeric
Surface tilt angles in decimal degrees. surface_tilt must be >=0
and <=180. The tilt angle is defined as degrees from horizontal
(e.g. surface facing up = 0, surface facing horizon = 90)
surface_azimuth : numeric
Surface azimuth angles in decimal degrees. surface_azimuth must
be >=0 and <=360. The azimuth convention is defined as degrees
east of north (e.g. North = 0, South=180 East = 90, West = 270).
dhi : numeric
Diffuse horizontal irradiance in W/m^2. DHI must be >=0.
dni : numeric
Direct normal irradiance in W/m^2. DNI must be >=0.
dni_extra : numeric
Extraterrestrial normal irradiance in W/m^2.
solar_zenith : numeric
apparent (refraction-corrected) zenith angles in decimal
degrees. solar_zenith must be >=0 and <=180.
solar_azimuth : numeric
Sun azimuth angles in decimal degrees. solar_azimuth must be >=0
and <=360. The azimuth convention is defined as degrees east of
north (e.g. North = 0, East = 90, West = 270).
airmass : numeric
Relative (not pressure-corrected) airmass values. If AM is a
DataFrame it must be of the same size as all other DataFrame
inputs. AM must be >=0 (careful using the 1/sec(z) model of AM
generation)
model : string (optional, default=)
A string which selects the desired set of Perez coefficients. If
model is not provided as an input, the default, will be
used. All possible model selections are:
*
* (same as )
*
*
*
*
*
*
*
*
*
*
return_components: bool (optional, default=False)
Flag used to decide whether to return the calculated diffuse components
or not.
Returns
--------
numeric, OrderedDict, or DataFrame
Return type controlled by `return_components` argument.
If ``return_components=False``, `sky_diffuse` is returned.
If ``return_components=True``, `diffuse_components` is returned.
sky_diffuse : numeric
The sky diffuse component of the solar radiation on a tilted
surface.
diffuse_components : OrderedDict (array input) or DataFrame (Series input)
Keys/columns are:
* sky_diffuse: Total sky diffuse
* isotropic
* circumsolar
* horizon
References
----------
[1] Loutzenhiser P.G. et. al. "Empirical validation of models to
compute solar irradiance on inclined surfaces for building energy
simulation" 2007, Solar Energy vol. 81. pp. 254-267
[2] Perez, R., Seals, R., Ineichen, P., Stewart, R., Menicucci, D.,
1987. A new simplified version of the Perez diffuse irradiance model
for tilted surfaces. Solar Energy 39(3), 221-232.
[3] Perez, R., Ineichen, P., Seals, R., Michalsky, J., Stewart, R.,
1990. Modeling daylight availability and irradiance components from
direct and global irradiance. Solar Energy 44 (5), 271-289.
[4] Perez, R. et. al 1988. "The Development and Verification of the
Perez Diffuse Radiation Model". SAND88-7030
s "brightness"
delta = dhi * airmass / dni_extra
mask = sky_diffuse == 0
if isinstance(sky_diffuse, pd.Series):
diffuse_components = pd.DataFrame(diffuse_components)
diffuse_components.loc[mask] = 0
else:
diffuse_components = {k: np.where(mask, 0, v) for k, v in
diffuse_components.items()}
return diffuse_components
else:
return sky_diffuse |
def reduce(infile, outfile):
if outfile is None:
outfile = infile
else:
outfile = outfile
reduce_osw(infile, outfile) | Reduce scored PyProphet file to minimum for global scoring | ### Input:
Reduce scored PyProphet file to minimum for global scoring
### Response:
def reduce(infile, outfile):
if outfile is None:
outfile = infile
else:
outfile = outfile
reduce_osw(infile, outfile) |
def _update_structure_lines(self):
structure_lines = []
atom_chain_order = []
chain_atoms = {}
for line in self.lines:
linetype = line[0:6]
if linetype == or linetype == or linetype == :
chain_id = line[21]
self.residue_types.add(line[17:20].strip())
if missing_chain_ids.get(self.pdb_id):
chain_id = missing_chain_ids[self.pdb_id]
structure_lines.append(line)
if (chain_id not in atom_chain_order) and (chain_id != ):
atom_chain_order.append(chain_id)
if linetype == :
atom_type = line[12:16].strip()
if atom_type:
chain_atoms[chain_id] = chain_atoms.get(chain_id, set())
chain_atoms[chain_id].add(atom_type)
if linetype == :
colortext.warning("ENDMDL detected: Breaking out early. We do not currently handle NMR structures properly.")
break
self.structure_lines = structure_lines
self.atom_chain_order = atom_chain_order
self.chain_atoms = chain_atoms | ATOM and HETATM lines may be altered by function calls. When this happens, this function should be called to keep self.structure_lines up to date. | ### Input:
ATOM and HETATM lines may be altered by function calls. When this happens, this function should be called to keep self.structure_lines up to date.
### Response:
def _update_structure_lines(self):
structure_lines = []
atom_chain_order = []
chain_atoms = {}
for line in self.lines:
linetype = line[0:6]
if linetype == or linetype == or linetype == :
chain_id = line[21]
self.residue_types.add(line[17:20].strip())
if missing_chain_ids.get(self.pdb_id):
chain_id = missing_chain_ids[self.pdb_id]
structure_lines.append(line)
if (chain_id not in atom_chain_order) and (chain_id != ):
atom_chain_order.append(chain_id)
if linetype == :
atom_type = line[12:16].strip()
if atom_type:
chain_atoms[chain_id] = chain_atoms.get(chain_id, set())
chain_atoms[chain_id].add(atom_type)
if linetype == :
colortext.warning("ENDMDL detected: Breaking out early. We do not currently handle NMR structures properly.")
break
self.structure_lines = structure_lines
self.atom_chain_order = atom_chain_order
self.chain_atoms = chain_atoms |
def set(self, value, samples=0):
if self.params.length > self.pos and samples > 0:
l = min(samples, self.params.length-self.pos)
self.data[self.pos:self.pos+l] = np.full(l, value, dtype=np.float)
self.pos += l
self.latest = value
return self | Set the current value and optionally maintain it for a period
:param value: New current value
:param samples: Add current value for this number of samples (if not zero)
:return: | ### Input:
Set the current value and optionally maintain it for a period
:param value: New current value
:param samples: Add current value for this number of samples (if not zero)
:return:
### Response:
def set(self, value, samples=0):
if self.params.length > self.pos and samples > 0:
l = min(samples, self.params.length-self.pos)
self.data[self.pos:self.pos+l] = np.full(l, value, dtype=np.float)
self.pos += l
self.latest = value
return self |
def get_config(config_path=_DEFAULT_CONFIG_PATH):
*
_validate_config(config_path)
cmd = [, , .format(config_path)]
cmd_ret = _cmd_run(cmd)
return salt.utils.json.loads(cmd_ret) | Get the configuration data.
:param str config_path: The path to the configuration file for the aptly instance.
:return: A dictionary containing the configuration data.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' aptly.get_config | ### Input:
Get the configuration data.
:param str config_path: The path to the configuration file for the aptly instance.
:return: A dictionary containing the configuration data.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' aptly.get_config
### Response:
def get_config(config_path=_DEFAULT_CONFIG_PATH):
*
_validate_config(config_path)
cmd = [, , .format(config_path)]
cmd_ret = _cmd_run(cmd)
return salt.utils.json.loads(cmd_ret) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.