language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def jac(x,a):
""" Jacobian matrix given Christophe's suggestion of f """
return (x-a) / np.sqrt(((x-a)**2).sum(1))[:,np.newaxis] |
java | @NonNull
public static DeleteSelection deleteFrom(
@Nullable CqlIdentifier keyspace, @NonNull CqlIdentifier table) {
return new DefaultDelete(keyspace, table);
} |
python | def add(self):
""" Add a new VRF.
"""
c.action = 'add'
if 'action' in request.params:
if request.params['action'] == 'add':
v = VRF()
if request.params['rt'].strip() != '':
v.rt = request.params['rt']
if request.params['name'].strip() != '':
v.name = request.params['name']
v.description = request.params['description']
v.save()
redirect(url(controller='vrf', action='list'))
return render('/vrf_add.html') |
java | public static String[] getParameterNames(CtMethod ctMethod) throws NotFoundException {
MethodInfo methodInfo = ctMethod.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
// logger.info("methodInfo.getConstPool().getSize():");
LocalVariableAttribute attribute = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
// String[] names = new String[attribute.tableLength() - 1];
String[] paramNames = new String[ctMethod.getParameterTypes().length];
int pos = 0;
if (true) {
int size = attribute.tableLength();
if (size > 0) {
String[] names = new String[size - 1];
for (int i = 0; i < names.length; i++) {
names[i] = attribute.variableName(i);
if ("this".equals(names[i])) {
pos = i + 1;
break;
}
}
// logger.info(methodInfo.getName() + " pos:" + pos + " allNames:" + StringUtils.join(names, ", "));
}
}
// logger.info(methodInfo.getName() + " pos:" + pos);
for (int i = 0; i < paramNames.length; i++) {
// paramNames[i] = attribute.variableName(i + 1);
try {
paramNames[i] = attribute.variableName(i + pos);
// logger.info("paramNames[" + i + "]:" + paramNames[i]);
}
catch (RuntimeException e) {
throw e;
}
}
// System.err.println("paramNames:" + StringUtils.join(paramNames));
return paramNames;
} |
python | def assert_200(response, max_len=500):
""" Check that a HTTP response returned 200. """
if response.status_code == 200:
return
raise ValueError(
"Response was {}, not 200:\n{}\n{}".format(
response.status_code,
json.dumps(dict(response.headers), indent=2),
response.content[:max_len])) |
java | boolean connectionFailed(IOException e) {
// Any future attempt to connect using this strategy will be a fallback attempt.
isFallback = true;
if (!isFallbackPossible) {
return false;
}
// If there was a protocol problem, don't recover.
if (e instanceof ProtocolException) {
return false;
}
// If there was an interruption or timeout (SocketTimeoutException), don't recover.
// For the socket connect timeout case we do not try the same host with a different
// ConnectionSpec: we assume it is unreachable.
if (e instanceof InterruptedIOException) {
return false;
}
// Look for known client-side or negotiation errors that are unlikely to be fixed by trying
// again with a different connection spec.
if (e instanceof SSLHandshakeException) {
// If the problem was a CertificateException from the X509TrustManager, do not retry.
if (e.getCause() instanceof CertificateException) {
return false;
}
}
if (e instanceof SSLPeerUnverifiedException) {
// e.g. a certificate pinning error.
return false;
}
// Retry for all other SSL failures.
return e instanceof SSLException;
} |
java | public static int execute(String[] commandArray, String[] alternativeEnvVars, File workingDir, Receiver outputReceiver) throws IOException {
Runtime rt = Runtime.getRuntime();
//command + arguments, environment parameters, workingdir
Process proc = null;
try {
proc = rt.exec(commandArray, alternativeEnvVars, workingDir);
} catch (Exception e) {
System.out.println("unable to execute command: " + ArraySupport.format(commandArray, ", "));
e.printStackTrace();
throw new RuntimeException("unable to execute command: " + ArraySupport.format(commandArray, ", "), e);
}
// any error message?
Transponder errorForwarder = new
Transponder(proc.getErrorStream(), new Pipe(outputReceiver));
// any output?
Transponder outputForwarder = new
Transponder(proc.getInputStream(), new Pipe(outputReceiver));
errorForwarder.start();
outputForwarder.start();
try {
int retval = proc.waitFor();//threads will stop when proc is done and InputStream and ErrorStream close
errorForwarder.stop();
outputForwarder.stop();
return retval;
}
catch (InterruptedException ie) {
//...
}
return -1;
} |
java | public void add(double datum) {
dbuf[nd++] = datum;
if (datum < q0) {
q0 = datum;
}
if (datum > qm) {
qm = datum;
}
if (nd == nbuf) {
update();
}
} |
python | def get_cookies(self):
'''
Retreive the cookies from the remote browser.
Return value is a list of http.cookiejar.Cookie() instances.
These can be directly used with the various http.cookiejar.XXXCookieJar
cookie management classes.
'''
ret = self.Network_getAllCookies()
assert 'result' in ret, "No return value in function response!"
assert 'cookies' in ret['result'], "No 'cookies' key in function response"
cookies = []
for raw_cookie in ret['result']['cookies']:
# Chromium seems to support the following key values for the cookie dict:
# "name"
# "value"
# "domain"
# "path"
# "expires"
# "httpOnly"
# "session"
# "secure"
#
# This seems supported by the fact that the underlying chromium cookie implementation has
# the following members:
# std::string name_;
# std::string value_;
# std::string domain_;
# std::string path_;
# base::Time creation_date_;
# base::Time expiry_date_;
# base::Time last_access_date_;
# bool secure_;
# bool httponly_;
# CookieSameSite same_site_;
# CookiePriority priority_;
#
# See chromium/net/cookies/canonical_cookie.h for more.
#
# I suspect the python cookie implementation is derived exactly from the standard, while the
# chromium implementation is more of a practically derived structure.
# Network.setCookie
baked_cookie = http.cookiejar.Cookie(
# We assume V0 cookies, principally because I don't think I've /ever/ actually encountered a V1 cookie.
# Chromium doesn't seem to specify it.
version = 0,
name = raw_cookie['name'],
value = raw_cookie['value'],
port = None,
port_specified = False,
domain = raw_cookie['domain'],
domain_specified = True,
domain_initial_dot = False,
path = raw_cookie['path'],
path_specified = False,
secure = raw_cookie['secure'],
expires = raw_cookie['expires'],
discard = raw_cookie['session'],
comment = None,
comment_url = None,
rest = {"httponly":"%s" % raw_cookie['httpOnly']},
rfc2109 = False
)
cookies.append(baked_cookie)
return cookies |
java | public void done() {
final int processing_time = processingTimeMillis();
final String url = request.getUri();
final String msg = String.format("HTTP %s done in %d ms", url, processing_time);
if (url.startsWith("/api/put") && LOG.isDebugEnabled()) {
// NOTE: Suppresses too many log lines from /api/put.
LOG.debug(msg);
} else {
logInfo(msg);
}
logInfo("HTTP " + request.getUri() + " done in " + processing_time + "ms");
} |
python | def generate(self,
x,
y=None,
y_target=None,
eps=None,
clip_min=None,
clip_max=None,
nb_iter=None,
is_targeted=None,
early_stop_loss_threshold=None,
learning_rate=DEFAULT_LEARNING_RATE,
delta=DEFAULT_DELTA,
spsa_samples=DEFAULT_SPSA_SAMPLES,
batch_size=None,
spsa_iters=DEFAULT_SPSA_ITERS,
is_debug=False,
epsilon=None,
num_steps=None):
"""
Generate symbolic graph for adversarial examples.
:param x: The model's symbolic inputs. Must be a batch of size 1.
:param y: A Tensor or None. The index of the correct label.
:param y_target: A Tensor or None. The index of the target label in a
targeted attack.
:param eps: The size of the maximum perturbation, measured in the
L-infinity norm.
:param clip_min: If specified, the minimum input value
:param clip_max: If specified, the maximum input value
:param nb_iter: The number of optimization steps.
:param early_stop_loss_threshold: A float or None. If specified, the
attack will end as soon as the loss
is below `early_stop_loss_threshold`.
:param learning_rate: Learning rate of ADAM optimizer.
:param delta: Perturbation size used for SPSA approximation.
:param spsa_samples: Number of inputs to evaluate at a single time.
The true batch size (the number of evaluated
inputs for each update) is `spsa_samples *
spsa_iters`
:param batch_size: Deprecated param that is an alias for spsa_samples
:param spsa_iters: Number of model evaluations before performing an
update, where each evaluation is on `spsa_samples`
different inputs.
:param is_debug: If True, print the adversarial loss after each update.
:param epsilon: Deprecated alias for `eps`
:param num_steps: Deprecated alias for `nb_iter`.
:param is_targeted: Deprecated argument. Ignored.
"""
if epsilon is not None:
if eps is not None:
raise ValueError("Should not specify both eps and its deprecated "
"alias, epsilon")
warnings.warn("`epsilon` is deprecated. Switch to `eps`. `epsilon` may "
"be removed on or after 2019-04-15.")
eps = epsilon
del epsilon
if num_steps is not None:
if nb_iter is not None:
raise ValueError("Should not specify both nb_iter and its deprecated "
"alias, num_steps")
warnings.warn("`num_steps` is deprecated. Switch to `nb_iter`. "
"`num_steps` may be removed on or after 2019-04-15.")
nb_iter = num_steps
del num_steps
assert nb_iter is not None
if (y is not None) + (y_target is not None) != 1:
raise ValueError("Must specify exactly one of y (untargeted attack, "
"cause the input not to be classified as this true "
"label) and y_target (targeted attack, cause the "
"input to be classified as this target label).")
if is_targeted is not None:
warnings.warn("`is_targeted` is deprecated. Simply do not specify it."
" It may become an error to specify it on or after "
"2019-04-15.")
assert is_targeted == y_target is not None
is_targeted = y_target is not None
if x.get_shape().as_list()[0] is None:
check_batch = utils_tf.assert_equal(tf.shape(x)[0], 1)
with tf.control_dependencies([check_batch]):
x = tf.identity(x)
elif x.get_shape().as_list()[0] != 1:
raise ValueError("For SPSA, input tensor x must have batch_size of 1.")
if batch_size is not None:
warnings.warn(
'The "batch_size" argument to SPSA is deprecated, and will '
'be removed on 2019-03-17. '
'Please use spsa_samples instead.')
spsa_samples = batch_size
optimizer = SPSAAdam(
lr=learning_rate,
delta=delta,
num_samples=spsa_samples,
num_iters=spsa_iters)
def loss_fn(x, label):
"""
Margin logit loss, with correct sign for targeted vs untargeted loss.
"""
logits = self.model.get_logits(x)
loss_multiplier = 1 if is_targeted else -1
return loss_multiplier * margin_logit_loss(
logits, label,
nb_classes=self.model.nb_classes or logits.get_shape()[-1])
y_attack = y_target if is_targeted else y
adv_x = projected_optimization(
loss_fn,
x,
y_attack,
eps,
num_steps=nb_iter,
optimizer=optimizer,
early_stop_loss_threshold=early_stop_loss_threshold,
is_debug=is_debug,
clip_min=clip_min,
clip_max=clip_max
)
return adv_x |
python | def get_project_name_from_path(path, append_mx=False):
"""Get the project name from a path.
For a path "/home/peter/hans/HLC12398/online/M1_13.tdms" or
For a path "/home/peter/hans/HLC12398/online/data/M1_13.tdms" or
without the ".tdms" file, this will return always "HLC12398".
Parameters
----------
path: str
path to tdms file
append_mx: bool
append measurement number, e.g. "M1"
"""
path = pathlib.Path(path)
if path.suffix == ".tdms":
dirn = path.parent
mx = path.name.split("_")[0]
elif path.is_dir():
dirn = path
mx = ""
else:
dirn = path.parent
mx = ""
project = ""
if mx:
# check para.ini
para = dirn / (mx + "_para.ini")
if para.exists():
with para.open() as fd:
lines = fd.readlines()
for line in lines:
if line.startswith("Sample Name ="):
project = line.split("=")[1].strip()
break
if not project:
# check if the directory contains data or is online
root1, trail1 = dirn.parent, dirn.name
root2, trail2 = root1.parent, root1.name
trail3 = root2.name
if trail1.lower() in ["online", "offline"]:
# /home/peter/hans/HLC12398/online/
project = trail2
elif (trail1.lower() == "data" and
trail2.lower() in ["online", "offline"]):
# this is olis new folder sctructure
# /home/peter/hans/HLC12398/online/data/
project = trail3
else:
project = trail1
if append_mx:
project += " - " + mx
return project |
java | public static boolean isPrimitive(Field field )
{
if(field == null)
return false;
String fieldName = field.getName();
if("serialVersionUID".equals(fieldName))
return false;
return isPrimitive(field.getType());
} |
java | protected void renderXML(String xml, String xslt, HttpServletResponse response)
throws FOPException, TransformerException, IOException {
//Setup sources
Source xmlSrc = convertString2Source(xml);
Source xsltSrc = convertString2Source(xslt);
//Setup the XSL transformation
Transformer transformer = this.transFactory.newTransformer(xsltSrc);
transformer.setURIResolver(this.uriResolver);
//Start transformation and rendering process
render(xmlSrc, transformer, response);
} |
java | public JKTableColumn getTableColumn(final int col, final boolean visibleIndex) {
int actualIndex;
if (visibleIndex) {
actualIndex = this.visibilityManager.getActualIndexFromVisibleIndex(col);
} else {
actualIndex = col;
}
return this.tableColumns.get(actualIndex);
} |
java | public static <T>
Collector<T, ?, DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper) {
return new CollectorImpl<T, DoubleSummaryStatistics, DoubleSummaryStatistics>(
DoubleSummaryStatistics::new,
(r, t) -> r.accept(mapper.applyAsDouble(t)),
(l, r) -> { l.combine(r); return l; }, CH_ID);
} |
java | public BasicDependencyContainer add(Dependency dependency)
{
if (dependency == this)
throw new IllegalArgumentException("Can't add self as a dependency.");
if (! _dependencyList.contains(dependency))
_dependencyList.add(dependency);
// server/1d0w
// XXX: _lastCheckTime = 0;
return this;
} |
python | def reflect_right(self, value):
"""Only reflects the value if is < self."""
if value < self:
value = self.reflect(value)
return value |
java | public static double convertToDouble (@Nonnull final Object aSrcValue)
{
if (aSrcValue == null)
throw new TypeConverterException (double.class, EReason.NULL_SOURCE_NOT_ALLOWED);
final Double aValue = convert (aSrcValue, Double.class);
return aValue.doubleValue ();
} |
python | def skip_redundant(iterable, skipset=None):
"""
Redundant items are repeated items or items in the original skipset.
"""
if skipset is None:
skipset = set()
for item in iterable:
if item not in skipset:
skipset.add(item)
yield item |
java | public static SourceFile scanSingleFileConfig(CxxLanguage language, InputFile file, CxxConfiguration cxxConfig,
SquidAstVisitor<Grammar>... visitors) {
if (!file.isFile()) {
throw new IllegalArgumentException("File '" + file + "' not found.");
}
AstScanner<Grammar> scanner = create(language, cxxConfig, visitors);
scanner.scanFile(file.file());
Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class));
if (sources.size() != 1) {
throw new IllegalStateException("Only one SourceFile was expected whereas "
+ sources.size() + " has been returned.");
}
return (SourceFile) sources.iterator().next();
} |
java | @Override
protected UUID doDeserialize( String key, JsonDeserializationContext ctx ) {
return UUID.fromString( key );
} |
java | public Matrix4f billboardCylindrical(Vector3fc objPos, Vector3fc targetPos, Vector3fc up) {
float dirX = targetPos.x() - objPos.x();
float dirY = targetPos.y() - objPos.y();
float dirZ = targetPos.z() - objPos.z();
// left = up x dir
float leftX = up.y() * dirZ - up.z() * dirY;
float leftY = up.z() * dirX - up.x() * dirZ;
float leftZ = up.x() * dirY - up.y() * dirX;
// normalize left
float invLeftLen = 1.0f / (float) Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ);
leftX *= invLeftLen;
leftY *= invLeftLen;
leftZ *= invLeftLen;
// recompute dir by constraining rotation around 'up'
// dir = left x up
dirX = leftY * up.z() - leftZ * up.y();
dirY = leftZ * up.x() - leftX * up.z();
dirZ = leftX * up.y() - leftY * up.x();
// normalize dir
float invDirLen = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ);
dirX *= invDirLen;
dirY *= invDirLen;
dirZ *= invDirLen;
// set matrix elements
this._m00(leftX);
this._m01(leftY);
this._m02(leftZ);
this._m03(0.0f);
this._m10(up.x());
this._m11(up.y());
this._m12(up.z());
this._m13(0.0f);
this._m20(dirX);
this._m21(dirY);
this._m22(dirZ);
this._m23(0.0f);
this._m30(objPos.x());
this._m31(objPos.y());
this._m32(objPos.z());
this._m33(1.0f);
_properties(PROPERTY_AFFINE | PROPERTY_ORTHONORMAL);
return this;
} |
java | public RouteMatcher connectWithRegEx(String regex, Handler<HttpServerRequest> handler) {
addRegEx(regex, handler, connectBindings);
return this;
} |
java | public void add(final Class<?> clazz) {
if (this.clazzes.contains(clazz)) {
throw new IllegalArgumentException(
"Only one class-instance per benchmark allowed");
} else {
this.clazzes.add(clazz);
}
} |
java | public void setRemoteMessageTask(RemoteTask messageTaskPeer) throws RemoteException
{
BaseTransport transport = this.createProxyTransport(SET_REMOTE_MESSAGE_TASK);
String strTaskID = null;
if (messageTaskPeer instanceof BaseProxy)
{ // Always a TaskProxy
strTaskID = ((BaseProxy)messageTaskPeer).getIDPath();
}
transport.addParam(ID, strTaskID);
transport.sendMessageAndGetReply();
} |
python | def remove(self, name_or_klass):
"""
Removes the specified panel.
:param name_or_klass: Name or class of the panel to remove.
:return: The removed panel
"""
logger.debug('removing panel %s' % name_or_klass)
panel = self.get(name_or_klass)
panel.on_uninstall()
panel.hide()
panel.setParent(None)
return self._panels[panel.position].pop(panel.name, None) |
java | @Override
protected void unserializeFrom(RawDataBuffer in)
{
super.unserializeFrom(in);
message = MessageSerializer.unserializeFrom(in, true);
} |
python | def validate(config):
'''
Validate the beacon configuration
'''
_config = {}
list(map(_config.update, config))
if not isinstance(config, list):
return False, ('Configuration for avahi_announce '
'beacon must be a list.')
elif not all(x in _config for x in ('servicetype',
'port',
'txt')):
return False, ('Configuration for avahi_announce beacon '
'must contain servicetype, port and txt items.')
return True, 'Valid beacon configuration.' |
python | def intersect(self, other):
"""Calculate the intersection of this rectangle and another rectangle.
Args:
other (Rect): The other rectangle.
Returns:
Rect: The intersection of this rectangle and the given other rectangle, or None if there is no such
intersection.
"""
intersection = Rect()
if lib.SDL_IntersectRect(self._ptr, self._ptr, intersection._ptr):
return intersection
else:
return None |
java | private void applyPatchForFeatures() {
for (int i = 0; i < totalFeatures.length; i++) {
int total = totalFeatures[i];
int failures = getFailedFeatures()[i];
if (total < failures) {
// this data must be changed since it was generated by invalid code
int tmp = total;
totalFeatures[i] = failures;
failedFeatures[i] = tmp;
}
}
} |
python | def levels_for(self, time_op, groups, df):
"""
Compute the partition at each `level` from the dataframe.
"""
levels = {}
for i in range(0, len(groups) + 1):
agg_df = df.groupby(groups[:i]) if i else df
levels[i] = (
agg_df.mean() if time_op == 'agg_mean'
else agg_df.sum(numeric_only=True))
return levels |
java | private static String internalBind(String message, Object[] args, String argZero, String argOne) {
if (message == null)
return "No message available."; //$NON-NLS-1$
if (args == null || args.length == 0)
args = EMPTY_ARGS;
int length = message.length();
//estimate correct size of string buffer to avoid growth
int bufLen = length + (args.length * 5);
if (argZero != null)
bufLen += argZero.length() - 3;
if (argOne != null)
bufLen += argOne.length() - 3;
StringBuffer buffer = new StringBuffer(bufLen < 0 ? 0 : bufLen);
for (int i = 0; i < length; i++) {
char c = message.charAt(i);
switch (c) {
case '{' :
int index = message.indexOf('}', i);
// if we don't have a matching closing brace then...
if (index == -1) {
buffer.append(c);
break;
}
i++;
if (i >= length) {
buffer.append(c);
break;
}
// look for a substitution
int number = -1;
try {
number = Integer.parseInt(message.substring(i, index));
} catch (NumberFormatException e) {
throw (IllegalArgumentException) new IllegalArgumentException().initCause(e);
}
if (number == 0 && argZero != null)
buffer.append(argZero);
else if (number == 1 && argOne != null)
buffer.append(argOne);
else {
if (number >= args.length || number < 0) {
buffer.append("<missing argument>"); //$NON-NLS-1$
i = index;
break;
}
buffer.append(args[number]);
}
i = index;
break;
case '\'' :
// if a single quote is the last char on the line then skip it
int nextIndex = i + 1;
if (nextIndex >= length) {
buffer.append(c);
break;
}
char next = message.charAt(nextIndex);
// if the next char is another single quote then write out one
if (next == '\'') {
i++;
buffer.append(c);
break;
}
// otherwise we want to read until we get to the next single quote
index = message.indexOf('\'', nextIndex);
// if there are no more in the string, then skip it
if (index == -1) {
buffer.append(c);
break;
}
// otherwise write out the chars inside the quotes
buffer.append(message.substring(nextIndex, index));
i = index;
break;
default :
buffer.append(c);
}
}
return buffer.toString();
} |
python | def launch_minecraft(port, installdir="MalmoPlatform", replaceable=False):
"""Launch Minecraft listening for malmoenv connections.
Args:
port: the TCP port to listen on.
installdir: the install dir name. Defaults to MalmoPlatform.
Must be same as given (or defaulted) in download call if used.
replaceable: whether or not to automatically restart Minecraft (default is false).
"""
launch_script = './launchClient.sh'
if os.name == 'nt':
launch_script = 'launchClient.bat'
cwd = os.getcwd()
os.chdir(installdir)
os.chdir("Minecraft")
try:
cmd = [launch_script, '-port', str(port), '-env']
if replaceable:
cmd.append('-replaceable')
subprocess.check_call(cmd)
finally:
os.chdir(cwd) |
java | @Override
public final void error(String error) throws IOException {
add(false);
setError(newCurrentPosition, error, newCurrentExisting);
} |
java | public void marshall(ProtectedResource protectedResource, ProtocolMarshaller protocolMarshaller) {
if (protectedResource == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(protectedResource.getResourceArn(), RESOURCEARN_BINDING);
protocolMarshaller.marshall(protectedResource.getResourceType(), RESOURCETYPE_BINDING);
protocolMarshaller.marshall(protectedResource.getLastBackupTime(), LASTBACKUPTIME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def close(self):
"""Close connection to this room"""
if hasattr(self, "conn"):
self.conn.close()
del self.conn
if hasattr(self, "user"):
del self.user |
java | public void init(ServletConfig servletConfig) throws ServletException {
// Save our ServletConfig instance
this.servletConfig = servletConfig;
// Acquire our FacesContextFactory instance
try {
facesContextFactory = (FacesContextFactory)
FactoryFinder.getFactory
(FactoryFinder.FACES_CONTEXT_FACTORY);
} catch (FacesException e) {
ResourceBundle rb = LOGGER.getResourceBundle();
String msg = rb.getString("severe.webapp.facesservlet.init_failed");
Throwable rootCause = (e.getCause() != null) ? e.getCause() : e;
LOGGER.log(Level.SEVERE, msg, rootCause);
throw new UnavailableException(msg);
}
// Acquire our Lifecycle instance
try {
LifecycleFactory lifecycleFactory = (LifecycleFactory)
FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
String lifecycleId ;
// First look in the servlet init-param set
if (null == (lifecycleId = servletConfig.getInitParameter(LIFECYCLE_ID_ATTR))) {
// If not found, look in the context-param set
lifecycleId = servletConfig.getServletContext().getInitParameter
(LIFECYCLE_ID_ATTR);
}
if (lifecycleId == null) {
lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE;
}
lifecycle = lifecycleFactory.getLifecycle(lifecycleId);
initHttpMethodValidityVerification();
} catch (FacesException e) {
Throwable rootCause = e.getCause();
if (rootCause == null) {
throw e;
} else {
throw new ServletException(e.getMessage(), rootCause);
}
}
} |
python | def to_internal_value(self, value):
"""Basically, each tag dict must include a full dict with id,
name and slug--or else you need to pass in a dict with just a name,
which indicated that the Tag doesn't exist, and should be added."""
if "id" in value:
tag = Tag.objects.get(id=value["id"])
else:
if "name" not in value:
raise ValidationError("Tags must include an ID or a name.")
if len(slugify(value["name"])) > 50:
raise ValidationError("Maximum tag length is 50 characters.")
name = value["name"]
slug = value.get("slug", slugify(name))
try:
tag = Tag.objects.get(slug=slug)
except Tag.DoesNotExist:
tag, created = Tag.objects.get_or_create(name=name, slug=slug)
return tag |
python | def ca_id(self, ca_id):
"""
Sets the ca_id of this DeviceData.
The certificate issuer's ID.
:param ca_id: The ca_id of this DeviceData.
:type: str
"""
if ca_id is not None and len(ca_id) > 500:
raise ValueError("Invalid value for `ca_id`, length must be less than or equal to `500`")
self._ca_id = ca_id |
java | protected void paintCustomItem(final WTree tree, final WTree.ExpandMode mode, final TreeItemModel model, final TreeItemIdNode node,
final XmlStringBuilder xml, final Set<String> selectedRows, final Set<String> expandedRows) {
String itemId = node.getItemId();
List<Integer> rowIndex = tree.getRowIndexForCustomItemId(itemId);
boolean selected = selectedRows.remove(itemId);
boolean expandable = node.hasChildren();
boolean expanded = expandedRows.remove(itemId);
TreeItemImage image = model.getItemImage(rowIndex);
String url = null;
if (image != null) {
url = tree.getItemImageUrl(image, itemId);
}
xml.appendTagOpen("ui:treeitem");
xml.appendAttribute("id", tree.getItemIdPrefix() + itemId);
xml.appendAttribute("label", model.getItemLabel(rowIndex));
xml.appendOptionalUrlAttribute("imageUrl", url);
xml.appendOptionalAttribute("selected", selected, "true");
xml.appendOptionalAttribute("expandable", expandable, "true");
xml.appendOptionalAttribute("open", expandable && expanded, "true");
xml.appendClose();
// Paint child items
if (expandable && (mode == WTree.ExpandMode.CLIENT || expanded)) {
for (TreeItemIdNode childNode : node.getChildren()) {
paintCustomItem(tree, mode, model, childNode, xml, selectedRows, expandedRows);
}
}
xml.appendEndTag("ui:treeitem");
} |
java | public void billingAccount_ovhPabx_serviceName_menu_menuId_PUT(String billingAccount, String serviceName, Long menuId, OvhOvhPabxMenu body) throws IOException {
String qPath = "/telephony/{billingAccount}/ovhPabx/{serviceName}/menu/{menuId}";
StringBuilder sb = path(qPath, billingAccount, serviceName, menuId);
exec(qPath, "PUT", sb.toString(), body);
} |
java | public MoneyAmountStyle withZeroCharacter(Character zeroCharacter) {
int zeroVal = (zeroCharacter == null ? -1 : zeroCharacter);
if (zeroVal == this.zeroCharacter) {
return this;
}
return new MoneyAmountStyle(
zeroVal,
positiveCharacter, negativeCharacter,
decimalPointCharacter, groupingStyle,
groupingCharacter, groupingSize, extendedGroupingSize, forceDecimalPoint, absValue);
} |
java | public static HtmlTree META(String httpEquiv, String content, String charSet) {
HtmlTree htmltree = new HtmlTree(HtmlTag.META);
String contentCharset = content + "; charset=" + charSet;
htmltree.addAttr(HtmlAttr.HTTP_EQUIV, nullCheck(httpEquiv));
htmltree.addAttr(HtmlAttr.CONTENT, contentCharset);
return htmltree;
} |
java | public static void checkArgument(boolean condition,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!condition) {
throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
} |
java | private FormValidation checkSpecificSignature(JSONObject json, JSONObject signatureJson, MessageDigest digest, String digestEntry, Signature signature, String signatureEntry, String digestName) throws IOException {
// this is for computing a digest to check sanity
DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), digest);
SignatureOutputStream sos = new SignatureOutputStream(signature);
String providedDigest = signatureJson.optString(digestEntry, null);
if (providedDigest == null) {
return FormValidation.warning("No '" + digestEntry + "' found");
}
String providedSignature = signatureJson.optString(signatureEntry, null);
if (providedSignature == null) {
return FormValidation.warning("No '" + signatureEntry + "' found");
}
// until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
// that only covers the earlier portion of the file. This was caused by the lack of close() call
// in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
// the digest output stream. This affects Jenkins [1.424,1,431].
// Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
// compute the correct digest, but it breaks all the existing UC json metadata out there. We then
// quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
// it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
//
// In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
// pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
// correctly.
//
// Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
// the attacker to inject a fragment at the end of the json.
json.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos,sos), Charsets.UTF_8)).close();
// did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
// (which is more likely than someone tampering with update center), we can tell
if (!digestMatches(digest.digest(), providedDigest)) {
String msg = digestName + " digest mismatch: expected=" + providedDigest + " in '" + name + "'";
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.severe(msg);
LOGGER.severe(json.toString(2));
}
return FormValidation.error(msg);
}
if (!verifySignature(signature, providedSignature)) {
return FormValidation.error(digestName + " based signature in the update center doesn't match with the certificate in '"+name + "'");
}
return FormValidation.ok();
} |
java | @Override
public DeleteLabelsResult deleteLabels(DeleteLabelsRequest request) {
request = beforeClientExecution(request);
return executeDeleteLabels(request);
} |
python | def is_vowel(char):
"""
Check whether the character is a vowel letter.
"""
if is_letter(char, strict=True):
return char in chart.vowels
return False |
java | private static String getDeploymentClassNameFromXml(ArquillianDescriptor descriptor) {
ExtensionDef extension = descriptor.extension("suite");
if (extension != null) {
return extension.getExtensionProperties().get("deploymentClass");
}
return null;
} |
python | def release_lock(self, verbose=VERBOSE, raiseError=RAISE_ERROR):
"""
Release the lock when set and close file descriptor if opened.
:Parameters:
#. verbose (bool): Whether to be verbose about errors when encountered
#. raiseError (bool): Whether to raise error exception when encountered
:Returns:
#. result (boolean): Whether the lock is succesfully released.
#. code (integer, Exception): Integer code indicating the reason how the
lock was successfully or unsuccessfully released. When releasing the
lock generates an error, this will be caught and returned in a message
Exception code.
* 0: Lock is not found, therefore successfully released
* 1: Lock is found empty, therefore successfully released
* 2: Lock is found owned by this locker and successfully released
* 3: Lock is found owned by this locker and successfully released and locked file descriptor was successfully closed
* 4: Lock is found owned by another locker, this locker has no permission to release it. Therefore unsuccessfully released
* Exception: Lock was not successfully released because of an unexpected error.
The error is caught and returned in this Exception. In this case
result is False.
"""
if not os.path.isfile(self.__lockPath):
released = True
code = 0
else:
try:
with open(self.__lockPath, 'rb') as fd:
lock = fd.readlines()
except Exception as err:
code = Exception( "Unable to read release lock file '%s' (%s)"%(self.__lockPath,str(err)) )
released = False
if verbose: print(str(code))
if raiseError: raise code
else:
if not len(lock):
code = 1
released = True
elif lock[0].rstrip() == self.__lockPass.encode():
try:
with open(self.__lockPath, 'wb') as f:
#f.write( ''.encode('utf-8') )
f.write( ''.encode() )
f.flush()
os.fsync(f.fileno())
except Exception as err:
released = False
code = Exception( "Unable to write release lock file '%s' (%s)"%(self.__lockPath,str(err)) )
if verbose: print(str(code))
if raiseError: raise code
else:
released = True
code = 2
else:
code = 4
released = False
# close file descriptor if lock is released and descriptor is not None
if released and self.__fd is not None:
try:
if not self.__fd.closed:
self.__fd.flush()
os.fsync(self.__fd.fileno())
self.__fd.close()
except Exception as err:
code = Exception( "Unable to close file descriptor of locked file '%s' (%s)"%(self.__filePath,str(err)) )
if verbose: print(str(code))
if raiseError: raise code
else:
code = 3
# return
return released, code |
java | @Override
public void setValue(final int index, final E value)
{
setParsed(true);
getValues().set(index, value);
} |
java | public ComponentMetadata getComponentMetadata(Class<?> componentClass) {
ComponentMetadata md = componentMetadataMap.get(componentClass.getName());
if (md == null) {
if (componentClass.getSuperclass() != null) {
return getComponentMetadata(componentClass.getSuperclass());
} else {
return null;
}
}
initMetadata(componentClass, md);
return md;
} |
java | public static String asHexWithAlpha( Color color ) {
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
int a = color.getAlpha();
String hex = String.format("#%02x%02x%02x%02x", r, g, b, a);
return hex;
} |
python | def http(self):
"""A thread local instance of httplib2.Http.
Returns:
httplib2.Http: An Http instance authorized by the credentials.
"""
if self._use_cached_http and hasattr(self._local, 'http'):
return self._local.http
if self._http_replay is not None:
# httplib2 instance is not thread safe
http = self._http_replay
else:
http = _build_http()
authorized_http = google_auth_httplib2.AuthorizedHttp(
self._credentials, http=http)
if self._use_cached_http:
self._local.http = authorized_http
return authorized_http |
python | def config(client, event, channel, nick, rest):
"Change the running config, something like a=b or a+=b or a-=b"
pattern = re.compile(r'(?P<key>\w+)\s*(?P<op>[+-]?=)\s*(?P<value>.*)$')
match = pattern.match(rest)
if not match:
return "Command not recognized"
res = match.groupdict()
key = res['key']
op = res['op']
value = yaml.safe_load(res['value'])
if op in ('+=', '-='):
# list operation
op_name = {'+=': 'append', '-=': 'remove'}[op]
op_name
if key not in pmxbot.config:
msg = "{key} not found in config. Can't {op_name}."
return msg.format(**locals())
if not isinstance(pmxbot.config[key], (list, tuple)):
msg = "{key} is not list or tuple. Can't {op_name}."
return msg.format(**locals())
op = getattr(pmxbot.config[key], op_name)
op(value)
else: # op is '='
pmxbot.config[key] = value |
java | public void setCVAL3(Integer newCVAL3) {
Integer oldCVAL3 = cval3;
cval3 = newCVAL3;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.TILE_SET_COLOR__CVAL3, oldCVAL3, cval3));
} |
java | public static int cufftExecZ2D(cufftHandle plan, double cIdata[], double rOdata[])
{
int cudaResult = 0;
boolean inPlace = (cIdata == rOdata);
// Allocate space for the input data on the device
Pointer hostCIdata = Pointer.to(cIdata);
Pointer deviceCIdata = new Pointer();
cudaResult = JCuda.cudaMalloc(deviceCIdata, cIdata.length * Sizeof.DOUBLE);
if (cudaResult != cudaError.cudaSuccess)
{
if (exceptionsEnabled)
{
throw new CudaException("JCuda error: "+cudaError.stringFor(cudaResult));
}
return cufftResult.JCUFFT_INTERNAL_ERROR;
}
// Allocate the output device data
Pointer hostROdata = null;
Pointer deviceROdata = null;
if (inPlace)
{
hostROdata = hostCIdata;
deviceROdata = deviceCIdata;
}
else
{
hostROdata = Pointer.to(rOdata);
deviceROdata = new Pointer();
cudaResult = JCuda.cudaMalloc(deviceROdata, rOdata.length * Sizeof.DOUBLE);
if (cudaResult != cudaError.cudaSuccess)
{
JCuda.cudaFree(deviceCIdata);
if (exceptionsEnabled)
{
throw new CudaException("JCuda error: "+cudaError.stringFor(cudaResult));
}
return cufftResult.JCUFFT_INTERNAL_ERROR;
}
}
// Copy the host input data to the device
cudaResult = JCuda.cudaMemcpy(deviceCIdata, hostCIdata, cIdata.length * Sizeof.DOUBLE, cudaMemcpyKind.cudaMemcpyHostToDevice);
if (cudaResult != cudaError.cudaSuccess)
{
JCuda.cudaFree(deviceCIdata);
if (!inPlace)
{
JCuda.cudaFree(deviceROdata);
}
if (exceptionsEnabled)
{
throw new CudaException("JCuda error: "+cudaError.stringFor(cudaResult));
}
return cufftResult.JCUFFT_INTERNAL_ERROR;
}
// Execute the transform
int result = cufftResult.CUFFT_SUCCESS;
try
{
result = JCufft.cufftExecZ2D(plan, deviceCIdata, deviceROdata);
}
catch (CudaException e)
{
JCuda.cudaFree(deviceCIdata);
if (!inPlace)
{
JCuda.cudaFree(deviceROdata);
}
result = cufftResult.JCUFFT_INTERNAL_ERROR;
}
if (result != cufftResult.CUFFT_SUCCESS)
{
if (exceptionsEnabled)
{
throw new CudaException(cufftResult.stringFor(cudaResult));
}
return result;
}
// Copy the device output data to the host
cudaResult = JCuda.cudaMemcpy(hostROdata, deviceROdata, rOdata.length * Sizeof.DOUBLE, cudaMemcpyKind.cudaMemcpyDeviceToHost);
if (cudaResult != cudaError.cudaSuccess)
{
JCuda.cudaFree(deviceCIdata);
if (!inPlace)
{
JCuda.cudaFree(deviceROdata);
}
if (exceptionsEnabled)
{
throw new CudaException("JCuda error: "+cudaError.stringFor(cudaResult));
}
return cufftResult.JCUFFT_INTERNAL_ERROR;
}
// Free the device data
cudaResult = JCuda.cudaFree(deviceCIdata);
if (cudaResult != cudaError.cudaSuccess)
{
if (exceptionsEnabled)
{
throw new CudaException("JCuda error: "+cudaError.stringFor(cudaResult));
}
return cufftResult.JCUFFT_INTERNAL_ERROR;
}
if (!inPlace)
{
cudaResult = JCuda.cudaFree(deviceROdata);
if (cudaResult != cudaError.cudaSuccess)
{
if (exceptionsEnabled)
{
throw new CudaException("JCuda error: "+cudaError.stringFor(cudaResult));
}
return cufftResult.JCUFFT_INTERNAL_ERROR;
}
}
return result;
} |
python | def bban(value, country=None, validate=False):
'''
Printable Basic Bank Account Number (BBAN) for the given country code. The
``country`` must be a valid ISO 3166-2 country code.
:param value: string or int
:param country: string
>>> bban('068-9999995-01', 'BE')
'068999999501'
>>> bban('555', 'NL')
'555'
>>> bban('555', 'NL', validate=True)
Traceback (most recent call last):
...
ValueError: Invalid BBAN, number does not match specification
>>> bban('123', 'XY', validate=True)
Traceback (most recent call last):
...
ValueError: Invalid BBAN, country unknown
'''
value = bban_compact(value)
if validate:
country = country.upper()
try:
rules = BBAN_RULES[country]
except KeyError:
raise ValueError(_('Invalid BBAN, country unknown'))
regex = _bban_regex(rules['bban'])
if not regex.match(value):
raise ValueError(
_('Invalid BBAN, number does not match specification')
)
return value |
java | protected void recursivelyCompareJSONArray(String key, JSONArray expected, JSONArray actual,
JSONCompareResult result) throws JSONException {
Set<Integer> matched = new HashSet<Integer>();
for (int i = 0; i < expected.length(); ++i) {
Object expectedElement = expected.get(i);
boolean matchFound = false;
for (int j = 0; j < actual.length(); ++j) {
Object actualElement = actual.get(j);
if (matched.contains(j) || !actualElement.getClass().equals(expectedElement.getClass())) {
continue;
}
if (expectedElement instanceof JSONObject) {
if (compareJSON((JSONObject) expectedElement, (JSONObject) actualElement).passed()) {
matched.add(j);
matchFound = true;
break;
}
} else if (expectedElement instanceof JSONArray) {
if (compareJSON((JSONArray) expectedElement, (JSONArray) actualElement).passed()) {
matched.add(j);
matchFound = true;
break;
}
} else if (expectedElement.equals(actualElement)) {
matched.add(j);
matchFound = true;
break;
}
}
if (!matchFound) {
result.fail(key + "[" + i + "] Could not find match for element " + expectedElement);
return;
}
}
} |
java | public SourceAlgorithmSpecification withSourceAlgorithms(SourceAlgorithm... sourceAlgorithms) {
if (this.sourceAlgorithms == null) {
setSourceAlgorithms(new java.util.ArrayList<SourceAlgorithm>(sourceAlgorithms.length));
}
for (SourceAlgorithm ele : sourceAlgorithms) {
this.sourceAlgorithms.add(ele);
}
return this;
} |
java | public NetworkWatcherInner createOrUpdate(String resourceGroupName, String networkWatcherName, NetworkWatcherInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().single().body();
} |
python | def _piped_input_cl(data, region, tmp_dir, out_base_file, prep_params):
"""Retrieve the commandline for streaming input into preparation step.
"""
return data["work_bam"], _gatk_extract_reads_cl(data, region, prep_params, tmp_dir) |
java | public static void bindToProperty (
String property, PrefsConfig config, AbstractButton button, boolean defval)
{
// create a config binding which will take care of everything
new ButtonConfigBinding(property, config, button, defval);
} |
java | public PactDslJsonArray stringMatcher(String regex, String value) {
if (!value.matches(regex)) {
throw new InvalidMatcherException(EXAMPLE + value + "\" does not match regular expression \"" +
regex + "\"");
}
body.put(value);
matchers.addRule(rootPath + appendArrayIndex(0), regexp(regex));
return this;
} |
python | def setExpanded(self, index, expanded):
""" Expands the model item specified by the index.
Overridden from QTreeView to make it persistent (between inspector changes).
"""
if index.isValid():
item = self.getItem(index)
item.expanded = expanded |
python | def chats_search(self, q=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/chats#search-chats"
api_path = "/api/v2/chats/search"
api_query = {}
if "query" in kwargs.keys():
api_query.update(kwargs["query"])
del kwargs["query"]
if q:
api_query.update({
"q": q,
})
return self.call(api_path, query=api_query, **kwargs) |
python | def delete(self, conn, key):
"""Deletes a key/value pair from the server.
:param key: is the key to delete.
:return: True if case values was deleted or False to indicate
that the item with this key was not found.
"""
assert self._validate_key(key)
command = b'delete ' + key + b'\r\n'
response = yield from self._execute_simple_command(conn, command)
if response not in (const.DELETED, const.NOT_FOUND):
raise ClientException('Memcached delete failed', response)
return response == const.DELETED |
python | def next_power_of_2(n):
""" Return next power of 2 greater than or equal to n """
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n + 1) & n: # n+1 is not a power of 2 yet
n |= n >> shift
shift *= 2
return max(4, n + 1) |
python | def track_exists(self, localdir):
""" Check if track exists in local directory. """
path = glob.glob(self.gen_localdir(localdir) +
self.gen_filename() + "*")
if len(path) > 0 and os.path.getsize(path[0]) > 0:
return True
return False |
python | def force_slash(fn):
"""
Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work
"""
@wraps(fn)
def wrapped(*args, **kwargs):
if request.environ['PATH_INFO'].endswith('/'):
return fn(*args, **kwargs)
else:
redirect(request.environ['SCRIPT_NAME'] + request.environ['PATH_INFO'] + '/')
return wrapped |
python | def imdct(y, L):
"""Inverse Modified Discrete Cosine Transform (MDCT)
Returns the Inverse Modified Discrete Cosine Transform
with fixed window size L of the vector of coefficients y.
The window is based on a sine window.
Parameters
----------
y : ndarray, shape (L/2, 2 * N / L)
The MDCT coefficients
L : int
The window length
Returns
-------
x : ndarray, shape (N,)
The reconstructed signal
See also
--------
mdct
"""
# Signal length
N = y.size
# Number of frequency channels
K = L // 2
# Test length
if N % K != 0:
raise ValueError('Input length must be a multiple of the half of '
'the window size')
# Number of frames
P = N // K
if P < 2:
raise ValueError('Signal too short')
# Reshape
temp = y
y = np.zeros((L, P), dtype=np.float)
y[:K, :] = temp
del temp
# Pre-twiddle
aL = np.arange(L, dtype=np.float)
y = y * np.exp((1j * np.pi * (L / 2. + 1.) / L) * aL)[:, None]
# IFFT
x = ifft(y, axis=0)
# Post-twiddle
x *= np.exp((1j * np.pi / L) * (aL + (L / 2. + 1.) / 2.))[:, None]
# Windowing
w_long = np.sin((np.pi / L) * (aL + 0.5))
w_edge_L = w_long.copy()
w_edge_L[:L // 4] = 0.
w_edge_L[L // 4:L // 2] = 1.
w_edge_R = w_long.copy()
w_edge_R[L // 2:L // 2 + L // 4] = 1.
w_edge_R[L // 2 + L // 4:L] = 0.
x[:, 0] *= w_edge_L
x[:, 1:-1] *= w_long[:, None]
x[:, -1] *= w_edge_R
# Real part and scaling
x = math.sqrt(2. / K) * L * np.real(x)
# Overlap and add
def overlap_add(y, x):
z = np.concatenate((y, np.zeros((K,))))
z[-2 * K:] += x
return z
x = six.moves.reduce(overlap_add, [x[:, i] for i in range(x.shape[1])])
# Cut edges
x = x[K // 2:-K // 2].copy()
return x |
java | private long addFilesInDir(Path path, List<FileStatus> files, boolean logExcludedFiles)
throws IOException {
final FileSystem fs = path.getFileSystem();
long length = 0;
for(FileStatus dir: fs.listStatus(path)) {
if (dir.isDir()) {
if (acceptFile(dir) && enumerateNestedFiles) {
length += addFilesInDir(dir.getPath(), files, logExcludedFiles);
} else {
if (logExcludedFiles && LOG.isDebugEnabled()) {
LOG.debug("Directory "+dir.getPath().toString()+" did not pass the file-filter and is excluded.");
}
}
}
else {
if(acceptFile(dir)) {
files.add(dir);
length += dir.getLen();
testForUnsplittable(dir);
} else {
if (logExcludedFiles && LOG.isDebugEnabled()) {
LOG.debug("Directory "+dir.getPath().toString()+" did not pass the file-filter and is excluded.");
}
}
}
}
return length;
} |
java | public synchronized void recordCommit(int commitLength) {
Preconditions.checkArgument(commitLength >= 0, "commitLength must be a non-negative number.");
// Update counters.
this.commitCount++;
this.accumulatedLength += commitLength;
int minCount = this.config.getCheckpointMinCommitCount();
int countThreshold = this.config.getCheckpointCommitCountThreshold();
long lengthThreshold = this.config.getCheckpointTotalCommitLengthThreshold();
if (this.commitCount >= minCount && (this.commitCount >= countThreshold || this.accumulatedLength >= lengthThreshold)) {
// Reset counters.
this.commitCount = 0;
this.accumulatedLength = 0;
// Invoke callback.
this.executor.execute(this.createCheckpointCallback);
}
} |
java | @Override
public void updateComponent(final Object data) {
MyDataBean myBean = (MyDataBean) data;
StringBuffer out = new StringBuffer();
out.append("Name: ").append(myBean.getName()).append("\n\n");
for (SomeDataBean bean : myBean.getMyBeans()) {
out.append("Field1: ").append(bean.getField1());
out.append("\nField2: ").append(bean.getField2()).append("\n\n");
}
beanDetails.setText(out.toString());
} |
java | public ImageBuilder withImageBuilderErrors(ResourceError... imageBuilderErrors) {
if (this.imageBuilderErrors == null) {
setImageBuilderErrors(new java.util.ArrayList<ResourceError>(imageBuilderErrors.length));
}
for (ResourceError ele : imageBuilderErrors) {
this.imageBuilderErrors.add(ele);
}
return this;
} |
python | def touch_tip(self,
location: Well = None,
radius: float = 1.0,
v_offset: float = -1.0,
speed: float = 60.0) -> 'InstrumentContext':
"""
Touch the pipette tip to the sides of a well, with the intent of
removing left-over droplets
:param location: If no location is passed, pipette will
touch tip at current well's edges
:type location: :py:class:`.Well` or None
:param radius: Describes the proportion of the target well's
radius. When `radius=1.0`, the pipette tip will move to
the edge of the target well; when `radius=0.5`, it will
move to 50% of the well's radius. Default: 1.0 (100%)
:type radius: float
:param v_offset: The offset in mm from the top of the well to touch tip
A positive offset moves the tip higher above the well,
while a negative offset moves it lower into the well
Default: -1.0 mm
:type v_offset: float
:param speed: The speed for touch tip motion, in mm/s.
Default: 60.0 mm/s, Max: 80.0 mm/s, Min: 20.0 mm/s
:type speed: float
:raises NoTipAttachedError: if no tip is attached to the pipette
:raises RuntimeError: If no location is specified and location cache is
None. This should happen if `touch_tip` is called
without first calling a method that takes a
location (eg, :py:meth:`.aspirate`,
:py:meth:`dispense`)
:returns: This instance
.. note::
This is behavior change from legacy API (which accepts any
:py:class:`.Placeable` as the ``location`` parameter)
"""
if not self.hw_pipette['has_tip']:
raise hc.NoTipAttachedError('Pipette has no tip to touch_tip()')
if speed > 80.0:
self._log.warning('Touch tip speed above limit. Setting to 80mm/s')
speed = 80.0
elif speed < 20.0:
self._log.warning('Touch tip speed below min. Setting to 20mm/s')
speed = 20.0
# If location is a valid well, move to the well first
if location is None:
if not self._ctx.location_cache:
raise RuntimeError('No valid current location cache present')
else:
location = self._ctx.location_cache.labware # type: ignore
# type checked below
if isinstance(location, Well):
if location.parent.is_tiprack:
self._log.warning('Touch_tip being performed on a tiprack. '
'Please re-check your code')
self.move_to(location.top())
else:
raise TypeError(
'location should be a Well, but it is {}'.format(location))
# Determine the touch_tip edges/points
offset_pt = types.Point(0, 0, v_offset)
well_edges = [
# right edge
location._from_center_cartesian(x=radius, y=0, z=1) + offset_pt,
# left edge
location._from_center_cartesian(x=-radius, y=0, z=1) + offset_pt,
# back edge
location._from_center_cartesian(x=0, y=radius, z=1) + offset_pt,
# front edge
location._from_center_cartesian(x=0, y=-radius, z=1) + offset_pt
]
for edge in well_edges:
self._hw_manager.hardware.move_to(self._mount, edge, speed)
return self |
python | def debug_query_result(rows: Sequence[Any]) -> None:
"""Writes a query result to the log."""
log.info("Retrieved {} rows", len(rows))
for i in range(len(rows)):
log.info("Row {}: {}", i, rows[i]) |
python | def get_time_variables(ds):
'''
Returns a list of variables describing the time coordinate
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
time_variables = set()
for variable in ds.get_variables_by_attributes(standard_name='time'):
time_variables.add(variable.name)
for variable in ds.get_variables_by_attributes(axis='T'):
if variable.name not in time_variables:
time_variables.add(variable.name)
regx = r'^(?:day|d|hour|hr|h|minute|min|second|s)s? since .*$'
for variable in ds.get_variables_by_attributes(units=lambda x: isinstance(x, basestring)):
if re.match(regx, variable.units) and variable.name not in time_variables:
time_variables.add(variable.name)
return time_variables |
python | def added(self) -> int:
"""
Return the total number of added lines in the file.
:return: int lines_added
"""
added = 0
for line in self.diff.replace('\r', '').split("\n"):
if line.startswith('+') and not line.startswith('+++'):
added += 1
return added |
java | public void removeProject(Project project, boolean cascade) throws GreenPepperServerException {
try {
sessionService.startSession();
sessionService.beginTransaction();
if (cascade) {
List<Repository> repositories = repositoryDao.getAll(project.getName());
for (Repository repo : repositories) {
repositoryDao.remove(repo.getUid());
}
List<SystemUnderTest> systemUnderTests = sutDao.getAllForProject(project.getName());
for (SystemUnderTest sut : systemUnderTests) {
sutDao.remove(sut.getProject().getName(), sut.getName());
}
}
projectDao.remove(project.getName());
log.debug("Removed Project: " + project.getName());
sessionService.commitTransaction();
} catch (Exception ex) {
sessionService.rollbackTransaction();
throw handleException(PROJECT_REMOVE_FAILED, ex);
} finally {
sessionService.closeSession();
}
} |
java | private void setCredential(Subject subject, WSPrincipal principal) throws CredentialException {
String securityName = principal.getName();
Hashtable<String, ?> customProperties = getUniqueIdHashtableFromSubject(subject);
if (customProperties == null || customProperties.isEmpty()) {
UserRegistryService urService = userRegistryServiceRef.getService();
if (urService != null) {
String urType = urService.getUserRegistryType();
if ("WIM".equalsIgnoreCase(urType) || "LDAP".equalsIgnoreCase(urType)) {
try {
securityName = urService.getUserRegistry().getUserDisplayName(securityName);
} catch (Exception e) {
//do nothing
}
}
}
}
if (securityName == null || securityName.length() == 0) {
securityName = principal.getName();
}
String accessId = principal.getAccessId();
String customRealm = null;
String realm = null;
String uniqueName = null;
if (customProperties != null) {
customRealm = (String) customProperties.get(AttributeNameConstants.WSCREDENTIAL_REALM);
}
if (customRealm != null) {
realm = customRealm;
String[] parts = accessId.split(realm + "/");
if (parts != null && parts.length == 2)
uniqueName = parts[1];
} else {
realm = AccessIdUtil.getRealm(accessId);
uniqueName = AccessIdUtil.getUniqueId(accessId);
}
if (AccessIdUtil.isServerAccessId(accessId)) {
// Create a server WSCredential
setCredential(null, subject, realm, securityName, uniqueName, null, accessId, null, null);
} else {
CredentialsService cs = credentialsServiceRef.getService();
String unauthenticatedUserid = cs.getUnauthenticatedUserid();
if (securityName != null && unauthenticatedUserid != null &&
securityName.equals(unauthenticatedUserid)) {
// Create an unauthenticated WSCredential
setCredential(unauthenticatedUserid, subject, realm, securityName, uniqueName, null, null, null, null);
} else if (AccessIdUtil.isUserAccessId(accessId)) {
// Create a user WSCredential
createUserWSCredential(subject, securityName, accessId, realm, uniqueName, unauthenticatedUserid);
}
}
} |
python | def execute_deploy_clone_from_vm(self, si, logger, vcenter_data_model, reservation_id, deployment_params, cancellation_context, folder_manager):
"""
Calls the deployer to deploy vm from another vm
:param cancellation_context:
:param str reservation_id:
:param si:
:param logger:
:type deployment_params: DeployFromTemplateDetails
:param vcenter_data_model:
:return:
"""
self._prepare_deployed_apps_folder(deployment_params, si, logger, folder_manager, vcenter_data_model)
deploy_result = self.deployer.deploy_clone_from_vm(si, logger, deployment_params, vcenter_data_model,
reservation_id, cancellation_context)
return deploy_result |
python | def replace(self, space, t, *, timeout=-1.0) -> _MethodRet:
"""
Replace request coroutine. Same as insert, but replace.
:param space: space id or space name.
:param t: tuple to insert (list object)
:param timeout: Request timeout
:returns: :class:`asynctnt.Response` instance
"""
return self._db.replace(space, t, timeout=timeout) |
python | def mpoint_(self, col, x=None, y=None, rsum=None, rmean=None):
"""
Splits a column into multiple series based on the column's
unique values. Then visualize theses series in a chart.
Parameters: column to split, x axis column, y axis column
Optional: rsum="1D" to resample and sum data an rmean="1D"
to mean the data
"""
return self._multiseries(col, x, y, "point", rsum, rmean) |
python | def _automaticallyDeriveSpatialReferenceId(self, directory):
"""
This method is used to automatically lookup the spatial reference ID of the GSSHA project. This method is a
wrapper for the ProjectionFile class method lookupSpatialReferenceID(). It requires an internet connection
(the lookup uses a web service) and the projection file to be present and the appropriate card in the project
file pointing to the projection file (#PROJECTION_FILE). If the process fails, it defaults to SRID 4326 which is
the id for WGS 84.
"""
# Only do automatic look up if spatial reference is not specified by the user
DEFAULT_SPATIAL_REFERENCE_ID = 4236
# Lookup the projection card in the project file
projectionCard = self.getCard('#PROJECTION_FILE')
if projectionCard is not None:
# Use lookup service
srid = ProjectionFile.lookupSpatialReferenceID(directory=directory,
filename=projectionCard.value.strip('"'))
try:
# Verify the resulting srid is a number
int(srid)
self.srid = srid
spatialReferenceID = srid
log.info("Automatic spatial reference ID lookup succeded. Using id: {0}".format(spatialReferenceID))
except:
# Otherwise, use the default id
spatialReferenceID = DEFAULT_SPATIAL_REFERENCE_ID
log.warning("Automatic spatial reference ID lookup failed. Using default id: {0}".format(DEFAULT_SPATIAL_REFERENCE_ID))
else:
# If there is no projection card in the project file, use default
spatialReferenceID = DEFAULT_SPATIAL_REFERENCE_ID
log.warning("Automatic spatial reference ID lookup failed. Using default id: {0}".format(DEFAULT_SPATIAL_REFERENCE_ID))
return spatialReferenceID |
python | def update_window_size(self):
"""
Update the current window object with its current
height and width and clear the screen if they've changed.
"""
height, width = self.window.getmaxyx()
if self.height != height or self.width != width:
self.height, self.width = height, width
self.window.clear() |
java | @Override
public List<CPInstance> findByCPDefinitionId(long CPDefinitionId) {
return findByCPDefinitionId(CPDefinitionId, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null);
} |
python | def raise_for_missing_namespace(self, line: str, position: int, namespace: str, name: str) -> None:
"""Raise an exception if the namespace is not defined."""
if not self.has_namespace(namespace):
raise UndefinedNamespaceWarning(self.get_line_number(), line, position, namespace, name) |
python | def generate():
################################################################################
### Build new network
net = Network(id='Example7_Brunel2000')
net.notes = 'Example 7: based on network of Brunel 2000'
net.parameters = { 'g': 4,
'eta': 1,
'order': 5,
'epsilon': 0.1,
'J': 0.1,
'delay': 1.5,
'tauMem': 20.0,
'tauSyn': 0.1,
'tauRef': 2.0,
'U0': 0.0,
'theta': 20.0}
cell = Cell(id='ifcell', pynn_cell='IF_curr_alpha')
cell.parameters = { 'tau_m': 'tauMem',
'tau_refrac': 'tauRef',
'v_rest': 'U0',
'v_reset': 'U0',
'v_thresh': 'theta',
'cm': 0.001,
"i_offset": 0}
#cell = Cell(id='hhcell', neuroml2_source_file='test_files/hhcell.cell.nml')
net.cells.append(cell)
expoisson = Cell(id='expoisson', pynn_cell='SpikeSourcePoisson')
expoisson.parameters = { 'rate': '1000 * (eta*theta/(J*4*order*epsilon*tauMem)) * (4*order*epsilon)',
'start': 0,
'duration': 1e9}
net.cells.append(expoisson)
'''
input_source = InputSource(id='iclamp0',
pynn_input='DCSource',
parameters={'amplitude':0.002, 'start':100., 'stop':900.})
input_source = InputSource(id='poissonFiringSyn',
neuroml2_input='poissonFiringSynapse',
parameters={'average_rate':"eta", 'synapse':"ampa", 'spike_target':"./ampa"})
net.input_sources.append(input_source)'''
pE = Population(id='Epop', size='4*order', component=cell.id, properties={'color':'1 0 0'})
pEpoisson = Population(id='Einput', size='4*order', component=expoisson.id, properties={'color':'.5 0 0'})
pI = Population(id='Ipop', size='1*order', component=cell.id, properties={'color':'0 0 1'})
net.populations.append(pE)
net.populations.append(pEpoisson)
net.populations.append(pI)
net.synapses.append(Synapse(id='ampa',
pynn_receptor_type='excitatory',
pynn_synapse_type='curr_alpha',
parameters={'tau_syn':0.1}))
net.synapses.append(Synapse(id='gaba',
pynn_receptor_type='inhibitory',
pynn_synapse_type='curr_alpha',
parameters={'tau_syn':0.1}))
net.projections.append(Projection(id='projEinput',
presynaptic=pEpoisson.id,
postsynaptic=pE.id,
synapse='ampa',
delay=2,
weight=0.02,
one_to_one_connector=OneToOneConnector()))
'''
net.projections.append(Projection(id='projEE',
presynaptic=pE.id,
postsynaptic=pE.id,
synapse='ampa',
delay=2,
weight=0.002,
random_connectivity=RandomConnectivity(probability=.5)))'''
net.projections.append(Projection(id='projEI',
presynaptic=pE.id,
postsynaptic=pI.id,
synapse='ampa',
delay=2,
weight=0.02,
random_connectivity=RandomConnectivity(probability=.5)))
'''
net.projections.append(Projection(id='projIE',
presynaptic=pI.id,
postsynaptic=pE.id,
synapse='gaba',
delay=2,
weight=0.02,
random_connectivity=RandomConnectivity(probability=.5)))
net.inputs.append(Input(id='stim',
input_source=input_source.id,
population=pE.id,
percentage=50))'''
#print(net)
#print(net.to_json())
new_file = net.to_json_file('%s.json'%net.id)
################################################################################
### Build Simulation object & save as JSON
sim = Simulation(id='SimExample7',
network=new_file,
duration='1000',
dt='0.025',
seed= 123,
recordTraces={pE.id:'*',pI.id:'*'},
recordSpikes={'all':'*'})
sim.to_json_file()
return sim, net |
python | def parse_sort_string(sort):
"""
Parse a sort string for use with elasticsearch
:param: sort: the sort string
"""
if sort is None:
return ['_score']
l = sort.rsplit(',')
sortlist = []
for se in l:
se = se.strip()
order = 'desc' if se[0:1] == '-' else 'asc'
field = se[1:] if se[0:1] in ['-', '+'] else se
field = field.strip()
sortlist.append({field: {"order": order, "unmapped_type": "string", "missing": "_last"}})
sortlist.append('_score')
return sortlist |
java | public boolean hasRequiredClientProps() {
boolean valid = true;
valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP);
valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);
valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);
valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);
return valid;
} |
python | def make_dict(cls, table):
"""Build a dictionary map int to `JobDetails` from an `astropy.table.Table`"""
ret_dict = {}
for row in table:
job_details = cls.create_from_row(row)
ret_dict[job_details.dbkey] = job_details
return ret_dict |
java | public String translate(Update u) {
final List<Expression> columns = u.getColumns();
final Expression table = u.getTable();
final Expression where = u.getWhere();
inject(table, where);
final List<String> temp = new ArrayList<>();
temp.add("UPDATE");
temp.add(table.translate());
if (table.isAliased()) {
temp.add(quotize(table.getAlias(), translateEscape()));
}
temp.add("SET");
List<String> setTranslations = new ArrayList<>();
for (Expression e : columns) {
inject(e);
setTranslations.add(e.translate());
}
temp.add(join(setTranslations, ", "));
if (where != null) {
temp.add("WHERE");
temp.add(where.translate());
}
return join(temp, " ");
} |
java | public static Map<String, String> pairsToMap(List<CmsPair<String, String>> pairs) {
LinkedHashMap<String, String> result = new LinkedHashMap<String, String>();
for (CmsPair<String, String> pair : pairs) {
result.put(pair.getFirst(), pair.getSecond());
}
return result;
} |
python | def delete_namespaced_lease(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_lease # noqa: E501
delete a Lease # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_lease(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Lease (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_namespaced_lease_with_http_info(name, namespace, **kwargs) # noqa: E501
else:
(data) = self.delete_namespaced_lease_with_http_info(name, namespace, **kwargs) # noqa: E501
return data |
java | public void marshall(DescribeBuildRequest describeBuildRequest, ProtocolMarshaller protocolMarshaller) {
if (describeBuildRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeBuildRequest.getBuildId(), BUILDID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def persist(self, storageLevel):
"""
Persists the underlying RDD with the specified storage level.
"""
if not isinstance(storageLevel, StorageLevel):
raise TypeError("`storageLevel` should be a StorageLevel, got %s" % type(storageLevel))
javaStorageLevel = self._java_matrix_wrapper._sc._getJavaStorageLevel(storageLevel)
self._java_matrix_wrapper.call("persist", javaStorageLevel)
return self |
java | private void traverseResources(Resource resource, int counter) throws XMLStreamException, RepositoryException,
IllegalResourceTypeException, URISyntaxException, UnsupportedEncodingException
{
xmlStreamWriter.writeStartElement("DAV:", "response");
xmlStreamWriter.writeStartElement("DAV:", "href");
String href = resource.getIdentifier().toASCIIString();
if (resource.isCollection())
{
xmlStreamWriter.writeCharacters(href + "/");
}
else
{
xmlStreamWriter.writeCharacters(href);
}
xmlStreamWriter.writeEndElement();
PropstatGroupedRepresentation propstat =
new PropstatGroupedRepresentation(resource, propertyNames, propertyNamesOnly, session);
PropertyWriteUtil.writePropStats(xmlStreamWriter, propstat.getPropStats());
xmlStreamWriter.writeEndElement();
int d = depth;
if (resource.isCollection())
{
if (counter < d)
{
CollectionResource collection = (CollectionResource)resource;
for (Resource child : collection.getResources())
{
traverseResources(child, counter + 1);
}
}
}
} |
python | def installed(name, # pylint: disable=C0103
ruby=None,
gem_bin=None,
user=None,
version=None,
rdoc=False,
ri=False,
pre_releases=False,
proxy=None,
source=None): # pylint: disable=C0103
'''
Make sure that a gem is installed.
name
The name of the gem to install
ruby: None
Only for RVM or rbenv installations: the ruby version and gemset to
target.
gem_bin: None
Custom ``gem`` command to run instead of the default.
Use this to install gems to a non-default ruby install. If you are
using rvm or rbenv use the ruby argument instead.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
version : None
Specify the version to install for the gem.
Doesn't play nice with multiple gems at once
rdoc : False
Generate RDoc documentation for the gem(s).
ri : False
Generate RI documentation for the gem(s).
pre_releases : False
Install pre-release version of gem(s) if available.
proxy : None
Use the specified HTTP proxy server for all outgoing traffic.
Format: http://hostname[:port]
source : None
Use the specified HTTP gem source server to download gem.
Format: http://hostname[:port]
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if ruby is not None and not(__salt__['rvm.is_installed'](runas=user) or __salt__['rbenv.is_installed'](runas=user)):
log.warning(
'Use of argument ruby found, but neither rvm or rbenv is installed'
)
gems = __salt__['gem.list'](name, ruby, gem_bin=gem_bin, runas=user)
if name in gems and version is not None:
versions = list([x.replace('default: ', '') for x in gems[name]])
match = re.match(r'(>=|>|<|<=)', version)
if match:
# Grab the comparison
cmpr = match.group()
# Clear out 'default:' and any whitespace
installed_version = re.sub('default: ', '', gems[name][0]).strip()
# Clear out comparison from version and whitespace
desired_version = re.sub(cmpr, '', version).strip()
if salt.utils.versions.compare(installed_version,
cmpr,
desired_version):
ret['result'] = True
ret['comment'] = 'Installed Gem meets version requirements.'
return ret
elif str(version) in versions:
ret['result'] = True
ret['comment'] = 'Gem is already installed.'
return ret
else:
if str(version) in gems[name]:
ret['result'] = True
ret['comment'] = 'Gem is already installed.'
return ret
elif name in gems and version is None:
ret['result'] = True
ret['comment'] = 'Gem is already installed.'
return ret
if __opts__['test']:
ret['comment'] = 'The gem {0} would have been installed'.format(name)
return ret
if __salt__['gem.install'](name,
ruby=ruby,
gem_bin=gem_bin,
runas=user,
version=version,
rdoc=rdoc,
ri=ri,
pre_releases=pre_releases,
proxy=proxy,
source=source):
ret['result'] = True
ret['changes'][name] = 'Installed'
ret['comment'] = 'Gem was successfully installed'
else:
ret['result'] = False
ret['comment'] = 'Could not install gem.'
return ret |
java | public void encodeBuffer(ByteBuffer aBuffer, OutputStream aStream)
throws IOException {
byte [] buf = getBytes(aBuffer);
encodeBuffer(buf, aStream);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.