code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
private void validateIfdCT(IFD ifd, int p) {
IfdTags metadata = ifd.getMetadata();
boolean rgb =
metadata.containsTagId(TiffTags.getTagId("PhotometricInterpretation"))
&& metadata.get(TiffTags.getTagId("PhotometricInterpretation")).getFirstNumericValue() == 2;
boolean lab =
metadata.containsTagId(TiffTags.getTagId("PhotometricInterpretation"))
&& metadata.get(TiffTags.getTagId("PhotometricInterpretation")).getFirstNumericValue() == 8;
int spp = -1;
if (metadata.containsTagId(TiffTags.getTagId("SamplesPerPixel"))) {
spp = (int) metadata.get(TiffTags.getTagId("SamplesPerPixel")).getFirstNumericValue();
}
int planar = 1;
if (metadata.containsTagId(TiffTags.getTagId("PlanarConfiguration"))) {
planar = (int) metadata.get(TiffTags.getTagId("PlanarConfiguration")).getFirstNumericValue();
}
int rps = -1;
if (metadata.containsTagId(TiffTags.getTagId("RowsPerStrip"))) {
rps = (int) metadata.get(TiffTags.getTagId("RowsPerStrip")).getFirstNumericValue();
}
int length = -1;
if (metadata.containsTagId(TiffTags.getTagId("ImageLength"))) {
length = (int) metadata.get(TiffTags.getTagId("ImageLength")).getFirstNumericValue();
}
int spi = Math.floorDiv(length + rps - 1, rps);
if (lab) {
} else {
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0});
}
}
checkRequiredTag(metadata, "ImageLength", 1);
checkRequiredTag(metadata, "ImageWidth", 1);
checkRequiredTag(metadata, "BitsPerSample", spp);
if (rgb || lab) {
checkRequiredTag(metadata, "BitsPerSample", 3, new long[]{8, 16});
} else {
if (p == 0) {
checkRequiredTag(metadata, "BitsPerSample", spp, new long[]{8, 16});
} else {
checkRequiredTag(metadata, "BitsPerSample", spp, new long[]{8});
}
}
if (p == 2 || rgb || lab) {
checkRequiredTag(metadata, "Compression", 1, new long[]{1,7,8});
} else if (p == 1) {
checkRequiredTag(metadata, "Compression", 1, new long[]{1});
}
if (p == 0) {
checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {2, 5, 6, 8});
if (metadata.containsTagId(TiffTags.getTagId("PhotometricInterpretation"))
&& metadata.get(TiffTags.getTagId("PhotometricInterpretation")).getFirstNumericValue() == 6
&&
metadata.get(TiffTags.getTagId("Compression")).getFirstNumericValue() != 7) {
validation.addErrorLoc("YCbCr shall be used only when compression has the value 7", "IFD"
+ currentIfd);
}
} else if (p == 1 || p == 2) {
checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {5});
}
if (planar == 1 || planar == 32768) {
checkRequiredTag(metadata, "StripOffsets", spi);
} else if (planar == 2) {
checkRequiredTag(metadata, "StripOffsets", spp * spi);
}
if (rgb || lab) {
} else if (p == 1 || p == 2) {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1});
}
if (rgb || lab) {
checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{3});
} else {
if (p == 0) {
checkRequiredTag(metadata, "SamplesPerPixel", 1);
} else if (p == 1 || p == 2) {
checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{4});
}
}
if (p == 1 || p == 2 || rgb || lab) {
if (planar == 1 || planar == 32768) {
checkRequiredTag(metadata, "StripBYTECount", spi);
} else if (planar == 2) {
checkRequiredTag(metadata, "StripBYTECount", spp * spi);
}
checkRequiredTag(metadata, "XResolution", 1);
checkRequiredTag(metadata, "YResolution", 1);
}
if (p == 0 || rgb || lab) {
checkRequiredTag(metadata, "PlanarConfiguration", 1, new long[]{1,2,32768});
} else if (p == 1 || p == 2) {
checkRequiredTag(metadata, "PlanarConfiguration", 1, new long[]{1});
}
if (rgb || lab) {
} else {
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3});
checkRequiredTag(metadata, "InkSet", 1, new long[]{1});
checkRequiredTag(metadata, "NumberOfInks", 1, new long[]{4});
checkRequiredTag(metadata, "DotRange", 2, new long[]{0, 255});
}
}
} | Validate Continuous Tone.
@param ifd the ifd
@param p the profile (default = 0, P1 = 1, P2 = 2) |
private void validateIfdLW(IFD ifd, int p) {
IfdTags metadata = ifd.getMetadata();
if (p == 1) {
checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0});
}
checkRequiredTag(metadata, "ImageLength", 1);
checkRequiredTag(metadata, "ImageWidth", 1);
checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{1});
if (p == 0) {
checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{4});
} else {
checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{8});
}
checkRequiredTag(metadata, "Compression", 1, new long[]{32896});
checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {5});
checkRequiredTag(metadata, "StripOffsets", 1);
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1});
}
checkRequiredTag(metadata, "StripBYTECount", 1);
checkRequiredTag(metadata, "XResolution", 1);
checkRequiredTag(metadata, "YResolution", 1);
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3});
checkRequiredTag(metadata, "InkSet", 1, new long[]{1});
checkRequiredTag(metadata, "NumberOfInks", 1, new long[]{4});
}
if (p == 1) {
checkRequiredTag(metadata, "DotRange", 2, new long[]{0, 255});
}
checkRequiredTag(metadata, "ColorTable", -1);
} | Validate Line Work.
@param ifd the ifd
@param p the profile (default = 0, P1 = 1, P2 = 2) |
private void validateIfdHC(IFD ifd, int p) {
IfdTags metadata = ifd.getMetadata();
int spp = -1;
if (metadata.containsTagId(TiffTags.getTagId("SampesPerPixel"))) {
spp = (int)metadata.get(TiffTags.getTagId("SampesPerPixel")).getFirstNumericValue();
}
if (p == 1) {
checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0});
}
checkRequiredTag(metadata, "ImageLength", 1);
checkRequiredTag(metadata, "ImageWidth", 1);
checkRequiredTag(metadata, "BitsPerSample", spp);
if (p == 1) {
checkRequiredTag(metadata, "BitsPerSample", 4, new long[]{8});
}
checkRequiredTag(metadata, "Compression", 1, new long[]{32897});
checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {5});
checkRequiredTag(metadata, "StripOffsets", 1);
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1});
}
if (p == 1) {
checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{4});
}
checkRequiredTag(metadata, "StripBYTECount", 1);
checkRequiredTag(metadata, "XResolution", 1);
checkRequiredTag(metadata, "YResolution", 1);
checkRequiredTag(metadata, "PlanarConfiguration", 1, new long[]{1});
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3});
checkRequiredTag(metadata, "InkSet", 1, new long[]{1});
checkRequiredTag(metadata, "NumberOfInks", 1, new long[]{4});
checkRequiredTag(metadata, "DotRange", 2, new long[]{0, 255});
}
checkRequiredTag(metadata, "TransparencyIndicator", 1, new long[]{0, 1});
} | Validate High-Resolution Continuous-Tone.
@param ifd the ifd
@param p the profile (default = 0, P1 = 1, P2 = 2) |
private void validateIfdMP(IFD ifd, int p) {
IfdTags metadata = ifd.getMetadata();
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0});
}
checkRequiredTag(metadata, "ImageLength", 1);
checkRequiredTag(metadata, "ImageWidth", 1);
if (p == 1) {
checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{8, 16});
} else {
checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{8});
}
if (p == 0) {
checkRequiredTag(metadata, "Compression", 1, new long[]{1,7,8,32895});
} else if (p == 1) {
checkRequiredTag(metadata, "Compression", 1, new long[]{1});
} else {
checkRequiredTag(metadata, "Compression", 1, new long[]{1,7,8});
}
if (p == 0) {
checkRequiredTag(metadata, "PhotometricInterpretation", 1);
} else {
checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0});
}
checkRequiredTag(metadata, "StripOffsets", 1);
if (p == 0) {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1,4,5,8});
} else {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1});
}
if (p == 1) {
checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{1});
}
checkRequiredTag(metadata, "StripBYTECount", 1);
checkRequiredTag(metadata, "XResolution", 1);
checkRequiredTag(metadata, "YResolution", 1);
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3});
checkRequiredTag(metadata, "DotRange", 2, new long[]{0, 255});
checkRequiredTag(metadata, "PixelIntensityRange", 2, new long[]{0, 255});
}
checkRequiredTag(metadata, "ImageColorIndicator", 1, new long[]{0, 1});
} | Validate Monochrome Picture.
@param ifd the ifd
@param p the profile (default = 0, P1 = 1, P2 = 2) |
private void validateIfdBP(IFD ifd, int p) {
IfdTags metadata = ifd.getMetadata();
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0});
}
checkRequiredTag(metadata, "ImageLength", 1);
checkRequiredTag(metadata, "ImageWidth", 1);
checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{1});
if (p == 0) {
checkRequiredTag(metadata, "Compression", 1, new long[]{1,4,8});
} else if (p == 1) {
checkRequiredTag(metadata, "Compression", 1, new long[]{1});
} else {
checkRequiredTag(metadata, "Compression", 1, new long[]{1,4,8});
}
if (p == 0) {
checkRequiredTag(metadata, "PhotometricInterpretation", 1);
} else {
checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0});
}
checkRequiredTag(metadata, "StripOffsets", 1);
if (p == 0) {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1,4,5,8});
} else {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1});
}
checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{1});
checkRequiredTag(metadata, "StripBYTECount", 1);
checkRequiredTag(metadata, "XResolution", 1);
checkRequiredTag(metadata, "YResolution", 1);
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3});
checkRequiredTag(metadata, "DotRange", 2, new long[]{0, 255});
}
checkRequiredTag(metadata, "ImageColorIndicator", 1, new long[]{0, 1, 2});
checkRequiredTag(metadata, "BackgroundColorIndicator", 1, new long[]{0, 1, 2});
} | Validate Binary Picture.
@param ifd the ifd
@param p the profile (default = 0, P1 = 1, P2 = 2) |
private void validateIfdBL(IFD ifd, int p) {
IfdTags metadata = ifd.getMetadata();
if (p == 1) {
checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0});
}
checkRequiredTag(metadata, "ImageLength", 1);
checkRequiredTag(metadata, "ImageWidth", 1);
checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{1});
checkRequiredTag(metadata, "Compression", 1, new long[]{32898});
if (p == 0) {
checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0, 1});
} else {
checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0});
}
checkRequiredTag(metadata, "StripOffsets", 1);
if (p == 0) {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1,4,5,8});
} else {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1});
}
checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{1});
checkRequiredTag(metadata, "StripBYTECount", 1);
checkRequiredTag(metadata, "XResolution", 1);
checkRequiredTag(metadata, "YResolution", 1);
if (p == 1) {
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3});
checkRequiredTag(metadata, "DotRange", 2, new long[]{0, 255});
}
checkRequiredTag(metadata, "ImageColorIndicator", 1, new long[]{0, 1, 2});
checkRequiredTag(metadata, "BackgroundColorIndicator", 1, new long[]{0, 1, 2});
} | Validate Binary Lineart.
@param ifd the ifd
@param p the profile (default = 0, P1 = 1) |
private void validateIfdSD(IFD ifd, int p) {
IfdTags metadata = ifd.getMetadata();
if (p == 2) {
checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0});
}
checkRequiredTag(metadata, "ImageLength", 1);
checkRequiredTag(metadata, "ImageWidth", 1);
checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{1});
checkRequiredTag(metadata, "Compression", 1, new long[]{1,4,8});
checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {5});
checkRequiredTag(metadata, "StripOffsets", 1);
if (p == 0) {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1,4,5,8});
} else {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1});
}
if (p == 2) {
checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{1,4});
}
checkRequiredTag(metadata, "StripBYTECount", 1);
checkRequiredTag(metadata, "XResolution", 1);
checkRequiredTag(metadata, "YResolution", 1);
checkRequiredTag(metadata, "PlanarConfiguration", 1, new long[]{2});
if (p == 2) {
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3});
checkRequiredTag(metadata, "NumberOfInks", 1, new long[]{4});
}
checkRequiredTag(metadata, "InkSet", 1, new long[]{1});
checkRequiredTag(metadata, "BackgroundColorIndicator", 1, new long[]{0, 1, 2});
} | Validate Screened Data image.
@param ifd the ifd
@param p the profile (default = 0, P2 = 2) |
private void validateIfdFP(IFD ifd, int p) {
IfdTags metadata = ifd.getMetadata();
checkRequiredTag(metadata, "ImageDescription", 1);
checkRequiredTag(metadata, "StripOffsets", 1);
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "StripOffsets", 1, new long[]{0});
}
checkRequiredTag(metadata, "NewSubfileType", 1);
checkRequiredTag(metadata, "ImageLength", 1);
checkRequiredTag(metadata, "ImageWidth", 1);
checkRequiredTag(metadata, "StripOffsets", 1);
if (p == 0) {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1,4,5,8});
} else {
checkRequiredTag(metadata, "Orientation", 1, new long[]{1});
}
checkRequiredTag(metadata, "StripBYTECount", 1);
checkRequiredTag(metadata, "XResolution", 1);
checkRequiredTag(metadata, "YResolution", 1);
checkRequiredTag(metadata, "PlanarConfiguration", 1, new long[]{2});
if (p == 1 || p == 2) {
checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3});
checkRequiredTag(metadata, "NumberOfInks", 1, new long[]{4});
}
} | Validate Final Page.
@param ifd the ifd
@param p the profile (default = 0, P1 = 1, P2 = 2) |
private boolean checkRequiredTag(IfdTags metadata, String tagName, int cardinality,
long[] possibleValues) {
boolean ok = true;
int tagid = TiffTags.getTagId(tagName);
if (!metadata.containsTagId(tagid)) {
validation.addErrorLoc("Missing required tag for TiffIT" + profile + " " + tagName, "IFD"
+ currentIfd);
ok = false;
} else if (cardinality != -1 && metadata.get(tagid).getCardinality() != cardinality) {
validation.addError("Invalid cardinality for TiffIT" + profile + " tag " + tagName, "IFD"
+ currentIfd,
metadata.get(tagid)
.getCardinality());
} else if (cardinality == 1 && possibleValues != null) {
long val = metadata.get(tagid).getFirstNumericValue();
boolean contained = false;
int i = 0;
while (i < possibleValues.length && !contained) {
contained = possibleValues[i] == val;
i++;
}
if (!contained)
validation.addError("Invalid value for TiffIT" + profile + " tag " + tagName, "IFD"
+ currentIfd, val);
}
return ok;
} | Check required tag is present, and its cardinality and value is correct.
@param metadata the metadata
@param tagName the name of the mandatory tag
@param cardinality the mandatory cardinality
@param possibleValues the possible tag values
@return true, if tag is found |
private boolean checkRequiredTag(IfdTags metadata, String tagName, int cardinality) {
return checkRequiredTag(metadata, tagName, cardinality, null);
} | Check a required tag is present.
@param metadata the metadata
@param tagName the name of the mandatory tag
@param cardinality the mandatory cardinality
@return true, if tag is present |
public void importStatic(String name) throws ELException {
int i = name.lastIndexOf('.');
if (i <= 0) {
throw new ELException(
"The name " + name + " is not a full static member name");
}
String memberName = name.substring(i+1);
String className = name.substring(0, i);
staticNameMap.put(memberName, className);
} | Import a static field or method.
@param name The static member name, including the full class name,
to be imported
@throws ELException if the name does not include a ".". |
public void importClass(String name) throws ELException {
int i = name.lastIndexOf('.');
if (i <= 0) {
throw new ELException(
"The name " + name + " is not a full class name");
}
String className = name.substring(i+1);
classNameMap.put(className, name);
} | Import a class.
@param name The full class name of the class to be imported
@throws ELException if the name does not include a ".". |
public Class<?> resolveClass(String name) {
String className = classNameMap.get(name);
if (className != null) {
return resolveClassFor(className);
}
for (String packageName: packages) {
String fullClassName = packageName + "." + name;
Class<?>c = resolveClassFor(fullClassName);
if (c != null) {
classNameMap.put(name, fullClassName);
return c;
}
}
return null;
} | Resolve a class name.
@param name The name of the class (without package name) to be resolved.
@return If the class has been imported previously, with
{@link #importClass} or {@link #importPackage}, then its
Class instance. Otherwise <code>null</code>.
@throws ELException if the class is abstract or is an interface, or
not public. |
public Class<?> resolveStatic(String name) {
String className = staticNameMap.get(name);
if (className != null) {
Class<?> c = resolveClassFor(className);
if (c != null) {
return c;
}
}
return null;
} | Resolve a static field or method name.
@param name The name of the member(without package and class name)
to be resolved.
@return If the field or method has been imported previously, with
{@link #importStatic}, then the class object representing the class that
declares the static field or method.
Otherwise <code>null</code>.
@throws ELException if the class is not public, or is abstract or
is an interface. |
public static void finalizeScanCollection(IScanCollection scans) throws FileParsingException {
// check if there is more than one MS level, otherwise there are no relationships to set up
if (scans.getMapMsLevel2index().size() < 2) {
return;
}
int msLevelLo = scans.getMapMsLevel2index().firstKey();
int msLevelHi = scans.getMapMsLevel2index().lastKey();
int scanNumLo = scans.getMapNum2scan().firstKey();
int scanNumHi = scans.getMapNum2scan().lastKey();
Set<Map.Entry<Integer, ScanIndex>> entries = scans.getMapMsLevel2index().entrySet();
Set<Integer> msLevels = scans.getMapMsLevel2index().keySet();
Integer[] msLevelsArr = msLevels.toArray(new Integer[msLevels.size()]);
Arrays.sort(msLevelsArr);
for (int i = 0; i < msLevelsArr.length - 1; i++) {
// if we're at the bottom MS level, these Scans can't have children, stop processing,
// hence i < msLevelsArr.length - 1 in the for loop
int msLevel = msLevelsArr[i];
int msLevelNext = msLevelsArr[i + 1];
TreeMap<Integer, IScan> num2scan = scans.getMapMsLevel2index().get(msLevel).getNum2scan();
for (Map.Entry<Integer, IScan> kv : num2scan.entrySet()) {
int curScanNum = kv.getKey();
IScan curScan = kv.getValue();
IScan nextScan = scans.getNextScanAtSameMsLevel(curScan);
Integer nextScanNumGuess = null;
if (nextScan != null) {
nextScanNumGuess = nextScan.getNum();
} else {
int lastScanNumAtNextMsLevel = scans.getMapMsLevel2index().get(msLevelNext).getNum2scan()
.lastKey();
if (lastScanNumAtNextMsLevel > curScanNum) {
nextScanNumGuess = lastScanNumAtNextMsLevel;
}
}
if (nextScanNumGuess == null) {
continue;
}
NavigableMap<Integer, IScan> childScansGuess =
scans.getScansByNumSpanAtMsLevel(curScanNum, nextScanNumGuess, msLevelNext);
if (childScansGuess == null) {
// there were no children found for this parent scan, so just leave it as is
// with NULL instead of children List
continue;
} else {
curScan.setChildScans(new ArrayList<Integer>(childScansGuess.size()));
}
for (Map.Entry<Integer, IScan> childNum2scan : childScansGuess.entrySet()) {
int childNum = childNum2scan.getKey();
IScan childScan = childNum2scan.getValue();
curScan.getChildScans().add(childScan.getNum());
PrecursorInfo precursor = childScan.getPrecursor();
if (precursor != null) {
Integer thisMsLevel = curScan.getMsLevel();
Integer chldMsLevel = childScan.getMsLevel();
if (precursor.getParentScanNum() == null && thisMsLevel != null && chldMsLevel != null
&& thisMsLevel + 1 == chldMsLevel) {
Double pLo = precursor.getMzRangeStart();
Double pHi = precursor.getMzRangeEnd();
Double sLo = curScan.getScanMzWindowLower();
Double sHi = curScan.getScanMzWindowUpper();
if (pLo != null && pHi != null && sLo != null && sHi != null) {
// if we know precursor isolation window and the scan's m/z scan range
// they must overlap
if (pLo <= sHi && sLo <= pHi) {
// they overlap!
if (pLo.equals(pHi)) { // it's a single point
precursor.setParentScanNum(curScanNum);
} else {
final double minOverlap = 0.75;
double overlap = Math.min(pHi, sHi) - Math.max(pLo, sLo);
precursor.setParentScanNum(curScanNum);
}
}
} else {
// otherwise blindly add it
precursor.setParentScanNum(curScanNum);
}
}
// this else condition seems to not hold when some scans were cut out from mzXML file with ProteoWizrd.
// E.g. when only MS2 scans are kept and all MS1 scans were removed, then the precursor info still
// has that link to MS1 scan, but the scan itself is not in the file, thus the inferred value is incorrect.
// else {
// // well this is weird, should never happen:
// // the Scan contained PrecursorInfo, but the number was different from the inferred one:
// // inference is done by selecting the first MS1 scan that is BEFORE this MSn scan
// throw new FileParsingException(String.format("When trying to set parent for Scan #%d, "+
// "the Scan contained PrecursorInfo, but the number was different from the inferred one.\n", childNum));
// }
} else {
// this should never happen, precursorInfo should be parsed from mzXML in the first place
throw new FileParsingException(
String.format("When trying to set parent for Scan #%d, " +
"the precursor (PrecursorInfo) field was null, which should not happen.\n",
childNum));
}
}
}
}
} | Sets relationships between parent/child scans based on scan numbering. If scan number P1 is
followed by a scan C1 with higher MS level, C1 is considered a child of P1. |
public static void finalizePrecursorWindows(IScanCollection scans) {
TreeMap<Integer, IntervalST<Double, TreeMap<Integer, IScan>>> mapMsLevel2rangeGroups = scans
.getMapMsLevel2rangeGroups();
List<Integer> msLevelsToRemove = new ArrayList<>();
msLevelLoop:
for (Map.Entry<Integer, IntervalST<Double, TreeMap<Integer, IScan>>> entry : mapMsLevel2rangeGroups
.entrySet()) {
int msLevel = entry.getKey();
IntervalST<Double, TreeMap<Integer, IScan>> rangeMapMS2 = entry.getValue();
if (rangeMapMS2.size() == 1) {
msLevelsToRemove.add(msLevel);
} else {
// if we have a precursor range map, we want to see if it actually contains
// ranges that have lots of MS2 spectra in them.
// ALL ranges are required to have more than 1 MS2 spectra
for (IntervalST.Node<Double, TreeMap<Integer, IScan>> node : rangeMapMS2) {
if (node.getValue().size() <= 1) {
// if we didn't have at least 1 scans in even one range, then discard the whole sub-tree
msLevelsToRemove.add(msLevel);
continue msLevelLoop;
}
}
// we also check that all ranges contain approximately equal amount of scans
// THIS WILL NOT WORK FOR MSX DATA, UNLESS "maxScanCountDiff" is set to some large value, which
// should be at least [ms1_mz_range / (msx_isolation_width * msx_multiplex_number)]
if (!isAllRangesHaveApproxSameScanCounts(rangeMapMS2)) {
msLevelsToRemove.add(msLevel);
continue msLevelLoop;
}
// otherwise we just keep it there, but the tree needs to be recreated, because the ranges are incorrect
}
}
for (Integer msLevel : msLevelsToRemove) {
mapMsLevel2rangeGroups.remove(msLevel);
}
} | Calling this method only makes sense if the whole LC/MS structure has been parsed.
@param scans the scan collection, it will be modified in-place |
private synchronized static <T> JAXBContext getContext(Class<T> type) throws JAXBException {
final SoftReference<Cache> existingCacheRef = CACHE;
if (existingCacheRef != null) {
Cache existingCache = existingCacheRef.get();
if (existingCache != null && existingCache.type == type) {
return existingCache.context;
}
}
// overwrite the cache
Cache newCache = new Cache(type);
CACHE = new SoftReference<Cache>(newCache);
return newCache.context;
} | Obtains the {@link JAXBContext} from the given type, by using the cache if possible.
<p>
The original code in {@link JAXB} class claimed that {@code volatile} on the {@code
WeakReference} variable that they stored the cache in was enough to provide thread safety, but
I don't think so as the reference itself, inside the {@code WeakReference} wrapper isn't
volatile.
<p>
My improvement |
public static XMLStreamReader createXmlStreamReader(Path path, boolean namespaceAware)
throws JAXBException {
XMLInputFactory xif = getXmlInputFactory(namespaceAware);
XMLStreamReader xsr = null;
try {
xsr = xif.createXMLStreamReader(new StreamSource(path.toFile()));
} catch (XMLStreamException e) {
throw new JAXBException(e);
}
return xsr;
} | Creates an XMLStreamReader based on a file path.
@param path the path to the file to be parsed
@param namespaceAware if {@code false} the XMLStreamReader will remove all namespaces from all
XML elements
@return platform-specific XMLStreamReader implementation
@throws JAXBException if the XMLStreamReader could not be created |
public static XMLStreamReader createXmlStreamReader(InputStream is, boolean namespaceAware)
throws JAXBException {
XMLInputFactory xif = getXmlInputFactory(namespaceAware);
XMLStreamReader xsr = null;
try {
xsr = xif.createXMLStreamReader(is);
} catch (XMLStreamException e) {
throw new JAXBException(e);
}
return xsr;
} | Creates an XMLStreamReader based on an input stream.
@param is the input stream from which the data to be parsed will be taken
@param namespaceAware if {@code false} the XMLStreamReader will remove all namespaces from all
XML elements
@return platform-specific XMLStreamReader implementation
@throws JAXBException if the XMLStreamReader could not be created |
public static XMLStreamReader createXmlStreamReader(Reader reader, boolean namespaceAware)
throws JAXBException {
XMLInputFactory xif = getXmlInputFactory(namespaceAware);
XMLStreamReader xsr = null;
try {
xsr = xif.createXMLStreamReader(reader);
} catch (XMLStreamException e) {
throw new JAXBException(e);
}
return xsr;
} | Creates an XMLStreamReader based on a Reader.
@param reader Note that XMLStreamReader, despite the name, does not implement the Reader
interface!
@param namespaceAware if {@code false} the XMLStreamReader will remove all namespaces from all
XML elements
@return platform-specific XMLStreamReader implementation
@throws JAXBException if the XMLStreamReader could not be created |
public static <T> T unmarshal(Class<T> cl, String s) throws JAXBException {
return unmarshal(cl, new StringReader(s));
} | Convert a string to an object of a given class.
@param cl Type of object
@param s Input string
@return Object of the given type |
public static <T> T unmarshal(Class<T> cl, File f) throws JAXBException {
return unmarshal(cl, new StreamSource(f));
} | Convert the contents of a file to an object of a given class.
@param cl Type of object
@param f File to be read
@return Object of the given type |
public static <T> T unmarshal(Class<T> cl, Reader r) throws JAXBException {
return unmarshal(cl, new StreamSource(r));
} | Convert the contents of a Reader to an object of a given class.
@param cl Type of object
@param r Reader to be read
@return Object of the given type |
public static <T> T unmarshal(Class<T> cl, InputStream s) throws JAXBException {
return unmarshal(cl, new StreamSource(s));
} | Convert the contents of an InputStream to an object of a given class.
@param cl Type of object
@param s InputStream to be read
@return Object of the given type |
public static <T> T unmarshal(Class<T> cl, Source s) throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(cl);
Unmarshaller u = ctx.createUnmarshaller();
return u.unmarshal(s, cl).getValue();
} | Convert the contents of a Source to an object of a given class.
@param cl Type of object
@param s Source to be used
@return Object of the given type |
public static <T> List<T> unmarshalCollection(Class<T> cl, String s) throws JAXBException {
return unmarshalCollection(cl, new StringReader(s));
} | Converts the contents of the string to a List with objects of the given class.
@param cl Type to be used
@param s Input string
@return List with objects of the given type |
public static <T> List<T> unmarshalCollection(Class<T> cl, Reader r) throws JAXBException {
return unmarshalCollection(cl, new StreamSource(r));
} | Converts the contents of the Reader to a List with objects of the given class.
@param cl Type to be used
@param r Input
@return List with objects of the given type |
public static <T> List<T> unmarshalCollection(Class<T> cl, InputStream s) throws JAXBException {
return unmarshalCollection(cl, new StreamSource(s));
} | Converts the contents of the InputStream to a List with objects of the given class.
@param cl Type to be used
@param s Input
@return List with objects of the given type |
public static <T> List<T> unmarshalCollection(Class<T> cl, Source s) throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(JAXBCollection.class, cl);
Unmarshaller u = ctx.createUnmarshaller();
JAXBCollection<T> collection = u.unmarshal(s, JAXBCollection.class).getValue();
return collection.getItems();
} | Converts the contents of the Source to a List with objects of the given class.
@param cl Type to be used
@param s Input
@return List with objects of the given type |
public static <T> String marshal(T obj) throws JAXBException {
StringWriter sw = new StringWriter();
marshal(obj, sw);
return sw.toString();
} | Convert an object to a string.
@param obj Object that needs to be serialized / marshalled.
@return String representation of obj |
public static <T> void marshal(T obj, Writer wr) throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
Marshaller m = ctx.createMarshaller();
m.marshal(obj, wr);
} | Convert an object to a string and send it to a Writer.
@param obj Object that needs to be serialized / marshalled
@param wr Writer used for outputting the marshalled object |
public static <T> void marshal(T obj, File f) throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
Marshaller m = ctx.createMarshaller();
m.marshal(obj, f);
} | Convert an object to a string and save it to a File.
@param obj Object that needs to be serialized / marshalled
@param f Save file |
public static <T> void marshal(T obj, OutputStream s) throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
Marshaller m = ctx.createMarshaller();
m.marshal(obj, s);
} | Convert an object to a string and send it to an OutputStream.
@param obj Object that needs to be serialized / marshalled
@param s Stream used for output |
public static <T> String marshal(String rootName, Collection<T> c) throws JAXBException {
StringWriter sw = new StringWriter();
marshal(rootName, c, sw);
return sw.toString();
} | Convert a collection to a string.
@param rootName Name of the XML root element
@param c Collection that needs to be marshalled
@return String representation of the collection |
public static <T> void marshal(String rootName, Collection<T> c, Writer w) throws JAXBException {
// Create context with generic type
JAXBContext ctx = JAXBContext.newInstance(findTypes(c));
Marshaller m = ctx.createMarshaller();
// Create wrapper collection
JAXBElement element = createCollectionElement(rootName, c);
m.marshal(element, w);
} | Convert a collection to a string and sends it to the Writer.
@param rootName Name of the XML root element
@param c Collection that needs to be marshalled
@param w Output |
protected static <T> Class[] findTypes(Collection<T> c) {
Set<Class> types = new HashSet<>();
types.add(JAXBCollection.class);
for (T o : c) {
if (o != null) {
types.add(o.getClass());
}
}
return types.toArray(new Class[0]);
} | Discovers all the classes in the given Collection. These need to be in the JAXBContext if you
want to marshal those objects. Unfortunatly there's no way of getting the generic type at
runtime.
@param c Collection that needs to be scanned
@return Classes found in the collection, including JAXBCollection. |
protected static <T> JAXBElement createCollectionElement(String rootName, Collection<T> c) {
JAXBCollection collection = new JAXBCollection(c);
return new JAXBElement<>(new QName(rootName), JAXBCollection.class, collection);
} | Create a JAXBElement containing a JAXBCollection. Needed for marshalling a generic collection
without a seperate wrapper class.
@param rootName Name of the XML root element
@return JAXBElement containing the given Collection, wrapped in a JAXBCollection. |
protected Column getColumn(String name) {
for (Column column : getColumns()) {
if (column.getColumnName().equals(name)) {
return column;
}
}
return null;
} | Find for the column associated with the given name.
@param name column name.
@return return the column if exits, otherwise returns null. |
public void replaceStringChildren(List<String> strings, String parentId) {
ArrayList<StringEntity> entities = new ArrayList<>();
for (String string : strings) {
if (string != null) {
StringEntity entity = new StringEntity();
entity.setParentId(parentId);
entity.setValue(string);
entities.add(entity);
}
}
replaceChildren(entities, parentId);
} | This method allows to replace all string children of a given parent, it will remove any children which are not in
the list, add the new ones and update which are in the list.
@param strings string children list to replace.
@param parentId id of parent entity. |
public void replaceStringChildren(List<String> strings) {
ArrayList<StringEntity> entities = new ArrayList<>();
for (String string : strings) {
StringEntity entity = new StringEntity();
entity.setValue(string);
entities.add(entity);
}
replaceAll(entities);
} | This method allows to replace all string children, it will remove any children which are not in the list, add the
new ones and update which are in the list.
@param strings string children list to replace. |
public List<String> getStringChildren(Long parentId) {
ArrayList<String> strings = new ArrayList<>();
List<StringEntity> entities = getByField(Column.PARENT_ID, parentId);
for (StringEntity entity : entities) {
strings.add(entity.getValue());
}
return strings;
} | This method returns the list of strings associated with given parent id.
@param parentId of parent entity.
@return list of strings |
public List<String> getAllString() {
ArrayList<String> strings = new ArrayList<>();
List<StringEntity> entities = getAll();
for (StringEntity entity : entities) {
strings.add(entity.getValue());
}
return strings;
} | Returns all strings.
@return list of strings |
public double overlapAbsolute(DoubleRange other) {
if (!intersects(other)) {
return 0;
}
int loCmp = lo.compareTo(other.lo);
int hiCmp = hi.compareTo(other.hi);
if (loCmp >= 0 && hiCmp <= 0) {
return this.length();
} else if (loCmp <= 0 && hiCmp >= 0) {
return other.length();
} else {
double newLo = (loCmp >= 0) ? this.lo : other.lo;
double newHi = (hiCmp <= 0) ? this.hi : other.hi;
return newHi - newLo;
}
} | If the interval contains just a single point (i.e. this.lo == this.hi), then the overlap is 0.
Consider using {@link #overlapRelative(DoubleRange)}.
@param other interval to compare to
@return 0 if one of the intervals is a single point |
public double overlapRelative(DoubleRange other) {
double lenThis = length();
double lenOther = other.length();
if (lenThis == 0 && lenOther == 0) {
// check for single points being compared, if it's the same point overlap is 1
// if points are different, overlap is 0
return this.equals(other) ? 1 : 0;
}
double overlapAbs = overlapAbsolute(other);
return overlapAbs / Math
.max(lenThis, lenOther); // one of the lengths is guaranteed to be non-zero
} | Relative overlap, that is the overlap, divided by the length of the largest interval. If both
intervals are single points and they're equal - returns 1
@param other interval to compare to
@return if the intervals are single points will return 1, if the points are the same. If a
point is compared against a non-point interval, then the result is zero. |
public void addSearch(Search<SolutionType> search) {
// synchronize with status updates
synchronized (getStatusLock()) {
// assert idle
assertIdle("Cannot add search to basic parallel search algorithm.");
if (search.getProblem().equals(getProblem())) {
// listen to events fired by subsearch
search.addSearchListener(subsearchListener);
// add search
searches.add(search);
} else {
throw new SearchException("Cannot add search " + search + " to basic parallel search algorithm " + this
+ " (does not solve the same problem).");
}
}
} | <p>
Add the given search, to be executed in parallel with the other searches. Only searches that solve
the same problem as the one specified when creating the parallel search can be added. An exception
will be thrown when attempting to add a search that solves a different problem. Note that this
method may only be called when the search is idle.
</p>
<p>
Because searches are executed in separate threads, it is important to ensure that any shared objects
(problem, objective, constraints, neighbourhood, ...) are thread-safe.
</p>
@param search search to add for parallel execution
@throws SearchException if the parallel search is not idle, or if the given search does not solve
the same problem as the parallel search |
public boolean removeSearch(Search<SolutionType> search) {
// synchronize with status updates
synchronized (getStatusLock()) {
// assert idle
assertIdle("Cannot remove search from basic parallel search algorithm.");
// check if search was added
if(searches.contains(search)){
// remove search
searches.remove(search);
// stop listening to events fired by this search
search.removeSearchListener(subsearchListener);
}
return false;
}
} | Remove the given search. If the search was never added, <code>false</code> is returned.
Note that this method may only be called when the search is idle.
@param search search to be removed from parallel algorithm
@return <code>true</code> if search is successfully removed
@throws SearchException if the search is not idle |
@Override
public void init() {
// init super
super.init();
// check: at least one search added
if (searches.isEmpty()) {
throw new SearchException("Cannot initialize basic parallel search: "
+ "no subsearches added for concurrent execution.");
}
// initialize subsearches
searches.parallelStream().forEach(Search::init);
} | When the search is initialized, it is verified whether at least one subsearch
has been added and all subsearches are initialized as well (in parallel).
An exception is thrown if no subsearches have been added.
@throws SearchException if no searches have been added |
@Override
protected void searchDisposed() {
// release thread pool
pool.shutdown();
// dispose contained searches
searches.forEach(s -> s.dispose());
// dispose super
super.searchDisposed();
} | When disposing a basic parallel search, each of the searches that have been added to the parallel
algorithm are disposed and the thread pool used for concurrent search execution is released. |
@Override
protected void searchStep() {
// (1) execute subsearches in parallel
searches.forEach(s -> futures.add(pool.submit(s)));
// (2) wait for termination of subsearches
while (!futures.isEmpty()) {
try {
futures.poll().get();
} catch (InterruptedException | ExecutionException ex) {
throw new SearchException("An error occured during concurrent execution of searches "
+ "in basic parallel search.", ex);
}
}
// (3) stop main search
stop();
} | This algorithm consists of a single search step only, in which (1) the contained subsearches are executed in
parallel, (2) the main search waits until they terminate and (3) the main search stops. A subsearch may terminate
because it has come to its natural end, because it has active stop criteria or because the main search was
requested to stop and propagated this request to the subsearches. |
@Override
public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) {
// get set of candidate IDs for deletion (fixed IDs are discarded)
Set<Integer> delCandidates = getRemoveCandidates(solution);
// compute number of deletions
int curNumDel = numDeletions(delCandidates, solution);
// return null if no removals are possible
if(curNumDel == 0){
return null;
}
// pick random IDs to remove from selection
Set<Integer> del = SetUtilities.getRandomSubset(delCandidates, curNumDel, rnd);
// create and return move
return new GeneralSubsetMove(Collections.emptySet(), del);
} | Generates a move for the given subset solution that deselects a random subset of currently selected IDs.
Whenever possible, the requested number of deletions is performed. However, taking into account the current
number of selected items, the imposed minimum subset size (if set) and the fixed IDs (if any) may result in
fewer deletions (as many as possible). If no items can be removed, <code>null</code> is returned.
@param solution solution for which a random multi deletion move is generated
@param rnd source of randomness used to generate random move
@return random multi deletion move, <code>null</code> if no items can be removed |
@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 removal (fixed IDs are discarded)
Set<Integer> delCandidates = getRemoveCandidates(solution);
// compute number of deletions
int curNumDel = numDeletions(delCandidates, solution);
if(curNumDel == 0){
// impossible: return empty set
return moves;
}
// create all moves that remove curNumDel items
Set<Integer> del;
SubsetIterator<Integer> itDel = new SubsetIterator<>(delCandidates, curNumDel);
while(itDel.hasNext()){
del = itDel.next();
// create and add move
moves.add(new GeneralSubsetMove(Collections.emptySet(), del));
}
// return all moves
return moves;
} | <p>
Generates the list of all possible moves that perform \(k\) deletions, where \(k\) is the fixed number
specified at construction. Note: taking into account the current number of selected items, the imposed
minimum subset size (if set) and the fixed IDs (if any) may result in fewer deletions (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 deletion moves are generated
@return list of all multi deletion moves, may be empty |
private int numDeletions(Set<Integer> remCandidates, SubsetSolution sol){
int d = Math.min(numDeletions, Math.min(remCandidates.size(), sol.getNumSelectedIDs()-minSubsetSize));
return Math.max(d, 0);
} | Computes the number of deletions that are to be performed, given the set of remove candidates
and the current subset solution. Takes into account the desired number of deletions \(k\)
specified at construction, the number of currently selected non-fixed items and the minimum
allowed subset size (if any).
@param remCandidates candidate IDs to be removed from the selection
@param sol subset solution for which moves are being generated
@return number of deletions to be performed |
public IScan add(IScan scan) {
int num = scan.getNum();
IScan oldScan = getNum2scan().put(num, scan);
log.trace("Adding scan #{} to ScanIndex. num2scan map already contained a scan for scanNum: {}",
num, num);
final Double rt = scan.getRt();
final TreeMap<Double, List<IScan>> rt2scan = getRt2scan();
if (scan.getRt() != null) {
List<IScan> scans = rt2scan.get(rt);
if (scans == null) {
// no entries for this RT yet
scans = new ArrayList<>(1);
scans.add(scan);
getRt2scan().put(rt, scans);
} else {
// check if this scan was in the list
boolean replaced = false;
for (int i = 0; i < scans.size(); i++) {
IScan s = scans.get(i);
if (s.getNum() == scan.getNum()) {
scans.set(i, scan);
replaced = true;
break;
}
}
if (!replaced) {
scans.add(scan);
}
}
} else {
log.debug("Adding scan # to ScanIndex. No RT.", num);
}
return oldScan;
} | Adds a scan to the index. If the scan has RT set to non-null, will also add it to RT index. If
a scan with the same scan number was already in the index, then it will get replaced.
@return if a scan with the same scan number was already in the index, then it will be returned. |
public static CompilationUnit parse(InputStream in, String encoding) throws ParseException {
if (cacheParser) {
if (parser == null) {
parser = new ASTParser(in, encoding);
} else {
parser.reset(in, encoding);
}
return parser.CompilationUnit();
}
return new ASTParser(in, encoding).CompilationUnit();
} | Parses the Java code contained in the {@link InputStream} and returns a
{@link CompilationUnit} that represents it.
@param in
{@link InputStream} containing Java source code
@param encoding
encoding of the source code
@return CompilationUnit representing the Java source code
@throws ParseException
if the source code has parser errors |
public static CompilationUnit parse(File file, String encoding) throws ParseException, IOException {
FileInputStream in = new FileInputStream(file);
try {
return parse(in, encoding);
} finally {
in.close();
}
} | Parses the Java code contained in a {@link File} and returns a
{@link CompilationUnit} that represents it.
@param file
{@link File} containing Java source code
@param encoding
encoding of the source code
@return CompilationUnit representing the Java source code
@throws ParseException
if the source code has parser errors
@throws IOException |
protected boolean beginTransaction(SQLiteDatabase db) {
boolean endTransaction = false;
if (!db.inTransaction()) {
db.beginTransaction();
endTransaction = true;
LOGGER.trace("Begin transaction");
}
return endTransaction;
} | Begins a transaction if there is not a transaction started yet.
@param db Database.
@return true if a transaction has been started. |
public void replaceChildren(List<T> list, String parentId) {
for (T item : list) {
item.setParentId(parentId);
}
@SuppressWarnings("resource")
SQLiteDatabase db = dbHelper.getWritableDatabase();
boolean endTransaction = beginTransaction(db);
try {
db.delete(getTableName(), getParentIdColumnName() + "=?", new String[] { parentId });
addAll(list);
LOGGER.trace("Replaced children of parent " + parentId + " and type " + getTableName());
successTransaction(db, endTransaction);
} finally {
endTransaction(db, endTransaction);
}
} | This method allows to replace all entity children of a given parent, it will remove any children which are not in
the list, add the new ones and update which are in the list..
@param list of children to replace.
@param parentId id of parent entity. |
public static <T extends Entity> void replaceChildren(List<T> list, String parentId, Class<T> clazz) {
SQLiteRepository<T> repository = (SQLiteRepository<T>)AbstractApplication.get().getRepositoryInstance(clazz);
repository.replaceChildren(list, parentId);
} | This method allows to replace all entity children of a given parent, it will remove any children which are not in
the list, add the new ones and update which are in the list..
@param list of children to replace.
@param parentId id of parent entity.
@param clazz entity class. |
public String getCreateTableSQL() {
StringBuilder builder = new StringBuilder();
// Add columns
for (Column column : getColumns()) {
addColumn(builder, column);
builder.append(", ");
}
// Add references
StringBuilder referencesBuilder = new StringBuilder();
for (Column column : getColumns()) {
if (column.getReference() != null) {
referencesBuilder.append("FOREIGN KEY(").append(column.getColumnName()).append(") REFERENCES ").append(
column.getReference().getTableName()).append("(").append(
column.getReference().getColumn().getColumnName()).append(") ON DELETE CASCADE, ");
}
}
// Add unique constraint
StringBuilder uniqueBuilder = new StringBuilder();
boolean first = true;
for (Column column : getColumns()) {
if (column.isUnique()) {
if (!first) {
uniqueBuilder.append(", ");
}
first = false;
uniqueBuilder.append(column.getColumnName());
}
}
return getCreateTableSQL(builder.toString(), referencesBuilder.toString(), uniqueBuilder.toString());
} | Creates the SQL statement to create the table according columns definitions.
@return SQL statement. |
private String getCreateTableSQL(String columns, String references, String uniqueColumns) {
StringBuilder builder = new StringBuilder();
builder.append("CREATE TABLE ").append(getTableName()).append("(");
builder.append(columns);
builder.append(references);
builder.append("UNIQUE (").append(uniqueColumns).append(") ON CONFLICT REPLACE");
builder.append(");");
return builder.toString();
} | Creates the SQL statement to create the table using given columns definitions.
@param columns columns definitions.
@param references reference constraints.
@param uniqueColumns unique constraints.
@return SQL statement. |
private void addColumn(StringBuilder builder, Column column) {
builder.append(column.getColumnName());
builder.append(" ");
builder.append(column.getDataType().getType());
Boolean optional = column.isOptional();
if (optional != null) {
builder.append(optional ? " NULL" : " NOT NULL");
}
String extraQualifier = column.getExtraQualifier();
if (extraQualifier != null) {
builder.append(" ");
builder.append(extraQualifier);
}
} | Generate the SQL definition for a column.
@param builder current StringBuilder to add the SQL definition.
@param column column definition. |
protected String[] getProjection() {
String[] projection = new String[getColumns().length];
for (int i = 0; i < projection.length; i++) {
projection[i] = getColumns()[i].getColumnName();
}
return projection;
} | Returns the default projection which includes all the columns defined by {@link #getColumns()}
@return the projection. |
@Override
public ELResolver getELResolver() {
if (elResolver == null) {
CompositeELResolver resolver = new CompositeELResolver();
customResolvers = new CompositeELResolver();
resolver.add(customResolvers);
resolver.add(new BeanNameELResolver(new LocalBeanNameResolver()));
if (streamELResolver != null) {
resolver.add(streamELResolver);
}
resolver.add(new StaticFieldELResolver());
resolver.add(new MapELResolver());
resolver.add(new ResourceBundleELResolver());
resolver.add(new ListELResolver());
resolver.add(new ArrayELResolver());
resolver.add(new BeanELResolver());
elResolver = resolver;
}
return elResolver;
} | Construct (if needed) and return a default ELResolver.
<p>Retrieves the <code>ELResolver</code> associated with this context.
This is a <code>CompositeELResover</code> consists of an ordered list of
<code>ELResolver</code>s.
<ol>
<li>A {@link BeanNameELResolver} for beans defined locally</li>
<li>Any custom <code>ELResolver</code>s</li>
<li>An <code>ELResolver</code> supporting the collection operations</li>
<li>A {@link StaticFieldELResolver} for resolving static fields</li>
<li>A {@link MapELResolver} for resolving Map properties</li>
<li>A {@link ResourceBundleELResolver} for resolving ResourceBundle properties</li>
<li>A {@link ListELResolver} for resolving List properties</li>
<li>An {@link ArrayELResolver} for resolving array properties</li>
<li>A {@link BeanELResolver} for resolving bean properties</li>
</ol>
</p>
@return The ELResolver for this context. |
public byte[] ensureBufferHasCapacityLeft(int size) throws FileParsingException {
if (bytesHolder == null) {
bytesHolder = new ByteArrayHolder(size);
} else {
bytesHolder.ensureHasSpace(size);
}
return bytesHolder.getUnderlyingBytes();
} | Ensure, that the output data buffer has enough space left for {@code size} mode bytes.
@return the output buffer |
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Map<String, Object> getAddressCache() {
try {
final Field cacheField = InetAddress.class.getDeclaredField("addressCache");
cacheField.setAccessible(true);
final Object addressCache = cacheField.get(InetAddress.class);
Class clazz = addressCache.getClass();
final Field cacheMapField = clazz.getDeclaredField("cache");
cacheMapField.setAccessible(true);
return (Map) cacheMapField.get(addressCache);
}
catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
} | 大约10年失效 |
protected Host[] toHost(Object entry) {
if (entry == null) {
throw new NullPointerException("entry不能为空.");
}
try {
Class<?> clazz = entry.getClass();
long expiration;
{
Field field = clazz.getDeclaredField("expiration");
field.setAccessible(true);
expiration = (Long) field.get(entry);
}
InetAddress[] addresses;
{
Field field = clazz.getDeclaredField("addresses");
field.setAccessible(true);
addresses = (InetAddress[]) field.get(entry);
}
Host[] hosts = new Host[addresses.length];
for (int i = 0; i < addresses.length; i++) {
InetAddress address = (InetAddress) addresses[i];
Host host = new Host();
host.setExpiration(expiration);
host.setHost(address.getHostName());
host.setIp(address.getHostAddress());
hosts[i] = host;
}
return hosts;
}
catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
} | } |
protected Object createCacheEntry(String host, String[] ips) {
try {
long expiration = System.currentTimeMillis() + EXPIRATION;// 10年失效
InetAddress[] addresses = new InetAddress[ips.length];
for (int i = 0; i < addresses.length; i++) {
// addresses[i] = InetAddress.getByAddress(host, toBytes(ips[i]));
addresses[i] = InetAddress.getByAddress(host, InetAddress.getByName(ips[i]).getAddress());
}
String className = "java.net.InetAddress$CacheEntry";
Class<?> clazz = Class.forName(className);
Constructor<?> constructor = clazz.getDeclaredConstructors()[0];
constructor.setAccessible(true);
return constructor.newInstance(addresses, expiration);
}
catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
} | } |
public boolean contains(Node node2) {
if ((getBeginLine() < node2.getBeginLine())
|| ((getBeginLine() == node2.getBeginLine()) && getBeginColumn() <= node2.getBeginColumn())) {
if (getEndLine() > node2.getEndLine()) {
return true;
} else if ((getEndLine() == node2.getEndLine()) && getEndColumn() >= node2.getEndColumn()) {
return true;
}
}
return false;
} | Return if this node contains another node according their line numbers and columns
@param node2
the probably contained node
@return if this node contains the argument as a child node by its position. |
public boolean isInEqualLocation(Node node2) {
if (!isNewNode() && !node2.isNewNode()) {
return getBeginLine() == node2.getBeginLine() && getBeginColumn() == node2.getBeginColumn()
&& getEndLine() == node2.getEndLine() && getEndColumn() == node2.getEndColumn();
}
return false;
} | Return if this node has the same columns and lines than another one.
@param node2
the node to compare
@return if this node has the same columns and lines than another one. |
public boolean isPreviousThan(Node node) {
if (getEndLine() < node.getBeginLine()) {
return true;
} else if ((getEndLine() == node.getBeginLine()) && (getEndColumn() <= node.getBeginColumn())) {
return true;
}
return false;
} | Return if this node is previous than another one according their line and column numbers
@param node
to compare
@return if this node is previous than another one according their line and |
@SuppressWarnings("unchecked")
static public <T extends Solution> T checkedCopy(T solution){
// copy solution
Solution copy = solution.copy();
// check for null
if (copy == null) {
throw new SolutionCopyException(
"Deep copy of solution of type " + solution.getClass().getSimpleName() + " failed. "
+ "Calling copy() yields null."
);
}
// verify type of copy
Class<?> origClass = solution.getClass();
Class<?> copyClass = copy.getClass();
if(copyClass == origClass){
return (T) copy;
} else {
// mismatching types: find out why and throw a detailed exception
try {
Class<?> declaringClassOfCopy = origClass.getMethod("copy").getDeclaringClass();
if(declaringClassOfCopy != origClass){
// method copy() not directly implemented in T
throw new SolutionCopyException(
"Deep copy of solution of type " + origClass.getSimpleName() + " failed. "
+ "Calling copy() yields a solution of type " + copyClass.getSimpleName() + ", not "
+ origClass.getSimpleName() + ". Expected cause of this type mismatch: "
+ origClass.getSimpleName() + " does not directly implement method copy() but "
+ "inherits an undesired implementation from super class "
+ declaringClassOfCopy.getSimpleName() + "."
);
} else {
// copy() implemented in T but does not return correct type
throw new SolutionCopyException(
"Deep copy of solution of type " + origClass.getSimpleName() + " failed. "
+ "Calling copy() yields a solution of type " + copyClass.getSimpleName() + ", not "
+ origClass.getSimpleName() + ". Expected cause of this type mismatch: "
+ "faulty implementation of copy() in " + origClass.getSimpleName() + ", "
+ "does not return solution of type " + origClass.getSimpleName() + "."
);
}
} catch (NoSuchMethodException noSuchMethodEx){
// this should never happen, all subclasses of Solution
// have a method copy() somewhere in the class hierarchy
throw new Error("Solution without method 'copy()': this should never happen; if it does, "
+ "there is a serious bug in Solution.", noSuchMethodEx);
}
}
} | Creates a checked deep copy of the given solution with specific type <code>T</code>
(a subclass of {@link Solution}). Both the given solution and return type are of the
same type <code>T</code>. This method calls {@link #copy()} on the given solution and
casts the result to the respective type <code>T</code>. If this cast fails, an exception
with a detailed error message is thrown, precisely indicating the expected cause of the
type mismatch: the method {@link #copy()} does not return a solution of the correct type
<code>T</code>, either because an undesired implementation is inherited from a super class
or because the direct implementation violates the general contract of {@link #copy()}.
@param <T> solution type, required to extend {@link Solution}
@param solution solution to copy, of type <code>T</code>
@throws SolutionCopyException if calling {@link #copy()} on the given solution of type <code>T</code>
does not yield a copy of the exact same type <code>T</code>, indicating
a faulty implementation (contains a detailed error message)
@return copy of type <code>T</code> |
public static BitmapDescriptor vectorToBitmap(@DrawableRes int drawableRes, @ColorRes int colorRes) {
Drawable vectorDrawable = VectorDrawableCompat.create(AbstractApplication.get().getResources(), drawableRes, null);
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
DrawableCompat.setTint(vectorDrawable, AbstractApplication.get().getResources().getColor(colorRes));
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
} | Convert a {@link Drawable} to a {@link BitmapDescriptor}, for use as a marker icon. |
public void add(ELResolver elResolver) {
if (elResolver == null) {
throw new NullPointerException();
}
if (size >= elResolvers.length) {
ELResolver[] newResolvers = new ELResolver[size * 2];
System.arraycopy(elResolvers, 0, newResolvers, 0, size);
elResolvers = newResolvers;
}
elResolvers[size++] = elResolver;
} | Adds the given resolver to the list of component resolvers.
<p>Resolvers are consulted in the order in which they are added.</p>
@param elResolver The component resolver to add.
@throws NullPointerException If the provided resolver is
<code>null</code>. |
public Object getValue(ELContext context,
Object base,
Object property) {
context.setPropertyResolved(false);
Object value = null;
for (int i = 0; i < size; i++) {
value = elResolvers[i].getValue(context, base, property);
if (context.isPropertyResolved()) {
return value;
}
}
return null;
} | Attempts to resolve the given <code>property</code> object on the given
<code>base</code> object by querying all component resolvers.
<p>If this resolver handles the given (base, property) pair,
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>First, <code>propertyResolved</code> is set to <code>false</code> on
the provided <code>ELContext</code>.</p>
<p>Next, for each component resolver in this composite:
<ol>
<li>The <code>getValue()</code> method is called, passing in
the provided <code>context</code>, <code>base</code> and
<code>property</code>.</li>
<li>If the <code>ELContext</code>'s <code>propertyResolved</code>
flag is <code>false</code> then iteration continues.</li>
<li>Otherwise, iteration stops and no more component resolvers are
considered. The value returned by <code>getValue()</code> is
returned by this method.</li>
</ol></p>
<p>If none of the component resolvers were able to perform this
operation, the value <code>null</code> is returned and the
<code>propertyResolved</code> flag remains set to
<code>false</code></p>.
<p>Any exception thrown by component resolvers during the iteration
is propagated to the caller of this method.</p>
@param context The context of this evaluation.
@param base The base object whose property value is to be returned,
or <code>null</code> to resolve a top-level variable.
@param property The property or variable to be resolved.
@return If the <code>propertyResolved</code> property of
<code>ELContext</code> was set to <code>true</code>, then
the result of the variable or property resolution; otherwise
undefined.
@throws NullPointerException if context is <code>null</code>
@throws PropertyNotFoundException if the given (base, property) pair
is handled by this <code>ELResolver</code> but the specified
variable or property does not exist or is not readable.
@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 Object invoke(ELContext context,
Object base,
Object method,
Class<?>[] paramTypes,
Object[] params) {
context.setPropertyResolved(false);
Object value;
for (int i = 0; i < size; i++) {
value = elResolvers[i].invoke(context, base, method,
paramTypes, params);
if (context.isPropertyResolved()) {
return value;
}
}
return null;
} | Attemps to resolve and invoke the given <code>method</code> on the given
<code>base</code> object by querying all component resolvers.
<p>If this resolver handles the given (base, method) pair,
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>First, <code>propertyResolved</code> is set to <code>false</code> on
the provided <code>ELContext</code>.</p>
<p>Next, for each component resolver in this composite:
<ol>
<li>The <code>invoke()</code> method is called, passing in
the provided <code>context</code>, <code>base</code>,
<code>method</code>, <code>paramTypes</code>, and
<code>params</code>.</li>
<li>If the <code>ELContext</code>'s <code>propertyResolved</code>
flag is <code>false</code> then iteration continues.</li>
<li>Otherwise, iteration stops and no more component resolvers are
considered. The value returned by <code>getValue()</code> is
returned by this method.</li>
</ol></p>
<p>If none of the component resolvers were able to perform this
operation, the value <code>null</code> is returned and the
<code>propertyResolved</code> flag remains set to
<code>false</code></p>.
<p>Any exception thrown by component resolvers during the iteration
is propagated to the caller of this method.</p>
@param context The context of this evaluation.
@param base The bean on which to invoke the method
@param method The simple name of the method to invoke.
Will be coerced to a <code>String</code>.
@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).
@since EL 2.2 |
public Class<?> getType(ELContext context,
Object base,
Object property) {
context.setPropertyResolved(false);
Class<?> type;
for (int i = 0; i < size; i++) {
type = elResolvers[i].getType(context, base, property);
if (context.isPropertyResolved()) {
return type;
}
}
return null;
} | For a given <code>base</code> and <code>property</code>, attempts to
identify the most general type that is acceptable for an object to be
passed as the <code>value</code> parameter in a future call
to the {@link #setValue} method. The result is obtained by
querying all component resolvers.
<p>If this resolver handles the given (base, property) pair,
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>First, <code>propertyResolved</code> is set to <code>false</code> on
the provided <code>ELContext</code>.</p>
<p>Next, for each component resolver in this composite:
<ol>
<li>The <code>getType()</code> method is called, passing in
the provided <code>context</code>, <code>base</code> and
<code>property</code>.</li>
<li>If the <code>ELContext</code>'s <code>propertyResolved</code>
flag is <code>false</code> then iteration continues.</li>
<li>Otherwise, iteration stops and no more component resolvers are
considered. The value returned by <code>getType()</code> is
returned by this method.</li>
</ol></p>
<p>If none of the component resolvers were able to perform this
operation, the value <code>null</code> is returned and the
<code>propertyResolved</code> flag remains set to
<code>false</code></p>.
<p>Any exception thrown by component resolvers during the iteration
is propagated to the caller of this method.</p>
@param context The context of this evaluation.
@param base The base object whose property value is to be analyzed,
or <code>null</code> to analyze a top-level variable.
@param property The property or variable to return the acceptable
type for.
@return If the <code>propertyResolved</code> property of
<code>ELContext</code> was set to <code>true</code>, then
the most general acceptable type; otherwise undefined.
@throws NullPointerException if context is <code>null</code>
@throws PropertyNotFoundException if the given (base, property) pair
is handled by this <code>ELResolver</code> but the specified
variable or property does not exist or is not readable.
@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) {
context.setPropertyResolved(false);
for (int i = 0; i < size; i++) {
elResolvers[i].setValue(context, base, property, val);
if (context.isPropertyResolved()) {
return;
}
}
} | Attempts to set the value of the given <code>property</code>
object on the given <code>base</code> object. All component
resolvers are asked to attempt to set the value.
<p>If this resolver handles the given (base, property) pair,
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>First, <code>propertyResolved</code> is set to <code>false</code> on
the provided <code>ELContext</code>.</p>
<p>Next, for each component resolver in this composite:
<ol>
<li>The <code>setValue()</code> method is called, passing in
the provided <code>context</code>, <code>base</code>,
<code>property</code> and <code>value</code>.</li>
<li>If the <code>ELContext</code>'s <code>propertyResolved</code>
flag is <code>false</code> then iteration continues.</li>
<li>Otherwise, iteration stops and no more component resolvers are
considered.</li>
</ol></p>
<p>If none of the component resolvers were able to perform this
operation, the <code>propertyResolved</code> flag remains set to
<code>false</code></p>.
<p>Any exception thrown by component resolvers during the iteration
is propagated to the caller of this method.</p>
@param context The context of this evaluation.
@param base The base object whose property value is to be set,
or <code>null</code> to set a top-level variable.
@param property The property or variable to be set.
@param val The value to set the property or variable to.
@throws NullPointerException if context is <code>null</code>
@throws PropertyNotFoundException if the given (base, property) pair
is handled by this <code>ELResolver</code> but the specified
variable or property does not exist.
@throws PropertyNotWritableException if the given (base, property)
pair is handled by this <code>ELResolver</code> but the specified
variable or property is not writable.
@throws ELException if an exception was thrown while attempting to
set the property or variable. The thrown exception
must be included as the cause property of this exception, if
available. |
public boolean isReadOnly(ELContext context,
Object base,
Object property) {
context.setPropertyResolved(false);
boolean readOnly;
for (int i = 0; i < size; i++) {
readOnly = elResolvers[i].isReadOnly(context, base, property);
if (context.isPropertyResolved()) {
return readOnly;
}
}
return false; // Does not matter
} | For a given <code>base</code> and <code>property</code>, attempts to
determine whether a call to {@link #setValue} will always fail. The
result is obtained by querying all component resolvers.
<p>If this resolver handles the given (base, property) pair,
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>First, <code>propertyResolved</code> is set to <code>false</code> on
the provided <code>ELContext</code>.</p>
<p>Next, for each component resolver in this composite:
<ol>
<li>The <code>isReadOnly()</code> method is called, passing in
the provided <code>context</code>, <code>base</code> and
<code>property</code>.</li>
<li>If the <code>ELContext</code>'s <code>propertyResolved</code>
flag is <code>false</code> then iteration continues.</li>
<li>Otherwise, iteration stops and no more component resolvers are
considered. The value returned by <code>isReadOnly()</code> is
returned by this method.</li>
</ol></p>
<p>If none of the component resolvers were able to perform this
operation, the value <code>false</code> is returned and the
<code>propertyResolved</code> flag remains set to
<code>false</code></p>.
<p>Any exception thrown by component resolvers during the iteration
is propagated to the caller of this method.</p>
@param context The context of this evaluation.
@param base The base object whose property value is to be analyzed,
or <code>null</code> to analyze a top-level variable.
@param property The property or variable to return the read-only status
for.
@return If the <code>propertyResolved</code> property of
<code>ELContext</code> was set to <code>true</code>, then
<code>true</code> if the property is read-only or
<code>false</code> if not; otherwise undefined.
@throws NullPointerException if context is <code>null</code>
@throws PropertyNotFoundException if the given (base, property) pair
is handled by this <code>ELResolver</code> but the specified
variable or property does not exist.
@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) {
return new CompositeIterator(elResolvers, size, context, base);
} | Returns information about the set of variables or properties that
can be resolved for the given <code>base</code> object. One use for
this method is to assist tools in auto-completion. The results are
collected from all component resolvers.
<p>The <code>propertyResolved</code> property of the
<code>ELContext</code> is not relevant to this method.
The results of all <code>ELResolver</code>s are concatenated.</p>
<p>The <code>Iterator</code> returned is an iterator over the
collection of <code>FeatureDescriptor</code> objects returned by
the iterators returned by each component resolver's
<code>getFeatureDescriptors</code> method. If <code>null</code> is
returned by a resolver, it is skipped.</p>
@param context The context of this evaluation.
@param base The base object whose set of valid properties is to
be enumerated, or <code>null</code> to enumerate the set of
top-level variables that this resolver can evaluate.
@return An <code>Iterator</code> containing zero or more (possibly
infinitely more) <code>FeatureDescriptor</code> objects, or
<code>null</code> if this resolver does not handle the given
<code>base</code> object or that the results are too complex to
represent with this method |
public Class<?> getCommonPropertyType(ELContext context,
Object base) {
Class<?> commonPropertyType = null;
for (int i = 0; i < size; i++) {
Class<?> type = elResolvers[i].getCommonPropertyType(context, base);
if (type == null) {
// skip this EL Resolver
continue;
} else if (commonPropertyType == null) {
commonPropertyType = type;
} else if (commonPropertyType.isAssignableFrom(type)) {
continue;
} else if (type.isAssignableFrom(commonPropertyType)) {
commonPropertyType = type;
} else {
// Don't have a commonPropertyType
return null;
}
}
return commonPropertyType;
} | Returns the most general type that this resolver accepts for the
<code>property</code> argument, given a <code>base</code> object.
One use for this method is to assist tools in auto-completion. The
result is obtained by querying all component resolvers.
<p>The <code>Class</code> returned is the most specific class that is
a common superclass of all the classes returned by each component
resolver's <code>getCommonPropertyType</code> method. If
<code>null</code> is returned by a resolver, it is skipped.</p>
@param context The context of this evaluation.
@param base The base object to return the most general property
type for, or <code>null</code> to enumerate the set of
top-level variables that this resolver can evaluate.
@return <code>null</code> if this <code>ELResolver</code> does not
know how to handle the given <code>base</code> object; otherwise
<code>Object.class</code> if any type of <code>property</code>
is accepted; otherwise the most general <code>property</code>
type accepted for the given <code>base</code>. |
@Override
public Object convertToType(ELContext context,
Object obj,
Class<?> targetType) {
context.setPropertyResolved(false);
Object value = null;
for (int i = 0; i < size; i++) {
value = elResolvers[i].convertToType(context, obj, targetType);
if (context.isPropertyResolved()) {
return value;
}
}
return null;
} | Converts an object to a specific type.
<p>An <code>ELException</code> is thrown if an error occurs during
the conversion.</p>
@param context The context of this evaluation.
@param obj The object to convert.
@param targetType The target type for the convertion.
@throws ELException thrown if errors occur.
@since EL 3.0 |
public DesignSpec setBaselineGridColor(int color) {
if (mBaselineGridPaint.getColor() == color) {
return this;
}
mBaselineGridPaint.setColor(color);
invalidateSelf();
return this;
} | Sets the baseline grid color. |
public DesignSpec setKeylinesColor(int color) {
if (mKeylinesPaint.getColor() == color) {
return this;
}
mKeylinesPaint.setColor(color);
invalidateSelf();
return this;
} | Sets the keyline color. |
public DesignSpec addKeyline(float position, From from) {
final Keyline keyline = new Keyline(position * mDensity, from);
if (mKeylines.contains(keyline)) {
return this;
}
mKeylines.add(keyline);
return this;
} | Adds a keyline to the {@link DesignSpec}. |
public DesignSpec setSpacingsColor(int color) {
if (mSpacingsPaint.getColor() == color) {
return this;
}
mSpacingsPaint.setColor(color);
invalidateSelf();
return this;
} | Sets the spacing mark color. |
public DesignSpec addSpacing(float position, float size, From from) {
final Spacing spacing = new Spacing(position * mDensity, size * mDensity, from);
if (mSpacings.contains(spacing)) {
return this;
}
mSpacings.add(spacing);
return this;
} | Adds a spacing mark to the {@link DesignSpec}. |
@Override
public void draw(Canvas canvas) {
drawSpacings(canvas);
drawBaselineGrid(canvas);
drawKeylines(canvas);
} | Draws the {@link DesignSpec}. You should call this in your {@link View}'s
{@link View#onDraw(Canvas)} method if you're not simply enclosing it with a
{@link DesignSpecFrameLayout}. |
public static DesignSpec fromResource(View view, int resId) {
final Resources resources = view.getResources();
final DesignSpec spec = new DesignSpec(resources, view);
if (resId == 0) {
return spec;
}
final JSONObject json;
try {
json = RawResource.getAsJSON(resources, resId);
} catch (IOException e) {
throw new IllegalStateException("Could not read design spec resource", e);
}
final float density = resources.getDisplayMetrics().density;
spec.setBaselineGridCellSize(density * json.optInt(JSON_KEY_BASELINE_GRID_CELL_SIZE,
DEFAULT_BASELINE_GRID_CELL_SIZE_DIP));
spec.setBaselineGridVisible(json.optBoolean(JSON_KEY_BASELINE_GRID_VISIBLE,
DEFAULT_BASELINE_GRID_VISIBLE));
spec.setKeylinesVisible(json.optBoolean(JSON_KEY_KEYLINES_VISIBLE,
DEFAULT_KEYLINES_VISIBLE));
spec.setSpacingsVisible(json.optBoolean(JSON_KEY_SPACINGS_VISIBLE,
DEFAULT_SPACINGS_VISIBLE));
spec.setBaselineGridColor(Color.parseColor(json.optString(JSON_KEY_BASELINE_GRID_COLOR,
DEFAULT_BASELINE_GRID_COLOR)));
spec.setKeylinesColor(Color.parseColor(json.optString(JSON_KEY_KEYLINES_COLOR,
DEFAULT_KEYLINE_COLOR)));
spec.setSpacingsColor(Color.parseColor(json.optString(JSON_KEY_SPACINGS_COLOR,
DEFAULT_SPACING_COLOR)));
final JSONArray keylines = json.optJSONArray(JSON_KEY_KEYLINES);
if (keylines != null) {
final int keylineCount = keylines.length();
for (int i = 0; i < keylineCount; i++) {
try {
final JSONObject keyline = keylines.getJSONObject(i);
spec.addKeyline(keyline.getInt(JSON_KEY_OFFSET),
From.valueOf(keyline.getString(JSON_KEY_FROM).toUpperCase()));
} catch (JSONException e) {
continue;
}
}
}
final JSONArray spacings = json.optJSONArray(JSON_KEY_SPACINGS);
if (spacings != null) {
final int spacingCount = spacings.length();
for (int i = 0; i < spacingCount; i++) {
try {
final JSONObject spacing = spacings.getJSONObject(i);
spec.addSpacing(spacing.getInt(JSON_KEY_OFFSET), spacing.getInt(JSON_KEY_SIZE),
From.valueOf(spacing.getString(JSON_KEY_FROM).toUpperCase()));
} catch (JSONException e) {
continue;
}
}
}
return spec;
} | Creates a new {@link DesignSpec} instance from a resource ID using a {@link View}
that will provide the {@link DesignSpec}'s intrinsic dimensions.
@param view The {@link View} who will own the new {@link DesignSpec} instance.
@param resId The resource ID pointing to a raw JSON resource.
@return The newly created {@link DesignSpec} instance. |
public List<Scan.ScanOrigin> getScanOrigin() {
if (scanOrigin == null) {
scanOrigin = new ArrayList<Scan.ScanOrigin>();
}
return this.scanOrigin;
} | Gets the value of the scanOrigin 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 scanOrigin property.
<p>
For example, to add a new item, do as follows:
<pre>
getScanOrigin().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list {@link Scan.ScanOrigin } |
public List<Scan.PrecursorMz> getPrecursorMz() {
if (precursorMz == null) {
precursorMz = new ArrayList<Scan.PrecursorMz>();
}
return this.precursorMz;
} | Gets the value of the precursorMz 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 precursorMz property.
<p>
For example, to add a new item, do as follows:
<pre>
getPrecursorMz().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list {@link Scan.PrecursorMz } |
public List<Scan.Peaks> getPeaks() {
if (peaks == null) {
peaks = new ArrayList<Scan.Peaks>();
}
return this.peaks;
} | Gets the value of the peaks 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 peaks property.
<p>
For example, to add a new item, do as follows:
<pre>
getPeaks().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list {@link Scan.Peaks } |
private void selectPage(long offset) {
if (currentBuffer == null || currentBuffer.seekSuccessful(offset)) {
currentBuffer = null;
int i = 0;
// Look if the given offset is already stored in a page
while (i < pages.size() && currentBuffer == null) {
if (pages.get(i).seekSuccessful(offset))
currentBuffer = pages.get(i);
i++;
}
if (currentBuffer == null) {
// If the offset is not contained in any of the loaded pages, create a new one
// FIFO
if (pages.size() >= MaxPages)
pages.remove(0);
pages.add(new InputBuffer(input));
currentBuffer = pages.get(pages.size() - 1);
}
}
} | Select buffer.
@param offset the offset |
private List<GeoLocation> decodePolyLine(String poly) {
int len = poly.length();
int index = 0;
List<GeoLocation> decoded = new ArrayList<>();
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = (result & 1) != 0 ? ~(result >> 1) : (result >> 1);
lat += dlat;
shift = 0;
result = 0;
do {
b = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = (result & 1) != 0 ? ~(result >> 1) : (result >> 1);
lng += dlng;
decoded.add(new GeoLocation(lat / 1E5, lng / 1E5));
}
return decoded;
} | Decode a polyline string into a list of GeoLocations. From
https://developers.google.com/maps/documentation/directions/?hl=es#Limits
@param poly polyline encoded string to decode.
@return the list of GeoLocations represented by this polystring. |
@Override
public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) {
// check minimum size
if(minSizeReached(solution)){
return null;
}
// get set of candidate IDs for deletion (possibly fixed IDs are discarded)
Set<Integer> removeCandidates = getRemoveCandidates(solution);
// check if removal is possible
if(removeCandidates.isEmpty()){
return null;
}
// select random ID to remove from selection
int del = SetUtilities.getRandomElement(removeCandidates, rnd);
// create and return deletion move
return new DeletionMove(del);
} | Generates a random deletion move for the given subset solution that removes a single ID from the selection.
Possible fixed IDs are not considered to be removed and the minimum subset size is taken into account.
If no deletion move can be generated, <code>null</code> is returned.
@param solution solution for which a random deletion move is generated
@param rnd source of randomness used to generate random move
@return random deletion move, <code>null</code> if no move can be generated |
@Override
public List<SubsetMove> getAllMoves(SubsetSolution solution) {
// check minimum size
if(minSizeReached(solution)){
return Collections.emptyList();
}
// get set of candidate IDs for deletion (possibly fixed IDs are discarded)
Set<Integer> removeCandidates = getRemoveCandidates(solution);
// check if there are any candidates to be removed
if(removeCandidates.isEmpty()){
return Collections.emptyList();
}
// create deletion move for all candidates
return removeCandidates.stream()
.map(del -> new DeletionMove(del))
.collect(Collectors.toList());
} | Generates a list of all possible deletion moves that remove a single ID from the selection of a given
subset solution. Possible fixed IDs are not considered to be removed and the minimum subset size
is taken into account. May return an empty list if no deletion moves can be generated.
@param solution solution for which all possible deletion moves are generated
@return list of all deletion moves, may be empty |
private void fireNewCurrentSolution(SolutionType newCurrentSolution,
Evaluation newCurrentSolutionEvaluation,
Validation newCurrentSolutionValidation){
for(SearchListener<? super SolutionType> l : getSearchListeners()){
l.newCurrentSolution(this, newCurrentSolution,
newCurrentSolutionEvaluation,
newCurrentSolutionValidation);
}
} | Calls {@link SearchListener#newCurrentSolution(LocalSearch, Solution, Evaluation, Validation)} on
every attached search listener. Should only be executed when the search is active (initializing,
running or terminating) and be fired exactly once for each update of the current solution. |
public void setCurrentSolution(SolutionType solution){
// synchronize with status updates
synchronized(getStatusLock()){
// assert idle
assertIdle("Cannot set current solution.");
// check not null
if(solution == null){
throw new NullPointerException("Cannot set current solution: received null.");
}
// update current solution and check for new best solution
updateCurrentAndBestSolution(solution);
}
} | Sets the current solution prior to execution or in between search runs. The given solution is evaluated and
validated, and it is checked whether it is a valid first/new best solution. This method may for example be
used to specify a custom initial solution before starting the search. Note that it may only be called when
the search is idle.
@param solution current solution to be adopted
@throws SearchException if the search is not idle
@throws NullPointerException if <code>solution</code> is <code>null</code> |
public void setCurrentSolution(SolutionType solution, Evaluation evaluation, Validation validation){
// synchronize with status updates
synchronized(getStatusLock()){
// assert idle
assertIdle("Cannot set current solution.");
// check not null
if(solution == null || evaluation == null || validation == null){
throw new NullPointerException(
"Cannot set current solution: solution, evaluation and validation can not be null."
);
}
// update current solution and check for new best solution
updateCurrentAndBestSolution(solution, evaluation, validation);
}
} | Sets the current solution given that it has already been evaluated and validated.
It is checked whether the new current solution is a valid first/new best solution.
Note that this method may only be called when the search is idle.
@param solution current solution to be adopted
@param evaluation current solution evaluation
@param validation current solution validation
@throws SearchException if the search is not idle
@throws NullPointerException if any argument is <code>null</code> |
protected void updateCurrentSolution(SolutionType solution){
updateCurrentSolution(solution, getProblem().evaluate(solution), getProblem().validate(solution));
} | Update the current solution during search. The solution is evaluated and validated but the update takes
place regardless of the actual obtained evaluation and validation. More precisely, it is <b>not</b> required
that the current solution is valid.
@param solution new current solution |
protected void updateCurrentSolution(SolutionType solution, Evaluation evaluation, Validation validation){
// store new current solution
curSolution = solution;
// store evaluation and validation
curSolutionEvaluation = evaluation;
curSolutionValidation = validation;
// inform listeners
fireNewCurrentSolution(curSolution, curSolutionEvaluation, curSolutionValidation);
} | Update the current solution during search, given that it has already been evaluated and validated.
The new current solution and its evaluation/validation are stored and attached local search listeners
are informed about this update. The update always takes place, it is <b>not</b> required that the
current solution is valid.
@param solution new current solution
@param evaluation evaluation of new current solution
@param validation validation of new current solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.