Security Aware Code
Collection
2 items
•
Updated
bug_id
stringlengths 5
19
| func_before
stringlengths 49
25.9k
⌀ | func_after
stringlengths 45
26k
|
---|---|---|
Compress-35 | public static boolean verifyCheckSum(byte[] header) {
long storedSum = 0;
long unsignedSum = 0;
long signedSum = 0;
int digits = 0;
for (int i = 0; i < header.length; i++) {
byte b = header[i];
if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) {
if ('0' <= b && b <= '7' && digits++ < 6) {
storedSum = storedSum * 8 + b - '0';
} else if (digits > 0) {
digits = 6;
}
b = ' ';
}
unsignedSum += 0xff & b;
signedSum += b;
}
return storedSum == unsignedSum || storedSum == signedSum;
}
| public static boolean verifyCheckSum(byte[] header) {
long storedSum = parseOctal(header, CHKSUM_OFFSET, CHKSUMLEN);
long unsignedSum = 0;
long signedSum = 0;
int digits = 0;
for (int i = 0; i < header.length; i++) {
byte b = header[i];
if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) {
b = ' ';
}
unsignedSum += 0xff & b;
signedSum += b;
}
return storedSum == unsignedSum || storedSum == signedSum;
}
|
JacksonCore-21 | public JsonToken nextToken() throws IOException
{
if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) {
if (_currToken.isStructEnd()) {
if (_headContext.isStartHandled()) {
return (_currToken = null);
}
} else if (_currToken.isScalarValue()) {
if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) {
return (_currToken = null);
}
}
}
TokenFilterContext ctxt = _exposedContext;
if (ctxt != null) {
while (true) {
JsonToken t = ctxt.nextTokenToRead();
if (t != null) {
_currToken = t;
return t;
}
if (ctxt == _headContext) {
_exposedContext = null;
if (ctxt.inArray()) {
t = delegate.getCurrentToken();
_currToken = t;
return t;
}
break;
}
ctxt = _headContext.findChildOf(ctxt);
_exposedContext = ctxt;
if (ctxt == null) {
throw _constructError("Unexpected problem: chain of filtered context broken");
}
}
}
JsonToken t = delegate.nextToken();
if (t == null) {
_currToken = t;
return t;
}
TokenFilter f;
switch (t.id()) {
case ID_START_ARRAY:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
if (f == null) {
delegate.skipChildren();
break;
}
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartArray();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildArrayContext(f, false);
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
case ID_START_OBJECT:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
if (f == null) {
delegate.skipChildren();
break;
}
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartObject();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildObjectContext(f, false);
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
case ID_END_ARRAY:
case ID_END_OBJECT:
{
boolean returnEnd = _headContext.isStartHandled();
f = _headContext.getFilter();
if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
f.filterFinishArray();
}
_headContext = _headContext.getParent();
_itemFilter = _headContext.getFilter();
if (returnEnd) {
return (_currToken = t);
}
}
break;
case ID_FIELD_NAME:
{
final String name = delegate.getCurrentName();
f = _headContext.setFieldName(name);
if (f == TokenFilter.INCLUDE_ALL) {
_itemFilter = f;
if (!_includePath) {
if (_includeImmediateParent && !_headContext.isStartHandled()) {
t = _headContext.nextTokenToRead();
_exposedContext = _headContext;
}
}
return (_currToken = t);
}
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
f = f.includeProperty(name);
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
if (_includePath) {
return (_currToken = t);
}
}
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
}
default:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
return (_currToken = t);
}
if (f != null) {
f = _headContext.checkValue(f);
if ((f == TokenFilter.INCLUDE_ALL)
|| ((f != null) && f.includeValue(delegate))) {
return (_currToken = t);
}
}
break;
}
return _nextToken2();
}
| public JsonToken nextToken() throws IOException
{
if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) {
if (!_includePath) {
if (_currToken.isStructEnd()) {
if (_headContext.isStartHandled()) {
return (_currToken = null);
}
} else if (_currToken.isScalarValue()) {
if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) {
return (_currToken = null);
}
}
}
}
TokenFilterContext ctxt = _exposedContext;
if (ctxt != null) {
while (true) {
JsonToken t = ctxt.nextTokenToRead();
if (t != null) {
_currToken = t;
return t;
}
if (ctxt == _headContext) {
_exposedContext = null;
if (ctxt.inArray()) {
t = delegate.getCurrentToken();
_currToken = t;
return t;
}
break;
}
ctxt = _headContext.findChildOf(ctxt);
_exposedContext = ctxt;
if (ctxt == null) {
throw _constructError("Unexpected problem: chain of filtered context broken");
}
}
}
JsonToken t = delegate.nextToken();
if (t == null) {
_currToken = t;
return t;
}
TokenFilter f;
switch (t.id()) {
case ID_START_ARRAY:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
if (f == null) {
delegate.skipChildren();
break;
}
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartArray();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildArrayContext(f, false);
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
case ID_START_OBJECT:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
if (f == null) {
delegate.skipChildren();
break;
}
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartObject();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildObjectContext(f, false);
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
case ID_END_ARRAY:
case ID_END_OBJECT:
{
boolean returnEnd = _headContext.isStartHandled();
f = _headContext.getFilter();
if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
f.filterFinishArray();
}
_headContext = _headContext.getParent();
_itemFilter = _headContext.getFilter();
if (returnEnd) {
return (_currToken = t);
}
}
break;
case ID_FIELD_NAME:
{
final String name = delegate.getCurrentName();
f = _headContext.setFieldName(name);
if (f == TokenFilter.INCLUDE_ALL) {
_itemFilter = f;
if (!_includePath) {
if (_includeImmediateParent && !_headContext.isStartHandled()) {
t = _headContext.nextTokenToRead();
_exposedContext = _headContext;
}
}
return (_currToken = t);
}
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
f = f.includeProperty(name);
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
if (_includePath) {
return (_currToken = t);
}
}
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
}
default:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
return (_currToken = t);
}
if (f != null) {
f = _headContext.checkValue(f);
if ((f == TokenFilter.INCLUDE_ALL)
|| ((f != null) && f.includeValue(delegate))) {
return (_currToken = t);
}
}
break;
}
return _nextToken2();
}
|
Lang-5 | public static Locale toLocale(final String str) {
if (str == null) {
return null;
}
final int len = str.length();
if (len < 2) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch0 = str.charAt(0);
final char ch1 = str.charAt(1);
if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 2) {
return new Locale(str);
}
if (len < 5) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(2) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch3 = str.charAt(3);
if (ch3 == '_') {
return new Locale(str.substring(0, 2), "", str.substring(4));
}
final char ch4 = str.charAt(4);
if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 5) {
return new Locale(str.substring(0, 2), str.substring(3, 5));
}
if (len < 7) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(5) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
}
| public static Locale toLocale(final String str) {
if (str == null) {
return null;
}
final int len = str.length();
if (len < 2) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch0 = str.charAt(0);
if (ch0 == '_') {
if (len < 3) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch1 = str.charAt(1);
final char ch2 = str.charAt(2);
if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 3) {
return new Locale("", str.substring(1, 3));
}
if (len < 5) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(3) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
return new Locale("", str.substring(1, 3), str.substring(4));
} else {
final char ch1 = str.charAt(1);
if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 2) {
return new Locale(str);
}
if (len < 5) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(2) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch3 = str.charAt(3);
if (ch3 == '_') {
return new Locale(str.substring(0, 2), "", str.substring(4));
}
final char ch4 = str.charAt(4);
if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 5) {
return new Locale(str.substring(0, 2), str.substring(3, 5));
}
if (len < 7) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(5) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
}
}
|
Codec-17 | public static String newStringIso8859_1(final byte[] bytes) {
return new String(bytes, Charsets.ISO_8859_1);
}
| public static String newStringIso8859_1(final byte[] bytes) {
return newString(bytes, Charsets.ISO_8859_1);
}
|
Compress-12 | public TarArchiveEntry getNextTarEntry() throws IOException {
if (hasHitEOF) {
return null;
}
if (currEntry != null) {
long numToSkip = entrySize - entryOffset;
while (numToSkip > 0) {
long skipped = skip(numToSkip);
if (skipped <= 0) {
throw new RuntimeException("failed to skip current tar entry");
}
numToSkip -= skipped;
}
readBuf = null;
}
byte[] headerBuf = getRecord();
if (hasHitEOF) {
currEntry = null;
return null;
}
currEntry = new TarArchiveEntry(headerBuf);
entryOffset = 0;
entrySize = currEntry.getSize();
if (currEntry.isGNULongNameEntry()) {
StringBuffer longName = new StringBuffer();
byte[] buf = new byte[SMALL_BUFFER_SIZE];
int length = 0;
while ((length = read(buf)) >= 0) {
longName.append(new String(buf, 0, length));
}
getNextEntry();
if (currEntry == null) {
return null;
}
if (longName.length() > 0
&& longName.charAt(longName.length() - 1) == 0) {
longName.deleteCharAt(longName.length() - 1);
}
currEntry.setName(longName.toString());
}
if (currEntry.isPaxHeader()){
paxHeaders();
}
if (currEntry.isGNUSparse()){
readGNUSparse();
}
entrySize = currEntry.getSize();
return currEntry;
}
| public TarArchiveEntry getNextTarEntry() throws IOException {
if (hasHitEOF) {
return null;
}
if (currEntry != null) {
long numToSkip = entrySize - entryOffset;
while (numToSkip > 0) {
long skipped = skip(numToSkip);
if (skipped <= 0) {
throw new RuntimeException("failed to skip current tar entry");
}
numToSkip -= skipped;
}
readBuf = null;
}
byte[] headerBuf = getRecord();
if (hasHitEOF) {
currEntry = null;
return null;
}
try {
currEntry = new TarArchiveEntry(headerBuf);
} catch (IllegalArgumentException e) {
IOException ioe = new IOException("Error detected parsing the header");
ioe.initCause(e);
throw ioe;
}
entryOffset = 0;
entrySize = currEntry.getSize();
if (currEntry.isGNULongNameEntry()) {
StringBuffer longName = new StringBuffer();
byte[] buf = new byte[SMALL_BUFFER_SIZE];
int length = 0;
while ((length = read(buf)) >= 0) {
longName.append(new String(buf, 0, length));
}
getNextEntry();
if (currEntry == null) {
return null;
}
if (longName.length() > 0
&& longName.charAt(longName.length() - 1) == 0) {
longName.deleteCharAt(longName.length() - 1);
}
currEntry.setName(longName.toString());
}
if (currEntry.isPaxHeader()){
paxHeaders();
}
if (currEntry.isGNUSparse()){
readGNUSparse();
}
entrySize = currEntry.getSize();
return currEntry;
}
|
Lang-31 | public static boolean containsAny(CharSequence cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return false;
}
int csLength = cs.length();
int searchLength = searchChars.length;
for (int i = 0; i < csLength; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLength; j++) {
if (searchChars[j] == ch) {
return true;
}
}
}
return false;
}
| public static boolean containsAny(CharSequence cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return false;
}
int csLength = cs.length();
int searchLength = searchChars.length;
int csLastIndex = csLength - 1;
int searchLastIndex = searchLength - 1;
for (int i = 0; i < csLength; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLength; j++) {
if (searchChars[j] == ch) {
if (i < csLastIndex && j < searchLastIndex && ch >= Character.MIN_HIGH_SURROGATE && ch <= Character.MAX_HIGH_SURROGATE) {
if (searchChars[j + 1] == cs.charAt(i + 1)) {
return true;
}
} else {
return true;
}
}
}
}
return false;
}
|
Closure-116 | private CanInlineResult canInlineReferenceDirectly(
Node callNode, Node fnNode) {
if (!isDirectCallNodeReplacementPossible(fnNode)) {
return CanInlineResult.NO;
}
Node block = fnNode.getLastChild();
Node cArg = callNode.getFirstChild().getNext();
if (!callNode.getFirstChild().isName()) {
if (NodeUtil.isFunctionObjectCall(callNode)) {
if (cArg == null || !cArg.isThis()) {
return CanInlineResult.NO;
}
cArg = cArg.getNext();
} else {
Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));
}
}
Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();
while (cArg != null || fnParam != null) {
if (fnParam != null) {
if (cArg != null) {
if (NodeUtil.mayEffectMutableState(cArg, compiler)
&& NodeUtil.getNameReferenceCount(
block, fnParam.getString()) > 1) {
return CanInlineResult.NO;
}
}
fnParam = fnParam.getNext();
}
if (cArg != null) {
if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {
return CanInlineResult.NO;
}
cArg = cArg.getNext();
}
}
return CanInlineResult.YES;
}
| private CanInlineResult canInlineReferenceDirectly(
Node callNode, Node fnNode) {
if (!isDirectCallNodeReplacementPossible(fnNode)) {
return CanInlineResult.NO;
}
Node block = fnNode.getLastChild();
boolean hasSideEffects = false;
if (block.hasChildren()) {
Preconditions.checkState(block.hasOneChild());
Node stmt = block.getFirstChild();
if (stmt.isReturn()) {
hasSideEffects = NodeUtil.mayHaveSideEffects(
stmt.getFirstChild(), compiler);
}
}
Node cArg = callNode.getFirstChild().getNext();
if (!callNode.getFirstChild().isName()) {
if (NodeUtil.isFunctionObjectCall(callNode)) {
if (cArg == null || !cArg.isThis()) {
return CanInlineResult.NO;
}
cArg = cArg.getNext();
} else {
Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));
}
}
Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();
while (cArg != null || fnParam != null) {
if (fnParam != null) {
if (cArg != null) {
if (hasSideEffects && NodeUtil.canBeSideEffected(cArg)) {
return CanInlineResult.NO;
}
if (NodeUtil.mayEffectMutableState(cArg, compiler)
&& NodeUtil.getNameReferenceCount(
block, fnParam.getString()) > 1) {
return CanInlineResult.NO;
}
}
fnParam = fnParam.getNext();
}
if (cArg != null) {
if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {
return CanInlineResult.NO;
}
cArg = cArg.getNext();
}
}
return CanInlineResult.YES;
}
|
Mockito-18 | Object returnValueFor(Class<?> type) {
if (Primitives.isPrimitiveOrWrapper(type)) {
return Primitives.defaultValueForPrimitiveOrWrapper(type);
} else if (type == Collection.class) {
return new LinkedList<Object>();
} else if (type == Set.class) {
return new HashSet<Object>();
} else if (type == HashSet.class) {
return new HashSet<Object>();
} else if (type == SortedSet.class) {
return new TreeSet<Object>();
} else if (type == TreeSet.class) {
return new TreeSet<Object>();
} else if (type == LinkedHashSet.class) {
return new LinkedHashSet<Object>();
} else if (type == List.class) {
return new LinkedList<Object>();
} else if (type == LinkedList.class) {
return new LinkedList<Object>();
} else if (type == ArrayList.class) {
return new ArrayList<Object>();
} else if (type == Map.class) {
return new HashMap<Object, Object>();
} else if (type == HashMap.class) {
return new HashMap<Object, Object>();
} else if (type == SortedMap.class) {
return new TreeMap<Object, Object>();
} else if (type == TreeMap.class) {
return new TreeMap<Object, Object>();
} else if (type == LinkedHashMap.class) {
return new LinkedHashMap<Object, Object>();
}
return null;
}
| Object returnValueFor(Class<?> type) {
if (Primitives.isPrimitiveOrWrapper(type)) {
return Primitives.defaultValueForPrimitiveOrWrapper(type);
} else if (type == Iterable.class) {
return new ArrayList<Object>(0);
} else if (type == Collection.class) {
return new LinkedList<Object>();
} else if (type == Set.class) {
return new HashSet<Object>();
} else if (type == HashSet.class) {
return new HashSet<Object>();
} else if (type == SortedSet.class) {
return new TreeSet<Object>();
} else if (type == TreeSet.class) {
return new TreeSet<Object>();
} else if (type == LinkedHashSet.class) {
return new LinkedHashSet<Object>();
} else if (type == List.class) {
return new LinkedList<Object>();
} else if (type == LinkedList.class) {
return new LinkedList<Object>();
} else if (type == ArrayList.class) {
return new ArrayList<Object>();
} else if (type == Map.class) {
return new HashMap<Object, Object>();
} else if (type == HashMap.class) {
return new HashMap<Object, Object>();
} else if (type == SortedMap.class) {
return new TreeMap<Object, Object>();
} else if (type == TreeMap.class) {
return new TreeMap<Object, Object>();
} else if (type == LinkedHashMap.class) {
return new LinkedHashMap<Object, Object>();
}
return null;
}
|
Time-7 | public int parseInto(ReadWritableInstant instant, String text, int position) {
DateTimeParser parser = requireParser();
if (instant == null) {
throw new IllegalArgumentException("Instant must not be null");
}
long instantMillis = instant.getMillis();
Chronology chrono = instant.getChronology();
long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);
chrono = selectChronology(chrono);
int defaultYear = chrono.year().get(instantLocal);
DateTimeParserBucket bucket = new DateTimeParserBucket(
instantLocal, chrono, iLocale, iPivotYear, defaultYear);
int newPos = parser.parseInto(bucket, text, position);
instant.setMillis(bucket.computeMillis(false, text));
if (iOffsetParsed && bucket.getOffsetInteger() != null) {
int parsedOffset = bucket.getOffsetInteger();
DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
chrono = chrono.withZone(parsedZone);
} else if (bucket.getZone() != null) {
chrono = chrono.withZone(bucket.getZone());
}
instant.setChronology(chrono);
if (iZone != null) {
instant.setZone(iZone);
}
return newPos;
}
| public int parseInto(ReadWritableInstant instant, String text, int position) {
DateTimeParser parser = requireParser();
if (instant == null) {
throw new IllegalArgumentException("Instant must not be null");
}
long instantMillis = instant.getMillis();
Chronology chrono = instant.getChronology();
int defaultYear = DateTimeUtils.getChronology(chrono).year().get(instantMillis);
long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);
chrono = selectChronology(chrono);
DateTimeParserBucket bucket = new DateTimeParserBucket(
instantLocal, chrono, iLocale, iPivotYear, defaultYear);
int newPos = parser.parseInto(bucket, text, position);
instant.setMillis(bucket.computeMillis(false, text));
if (iOffsetParsed && bucket.getOffsetInteger() != null) {
int parsedOffset = bucket.getOffsetInteger();
DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
chrono = chrono.withZone(parsedZone);
} else if (bucket.getZone() != null) {
chrono = chrono.withZone(bucket.getZone());
}
instant.setChronology(chrono);
if (iZone != null) {
instant.setZone(iZone);
}
return newPos;
}
|
Closure-18 | Node parseInputs() {
boolean devMode = options.devMode != DevMode.OFF;
if (externsRoot != null) {
externsRoot.detachChildren();
}
if (jsRoot != null) {
jsRoot.detachChildren();
}
jsRoot = IR.block();
jsRoot.setIsSyntheticBlock(true);
externsRoot = IR.block();
externsRoot.setIsSyntheticBlock(true);
externAndJsRoot = IR.block(externsRoot, jsRoot);
externAndJsRoot.setIsSyntheticBlock(true);
if (options.tracer.isOn()) {
tracker = new PerformanceTracker(jsRoot, options.tracer);
addChangeHandler(tracker.getCodeChangeHandler());
}
Tracer tracer = newTracer("parseInputs");
try {
for (CompilerInput input : externs) {
Node n = input.getAstRoot(this);
if (hasErrors()) {
return null;
}
externsRoot.addChildToBack(n);
}
if (options.transformAMDToCJSModules || options.processCommonJSModules) {
processAMDAndCommonJSModules();
}
hoistExterns(externsRoot);
boolean staleInputs = false;
if (options.dependencyOptions.needsManagement() && options.closurePass) {
for (CompilerInput input : inputs) {
for (String provide : input.getProvides()) {
getTypeRegistry().forwardDeclareType(provide);
}
}
try {
inputs =
(moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)
.manageDependencies(options.dependencyOptions, inputs);
staleInputs = true;
} catch (CircularDependencyException e) {
report(JSError.make(
JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));
if (hasErrors()) {
return null;
}
} catch (MissingProvideException e) {
report(JSError.make(
MISSING_ENTRY_ERROR, e.getMessage()));
if (hasErrors()) {
return null;
}
}
}
hoistNoCompileFiles();
if (staleInputs) {
repartitionInputs();
}
for (CompilerInput input : inputs) {
Node n = input.getAstRoot(this);
if (n == null) {
continue;
}
if (devMode) {
runSanityCheck();
if (hasErrors()) {
return null;
}
}
if (options.sourceMapOutputPath != null ||
options.nameReferenceReportPath != null) {
SourceInformationAnnotator sia =
new SourceInformationAnnotator(
input.getName(), options.devMode != DevMode.OFF);
NodeTraversal.traverse(this, n, sia);
}
jsRoot.addChildToBack(n);
}
if (hasErrors()) {
return null;
}
return externAndJsRoot;
} finally {
stopTracer(tracer, "parseInputs");
}
}
| Node parseInputs() {
boolean devMode = options.devMode != DevMode.OFF;
if (externsRoot != null) {
externsRoot.detachChildren();
}
if (jsRoot != null) {
jsRoot.detachChildren();
}
jsRoot = IR.block();
jsRoot.setIsSyntheticBlock(true);
externsRoot = IR.block();
externsRoot.setIsSyntheticBlock(true);
externAndJsRoot = IR.block(externsRoot, jsRoot);
externAndJsRoot.setIsSyntheticBlock(true);
if (options.tracer.isOn()) {
tracker = new PerformanceTracker(jsRoot, options.tracer);
addChangeHandler(tracker.getCodeChangeHandler());
}
Tracer tracer = newTracer("parseInputs");
try {
for (CompilerInput input : externs) {
Node n = input.getAstRoot(this);
if (hasErrors()) {
return null;
}
externsRoot.addChildToBack(n);
}
if (options.transformAMDToCJSModules || options.processCommonJSModules) {
processAMDAndCommonJSModules();
}
hoistExterns(externsRoot);
boolean staleInputs = false;
if (options.dependencyOptions.needsManagement()) {
for (CompilerInput input : inputs) {
for (String provide : input.getProvides()) {
getTypeRegistry().forwardDeclareType(provide);
}
}
try {
inputs =
(moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)
.manageDependencies(options.dependencyOptions, inputs);
staleInputs = true;
} catch (CircularDependencyException e) {
report(JSError.make(
JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));
if (hasErrors()) {
return null;
}
} catch (MissingProvideException e) {
report(JSError.make(
MISSING_ENTRY_ERROR, e.getMessage()));
if (hasErrors()) {
return null;
}
}
}
hoistNoCompileFiles();
if (staleInputs) {
repartitionInputs();
}
for (CompilerInput input : inputs) {
Node n = input.getAstRoot(this);
if (n == null) {
continue;
}
if (devMode) {
runSanityCheck();
if (hasErrors()) {
return null;
}
}
if (options.sourceMapOutputPath != null ||
options.nameReferenceReportPath != null) {
SourceInformationAnnotator sia =
new SourceInformationAnnotator(
input.getName(), options.devMode != DevMode.OFF);
NodeTraversal.traverse(this, n, sia);
}
jsRoot.addChildToBack(n);
}
if (hasErrors()) {
return null;
}
return externAndJsRoot;
} finally {
stopTracer(tracer, "parseInputs");
}
}
|
JacksonDatabind-17 | public boolean useForType(JavaType t)
{
switch (_appliesFor) {
case NON_CONCRETE_AND_ARRAYS:
while (t.isArrayType()) {
t = t.getContentType();
}
case OBJECT_AND_NON_CONCRETE:
return (t.getRawClass() == Object.class)
|| (!t.isConcrete()
|| TreeNode.class.isAssignableFrom(t.getRawClass()));
case NON_FINAL:
while (t.isArrayType()) {
t = t.getContentType();
}
return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());
default:
return (t.getRawClass() == Object.class);
}
}
| public boolean useForType(JavaType t)
{
switch (_appliesFor) {
case NON_CONCRETE_AND_ARRAYS:
while (t.isArrayType()) {
t = t.getContentType();
}
case OBJECT_AND_NON_CONCRETE:
return (t.getRawClass() == Object.class)
|| (!t.isConcrete()
&& !TreeNode.class.isAssignableFrom(t.getRawClass()));
case NON_FINAL:
while (t.isArrayType()) {
t = t.getContentType();
}
return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());
default:
return (t.getRawClass() == Object.class);
}
}
|
Math-52 | public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) {
double u1u1 = u1.getNormSq();
double u2u2 = u2.getNormSq();
double v1v1 = v1.getNormSq();
double v2v2 = v2.getNormSq();
if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) {
throw MathRuntimeException.createIllegalArgumentException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);
}
v1 = new Vector3D(FastMath.sqrt(u1u1 / v1v1), v1);
double u1u2 = u1.dotProduct(u2);
double v1v2 = v1.dotProduct(v2);
double coeffU = u1u2 / u1u1;
double coeffV = v1v2 / u1u1;
double beta = FastMath.sqrt((u2u2 - u1u2 * coeffU) / (v2v2 - v1v2 * coeffV));
double alpha = coeffU - beta * coeffV;
v2 = new Vector3D(alpha, v1, beta, v2);
Vector3D uRef = u1;
Vector3D vRef = v1;
Vector3D v1Su1 = v1.subtract(u1);
Vector3D v2Su2 = v2.subtract(u2);
Vector3D k = v1Su1.crossProduct(v2Su2);
Vector3D u3 = u1.crossProduct(u2);
double c = k.dotProduct(u3);
if (c == 0) {
Vector3D v3 = Vector3D.crossProduct(v1, v2);
Vector3D v3Su3 = v3.subtract(u3);
k = v1Su1.crossProduct(v3Su3);
Vector3D u2Prime = u1.crossProduct(u3);
c = k.dotProduct(u2Prime);
if (c == 0) {
k = v2Su2.crossProduct(v3Su3);;
c = k.dotProduct(u2.crossProduct(u3));;
if (c == 0) {
q0 = 1.0;
q1 = 0.0;
q2 = 0.0;
q3 = 0.0;
return;
}
uRef = u2;
vRef = v2;
}
}
c = FastMath.sqrt(c);
double inv = 1.0 / (c + c);
q1 = inv * k.getX();
q2 = inv * k.getY();
q3 = inv * k.getZ();
k = new Vector3D(uRef.getY() * q3 - uRef.getZ() * q2,
uRef.getZ() * q1 - uRef.getX() * q3,
uRef.getX() * q2 - uRef.getY() * q1);
q0 = vRef.dotProduct(k) / (2 * k.getNormSq());
}
| public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) {
double u1u1 = u1.getNormSq();
double u2u2 = u2.getNormSq();
double v1v1 = v1.getNormSq();
double v2v2 = v2.getNormSq();
if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) {
throw MathRuntimeException.createIllegalArgumentException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);
}
v1 = new Vector3D(FastMath.sqrt(u1u1 / v1v1), v1);
double u1u2 = u1.dotProduct(u2);
double v1v2 = v1.dotProduct(v2);
double coeffU = u1u2 / u1u1;
double coeffV = v1v2 / u1u1;
double beta = FastMath.sqrt((u2u2 - u1u2 * coeffU) / (v2v2 - v1v2 * coeffV));
double alpha = coeffU - beta * coeffV;
v2 = new Vector3D(alpha, v1, beta, v2);
Vector3D uRef = u1;
Vector3D vRef = v1;
Vector3D v1Su1 = v1.subtract(u1);
Vector3D v2Su2 = v2.subtract(u2);
Vector3D k = v1Su1.crossProduct(v2Su2);
Vector3D u3 = u1.crossProduct(u2);
double c = k.dotProduct(u3);
final double inPlaneThreshold = 0.001;
if (c <= inPlaneThreshold * k.getNorm() * u3.getNorm()) {
Vector3D v3 = Vector3D.crossProduct(v1, v2);
Vector3D v3Su3 = v3.subtract(u3);
k = v1Su1.crossProduct(v3Su3);
Vector3D u2Prime = u1.crossProduct(u3);
c = k.dotProduct(u2Prime);
if (c <= inPlaneThreshold * k.getNorm() * u2Prime.getNorm()) {
k = v2Su2.crossProduct(v3Su3);;
c = k.dotProduct(u2.crossProduct(u3));;
if (c <= 0) {
q0 = 1.0;
q1 = 0.0;
q2 = 0.0;
q3 = 0.0;
return;
}
uRef = u2;
vRef = v2;
}
}
c = FastMath.sqrt(c);
double inv = 1.0 / (c + c);
q1 = inv * k.getX();
q2 = inv * k.getY();
q3 = inv * k.getZ();
k = new Vector3D(uRef.getY() * q3 - uRef.getZ() * q2,
uRef.getZ() * q1 - uRef.getX() * q3,
uRef.getX() * q2 - uRef.getY() * q1);
q0 = vRef.dotProduct(k) / (2 * k.getNormSq());
}
|
Chart-8 | public Week(Date time, TimeZone zone) {
this(time, RegularTimePeriod.DEFAULT_TIME_ZONE, Locale.getDefault());
}
| public Week(Date time, TimeZone zone) {
this(time, zone, Locale.getDefault());
}
|
Chart-11 | public static boolean equal(GeneralPath p1, GeneralPath p2) {
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
if (p1.getWindingRule() != p2.getWindingRule()) {
return false;
}
PathIterator iterator1 = p1.getPathIterator(null);
PathIterator iterator2 = p1.getPathIterator(null);
double[] d1 = new double[6];
double[] d2 = new double[6];
boolean done = iterator1.isDone() && iterator2.isDone();
while (!done) {
if (iterator1.isDone() != iterator2.isDone()) {
return false;
}
int seg1 = iterator1.currentSegment(d1);
int seg2 = iterator2.currentSegment(d2);
if (seg1 != seg2) {
return false;
}
if (!Arrays.equals(d1, d2)) {
return false;
}
iterator1.next();
iterator2.next();
done = iterator1.isDone() && iterator2.isDone();
}
return true;
}
| public static boolean equal(GeneralPath p1, GeneralPath p2) {
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
if (p1.getWindingRule() != p2.getWindingRule()) {
return false;
}
PathIterator iterator1 = p1.getPathIterator(null);
PathIterator iterator2 = p2.getPathIterator(null);
double[] d1 = new double[6];
double[] d2 = new double[6];
boolean done = iterator1.isDone() && iterator2.isDone();
while (!done) {
if (iterator1.isDone() != iterator2.isDone()) {
return false;
}
int seg1 = iterator1.currentSegment(d1);
int seg2 = iterator2.currentSegment(d2);
if (seg1 != seg2) {
return false;
}
if (!Arrays.equals(d1, d2)) {
return false;
}
iterator1.next();
iterator2.next();
done = iterator1.isDone() && iterator2.isDone();
}
return true;
}
|
Closure-10 | static boolean mayBeString(Node n, boolean recurse) {
if (recurse) {
return allResultsMatch(n, MAY_BE_STRING_PREDICATE);
} else {
return mayBeStringHelper(n);
}
}
| static boolean mayBeString(Node n, boolean recurse) {
if (recurse) {
return anyResultsMatch(n, MAY_BE_STRING_PREDICATE);
} else {
return mayBeStringHelper(n);
}
}
|
Jsoup-40 | public DocumentType(String name, String publicId, String systemId, String baseUri) {
super(baseUri);
Validate.notEmpty(name);
attr("name", name);
attr("publicId", publicId);
attr("systemId", systemId);
}
| public DocumentType(String name, String publicId, String systemId, String baseUri) {
super(baseUri);
attr("name", name);
attr("publicId", publicId);
attr("systemId", systemId);
}
|
Time-24 | public long computeMillis(boolean resetFields, String text) {
SavedField[] savedFields = iSavedFields;
int count = iSavedFieldsCount;
if (iSavedFieldsShared) {
iSavedFields = savedFields = (SavedField[])iSavedFields.clone();
iSavedFieldsShared = false;
}
sort(savedFields, count);
if (count > 0) {
DurationField months = DurationFieldType.months().getField(iChrono);
DurationField days = DurationFieldType.days().getField(iChrono);
DurationField first = savedFields[0].iField.getDurationField();
if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) {
saveField(DateTimeFieldType.year(), iDefaultYear);
return computeMillis(resetFields, text);
}
}
long millis = iMillis;
try {
for (int i = 0; i < count; i++) {
millis = savedFields[i].set(millis, resetFields);
}
} catch (IllegalFieldValueException e) {
if (text != null) {
e.prependMessage("Cannot parse \"" + text + '"');
}
throw e;
}
if (iZone == null) {
millis -= iOffset;
} else {
int offset = iZone.getOffsetFromLocal(millis);
millis -= offset;
if (offset != iZone.getOffset(millis)) {
String message =
"Illegal instant due to time zone offset transition (" + iZone + ')';
if (text != null) {
message = "Cannot parse \"" + text + "\": " + message;
}
throw new IllegalArgumentException(message);
}
}
return millis;
}
| public long computeMillis(boolean resetFields, String text) {
SavedField[] savedFields = iSavedFields;
int count = iSavedFieldsCount;
if (iSavedFieldsShared) {
iSavedFields = savedFields = (SavedField[])iSavedFields.clone();
iSavedFieldsShared = false;
}
sort(savedFields, count);
if (count > 0) {
DurationField months = DurationFieldType.months().getField(iChrono);
DurationField days = DurationFieldType.days().getField(iChrono);
DurationField first = savedFields[0].iField.getDurationField();
if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) {
saveField(DateTimeFieldType.year(), iDefaultYear);
return computeMillis(resetFields, text);
}
}
long millis = iMillis;
try {
for (int i = 0; i < count; i++) {
millis = savedFields[i].set(millis, resetFields);
}
if (resetFields) {
for (int i = 0; i < count; i++) {
millis = savedFields[i].set(millis, i == (count - 1));
}
}
} catch (IllegalFieldValueException e) {
if (text != null) {
e.prependMessage("Cannot parse \"" + text + '"');
}
throw e;
}
if (iZone == null) {
millis -= iOffset;
} else {
int offset = iZone.getOffsetFromLocal(millis);
millis -= offset;
if (offset != iZone.getOffset(millis)) {
String message =
"Illegal instant due to time zone offset transition (" + iZone + ')';
if (text != null) {
message = "Cannot parse \"" + text + "\": " + message;
}
throw new IllegalArgumentException(message);
}
}
return millis;
}
|
Cli-26 | public static Option create(String opt) throws IllegalArgumentException
{
Option option = new Option(opt, description);
option.setLongOpt(longopt);
option.setRequired(required);
option.setOptionalArg(optionalArg);
option.setArgs(numberOfArgs);
option.setType(type);
option.setValueSeparator(valuesep);
option.setArgName(argName);
OptionBuilder.reset();
return option;
}
| public static Option create(String opt) throws IllegalArgumentException
{
Option option = null;
try {
option = new Option(opt, description);
option.setLongOpt(longopt);
option.setRequired(required);
option.setOptionalArg(optionalArg);
option.setArgs(numberOfArgs);
option.setType(type);
option.setValueSeparator(valuesep);
option.setArgName(argName);
} finally {
OptionBuilder.reset();
}
return option;
}
|
Math-82 | private Integer getPivotRow(final int col, final SimplexTableau tableau) {
double minRatio = Double.MAX_VALUE;
Integer minRatioPos = null;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
final double entry = tableau.getEntry(i, col);
if (MathUtils.compareTo(entry, 0, epsilon) >= 0) {
final double ratio = rhs / entry;
if (ratio < minRatio) {
minRatio = ratio;
minRatioPos = i;
}
}
}
return minRatioPos;
}
| private Integer getPivotRow(final int col, final SimplexTableau tableau) {
double minRatio = Double.MAX_VALUE;
Integer minRatioPos = null;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
final double entry = tableau.getEntry(i, col);
if (MathUtils.compareTo(entry, 0, epsilon) > 0) {
final double ratio = rhs / entry;
if (ratio < minRatio) {
minRatio = ratio;
minRatioPos = i;
}
}
}
return minRatioPos;
}
|
JacksonDatabind-82 | protected void addBeanProps(DeserializationContext ctxt,
BeanDescription beanDesc, BeanDeserializerBuilder builder)
throws JsonMappingException
{
final boolean isConcrete = !beanDesc.getType().isAbstract();
final SettableBeanProperty[] creatorProps = isConcrete
? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig())
: null;
final boolean hasCreatorProps = (creatorProps != null);
JsonIgnoreProperties.Value ignorals = ctxt.getConfig()
.getDefaultPropertyIgnorals(beanDesc.getBeanClass(),
beanDesc.getClassInfo());
Set<String> ignored;
if (ignorals != null) {
boolean ignoreAny = ignorals.getIgnoreUnknown();
builder.setIgnoreUnknownProperties(ignoreAny);
ignored = ignorals.getIgnored();
for (String propName : ignored) {
builder.addIgnorable(propName);
}
} else {
ignored = Collections.emptySet();
}
AnnotatedMethod anySetterMethod = beanDesc.findAnySetter();
AnnotatedMember anySetterField = null;
if (anySetterMethod != null) {
builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod));
}
else {
anySetterField = beanDesc.findAnySetterField();
if(anySetterField != null) {
builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField));
}
}
if (anySetterMethod == null && anySetterField == null) {
Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames();
if (ignored2 != null) {
for (String propName : ignored2) {
builder.addIgnorable(propName);
}
}
}
final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)
&& ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS);
List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt,
beanDesc, builder, beanDesc.findProperties(), ignored);
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);
}
}
for (BeanPropertyDefinition propDef : propDefs) {
SettableBeanProperty prop = null;
if (propDef.hasSetter()) {
JavaType propertyType = propDef.getSetter().getParameterType(0);
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (propDef.hasField()) {
JavaType propertyType = propDef.getField().getType();
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (useGettersAsSetters && propDef.hasGetter()) {
AnnotatedMethod getter = propDef.getGetter();
Class<?> rawPropertyType = getter.getRawType();
if (Collection.class.isAssignableFrom(rawPropertyType)
|| Map.class.isAssignableFrom(rawPropertyType)) {
prop = constructSetterlessProperty(ctxt, beanDesc, propDef);
}
}
if (hasCreatorProps && propDef.hasConstructorParameter()) {
final String name = propDef.getName();
CreatorProperty cprop = null;
if (creatorProps != null) {
for (SettableBeanProperty cp : creatorProps) {
if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {
cprop = (CreatorProperty) cp;
break;
}
}
}
if (cprop == null) {
List<String> n = new ArrayList<>();
for (SettableBeanProperty cp : creatorProps) {
n.add(cp.getName());
}
ctxt.reportBadPropertyDefinition(beanDesc, propDef,
"Could not find creator property with name '%s' (known Creator properties: %s)",
name, n);
continue;
}
if (prop != null) {
cprop.setFallbackSetter(prop);
}
prop = cprop;
builder.addCreatorProperty(cprop);
continue;
}
if (prop != null) {
Class<?>[] views = propDef.findViews();
if (views == null) {
if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {
views = NO_VIEWS;
}
}
prop.setViews(views);
builder.addProperty(prop);
}
}
}
| protected void addBeanProps(DeserializationContext ctxt,
BeanDescription beanDesc, BeanDeserializerBuilder builder)
throws JsonMappingException
{
final boolean isConcrete = !beanDesc.getType().isAbstract();
final SettableBeanProperty[] creatorProps = isConcrete
? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig())
: null;
final boolean hasCreatorProps = (creatorProps != null);
JsonIgnoreProperties.Value ignorals = ctxt.getConfig()
.getDefaultPropertyIgnorals(beanDesc.getBeanClass(),
beanDesc.getClassInfo());
Set<String> ignored;
if (ignorals != null) {
boolean ignoreAny = ignorals.getIgnoreUnknown();
builder.setIgnoreUnknownProperties(ignoreAny);
ignored = ignorals.findIgnoredForDeserialization();
for (String propName : ignored) {
builder.addIgnorable(propName);
}
} else {
ignored = Collections.emptySet();
}
AnnotatedMethod anySetterMethod = beanDesc.findAnySetter();
AnnotatedMember anySetterField = null;
if (anySetterMethod != null) {
builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod));
}
else {
anySetterField = beanDesc.findAnySetterField();
if(anySetterField != null) {
builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField));
}
}
if (anySetterMethod == null && anySetterField == null) {
Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames();
if (ignored2 != null) {
for (String propName : ignored2) {
builder.addIgnorable(propName);
}
}
}
final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)
&& ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS);
List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt,
beanDesc, builder, beanDesc.findProperties(), ignored);
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);
}
}
for (BeanPropertyDefinition propDef : propDefs) {
SettableBeanProperty prop = null;
if (propDef.hasSetter()) {
JavaType propertyType = propDef.getSetter().getParameterType(0);
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (propDef.hasField()) {
JavaType propertyType = propDef.getField().getType();
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (useGettersAsSetters && propDef.hasGetter()) {
AnnotatedMethod getter = propDef.getGetter();
Class<?> rawPropertyType = getter.getRawType();
if (Collection.class.isAssignableFrom(rawPropertyType)
|| Map.class.isAssignableFrom(rawPropertyType)) {
prop = constructSetterlessProperty(ctxt, beanDesc, propDef);
}
}
if (hasCreatorProps && propDef.hasConstructorParameter()) {
final String name = propDef.getName();
CreatorProperty cprop = null;
if (creatorProps != null) {
for (SettableBeanProperty cp : creatorProps) {
if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {
cprop = (CreatorProperty) cp;
break;
}
}
}
if (cprop == null) {
List<String> n = new ArrayList<>();
for (SettableBeanProperty cp : creatorProps) {
n.add(cp.getName());
}
ctxt.reportBadPropertyDefinition(beanDesc, propDef,
"Could not find creator property with name '%s' (known Creator properties: %s)",
name, n);
continue;
}
if (prop != null) {
cprop.setFallbackSetter(prop);
}
prop = cprop;
builder.addCreatorProperty(cprop);
continue;
}
if (prop != null) {
Class<?>[] views = propDef.findViews();
if (views == null) {
if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {
views = NO_VIEWS;
}
}
prop.setViews(views);
builder.addProperty(prop);
}
}
}
|
Jsoup-35 | boolean process(Token t, HtmlTreeBuilder tb) {
switch (t.type) {
case Character: {
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
tb.error(this);
return false;
} else if (isWhitespace(c)) {
tb.reconstructFormattingElements();
tb.insert(c);
} else {
tb.reconstructFormattingElements();
tb.insert(c);
tb.framesetOk(false);
}
break;
}
case Comment: {
tb.insert(t.asComment());
break;
}
case Doctype: {
tb.error(this);
return false;
}
case StartTag:
Token.StartTag startTag = t.asStartTag();
String name = startTag.name();
if (name.equals("html")) {
tb.error(this);
Element html = tb.getStack().getFirst();
for (Attribute attribute : startTag.getAttributes()) {
if (!html.hasAttr(attribute.getKey()))
html.attributes().put(attribute);
}
} else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title")) {
return tb.process(t, InHead);
} else if (name.equals("body")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
return false;
} else {
tb.framesetOk(false);
Element body = stack.get(1);
for (Attribute attribute : startTag.getAttributes()) {
if (!body.hasAttr(attribute.getKey()))
body.attributes().put(attribute);
}
}
} else if (name.equals("frameset")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
return false;
} else if (!tb.framesetOk()) {
return false;
} else {
Element second = stack.get(1);
if (second.parent() != null)
second.remove();
while (stack.size() > 1)
stack.removeLast();
tb.insert(startTag);
tb.transition(InFrameset);
}
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl",
"fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol",
"p", "section", "summary", "ul")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) {
tb.error(this);
tb.pop();
}
tb.insert(startTag);
} else if (StringUtil.in(name, "pre", "listing")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
} else if (name.equals("form")) {
if (tb.getFormElement() != null) {
tb.error(this);
return false;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertForm(startTag, true);
} else if (name.equals("li")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (el.nodeName().equals("li")) {
tb.process(new Token.EndTag("li"));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "dd", "dt")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (StringUtil.in(el.nodeName(), "dd", "dt")) {
tb.process(new Token.EndTag(el.nodeName()));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (name.equals("plaintext")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.PLAINTEXT);
} else if (name.equals("button")) {
if (tb.inButtonScope("button")) {
tb.error(this);
tb.process(new Token.EndTag("button"));
tb.process(startTag);
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
}
} else if (name.equals("a")) {
if (tb.getActiveFormattingElement("a") != null) {
tb.error(this);
tb.process(new Token.EndTag("a"));
Element remainingA = tb.getFromStack("a");
if (remainingA != null) {
tb.removeFromActiveFormattingElements(remainingA);
tb.removeFromStack(remainingA);
}
}
tb.reconstructFormattingElements();
Element a = tb.insert(startTag);
tb.pushActiveFormattingElements(a);
} else if (StringUtil.in(name,
"b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) {
tb.reconstructFormattingElements();
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (name.equals("nobr")) {
tb.reconstructFormattingElements();
if (tb.inScope("nobr")) {
tb.error(this);
tb.process(new Token.EndTag("nobr"));
tb.reconstructFormattingElements();
}
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
} else if (name.equals("table")) {
if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InTable);
} else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) {
tb.reconstructFormattingElements();
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("input")) {
tb.reconstructFormattingElements();
Element el = tb.insertEmpty(startTag);
if (!el.attr("type").equalsIgnoreCase("hidden"))
tb.framesetOk(false);
} else if (StringUtil.in(name, "param", "source", "track")) {
tb.insertEmpty(startTag);
} else if (name.equals("hr")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("image")) {
startTag.name("img");
return tb.process(startTag);
} else if (name.equals("isindex")) {
tb.error(this);
if (tb.getFormElement() != null)
return false;
tb.tokeniser.acknowledgeSelfClosingFlag();
tb.process(new Token.StartTag("form"));
if (startTag.attributes.hasKey("action")) {
Element form = tb.getFormElement();
form.attr("action", startTag.attributes.get("action"));
}
tb.process(new Token.StartTag("hr"));
tb.process(new Token.StartTag("label"));
String prompt = startTag.attributes.hasKey("prompt") ?
startTag.attributes.get("prompt") :
"This is a searchable index. Enter search keywords: ";
tb.process(new Token.Character(prompt));
Attributes inputAttribs = new Attributes();
for (Attribute attr : startTag.attributes) {
if (!StringUtil.in(attr.getKey(), "name", "action", "prompt"))
inputAttribs.put(attr);
}
inputAttribs.put("name", "isindex");
tb.process(new Token.StartTag("input", inputAttribs));
tb.process(new Token.EndTag("label"));
tb.process(new Token.StartTag("hr"));
tb.process(new Token.EndTag("form"));
} else if (name.equals("textarea")) {
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.framesetOk(false);
tb.transition(Text);
} else if (name.equals("xmp")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.reconstructFormattingElements();
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("iframe")) {
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("noembed")) {
handleRawtext(startTag, tb);
} else if (name.equals("select")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
HtmlTreeBuilderState state = tb.state();
if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))
tb.transition(InSelectInTable);
else
tb.transition(InSelect);
} else if (StringUtil.in("optgroup", "option")) {
if (tb.currentElement().nodeName().equals("option"))
tb.process(new Token.EndTag("option"));
tb.reconstructFormattingElements();
tb.insert(startTag);
} else if (StringUtil.in("rp", "rt")) {
if (tb.inScope("ruby")) {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals("ruby")) {
tb.error(this);
tb.popStackToBefore("ruby");
}
tb.insert(startTag);
}
} else if (name.equals("math")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (name.equals("svg")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (StringUtil.in(name,
"caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) {
tb.error(this);
return false;
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
}
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
name = endTag.name();
if (name.equals("body")) {
if (!tb.inScope("body")) {
tb.error(this);
return false;
} else {
tb.transition(AfterBody);
}
} else if (name.equals("html")) {
boolean notIgnored = tb.process(new Token.EndTag("body"));
if (notIgnored)
return tb.process(endTag);
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div",
"dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu",
"nav", "ol", "pre", "section", "summary", "ul")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("form")) {
Element currentForm = tb.getFormElement();
tb.setFormElement(null);
if (currentForm == null || !tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.removeFromStack(currentForm);
}
} else if (name.equals("p")) {
if (!tb.inButtonScope(name)) {
tb.error(this);
tb.process(new Token.StartTag(name));
return tb.process(endTag);
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("li")) {
if (!tb.inListItemScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "dd", "dt")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6");
}
} else if (name.equals("sarcasm")) {
return anyOtherEndTag(t, tb);
} else if (StringUtil.in(name,
"a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) {
OUTER:
for (int i = 0; i < 8; i++) {
Element formatEl = tb.getActiveFormattingElement(name);
if (formatEl == null)
return anyOtherEndTag(t, tb);
else if (!tb.onStack(formatEl)) {
tb.error(this);
tb.removeFromActiveFormattingElements(formatEl);
return true;
} else if (!tb.inScope(formatEl.nodeName())) {
tb.error(this);
return false;
} else if (tb.currentElement() != formatEl)
tb.error(this);
Element furthestBlock = null;
Element commonAncestor = null;
boolean seenFormattingElement = false;
LinkedList<Element> stack = tb.getStack();
for (int si = 0; si < stack.size() && si < 64; si++) {
Element el = stack.get(si);
if (el == formatEl) {
commonAncestor = stack.get(si - 1);
seenFormattingElement = true;
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el;
break;
}
}
if (furthestBlock == null) {
tb.popStackToClose(formatEl.nodeName());
tb.removeFromActiveFormattingElements(formatEl);
return true;
}
Element node = furthestBlock;
Element lastNode = furthestBlock;
INNER:
for (int j = 0; j < 3; j++) {
if (tb.onStack(node))
node = tb.aboveOnStack(node);
if (!tb.isInActiveFormattingElements(node)) {
tb.removeFromStack(node);
continue INNER;
} else if (node == formatEl)
break INNER;
Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());
tb.replaceActiveFormattingElement(node, replacement);
tb.replaceOnStack(node, replacement);
node = replacement;
if (lastNode == furthestBlock) {
}
if (lastNode.parent() != null)
lastNode.remove();
node.appendChild(lastNode);
lastNode = node;
}
if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) {
if (lastNode.parent() != null)
lastNode.remove();
tb.insertInFosterParent(lastNode);
} else {
if (lastNode.parent() != null)
lastNode.remove();
commonAncestor.appendChild(lastNode);
}
Element adopter = new Element(formatEl.tag(), tb.getBaseUri());
Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);
for (Node childNode : childNodes) {
adopter.appendChild(childNode);
}
furthestBlock.appendChild(adopter);
tb.removeFromActiveFormattingElements(formatEl);
tb.removeFromStack(formatEl);
tb.insertOnStackAfter(furthestBlock, adopter);
}
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
if (!tb.inScope("name")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
}
} else if (name.equals("br")) {
tb.error(this);
tb.process(new Token.StartTag("br"));
return false;
} else {
return anyOtherEndTag(t, tb);
}
break;
case EOF:
break;
}
return true;
}
| boolean process(Token t, HtmlTreeBuilder tb) {
switch (t.type) {
case Character: {
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
tb.error(this);
return false;
} else if (isWhitespace(c)) {
tb.reconstructFormattingElements();
tb.insert(c);
} else {
tb.reconstructFormattingElements();
tb.insert(c);
tb.framesetOk(false);
}
break;
}
case Comment: {
tb.insert(t.asComment());
break;
}
case Doctype: {
tb.error(this);
return false;
}
case StartTag:
Token.StartTag startTag = t.asStartTag();
String name = startTag.name();
if (name.equals("html")) {
tb.error(this);
Element html = tb.getStack().getFirst();
for (Attribute attribute : startTag.getAttributes()) {
if (!html.hasAttr(attribute.getKey()))
html.attributes().put(attribute);
}
} else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title")) {
return tb.process(t, InHead);
} else if (name.equals("body")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
return false;
} else {
tb.framesetOk(false);
Element body = stack.get(1);
for (Attribute attribute : startTag.getAttributes()) {
if (!body.hasAttr(attribute.getKey()))
body.attributes().put(attribute);
}
}
} else if (name.equals("frameset")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
return false;
} else if (!tb.framesetOk()) {
return false;
} else {
Element second = stack.get(1);
if (second.parent() != null)
second.remove();
while (stack.size() > 1)
stack.removeLast();
tb.insert(startTag);
tb.transition(InFrameset);
}
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl",
"fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol",
"p", "section", "summary", "ul")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) {
tb.error(this);
tb.pop();
}
tb.insert(startTag);
} else if (StringUtil.in(name, "pre", "listing")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
} else if (name.equals("form")) {
if (tb.getFormElement() != null) {
tb.error(this);
return false;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertForm(startTag, true);
} else if (name.equals("li")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (el.nodeName().equals("li")) {
tb.process(new Token.EndTag("li"));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "dd", "dt")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (StringUtil.in(el.nodeName(), "dd", "dt")) {
tb.process(new Token.EndTag(el.nodeName()));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (name.equals("plaintext")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.PLAINTEXT);
} else if (name.equals("button")) {
if (tb.inButtonScope("button")) {
tb.error(this);
tb.process(new Token.EndTag("button"));
tb.process(startTag);
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
}
} else if (name.equals("a")) {
if (tb.getActiveFormattingElement("a") != null) {
tb.error(this);
tb.process(new Token.EndTag("a"));
Element remainingA = tb.getFromStack("a");
if (remainingA != null) {
tb.removeFromActiveFormattingElements(remainingA);
tb.removeFromStack(remainingA);
}
}
tb.reconstructFormattingElements();
Element a = tb.insert(startTag);
tb.pushActiveFormattingElements(a);
} else if (StringUtil.in(name,
"b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) {
tb.reconstructFormattingElements();
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (name.equals("nobr")) {
tb.reconstructFormattingElements();
if (tb.inScope("nobr")) {
tb.error(this);
tb.process(new Token.EndTag("nobr"));
tb.reconstructFormattingElements();
}
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
} else if (name.equals("table")) {
if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InTable);
} else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) {
tb.reconstructFormattingElements();
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("input")) {
tb.reconstructFormattingElements();
Element el = tb.insertEmpty(startTag);
if (!el.attr("type").equalsIgnoreCase("hidden"))
tb.framesetOk(false);
} else if (StringUtil.in(name, "param", "source", "track")) {
tb.insertEmpty(startTag);
} else if (name.equals("hr")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("image")) {
startTag.name("img");
return tb.process(startTag);
} else if (name.equals("isindex")) {
tb.error(this);
if (tb.getFormElement() != null)
return false;
tb.tokeniser.acknowledgeSelfClosingFlag();
tb.process(new Token.StartTag("form"));
if (startTag.attributes.hasKey("action")) {
Element form = tb.getFormElement();
form.attr("action", startTag.attributes.get("action"));
}
tb.process(new Token.StartTag("hr"));
tb.process(new Token.StartTag("label"));
String prompt = startTag.attributes.hasKey("prompt") ?
startTag.attributes.get("prompt") :
"This is a searchable index. Enter search keywords: ";
tb.process(new Token.Character(prompt));
Attributes inputAttribs = new Attributes();
for (Attribute attr : startTag.attributes) {
if (!StringUtil.in(attr.getKey(), "name", "action", "prompt"))
inputAttribs.put(attr);
}
inputAttribs.put("name", "isindex");
tb.process(new Token.StartTag("input", inputAttribs));
tb.process(new Token.EndTag("label"));
tb.process(new Token.StartTag("hr"));
tb.process(new Token.EndTag("form"));
} else if (name.equals("textarea")) {
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.framesetOk(false);
tb.transition(Text);
} else if (name.equals("xmp")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.reconstructFormattingElements();
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("iframe")) {
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("noembed")) {
handleRawtext(startTag, tb);
} else if (name.equals("select")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
HtmlTreeBuilderState state = tb.state();
if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))
tb.transition(InSelectInTable);
else
tb.transition(InSelect);
} else if (StringUtil.in("optgroup", "option")) {
if (tb.currentElement().nodeName().equals("option"))
tb.process(new Token.EndTag("option"));
tb.reconstructFormattingElements();
tb.insert(startTag);
} else if (StringUtil.in("rp", "rt")) {
if (tb.inScope("ruby")) {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals("ruby")) {
tb.error(this);
tb.popStackToBefore("ruby");
}
tb.insert(startTag);
}
} else if (name.equals("math")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (name.equals("svg")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (StringUtil.in(name,
"caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) {
tb.error(this);
return false;
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
}
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
name = endTag.name();
if (name.equals("body")) {
if (!tb.inScope("body")) {
tb.error(this);
return false;
} else {
tb.transition(AfterBody);
}
} else if (name.equals("html")) {
boolean notIgnored = tb.process(new Token.EndTag("body"));
if (notIgnored)
return tb.process(endTag);
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div",
"dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu",
"nav", "ol", "pre", "section", "summary", "ul")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("form")) {
Element currentForm = tb.getFormElement();
tb.setFormElement(null);
if (currentForm == null || !tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.removeFromStack(currentForm);
}
} else if (name.equals("p")) {
if (!tb.inButtonScope(name)) {
tb.error(this);
tb.process(new Token.StartTag(name));
return tb.process(endTag);
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("li")) {
if (!tb.inListItemScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "dd", "dt")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6");
}
} else if (name.equals("sarcasm")) {
return anyOtherEndTag(t, tb);
} else if (StringUtil.in(name,
"a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) {
OUTER:
for (int i = 0; i < 8; i++) {
Element formatEl = tb.getActiveFormattingElement(name);
if (formatEl == null)
return anyOtherEndTag(t, tb);
else if (!tb.onStack(formatEl)) {
tb.error(this);
tb.removeFromActiveFormattingElements(formatEl);
return true;
} else if (!tb.inScope(formatEl.nodeName())) {
tb.error(this);
return false;
} else if (tb.currentElement() != formatEl)
tb.error(this);
Element furthestBlock = null;
Element commonAncestor = null;
boolean seenFormattingElement = false;
LinkedList<Element> stack = tb.getStack();
for (int si = 0; si < stack.size() && si < 64; si++) {
Element el = stack.get(si);
if (el == formatEl) {
commonAncestor = stack.get(si - 1);
seenFormattingElement = true;
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el;
break;
}
}
if (furthestBlock == null) {
tb.popStackToClose(formatEl.nodeName());
tb.removeFromActiveFormattingElements(formatEl);
return true;
}
Element node = furthestBlock;
Element lastNode = furthestBlock;
INNER:
for (int j = 0; j < 3; j++) {
if (tb.onStack(node))
node = tb.aboveOnStack(node);
if (!tb.isInActiveFormattingElements(node)) {
tb.removeFromStack(node);
continue INNER;
} else if (node == formatEl)
break INNER;
Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());
tb.replaceActiveFormattingElement(node, replacement);
tb.replaceOnStack(node, replacement);
node = replacement;
if (lastNode == furthestBlock) {
}
if (lastNode.parent() != null)
lastNode.remove();
node.appendChild(lastNode);
lastNode = node;
}
if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) {
if (lastNode.parent() != null)
lastNode.remove();
tb.insertInFosterParent(lastNode);
} else {
if (lastNode.parent() != null)
lastNode.remove();
commonAncestor.appendChild(lastNode);
}
Element adopter = new Element(formatEl.tag(), tb.getBaseUri());
adopter.attributes().addAll(formatEl.attributes());
Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);
for (Node childNode : childNodes) {
adopter.appendChild(childNode);
}
furthestBlock.appendChild(adopter);
tb.removeFromActiveFormattingElements(formatEl);
tb.removeFromStack(formatEl);
tb.insertOnStackAfter(furthestBlock, adopter);
}
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
if (!tb.inScope("name")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
}
} else if (name.equals("br")) {
tb.error(this);
tb.process(new Token.StartTag("br"));
return false;
} else {
return anyOtherEndTag(t, tb);
}
break;
case EOF:
break;
}
return true;
}
|
Lang-48 | public EqualsBuilder append(Object lhs, Object rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
Class lhsClass = lhs.getClass();
if (!lhsClass.isArray()) {
isEquals = lhs.equals(rhs);
} else if (lhs.getClass() != rhs.getClass()) {
this.setEquals(false);
}
else if (lhs instanceof long[]) {
append((long[]) lhs, (long[]) rhs);
} else if (lhs instanceof int[]) {
append((int[]) lhs, (int[]) rhs);
} else if (lhs instanceof short[]) {
append((short[]) lhs, (short[]) rhs);
} else if (lhs instanceof char[]) {
append((char[]) lhs, (char[]) rhs);
} else if (lhs instanceof byte[]) {
append((byte[]) lhs, (byte[]) rhs);
} else if (lhs instanceof double[]) {
append((double[]) lhs, (double[]) rhs);
} else if (lhs instanceof float[]) {
append((float[]) lhs, (float[]) rhs);
} else if (lhs instanceof boolean[]) {
append((boolean[]) lhs, (boolean[]) rhs);
} else {
append((Object[]) lhs, (Object[]) rhs);
}
return this;
}
| public EqualsBuilder append(Object lhs, Object rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
Class lhsClass = lhs.getClass();
if (!lhsClass.isArray()) {
if (lhs instanceof java.math.BigDecimal) {
isEquals = (((java.math.BigDecimal)lhs).compareTo(rhs) == 0);
} else {
isEquals = lhs.equals(rhs);
}
} else if (lhs.getClass() != rhs.getClass()) {
this.setEquals(false);
}
else if (lhs instanceof long[]) {
append((long[]) lhs, (long[]) rhs);
} else if (lhs instanceof int[]) {
append((int[]) lhs, (int[]) rhs);
} else if (lhs instanceof short[]) {
append((short[]) lhs, (short[]) rhs);
} else if (lhs instanceof char[]) {
append((char[]) lhs, (char[]) rhs);
} else if (lhs instanceof byte[]) {
append((byte[]) lhs, (byte[]) rhs);
} else if (lhs instanceof double[]) {
append((double[]) lhs, (double[]) rhs);
} else if (lhs instanceof float[]) {
append((float[]) lhs, (float[]) rhs);
} else if (lhs instanceof boolean[]) {
append((boolean[]) lhs, (boolean[]) rhs);
} else {
append((Object[]) lhs, (Object[]) rhs);
}
return this;
}
|
Chart-20 | public ValueMarker(double value, Paint paint, Stroke stroke,
Paint outlinePaint, Stroke outlineStroke, float alpha) {
super(paint, stroke, paint, stroke, alpha);
this.value = value;
}
| public ValueMarker(double value, Paint paint, Stroke stroke,
Paint outlinePaint, Stroke outlineStroke, float alpha) {
super(paint, stroke, outlinePaint, outlineStroke, alpha);
this.value = value;
}
|
Lang-45 | public static String abbreviate(String str, int lower, int upper, String appendToEnd) {
if (str == null) {
return null;
}
if (str.length() == 0) {
return StringUtils.EMPTY;
}
if (upper == -1 || upper > str.length()) {
upper = str.length();
}
if (upper < lower) {
upper = lower;
}
StringBuffer result = new StringBuffer();
int index = StringUtils.indexOf(str, " ", lower);
if (index == -1) {
result.append(str.substring(0, upper));
if (upper != str.length()) {
result.append(StringUtils.defaultString(appendToEnd));
}
} else if (index > upper) {
result.append(str.substring(0, upper));
result.append(StringUtils.defaultString(appendToEnd));
} else {
result.append(str.substring(0, index));
result.append(StringUtils.defaultString(appendToEnd));
}
return result.toString();
}
| public static String abbreviate(String str, int lower, int upper, String appendToEnd) {
if (str == null) {
return null;
}
if (str.length() == 0) {
return StringUtils.EMPTY;
}
if (lower > str.length()) {
lower = str.length();
}
if (upper == -1 || upper > str.length()) {
upper = str.length();
}
if (upper < lower) {
upper = lower;
}
StringBuffer result = new StringBuffer();
int index = StringUtils.indexOf(str, " ", lower);
if (index == -1) {
result.append(str.substring(0, upper));
if (upper != str.length()) {
result.append(StringUtils.defaultString(appendToEnd));
}
} else if (index > upper) {
result.append(str.substring(0, upper));
result.append(StringUtils.defaultString(appendToEnd));
} else {
result.append(str.substring(0, index));
result.append(StringUtils.defaultString(appendToEnd));
}
return result.toString();
}
|
Codec-7 | public static String encodeBase64String(byte[] binaryData) {
return StringUtils.newStringUtf8(encodeBase64(binaryData, true));
}
| public static String encodeBase64String(byte[] binaryData) {
return StringUtils.newStringUtf8(encodeBase64(binaryData, false));
}
|
Gson-2 | public static <T1> TypeAdapterFactory newTypeHierarchyFactory(
final Class<T1> clazz, final TypeAdapter<T1> typeAdapter) {
return new TypeAdapterFactory() {
@SuppressWarnings("unchecked")
public <T2> TypeAdapter<T2> create(Gson gson, TypeToken<T2> typeToken) {
final Class<? super T2> requestedType = typeToken.getRawType();
if (!clazz.isAssignableFrom(requestedType)) {
return null;
}
return (TypeAdapter<T2>) typeAdapter;
}
@Override public String toString() {
return "Factory[typeHierarchy=" + clazz.getName() + ",adapter=" + typeAdapter + "]";
}
};
}
| public static <T1> TypeAdapterFactory newTypeHierarchyFactory(
final Class<T1> clazz, final TypeAdapter<T1> typeAdapter) {
return new TypeAdapterFactory() {
@SuppressWarnings("unchecked")
public <T2> TypeAdapter<T2> create(Gson gson, TypeToken<T2> typeToken) {
final Class<? super T2> requestedType = typeToken.getRawType();
if (!clazz.isAssignableFrom(requestedType)) {
return null;
}
return (TypeAdapter<T2>) new TypeAdapter<T1>() {
@Override public void write(JsonWriter out, T1 value) throws IOException {
typeAdapter.write(out, value);
}
@Override public T1 read(JsonReader in) throws IOException {
T1 result = typeAdapter.read(in);
if (result != null && !requestedType.isInstance(result)) {
throw new JsonSyntaxException("Expected a " + requestedType.getName()
+ " but was " + result.getClass().getName());
}
return result;
}
};
}
@Override public String toString() {
return "Factory[typeHierarchy=" + clazz.getName() + ",adapter=" + typeAdapter + "]";
}
};
}
|
Chart-5 | public XYDataItem addOrUpdate(Number x, Number y) {
if (x == null) {
throw new IllegalArgumentException("Null 'x' argument.");
}
XYDataItem overwritten = null;
int index = indexOf(x);
if (index >= 0 && !this.allowDuplicateXValues) {
XYDataItem existing = (XYDataItem) this.data.get(index);
try {
overwritten = (XYDataItem) existing.clone();
}
catch (CloneNotSupportedException e) {
throw new SeriesException("Couldn't clone XYDataItem!");
}
existing.setY(y);
}
else {
if (this.autoSort) {
this.data.add(-index - 1, new XYDataItem(x, y));
}
else {
this.data.add(new XYDataItem(x, y));
}
if (getItemCount() > this.maximumItemCount) {
this.data.remove(0);
}
}
fireSeriesChanged();
return overwritten;
}
| public XYDataItem addOrUpdate(Number x, Number y) {
if (x == null) {
throw new IllegalArgumentException("Null 'x' argument.");
}
if (this.allowDuplicateXValues) {
add(x, y);
return null;
}
XYDataItem overwritten = null;
int index = indexOf(x);
if (index >= 0) {
XYDataItem existing = (XYDataItem) this.data.get(index);
try {
overwritten = (XYDataItem) existing.clone();
}
catch (CloneNotSupportedException e) {
throw new SeriesException("Couldn't clone XYDataItem!");
}
existing.setY(y);
}
else {
if (this.autoSort) {
this.data.add(-index - 1, new XYDataItem(x, y));
}
else {
this.data.add(new XYDataItem(x, y));
}
if (getItemCount() > this.maximumItemCount) {
this.data.remove(0);
}
}
fireSeriesChanged();
return overwritten;
}
|
Closure-5 | private boolean isInlinableObject(List<Reference> refs) {
boolean ret = false;
Set<String> validProperties = Sets.newHashSet();
for (Reference ref : refs) {
Node name = ref.getNode();
Node parent = ref.getParent();
Node gramps = ref.getGrandparent();
if (parent.isGetProp()) {
Preconditions.checkState(parent.getFirstChild() == name);
if (gramps.isCall()
&& gramps.getFirstChild() == parent) {
return false;
}
String propName = parent.getLastChild().getString();
if (!validProperties.contains(propName)) {
if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) {
validProperties.add(propName);
} else {
return false;
}
}
continue;
}
if (!isVarOrAssignExprLhs(name)) {
return false;
}
Node val = ref.getAssignedValue();
if (val == null) {
continue;
}
if (!val.isObjectLit()) {
return false;
}
for (Node child = val.getFirstChild(); child != null;
child = child.getNext()) {
if (child.isGetterDef() ||
child.isSetterDef()) {
return false;
}
validProperties.add(child.getString());
Node childVal = child.getFirstChild();
for (Reference t : refs) {
Node refNode = t.getParent();
while (!NodeUtil.isStatementBlock(refNode)) {
if (refNode == childVal) {
return false;
}
refNode = refNode.getParent();
}
}
}
ret = true;
}
return ret;
}
| private boolean isInlinableObject(List<Reference> refs) {
boolean ret = false;
Set<String> validProperties = Sets.newHashSet();
for (Reference ref : refs) {
Node name = ref.getNode();
Node parent = ref.getParent();
Node gramps = ref.getGrandparent();
if (parent.isGetProp()) {
Preconditions.checkState(parent.getFirstChild() == name);
if (gramps.isCall()
&& gramps.getFirstChild() == parent) {
return false;
}
if (gramps.isDelProp()) {
return false;
}
String propName = parent.getLastChild().getString();
if (!validProperties.contains(propName)) {
if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) {
validProperties.add(propName);
} else {
return false;
}
}
continue;
}
if (!isVarOrAssignExprLhs(name)) {
return false;
}
Node val = ref.getAssignedValue();
if (val == null) {
continue;
}
if (!val.isObjectLit()) {
return false;
}
for (Node child = val.getFirstChild(); child != null;
child = child.getNext()) {
if (child.isGetterDef() ||
child.isSetterDef()) {
return false;
}
validProperties.add(child.getString());
Node childVal = child.getFirstChild();
for (Reference t : refs) {
Node refNode = t.getParent();
while (!NodeUtil.isStatementBlock(refNode)) {
if (refNode == childVal) {
return false;
}
refNode = refNode.getParent();
}
}
}
ret = true;
}
return ret;
}
|
Math-64 | protected VectorialPointValuePair doOptimize()
throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {
solvedCols = Math.min(rows, cols);
diagR = new double[cols];
jacNorm = new double[cols];
beta = new double[cols];
permutation = new int[cols];
lmDir = new double[cols];
double delta = 0;
double xNorm = 0;
double[] diag = new double[cols];
double[] oldX = new double[cols];
double[] oldRes = new double[rows];
double[] work1 = new double[cols];
double[] work2 = new double[cols];
double[] work3 = new double[cols];
updateResidualsAndCost();
lmPar = 0;
boolean firstIteration = true;
VectorialPointValuePair current = new VectorialPointValuePair(point, objective);
while (true) {
incrementIterationsCounter();
VectorialPointValuePair previous = current;
updateJacobian();
qrDecomposition();
qTy(residuals);
for (int k = 0; k < solvedCols; ++k) {
int pk = permutation[k];
jacobian[k][pk] = diagR[pk];
}
if (firstIteration) {
xNorm = 0;
for (int k = 0; k < cols; ++k) {
double dk = jacNorm[k];
if (dk == 0) {
dk = 1.0;
}
double xk = dk * point[k];
xNorm += xk * xk;
diag[k] = dk;
}
xNorm = Math.sqrt(xNorm);
delta = (xNorm == 0) ? initialStepBoundFactor : (initialStepBoundFactor * xNorm);
}
double maxCosine = 0;
if (cost != 0) {
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double s = jacNorm[pj];
if (s != 0) {
double sum = 0;
for (int i = 0; i <= j; ++i) {
sum += jacobian[i][pj] * residuals[i];
}
maxCosine = Math.max(maxCosine, Math.abs(sum) / (s * cost));
}
}
}
if (maxCosine <= orthoTolerance) {
return current;
}
for (int j = 0; j < cols; ++j) {
diag[j] = Math.max(diag[j], jacNorm[j]);
}
for (double ratio = 0; ratio < 1.0e-4;) {
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
oldX[pj] = point[pj];
}
double previousCost = cost;
double[] tmpVec = residuals;
residuals = oldRes;
oldRes = tmpVec;
determineLMParameter(oldRes, delta, diag, work1, work2, work3);
double lmNorm = 0;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
lmDir[pj] = -lmDir[pj];
point[pj] = oldX[pj] + lmDir[pj];
double s = diag[pj] * lmDir[pj];
lmNorm += s * s;
}
lmNorm = Math.sqrt(lmNorm);
if (firstIteration) {
delta = Math.min(delta, lmNorm);
}
updateResidualsAndCost();
current = new VectorialPointValuePair(point, objective);
double actRed = -1.0;
if (0.1 * cost < previousCost) {
double r = cost / previousCost;
actRed = 1.0 - r * r;
}
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double dirJ = lmDir[pj];
work1[j] = 0;
for (int i = 0; i <= j; ++i) {
work1[i] += jacobian[i][pj] * dirJ;
}
}
double coeff1 = 0;
for (int j = 0; j < solvedCols; ++j) {
coeff1 += work1[j] * work1[j];
}
double pc2 = previousCost * previousCost;
coeff1 = coeff1 / pc2;
double coeff2 = lmPar * lmNorm * lmNorm / pc2;
double preRed = coeff1 + 2 * coeff2;
double dirDer = -(coeff1 + coeff2);
ratio = (preRed == 0) ? 0 : (actRed / preRed);
if (ratio <= 0.25) {
double tmp =
(actRed < 0) ? (0.5 * dirDer / (dirDer + 0.5 * actRed)) : 0.5;
if ((0.1 * cost >= previousCost) || (tmp < 0.1)) {
tmp = 0.1;
}
delta = tmp * Math.min(delta, 10.0 * lmNorm);
lmPar /= tmp;
} else if ((lmPar == 0) || (ratio >= 0.75)) {
delta = 2 * lmNorm;
lmPar *= 0.5;
}
if (ratio >= 1.0e-4) {
firstIteration = false;
xNorm = 0;
for (int k = 0; k < cols; ++k) {
double xK = diag[k] * point[k];
xNorm += xK * xK;
}
xNorm = Math.sqrt(xNorm);
} else {
cost = previousCost;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
point[pj] = oldX[pj];
}
tmpVec = residuals;
residuals = oldRes;
oldRes = tmpVec;
}
if (checker==null) {
if (((Math.abs(actRed) <= costRelativeTolerance) &&
(preRed <= costRelativeTolerance) &&
(ratio <= 2.0)) ||
(delta <= parRelativeTolerance * xNorm)) {
return current;
}
} else {
if (checker.converged(getIterations(), previous, current)) {
return current;
}
}
if ((Math.abs(actRed) <= 2.2204e-16) && (preRed <= 2.2204e-16) && (ratio <= 2.0)) {
throw new OptimizationException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE,
costRelativeTolerance);
} else if (delta <= 2.2204e-16 * xNorm) {
throw new OptimizationException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE,
parRelativeTolerance);
} else if (maxCosine <= 2.2204e-16) {
throw new OptimizationException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE,
orthoTolerance);
}
}
}
}
| protected VectorialPointValuePair doOptimize()
throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {
solvedCols = Math.min(rows, cols);
diagR = new double[cols];
jacNorm = new double[cols];
beta = new double[cols];
permutation = new int[cols];
lmDir = new double[cols];
double delta = 0;
double xNorm = 0;
double[] diag = new double[cols];
double[] oldX = new double[cols];
double[] oldRes = new double[rows];
double[] oldObj = new double[rows];
double[] qtf = new double[rows];
double[] work1 = new double[cols];
double[] work2 = new double[cols];
double[] work3 = new double[cols];
updateResidualsAndCost();
lmPar = 0;
boolean firstIteration = true;
VectorialPointValuePair current = new VectorialPointValuePair(point, objective);
while (true) {
for (int i=0;i<rows;i++) {
qtf[i]=residuals[i];
}
incrementIterationsCounter();
VectorialPointValuePair previous = current;
updateJacobian();
qrDecomposition();
qTy(qtf);
for (int k = 0; k < solvedCols; ++k) {
int pk = permutation[k];
jacobian[k][pk] = diagR[pk];
}
if (firstIteration) {
xNorm = 0;
for (int k = 0; k < cols; ++k) {
double dk = jacNorm[k];
if (dk == 0) {
dk = 1.0;
}
double xk = dk * point[k];
xNorm += xk * xk;
diag[k] = dk;
}
xNorm = Math.sqrt(xNorm);
delta = (xNorm == 0) ? initialStepBoundFactor : (initialStepBoundFactor * xNorm);
}
double maxCosine = 0;
if (cost != 0) {
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double s = jacNorm[pj];
if (s != 0) {
double sum = 0;
for (int i = 0; i <= j; ++i) {
sum += jacobian[i][pj] * qtf[i];
}
maxCosine = Math.max(maxCosine, Math.abs(sum) / (s * cost));
}
}
}
if (maxCosine <= orthoTolerance) {
updateResidualsAndCost();
current = new VectorialPointValuePair(point, objective);
return current;
}
for (int j = 0; j < cols; ++j) {
diag[j] = Math.max(diag[j], jacNorm[j]);
}
for (double ratio = 0; ratio < 1.0e-4;) {
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
oldX[pj] = point[pj];
}
double previousCost = cost;
double[] tmpVec = residuals;
residuals = oldRes;
oldRes = tmpVec;
tmpVec = objective;
objective = oldObj;
oldObj = tmpVec;
determineLMParameter(qtf, delta, diag, work1, work2, work3);
double lmNorm = 0;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
lmDir[pj] = -lmDir[pj];
point[pj] = oldX[pj] + lmDir[pj];
double s = diag[pj] * lmDir[pj];
lmNorm += s * s;
}
lmNorm = Math.sqrt(lmNorm);
if (firstIteration) {
delta = Math.min(delta, lmNorm);
}
updateResidualsAndCost();
double actRed = -1.0;
if (0.1 * cost < previousCost) {
double r = cost / previousCost;
actRed = 1.0 - r * r;
}
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double dirJ = lmDir[pj];
work1[j] = 0;
for (int i = 0; i <= j; ++i) {
work1[i] += jacobian[i][pj] * dirJ;
}
}
double coeff1 = 0;
for (int j = 0; j < solvedCols; ++j) {
coeff1 += work1[j] * work1[j];
}
double pc2 = previousCost * previousCost;
coeff1 = coeff1 / pc2;
double coeff2 = lmPar * lmNorm * lmNorm / pc2;
double preRed = coeff1 + 2 * coeff2;
double dirDer = -(coeff1 + coeff2);
ratio = (preRed == 0) ? 0 : (actRed / preRed);
if (ratio <= 0.25) {
double tmp =
(actRed < 0) ? (0.5 * dirDer / (dirDer + 0.5 * actRed)) : 0.5;
if ((0.1 * cost >= previousCost) || (tmp < 0.1)) {
tmp = 0.1;
}
delta = tmp * Math.min(delta, 10.0 * lmNorm);
lmPar /= tmp;
} else if ((lmPar == 0) || (ratio >= 0.75)) {
delta = 2 * lmNorm;
lmPar *= 0.5;
}
if (ratio >= 1.0e-4) {
firstIteration = false;
xNorm = 0;
for (int k = 0; k < cols; ++k) {
double xK = diag[k] * point[k];
xNorm += xK * xK;
}
xNorm = Math.sqrt(xNorm);
current = new VectorialPointValuePair(point, objective);
if (checker != null) {
if (checker.converged(getIterations(), previous, current)) {
return current;
}
}
} else {
cost = previousCost;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
point[pj] = oldX[pj];
}
tmpVec = residuals;
residuals = oldRes;
oldRes = tmpVec;
tmpVec = objective;
objective = oldObj;
oldObj = tmpVec;
}
if (checker==null) {
if (((Math.abs(actRed) <= costRelativeTolerance) &&
(preRed <= costRelativeTolerance) &&
(ratio <= 2.0)) ||
(delta <= parRelativeTolerance * xNorm)) {
return current;
}
}
if ((Math.abs(actRed) <= 2.2204e-16) && (preRed <= 2.2204e-16) && (ratio <= 2.0)) {
throw new OptimizationException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE,
costRelativeTolerance);
} else if (delta <= 2.2204e-16 * xNorm) {
throw new OptimizationException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE,
parRelativeTolerance);
} else if (maxCosine <= 2.2204e-16) {
throw new OptimizationException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE,
orthoTolerance);
}
}
}
}
|
Mockito-22 | public static boolean areEqual(Object o1, Object o2) {
if (o1 == null || o2 == null) {
return o1 == null && o2 == null;
} else if (isArray(o1)) {
return isArray(o2) && areArraysEqual(o1, o2);
} else {
return o1.equals(o2);
}
}
| public static boolean areEqual(Object o1, Object o2) {
if (o1 == o2 ) {
return true;
} else if (o1 == null || o2 == null) {
return o1 == null && o2 == null;
} else if (isArray(o1)) {
return isArray(o2) && areArraysEqual(o1, o2);
} else {
return o1.equals(o2);
}
}
|
JacksonXml-1 | public JsonToken nextToken() throws IOException
{
_binaryValue = null;
if (_nextToken != null) {
JsonToken t = _nextToken;
_currToken = t;
_nextToken = null;
switch (t) {
case START_OBJECT:
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
break;
case START_ARRAY:
_parsingContext = _parsingContext.createChildArrayContext(-1, -1);
break;
case END_OBJECT:
case END_ARRAY:
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
break;
case FIELD_NAME:
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
break;
default:
}
return t;
}
int token = _xmlTokens.next();
while (token == XmlTokenStream.XML_START_ELEMENT) {
if (_mayBeLeaf) {
_nextToken = JsonToken.FIELD_NAME;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
if (_parsingContext.inArray()) {
token = _xmlTokens.next();
_mayBeLeaf = true;
continue;
}
String name = _xmlTokens.getLocalName();
_parsingContext.setCurrentName(name);
if (_namesToWrap != null && _namesToWrap.contains(name)) {
_xmlTokens.repeatStartElement();
}
_mayBeLeaf = true;
return (_currToken = JsonToken.FIELD_NAME);
}
switch (token) {
case XmlTokenStream.XML_END_ELEMENT:
if (_mayBeLeaf) {
_mayBeLeaf = false;
return (_currToken = JsonToken.VALUE_NULL);
}
_currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
case XmlTokenStream.XML_ATTRIBUTE_NAME:
if (_mayBeLeaf) {
_mayBeLeaf = false;
_nextToken = JsonToken.FIELD_NAME;
_currText = _xmlTokens.getText();
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
return (_currToken = JsonToken.FIELD_NAME);
case XmlTokenStream.XML_ATTRIBUTE_VALUE:
_currText = _xmlTokens.getText();
return (_currToken = JsonToken.VALUE_STRING);
case XmlTokenStream.XML_TEXT:
_currText = _xmlTokens.getText();
if (_mayBeLeaf) {
_mayBeLeaf = false;
_xmlTokens.skipEndElement();
if (_parsingContext.inArray()) {
if (_isEmpty(_currText)) {
_currToken = JsonToken.END_ARRAY;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
}
}
return (_currToken = JsonToken.VALUE_STRING);
} else {
if (_parsingContext.inObject()
&& (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) {
_currToken = JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
}
}
_parsingContext.setCurrentName(_cfgNameForTextElement);
_nextToken = JsonToken.VALUE_STRING;
return (_currToken = JsonToken.FIELD_NAME);
case XmlTokenStream.XML_END:
return (_currToken = null);
}
_throwInternal();
return null;
}
| public JsonToken nextToken() throws IOException
{
_binaryValue = null;
if (_nextToken != null) {
JsonToken t = _nextToken;
_currToken = t;
_nextToken = null;
switch (t) {
case START_OBJECT:
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
break;
case START_ARRAY:
_parsingContext = _parsingContext.createChildArrayContext(-1, -1);
break;
case END_OBJECT:
case END_ARRAY:
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
break;
case FIELD_NAME:
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
break;
default:
}
return t;
}
int token = _xmlTokens.next();
while (token == XmlTokenStream.XML_START_ELEMENT) {
if (_mayBeLeaf) {
_nextToken = JsonToken.FIELD_NAME;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
if (_parsingContext.inArray()) {
token = _xmlTokens.next();
_mayBeLeaf = true;
continue;
}
String name = _xmlTokens.getLocalName();
_parsingContext.setCurrentName(name);
if (_namesToWrap != null && _namesToWrap.contains(name)) {
_xmlTokens.repeatStartElement();
}
_mayBeLeaf = true;
return (_currToken = JsonToken.FIELD_NAME);
}
switch (token) {
case XmlTokenStream.XML_END_ELEMENT:
if (_mayBeLeaf) {
_mayBeLeaf = false;
if (_parsingContext.inArray()) {
_nextToken = JsonToken.END_OBJECT;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
return (_currToken = JsonToken.VALUE_NULL);
}
_currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
case XmlTokenStream.XML_ATTRIBUTE_NAME:
if (_mayBeLeaf) {
_mayBeLeaf = false;
_nextToken = JsonToken.FIELD_NAME;
_currText = _xmlTokens.getText();
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
return (_currToken = JsonToken.FIELD_NAME);
case XmlTokenStream.XML_ATTRIBUTE_VALUE:
_currText = _xmlTokens.getText();
return (_currToken = JsonToken.VALUE_STRING);
case XmlTokenStream.XML_TEXT:
_currText = _xmlTokens.getText();
if (_mayBeLeaf) {
_mayBeLeaf = false;
_xmlTokens.skipEndElement();
if (_parsingContext.inArray()) {
if (_isEmpty(_currText)) {
_nextToken = JsonToken.END_OBJECT;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
}
return (_currToken = JsonToken.VALUE_STRING);
} else {
if (_parsingContext.inObject()
&& (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) {
_currToken = JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
}
}
_parsingContext.setCurrentName(_cfgNameForTextElement);
_nextToken = JsonToken.VALUE_STRING;
return (_currToken = JsonToken.FIELD_NAME);
case XmlTokenStream.XML_END:
return (_currToken = null);
}
_throwInternal();
return null;
}
|
Gson-15 | public JsonWriter value(double value) throws IOException {
writeDeferredName();
if (Double.isNaN(value) || Double.isInfinite(value)) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
beforeValue();
out.append(Double.toString(value));
return this;
}
| public JsonWriter value(double value) throws IOException {
writeDeferredName();
if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
beforeValue();
out.append(Double.toString(value));
return this;
}
|
Math-74 | public double integrate(final FirstOrderDifferentialEquations equations,
final double t0, final double[] y0,
final double t, final double[] y)
throws DerivativeException, IntegratorException {
sanityChecks(equations, t0, y0, t, y);
setEquations(equations);
resetEvaluations();
final boolean forward = t > t0;
final int stages = c.length + 1;
if (y != y0) {
System.arraycopy(y0, 0, y, 0, y0.length);
}
final double[][] yDotK = new double[stages][y0.length];
final double[] yTmp = new double[y0.length];
AbstractStepInterpolator interpolator;
if (requiresDenseOutput() || (! eventsHandlersManager.isEmpty())) {
final RungeKuttaStepInterpolator rki = (RungeKuttaStepInterpolator) prototype.copy();
rki.reinitialize(this, yTmp, yDotK, forward);
interpolator = rki;
} else {
interpolator = new DummyStepInterpolator(yTmp, forward);
}
interpolator.storeTime(t0);
stepStart = t0;
double hNew = 0;
boolean firstTime = true;
for (StepHandler handler : stepHandlers) {
handler.reset();
}
CombinedEventsManager manager = addEndTimeChecker(t0, t, eventsHandlersManager);
boolean lastStep = false;
while (!lastStep) {
interpolator.shift();
double error = 0;
for (boolean loop = true; loop;) {
if (firstTime || !fsal) {
computeDerivatives(stepStart, y, yDotK[0]);
}
if (firstTime) {
final double[] scale;
if (vecAbsoluteTolerance == null) {
scale = new double[y0.length];
java.util.Arrays.fill(scale, scalAbsoluteTolerance);
} else {
scale = vecAbsoluteTolerance;
}
hNew = initializeStep(equations, forward, getOrder(), scale,
stepStart, y, yDotK[0], yTmp, yDotK[1]);
firstTime = false;
}
stepSize = hNew;
for (int k = 1; k < stages; ++k) {
for (int j = 0; j < y0.length; ++j) {
double sum = a[k-1][0] * yDotK[0][j];
for (int l = 1; l < k; ++l) {
sum += a[k-1][l] * yDotK[l][j];
}
yTmp[j] = y[j] + stepSize * sum;
}
computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]);
}
for (int j = 0; j < y0.length; ++j) {
double sum = b[0] * yDotK[0][j];
for (int l = 1; l < stages; ++l) {
sum += b[l] * yDotK[l][j];
}
yTmp[j] = y[j] + stepSize * sum;
}
error = estimateError(yDotK, y, yTmp, stepSize);
if (error <= 1.0) {
interpolator.storeTime(stepStart + stepSize);
if (manager.evaluateStep(interpolator)) {
final double dt = manager.getEventTime() - stepStart;
if (Math.abs(dt) <= Math.ulp(stepStart)) {
loop = false;
} else {
hNew = dt;
}
} else {
loop = false;
}
} else {
final double factor =
Math.min(maxGrowth,
Math.max(minReduction, safety * Math.pow(error, exp)));
hNew = filterStep(stepSize * factor, forward, false);
}
}
final double nextStep = stepStart + stepSize;
System.arraycopy(yTmp, 0, y, 0, y0.length);
manager.stepAccepted(nextStep, y);
lastStep = manager.stop();
interpolator.storeTime(nextStep);
for (StepHandler handler : stepHandlers) {
handler.handleStep(interpolator, lastStep);
}
stepStart = nextStep;
if (fsal) {
System.arraycopy(yDotK[stages - 1], 0, yDotK[0], 0, y0.length);
}
if (manager.reset(stepStart, y) && ! lastStep) {
computeDerivatives(stepStart, y, yDotK[0]);
}
if (! lastStep) {
stepSize = filterStep(stepSize, forward, true);
final double factor = Math.min(maxGrowth,
Math.max(minReduction,
safety * Math.pow(error, exp)));
final double scaledH = stepSize * factor;
final double nextT = stepStart + scaledH;
final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);
hNew = filterStep(scaledH, forward, nextIsLast);
}
}
final double stopTime = stepStart;
resetInternalState();
return stopTime;
}
| public double integrate(final FirstOrderDifferentialEquations equations,
final double t0, final double[] y0,
final double t, final double[] y)
throws DerivativeException, IntegratorException {
sanityChecks(equations, t0, y0, t, y);
setEquations(equations);
resetEvaluations();
final boolean forward = t > t0;
final int stages = c.length + 1;
if (y != y0) {
System.arraycopy(y0, 0, y, 0, y0.length);
}
final double[][] yDotK = new double[stages][y0.length];
final double[] yTmp = new double[y0.length];
AbstractStepInterpolator interpolator;
if (requiresDenseOutput() || (! eventsHandlersManager.isEmpty())) {
final RungeKuttaStepInterpolator rki = (RungeKuttaStepInterpolator) prototype.copy();
rki.reinitialize(this, yTmp, yDotK, forward);
interpolator = rki;
} else {
interpolator = new DummyStepInterpolator(yTmp, forward);
}
interpolator.storeTime(t0);
stepStart = t0;
double hNew = 0;
boolean firstTime = true;
for (StepHandler handler : stepHandlers) {
handler.reset();
}
CombinedEventsManager manager = addEndTimeChecker(t0, t, eventsHandlersManager);
boolean lastStep = false;
while (!lastStep) {
interpolator.shift();
double error = 0;
for (boolean loop = true; loop;) {
if (firstTime || !fsal) {
computeDerivatives(stepStart, y, yDotK[0]);
}
if (firstTime) {
final double[] scale = new double[y0.length];
if (vecAbsoluteTolerance == null) {
for (int i = 0; i < scale.length; ++i) {
scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * Math.abs(y[i]);
}
} else {
for (int i = 0; i < scale.length; ++i) {
scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * Math.abs(y[i]);
}
}
hNew = initializeStep(equations, forward, getOrder(), scale,
stepStart, y, yDotK[0], yTmp, yDotK[1]);
firstTime = false;
}
stepSize = hNew;
for (int k = 1; k < stages; ++k) {
for (int j = 0; j < y0.length; ++j) {
double sum = a[k-1][0] * yDotK[0][j];
for (int l = 1; l < k; ++l) {
sum += a[k-1][l] * yDotK[l][j];
}
yTmp[j] = y[j] + stepSize * sum;
}
computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]);
}
for (int j = 0; j < y0.length; ++j) {
double sum = b[0] * yDotK[0][j];
for (int l = 1; l < stages; ++l) {
sum += b[l] * yDotK[l][j];
}
yTmp[j] = y[j] + stepSize * sum;
}
error = estimateError(yDotK, y, yTmp, stepSize);
if (error <= 1.0) {
interpolator.storeTime(stepStart + stepSize);
if (manager.evaluateStep(interpolator)) {
final double dt = manager.getEventTime() - stepStart;
if (Math.abs(dt) <= Math.ulp(stepStart)) {
loop = false;
} else {
hNew = dt;
}
} else {
loop = false;
}
} else {
final double factor =
Math.min(maxGrowth,
Math.max(minReduction, safety * Math.pow(error, exp)));
hNew = filterStep(stepSize * factor, forward, false);
}
}
final double nextStep = stepStart + stepSize;
System.arraycopy(yTmp, 0, y, 0, y0.length);
manager.stepAccepted(nextStep, y);
lastStep = manager.stop();
interpolator.storeTime(nextStep);
for (StepHandler handler : stepHandlers) {
handler.handleStep(interpolator, lastStep);
}
stepStart = nextStep;
if (fsal) {
System.arraycopy(yDotK[stages - 1], 0, yDotK[0], 0, y0.length);
}
if (manager.reset(stepStart, y) && ! lastStep) {
computeDerivatives(stepStart, y, yDotK[0]);
}
if (! lastStep) {
stepSize = filterStep(stepSize, forward, true);
final double factor = Math.min(maxGrowth,
Math.max(minReduction,
safety * Math.pow(error, exp)));
final double scaledH = stepSize * factor;
final double nextT = stepStart + scaledH;
final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);
hNew = filterStep(scaledH, forward, nextIsLast);
}
}
final double stopTime = stepStart;
resetInternalState();
return stopTime;
}
|
Gson-11 | public Number read(JsonReader in) throws IOException {
JsonToken jsonToken = in.peek();
switch (jsonToken) {
case NULL:
in.nextNull();
return null;
case NUMBER:
return new LazilyParsedNumber(in.nextString());
default:
throw new JsonSyntaxException("Expecting number, got: " + jsonToken);
}
}
| public Number read(JsonReader in) throws IOException {
JsonToken jsonToken = in.peek();
switch (jsonToken) {
case NULL:
in.nextNull();
return null;
case NUMBER:
case STRING:
return new LazilyParsedNumber(in.nextString());
default:
throw new JsonSyntaxException("Expecting number, got: " + jsonToken);
}
}
|