language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def _ensure_channel_connected(self, destination_id):
""" Ensure we opened a channel to destination_id. """
if destination_id not in self._open_channels:
self._open_channels.append(destination_id)
self.send_message(
destination_id, NS_CONNECTION,
{MESSAGE_TYPE: TYPE_CONNECT,
'origin': {},
'userAgent': 'PyChromecast',
'senderInfo': {
'sdkType': 2,
'version': '15.605.1.3',
'browserVersion': "44.0.2403.30",
'platform': 4,
'systemVersion': 'Macintosh; Intel Mac OS X10_10_3',
'connectionType': 1}},
no_add_request_id=True) |
java | public int getCountOfContextNodeList(XPathContext xctxt)
throws javax.xml.transform.TransformerException
{
// assert(null != m_contextNodeList, "m_contextNodeList must be non-null");
// If we're in a predicate, then this will return non-null.
SubContextList iter = m_isTopLevel ? null : xctxt.getSubContextList();
// System.out.println("iter: "+iter);
if (null != iter)
return iter.getLastPos(xctxt);
DTMIterator cnl = xctxt.getContextNodeList();
int count;
if(null != cnl)
{
count = cnl.getLength();
// System.out.println("count: "+count);
}
else
count = 0;
return count;
} |
java | private GeometryCollection asGeomCollection(CrsId crsId) throws IOException {
try {
String subJson = getSubJson("geometries", "A geometrycollection requires a geometries parameter")
.replaceAll(" ", "");
String noSpaces = subJson.replace(" ", "");
if (noSpaces.contains("\"crs\":{"))
{
throw new IOException("Specification of the crs information is forbidden in child elements. Either " +
"leave it out, or specify it at the toplevel object.");
}
// add crs to each of the json geometries, otherwise they are deserialized with an undefined crs and the
// collection will then also have an undefined crs.
subJson = setCrsIds(subJson, crsId);
List<Geometry> geometries = parent.collectionFromJson(subJson, Geometry.class);
return new GeometryCollection(geometries.toArray(new Geometry[geometries.size()]));
} catch (JsonException e) {
throw new IOException(e);
}
} |
python | def funk(p, x, y):
"""
Function misfit evaluation for best-fit tanh curve
f(x[:]) = alpha*tanh(beta*x[:])
alpha = params[0]
beta = params[1]
funk(params) = sqrt(sum((y[:] - f(x[:]))**2)/len(y[:]))
Output is RMS misfit
x=xx[0][:]
y=xx[1][:]q
"""
alpha=p[0]
beta=p[1]
dev=0
for i in range(len(x)):
dev=dev+((y[i]-(alpha*math.tanh(beta*x[i])))**2)
rms=math.sqrt(old_div(dev,float(len(y))))
return rms |
python | def get_error_page(self):
"""
Method returning error page. Should return string.
By default it find element with class ``error-page`` and returns text
of ``h1`` header. You can change this method accordingly to your app.
Error page returned from this method is used in decorators
:py:func:`.expected_error_page` and :py:func:`.allowed_error_pages`.
"""
try:
error_page = self.get_elm(class_name='error-page')
except NoSuchElementException:
pass
else:
header = error_page.get_elm(tag_name='h1')
return header.text |
java | public void randomWait(long min, long max) {
final long waitTime = randomLong(min, max);
try {
Thread.sleep(waitTime);
} catch (InterruptedException interruptedException) {
// ignored
}
} |
python | def report(self, job_ids=None, array_ids=None, output=True, error=True, status=Status, name=None):
"""Iterates through the output and error files and write the results to command line."""
def _write_contents(job):
# Writes the contents of the output and error files to command line
out_file, err_file = job.std_out_file(), job.std_err_file()
logger.info("Contents of output file: '%s'" % out_file)
if output and out_file is not None and os.path.exists(out_file) and os.stat(out_file).st_size > 0:
print(open(out_file).read().rstrip())
print("-"*20)
if error and err_file is not None and os.path.exists(err_file) and os.stat(err_file).st_size > 0:
logger.info("Contents of error file: '%s'" % err_file)
print(open(err_file).read().rstrip())
print("-"*40)
def _write_array_jobs(array_jobs):
for array_job in array_jobs:
print("Array Job", str(array_job.id), ("(%s) :"%array_job.machine_name if array_job.machine_name is not None else ":"))
_write_contents(array_job)
self.lock()
# check if an array job should be reported
if array_ids:
if len(job_ids) != 1: logger.error("If array ids are specified exactly one job id must be given.")
array_jobs = list(self.session.query(ArrayJob).join(Job).filter(Job.unique.in_(job_ids)).filter(Job.unique == ArrayJob.job_id).filter(ArrayJob.id.in_(array_ids)))
if array_jobs: print(array_jobs[0].job)
_write_array_jobs(array_jobs)
else:
# iterate over all jobs
jobs = self.get_jobs(job_ids)
for job in jobs:
if name is not None and job.name != name:
continue
if job.status not in status:
continue
if job.array:
print(job)
_write_array_jobs(job.array)
else:
print(job)
_write_contents(job)
if job.log_dir is not None:
print("-"*60)
self.unlock() |
python | def y_lower_limit(self, limit=None):
"""Returns or sets (if a value is provided) the value at which the
y-axis should start. By default this is zero (unless there are negative
values).
:param limit: If given, the chart's y_lower_limit will be set to this.
:raises ValueError: if you try to make the lower limit larger than the\
upper limit."""
if limit is None:
if self._y_lower_limit is None:
if self.smallest_y() < 0:
if self.smallest_y() == self.largest_y():
return int(self.smallest_y() - 1)
else:
return self.smallest_y()
else:
return 0
else:
return self._y_lower_limit
else:
if not is_numeric(limit):
raise TypeError(
"lower y limit must be numeric, not '%s'" % str(limit)
)
if limit >= self.largest_y():
raise ValueError(
"lower y limit must be less than upper limit (%s), not %s" % (
str(self.largest_y()), str(limit)
)
)
self._y_lower_limit = limit |
java | @Override
public CreatePortfolioResult createPortfolio(CreatePortfolioRequest request) {
request = beforeClientExecution(request);
return executeCreatePortfolio(request);
} |
python | def plot(self, y_axis='attenuation', x_axis='energy',
logx=False, logy=False,
mixed=True, all_layers=False, all_elements=False,
all_isotopes=False, items_to_plot=None,
time_unit='us', offset_us=0., source_to_detector_m=16.,
time_resolution_us=0.16, t_start_us=1,
plotly=False, ax_mpl=None,
fmt='-', ms='2', lw='1.5', alpha=1):
# offset delay values is normal 2.99 us with NONE actual MCP delay settings
"""display the transmission or attenuation of compound, element and/or isotopes specified
Parameters:
===========
:param x_axis: x type for export. Must be either ['energy'|'lambda'|'time'|'number']
:type x_axis: str
:param y_axis: y type for export. Must be either ['transmission'|'attenuation'|'sigma'|'sigma_raw'|'miu_per_cm']
:type y_axis: str
:param logx: True -> display x in log scale
:type logx: boolean.
:param logy: True -> display y in log scale
:type logy: boolean.
:param mixed: boolean. True -> display the total of each layer
False -> not displayed
:param all_layers: boolean. True -> display all layers
False -> not displayed
:param all_elements: boolean. True -> display all elements signal
False -> not displayed
:param all_isotopes: boolean. True -> display all isotopes signal
False -> not displayed
:param items_to_plot: array that describes what to plot
ex:
[['CoAg','Ag','107-Ag'], ['CoAg']]
if the dictionary is empty, everything is exported
:param time_unit: string. Must be either ['s'|'us'|'ns']
Note: this will be used only when x_axis='time'
:param offset_us: default: 0
Note: only used when x_axis='number' or 'time'
:param source_to_detector_m: Note: this will be used only when x_axis='number' or 'time'
:param time_resolution_us: Note: this will be used only when x_axis='number'
:param t_start_us: when is the first acquisition occurred. default: 1
Note: this will be used only when x_axis='number'
:param plotly: control to use plotly to display or not.
:type plotly: bool
:param ax_mpl: matplotlib.axes to plot against
:type ax_mpl: matplotlib.axes
:param fmt: matplotlib.axes.plot kwargs
:type fmt: str
:param ms: matplotlib.axes.plot kwargs
:type ms: float
:param lw: matplotlib.axes.plot kwargs
:type lw: float
:param alpha: matplotlib.axes.plot kwargs
:type alpha: float
"""
if x_axis not in x_type_list:
raise ValueError("Please specify the x-axis type using one from '{}'.".format(x_type_list))
if time_unit not in time_unit_list:
raise ValueError("Please specify the time unit using one from '{}'.".format(time_unit_list))
if y_axis not in y_type_list:
raise ValueError("Please specify the y-axis type using one from '{}'.".format(y_type_list))
# figure size
# plt.figure(figsize=(8, 8))
# stack from self
_stack_signal = self.stack_signal
_stack = self.stack
_stack_sigma = self.stack_sigma
_x_axis = self.total_signal['energy_eV']
x_axis_label = None
# Creating the matplotlib graph..
if ax_mpl is None:
fig_mpl, ax_mpl = plt.subplots()
"""X-axis"""
# determine values and labels for x-axis with options from
# 'energy(eV)' & 'lambda(A)' & 'time(us)' & 'image number(#)'
if x_axis == 'energy':
x_axis_label = 'Energy (eV)'
if x_axis == 'lambda':
x_axis_label = u"Wavelength (\u212B)"
_x_axis = _utilities.ev_to_angstroms(array=_x_axis)
if x_axis == 'time':
if time_unit == 's':
x_axis_label = 'Time (s)'
_x_axis = _utilities.ev_to_s(array=_x_axis,
source_to_detector_m=source_to_detector_m,
offset_us=offset_us)
if time_unit == 'us':
x_axis_label = 'Time (us)'
_x_axis = 1e6 * _utilities.ev_to_s(array=_x_axis,
source_to_detector_m=source_to_detector_m,
offset_us=offset_us)
if time_unit == 'ns':
x_axis_label = 'Time (ns)'
_x_axis = 1e9 * _utilities.ev_to_s(array=_x_axis,
source_to_detector_m=source_to_detector_m,
offset_us=offset_us)
print("'{}' was obtained with the following:\nsource_to_detector_m={}\noffset_us={}"
.format(x_axis_label, source_to_detector_m, offset_us))
if x_axis == 'number':
x_axis_label = 'Image number (#)'
_x_axis = _utilities.ev_to_image_number(array=_x_axis,
source_to_detector_m=source_to_detector_m,
offset_us=offset_us,
time_resolution_us=time_resolution_us,
t_start_us=t_start_us)
print("'{}' was obtained with the following:\nsource_to_detector_m={}\noffset_us={}\ntime_resolution_us={}"
.format(x_axis_label, source_to_detector_m, offset_us, time_resolution_us))
if x_axis_label is None:
raise ValueError("x_axis_label does NOT exist, please check.")
"""Y-axis"""
# determine to plot transmission or attenuation
# determine to put transmission or attenuation words for y-axis
y_axis_tag = y_axis
if y_axis == 'transmission':
y_axis_label = 'Neutron Transmission'
elif y_axis == 'attenuation':
y_axis_label = 'Neutron Attenuation'
elif y_axis == 'sigma':
y_axis_tag = 'sigma_b'
y_axis_label = 'Cross-section (barns)'
elif y_axis == 'sigma_raw':
y_axis_tag = 'sigma_b_raw'
y_axis_label = 'Cross-section (barns)'
else:
y_axis_tag = 'miu_per_cm'
y_axis_label = "Attenuation coefficient (cm\u207B\u00B9)"
if y_axis_tag[:5] == 'sigma':
mixed = False
all_layers = False
print("'y_axis='sigma'' is selected. Auto force 'mixed=False', 'all_layers=False'")
if y_axis_tag[-3:] == 'raw':
all_elements = False
print("'y_axis='sigma_raw'' is selected. Auto force 'all_elements=False'")
if y_axis_tag == 'miu_per_cm':
mixed = False
print("'y_axis='miu_per_cm'' is selected. Auto force 'mixed=False'")
# Plotting begins
if mixed:
_y_axis = self.total_signal[y_axis_tag]
ax_mpl.plot(_x_axis, _y_axis, fmt, ms=ms, lw=lw, alpha=alpha, label="Total")
if all_layers:
for _compound in _stack.keys():
_y_axis = _stack_signal[_compound][y_axis_tag]
ax_mpl.plot(_x_axis, _y_axis, fmt, ms=ms, lw=lw, alpha=alpha, label=_compound)
if all_elements:
for _compound in _stack.keys():
for _element in _stack[_compound]['elements']:
if y_axis_tag[:5] != 'sigma':
_y_axis = _stack_signal[_compound][_element][y_axis_tag]
ax_mpl.plot(_x_axis, _y_axis, fmt, ms=ms, lw=lw, alpha=alpha,
label="{}/{}".format(_compound, _element))
else:
_y_axis = _stack_sigma[_compound][_element]['sigma_b']
ax_mpl.plot(_x_axis, _y_axis, fmt, ms=ms, lw=lw, alpha=alpha,
label="{}/{}".format(_compound, _element))
if all_isotopes:
for _compound in _stack.keys():
for _element in _stack[_compound]['elements']:
for _isotope in _stack[_compound][_element]['isotopes']['list']:
if y_axis_tag[:5] != 'sigma':
_y_axis = _stack_signal[_compound][_element][_isotope][y_axis_tag]
ax_mpl.plot(_x_axis, _y_axis, fmt, ms=ms, lw=lw, alpha=alpha,
label="{}/{}/{}".format(_compound, _element, _isotope))
else:
_y_axis = _stack_sigma[_compound][_element][_isotope][y_axis_tag]
ax_mpl.plot(_x_axis, _y_axis, fmt, ms=ms, lw=lw, alpha=alpha,
label="{}/{}/{}".format(_compound, _element, _isotope))
"""Y-axis for specified items_to_plot"""
if items_to_plot is not None:
for _path_to_plot in items_to_plot:
_path_to_plot = list(_path_to_plot)
if y_axis_tag[:5] != 'sigma':
_live_path = _stack_signal
else:
_len_of_path = len(_path_to_plot)
if y_axis_tag[-3:] == 'raw':
if _len_of_path < 3:
raise ValueError("'y_axis={}' is not supported for layer or element levels '{}'.".format(
y_axis_tag, _path_to_plot[-1]))
else:
if _len_of_path < 2:
raise ValueError("'y_axis={}' is not supported for layer level '{}'.".format(
y_axis_tag, _path_to_plot[-1]))
_live_path = _stack_sigma
_label = "/".join(_path_to_plot)
while _path_to_plot:
_item = _path_to_plot.pop(0)
_live_path = _live_path[_item]
_y_axis = _live_path[y_axis_tag]
ax_mpl.plot(_x_axis, _y_axis, fmt, ms=ms, lw=lw, alpha=alpha, label=_label)
if y_axis_tag[:5] != 'sigma' and y_axis_tag != 'miu_per_cm':
ax_mpl.set_ylim(-0.01, 1.01)
if logy is True:
ax_mpl.set_yscale('log')
if logx is True:
ax_mpl.set_xscale('log')
ax_mpl.set_xlabel(x_axis_label)
ax_mpl.set_ylabel(y_axis_label)
if not plotly:
ax_mpl.legend(loc='best')
# plt.tight_layout()
return ax_mpl
else:
fig_mpl = ax_mpl.get_figure()
plotly_fig = tls.mpl_to_plotly(fig_mpl)
plotly_fig.layout.showlegend = True
return plotly_fig |
java | public static boolean doesStringContainOpenQuote(String text) {
boolean doubleQuote = false;
boolean singleQuote = false;
boolean escapedByBackSlash = false;
// do not parse comment
if (commentPattern.matcher(text).find())
return false;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == BACK_SLASH || escapedByBackSlash) {
escapedByBackSlash = !escapedByBackSlash;
continue;
}
if (text.charAt(i) == SINGLE_QUOTE) {
if (!doubleQuote)
singleQuote = !singleQuote;
}
else if (text.charAt(i) == DOUBLE_QUOTE) {
if (!singleQuote)
doubleQuote = !doubleQuote;
}
}
return doubleQuote || singleQuote;
} |
python | def delete(self, file_, delete_file=True):
"""
Deletes file_ references in Key Value store and optionally the file_
it self.
"""
image_file = ImageFile(file_)
if delete_file:
image_file.delete()
default.kvstore.delete(image_file) |
java | public static INDArray firstIndex(INDArray array, Condition condition, int... dimension) {
if (!(condition instanceof BaseCondition))
throw new UnsupportedOperationException("Only static Conditions are supported");
return Nd4j.getExecutioner().exec(new FirstIndex(array, condition, dimension));
} |
java | public static <T> Set<T> enumerationToSet(Enumeration<T> enumeration) {
Set<T> set = new HashSet<>();
while (enumeration.hasMoreElements()) {
set.add(enumeration.nextElement());
}
return set;
} |
java | public synchronized void add(VisitState visitState) {
final boolean wasEntirelyBroken = isEntirelyBroken();
if (visitState.lastExceptionClass != null) brokenVisitStates++;
visitStates.add(visitState);
assert brokenVisitStates <= visitStates.size();
if (wasEntirelyBroken && ! isEntirelyBroken()) workbenchBroken.decrementAndGet();
if (! wasEntirelyBroken && isEntirelyBroken()) workbenchBroken.incrementAndGet();
} |
java | public int previous() {
int index; // offset in ICU4C
if (search_.reset_) {
index = search_.endIndex(); // m_search_->textLength in ICU4C
search_.isForwardSearching_ = false;
search_.reset_ = false;
setIndex(index);
} else {
index = getIndex();
}
int matchindex = search_.matchedIndex_;
if (search_.isForwardSearching_) {
// switching direction.
// if matchedIndex == DONE, it means that either a
// setIndex (setOffset in C) has been called or that next ran off the text
// string. the iterator would have been set to offset textLength if
// a match is not found.
search_.isForwardSearching_ = false;
if (matchindex != DONE) {
return matchindex;
}
} else {
int startIdx = search_.beginIndex();
if (index == startIdx || matchindex == startIdx) {
// not enough characters to match
setMatchNotFound();
return DONE;
}
}
if (matchindex != DONE) {
if (search_.isOverlap_) {
matchindex += search_.matchedLength() - 2;
}
return handlePrevious(matchindex);
}
return handlePrevious(index);
} |
python | def combine_HSPs(a):
"""
Combine HSPs into a single BlastLine.
"""
m = a[0]
if len(a) == 1:
return m
for b in a[1:]:
assert m.query == b.query
assert m.subject == b.subject
m.hitlen += b.hitlen
m.nmismatch += b.nmismatch
m.ngaps += b.ngaps
m.qstart = min(m.qstart, b.qstart)
m.qstop = max(m.qstop, b.qstop)
m.sstart = min(m.sstart, b.sstart)
m.sstop = max(m.sstop, b.sstop)
if m.has_score:
m.score += b.score
m.pctid = 100 - (m.nmismatch + m.ngaps) * 100. / m.hitlen
return m |
java | protected static boolean loadDefaultConf(String packageName) throws ParseException {
if (packageName.endsWith(".conf")) {
return false;
}
packageName = packageName.replaceAll("\\$[0-9]+$", "");
Resource defaultConf = new ClasspathResource((packageName.replaceAll("\\.",
"/"
) + "/" + DEFAULT_CONFIG_FILE_NAME).trim(),
Config.getDefaultClassLoader()
);
// Go through each level of the package until we find one that
// has a default properties file or we cannot go any further.
while (!defaultConf.exists()) {
int idx = packageName.lastIndexOf('.');
if (idx == -1) {
defaultConf = new ClasspathResource(packageName + "/" + DEFAULT_CONFIG_FILE_NAME,
Config.getDefaultClassLoader()
);
break;
}
packageName = packageName.substring(0, idx);
defaultConf = new ClasspathResource(packageName.replaceAll("\\.", "/") + "/" + DEFAULT_CONFIG_FILE_NAME,
Config.getDefaultClassLoader()
);
}
if (defaultConf.exists()) {
loadConfig(defaultConf);
return true;
}
return false;
} |
python | def autocorrfunc(freq, power):
"""
Calculate autocorrelation function(s) for given power spectrum/spectra.
Parameters
----------
freq : numpy.ndarray
1 dimensional array of frequencies.
power : numpy.ndarray
2 dimensional power spectra, 1st axis units, 2nd axis frequencies.
Returns
-------
time : tuple
1 dim numpy.ndarray of times.
autof : tuple
2 dim numpy.ndarray; autocorrelation functions, 1st axis units,
2nd axis times.
"""
tbin = 1. / (2. * np.max(freq)) * 1e3 # tbin in ms
time = np.arange(-len(freq) / 2. + 1, len(freq) / 2. + 1) * tbin
# T = max(time)
multidata = False
if len(np.shape(power)) > 1:
multidata = True
if multidata:
N = len(power)
autof = np.zeros((N, len(freq)))
for i in range(N):
raw_autof = np.real(np.fft.ifft(power[i]))
mid = int(len(raw_autof) / 2.)
autof[i] = np.hstack([raw_autof[mid + 1:], raw_autof[:mid + 1]])
assert(len(time) == len(autof[0]))
else:
raw_autof = np.real(np.fft.ifft(power))
mid = int(len(raw_autof) / 2.)
autof = np.hstack([raw_autof[mid + 1:], raw_autof[:mid + 1]])
assert(len(time) == len(autof))
# autof *= T*1e-3 # normalization is done in powerspec()
return time, autof |
python | def list_roles(self, principal_name, principal_type):
"""
Parameters:
- principal_name
- principal_type
"""
self.send_list_roles(principal_name, principal_type)
return self.recv_list_roles() |
python | def get_ancestors(self):
""" Get all unique instance ancestors """
ancestors = list(self.get_parents())
ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors])
ancestors_with_parents = [a for a in ancestors if isinstance(a, DescendantMixin)]
for ancestor in ancestors_with_parents:
for parent in ancestor.get_ancestors():
if (parent.__class__, parent.id) not in ancestor_unique_attributes:
ancestors.append(parent)
return ancestors |
python | def bayesian(self, params=None):
'''
Run the Bayesian Bandit algorithm which utilizes a beta distribution
for exploration and exploitation.
Parameters
----------
params : None
For API consistency, this function can take a parameters argument,
but it is ignored.
Returns
-------
int
Index of chosen bandit
'''
p_success_arms = [
np.random.beta(self.wins[i] + 1, self.pulls[i] - self.wins[i] + 1)
for i in range(len(self.wins))
]
return np.array(p_success_arms).argmax() |
java | private Token attributesBlock() {
Matcher matcher = scanner.getMatcherForPattern("^&attributes\\b");
if (matcher.find(0) && matcher.group(0) != null) {
this.scanner.consume(11);
CharacterParser.Match match = this.bracketExpression();
this.scanner.consume(match.getEnd()+1);
return new AttributesBlock(match.getSrc(),lineno);
}
return null;
} |
python | def quaternion_imag(quaternion):
"""Return imaginary part of quaternion.
>>> quaternion_imag([3, 0, 1, 2])
array([0., 1., 2.])
"""
return np.array(quaternion[1:4], dtype=np.float64, copy=True) |
python | def _load_data_alignment(self, chain1, chain2):
"""
Extract the sequences from the PDB file, perform the alignment,
and load the coordinates of the CA of the common residues.
"""
parser = PDB.PDBParser(QUIET=True)
ppb = PDB.PPBuilder()
structure1 = parser.get_structure(chain1, self.pdb1)
structure2 = parser.get_structure(chain2, self.pdb2)
seq1 = str(ppb.build_peptides(structure1)[0].get_sequence())
seq2 = str(ppb.build_peptides(structure2)[0].get_sequence())
# Alignment parameters taken from PconsFold renumbering script.
align = pairwise2.align.globalms(seq1, seq2, 2, -1, -0.5, -0.1)[0]
indexes = set(i for i, (s1, s2) in enumerate(zip(align[0], align[1]))
if s1 != '-' and s2 != '-')
coord1 = np.hstack([np.concatenate((r['CA'].get_coord(), (1,)))[:, None]
for i, r in enumerate(structure1.get_residues())
if i in indexes and 'CA' in r]).astype(DTYPE,
copy=False)
coord2 = np.hstack([np.concatenate((r['CA'].get_coord(), (1,)))[:, None]
for i, r in enumerate(structure2.get_residues())
if i in indexes and 'CA' in r]).astype(DTYPE,
copy=False)
self.coord1 = coord1
self.coord2 = coord2
self.N = len(seq1) |
java | void put(String uuid, CachingIndexReader reader, int n)
{
LRUMap cacheSegment = docNumbers[getSegmentIndex(uuid.charAt(0))];
//UUID key = UUID.fromString(uuid);
String key = uuid;
synchronized (cacheSegment)
{
Entry e = (Entry)cacheSegment.get(key);
if (e != null)
{
// existing entry
// ignore if reader is older than the one in entry
if (reader.getCreationTick() <= e.creationTick)
{
if (log.isDebugEnabled())
{
log.debug("Ignoring put(). New entry is not from a newer reader. " + "existing: " + e.creationTick
+ ", new: " + reader.getCreationTick());
}
e = null;
}
}
else
{
// entry did not exist
e = new Entry(reader.getCreationTick(), n);
}
if (e != null)
{
cacheSegment.put(key, e);
}
}
} |
python | def getrange(self, key, start, end):
"""Returns the bit value at offset in the string value stored at key.
When offset is beyond the string length, the string is assumed to be a
contiguous space with 0 bits. When key does not exist it is assumed to
be an empty string, so offset is always out of range and the value is
also assumed to be a contiguous space with 0 bits.
.. versionadded:: 0.2.0
.. note:: **Time complexity**: ``O(N)`` where ``N`` is the length of
the returned string. The complexity is ultimately determined by the
returned length, but because creating a substring from an existing
string is very cheap, it can be considered ``O(1)`` for small
strings.
:param key: The key to get the bit from
:type key: :class:`str`, :class:`bytes`
:param int start: The start position to evaluate in the string
:param int end: The end position to evaluate in the string
:rtype: bytes|None
:raises: :exc:`~tredis.exceptions.RedisError`
"""
return self._execute([b'GETRANGE', key, ascii(start), ascii(end)]) |
python | def get(cls, sensor_type):
""" Shortcut that acquires the default Sensor of a given type.
Parameters
----------
sensor_type: int
Type of sensor to get.
Returns
-------
result: Future
A future that resolves to an instance of the Sensor or None
if the sensor is not present or access is not allowed.
"""
app = AndroidApplication.instance()
f = app.create_future()
def on_sensor(sid, mgr):
if sid is None:
f.set_result(None)
else:
f.set_result(Sensor(__id__=sid, manager=mgr, type=sensor_type))
SensorManager.get().then(
lambda sm: sm.getDefaultSensor(sensor_type).then(
lambda sid, sm=sm:on_sensor(sid, sm)))
return f |
java | private Optional tryCreate(Constructor<?> constructor) {
Object[] args = new Object[constructor.getParameterCount()];
Object arg;
Optional<Object> resolved;
int i = 0;
for (Parameter parameter : constructor.getParameters()) {
resolved = context.resolve(parameter);
if (!resolved.isPresent()) {
return Optional.empty();
}
arg = resolved.value();
args[i++] = arg;
}
return Optional.of(createFunction.apply(constructor, args));
} |
java | static Key str2Key(String s) {
Key k = str2Key_impl(s);
assert key2Str_impl(k, decodeType(s)).equals(s) : "bijection fail " + s + " <-> " + k;
return k;
} |
java | public static boolean isNumberStr(String arg) {
if (StringUtils.isEmpty(arg)) {
return false;
}
return check(arg, NUMBER_STR_PARTER);
} |
python | def rhombohedral(a: float, alpha: float):
"""
Convenience constructor for a rhombohedral lattice.
Args:
a (float): *a* lattice parameter of the rhombohedral cell.
alpha (float): Angle for the rhombohedral lattice in degrees.
Returns:
Rhombohedral lattice of dimensions a x a x a.
"""
return Lattice.from_parameters(a, a, a, alpha, alpha, alpha) |
python | def get_uninvoiced_hours(entries, billable=None):
"""Given an iterable of entries, return the total hours that have
not been invoiced. If billable is passed as 'billable' or 'nonbillable',
limit to the corresponding entries.
"""
statuses = ('invoiced', 'not-invoiced')
if billable is not None:
billable = (billable.lower() == u'billable')
entries = [e for e in entries if e.activity.billable == billable]
hours = sum([e.hours for e in entries if e.status not in statuses])
return '{0:.2f}'.format(hours) |
python | def prep_doc(self, doc_obj):
"""
This method Validates, gets the Python value, checks unique indexes,
gets the db value, and then returns the prepared doc dict object.
Useful for save and backup functions.
@param doc_obj:
@return:
"""
doc = doc_obj._data.copy()
for key, prop in list(doc_obj._base_properties.items()):
prop.validate(doc.get(key), key)
raw_value = prop.get_python_value(doc.get(key))
if prop.unique:
self.check_unique(doc_obj, key, raw_value)
value = prop.get_db_value(raw_value)
doc[key] = value
doc['_doc_type'] = get_doc_type(doc_obj.__class__)
return doc |
python | def rebuild( self, gridRect ):
"""
Rebuilds the tracker item.
"""
scene = self.scene()
if ( not scene ):
return
self.setVisible(gridRect.contains(self.pos()))
self.setZValue(100)
path = QPainterPath()
path.moveTo(0, 0)
path.lineTo(0, gridRect.height())
tip = ''
tip_point = None
self._ellipses = []
items = scene.collidingItems(self)
self._basePath = QPainterPath(path)
for item in items:
item_path = item.path()
found = None
for y in range(int(gridRect.top()), int(gridRect.bottom())):
point = QPointF(self.pos().x(), y)
if ( item_path.contains(point) ):
found = QPointF(0, y - self.pos().y())
break
if ( found ):
path.addEllipse(found, 6, 6)
self._ellipses.append(found)
# update the value information
value = scene.valueAt(self.mapToScene(found))
tip_point = self.mapToScene(found)
hruler = scene.horizontalRuler()
vruler = scene.verticalRuler()
x_value = hruler.formatValue(value[0])
y_value = vruler.formatValue(value[1])
tip = '<b>x:</b> %s<br/><b>y:</b> %s' % (x_value, y_value)
self.setPath(path)
self.setVisible(True)
# show the popup widget
if ( tip ):
anchor = XPopupWidget.Anchor.RightCenter
widget = self.scene().chartWidget()
tip_point = widget.mapToGlobal(widget.mapFromScene(tip_point))
XPopupWidget.showToolTip(tip,
anchor = anchor,
parent = widget,
point = tip_point,
foreground = QColor('blue'),
background = QColor(148, 148, 255)) |
java | public void mutateIndex(StaticBuffer key, List<Entry> additions, List<Entry> deletions) throws BackendException {
indexStore.mutateEntries(key, additions, deletions, storeTx);
} |
python | def pendingvalidation(self, warnonly=None):
"""Perform any pending validations
Parameters:
warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5)
Returns:
bool
"""
if self.debug: print("[PyNLPl FoLiA DEBUG] Processing pending validations (if any)",file=stderr)
if warnonly is None and self and self.version:
warnonly = (checkversion(self.version, '1.5.0') < 0) #warn only for documents older than FoLiA v1.5
if self.textvalidation:
while self.offsetvalidationbuffer:
structureelement, textclass = self.offsetvalidationbuffer.pop()
if self.debug: print("[PyNLPl FoLiA DEBUG] Performing offset validation on " + repr(structureelement) + " textclass " + textclass,file=stderr)
#validate offsets
tc = structureelement.textcontent(textclass)
if tc.offset is not None:
try:
tc.getreference(validate=True)
except UnresolvableTextContent:
msg = "Text for " + structureelement.__class__.__name__ + ", ID " + str(structureelement.id) + ", textclass " + textclass + ", has incorrect offset " + str(tc.offset) + " or invalid reference"
print("TEXT VALIDATION ERROR: " + msg,file=sys.stderr)
if not warnonly:
raise |
python | def splitlines(self, keepends=False):
"""
S.splitlines(keepends=False) -> list of strings
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
# Py2 unicode.splitlines() takes keepends as an optional parameter,
# not as a keyword argument as in Python 3 str.
parts = super(newstr, self).splitlines(keepends)
return [newstr(part) for part in parts] |
python | def to_frame(self, slot=SLOT.SCAN_MAP):
"""
Return the current configuration as a YubiKeyFrame object.
"""
payload = self.scanmap.ljust(64, b'\0')
return yubikey_frame.YubiKeyFrame(command=slot, payload=payload) |
java | @Nonnull
@ReturnsMutableCopy
public ICommonsList <CSSStyleRule> getAllStyleRules ()
{
return m_aRules.getAllMapped (r -> r instanceof CSSStyleRule, r -> (CSSStyleRule) r);
} |
java | public static boolean isAncestorOrSame(URI descendant, URI ancestor) {
Preconditions.checkNotNull(descendant, "input can not be null");
Preconditions.checkNotNull(ancestor, "input can not be null");
if (!stringSame(descendant.getScheme(), ancestor.getScheme())) {
return false;
}
if (!stringSame(descendant.getAuthority(), ancestor.getAuthority())) {
return false;
}
return isAncestorOrSame(getConfigKeyPath(descendant.getPath()), getConfigKeyPath(ancestor.getPath()));
} |
python | def js():
"returns home directory of js"
return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'js') |
java | public ListPipelinesResult withPipelines(PipelineSummary... pipelines) {
if (this.pipelines == null) {
setPipelines(new java.util.ArrayList<PipelineSummary>(pipelines.length));
}
for (PipelineSummary ele : pipelines) {
this.pipelines.add(ele);
}
return this;
} |
python | def _map_arguments(self, input_dict):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
data = input_dict.get('data')
comp = input_dict.get('comp')
library = input_dict.get('library')
models = input_dict.get('models')
hpx_order = input_dict.get('hpx_order_fitting')
dry_run = input_dict.get('dry_run', False)
self._set_link('init-model', InitModel,
comp=comp, data=data,
library=library,
models=models,
hpx_order=hpx_order,
dry_run=dry_run)
self._set_link('assemble-model', AssembleModel_SG,
comp=comp, data=data,
models=models) |
java | @Override
public UnitFactory getUnitFactory() throws DataSourceReadException {
initializeIfNeeded();
UnitFactory result = null;
DataSourceBackend b = null;
for (DataSourceBackend backend : getBackends()) {
result = backend.getUnitFactory();
b = backend;
break;
}
assert result != null : "no unit factory returned from "
+ b.getClass() + "!";
return result;
} |
python | def pretty(self,verbose=0):
"""Return pretty list description of parameter"""
# split prompt lines and add blanks in later lines to align them
plines = self.prompt.split('\n')
for i in range(len(plines)-1): plines[i+1] = 32*' ' + plines[i+1]
plines = '\n'.join(plines)
namelen = min(len(self.name), 12)
pvalue = self.get(prompt=0,lpar=1)
alwaysquoted = ['s', 'f', '*gcur', '*imcur', '*ukey', 'pset']
if self.type in alwaysquoted and self.value is not None: pvalue = '"' + pvalue + '"'
if self.mode == "h":
s = "%13s = %-15s %s" % ("("+self.name[:namelen],
pvalue+")", plines)
else:
s = "%13s = %-15s %s" % (self.name[:namelen],
pvalue, plines)
if not verbose: return s
if self.choice is not None:
s = s + "\n" + 32*" " + "|"
nline = 33
for i in range(len(self.choice)):
sch = str(self.choice[i]) + "|"
s = s + sch
nline = nline + len(sch) + 1
if nline > 80:
s = s + "\n" + 32*" " + "|"
nline = 33
elif self.min not in [None, INDEF] or self.max not in [None, INDEF]:
s = s + "\n" + 32*" "
if self.min not in [None, INDEF]:
s = s + str(self.min) + " <= "
s = s + self.name
if self.max not in [None, INDEF]:
s = s + " <= " + str(self.max)
return s |
java | public void blockUser(Integer targetUserId) throws IOException {
String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabUser.BLOCK_URL;
retrieve().method(POST).to(tailUrl, Void.class);
} |
java | private static String getPreDefOuFqn(CmsObject cms, HttpServletRequest request, boolean logout) {
if (logout && (request.getAttribute(PARAM_PREDEF_OUFQN) == null)) {
String oufqn = cms.getRequestContext().getOuFqn();
if (!oufqn.startsWith(CmsOrganizationalUnit.SEPARATOR)) {
oufqn = CmsOrganizationalUnit.SEPARATOR + oufqn;
}
request.setAttribute(CmsLoginHelper.PARAM_PREDEF_OUFQN, oufqn);
}
return (String)request.getAttribute(PARAM_PREDEF_OUFQN);
} |
python | def setPrevUpNextLinks(self, prev=None, up=None, next=None):
"""Sets Prev link to point to the LogEntry object "prev". Set that object's Next link to point to us. Sets the "up" link to the URL 'up' (if up != None.)
Sets the Next link to the entry 'next' (if next != None), or to nothing if next == ''."""
if prev is not None:
if prev:
self._prev_link = quote_url(prev._relIndexLink())
prev._next_link = quote_url(self._relIndexLink())
else:
self._prev_link = None
if up is not None:
self._up_link = up and quote_url(up)
if next is not None:
self._next_link = next and quote_url(next._relIndexLink()) |
java | static ImmutableSet<ExecutableElement> propertyMethodsIn(Set<ExecutableElement> abstractMethods) {
ImmutableSet.Builder<ExecutableElement> properties = ImmutableSet.builder();
for (ExecutableElement method : abstractMethods) {
if (method.getParameters().isEmpty()
&& method.getReturnType().getKind() != TypeKind.VOID
&& objectMethodToOverride(method) == ObjectMethod.NONE) {
properties.add(method);
}
}
return properties.build();
} |
python | def db_for_write(self, model, **hints):
"""
If given some hints['instance'] that is saved in a db, use related
fields from the same db. Otherwise if passed a class or instance to
model, return the salesforce alias if it's a subclass of SalesforceModel.
"""
if 'instance' in hints:
db = hints['instance']._state.db
if db:
return db
if getattr(model, '_salesforce_object', False):
return self.sf_alias |
java | protected void parseIntegerLists(TokenList tokens) {
TokenList.Token t = tokens.getFirst();
if( t == null || t.next == null )
return;
int state = 0;
TokenList.Token start = null;
TokenList.Token prev = t;
boolean last = false;
while( true ) {
if( state == 0 ) {
if( isVariableInteger(t) ) {
start = t;
state = 1;
}
} else if( state == 1 ) {
// var ?
if( isVariableInteger(t)) { // see if its explicit number sequence
state = 2;
} else { // just scalar integer, skip
state = 0;
}
} else if ( state == 2 ) {
// var var ....
if( !isVariableInteger(t) ) {
// create explicit list sequence
IntegerSequence sequence = new IntegerSequence.Explicit(start,prev);
VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);
replaceSequence(tokens, varSequence, start, prev);
state = 0;
}
}
if( last ) {
break;
} else if( t.next == null ) {
// handle the case where it is the last token in the sequence
last = true;
}
prev = t;
t = t.next;
}
} |
java | @XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "extension", scope = ApplyPolicy.class)
public JAXBElement<CmisExtensionType> createApplyPolicyExtension(
CmisExtensionType value) {
return new JAXBElement<CmisExtensionType>(
_GetPropertiesExtension_QNAME, CmisExtensionType.class,
ApplyPolicy.class, value);
} |
python | def hugepage_support(user, group='hugetlb', nr_hugepages=256,
max_map_count=65536, mnt_point='/run/hugepages/kvm',
pagesize='2MB', mount=True, set_shmmax=False):
"""Enable hugepages on system.
Args:
user (str) -- Username to allow access to hugepages to
group (str) -- Group name to own hugepages
nr_hugepages (int) -- Number of pages to reserve
max_map_count (int) -- Number of Virtual Memory Areas a process can own
mnt_point (str) -- Directory to mount hugepages on
pagesize (str) -- Size of hugepages
mount (bool) -- Whether to Mount hugepages
"""
group_info = add_group(group)
gid = group_info.gr_gid
add_user_to_group(user, group)
if max_map_count < 2 * nr_hugepages:
max_map_count = 2 * nr_hugepages
sysctl_settings = {
'vm.nr_hugepages': nr_hugepages,
'vm.max_map_count': max_map_count,
'vm.hugetlb_shm_group': gid,
}
if set_shmmax:
shmmax_current = int(check_output(['sysctl', '-n', 'kernel.shmmax']))
shmmax_minsize = bytes_from_string(pagesize) * nr_hugepages
if shmmax_minsize > shmmax_current:
sysctl_settings['kernel.shmmax'] = shmmax_minsize
sysctl.create(yaml.dump(sysctl_settings), '/etc/sysctl.d/10-hugepage.conf')
mkdir(mnt_point, owner='root', group='root', perms=0o755, force=False)
lfstab = fstab.Fstab()
fstab_entry = lfstab.get_entry_by_attr('mountpoint', mnt_point)
if fstab_entry:
lfstab.remove_entry(fstab_entry)
entry = lfstab.Entry('nodev', mnt_point, 'hugetlbfs',
'mode=1770,gid={},pagesize={}'.format(gid, pagesize), 0, 0)
lfstab.add_entry(entry)
if mount:
fstab_mount(mnt_point) |
java | public CmsRelationType addRelationType(String name, String type) throws CmsConfigurationException {
// check if new relation types can still be added
if (m_frozen) {
throw new CmsConfigurationException(Messages.get().container(Messages.ERR_NO_CONFIG_AFTER_STARTUP_0));
}
CmsRelationType relationType = new CmsRelationType(m_configuredRelationTypes.size(), name, type);
m_configuredRelationTypes.add(relationType);
return relationType;
} |
java | public void marshall(DescribeCopyProductStatusRequest describeCopyProductStatusRequest, ProtocolMarshaller protocolMarshaller) {
if (describeCopyProductStatusRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeCopyProductStatusRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING);
protocolMarshaller.marshall(describeCopyProductStatusRequest.getCopyProductToken(), COPYPRODUCTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def valUserCert(self, byts, cacerts=None):
'''
Validate the PEM encoded x509 user certificate bytes and return it.
Args:
byts (bytes): The bytes for the User Certificate.
cacerts (tuple): A tuple of OpenSSL.crypto.X509 CA Certificates.
Raises:
OpenSSL.crypto.X509StoreContextError: If the certificate is not valid.
Returns:
OpenSSL.crypto.X509: The certificate, if it is valid.
'''
cert = crypto.load_certificate(crypto.FILETYPE_PEM, byts)
if cacerts is None:
cacerts = self.getCaCerts()
store = crypto.X509Store()
[store.add_cert(cacert) for cacert in cacerts]
ctx = crypto.X509StoreContext(store, cert)
ctx.verify_certificate() # raises X509StoreContextError if unable to verify
return cert |
java | private List<Tuple2<String, String>> getHelpOptions() {
final List<Tuple2<String, String>> options = new ArrayList<>();
options.add(Tuple2.of("Q", CliStrings.RESULT_QUIT));
options.add(Tuple2.of("R", CliStrings.RESULT_REFRESH));
options.add(Tuple2.of("+", CliStrings.RESULT_INC_REFRESH));
options.add(Tuple2.of("-", CliStrings.RESULT_DEC_REFRESH));
options.add(Tuple2.of("O", CliStrings.RESULT_OPEN));
return options;
} |
java | private String getText(JsonNode jsonObject, String nodeName) {
JsonNode subNode = jsonObject.get(nodeName);
if (subNode == null) {
return null;
}
if (!subNode.isTextual()) {
throw new IllegalStateException(nodeName + " from credential process should be textual, but was " +
subNode.getNodeType());
}
return subNode.asText();
} |
python | def packto(self, namedstruct, stream):
"""
Pack a struct to a stream
:param namedstruct: struct to pack
:param stream: a buffered stream
:return: appended bytes size
"""
# Default implementation
data = self.pack(namedstruct)
return stream.write(data) |
python | def add(self, *args, **kwargs):
"""Add a new record to the section"""
if self.start and self.start.state == 'done' and kwargs.get('log_action') != 'done':
raise ProgressLoggingError("Can't add -- process section is done")
self.augment_args(args, kwargs)
kwargs['log_action'] = kwargs.get('log_action', 'add')
rec = Process(**kwargs)
self._session.add(rec)
self.rec = rec
if self._logger:
self._logger.info(self.rec.log_str)
self._session.commit()
self._ai_rec_id = None
return self.rec.id |
java | @Override
public MtasSpanWeight createWeight(IndexSearcher searcher,
boolean needsScores, float boost) throws IOException {
if (q1 == null || q2 == null) {
return null;
} else {
MtasSpanIntersectingQueryWeight w1 = new MtasSpanIntersectingQueryWeight(
q1.createWeight(searcher, needsScores, boost));
MtasSpanIntersectingQueryWeight w2 = new MtasSpanIntersectingQueryWeight(
q2.createWeight(searcher, needsScores, boost));
// subWeights
List<MtasSpanIntersectingQueryWeight> subWeights = new ArrayList<>();
subWeights.add(w1);
subWeights.add(w2);
// return
return new SpanIntersectingWeight(w1, w2, searcher,
needsScores ? getTermContexts(subWeights) : null, boost);
}
} |
python | def fetch(self):
"""
Fetch a AssetVersionInstance
:returns: Fetched AssetVersionInstance
:rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return AssetVersionInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
asset_sid=self._solution['asset_sid'],
sid=self._solution['sid'],
) |
java | public String trimLeading(String str) {
if (str == null) {
return null;
}
int length = str.length();
for (int i=0; i<length; i++) {
if (str.charAt(i) > ' ') {
return str.substring(i);
}
}
return "";
} |
java | @PostConstruct
public void init() {
//init Bus and LifeCycle listeners
if (bus != null && sendLifecycleEvent ) {
ServerLifeCycleManager slcm = bus.getExtension(ServerLifeCycleManager.class);
if (null != slcm) {
ServiceListenerImpl svrListener = new ServiceListenerImpl();
svrListener.setSendLifecycleEvent(sendLifecycleEvent);
svrListener.setQueue(queue);
svrListener.setMonitoringServiceClient(monitoringServiceClient);
slcm.registerListener(svrListener);
}
ClientLifeCycleManager clcm = bus.getExtension(ClientLifeCycleManager.class);
if (null != clcm) {
ClientListenerImpl cltListener = new ClientListenerImpl();
cltListener.setSendLifecycleEvent(sendLifecycleEvent);
cltListener.setQueue(queue);
cltListener.setMonitoringServiceClient(monitoringServiceClient);
clcm.registerListener(cltListener);
}
}
if(executorQueueSize == 0) {
executor = Executors.newFixedThreadPool(this.executorPoolSize);
}else{
executor = new ThreadPoolExecutor(executorPoolSize, executorPoolSize, 0, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(executorQueueSize), Executors.defaultThreadFactory(),
new RejectedExecutionHandlerImpl());
}
scheduler = new Timer();
scheduler.scheduleAtFixedRate(new TimerTask() {
public void run() {
sendEventsFromQueue();
}
}, 0, getDefaultInterval());
} |
java | @Override
public void runInvalidation() {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[RUN_INVALIDATION], appNameForLogging);
}
/*
* if (_isApplicationSessionStore) {
* runApplicationStoreInvalidation();
* } else {
*/
long nowTime = System.currentTimeMillis();
Iterator iter = _sessions.keySet().iterator();
try {
//setThreadContext threw a NPE because we were trying to get the config from within getModuleMetaData and it was returning null
//this only happens after the app has been shutdown. There was a small timing window where this was possible.
//Anyway, we're going to check for isInProcessOfStopping, but there could still be a timing window. So, we are going to call a different
//setThreadContext method that will not log the errors and we will log it here only if we are not in the process of stopping
if (this.isInProcessOfStopping()) {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[RUN_INVALIDATION], "application in the process of stopping - " + appNameForLogging);
}
return;
}
// PK99859: Set the thread context
try {
setThreadContextDuringRunInvalidation();
} catch (RuntimeException e) {
if (!this.isInProcessOfStopping()) {
//the exception is only expected if we are in the process of stopping the application
//therefore, if we have not stopped the app, report the error
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.SEVERE, MemoryStore.class.getSimpleName(), methodNames[RUN_INVALIDATION], "CommonMessage.exception", e);
}
return;
}
while (iter.hasNext()) {
String key = (String) iter.next();
ISession s = (ISession) _sessions.get(key);
// sync on the session and check if its active...
if (s != null) {
synchronized (s) {
if (s.isValid()) {
if (s.getMaxInactiveInterval() != -1) {
long currentAccessTime = s.getCurrentAccessTime(); // currentAccessTime
// updated on
// session
// access
// lastAccessedTime
// updated at
// releaseSession
long maxinact = 1000 * (long) s.getMaxInactiveInterval();
boolean active = s.getRefCount() > 0;
if (_isApplicationSessionStore) {
// the RefCount is not correct when dealing with an
// applicationSessionStore
s.setRefCount(0);
active = false;
}
boolean timedOut = (currentAccessTime <= nowTime - maxinact);
/*
* invalidate if:
* session has timedOut AND (is not active OR (the Invalidation
* Multiple has not been set to 0
* and the session is that many times the invalidation interval)
*
* The default value for the invalidation interval is 3.
*
* PK03711 removed check for active and always invalidated
* timedout sessions for v6.1 and earlier
* v7 CTS defect 391577 forced us to put this code back, so we
* introduced the InvalidateIfActive property
* In the service stream, the ForceSessionInvalidationMultiple was
* used, so we are using the same property
*/
if ((timedOut)
&& ((!active) || ((_smc.getForceSessionInvalidationMultiple() != 0) && (currentAccessTime <= nowTime
- (_smc.getForceSessionInvalidationMultiple() * maxinact))))) {
_storeCallback.sessionInvalidatedByTimeout(s);
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
String message = "Going to invalidate session with id=" + s.getId();
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[RUN_INVALIDATION], message);
}
s.invalidate();
}
}
} // isValid
}
}
} // end "while"
} finally {
// PK99859: Unset the thread context
unsetThreadContext();
}
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[RUN_INVALIDATION]);
}
} |
python | def IterQueryInstances(self, FilterQueryLanguage, FilterQuery,
namespace=None, ReturnQueryResultClass=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCount=DEFAULT_ITER_MAXOBJECTCOUNT,
**extra):
# pylint: disable=line-too-long
"""
Execute a query in a namespace, using the Python :term:`py:generator`
idiom to return the result.
*New in pywbem 0.10 as experimental and finalized in 0.12.*
This method uses the corresponding pull operations if supported by the
WBEM server or otherwise the corresponding traditional operation.
This method is an alternative to using the pull operations directly,
that frees the user of having to know whether the WBEM server supports
pull operations.
Other than the other Iter...() methods, this method does not return
a generator object directly, but as a property of the returned object.
The reason for this design is the additionally returned query
result class. The generator property in the returned object is a
generator object that returns the instances in the query result one by
one (using :keyword:`yield`) when the caller iterates through the
generator object. This design causes the entire query result to be
materialized, even if pull operations are used.
By default, this method attempts to perform the corresponding pull
operations
(:meth:`~pywbem.WBEMConnection.OpenQueryInstances` and
:meth:`~pywbem.WBEMConnection.PullInstances`).
If these pull operations are not supported by the WBEM server, this
method falls back to using the corresponding traditional operation
(:meth:`~pywbem.WBEMConnection.ExecQuery`).
Whether the WBEM server supports these pull operations is remembered
in the :class:`~pywbem.WBEMConnection` object (by operation type), and
avoids unnecessary attempts to try these pull operations on that
connection in the future.
The `use_pull_operations` init parameter of
:class:`~pywbem.WBEMConnection` can be used to control the preference
for always using pull operations, always using traditional operations,
or using pull operations if supported by the WBEM server (the default).
This method provides all of the controls of the corresponding pull
operations except for the ability to set different response sizes on
each request; the response size (defined by the `MaxObjectCount`
parameter) is the same for all pull operations in the enumeration
session.
In addition, some functionality is only available if the corresponding
pull operations are used by this method:
* Setting the `ContinueOnError` parameter to `True` will be rejected if
the corresponding traditional operation is used by this method.
The enumeration session that is opened with the WBEM server when using
pull operations is closed automatically when the returned generator
object is exhausted, or when the generator object is closed using its
:meth:`~py:generator.close` method (which may also be called before the
generator is exhausted).
Parameters:
QueryLanguage (:term:`string`):
Name of the query language used in the `Query` parameter, e.g.
"DMTF:CQL" for CIM Query Language, and "WQL" for WBEM Query
Language. Because this is not a filter query, "DMTF:FQL" is not a
valid query language for this request.
Query (:term:`string`):
Query string in the query language specified in the `QueryLanguage`
parameter.
namespace (:term:`string`):
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical
case will be preserved.
If `None`, the default namespace of the connection object will be
used.
ReturnQueryResultClass (:class:`py:bool`):
Controls whether a class definition describing the returned
instances will be returned.
`None` will cause the server to use its default of `False`.
`None` will cause the server to use its default of `False`.
OperationTimeout (:class:`~pywbem.Uint32`):
Minimum time in seconds the WBEM Server shall maintain an open
enumeration session after a previous Open or Pull request is
sent to the client. Once this timeout time has expired, the
WBEM server may close the enumeration session.
* If not `None`, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_INVALID_OPERATION_TIMEOUT`.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default timeout to be used.
ContinueOnError (:class:`py:bool`):
Indicates to the WBEM server to continue sending responses
after an error response has been sent.
* If `True`, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if `True` was specified, causing
:class:`~pywbem.CIMError` to be raised with status code
:attr:`~pywbem.CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED`.
If the corresponding traditional operation is used by this
method, :exc:`~py:exceptions.ValueError` will be raised.
* If `False`, the server is requested to close the enumeration after
sending an error response.
* If `None`, this parameter is not passed to the WBEM server, and
causes the server-implemented default behaviour to be used.
:term:`DSP0200` defines that the server-implemented default is
`False`.
MaxObjectCount (:class:`~pywbem.Uint32`)
Maximum number of instances the WBEM server may return for each of
the open and pull requests issued during the iterations over the
returned generator object.
* If positive, the WBEM server is to return no more than the
specified number of instances.
* Zero is not allowed; it would mean that zero instances
are to be returned for open and all pull requests issued to the
server.
* The default is defined as a system config variable.
* `None` is not allowed.
**extra :
Additional keyword arguments are passed as additional operation
parameters to the WBEM server.
Note that :term:`DSP0200` does not define any additional parameters
for this operation.
Returns:
:class:`~pywbem.IterQueryInstancesReturn`: An object with the
following properties:
* **query_result_class** (:class:`~pywbem.CIMClass`):
The query result class, if requested via the
`ReturnQueryResultClass` parameter.
`None`, if a query result class was not requested.
* **generator** (:term:`py:generator` iterating :class:`~pywbem.CIMInstance`):
A generator object that iterates the CIM instances representing the
query result. These instances do not have an instance path set.
Raises:
Exceptions described in :class:`~pywbem.WBEMConnection`.
Example::
result = conn.IterQueryInstances(
'DMTF:CQL',
'SELECT FROM * where pl > 2')
for inst in result.generator:
print('instance {0}'.format(inst.tomof()))
""" # noqa: E501
# pylint: enable=line-too-long
class IterQueryInstancesReturn(object):
"""
The return data for
:meth:`~pywbem.WBEMConnection.IterQueryInstances`.
"""
def __init__(self, instances, query_result_class=None):
"""Save any query_result_class and instances returned"""
self._query_result_class = query_result_class
self.instances = instances
@property
def query_result_class(self):
"""
:class:`~pywbem.CIMClass`: The query result class, if requested
via the `ReturnQueryResultClass` parameter of
:meth:`~pywbem.WBEMConnection.IterQueryInstances`.
`None`, if a query result class was not requested.
"""
return self._query_result_class
@property
def generator(self):
"""
:term:`py:generator` iterating :class:`~pywbem.CIMInstance`:
A generator object that iterates the CIM instances representing
the query result. These instances do not have an instance path
set.
"""
for inst in self.instances:
yield inst
_validateIterCommonParams(MaxObjectCount, OperationTimeout)
# Common variable for pull result tuple used by pulls and finally:
pull_result = None
try: # try / finally block to allow iter.close()
_instances = []
if (self._use_query_pull_operations is None or
self._use_query_pull_operations):
try: # operation try block
pull_result = self.OpenQueryInstances(
FilterQueryLanguage,
FilterQuery,
namespace=namespace,
ReturnQueryResultClass=ReturnQueryResultClass,
OperationTimeout=OperationTimeout,
ContinueOnError=ContinueOnError,
MaxObjectCount=MaxObjectCount, **extra)
# Open operation succeeded; set has_pull flag
self._use_query_pull_operations = True
_instances = pull_result.instances
# get QueryResultClass from if returned with open
# request.
qrc = pull_result.query_result_class if \
ReturnQueryResultClass else None
if not pull_result.eos:
while not pull_result.eos:
pull_result = self.PullInstances(
pull_result.context,
MaxObjectCount=MaxObjectCount)
_instances.extend(pull_result.instances)
rtn = IterQueryInstancesReturn(_instances,
query_result_class=qrc)
pull_result = None # clear the pull_result
return rtn
# If NOT_SUPPORTED and first request, set flag and try
# alternative request operation.
# If _use_query_pull_operations is True, always raise
# the exception
except CIMError as ce:
if self._use_query_pull_operations is None and \
ce.status_code == CIM_ERR_NOT_SUPPORTED:
self._use_query_pull_operations = False
else:
raise
# Alternate request if Pull not implemented. This does not allow
# the ContinueOnError or ReturnQueryResultClass
assert self._use_query_pull_operations is False
if ReturnQueryResultClass is not None:
raise ValueError('ExecQuery does not support'
' ReturnQueryResultClass.')
if ContinueOnError is not None:
raise ValueError('ExecQuery does not support '
'ContinueOnError.')
# The parameters are QueryLanguage and Query for ExecQuery
_instances = self.ExecQuery(FilterQueryLanguage,
FilterQuery,
namespace=namespace, **extra)
rtn = IterQueryInstancesReturn(_instances)
return rtn
# Cleanup if caller closes the iterator before exhausting it
finally:
# Cleanup only required if the pull context is open and not complete
if pull_result is not None and not pull_result.eos:
self.CloseEnumeration(pull_result.context)
pull_result = None |
java | public void readObject(java.io.DataInputStream dataInputStream,
ObjectManagerState objectManagerState)
throws ObjectManagerException {
final String methodName = "readObject";
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this, cclass, methodName, new Object[] { dataInputStream,
objectManagerState });
try {
byte version = dataInputStream.readByte();
if (Tracing.isAnyTracingEnabled() && trace.isDebugEnabled())
trace.debug(this, cclass, methodName, new Object[] { new Byte(version) });
super.readObject(dataInputStream, objectManagerState);
if (dataInputStream.readByte() == 1) {
// Use ManagedObjectInpuStream so as to get the correct classloader.
java.io.ObjectInputStream objectInputStream = new ManagedObjectInputStream(dataInputStream, objectManagerState);
comparator = (java.util.Comparator) objectInputStream.readObject();
objectInputStream.close();
} // if (dataInputStream.readByte() == 1).
if (dataInputStream.readByte() == 1) {
root = Token.restore(dataInputStream
, objectManagerState
);
} // if (dataInputStream.readByte() == 1).
size = dataInputStream.readLong();
} catch (java.io.IOException exception) {
// No FFDC Code Needed.
ObjectManager.ffdc.processException(this, cclass, methodName, exception, "1:2412:1.44");
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this, cclass, methodName, exception);
throw new PermanentIOException(this, exception);
} catch (java.lang.ClassNotFoundException exception) {
// No FFDC Code Needed.
ObjectManager.ffdc.processException(this, cclass, methodName, exception, "1:2420:1.44");
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this, cclass, methodName, new Object[] { "ClassNotFoundException:2423",
exception });
throw new com.ibm.ws.objectManager.ClassNotFoundException(this, exception);
} // try.
availableSize = size; // Start as last commited.
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this, cclass, methodName);
} |
java | public void start() throws Exception {
// 1. Do prepare work
// create an instance of state manager
String statemgrClass = Context.stateManagerClass(config);
LOG.info("Context.stateManagerClass " + statemgrClass);
IStateManager statemgr;
try {
statemgr = ReflectionUtils.newInstance(statemgrClass);
} catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
throw new Exception(String.format(
"Failed to instantiate state manager class '%s'",
statemgrClass), e);
}
// Put it in a try block so that we can always clean resources
try {
// initialize the statemgr
statemgr.initialize(config);
Boolean b = statemgr.setMetricsCacheLocation(metricsCacheLocation, topologyName)
.get(5000, TimeUnit.MILLISECONDS);
if (b != null && b) {
LOG.info("metricsCacheLocation " + metricsCacheLocation.toString());
LOG.info("topologyName " + topologyName.toString());
LOG.info("Starting Metrics Cache HTTP Server");
metricsCacheManagerHttpServer.start();
// 2. The MetricsCacheServer would run in the main thread
// We do it in the final step since it would await the main thread
LOG.info("Starting Metrics Cache Server");
metricsCacheManagerServer.start();
metricsCacheManagerServerLoop.loop();
} else {
throw new RuntimeException("Failed to set metricscahe location.");
}
} finally {
// 3. Do post work basing on the result
// Currently nothing to do here
// 4. Close the resources
SysUtils.closeIgnoringExceptions(statemgr);
}
} |
python | def if_else(self, pred, likely=None):
"""
A context manager which sets up two conditional basic blocks based
on the given predicate (a i1 value).
A tuple of context managers is yield'ed. Each context manager
acts as a if_then() block.
*likely* has the same meaning as in if_then().
Typical use::
with builder.if_else(pred) as (then, otherwise):
with then:
# emit instructions for when the predicate is true
with otherwise:
# emit instructions for when the predicate is false
"""
bb = self.basic_block
bbif = self.append_basic_block(name=_label_suffix(bb.name, '.if'))
bbelse = self.append_basic_block(name=_label_suffix(bb.name, '.else'))
bbend = self.append_basic_block(name=_label_suffix(bb.name, '.endif'))
br = self.cbranch(pred, bbif, bbelse)
if likely is not None:
br.set_weights([99, 1] if likely else [1, 99])
then = self._branch_helper(bbif, bbend)
otherwise = self._branch_helper(bbelse, bbend)
yield then, otherwise
self.position_at_end(bbend) |
java | public List<Milestone> getGroupMilestones(Object groupIdOrPath) throws GitLabApiException {
return (getGroupMilestones(groupIdOrPath, getDefaultPerPage()).all());
} |
java | public void setLoggedOutIndicatorPattern(String loggedOutIndicatorPattern) {
if (loggedOutIndicatorPattern == null || loggedOutIndicatorPattern.trim().length() == 0) {
this.loggedOutIndicatorPattern = null;
} else {
this.loggedOutIndicatorPattern = Pattern.compile(loggedOutIndicatorPattern);
}
} |
python | def table_as_df(self, table_name):
"""Return a table as a dataframe."""
self.table_must_exist(table_name)
query = "SELECT * FROM `%s`" % table_name.lower()
return pandas.read_sql(query, self.own_conn) |
python | def report(self, req):
"""Adds a report request to the cache.
Returns ``None`` if it could not be aggregated, and callers need to
send the request to the server, otherwise it returns ``CACHED_OK``.
Args:
req (:class:`sc_messages.ReportRequest`): the request
to be aggregated
Result:
``None`` if the request as not cached, otherwise ``CACHED_OK``
"""
if self._cache is None:
return None # no cache, send request now
if not isinstance(req, sc_messages.ServicecontrolServicesReportRequest):
raise ValueError(u'Invalid request')
if req.serviceName != self.service_name:
_logger.error(u'bad report(): service_name %s does not match ours %s',
req.serviceName, self.service_name)
raise ValueError(u'Service name mismatch')
report_req = req.reportRequest
if report_req is None:
_logger.error(u'bad report(): no report_request in %s', req)
raise ValueError(u'Expected report_request not set')
if _has_high_important_operation(report_req) or self._cache is None:
return None
ops_by_signature = _key_by_signature(report_req.operations,
_sign_operation)
# Concurrency:
#
# This holds a lock on the cache while updating it. No i/o operations
# are performed, so any waiting threads see minimal delays
with self._cache as cache:
for key, op in ops_by_signature.items():
agg = cache.get(key)
if agg is None:
cache[key] = operation.Aggregator(op, self._kinds)
else:
agg.add(op)
return self.CACHED_OK |
java | @Override
public LogIterator getIterator(Zxid zxid) throws IOException {
SimpleLogIterator iter = new SimpleLogIterator(this.logFile);
while(iter.hasNext()) {
Transaction txn = iter.next();
if(txn.getZxid().compareTo(zxid) >= 0) {
iter.backward();
break;
}
}
return iter;
} |
python | def parse_plain_scalar_indent(TokenClass):
"""Process indentation spaces in a plain scalar."""
def callback(lexer, match, context):
text = match.group()
if len(text) <= context.indent:
context.stack.pop()
context.stack.pop()
return
if text:
yield match.start(), TokenClass, text
context.pos = match.end()
return callback |
java | protected void deliverInvokeTimeout(MAPDialog mapDialog, Invoke invoke) {
for (MAPServiceListener serLis : this.serviceListeners) {
serLis.onInvokeTimeout(mapDialog, invoke.getInvokeId());
}
} |
java | public void setDefinitions(java.util.Collection<DefinitionInformation> definitions) {
if (definitions == null) {
this.definitions = null;
return;
}
this.definitions = new java.util.ArrayList<DefinitionInformation>(definitions);
} |
java | public WriteResponse write (String record) throws IOException {
recordsAttempted.mark();
String encoded = encodeRecord(record);
int returnCode = request (encoded);
recordsSuccess.mark();
bytesWritten.mark(encoded.length());
return WRITE_RESPONSE_WRAPPER.wrap(returnCode);
} |
python | def find_this(search, source=SOURCE):
"""Take a string and a filename path string and return the found value."""
print("Searching for {what}.".format(what=search))
if not search or not source:
print("Not found on source: {what}.".format(what=search))
return ""
return str(re.compile(r'.*__{what}__ = "(.*?)"'.format(
what=search), re.S).match(source).group(1)).strip() |
java | public static <E> List<E> search(Iterator<E> iterator, Predicate<E> predicate) {
final Function<Iterator<E>, ArrayList<E>> consumer = new ConsumeIntoCollection<>(new ArrayListFactory<E>());
final FilteringIterator<E> filtered = new FilteringIterator<E>(iterator, predicate);
return consumer.apply(filtered);
} |
python | async def uint(self, elem, elem_type, params=None):
"""
Integer types
:param elem:
:param elem_type:
:param params:
:return:
"""
if self.writing:
return await x.dump_uint(self.iobj, elem, elem_type.WIDTH)
else:
return await x.load_uint(self.iobj, elem_type.WIDTH) |
java | private static void reduce(int size) {
for (int i = 0; i < maxSelectors - size; i++) {
try {
Selector selector = selectors.pop();
selector.close();
} catch (IOException e) {
logger.error("SelectorFactory.reduce", e);
}
}
} |
java | public static org.neo4j.graphdb.Node createTemplateFieldInfoNode(
final AbstractGraphDatabase graphDatabase,
final TemplateFieldInfo fieldInfo) {
final org.neo4j.graphdb.Node fieldNode = TemplateItemInfo
.createTemplateItemNode(graphDatabase, fieldInfo);
fieldNode
.setProperty(TemplateXMLFields.FIELD_TYPE, fieldInfo.getType());
return fieldNode;
} |
java | public void cancel() {
try {
// FileOutputStream is also closed cascadingly
if (outStream != null) {
outStream.close();
outStream = null;
}
// Clear encryptor:
encryptor = null;
} catch (IOException e) {
Log.w(Log.TAG_BLOB_STORE, "Exception closing buffered output stream", e);
}
tempFile.delete();
} |
java | final void warnInvalidRecord(DnsRecordType type, ByteBuf content) {
if (logger().isWarnEnabled()) {
final String dump = ByteBufUtil.hexDump(content);
logger().warn("{} Skipping invalid {} record: {}",
logPrefix(), type.name(), dump.isEmpty() ? "<empty>" : dump);
}
} |
python | def ParseFromUnicode(self, value):
"""Parse a string into a client URN.
Convert case so that all URNs are of the form C.[0-9a-f].
Args:
value: string value to parse
"""
precondition.AssertType(value, Text)
value = value.strip()
super(ClientURN, self).ParseFromUnicode(value)
match = self.CLIENT_ID_RE.match(self._string_urn)
if not match:
raise type_info.TypeValueError("Client urn malformed: %s" % value)
clientid = match.group("clientid")
clientid_correctcase = "".join((clientid[0].upper(), clientid[1:].lower()))
self._string_urn = self._string_urn.replace(clientid, clientid_correctcase,
1) |
java | public static <T> T parse(byte[] in, Class<T> mapTo) {
try {
JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
return p.parse(in, defaultReader.getMapper(mapTo));
} catch (Exception e) {
return null;
}
} |
java | public static char matchBracket(char c)
{
if(openBrackets.containsKey(c))
{
return openBrackets.get(c);
}
else if(closingBrackets.containsKey(c))
{
return closingBrackets.get(c);
}
return c;
} |
java | protected void addInvalidValues(Set<ConstraintViolation<T>> invalidValues) {
if (invalidValues != null) {
for (ConstraintViolation invalidValue : invalidValues) {
results.addMessage(translateMessage(invalidValue));
}
}
} |
java | public StoreAsBinaryConfigurationBuilder disable() {
attributes.attribute(ENABLED).set(false);
getBuilder().memory().storageType(StorageType.OBJECT);
return this;
} |
python | def on_header(self, name: bytes, value: bytes) -> None:
"""
header 回调
"""
name_ = decode_bytes(name).casefold()
val = decode_bytes(value)
if name_ == "cookie":
# 加载上次的 cookie
self._cookies.load(val)
if name_ in self._headers:
# 多个相同的 header
old = self._headers[name_]
if isinstance(old, list):
old.append(val)
else:
self._headers[name_] = [old, val]
else:
self._headers[name_] = val |
java | public void setGravity(double gravity)
{
if(Double.isInfinite(gravity) || Double.isNaN(gravity) || gravity <= 0)
throw new IllegalArgumentException("Gravity must be positive, not " + gravity);
this.gravity = gravity;
} |
java | public JSONArray element( Map value, JsonConfig jsonConfig ) {
if( value instanceof JSONObject ){
elements.add( value );
return this;
}else{
return element( JSONObject.fromObject( value, jsonConfig ) );
}
} |
java | public static Iterable<Map<String, Object>> scan(final DataStore dataStore,
final String table,
final @Nullable String fromKeyExclusive,
final long limit,
final boolean includeDeletes,
final ReadConsistency consistency) {
return RestartingStreamingIterator.stream(fromKeyExclusive, limit,
new StreamingIteratorSupplier<Map<String, Object>, String>() {
@Override
public Iterator<Map<String, Object>> get(String fromToken, long limit) {
return dataStore.scan(table, fromToken, limit, includeDeletes, consistency);
}
@Override
public String getNextToken(Map<String, Object> object) {
return Intrinsic.getId(object);
}
});
} |
java | protected static String buildMessage(String msg) {
StackTraceElement caller = new Throwable().fillInStackTrace().getStackTrace()[2];
return caller.getClassName() + "." + caller.getMethodName() + "(): \n" + msg;
} |
python | def find_source_files(input_path, excludes):
""" Get a list of filenames for all Java source files within the given
directory.
"""
java_files = []
input_path = os.path.normpath(os.path.abspath(input_path))
for dirpath, dirnames, filenames in os.walk(input_path):
if is_excluded(dirpath, excludes):
del dirnames[:]
continue
for filename in filenames:
if filename.endswith(".java"):
java_files.append(os.path.join(dirpath, filename))
return java_files |
python | def get_single_hdd_only_candidate_model(
data,
minimum_non_zero_hdd,
minimum_total_hdd,
beta_hdd_maximum_p_value,
weights_col,
balance_point,
):
""" Return a single candidate hdd-only model for a particular balance
point.
Parameters
----------
data : :any:`pandas.DataFrame`
A DataFrame containing at least the column ``meter_value`` and
``hdd_<balance_point>``
DataFrames of this form can be made using the
:any:`eemeter.create_caltrack_daily_design_matrix` or
:any:`eemeter.create_caltrack_billing_design_matrix` methods.
minimum_non_zero_hdd : :any:`int`
Minimum allowable number of non-zero heating degree day values.
minimum_total_hdd : :any:`float`
Minimum allowable total sum of heating degree day values.
beta_hdd_maximum_p_value : :any:`float`
The maximum allowable p-value of the beta hdd parameter.
weights_col : :any:`str` or None
The name of the column (if any) in ``data`` to use as weights.
balance_point : :any:`float`
The heating balance point for this model.
Returns
-------
candidate_model : :any:`CalTRACKUsagePerDayCandidateModel`
A single hdd-only candidate model, with any associated warnings.
"""
model_type = "hdd_only"
hdd_column = "hdd_%s" % balance_point
formula = "meter_value ~ %s" % hdd_column
if weights_col is None:
weights = 1
else:
weights = data[weights_col]
period_days = weights
degree_day_warnings = []
degree_day_warnings.extend(
get_total_degree_day_too_low_warning(
model_type,
balance_point,
"hdd",
data[hdd_column],
period_days,
minimum_total_hdd,
)
)
degree_day_warnings.extend(
get_too_few_non_zero_degree_day_warning(
model_type, balance_point, "hdd", data[hdd_column], minimum_non_zero_hdd
)
)
if len(degree_day_warnings) > 0:
return CalTRACKUsagePerDayCandidateModel(
model_type=model_type,
formula=formula,
status="NOT ATTEMPTED",
warnings=degree_day_warnings,
)
try:
model = smf.wls(formula=formula, data=data, weights=weights)
except Exception as e:
return get_fit_failed_candidate_model(model_type, formula)
result = model.fit()
r_squared_adj = result.rsquared_adj
beta_hdd_p_value = result.pvalues[hdd_column]
# CalTrack 3.3.1.3
model_params = {
"intercept": result.params["Intercept"],
"beta_hdd": result.params[hdd_column],
"heating_balance_point": balance_point,
}
model_warnings = []
# CalTrack 3.4.3.2
for parameter in ["intercept", "beta_hdd"]:
model_warnings.extend(
get_parameter_negative_warning(model_type, model_params, parameter)
)
model_warnings.extend(
get_parameter_p_value_too_high_warning(
model_type,
model_params,
parameter,
beta_hdd_p_value,
beta_hdd_maximum_p_value,
)
)
if len(model_warnings) > 0:
status = "DISQUALIFIED"
else:
status = "QUALIFIED"
return CalTRACKUsagePerDayCandidateModel(
model_type=model_type,
formula=formula,
status=status,
warnings=model_warnings,
model_params=model_params,
model=model,
result=result,
r_squared_adj=r_squared_adj,
) |
python | def _api_action(url, req, data=None):
"""Take action based on what kind of request is needed."""
requisite_headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
auth = (user, token)
if req == "GET":
response = requests.get(url, headers=requisite_headers, auth=auth)
elif req == "PUT":
response = requests.put(url, headers=requisite_headers, auth=auth,
data=data)
elif req == "POST":
response = requests.post(url, headers=requisite_headers, auth=auth,
data=data)
elif req == "DELETE":
response = requests.delete(url, headers=requisite_headers, auth=auth)
return response.status_code, response.text |
python | def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]:
"""
For the given iterable of object iterations, return an iterable of the most common object at each position of the
inner iterations.
E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the most common objects
at the first and second positions respectively.
:param all_votes: an iterable of object iterations
:return: the most common objects in the iterations (the major vote)
"""
return [Counter(votes).most_common()[0][0] for votes in zip(*all_votes)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.