code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
protected int findScanLength(long offset) throws FileParsingException {
int length = -1;
try {
RandomAccessFile raf = source.getRandomAccessFile();
raf.seek(offset);
InputStream is = Channels.newInputStream(raf.getChannel());
BufferedInputStream bis = new BufferedInputStream(is);
MZXMLMultiSpectraParser parser = source.getSpectraParser(
bis, LCMSDataSubset.STRUCTURE_ONLY, source.getReaderPool(), 1);
length = parser.findThisStreamFirstScanLen();
is.close();
} catch (IOException e) {
throw new FileParsingException(e);
} finally {
source.close();
}
return length;
} | Finds the length of a scan entry in the original file by reading it, starting at the provided
offset and looking for an "end of scan" tag.
<b>Note that the {@code} source must be closed prior to calling this method.</b>
@param offset offset in the file, where to start reading
@return -1 if no end of scan was found |
protected long findIndexOffset(RandomAccessFile raf)
throws IOException, IndexNotFoundException, IndexBrokenException {
long fileLen = raf.length();
int bytesToRead =
fileLen > MAX_BYTES_FROM_END_TO_SEARCH_FOR_INDEX ? MAX_BYTES_FROM_END_TO_SEARCH_FOR_INDEX
: (int) fileLen;
long offsetFromEOF = fileLen - bytesToRead;
raf.seek(offsetFromEOF);
byte[] bytes = new byte[bytesToRead];
raf.readFully(bytes, 0, bytes.length);
String fileEndingStr = new String(bytes);
Matcher matcherIdxOffest = RE_INDEX_OFFSET.matcher(fileEndingStr);
long indexOffset = -1;
if (matcherIdxOffest.find()) {
indexOffset = Long.parseLong(matcherIdxOffest.group(1));
}
if (indexOffset == -1) {
throw new IndexNotFoundException(String.format(
"%s <%s> section was not found within the last %d bytes in the file! (%s)",
FILE_TYPE_NAME, TAG_INDEXOFFSET, MAX_BYTES_FROM_END_TO_SEARCH_FOR_INDEX,
source.getPath()));
}
if (indexOffset < INDEX_OFFSET_MIN_VALUE) {
throw new IndexBrokenException(String.format(
"Index offset was less than %d, actual value: [%d] - not allowed", INDEX_OFFSET_MIN_VALUE,
indexOffset));
}
if (indexOffset > fileLen) {
throw new IndexBrokenException(String.format(
"Index offset was larger than the length of the file, actual value: [%d]", indexOffset));
}
// now check the first few values of the entries in the index
long lenFromIndexStartToEOF = fileLen - indexOffset;
int indexBeginLength =
lenFromIndexStartToEOF >= NUM_BYTES_TO_CHECK_INDEX ? NUM_BYTES_TO_CHECK_INDEX
: (int) lenFromIndexStartToEOF;
byte[] indexBeginBytes = new byte[indexBeginLength];
raf.seek(indexOffset);
raf.readFully(indexBeginBytes, 0, indexBeginBytes.length);
String indexBeginStr = new String(indexBeginBytes);
Matcher matcherIdxEntry = RE_INDEX_ENTRY_SIMPLE.matcher(indexBeginStr);
long offsetPrev = -2, offsetCur;
while (matcherIdxEntry.find()) {
offsetCur = Long.parseLong(matcherIdxEntry.group(1));
if (offsetCur < 0) {
throw new IndexBrokenException(String.format(
"The index contained an element less than zero: '%s'", matcherIdxEntry.group(0)));
}
if (offsetCur <= offsetPrev) {
throw new IndexBrokenException(String.format(
"The index contained an element less or equal to a previous one. The match was: '%s'",
matcherIdxEntry.group(0)));
}
if (offsetCur >= indexOffset) {
throw new IndexBrokenException(String.format(
"The index contained an element that was further in the file than the '%s'.",
TAG_INDEXOFFSET));
}
offsetPrev = offsetCur;
}
return indexOffset;
} | Reads the last few kB of the file, looking for {@link #TAG_INDEXOFFSET} tag. |
@TargetApi(Build.VERSION_CODES.N_MR1)
public static void setDynamicShortcutsLoader(DynamicShortcutsLoader dynamicShortcutsLoader) {
AppShortcutsHelper.dynamicShortcutsLoader = dynamicShortcutsLoader;
} | Dynamic Shortcuts |
public List<abstractTiffType> getDescriptiveValueObject() {
Tag tag = TiffTags.getTag(id);
if (tag != null) {
if (tag.hasReadableDescription()){
String desc = this.toString();
String tagDescription = tag.getTextDescription(toString());
if (tagDescription != null){
desc = tagDescription;
}
return Arrays.asList(new Text(desc));
} else {
return getValue();
}
}
return null;
} | Gets the descriptive value.
@return the descriptive value |
public long getFirstNumericValue() {
String val = (value != null) ? value.get(0).toString() : readValue.get(0).toString();
if (isInteger(val)) {
return Long.parseLong(val);
} else {
return 0;
}
} | Gets the first value of the list parsed as a number.
@return the first integer value |
public String readString() {
int size = value.size();
if (size > Constants.MaxStringSize)
size = Constants.MaxStringSize;
if (value == null || size == 0)
return "";
byte[] bbs = new byte[size - 1];
for (int i = 0; i < size - 1; i++) {
abstractTiffType att = value.get(i);
bbs[i] = att.toByte();
}
try {
return new String(bbs, "UTF8");
} catch (UnsupportedEncodingException e) {
return "";
}
} | Read string.
@return String string |
public String getName() {
String name = "" + id;
if (TiffTags.hasTag(id))
name = TiffTags.getTag(id).getName();
return name;
} | Gets the name of the tag.
@return the name |
public int getBytesBigEndian(int i, int j) {
int result = 0;
for (int k = i; k < i + j; k++) {
result += value.get(k).toUint();
if (k + 1 < i + j)
result <<= 8;
}
return result;
} | Gets the bytes.
@param i the i
@param j the j
@return the bytes |
private static Object newInstance(String className,
ClassLoader classLoader,
Properties properties)
{
try {
Class<?> spiClass;
if (classLoader == null) {
spiClass = Class.forName(className);
} else {
spiClass = classLoader.loadClass(className);
}
if (properties != null) {
Constructor constr = null;
try {
constr = spiClass.getConstructor(Properties.class);
} catch (Exception ex) {
}
if (constr != null) {
return constr.newInstance(properties);
}
}
return spiClass.newInstance();
} catch (ClassNotFoundException x) {
throw new ELException(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new ELException(
"Provider " + className + " could not be instantiated: " + x,
x);
}
} | Creates an instance of the specified class using the specified
<code>ClassLoader</code> object.
@exception ELException if the given class could not be found
or could not be instantiated |
static Object find(String factoryId, String fallbackClassName,
Properties properties)
{
ClassLoader classLoader;
try {
if (System.getSecurityManager() == null) {
classLoader = Thread.currentThread().getContextClassLoader();
} else {
classLoader = AccessController.doPrivileged(
(PrivilegedAction<ClassLoader>) () -> Thread.currentThread().getContextClassLoader());
}
} catch (Exception x) {
throw new ELException(x.toString(), x);
}
final String deploymentFactoryClassName = FactoryFinderCache.loadImplementationClassName(factoryId, classLoader);
if(deploymentFactoryClassName != null && !deploymentFactoryClassName.equals("")) {
return newInstance(deploymentFactoryClassName, classLoader, properties);
}
// try to read from $java.home/lib/el.properties
try {
String javah=System.getProperty( "java.home" );
String configFile = javah + File.separator +
"lib" + File.separator + "el.properties";
File f=new File( configFile );
if( f.exists()) {
Properties props=new Properties();
props.load( new FileInputStream(f));
String factoryClassName = props.getProperty(factoryId);
return newInstance(factoryClassName, classLoader, properties);
}
} catch(Exception ex ) {
}
// Use the system property
try {
String systemProp =
System.getProperty( factoryId );
if( systemProp!=null) {
return newInstance(systemProp, classLoader, properties);
}
} catch (SecurityException se) {
}
if (fallbackClassName == null) {
throw new ELException(
"Provider for " + factoryId + " cannot be found", null);
}
return newInstance(fallbackClassName, classLoader, properties);
} | Finds the implementation <code>Class</code> object for the given
factory name, or if that fails, finds the <code>Class</code> object
for the given fallback class name. The arguments supplied must be
used in order. If using the first argument is successful, the second
one will not be used.
<P>
This method is package private so that this code can be shared.
@return the <code>Class</code> object of the specified message factory;
may not be <code>null</code>
@param factoryId the name of the factory to find, which is
a system property
@param fallbackClassName the implementation class name, which is
to be used only if nothing else
is found; <code>null</code> to indicate that
there is no fallback class name
@exception ELException if there is an error |
@MainThread
public void startSetup() {
try {
LOGGER.debug("Starting in-app billing setup.");
billingClient = BillingClient.newBuilder(AbstractApplication.get()).setListener(this).build();
Runnable runnable = new Runnable() {
@Override
public void run() {
LOGGER.debug("In-app billing setup successful.");
for (ProductType productType : InAppBillingAppModule.get().getInAppBillingContext().getManagedProductTypes()) {
inventory.addProduct(new Product(productType));
}
if (isSubscriptionsSupported()) {
for (ProductType productType : InAppBillingAppModule.get().getInAppBillingContext().getSubscriptionsProductTypes()) {
inventory.addProduct(new Product(productType));
}
}
if (listener != null) {
listener.onSetupFinished();
}
}
};
if (isServiceConnected) {
runnable.run();
} else {
startServiceConnection(runnable);
}
} catch (Exception e) {
AbstractApplication.get().getExceptionHandler().logHandledException(e);
if (listener != null) {
listener.onSetupFailed(new UnexpectedException(e));
}
}
} | Starts the setup process. This will start up the setup process asynchronously. You will be notified through the
listener when the setup process is complete. |
@Override
// TODO This is executed for each client connected. Should we have only one client connected?
// TODO Call queryPurchases() at least twice in your code:
// - Every time your app launches so that you can restore any purchases that a user has made since the app last stopped.
// - In your onResume() method because a user can make a purchase when your app is in the background (for example, redeeming a promo code in Play Store app).
// Calling queryPurchases() on startup and resume guarantees that your app finds out about all purchases and redemptions
// the user may have made while the app wasn't running. Furthermore, if a user makes a purchase while the app is running
// and your app misses it for any reason, your app still finds out about the purchase the next time the activity resumes and calls queryPurchases().
// The simplest approach is to call queryPurchases() in your activity's onResume() method, since that callback fires
// when the activity is created, as well as when the activity is unpaused.
public void onPurchasesUpdated(@BillingClient.BillingResponse int resultCode, @Nullable List<Purchase> purchases) {
InAppBillingErrorCode inAppBillingErrorCode = InAppBillingErrorCode.findByErrorResponseCode(resultCode);
if (inAppBillingErrorCode == null) {
if (purchases != null) {
for (Purchase purchase : purchases) {
String productId = purchase.getSku();
Product product = inventory.getProduct(productId);
try {
if (product != null) {
product.setPurchase(signatureBase64, purchase.getOriginalJson(), purchase.getSignature(), InAppBillingAppModule.get().getDeveloperPayloadVerificationStrategy());
InAppBillingAppModule.get().getInAppBillingContext().addPurchasedProductType(product.getProductType());
// TODO Add logic here to see if we are replacing the same purchase. If yes, dont track
InAppBillingAppModule.get().getModuleAnalyticsSender().trackInAppBillingPurchase(product);
if (listener != null) {
listener.onPurchaseFinished(product);
}
if (product.isWaitingToConsume()) {
consume(product);
} else if (listener != null) {
listener.onProvideProduct(product);
}
} else {
AbstractApplication.get().getExceptionHandler().logWarningException(
"The purchased product [" + productId + "] is not supported by the app, so it is ignored");
}
} catch (ErrorCodeException e) {
AbstractApplication.get().getExceptionHandler().logHandledException(e);
if (listener != null) {
listener.onPurchaseFailed(e);
}
} catch (JSONException e) {
AbstractApplication.get().getExceptionHandler().logHandledException(e);
if (listener != null) {
listener.onPurchaseFailed(InAppBillingErrorCode.BAD_PURCHASE_DATA.newErrorCodeException(e));
}
}
}
}
} else if (inAppBillingErrorCode.equals(InAppBillingErrorCode.USER_CANCELED)) {
LOGGER.warn("User cancelled the purchase flow.");
if (listener != null) {
listener.onPurchaseFailed(InAppBillingErrorCode.USER_CANCELED.newErrorCodeException("User cancelled the purchase flow."));
}
} else {
AbstractApplication.get().getExceptionHandler().logHandledException(inAppBillingErrorCode.newErrorCodeException());
if (listener != null) {
listener.onPurchaseFailed(inAppBillingErrorCode.newErrorCodeException("Purchase failed."));
}
}
} | Handle a callback that purchases were updated from the Billing library |
private void launchPurchaseFlow(Activity activity, Product product, ItemType itemType, String oldProductId) {
executeServiceRequest(new Runnable() {
@Override
public void run() {
if (itemType.equals(ItemType.SUBSCRIPTION) && !isSubscriptionsSupported()) {
LOGGER.debug("Failed in-app purchase flow for product id " + product.getId() + ", item type: " + itemType + ". Subscriptions not supported.");
if (listener != null) {
listener.onPurchaseFailed(InAppBillingErrorCode.SUBSCRIPTIONS_NOT_AVAILABLE.newErrorCodeException());
}
} else {
LOGGER.debug("Launching in-app purchase flow for product id " + product.getId() + ", item type: " + itemType);
String productIdToBuy = InAppBillingAppModule.get().getInAppBillingContext().isStaticResponsesEnabled() ?
product.getProductType().getTestProductId() : product.getId();
BillingFlowParams purchaseParams = BillingFlowParams.newBuilder()
.setSku(productIdToBuy)
.setType(itemType.getType())
.setOldSku(oldProductId)
.build();
int responseCode = billingClient.launchBillingFlow(activity, purchaseParams);
InAppBillingErrorCode inAppBillingErrorCode = InAppBillingErrorCode.findByErrorResponseCode(responseCode);
if (inAppBillingErrorCode != null) {
if (listener != null) {
AbstractApplication.get().getExceptionHandler().logHandledException(inAppBillingErrorCode.newErrorCodeException());
listener.onPurchaseFailed(inAppBillingErrorCode.newErrorCodeException());
}
}
}
}
});
} | Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase, which will involve
bringing up the Google Play screen. The calling activity will be paused while the user interacts with Google
Play
This method MUST be called from the UI thread of the Activity.
@param activity The calling activity.
@param product The product to purchase.
@param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS)
@param oldProductId The SKU which the new SKU is replacing or null if there is none |
@MainThread
public void consume(final Product product) {
if (product.getProductType().getItemType().equals(ItemType.MANAGED)) {
String token = product.getPurchase().getToken();
String productId = product.getId();
if (StringUtils.isBlank(token)) {
ErrorCodeException errorCodeException = InAppBillingErrorCode.MISSING_TOKEN.newErrorCodeException("Can't consume " + product.getId() + ". No token.");
AbstractApplication.get().getExceptionHandler().logHandledException(errorCodeException);
if (listener != null) {
listener.onConsumeFailed(errorCodeException);
}
}
// If we've already scheduled to consume this token - no action is needed (this could happen
// if you received the token when querying purchases inside onReceive() and later from
// onActivityResult()
if (tokensToBeConsumed == null) {
tokensToBeConsumed = new HashSet<>();
} else if (tokensToBeConsumed.contains(token)) {
LOGGER.debug("Token was already scheduled to be consumed - skipping...");
return;
}
tokensToBeConsumed.add(token);
LOGGER.debug("Consuming productId: " + productId + ", token: " + token);
// Generating Consume Response listener
ConsumeResponseListener onConsumeListener = new ConsumeResponseListener() {
@Override
public void onConsumeResponse(@BillingClient.BillingResponse int responseCode, String purchaseToken) {
InAppBillingErrorCode inAppBillingErrorCode = InAppBillingErrorCode.findByErrorResponseCode(responseCode);
if (inAppBillingErrorCode == null) {
LOGGER.debug("Successfully consumed productId: " + productId);
if (listener != null) {
listener.onConsumeFinished(product);
listener.onProvideProduct(product);
}
} else {
AbstractApplication.get().getExceptionHandler().logHandledException(inAppBillingErrorCode.newErrorCodeException());
if (listener != null) {
listener.onConsumeFailed(inAppBillingErrorCode.newErrorCodeException("Consume failed."));
}
}
}
};
// Creating a runnable from the request to use it inside our connection retry policy below
executeServiceRequest(new Runnable() {
@Override
public void run() {
billingClient.consumeAsync(token, onConsumeListener);
}
});
} else {
ErrorCodeException errorCodeException = InAppBillingErrorCode.INVALID_CONSUMPTION.newErrorCodeException("Items of type '"
+ product.getProductType().getItemType() + "' can't be consumed.");
AbstractApplication.get().getExceptionHandler().logHandledException(errorCodeException);
if (listener != null) {
listener.onConsumeFailed(errorCodeException);
}
}
} | Consumes a given in-app product. Consuming can only be done on an item that's owned, and as a result of
consumption, the user will no longer own it.
@param product The {@link Product} that represents the item to consume. |
private int fillBuffer() throws IOException {
int n = super.read(buffer, 0, BUF_SIZE);
if (n >= 0) {
real_pos += n;
buf_end = n;
buf_pos = 0;
}
return n;
} | Reads the next BUF_SIZE bytes into the internal buffer. |
@Override
public int read(byte b[], int off, int len) throws IOException {
int leftover = buf_end - buf_pos;
if (len <= leftover) {
System.arraycopy(buffer, buf_pos, b, off, len);
buf_pos += len;
return len;
}
for (int i = 0; i < len; i++) {
int c = this.read();
if (c != -1) {
b[off + i] = (byte) c;
} else {
return i;
}
}
return len;
} | Reads the set number of bytes into the passed buffer.
@param b The buffer to read the bytes into.
@param off Byte offset within the file to start reading from
@param len Number of bytes to read into the buffer.
@return Number of bytes read. |
@Override
public void seek(long pos) throws IOException {
int n = (int) (real_pos - pos);
if (n >= 0 && n <= buf_end) {
buf_pos = buf_end - n;
} else {
super.seek(pos);
invalidate();
}
} | Moves the internal pointer to the passed (byte) position in the file.
@param pos The byte position to move to. |
public final String getNextLine() throws IOException {
String str = null;
if (buf_end - buf_pos <= 0) {
if (fillBuffer() < 0) {
return null;
}
}
int lineend = -1;
for (int i = buf_pos; i < buf_end; i++) {
if (buffer[i] == '\n') {
lineend = i;
break;
}
// check for only '\r' as line end
if ((i - buf_pos > 0) && buffer[i - 1] == '\r') {
lineend = i - 1;
break;
}
}
if (lineend < 0) {
StringBuilder input = new StringBuilder(256);
int c;
int lastC = 0;
while (((c = read()) != -1) && (c != '\n') && (lastC != '\r')) {
input.append((char) c);
lastC = c;
}
if ((c == -1) && (input.length() == 0)) {
return null;
}
return input.toString();
}
if (lineend > 0 && buffer[lineend] == '\n' && buffer[lineend - 1] == '\r') {
str = new String(buffer, buf_pos, lineend - buf_pos - 1);
} else {
str = new String(buffer, buf_pos, lineend - buf_pos);
}
buf_pos = lineend + 1;
return str;
} | Returns the next line from the file. In case no data could be loaded (generally as the end of
the file was reached) null is returned.
@return The next string on the file or null in case the end of the file was reached. |
@Override
protected void searchStep() {
// execute pipeline
pipeline.stream().forEachOrdered(l -> {
// attach listener
l.addSearchListener(pipelineListener);
// set initial solution (copy!)
l.setCurrentSolution(Solution.checkedCopy(getCurrentSolution()));
// run local search
l.start();
// get best solution found by search l
SolutionType bestSol = l.getBestSolution();
Evaluation bestSolEvaluation = l.getBestSolutionEvaluation();
Validation bestSolValidation = l.getBestSolutionValidation();
// if not null and different from current solution (i.e. improved):
// update current and best solution accordingly
if(bestSol != null && !bestSol.equals(getCurrentSolution())){
updateCurrentAndBestSolution(bestSol, bestSolEvaluation, bestSolValidation);
}
// remove listener
l.removeSearchListener(pipelineListener);
});
// pipeline complete: stop search
stop();
} | Executes all local searches in the pipeline, where the best solution of the previous search is used as initial
solution for the next search. When the entire pipeline has been executed, the search step is complete and the
search terminates. |
public Object getValue(ELContext context,
Object base,
Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base instanceof Map) {
context.setPropertyResolved(base, property);
Map map = (Map) base;
return map.get(property);
}
return null;
} | If the base object is a map, returns the value associated with the
given key, as specified by the <code>property</code> argument. If the
key was not found, <code>null</code> is returned.
<p>If the base is a <code>Map</code>, the <code>propertyResolved</code>
property of the <code>ELContext</code> object must be set to
<code>true</code> by this resolver, before returning. If this property
is not <code>true</code> after this method is called, the caller
should ignore the return value.</p>
<p>Just as in {@link java.util.Map#get}, just because <code>null</code>
is returned doesn't mean there is no mapping for the key; it's also
possible that the <code>Map</code> explicitly maps the key to
<code>null</code>.</p>
@param context The context of this evaluation.
@param base The map to be analyzed. Only bases of type <code>Map</code>
are handled by this resolver.
@param property The key whose associated value is to be returned.
@return If the <code>propertyResolved</code> property of
<code>ELContext</code> was set to <code>true</code>, then
the value associated with the given key or <code>null</code>
if the key was not found. Otherwise, undefined.
@throws ClassCastException if the key is of an inappropriate type
for this map (optionally thrown by the underlying <code>Map</code>).
@throws NullPointerException if context is <code>null</code>, or if
the key is null and this map does not permit null keys (the
latter is optionally thrown by the underlying <code>Map</code>).
@throws ELException if an exception was thrown while performing
the property or variable resolution. The thrown exception
must be included as the cause property of this exception, if
available. |
public void setValue(ELContext context,
Object base,
Object property,
Object val) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base instanceof Map) {
context.setPropertyResolved(base, property);
// The cast is safe
@SuppressWarnings("unchecked")
Map<Object, Object> map = (Map)base;
if (isReadOnly || map.getClass() == theUnmodifiableMapClass) {
throw new PropertyNotWritableException();
}
try {
map.put(property, val);
} catch (UnsupportedOperationException ex) {
throw new PropertyNotWritableException();
}
}
} | If the base object is a map, attempts to set the value associated with
the given key, as specified by the <code>property</code> argument.
<p>If the base is a <code>Map</code>, the <code>propertyResolved</code>
property of the <code>ELContext</code> object must be set to
<code>true</code> by this resolver, before returning. If this property
is not <code>true</code> after this method is called, the caller
can safely assume no value was set.</p>
<p>If this resolver was constructed in read-only mode, this method will
always throw <code>PropertyNotWritableException</code>.</p>
<p>If a <code>Map</code> was created using
{@link java.util.Collections#unmodifiableMap}, this method must
throw <code>PropertyNotWritableException</code>. Unfortunately,
there is no Collections API method to detect this. However, an
implementation can create a prototype unmodifiable <code>Map</code>
and query its runtime type to see if it matches the runtime type of
the base object as a workaround.</p>
@param context The context of this evaluation.
@param base The map to be modified. Only bases of type <code>Map</code>
are handled by this resolver.
@param property The key with which the specified value is to be
associated.
@param val The value to be associated with the specified key.
@throws ClassCastException if the class of the specified key or
value prevents it from being stored in this map.
@throws NullPointerException if context is <code>null</code>, or if
this map does not permit <code>null</code> keys or values, and
the specified key or value is <code>null</code>.
@throws IllegalArgumentException if some aspect of this key or
value prevents it from being stored in this map.
@throws ELException if an exception was thrown while performing
the property or variable resolution. The thrown exception
must be included as the cause property of this exception, if
available.
@throws PropertyNotWritableException if this resolver was constructed
in read-only mode, or if the put operation is not supported by
the underlying map. |
public boolean isReadOnly(ELContext context,
Object base,
Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base instanceof Map) {
context.setPropertyResolved(true);
Map map = (Map) base;
return isReadOnly || map.getClass() == theUnmodifiableMapClass;
}
return false;
} | If the base object is a map, returns whether a call to
{@link #setValue} will always fail.
<p>If the base is a <code>Map</code>, the <code>propertyResolved</code>
property of the <code>ELContext</code> object must be set to
<code>true</code> by this resolver, before returning. If this property
is not <code>true</code> after this method is called, the caller
should ignore the return value.</p>
<p>If this resolver was constructed in read-only mode, this method will
always return <code>true</code>.</p>
<p>If a <code>Map</code> was created using
{@link java.util.Collections#unmodifiableMap}, this method must
return <code>true</code>. Unfortunately, there is no Collections API
method to detect this. However, an implementation can create a
prototype unmodifiable <code>Map</code> and query its runtime type
to see if it matches the runtime type of the base object as a
workaround.</p>
@param context The context of this evaluation.
@param base The map to analyze. Only bases of type <code>Map</code>
are handled by this resolver.
@param property The key to return the read-only status for.
Ignored by this resolver.
@return If the <code>propertyResolved</code> property of
<code>ELContext</code> was set to <code>true</code>, then
<code>true</code> if calling the <code>setValue</code> method
will always fail or <code>false</code> if it is possible that
such a call may succeed; otherwise undefined.
@throws NullPointerException if context is <code>null</code>
@throws ELException if an exception was thrown while performing
the property or variable resolution. The thrown exception
must be included as the cause property of this exception, if
available. |
public Iterator<FeatureDescriptor> getFeatureDescriptors(
ELContext context,
Object base) {
if (base != null && base instanceof Map) {
Map map = (Map) base;
Iterator iter = map.keySet().iterator();
List<FeatureDescriptor> list = new ArrayList<FeatureDescriptor>();
while (iter.hasNext()) {
Object key = iter.next();
FeatureDescriptor descriptor = new FeatureDescriptor();
String name = (key==null)? null: key.toString();
descriptor.setName(name);
descriptor.setDisplayName(name);
descriptor.setShortDescription("");
descriptor.setExpert(false);
descriptor.setHidden(false);
descriptor.setPreferred(true);
if (key != null) {
descriptor.setValue("type", key.getClass());
}
descriptor.setValue("resolvableAtDesignTime", Boolean.TRUE);
list.add(descriptor);
}
return list.iterator();
}
return null;
} | If the base object is a map, returns an <code>Iterator</code>
containing the set of keys available in the <code>Map</code>.
Otherwise, returns <code>null</code>.
<p>The <code>Iterator</code> returned must contain zero or more
instances of {@link java.beans.FeatureDescriptor}. Each info object
contains information about a key in the Map, and is initialized as
follows:
<dl>
<li>displayName - The return value of calling the
<code>toString</code> method on this key, or
<code>"null"</code> if the key is <code>null</code>.</li>
<li>name - Same as displayName property.</li>
<li>shortDescription - Empty string</li>
<li>expert - <code>false</code></li>
<li>hidden - <code>false</code></li>
<li>preferred - <code>true</code></li>
</dl>
In addition, the following named attributes must be set in the
returned <code>FeatureDescriptor</code>s:
<dl>
<li>{@link ELResolver#TYPE} - The return value of calling the <code>getClass()</code>
method on this key, or <code>null</code> if the key is
<code>null</code>.</li>
<li>{@link ELResolver#RESOLVABLE_AT_DESIGN_TIME} - <code>true</code></li>
</dl>
</p>
@param context The context of this evaluation.
@param base The map whose keys are to be iterated over. Only bases
of type <code>Map</code> are handled by this resolver.
@return An <code>Iterator</code> containing zero or more (possibly
infinitely more) <code>FeatureDescriptor</code> objects, each
representing a key in this map, or <code>null</code> if
the base object is not a map. |
private void readVersion(TagValue tv) {
int maj = tv.getBytesBigEndian(8, 1); // Major version
int min = (tv.getBytesBigEndian(9, 1) & 0xF0) >> 4; // Minor version (in the first 4 bits of the
// byte)
version = maj + "." + min;
} | Read version.
@param tv the tv |
private void readClass(TagValue tv) {
int profileClass = tv.getBytesBigEndian(12, 4);
String hex = Integer.toHexString(profileClass);
if (hex.equals("73636e72")) {
this.profileClass = ProfileClass.Input;
} else if (hex.equals("6d6e7472")) {
this.profileClass = ProfileClass.Display;
} else if (hex.equals("70727472")) {
this.profileClass = ProfileClass.Output;
} else if (hex.equals("6C696e6b")) {
this.profileClass = ProfileClass.DeviceLink;
} else if (hex.equals("73706163")) {
this.profileClass = ProfileClass.ColorSpace;
} else if (hex.equals("61627374")) {
this.profileClass = ProfileClass.Abstract;
} else if (hex.equals("6e6d636c")) {
this.profileClass = ProfileClass.NamedColor;
} else {
this.profileClass = ProfileClass.Unknown;
}
} | Read class.
@param tv the tv |
private void readCreator(TagValue tv) {
int creatorSignature = tv.getBytesBigEndian(4, 4);
creator = IccProfileCreators.getIccProfile(creatorSignature);
} | Read creator.
@param tv the tv |
private void readDescription(TagValue tv) throws NumberFormatException, IOException {
int index = 128;
int tagCount = tv.getBytesBigEndian(index, 4);
index += 4;
for (int i = 0; i < tagCount; i++) {
int signature = tv.getBytesBigEndian(index, 4);
int tagOffset = tv.getBytesBigEndian(index + 4, 4);
if (Integer.toHexString(signature).equals("64657363")) {
String typedesc = Integer.toHexString(tv.getBytesBigEndian(tagOffset, 4));
if (typedesc.equals("64657363")) {
int size = tv.getBytesBigEndian(tagOffset + 8, 4) - 1;
String s = "";
int j = 0;
int begin = tagOffset + 12;
while (begin + j < begin + size) {
int unicode_char = tv.getBytesBigEndian(begin + j, 1);
s += Character.toString((char) unicode_char);
j++;
}
description = s;
} else {
description = "";
}
}
index += 12;
}
} | Read description.
@param tv the tag value
@throws IOException exception
@throws NumberFormatException exception |
@Override
public void read(TagValue tv) {
readClass(tv);
readVersion(tv);
readCreator(tv);
readEmbedded(tv);
try {
readDescription(tv);
} catch (NumberFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tv.clear();
tv.add(this);
} | Reads the desired values of the ICCProfile.
@param tv the TagValue containing the array of bytes of the ICCProfile |
public void putShort(short val) throws IOException {
if (byteOrder == ByteOrder.BIG_ENDIAN) {
writeIntCurrentPosition((val >>> 8) & 0xFF);
writeIntCurrentPosition((val >>> 0) & 0xFF);
}
else {
writeIntCurrentPosition((val >>> 0) & 0xFF);
writeIntCurrentPosition((val >>> 8) & 0xFF);
}
} | Puts a short (2 bytes).
@param val the val
@throws IOException Signals that an I/O exception has occurred. |
public void putInt(int val) throws IOException {
if (byteOrder == ByteOrder.BIG_ENDIAN) {
writeIntCurrentPosition((val >>> 24) & 0xFF);
writeIntCurrentPosition((val >>> 16) & 0xFF);
writeIntCurrentPosition((val >>> 8) & 0xFF);
writeIntCurrentPosition((val >>> 0) & 0xFF);
}
else {
writeIntCurrentPosition((val >>> 0) & 0xFF);
writeIntCurrentPosition((val >>> 8) & 0xFF);
writeIntCurrentPosition((val >>> 16) & 0xFF);
writeIntCurrentPosition((val >>> 24) & 0xFF);
}
} | Puts a int (4 bytes).
@param val the val
@throws IOException Signals that an I/O exception has occurred. |
public void putRational(Rational val) throws IOException {
putInt(val.getNumerator());
putInt(val.getDenominator());
} | Puts a Rational (4 bytes).
@param val the val
@throws IOException Signals that an I/O exception has occurred. |
public void putSRational(SRational val) throws IOException {
putInt(val.getNumerator());
putInt(val.getDenominator());
} | Puts a SRational (4 bytes).
@param val the val
@throws IOException Signals that an I/O exception has occurred. |
public void putFloat(Float val) throws IOException {
putInt(java.lang.Float.floatToIntBits(val.getValue()));
} | Puts a float (4 bytes).
@param val the val
@throws IOException Signals that an I/O exception has occurred. |
public void putDouble(Double val) throws IOException {
long v = java.lang.Double.doubleToLongBits(val.getValue());
if (byteOrder == ByteOrder.BIG_ENDIAN) {
writeIntCurrentPosition((int) (v >>> 56) & 0xFF);
writeIntCurrentPosition((int) (v >>> 48) & 0xFF);
writeIntCurrentPosition((int) (v >>> 40) & 0xFF);
writeIntCurrentPosition((int) (v >>> 32) & 0xFF);
writeIntCurrentPosition((int) (v >>> 24) & 0xFF);
writeIntCurrentPosition((int) (v >>> 16) & 0xFF);
writeIntCurrentPosition((int) (v >>> 8) & 0xFF);
writeIntCurrentPosition((int) (v >>> 0) & 0xFF);
} else {
writeIntCurrentPosition((int) (v >>> 0) & 0xFF);
writeIntCurrentPosition((int) (v >>> 8) & 0xFF);
writeIntCurrentPosition((int) (v >>> 16) & 0xFF);
writeIntCurrentPosition((int) (v >>> 24) & 0xFF);
writeIntCurrentPosition((int) (v >>> 32) & 0xFF);
writeIntCurrentPosition((int) (v >>> 40) & 0xFF);
writeIntCurrentPosition((int) (v >>> 48) & 0xFF);
writeIntCurrentPosition((int) (v >>> 56) & 0xFF);
}
} | Puts a double (4 bytes).
@param val the val
@throws IOException Signals that an I/O exception has occurred. |
@SuppressWarnings("unused")
private void setRetry() {
if (retryButton != null) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.jdroid_retry, this, true);
retryButton = (Button)this.findViewById(R.id.retry);
retryButton.setVisibility(View.VISIBLE);
}
} | TODO Retry. WIP |
@Override
public void init(){
// solution not yet set?
// NOTE: important to set solution before calling super,
// else super sets a random initial solution
if(getCurrentSolution() == null){
if(isIncreasing()){
// increasing: start with empty solution
SubsetSolution initial = getProblem().createEmptySubsetSolution();
updateCurrentAndBestSolution(initial);
} else {
// decreasing: start with full set
SubsetSolution initial = getProblem().createEmptySubsetSolution();
initial.selectAll();
updateCurrentAndBestSolution(initial);
}
}
// init super
super.init();
} | When the search is initialized, and no custom initial solution has been set,
an empty or full subset solution is created depending on whether \(L \gt R\)
or \(R \gt L\), respectively. |
private boolean validSubsetSizeRangeExplored(){
if(isIncreasing()){
return getCurrentSolution().getNumSelectedIDs() >= getProblem().getMaxSubsetSize();
} else {
return getCurrentSolution().getNumSelectedIDs() <= getProblem().getMinSubsetSize();
}
} | Indicates whether the entire valid subset size range has been explored. When the subset size is increasing
(\(L \gt R\)) this happens when the current subset size is larger than or equal to the maximum size. For
decreasing size, this happens when the current size is smaller than or equal to the minimum subset size.
@return <code>true</code> if the entire valid subset size range has been explored |
@Override
protected void searchStep() {
// check: valid subset size range completely explored?
if(validSubsetSizeRangeExplored()){
// we are done
stop();
} else {
int numAdd, numDel;
if(isIncreasing()){
// perform L additions
numAdd = greedyMoves(l, singleAddNeigh);
// perform number of deletions (<= R) that yields a delta of |L-R|,
// taking into account the actual number of added items
numDel = numAdd - getDelta();
greedyMoves(numDel, singleDelNeigh);
} else {
// perform R deletions
numDel = greedyMoves(r, singleDelNeigh);
// perform number of additions (<= L) that yields a delta of |L-R|,
// taking into account the actual number of deleted items
numAdd = numDel - getDelta();
greedyMoves(numAdd, singleAddNeigh);
}
if(numAdd == 0 || numDel == 0){
stop();
}
}
} | In every search step, the \(L\) best additions and \(R\) best deletions of a single item are performed.
If \(L \gt R\), additions are performed first, else, deletions are performed first. |
private int greedyMoves(int n, SubsetNeighbourhood neigh){
int applied = 0;
boolean cont = true;
while(applied < n && cont){
// go through all moves to find the best one
Move<? super SubsetSolution> bestMove = null;
double bestDelta = -Double.MAX_VALUE, delta;
Evaluation newEvaluation, bestEvaluation = null;
SubsetValidation newValidation, bestValidation = null;
for(Move<? super SubsetSolution> move : neigh.getAllMoves(getCurrentSolution())){
// validate move (IMPORTANT: ignore current subset size)
newValidation = getProblem().validate(move, getCurrentSolution(), getCurrentSolutionValidation());
if(newValidation.passed(false)){
// evaluate move
newEvaluation = getProblem().evaluate(move, getCurrentSolution(), getCurrentSolutionEvaluation());
// compute delta
delta = computeDelta(newEvaluation, getCurrentSolutionEvaluation());
// new best move?
if(delta > bestDelta){
bestDelta = delta;
bestMove = move;
bestEvaluation = newEvaluation;
bestValidation = newValidation;
}
}
}
// apply best move, if any
if(bestMove != null){
// apply move
bestMove.apply(getCurrentSolution());
// update current and best solution (NOTe: best solution will only be updated
// if it is fully valid, also taking into account the current subset size)
updateCurrentAndBestSolution(getCurrentSolution(), bestEvaluation, bestValidation);
// increase counter
applied++;
} else {
// no valid move found, stop
cont = false;
}
}
// return actual number of applied moves
return applied;
} | Greedily apply a series of n moves generated by the given neighbourhood, where the move yielding the most
improvement (or smallest decline) is iteratively selected. Returns the actual number of performed moves,
which is always lower than or equal to the requested number of moves. It may be strictly lower in case
no more moves can be applied at some point.
@param n number of requested moves
@return actual number of applied moves, lower than or equal to requested number of moves |
public MsRun.Spotting.Plate.Pattern.Orientation createMsRunSpottingPlatePatternOrientation() {
return new MsRun.Spotting.Plate.Pattern.Orientation();
} | Create an instance of {@link MsRun.Spotting.Plate.Pattern.Orientation } |
@XmlElementDecl(namespace = "http://sashimi.sourceforge.net/schema_revision/mzXML_3.2", name = "separationTechnique")
public JAXBElement<SeparationTechniqueType> createSeparationTechnique(
SeparationTechniqueType value) {
return new JAXBElement<SeparationTechniqueType>(_SeparationTechnique_QNAME,
SeparationTechniqueType.class, null, value);
} | Create an instance of {@link JAXBElement }{@code <}{@link SeparationTechniqueType }{@code >}} |
@SuppressWarnings("unchecked")
public <V extends View> V findView(View containerView, int id) {
return (V)containerView.findViewById(id);
} | Finds a view that was identified by the id attribute from the {@link View} view.
@param containerView The view that contains the view to find.
@param id The id to search for.
@param <V> The {@link View} class.
@return The view if found or null otherwise. |
public List<MsRun.ParentFile> getParentFile() {
if (parentFile == null) {
parentFile = new ArrayList<MsRun.ParentFile>();
}
return this.parentFile;
} | Gets the value of the parentFile property.
<p>
This accessor method returns a reference to the live list, not a snapshot. Therefore any
modification you make to the returned list will be present inside the JAXB object. This is why
there is not a <CODE>set</CODE> method for the parentFile property.
<p>
For example, to add a new item, do as follows:
<pre>
getParentFile().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list {@link MsRun.ParentFile } |
public List<MsRun.MsInstrument> getMsInstrument() {
if (msInstrument == null) {
msInstrument = new ArrayList<MsRun.MsInstrument>();
}
return this.msInstrument;
} | Gets the value of the msInstrument property.
<p>
This accessor method returns a reference to the live list, not a snapshot. Therefore any
modification you make to the returned list will be present inside the JAXB object. This is why
there is not a <CODE>set</CODE> method for the msInstrument property.
<p>
For example, to add a new item, do as follows:
<pre>
getMsInstrument().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list {@link MsRun.MsInstrument } |
public List<MsRun.DataProcessing> getDataProcessing() {
if (dataProcessing == null) {
dataProcessing = new ArrayList<MsRun.DataProcessing>();
}
return this.dataProcessing;
} | Gets the value of the dataProcessing property.
<p>
This accessor method returns a reference to the live list, not a snapshot. Therefore any
modification you make to the returned list will be present inside the JAXB object. This is why
there is not a <CODE>set</CODE> method for the dataProcessing property.
<p>
For example, to add a new item, do as follows:
<pre>
getDataProcessing().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list {@link MsRun.DataProcessing } |
@Override
public void setValue(ELContext context, Object base, Object property,
Object value) {
if (context == null) {
throw new NullPointerException();
}
if (base instanceof ELClass && property instanceof String) {
Class<?> klass = ((ELClass)base).getKlass();
String fieldName = (String) property;
throw new PropertyNotWritableException(
ELUtil.getExceptionMessageString(context,
"staticFieldWriteError",
new Object[] { klass.getName(), fieldName}));
}
} | <p> Attempts to write to a static field.</p>
<p>If the base object is an instance of <code>ELClass</code>and the
property is String, a <code>PropertyNotWritableException</code>
will always be thrown, because writing to a static field is not
allowed.
@param context The context of this evaluation.
@param base An <code>ELClass</code>
@param property The name of the field
@param value The value to set the field of the class to.
@throws NullPointerException if context is <code>null</code>
@throws PropertyNotWritableException |
@Override
public Object invoke(ELContext context,
Object base,
Object method,
Class<?>[] paramTypes,
Object[] params) {
if (context == null) {
throw new NullPointerException();
}
if (!(base instanceof ELClass && method instanceof String)) {
return null;
}
Class<?> klass = ((ELClass)base).getKlass();
String name = (String) method;
Object ret;
if ("<init>".equals(name)) {
Constructor<?> constructor =
ELUtil.findConstructor(klass, paramTypes, params);
ret = ELUtil.invokeConstructor(context, constructor, params);
} else {
Method meth =
ELUtil.findMethod(klass, name, paramTypes, params, true);
ret = ELUtil.invokeMethod(context, meth, null, params);
}
context.setPropertyResolved(base, method);
return ret;
} | <p>Invokes a public static method or the constructor for a class.</p>
If the base object is an instance of <code>ELClass</code> and the
method is a String,
the <code>propertyResolved</code> property of the
<code>ELContext</code> object must be set to <code>true</code>
by the resolver, before returning. If this property is not
<code>true</code> after this method is called, the caller
should ignore the return value.</p>
<p>Invoke the public static method specified by <code>method</code>.</p>
<p>The process involved in the method selection is
the same as that used in {@link BeanELResolver}.</p>
<p>As a special case, if the name of the method is "<init>", the
constructor for the class will be invoked.</p>
@param base An <code>ELClass</code>
@param method When coerced to a <code>String</code>,
the simple name of the method.
@param paramTypes An array of Class objects identifying the
method's formal parameter types, in declared order.
Use an empty array if the method has no parameters.
Can be <code>null</code>, in which case the method's formal
parameter types are assumed to be unknown.
@param params The parameters to pass to the method, or
<code>null</code> if no parameters.
@return The result of the method invocation (<code>null</code> if
the method has a <code>void</code> return type).
@throws MethodNotFoundException if no suitable method can be found.
@throws ELException if an exception was thrown while performing
(base, method) resolution. The thrown exception must be
included as the cause property of this exception, if
available. If the exception thrown is an
<code>InvocationTargetException</code>, extract its
<code>cause</code> and pass it to the
<code>ELException</code> constructor. |
@Override
public Class<?> getType(ELContext context, Object base, Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base instanceof ELClass && property instanceof String) {
Class<?> klass = ((ELClass)base).getKlass();
String fieldName = (String) property;
try {
context.setPropertyResolved(true);
Field field = klass.getField(fieldName);
int mod = field.getModifiers();
if (Modifier.isPublic(mod) && Modifier.isStatic(mod)) {
return field.getType();
}
} catch (NoSuchFieldException ex) {
}
throw new PropertyNotFoundException(
ELUtil.getExceptionMessageString(context,
"staticFieldReadError",
new Object[] { klass.getName(), fieldName}));
}
return null;
} | <p>Returns the type of a static field.</p>
<p>If the base object is an instance of <code>ELClass</code>and the
property is a String,
the <code>propertyResolved</code> property of the
<code>ELContext</code> object must be set to <code>true</code>
by the resolver, before returning. If this property is not
<code>true</code> after this method is called, the caller can
safely assume no value has been set.</p>
If the property string is a public static field of class specified in
ELClass, return the type of the static field.</p>
@param context The context of this evaluation.
@param base An <code>ELClass</code>.
@param property The name of the field.
@return If the <code>propertyResolved</code> property of
<code>ELContext</code> was set to <code>true</code>, then
the type of the type of the field.
@throws NullPointerException if context is <code>null</code>.
@throws PropertyNotFoundException if field is not a public static
filed of the class, or if the field is inaccessible. |
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base instanceof ELClass && property instanceof String) {
Class<?> klass = ((ELClass)base).getKlass();
context.setPropertyResolved(true);
}
return true;
} | <p>Inquires whether the static field is writable.</p>
<p>If the base object is an instance of <code>ELClass</code>and the
property is a String,
the <code>propertyResolved</code> property of the
<code>ELContext</code> object must be set to <code>true</code>
by the resolver, before returning. If this property is not
<code>true</code> after this method is called, the caller can
safely assume no value has been set.</p>
<p>Always returns a <code>true</code> because writing to a static field
is not allowed.</p>
@param context The context of this evaluation.
@param base An <code>ELClass</code>.
@param property The name of the bean.
@return <code>true</code>
@throws NullPointerException if context is <code>null</code>. |
public Base64Context decode(final byte[] pArray, Base64Context ctx)
throws FileParsingException {
return decode(pArray, 0, pArray.length, ctx);
} | Decodes a byte[] containing characters in the Base-N alphabet.
@param pArray A byte array containing Base-N character data
@return a byte array containing binary data |
public Base64Context decode(final char[] pArray, final int offset, final int length,
Base64Context ctx)
throws FileParsingException {
if (pArray == null || pArray.length == 0) {
return null;
}
decodeImpl(pArray, offset, length, ctx);
decodeImpl(pArray, 0, EOF, ctx); // Notify decoder of EOF.
return ctx;
} | Decodes a char[] containing characters in the Base-N alphabet.
@param pArray A byte array containing Base-N character data
@param offset offset in the input array where the data starts
@param length length of the data, starting at offset in the input array
@param ctx {@link Base64Context} or {@link Base64ContextPooled}, pooled version is preferred
@return a byte array containing binary data |
void decodeImpl(final char[] chars, final int offset, final int length, Base64Context ctx)
throws FileParsingException {
try {
if (ctx.eof) {
return;
}
byte[] buffer = null;
if (length < 0) {
ctx.eof = true;
} else {
// in general the resulting decoded array should be 3/4 the
// length of the input. We double that amount, as consequent scans
// might have longer base64 strings
buffer = ctx.ensureBufferHasCapacityLeft(length * 2);
}
int readPos = offset;
byte b;
for (int i = 0; i < length; i++) {
// I don't know why in Apache impl this has been checked on every iteration
//final byte[] buffer = ensureBufferSize(decodeSize, context);
b = (byte) chars[readPos++];
if (b == PAD) {
// We're done.
ctx.eof = true;
break;
} else {
try {
if (b >= 0 && b < DECODE_TABLE.length) {
final int result = DECODE_TABLE[b];
if (result >= 0) {
ctx.modulus = (ctx.modulus + 1) % BYTES_PER_ENCODED_BLOCK;
ctx.ibitWorkArea = (ctx.ibitWorkArea << BITS_PER_ENCODED_BYTE) + result;
if (ctx.modulus == 0) {
buffer[ctx.pos] = (byte) ((ctx.ibitWorkArea >> 16) & MASK_8BITS);
ctx.pos++;
buffer[ctx.pos] = (byte) ((ctx.ibitWorkArea >> 8) & MASK_8BITS);
ctx.pos++;
buffer[ctx.pos] = (byte) (ctx.ibitWorkArea & MASK_8BITS);
ctx.pos++;
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new FileParsingException(
"Something went wrong in Base64 decoder, got out of array bounds", e);
}
}
}
// Two forms of EOF as far as base64 decoder is concerned: actual
// EOF (-1) and first time '=' character is encountered in stream.
// This approach makes the '=' padding characters completely optional.
if (ctx.eof && ctx.modulus != 0) {
buffer = ctx.ensureBufferHasCapacityLeft(decodeSize);
// We have some spare bits remaining
// Output all whole multiples of 8 bits and ignore the rest
switch (ctx.modulus) {
//case 0 : // impossible, as excluded above
case 1: // 6 bits - ignore entirely
// TODO not currently tested; perhaps it is impossible?
break;
case 2: // 12 bits = 8 + 4
ctx.ibitWorkArea = ctx.ibitWorkArea >> 4; // dump the extra 4 bits
buffer[ctx.pos++] = (byte) ((ctx.ibitWorkArea) & MASK_8BITS);
break;
case 3: // 18 bits = 8 + 8 + 2
ctx.ibitWorkArea = ctx.ibitWorkArea >> 2; // dump 2 bits
buffer[ctx.pos++] = (byte) ((ctx.ibitWorkArea >> 8) & MASK_8BITS);
buffer[ctx.pos++] = (byte) ((ctx.ibitWorkArea) & MASK_8BITS);
break;
default:
throw new IllegalStateException("Impossible modulus " + ctx.modulus);
}
}
} finally {
ctx.syncBufferPos();
}
} | <p>
Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at
least twice: once with the data to decode, and once with inAvail set to "-1" to alert decoder
that EOF has been reached. The "-1" call is not necessary when decoding, but it doesn't hurt,
either.
</p>
<p>
Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled,
since CR and LF are silently ignored, but has implications for other bytes, too. This method
subscribes to the garbage-in, garbage-out philosophy: it will not check the provided data for
validity.
</p>
<p>
Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
</p>
@param chars char[] array of ascii data to base64 decode.
@param offset offset in the input array where the data starts
@param length length of the data, starting at offset in the input array
@param ctx the context to be used |
public static void addCacheEntry(final ClassLoader classLoader, final String factoryId, final String factoryClassName) {
if (factoryClassName == null) {
CLASS_CACHE.put(new CacheKey(classLoader, factoryId), "");
} else {
CLASS_CACHE.put(new CacheKey(classLoader, factoryId), factoryClassName);
}
} | Called by the container at deployment time to set the name of a given factory, to remove the need for the
implementation to look it up on every call.
@param classLoader The deployments class loader
@param factoryId The type of factory that is being recorded (at this stage only javax.el.ExpressionFactory has any effect
@param factoryClassName The name of the factory class that is present in the deployment, or null if none is present |
public static void clearClassLoader(final ClassLoader classLoader) {
BeanPropertiesCache.clear(classLoader);
final Iterator<Map.Entry<CacheKey, String>> it = CLASS_CACHE.entrySet().iterator();
while (it.hasNext()) {
final CacheKey key = it.next().getKey();
if (key.loader == classLoader) {
it.remove();
}
}
} | This should be called by the container on undeploy to remove all references to the given class loader
from the cache.
@param classLoader The class loader to remove |
public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) || TextUtils.isEmpty(signature)) {
LOGGER.error("Purchase verification failed: missing data.");
return false;
}
PublicKey key = Security.generatePublicKey(base64PublicKey);
return Security.verify(key, signedData, signature);
} | Verifies that the data was signed with the given signature, and returns the verified purchase. The data is in
JSON format and signed with a private key.
@param base64PublicKey the base64-encoded public key to use for verifying.
@param signedData the signed JSON string (signed, not encrypted)
@param signature the signature for the data, signed with the private key
@return Whether the verification was successful or not |
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
byte[] signatureBytes;
try {
signatureBytes = Base64.decode(signature, Base64.DEFAULT);
} catch (IllegalArgumentException e) {
LOGGER.error("Base64 decoding failed.");
return false;
}
try {
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(signatureBytes)) {
LOGGER.error("Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
LOGGER.error("NoSuchAlgorithmException.");
} catch (InvalidKeyException e) {
LOGGER.error("Invalid key specification.");
} catch (SignatureException e) {
LOGGER.error("Signature exception.");
}
return false;
} | Verifies that the signature from the server matches the computed signature on the data.
Returns true if the data is correctly signed.
@param publicKey public key associated with the developer account
@param signedData signed data from server
@param signature server signature
@return true if the data and signature match |
public void createValuesDictionary() {
tagValueDescriptions = new HashMap<String, String>();
if (valueCodes != null && valueDescriptions != null && valueCodes.size() > 0
&& valueCodes.size() == valueDescriptions.size()) {
for (int i = 0; i < valueCodes.size(); i++) {
tagValueDescriptions.put(valueCodes.get(i) + "", valueDescriptions.get(i));
}
}
} | Creates the values dictionary. |
public String getTextDescription(String encodedValue) {
if (forceDescription != null) {
return forceDescription;
}
String desc = null;
if (tagValueDescriptions.containsKey(encodedValue)) {
desc = tagValueDescriptions.get(encodedValue);
}
return desc;
} | Gets the tag value description.
@param encodedValue the encoded value
@return the tag value description |
@Override
public void validate() {
try {
IFD ifd = model.getFirstIFD();
int n = 0;
while (ifd != null) {
validateIfd(ifd, n);
ifd = ifd.getNextIFD();
n++;
}
} catch (Exception e) {
}
} | Validates that the IFD conforms the Tiff/EP standard. |
private void validateIfd(IFD ifd, int n) {
boolean hasSubIfd = ifd.hasSubIFD();
boolean thumbnail = hasSubIfd && ifd.getsubIFD().getImageSize() > ifd.getImageSize();
boolean structureOk = false;
IfdTags metadata;
if (!hasSubIfd) {
validation.addErrorLoc("Missing Sub IFD", "IFD" + n);
metadata = ifd.getMetadata();
} else if (!thumbnail) {
validation.addErrorLoc("Sub IFD image is not bigger than the main image", "IFD" + n);
metadata = ifd.getMetadata();
} else {
metadata = ifd.getsubIFD().getMetadata();
structureOk = true;
}
checkRequiredTag(metadata, "ImageLength", 1, "IFD" + n);
checkRequiredTag(metadata, "ImageWidth", 1, "IFD" + n);
int spp = -1;
if (checkRequiredTag(metadata, "SamplesPerPixel", 1, "IFD" + n)) {
spp = (int) metadata.get("SamplesPerPixel").getFirstNumericValue();
checkRequiredTag(metadata, "BitsPerSample", spp, "IFD" + n);
}
if (n == 0)
checkRequiredTag(metadata, "ImageDescription", -1, "IFD" + n);
if (checkRequiredTag(metadata, "Compression", 1, "IFD" + n)) {
int comp = (int) metadata.get("Compression").getFirstNumericValue();
if (comp == 1)
checkForbiddenTag(metadata, "CompressedBitsPerPixel", "IFD" + n);
}
checkRequiredTag(metadata, "XResolution", 1, "IFD" + n);
checkRequiredTag(metadata, "YResolution", 1, "IFD" + n);
if (n == 0)
checkRequiredTag(metadata, "Make", -1, "IFD" + n);
if (n == 0)
checkRequiredTag(metadata, "Model", -1, "IFD" + n);
if (n == 0)
checkRequiredTag(metadata, "Software", -1, "IFD" + n);
if (n == 0)
checkRequiredTag(metadata, "Copyright", -1, "IFD" + n);
if (n == 0)
checkRequiredTag(metadata, "DateTimeOriginal", 20, "IFD" + n);
if (n == 0)
checkRequiredTag(metadata, "DateTime", 20, "IFD" + n);
if (n == 0)
checkRequiredTag(metadata, "TIFFEPStandardID", 4, "IFD" + n);
if (checkRequiredTag(metadata, "NewSubfileType", 1, new long[] {0, 1}, "IFD" + n)) {
if (structureOk) {
checkRequiredTag(ifd.getMetadata(), "NewSubfileType", 1, new long[] {1}, "IFD" + n);
checkRequiredTag(metadata, "NewSubfileType", 1, new long[] {0}, "IFD" + n);
}
int nst = (int) metadata.get("NewSubfileType").getFirstNumericValue();
if (nst != 0) {
if (n == 0)
checkRequiredTag(metadata, "SubIFDs", -1, "IFD" + n);
}
}
if (checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[]{1, 2, 6, 32803,
32767}, "IFD" + n)) {
int photo = (int) metadata.get("PhotometricInterpretation").getFirstNumericValue();
if (photo != 6) {
checkForbiddenTag(metadata, "YCbCrCoefficients", "IFD" + n);
checkForbiddenTag(metadata, "YCbCrSubSampling", "IFD" + n);
checkForbiddenTag(metadata, "YCbCrPositioning", "IFD" + n);
checkForbiddenTag(metadata, "ReferenceBlackWhite", "IFD" + n);
}
if (photo == 2 || photo == 3) {
if (spp != 3) {
validation.addError("Invalid SampesPerPixel value fo TiffEP", "IFD" + n, spp);
}
} else if (photo == 1 || photo == 32803) {
if (spp != 1) {
validation.addError("Invalid SampesPerPixel value fo TiffEP", "IFD" + n, spp);
}
if (photo == 32803) {
checkRequiredTag(metadata, "CFARepeatPatternDim", 2, "IFD" + n);
checkRequiredTag(metadata, "CFAPattern", -1, "IFD" + n);
}
}
}
checkRequiredTag(metadata, "PlanarConfiguration", 1, new long[] {1, 2}, "IFD" + n);
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[] {1, 2, 3}, "IFD" + n);
if (metadata.containsTagId(TiffTags.getTagId("Orientation")))
checkRequiredTag(metadata, "Orientation", 1, new long[] {1, 3, 6, 8, 9}, "IFD" + n);
if (!thumbnail) {
if (ifd.hasStrips()) {
checkRequiredTag(metadata, "StripBYTECount", -1, "IFD" + n);
checkRequiredTag(metadata, "StripOffsets", -1, "IFD" + n);
checkRequiredTag(metadata, "RowsPerStrip", 1, "IFD" + n);
if (ifd.hasTiles()) {
validation.addErrorLoc("Image in both strips and tiles", "IFD" + n);
}
} else if (ifd.hasTiles()) {
checkRequiredTag(metadata, "TileLength", 1, "IFD" + n);
checkRequiredTag(metadata, "TileOffsets", 1, "IFD" + n);
checkRequiredTag(metadata, "TileWidth", -1, "IFD" + n);
}
} else {
checkRequiredTag(metadata, "StripBYTECount", -1, "IFD" + n);
checkRequiredTag(metadata, "StripOffsets", -1, "IFD" + n);
checkRequiredTag(metadata, "RowsPerStrip", 1, "IFD" + n);
checkForbiddenTag(metadata, "TileLength", "IFD" + n);
checkForbiddenTag(metadata, "TileOffsets", "IFD" + n);
checkForbiddenTag(metadata, "TileWidth", "IFD" + n);
}
int nycbcr = 0;
if (metadata.containsTagId(TiffTags.getTagId("YCbCrCoefficients")))
nycbcr++;
if (metadata.containsTagId(TiffTags.getTagId("YCbCrSubSampling")))
nycbcr++;
if (metadata.containsTagId(TiffTags.getTagId("YCbCrPositioning")))
nycbcr++;
if (metadata.containsTagId(TiffTags.getTagId("ReferenceBlackWhite")))
nycbcr++;
if (nycbcr > 0 && nycbcr != 4) {
checkRequiredTag(metadata, "YCbCrCoefficients", 3, "IFD" + n);
checkRequiredTag(metadata, "YCbCrSubSampling", 2, "IFD" + n);
checkRequiredTag(metadata, "YCbCrPositioning", 1, "IFD" + n);
checkRequiredTag(metadata, "ReferenceBlackWhite", 6, "IFD" + n);
}
if (thumbnail) {
checkForbiddenTag(metadata, "YCbCrCoefficients", "IFD" + n);
checkForbiddenTag(metadata, "YCbCrSubSampling", "IFD" + n);
checkForbiddenTag(metadata, "YCbCrPositioning", "IFD" + n);
checkForbiddenTag(metadata, "ReferenceBlackWhite", "IFD" + n);
}
checkForbiddenTag(metadata, "PrimaryChromaticities", "IFD" + n);
checkForbiddenTag(metadata, "WhitePoint", "IFD" + n);
checkForbiddenTag(metadata, "TransferFunction", "IFD" + n);
if (metadata.containsTagId(TiffTags.getTagId("FocalPlaneResolutionUnit"))) {
int focal = (int) metadata.get("FocalPlaneResolutionUnit").getFirstNumericValue();
if (focal < 1 || focal > 5)
validation.addErrorLoc("Invalid value fot TiffEP tag FocalPlaneResolutionUnit", "IFD" + n);
}
if (metadata.containsTagId(TiffTags.getTagId("SensingMethod"))) {
int sensing = (int) metadata.get("SensingMethod").getFirstNumericValue();
if (sensing < 0 || sensing > 8)
validation.addErrorLoc("Invalid value fot TiffEP tag SensingMethod", "IFD" + n);
}
} | Validate ifd.
@param ifd the ifd
@param n the ifd number |
@SuppressWarnings("unused")
@Deprecated
private void validateSubIfd(IFD ifd, int n) {
boolean thumbnail = ifd.getParent().getImageSize() > ifd.getImageSize();
IfdTags metadata = ifd.getMetadata();
checkRequiredTag(metadata, "ImageLength", 1, "SubIFD" + n);
checkRequiredTag(metadata, "ImageWidth", 1, "SubIFD" + n);
int spp = -1;
if (checkRequiredTag(metadata, "SamplesPerPixel", 1, "SubIFD" + n)) {
spp = (int) metadata.get("SamplesPerPixel").getFirstNumericValue();
checkRequiredTag(metadata, "BitsPerSample", spp, "SubIFD" + n);
}
if (checkRequiredTag(metadata, "Compression", 1, "SubIFD" + n)) {
int comp = (int) metadata.get("Compression").getFirstNumericValue();
if (comp == 1)
checkForbiddenTag(metadata, "CompressedBitsPerPixel", "IFD" + n);
}
checkRequiredTag(metadata, "XResolution", 1, "SubIFD" + n);
checkRequiredTag(metadata, "YResolution", 1, "SubIFD" + n);
checkForbiddenTag(metadata, "SubIFDs", "IFD" + n);
if (thumbnail)
checkRequiredTag(metadata, "NewSubfileType", 1, new long[] {1}, "SubIFD" + n);
else
checkRequiredTag(metadata, "NewSubfileType", 1, new long[] {0}, "SubIFD" + n);
if (checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {1, 2, 6, 32803,
32767}, "SubIFD" + n)) {
int photo = (int) metadata.get("PhotometricInterpretation").getFirstNumericValue();
if (photo != 6) {
checkForbiddenTag(metadata, "YCbCrCoefficients", "SubIFD" + n);
checkForbiddenTag(metadata, "YCbCrSubSampling", "SubIFD" + n);
checkForbiddenTag(metadata, "YCbCrPositioning", "SubIFD" + n);
checkForbiddenTag(metadata, "ReferenceBlackWhite", "SubIFD" + n);
}
if (photo == 2 || photo == 3) {
if (spp != 3) {
validation.addError("Invalid SampesPerPixel value fo TiffEP", "SubIFD" + n, spp);
}
} else if (photo == 1 || photo == 32803) {
if (spp != 1) {
validation.addError("Invalid SampesPerPixel value fo TiffEP", "SubIFD" + n, spp);
}
if (photo == 32803) {
checkRequiredTag(metadata, "CFARepeatPatternDim", 2, "SubIFD" + n);
checkRequiredTag(metadata, "CFAPattern", -1, "SubIFD" + n);
}
}
}
checkRequiredTag(metadata, "PlanarConfiguration", 1, new long[] {1, 2}, "SubIFD" + n);
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[] {1, 2, 3}, "SubIFD" + n);
if (!thumbnail) {
if (ifd.hasStrips()) {
checkRequiredTag(metadata, "StripBYTECount", -1, "SubIFD" + n);
checkRequiredTag(metadata, "StripOffsets", -1, "SubIFD" + n);
checkRequiredTag(metadata, "RowsPerStrip", 1, "SubIFD" + n);
if (ifd.hasTiles()) {
validation.addErrorLoc("Image in both strips and tiles", "SubIFD");
}
} else if (ifd.hasTiles()) {
checkRequiredTag(metadata, "TileLength", 1, "SubIFD" + n);
checkRequiredTag(metadata, "TileOffsets", 1, "SubIFD" + n);
checkRequiredTag(metadata, "TileWidth", -1, "SubIFD" + n);
}
} else {
checkRequiredTag(metadata, "StripBYTECount", -1, "SubIFD" + n);
checkRequiredTag(metadata, "StripOffsets", -1, "SubIFD" + n);
checkRequiredTag(metadata, "RowsPerStrip", 1, "SubIFD" + n);
checkForbiddenTag(metadata, "TileLength", "SubIFD" + n);
checkForbiddenTag(metadata, "TileOffsets", "SubIFD" + n);
checkForbiddenTag(metadata, "TileWidth", "SubIFD" + n);
}
int nycbcr = 0;
if (metadata.containsTagId(TiffTags.getTagId("YCbCrCoefficients")))
nycbcr++;
if (metadata.containsTagId(TiffTags.getTagId("YCbCrSubSampling")))
nycbcr++;
if (metadata.containsTagId(TiffTags.getTagId("YCbCrPositioning")))
nycbcr++;
if (metadata.containsTagId(TiffTags.getTagId("ReferenceBlackWhite")))
nycbcr++;
if (nycbcr > 0 && nycbcr != 4) {
checkRequiredTag(metadata, "YCbCrCoefficients", 3, "SubIFD" + n);
checkRequiredTag(metadata, "YCbCrSubSampling", 2, "SubIFD" + n);
checkRequiredTag(metadata, "YCbCrPositioning", 1, "SubIFD" + n);
checkRequiredTag(metadata, "ReferenceBlackWhite", 6, "SubIFD" + n);
}
if (thumbnail) {
checkForbiddenTag(metadata, "YCbCrCoefficients", "IFD" + n);
checkForbiddenTag(metadata, "YCbCrSubSampling", "IFD" + n);
checkForbiddenTag(metadata, "YCbCrPositioning", "IFD" + n);
checkForbiddenTag(metadata, "ReferenceBlackWhite", "IFD" + n);
}
checkForbiddenTag(metadata, "PrimaryChromaticities", "IFD" + n);
checkForbiddenTag(metadata, "WhitePoint", "IFD" + n);
checkForbiddenTag(metadata, "TransferFunction", "IFD" + n);
} | Validate sub ifd.
@param ifd the subifd
@param n the ifd number |
private void checkForbiddenTag(IfdTags metadata, String tagName, String ext) {
int tagid = TiffTags.getTagId(tagName);
if (metadata.containsTagId(tagid)) {
validation.addErrorLoc("Forbidden tag for TiffEP found " + tagName, ext);
}
} | Check a forbidden tag is not present.
@param metadata the metadata
@param tagName the tag name
@param ext string extension |
public static IccProfileCreator getIccProfile(int identifier) {
IccProfileCreator icc = null;
try {
if (instance == null)
getIccProfileCreators();
if (creatorsMap.containsKey(identifier))
icc = creatorsMap.get(identifier);
} catch (ReadIccConfigIOException e) {
}
return icc;
} | Gets tag information.
@param identifier Tag id
@return the tag or null if the identifier does not exist |
@Override
protected void searchStep() {
// get best valid move with positive delta
Move<? super SolutionType> move = getBestMove(
getNeighbourhood().getAllMoves(getCurrentSolution()), // generate all moves
true); // only improvements
// found improvement ?
if(move != null){
// accept move
accept(move);
} else {
// no improvement found
stop();
}
} | Investigates all neighbours of the current solution and adopts the best one as the new current solution,
if it is an improvement. If no improvement is found, the search is requested to stop and no further steps
will be performed.
@throws JamesRuntimeException if depending on malfunctioning components (problem, neighbourhood, ...) |
public ELContext setELContext(ELContext context) {
ELContext prev = elContext;
elContext = new StandardELContext(context);
return prev;
} | Set the ELContext used for parsing and evaluating EL expressions.
The supplied ELContext will not be modified, except for the context
object map.
@param context The new ELContext.
@return The previous ELContext, null if none. |
public void mapFunction(String prefix, String function, Method meth) {
getELContext().getFunctionMapper().mapFunction(prefix, function, meth);
} | Maps a static method to an EL function.
@param prefix The namespace of the functions, can be "".
@param function The name of the function.
@param meth The static method to be invoked when the function is used. |
public Object defineBean(String name, Object bean) {
Object ret = getELContext().getBeans().get(name);
getELContext().getBeans().put(name, bean);
return ret;
} | Define a bean in the local bean repository
@param name The name of the bean
@param bean The bean instance to be defined. If null, the definition
of the bean is removed. |
@Override
public SubsetValidation validate(SubsetSolution solution){
// check size
boolean validSize = solution.getNumSelectedIDs() >= getMinSubsetSize()
&& solution.getNumSelectedIDs() <= getMaxSubsetSize();
// combine with mandatory constraint validation
if(getMandatoryConstraints().isEmpty()){
// CASE 1: no mandatory constraints -- return constant validation object
return validSize ? UNCONSTRAINED_VALID_SIZE : UNCONSTRAINED_INVALID_SIZE;
} else {
// CASE 2: mandatory constraint(s) -- wrap constraints validation in subset validation
Validation constraintVal = super.validate(solution);
return new SubsetValidation(validSize, constraintVal);
}
} | Validate a subset solution. The returned validation object separately indicates whether
the solution passed general mandatory constraint validation and whether it has a valid size.
@param solution solution to validate
@return subset validation |
@Override
public SubsetValidation validate(Move<? super SubsetSolution> move,
SubsetSolution curSolution,
Validation curValidation){
// check type and cast
if(move instanceof SubsetMove){
SubsetMove subsetMove = (SubsetMove) move;
// update and check size
int newSize = curSolution.getNumSelectedIDs() + subsetMove.getNumAdded() - subsetMove.getNumDeleted();
boolean validSize = newSize >= getMinSubsetSize() && newSize <= getMaxSubsetSize();
// combine with mandatory constraint delta validation
if(getMandatoryConstraints().isEmpty()){
// CASE 1: no mandatory constraints -- return constant validation object
return validSize ? UNCONSTRAINED_VALID_SIZE : UNCONSTRAINED_INVALID_SIZE;
} else {
// CASE 2: mandatory constraint(s) -- extract and update mandatory constraints validation
SubsetValidation subsetVal = (SubsetValidation) curValidation;
// delta validation of mandatory constraints
Validation deltaVal = super.validate(subsetMove, curSolution, subsetVal.getConstraintValidation());
// create and return new subset validation
return new SubsetValidation(validSize, deltaVal);
}
} else {
throw new IncompatibleDeltaValidationException("Delta validation in subset problem expects moves "
+ "of type SubsetMove. Received: "
+ move.getClass().getSimpleName());
}
} | Validate a move to be applied to the current subset solution of a local search (delta validation).
A subset problem can only perform delta validation for moves of type {@link SubsetMove}. If the
received move has a different type an {@link IncompatibleDeltaValidationException} is thrown.
@param move subset move to be validated
@param curSolution current solution
@param curValidation current validation
@return subset validation of modified subset solution
@throws IncompatibleDeltaValidationException if the received move is not of type {@link SubsetMove}
or if the delta validation of any mandatory constraint
is not compatible with the received move type |
public void setMaxSubsetSize(int maxSubsetSize) {
// check size
if(maxSubsetSize < minSubsetSize){
throw new IllegalArgumentException("Error while setting maximum subset size: should be >= minimum subset size.");
}
if(maxSubsetSize > getData().getIDs().size()){
throw new IllegalArgumentException("Error while setting maximum subset size: can not be larger "
+ "than number of items in underlying data.");
}
this.maxSubsetSize = maxSubsetSize;
} | Set the maximum subset size. Specified size should be ≥ the current minimum subset size
and ≤ the number of items in the underlying data.
@param maxSubsetSize new maximum subset size
@throws IllegalArgumentException if an invalid maximum size is given |
public static <T> T getRandomElement(Set<? extends T> set, Random rg){
Iterator<? extends T> it = set.iterator();
int r = rg.nextInt(set.size());
T selected = it.next();
for(int i=0; i<r; i++){
selected = it.next();
}
return selected;
} | Select a random element from a given set (uniformly distributed). This implementation generates
a random number r in [0,|set|-1] and traverses the set using an iterator, where the element obtained
after r+1 applications of {@link Iterator#next()} is returned. In the worst case, this algorithm has
linear time complexity with respect to the size of the given set.
@param <T> type of randomly selected element
@param set set from which to select a random element
@param rg random generator
@return random element (uniformly distributed) |
public static <T> Collection<T> getRandomSubset(Set<? extends T> set, int size, Random rg, Collection<T> subset) {
// check size
if(size < 0 || size > set.size()){
throw new IllegalArgumentException("Error in SetUtilities: desired subset size should be a number in [0,|set|].");
}
// remaining number of items to select
int remainingToSelect = size;
// remaining number of candidates to consider
int remainingToScan = set.size();
Iterator<? extends T> it = set.iterator();
// randomly add items until desired size is obtained
while (remainingToSelect > 0){
// get next element
T item = it.next();
// select item:
// 1) always, if all remaining items have to be selected (#remaining to select == #remaining to scan)
// 2) else, with probability (#remaining to select)/(#remaining to scan) < 1
if (remainingToSelect == remainingToScan
|| rg.nextDouble() < ((double)remainingToSelect) / remainingToScan){
subset.add(item);
remainingToSelect--;
}
remainingToScan--;
}
// return selected subset
return subset;
} | <p>
Selects a random subset of a specific size from a given set (uniformly distributed).
Applies a full scan algorithm that iterates once through the given set and selects each item with probability
(#remaining to select)/(#remaining to scan). It can be proven that this algorithm creates uniformly distributed
random subsets (for example, a proof is given <a href="http://eyalsch.wordpress.com/2010/04/01/random-sample">here</a>).
In the worst case, this algorithm has linear time complexity with respect to the size of the given set.
</p>
<p>
The items from the selected subset are added to the given collection <code>subset</code>. This collection is
<b>not</b> cleared so that already contained items will be retained. A reference to this same collection is
returned after it has been modified. To store the generated subset in a newly allocated {@link LinkedHashSet}
the alternative method {@link #getRandomSubset(Set, int, Random)} may also be used.
</p>
@see <a href="http://eyalsch.wordpress.com/2010/04/01/random-sample">http://eyalsch.wordpress.com/2010/04/01/random-sample</a>
@param <T> type of elements in randomly selected subset
@param set set from which a random subset is to be sampled
@param size desired subset size, should be a number in [0,|set|]
@param rg random generator
@param subset collection to which the items from the selected subset are added
@throws IllegalArgumentException if an invalid subset size outside [0,|set|] is specified
@return reference to given collection <code>subset</code> after it has been filled with the
items from the randomly generated subset |
public static <T> Set<T> getRandomSubset(Set<? extends T> set, int size, Random rg) {
Set<T> subset = new LinkedHashSet<>();
getRandomSubset(set, size, rg, subset);
return subset;
} | <p>
Selects a random subset of a specific size from a given set (uniformly distributed).
Applies a full scan algorithm that iterates once through the given set and selects each item with probability
(#remaining to select)/(#remaining to scan). It can be proven that this algorithm creates uniformly distributed
random subsets (for example, a proof is given <a href="http://eyalsch.wordpress.com/2010/04/01/random-sample">here</a>).
In the worst case, this algorithm has linear time complexity with respect to the size of the given set.
</p>
<p>
The generated subset is stored in a newly allocated {@link LinkedHashSet}.
</p>
@see <a href="http://eyalsch.wordpress.com/2010/04/01/random-sample">http://eyalsch.wordpress.com/2010/04/01/random-sample</a>
@param <T> type of elements in randomly selected subset
@param set set from which a random subset is to be selected
@param size desired subset size, should be a number in [0,|set|]
@param rg random generator
@throws IllegalArgumentException if an invalid subset size outside [0,|set|] is specified
@return random subset stored in a newly allocated {@link LinkedHashSet}. |
public void onCreate(Bundle savedInstanceState) {
LOGGER.debug("Executing onCreate on " + fragment);
fragment.setRetainInstance(getFragmentIf().shouldRetainInstance());
fragmentDelegatesMap = Maps.newHashMap();
for (AppModule appModule : AbstractApplication.get().getAppModules()) {
FragmentDelegate fragmentDelegate = getFragmentIf().createFragmentDelegate(appModule);
if (fragmentDelegate != null) {
fragmentDelegatesMap.put(appModule, fragmentDelegate);
fragmentDelegate.onCreate(savedInstanceState);
}
}
} | //////////////////////// Life cycle //////////////////////// // |
@Override
public void showLoading() {
final FragmentIf fragmentIf = getFragmentIf();
fragmentIf.executeOnUIThread(new Runnable() {
@Override
public void run() {
if (loading != null) {
loading.show(fragmentIf);
}
}
});
} | //////////////////////// Loading //////////////////////// // |
@Override
public void executeOnUIThread(Runnable runnable) {
Activity activity = fragment.getActivity();
if (activity != null && !activity.isDestroyed()) {
activity.runOnUiThread(new SafeExecuteWrapperRunnable(fragment, runnable));
}
} | //////////////////////// Others //////////////////////// // |
@SuppressLint("SetTextI18n")
public void setNotifications(Integer notifications) {
if ((notifications != null) && (notifications > 0)) {
setVisibility(VISIBLE);
if (notifications > maximum) {
this.setText(maximum + "+");
} else {
this.setText(notifications.toString());
}
} else {
setVisibility(GONE);
}
} | Sets a notification number in the badge.
@param notifications |
@Override
protected void searchStep() {
// use k-th neighbourhood to get a random valid move
Move<? super SolutionType> move = getNeighbourhoods().get(k).getRandomMove(getCurrentSolution(), getRandom());
// check: got move ?
if(move != null){
// check: improvement ?
if(isImprovement(move)){
// improvement: accept move and reset k
accept(move);
k = 0;
} else {
reject(move);
// no improvement: switch to next neighbourhood, if any
nextNeighbourhood();
}
} else {
// k-th neighbourhood did not produce any random move: switch to next neighbourhood, if any
nextNeighbourhood();
}
} | Samples a random neighbour of the current solution, using the k-th neighbourhood, and accepts it as the new
current solution if it is an improvement. If no improvement is found, k is increased. Upon each improvement,
k is reset to 0. If cycling is enabled (which is the default setting), k is also reset to 0 when all
neighbourhoods have been used so that the first neighbourhood will again be applied in the next step.
If cycling is disabled, the search stops if no improvement was found using the last available neighbourhood.
<p>
If the k-th neighbourhood is unable to generate any move, k is also increased to try the next neighbourhood
(if any) in the next step.
@throws JamesRuntimeException if depending on malfunctioning components (problem, neighbourhood, ...) |
private void nextNeighbourhood(){
if(cycleNeighbourhoods || k < getNeighbourhoods().size()-1){
// try again with next neighbourhood in next step
k = (k+1) % getNeighbourhoods().size();
} else {
// no next neighbourhood... stop
stop();
}
} | Switches to the next neighbourhood in the list, if any,
going back to the start if cycling is enabled and all
neighbourhoods have been used. |
public static Method getMethod(Class<?> cl, Method method) {
if (method == null) {
return null;
}
if (Modifier.isPublic(cl.getModifiers())) {
return method;
}
Class<?> [] interfaces = cl.getInterfaces ();
for (int i = 0; i < interfaces.length; i++) {
Class<?> c = interfaces[i];
Method m = null;
try {
m = c.getMethod(method.getName(), method.getParameterTypes());
c = m.getDeclaringClass();
if ((m = getMethod(c, m)) != null)
return m;
} catch (NoSuchMethodException ex) {
}
}
Class<?> c = cl.getSuperclass();
if (c != null) {
Method m = null;
try {
m = c.getMethod(method.getName(), method.getParameterTypes());
c = m.getDeclaringClass();
if ((m = getMethod(c, m)) != null)
return m;
} catch (NoSuchMethodException ex) {
}
}
return null;
} | /*
Get a public method form a public class or interface of a given method.
Note that if a PropertyDescriptor is obtained for a non-public class that
implements a public interface, the read/write methods will be for the
class, and therefore inaccessible. To correct this, a version of the
same method must be found in a superclass or interface. |
public static umich.ms.fileio.filetypes.mzidentml.jaxb.standard.MzIdentMLType parse(Path path)
throws FileParsingException {
try {
XMLStreamReader xsr = JaxbUtils.createXmlStreamReader(path, false);
umich.ms.fileio.filetypes.mzidentml.jaxb.standard.MzIdentMLType mzIdentMLType = JaxbUtils
.unmarshal(umich.ms.fileio.filetypes.mzidentml.jaxb.standard.MzIdentMLType.class, xsr);
return mzIdentMLType;
} catch (JAXBException e) {
throw new FileParsingException(
String.format("JAXB parsing of MzIdentML file failed (%s)",
path.toAbsolutePath().toString()), e);
}
} | Will parse the whole file. Might be not very efficient memory-wise.
@param path path to the file to parse
@return auto-generated representation of the file, read the MzIdentML schema for details. |
@NonNull
@MainThread
protected LiveData<ApiResponse<NetworkDataType>> loadFromNetwork() {
MutableLiveData<ApiResponse<NetworkDataType>> mutableLiveData = new MutableLiveData<>();
AppExecutors.getNetworkIOExecutor().execute(new Runnable() {
@Override
public void run() {
LOGGER.info(getTag() + ": Loading resource from network");
ApiResponse<NetworkDataType> apiResponse;
try {
apiResponse = doLoadFromNetwork();
} catch (Exception e) {
AbstractException abstractException = wrapException(e);
logHandledException(abstractException);
apiResponse = new ApiErrorResponse<>(abstractException);
}
mutableLiveData.postValue(apiResponse);
}
});
return mutableLiveData;
} | /*
Called to create the API call. |
private void iaddError(String desc, String value, String loc) {
if (!validate) return;
ValidationEvent ve = new ValidationEvent(desc, value, loc);
errors.add(ve);
correct = false;
} | Adds an error.
@param desc error description
@param value the value that caused the error
@param loc the error location |
private void iaddWarning(String desc, String value, String loc) {
if (!validate) return;
ValidationEvent ve = new ValidationEvent(desc, value, loc);
warnings.add(ve);
} | Adds a warning.
@param desc warning description
@param value the value that caused the warning
@param loc the location |
public void addError(String desc, String loc, long value) {
iaddError(desc, "" + value, loc);
} | Adds an error.
@param desc Error description
@param loc Error Location
@param value the integer value that caused the error |
public void addWarning(String desc, String value, String loc) {
iaddWarning(desc, value, loc);
} | Adds an warning.
@param desc Warning description
@param value the String that caused the warning
@param loc the location |
public void add(ValidationResult validation) {
correct &= validation.correct;
if (!validate) return;
errors.addAll(validation.errors);
warnings.addAll(validation.warnings);
} | Adds a validation result to this.
@param validation the validation to add |
public static double min(double... nums) {
double min = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > min) {
min = nums[i];
}
}
return min;
} | Find the minimum in an array of numbers. |
public void init() throws IOException {
if (!Files.exists(path)) {
throw new FileNotFoundException(
"Could not find a file under path: " + path.toAbsolutePath().toString());
}
if (Files.size(path) == 0) {
throw new IllegalStateException("File size can't be zero for chunked files");
}
chunks = chunkFile();
chunksInUse = new ConcurrentSkipListMap<>();
chunksPreRead = new ConcurrentSkipListMap<>();
chunksScheduled = new ConcurrentSkipListMap<>();
nextChunkNum = new AtomicInteger(-1);
if (raf != null) {
raf.close();
}
execIo = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
execFinalize = Executors.newSingleThreadExecutor();
} | Check if the file is still valid. |
public Object getValue(ELContext context,
Object base,
Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base.getClass().isArray()) {
context.setPropertyResolved(base, property);
int index = toInteger (property);
if (index >= 0 && index < Array.getLength(base)) {
return Array.get(base, index);
}
}
return null;
} | If the base object is a Java language array, returns the value at the
given index. The index is specified by the <code>property</code>
argument, and coerced into an integer. If the coercion could not be
performed, an <code>IllegalArgumentException</code> is thrown. If the
index is out of bounds, <code>null</code> is returned.
<p>If the base is a Java language array, the
<code>propertyResolved</code> property of the <code>ELContext</code>
object must be set to <code>true</code> by this resolver, before
returning. If this property is not <code>true</code> after this
method is called, the caller should ignore the return value.</p>
@param context The context of this evaluation.
@param base The array to analyze. Only bases that are Java language
arrays are handled by this resolver.
@param property The index of the value to be returned. Will be coerced
into an integer.
@return If the <code>propertyResolved</code> property of
<code>ELContext</code> was set to <code>true</code>, then
the value at the given index or <code>null</code>
if the index was out of bounds. Otherwise, undefined.
@throws IllegalArgumentException if the property could not be coerced
into an integer.
@throws NullPointerException if context is <code>null</code>.
@throws ELException if an exception was thrown while performing
the property or variable resolution. The thrown exception
must be included as the cause property of this exception, if
available. |
public void setValue(ELContext context,
Object base,
Object property,
Object val) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base.getClass().isArray()) {
context.setPropertyResolved(base, property);
if (isReadOnly) {
throw new PropertyNotWritableException();
}
Class<?> type = base.getClass().getComponentType();
if (val != null && !Util.isAssignableFrom(val.getClass(), type)) {
throw new ClassCastException(Util.message(context,
"objectNotAssignable", val.getClass().getName(),
type.getName()));
}
int index = toInteger (property);
if (index < 0 || index >= Array.getLength(base)) {
throw new PropertyNotFoundException();
}
Array.set(base, index, val);
}
} | If the base object is a Java language array, attempts to set the
value at the given index with the given value. The index is specified
by the <code>property</code> argument, and coerced into an integer.
If the coercion could not be performed, an
<code>IllegalArgumentException</code> is thrown. If the index is
out of bounds, a <code>PropertyNotFoundException</code> is thrown.
<p>If the base is a Java language array, the
<code>propertyResolved</code> property of the <code>ELContext</code>
object must be set to <code>true</code> by this resolver, before
returning. If this property is not <code>true</code> after this method
is called, the caller can safely assume no value was set.</p>
<p>If this resolver was constructed in read-only mode, this method will
always throw <code>PropertyNotWritableException</code>.</p>
@param context The context of this evaluation.
@param base The array to be modified. Only bases that are Java language
arrays are handled by this resolver.
@param property The index of the value to be set. Will be coerced
into an integer.
@param val The value to be set at the given index.
@throws ClassCastException if the class of the specified element
prevents it from being added to this array.
@throws NullPointerException if context is <code>null</code>.
@throws IllegalArgumentException if the property could not be coerced
into an integer, or if some aspect of the specified element
prevents it from being added to this array.
@throws PropertyNotWritableException if this resolver was constructed
in read-only mode.
@throws PropertyNotFoundException if the given index is out of
bounds for this array.
@throws ELException if an exception was thrown while performing
the property or variable resolution. The thrown exception
must be included as the cause property of this exception, if
available. |
public boolean isReadOnly(ELContext context,
Object base,
Object property) {
if (context == null) {
throw new NullPointerException();
}
if (base != null && base.getClass().isArray()) {
context.setPropertyResolved(true);
int index = toInteger (property);
if (index < 0 || index >= Array.getLength(base)) {
throw new PropertyNotFoundException();
}
}
return isReadOnly;
} | If the base object is a Java language array, returns whether a call to
{@link #setValue} will always fail.
<p>If the base is a Java language array, the
<code>propertyResolved</code> property of the <code>ELContext</code>
object must be set to <code>true</code> by this resolver, before
returning. If this property is not <code>true</code> after this method
is called, the caller should ignore the return value.</p>
<p>If this resolver was constructed in read-only mode, this method will
always return <code>true</code>. Otherwise, it returns
<code>false</code>.</p>
@param context The context of this evaluation.
@param base The array to analyze. Only bases that are a Java language
array are handled by this resolver.
@param property The index of the element in the array to return the
acceptable type for. Will be coerced into an integer, but
otherwise ignored by this resolver.
@return If the <code>propertyResolved</code> property of
<code>ELContext</code> was set to <code>true</code>, then
<code>true</code> if calling the <code>setValue</code> method
will always fail or <code>false</code> if it is possible that
such a call may succeed; otherwise undefined.
@throws PropertyNotFoundException if the given index is out of
bounds for this array.
@throws NullPointerException if context is <code>null</code>
@throws ELException if an exception was thrown while performing
the property or variable resolution. The thrown exception
must be included as the cause property of this exception, if
available. |
public Class<?> getCommonPropertyType(ELContext context,
Object base) {
if (base != null && base.getClass().isArray()) {
return Integer.class;
}
return null;
} | If the base object is a Java language array, returns the most general
type that this resolver accepts for the <code>property</code> argument.
Otherwise, returns <code>null</code>.
<p>Assuming the base is an array, this method will always return
<code>Integer.class</code>. This is because arrays accept integers
for their index.</p>
@param context The context of this evaluation.
@param base The array to analyze. Only bases that are a Java language
array are handled by this resolver.
@return <code>null</code> if base is not a Java language array;
otherwise <code>Integer.class</code>. |
public void setValue(ELContext context, Object base, Object property,
Object value) {
if (context == null) {
throw new NullPointerException();
}
if (base instanceof ResourceBundle) {
context.setPropertyResolved(true);
throw new PropertyNotWritableException(
"ResourceBundles are immutable");
}
} | If the base object is a ResourceBundle, throw a
{@link PropertyNotWritableException}.
@param context
The context of this evaluation.
@param base
The ResourceBundle to be modified. Only bases that are of type
ResourceBundle are handled.
@param property
The String property to use.
@param value
The value to be set.
@throws NullPointerException
if context is <code>null</code>.
@throws PropertyNotWritableException
Always thrown if base is an instance of ReasourceBundle. |
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
if (base instanceof ResourceBundle) {
ResourceBundle bundle = (ResourceBundle) base;
List<FeatureDescriptor> features = new ArrayList<FeatureDescriptor>();
String key = null;
FeatureDescriptor desc = null;
for (Enumeration<String> e = bundle.getKeys(); e.hasMoreElements();) {
key = e.nextElement();
desc = new FeatureDescriptor();
desc.setDisplayName(key);
desc.setExpert(false);
desc.setHidden(false);
desc.setName(key);
desc.setPreferred(true);
desc.setValue(TYPE, String.class);
desc.setValue(RESOLVABLE_AT_DESIGN_TIME, Boolean.TRUE);
features.add(desc);
}
return features.iterator();
}
return null;
} | If the base object is a ResourceBundle, returns an <code>Iterator</code>
containing the set of keys available in the <code>ResourceBundle</code>.
Otherwise, returns <code>null</code>.
<p>
The <code>Iterator</code> returned must contain zero or more instances
of {@link java.beans.FeatureDescriptor}. Each info object contains
information about a key in the ResourceBundle, and is initialized as
follows:
<dl>
<li>displayName - The <code>String</code> key
<li>name - Same as displayName property.</li>
<li>shortDescription - Empty string</li>
<li>expert - <code>false</code></li>
<li>hidden - <code>false</code></li>
<li>preferred - <code>true</code></li>
</dl>
In addition, the following named attributes must be set in the returned
<code>FeatureDescriptor</code>s:
<dl>
<li>{@link ELResolver#TYPE} - <code>String.class</code></li>
<li>{@link ELResolver#RESOLVABLE_AT_DESIGN_TIME} - <code>true</code></li>
</dl>
</p>
@param context
The context of this evaluation.
@param base
The bundle whose keys are to be iterated over. Only bases of
type <code>ResourceBundle</code> are handled by this
resolver.
@return An <code>Iterator</code> containing zero or more (possibly
infinitely more) <code>FeatureDescriptor</code> objects, each
representing a key in this bundle, or <code>null</code> if the
base object is not a ResourceBundle. |
@Override
public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) {
// get set of candidate IDs for addition (fixed IDs are discarded)
Set<Integer> addCandidates = getAddCandidates(solution);
// compute number of additions
int curNumAdd = numAdditions(addCandidates, solution);
// return null if no additions are possible
if(curNumAdd == 0){
return null;
}
// pick random IDs to add to selection
Set<Integer> add = SetUtilities.getRandomSubset(addCandidates, curNumAdd, rnd);
// create and return move
return new GeneralSubsetMove(add, Collections.emptySet());
} | Generates a move for the given subset solution that selects a random subset of currently unselected IDs.
Whenever possible, the requested number of additions is performed. However, taking into account the current
number of unselected items, the imposed maximum subset size (if set) and the fixed IDs (if any) may result in
fewer additions (as many as possible). If no items can be added, <code>null</code> is returned.
@param solution solution for which a random multi addition move is generated
@param rnd source of randomness used to generate random move
@return random multi addition move, <code>null</code> if no items can be added |
@Override
public List<SubsetMove> getAllMoves(SubsetSolution solution) {
// create empty list to store generated moves
List<SubsetMove> moves = new ArrayList<>();
// get set of candidate IDs for addition (fixed IDs are discarded)
Set<Integer> addCandidates = getAddCandidates(solution);
// compute number of additions
int curNumAdd = numAdditions(addCandidates, solution);
if(curNumAdd == 0){
// impossible: return empty set
return moves;
}
// create all moves that add curNumAdd items
Set<Integer> add;
SubsetIterator<Integer> itAdd = new SubsetIterator<>(addCandidates, curNumAdd);
while(itAdd.hasNext()){
add = itAdd.next();
// create and add move
moves.add(new GeneralSubsetMove(add, Collections.emptySet()));
}
// return all moves
return moves;
} | <p>
Generates the list of all possible moves that perform \(k\) additions, where \(k\) is the fixed number
specified at construction. Note: taking into account the current number of unselected items, the imposed
maximum subset size (if set) and the fixed IDs (if any) may result in fewer additions (as many as possible).
</p>
<p>
May return an empty list if no moves can be generated.
</p>
@param solution solution for which all possible multi addition moves are generated
@return list of all multi addition moves, may be empty |
private int numAdditions(Set<Integer> addCandidates, SubsetSolution sol){
int a = Math.min(numAdditions, Math.min(addCandidates.size(), maxSubsetSize-sol.getNumSelectedIDs()));
return Math.max(a, 0);
} | Computes the number of additions that are to be performed, given the set of add candidates
and the current subset solution. Takes into account the desired number of additions \(k\)
specified at construction, the number of currently unselected non-fixed items and the maximum
allowed subset size (if any).
@param addCandidates candidate IDs to be added to the selection
@param sol subset solution for which moves are being generated
@return number of additions to be performed |
@Override
protected void searchStep() {
// more solutions to generate ?
if(solutionIterator.hasNext()){
// generate next solution
SolutionType sol = solutionIterator.next();
// update best solution
updateBestSolution(sol);
} else {
// done
stop();
}
} | In every search step it is verified whether there are more solution to be generated using the solution iterator.
If so, the next solution is generated, evaluated, and presented for comparison with the current best solution.
Else, the search stops. |
private boolean checkBuffer(long offset) throws IOException {
if (offset - bufferOffset < 0 || offset - bufferOffset >= currentBufferSize) {
// the given offset is not contained in the buffer
bufferOffset = offset;
int index = 0;
input.seek(offset);
try {
//input.read(buffer, 0, maxBufferSize);
for (long pos = offset; pos < offset + maxBufferSize; pos++) {
int ch = input.read();
if (ch > -1) {
buffer[index] = (byte)ch;
index++;
}
}
} catch (IOException ex) {
// not possible
ex.printStackTrace();
}
currentBufferSize = index;
return true;
}
return false;
} | Checks if the given offset is already contained in the internal buffer.<br>
If not, fills the buffer starting at the given offset position.
@param offset the offset to check
@throws IOException Signals that an I/O exception has occurred. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.