bug_id
stringlengths
5
19
func_before
stringlengths
49
25.9k
func_after
stringlengths
45
26k
Chart-12
public MultiplePiePlot(CategoryDataset dataset) { super(); this.dataset = dataset; PiePlot piePlot = new PiePlot(null); this.pieChart = new JFreeChart(piePlot); this.pieChart.removeLegend(); this.dataExtractOrder = TableOrder.BY_COLUMN; this.pieChart.setBackgroundPaint(null); TextTitle seriesTitle = new TextTitle("Series Title", new Font("SansSerif", Font.BOLD, 12)); seriesTitle.setPosition(RectangleEdge.BOTTOM); this.pieChart.setTitle(seriesTitle); this.aggregatedItemsKey = "Other"; this.aggregatedItemsPaint = Color.lightGray; this.sectionPaints = new HashMap(); }
public MultiplePiePlot(CategoryDataset dataset) { super(); setDataset(dataset); PiePlot piePlot = new PiePlot(null); this.pieChart = new JFreeChart(piePlot); this.pieChart.removeLegend(); this.dataExtractOrder = TableOrder.BY_COLUMN; this.pieChart.setBackgroundPaint(null); TextTitle seriesTitle = new TextTitle("Series Title", new Font("SansSerif", Font.BOLD, 12)); seriesTitle.setPosition(RectangleEdge.BOTTOM); this.pieChart.setTitle(seriesTitle); this.aggregatedItemsKey = "Other"; this.aggregatedItemsPaint = Color.lightGray; this.sectionPaints = new HashMap(); }
Closure-125
private void visitNew(NodeTraversal t, Node n) { Node constructor = n.getFirstChild(); JSType type = getJSType(constructor).restrictByNotNullOrUndefined(); if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) { FunctionType fnType = type.toMaybeFunctionType(); if (fnType != null) { visitParameterList(t, n, fnType); ensureTyped(t, n, fnType.getInstanceType()); } else { ensureTyped(t, n); } } else { report(t, n, NOT_A_CONSTRUCTOR); ensureTyped(t, n); } }
private void visitNew(NodeTraversal t, Node n) { Node constructor = n.getFirstChild(); JSType type = getJSType(constructor).restrictByNotNullOrUndefined(); if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) { FunctionType fnType = type.toMaybeFunctionType(); if (fnType != null && fnType.hasInstanceType()) { visitParameterList(t, n, fnType); ensureTyped(t, n, fnType.getInstanceType()); } else { ensureTyped(t, n); } } else { report(t, n, NOT_A_CONSTRUCTOR); ensureTyped(t, n); } }
Lang-16
public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { } default : throw new NumberFormatException(str + " is not a valid number."); } } else { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { try { return createInteger(str); } catch (NumberFormatException nfe) { } try { return createLong(str); } catch (NumberFormatException nfe) { } return createBigInteger(str); } else { boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } return createBigDecimal(str); } } }
public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { return null; } if (str.startsWith("0x") || str.startsWith("-0x") || str.startsWith("0X") || str.startsWith("-0X")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { } default : throw new NumberFormatException(str + " is not a valid number."); } } else { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { try { return createInteger(str); } catch (NumberFormatException nfe) { } try { return createLong(str); } catch (NumberFormatException nfe) { } return createBigInteger(str); } else { boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } return createBigDecimal(str); } } }
Codec-4
public Base64() { this(false); }
public Base64() { this(0); }
JacksonDatabind-28
public ObjectNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (p.getCurrentToken() == JsonToken.START_OBJECT) { p.nextToken(); return deserializeObject(p, ctxt, ctxt.getNodeFactory()); } if (p.getCurrentToken() == JsonToken.FIELD_NAME) { return deserializeObject(p, ctxt, ctxt.getNodeFactory()); } throw ctxt.mappingException(ObjectNode.class); }
public ObjectNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (p.isExpectedStartObjectToken() || p.hasToken(JsonToken.FIELD_NAME)) { return deserializeObject(p, ctxt, ctxt.getNodeFactory()); } if (p.hasToken(JsonToken.END_OBJECT)) { return ctxt.getNodeFactory().objectNode(); } throw ctxt.mappingException(ObjectNode.class); }
JacksonDatabind-16
protected final boolean _add(Annotation ann) { if (_annotations == null) { _annotations = new HashMap<Class<? extends Annotation>,Annotation>(); } Annotation previous = _annotations.put(ann.annotationType(), ann); return (previous != null) && previous.equals(ann); }
protected final boolean _add(Annotation ann) { if (_annotations == null) { _annotations = new HashMap<Class<? extends Annotation>,Annotation>(); } Annotation previous = _annotations.put(ann.annotationType(), ann); return (previous == null) || !previous.equals(ann); }
JacksonDatabind-88
protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException { TypeFactory tf = ctxt.getTypeFactory(); if (id.indexOf('<') > 0) { JavaType t = tf.constructFromCanonical(id); return t; } Class<?> cls; try { cls = tf.findClass(id); } catch (ClassNotFoundException e) { if (ctxt instanceof DeserializationContext) { DeserializationContext dctxt = (DeserializationContext) ctxt; return dctxt.handleUnknownTypeId(_baseType, id, this, "no such class found"); } return null; } catch (Exception e) { throw new IllegalArgumentException("Invalid type id '"+id+"' (for id type 'Id.class'): "+e.getMessage(), e); } return tf.constructSpecializedType(_baseType, cls); }
protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException { TypeFactory tf = ctxt.getTypeFactory(); if (id.indexOf('<') > 0) { JavaType t = tf.constructFromCanonical(id); if (!t.isTypeOrSubTypeOf(_baseType.getRawClass())) { throw new IllegalArgumentException(String.format( "Class %s not subtype of %s", t.getRawClass().getName(), _baseType)); } return t; } Class<?> cls; try { cls = tf.findClass(id); } catch (ClassNotFoundException e) { if (ctxt instanceof DeserializationContext) { DeserializationContext dctxt = (DeserializationContext) ctxt; return dctxt.handleUnknownTypeId(_baseType, id, this, "no such class found"); } return null; } catch (Exception e) { throw new IllegalArgumentException("Invalid type id '"+id+"' (for id type 'Id.class'): "+e.getMessage(), e); } return tf.constructSpecializedType(_baseType, cls); }
Closure-35
private void inferPropertyTypesToMatchConstraint( JSType type, JSType constraint) { if (type == null || constraint == null) { return; } ObjectType constraintObj = ObjectType.cast(constraint.restrictByNotNullOrUndefined()); if (constraintObj != null && constraintObj.isRecordType()) { ObjectType objType = ObjectType.cast(type.restrictByNotNullOrUndefined()); if (objType != null) { for (String prop : constraintObj.getOwnPropertyNames()) { JSType propType = constraintObj.getPropertyType(prop); if (!objType.isPropertyTypeDeclared(prop)) { JSType typeToInfer = propType; if (!objType.hasProperty(prop)) { typeToInfer = getNativeType(VOID_TYPE).getLeastSupertype(propType); } objType.defineInferredProperty(prop, typeToInfer, null); } } } } }
private void inferPropertyTypesToMatchConstraint( JSType type, JSType constraint) { if (type == null || constraint == null) { return; } ObjectType constraintObj = ObjectType.cast(constraint.restrictByNotNullOrUndefined()); if (constraintObj != null) { type.matchConstraint(constraintObj); } }
Closure-19
protected void declareNameInScope(FlowScope scope, Node node, JSType type) { switch (node.getType()) { case Token.NAME: scope.inferSlotType(node.getString(), type); break; case Token.GETPROP: String qualifiedName = node.getQualifiedName(); Preconditions.checkNotNull(qualifiedName); JSType origType = node.getJSType(); origType = origType == null ? getNativeType(UNKNOWN_TYPE) : origType; scope.inferQualifiedSlot(node, qualifiedName, origType, type); break; default: throw new IllegalArgumentException("Node cannot be refined. \n" + node.toStringTree()); } }
protected void declareNameInScope(FlowScope scope, Node node, JSType type) { switch (node.getType()) { case Token.NAME: scope.inferSlotType(node.getString(), type); break; case Token.GETPROP: String qualifiedName = node.getQualifiedName(); Preconditions.checkNotNull(qualifiedName); JSType origType = node.getJSType(); origType = origType == null ? getNativeType(UNKNOWN_TYPE) : origType; scope.inferQualifiedSlot(node, qualifiedName, origType, type); break; case Token.THIS: break; default: throw new IllegalArgumentException("Node cannot be refined. \n" + node.toStringTree()); } }
Jsoup-76
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 (tb.framesetOk() && 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.normalName(); if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.processEndTag("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.inSorted(name, Constants.InBodyStartEmptyFormatters)) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (StringUtil.inSorted(name, Constants.InBodyStartPClosers)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("span")) { tb.reconstructFormattingElements(); tb.insert(startTag); } else if (name.equals("li")) { tb.framesetOk(false); ArrayList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.processEndTag("li"); break; } if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("html")) { tb.error(this); Element html = tb.getStack().get(0); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.inSorted(name, Constants.InBodyStartToHead)) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); ArrayList<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); ArrayList<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.remove(stack.size()-1); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.inSorted(name, Constants.Headings)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } if (StringUtil.inSorted(tb.currentElement().nodeName(), Constants.Headings)) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartPreListing)) { if (tb.inButtonScope("p")) { tb.processEndTag("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.processEndTag("p"); } tb.insertForm(startTag, true); } else if (StringUtil.inSorted(name, Constants.DdDt)) { tb.framesetOk(false); ArrayList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.inSorted(el.nodeName(), Constants.DdDt)) { tb.processEndTag(el.nodeName()); break; } if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); } else if (name.equals("button")) { if (tb.inButtonScope("button")) { tb.error(this); tb.processEndTag("button"); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (StringUtil.inSorted(name, Constants.Formatters)) { 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.processEndTag("nobr"); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) { 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.processEndTag("p"); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.inSorted(name, Constants.InBodyStartMedia)) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { if (tb.getFromStack("svg") == null) return tb.process(startTag.name("img")); else tb.insert(startTag); } else if (name.equals("isindex")) { tb.error(this); if (tb.getFormElement() != null) return false; tb.processStartTag("form"); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.processStartTag("hr"); tb.processStartTag("label"); String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character().data(prompt)); Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.inSorted(attr.getKey(), Constants.InBodyStartInputAttribs)) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.processStartTag("input", inputAttribs); tb.processEndTag("label"); tb.processStartTag("hr"); tb.processEndTag("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.processEndTag("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.inSorted(name, Constants.InBodyStartOptions)) { if (tb.currentElement().nodeName().equals("option")) tb.processEndTag("option"); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartRuby)) { 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); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartDrop)) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.normalName(); if (StringUtil.inSorted(name, Constants.InBodyEndAdoptionFormatters)) { 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; ArrayList<Element> stack = tb.getStack(); final int stackSize = stack.size(); for (int si = 0; si < stackSize && 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; for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { tb.removeFromStack(node); continue; } else if (node == formatEl) break; Element replacement = new Element(Tag.valueOf(node.nodeName(), ParseSettings.preserveCase), 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.inSorted(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) { 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.inSorted(name, Constants.InBodyEndClosers)) { 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("span")) { return anyOtherEndTag(t, tb); } 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 (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.processEndTag("body"); if (notIgnored) return tb.process(endTag); } 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.processStartTag(name); return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.inSorted(name, Constants.DdDt)) { 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.inSorted(name, Constants.Headings)) { if (!tb.inScope(Constants.Headings)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(Constants.Headings); } } else if (name.equals("sarcasm")) { return anyOtherEndTag(t, tb); } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) { 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.processStartTag("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 (tb.framesetOk() && 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.normalName(); if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.processEndTag("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.inSorted(name, Constants.InBodyStartEmptyFormatters)) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (StringUtil.inSorted(name, Constants.InBodyStartPClosers)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("span")) { tb.reconstructFormattingElements(); tb.insert(startTag); } else if (name.equals("li")) { tb.framesetOk(false); ArrayList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.processEndTag("li"); break; } if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("html")) { tb.error(this); Element html = tb.getStack().get(0); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.inSorted(name, Constants.InBodyStartToHead)) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); ArrayList<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); ArrayList<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.remove(stack.size()-1); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.inSorted(name, Constants.Headings)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } if (StringUtil.inSorted(tb.currentElement().nodeName(), Constants.Headings)) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartPreListing)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); tb.reader.matchConsume("\n"); tb.framesetOk(false); } else if (name.equals("form")) { if (tb.getFormElement() != null) { tb.error(this); return false; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insertForm(startTag, true); } else if (StringUtil.inSorted(name, Constants.DdDt)) { tb.framesetOk(false); ArrayList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.inSorted(el.nodeName(), Constants.DdDt)) { tb.processEndTag(el.nodeName()); break; } if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); } else if (name.equals("button")) { if (tb.inButtonScope("button")) { tb.error(this); tb.processEndTag("button"); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (StringUtil.inSorted(name, Constants.Formatters)) { 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.processEndTag("nobr"); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) { 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.processEndTag("p"); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.inSorted(name, Constants.InBodyStartMedia)) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { if (tb.getFromStack("svg") == null) return tb.process(startTag.name("img")); else tb.insert(startTag); } else if (name.equals("isindex")) { tb.error(this); if (tb.getFormElement() != null) return false; tb.processStartTag("form"); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.processStartTag("hr"); tb.processStartTag("label"); String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character().data(prompt)); Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.inSorted(attr.getKey(), Constants.InBodyStartInputAttribs)) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.processStartTag("input", inputAttribs); tb.processEndTag("label"); tb.processStartTag("hr"); tb.processEndTag("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.processEndTag("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.inSorted(name, Constants.InBodyStartOptions)) { if (tb.currentElement().nodeName().equals("option")) tb.processEndTag("option"); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartRuby)) { 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); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartDrop)) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.normalName(); if (StringUtil.inSorted(name, Constants.InBodyEndAdoptionFormatters)) { 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; ArrayList<Element> stack = tb.getStack(); final int stackSize = stack.size(); for (int si = 0; si < stackSize && 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; for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { tb.removeFromStack(node); continue; } else if (node == formatEl) break; Element replacement = new Element(Tag.valueOf(node.nodeName(), ParseSettings.preserveCase), 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.inSorted(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) { 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.inSorted(name, Constants.InBodyEndClosers)) { 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("span")) { return anyOtherEndTag(t, tb); } 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 (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.processEndTag("body"); if (notIgnored) return tb.process(endTag); } 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.processStartTag(name); return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.inSorted(name, Constants.DdDt)) { 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.inSorted(name, Constants.Headings)) { if (!tb.inScope(Constants.Headings)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(Constants.Headings); } } else if (name.equals("sarcasm")) { return anyOtherEndTag(t, tb); } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) { 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.processStartTag("br"); return false; } else { return anyOtherEndTag(t, tb); } break; case EOF: break; } return true; }
Jsoup-82
static Document parseInputStream(InputStream input, String charsetName, String baseUri, Parser parser) throws IOException { if (input == null) return new Document(baseUri); input = ConstrainableInputStream.wrap(input, bufferSize, 0); Document doc = null; boolean fullyRead = false; input.mark(bufferSize); ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); fullyRead = input.read() == -1; input.reset(); BomCharset bomCharset = detectCharsetFromBom(firstBytes); if (bomCharset != null) charsetName = bomCharset.charset; if (charsetName == null) { String docData = Charset.forName(defaultCharset).decode(firstBytes).toString(); doc = parser.parseInput(docData, baseUri); Elements metaElements = doc.select("meta[http-equiv=content-type], meta[charset]"); String foundCharset = null; for (Element meta : metaElements) { if (meta.hasAttr("http-equiv")) foundCharset = getCharsetFromContentType(meta.attr("content")); if (foundCharset == null && meta.hasAttr("charset")) foundCharset = meta.attr("charset"); if (foundCharset != null) break; } if (foundCharset == null && doc.childNodeSize() > 0) { Node first = doc.childNode(0); XmlDeclaration decl = null; if (first instanceof XmlDeclaration) decl = (XmlDeclaration) first; else if (first instanceof Comment) { Comment comment = (Comment) first; if (comment.isXmlDeclaration()) decl = comment.asXmlDeclaration(); } if (decl != null) { if (decl.name().equalsIgnoreCase("xml")) foundCharset = decl.attr("encoding"); } } foundCharset = validateCharset(foundCharset); if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharset)) { foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; doc = null; } else if (!fullyRead) { doc = null; } } else { Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); } if (doc == null) { if (charsetName == null) charsetName = defaultCharset; BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize); if (bomCharset != null && bomCharset.offset) reader.skip(1); try { doc = parser.parseInput(reader, baseUri); } catch (UncheckedIOException e) { throw e.ioException(); } Charset charset = Charset.forName(charsetName); doc.outputSettings().charset(charset); } input.close(); return doc; }
static Document parseInputStream(InputStream input, String charsetName, String baseUri, Parser parser) throws IOException { if (input == null) return new Document(baseUri); input = ConstrainableInputStream.wrap(input, bufferSize, 0); Document doc = null; boolean fullyRead = false; input.mark(bufferSize); ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); fullyRead = input.read() == -1; input.reset(); BomCharset bomCharset = detectCharsetFromBom(firstBytes); if (bomCharset != null) charsetName = bomCharset.charset; if (charsetName == null) { String docData = Charset.forName(defaultCharset).decode(firstBytes).toString(); doc = parser.parseInput(docData, baseUri); Elements metaElements = doc.select("meta[http-equiv=content-type], meta[charset]"); String foundCharset = null; for (Element meta : metaElements) { if (meta.hasAttr("http-equiv")) foundCharset = getCharsetFromContentType(meta.attr("content")); if (foundCharset == null && meta.hasAttr("charset")) foundCharset = meta.attr("charset"); if (foundCharset != null) break; } if (foundCharset == null && doc.childNodeSize() > 0) { Node first = doc.childNode(0); XmlDeclaration decl = null; if (first instanceof XmlDeclaration) decl = (XmlDeclaration) first; else if (first instanceof Comment) { Comment comment = (Comment) first; if (comment.isXmlDeclaration()) decl = comment.asXmlDeclaration(); } if (decl != null) { if (decl.name().equalsIgnoreCase("xml")) foundCharset = decl.attr("encoding"); } } foundCharset = validateCharset(foundCharset); if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharset)) { foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; doc = null; } else if (!fullyRead) { doc = null; } } else { Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); } if (doc == null) { if (charsetName == null) charsetName = defaultCharset; BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize); if (bomCharset != null && bomCharset.offset) reader.skip(1); try { doc = parser.parseInput(reader, baseUri); } catch (UncheckedIOException e) { throw e.ioException(); } Charset charset = Charset.forName(charsetName); doc.outputSettings().charset(charset); if (!charset.canEncode()) { doc.charset(Charset.forName(defaultCharset)); } } input.close(); return doc; }
Time-22
protected BasePeriod(long duration) { this(duration, null, null); }
protected BasePeriod(long duration) { super(); iType = PeriodType.time(); int[] values = ISOChronology.getInstanceUTC().get(this, duration); iType = PeriodType.standard(); iValues = new int[8]; System.arraycopy(values, 0, iValues, 4, 4); }
Closure-164
public boolean isSubtype(JSType other) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; if (!this.returnType.isSubtype(that.returnType)) { return false; } Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } return true; }
public boolean isSubtype(JSType other) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; if (!this.returnType.isSubtype(that.returnType)) { return false; } Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); boolean thisIsOptional = thisIsVarArgs || thisParam.isOptionalArg(); boolean thatIsOptional = thatIsVarArgs || thatParam.isOptionalArg(); if (!thisIsOptional && thatIsOptional) { boolean isTopFunction = thatIsVarArgs && (thatParamType == null || thatParamType.isUnknownType() || thatParamType.isNoType()); if (!isTopFunction) { return false; } } if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } if (thisParam != null && !thisParam.isOptionalArg() && !thisParam.isVarArgs() && thatParam == null) { return false; } return true; }
Math-11
public double density(final double[] vals) throws DimensionMismatchException { final int dim = getDimension(); if (vals.length != dim) { throw new DimensionMismatchException(vals.length, dim); } return FastMath.pow(2 * FastMath.PI, -dim / 2) * FastMath.pow(covarianceMatrixDeterminant, -0.5) * getExponentTerm(vals); }
public double density(final double[] vals) throws DimensionMismatchException { final int dim = getDimension(); if (vals.length != dim) { throw new DimensionMismatchException(vals.length, dim); } return FastMath.pow(2 * FastMath.PI, -0.5 * dim) * FastMath.pow(covarianceMatrixDeterminant, -0.5) * getExponentTerm(vals); }
Closure-160
public void initOptions(CompilerOptions options) { this.options = options; if (errorManager == null) { if (outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } if (options.checkGlobalThisLevel.isOn()) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } List<WarningsGuard> guards = Lists.newArrayList(); guards.add( new SuppressDocWarningsGuard( getDiagnosticGroups().getRegisteredGroups())); guards.add(options.getWarningsGuard()); if (!options.checkSymbols && (warningsGuard == null || !warningsGuard.disables( DiagnosticGroups.CHECK_VARIABLES))) { guards.add(new DiagnosticGroupWarningsGuard( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF)); } this.warningsGuard = new ComposeWarningsGuard(guards); }
public void initOptions(CompilerOptions options) { this.options = options; if (errorManager == null) { if (outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } if (options.checkGlobalThisLevel.isOn()) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } List<WarningsGuard> guards = Lists.newArrayList(); guards.add( new SuppressDocWarningsGuard( getDiagnosticGroups().getRegisteredGroups())); guards.add(options.getWarningsGuard()); ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards); if (!options.checkSymbols && !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) { composedGuards.addGuard(new DiagnosticGroupWarningsGuard( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF)); } this.warningsGuard = composedGuards; }
Closure-50
private Node tryFoldArrayJoin(Node n) { Node callTarget = n.getFirstChild(); if (callTarget == null || !NodeUtil.isGetProp(callTarget)) { return n; } Node right = callTarget.getNext(); if (right != null) { if (!NodeUtil.isImmutableValue(right)) { return n; } } Node arrayNode = callTarget.getFirstChild(); Node functionName = arrayNode.getNext(); if ((arrayNode.getType() != Token.ARRAYLIT) || !functionName.getString().equals("join")) { return n; } String joinString = (right == null) ? "," : NodeUtil.getStringValue(right); List<Node> arrayFoldedChildren = Lists.newLinkedList(); StringBuilder sb = null; int foldedSize = 0; Node prev = null; Node elem = arrayNode.getFirstChild(); while (elem != null) { if (NodeUtil.isImmutableValue(elem) || elem.getType() == Token.EMPTY) { if (sb == null) { sb = new StringBuilder(); } else { sb.append(joinString); } sb.append(NodeUtil.getArrayElementStringValue(elem)); } else { if (sb != null) { Preconditions.checkNotNull(prev); foldedSize += sb.length() + 2; arrayFoldedChildren.add( Node.newString(sb.toString()).copyInformationFrom(prev)); sb = null; } foldedSize += InlineCostEstimator.getCost(elem); arrayFoldedChildren.add(elem); } prev = elem; elem = elem.getNext(); } if (sb != null) { Preconditions.checkNotNull(prev); foldedSize += sb.length() + 2; arrayFoldedChildren.add( Node.newString(sb.toString()).copyInformationFrom(prev)); } foldedSize += arrayFoldedChildren.size() - 1; int originalSize = InlineCostEstimator.getCost(n); switch (arrayFoldedChildren.size()) { case 0: Node emptyStringNode = Node.newString(""); n.getParent().replaceChild(n, emptyStringNode); reportCodeChange(); return emptyStringNode; case 1: Node foldedStringNode = arrayFoldedChildren.remove(0); if (foldedSize > originalSize) { return n; } arrayNode.detachChildren(); if (foldedStringNode.getType() != Token.STRING) { Node replacement = new Node(Token.ADD, Node.newString("").copyInformationFrom(n), foldedStringNode); foldedStringNode = replacement; } n.getParent().replaceChild(n, foldedStringNode); reportCodeChange(); return foldedStringNode; default: if (arrayFoldedChildren.size() == arrayNode.getChildCount()) { return n; } int kJoinOverhead = "[].join()".length(); foldedSize += kJoinOverhead; foldedSize += (right != null) ? InlineCostEstimator.getCost(right) : 0; if (foldedSize > originalSize) { return n; } arrayNode.detachChildren(); for (Node node : arrayFoldedChildren) { arrayNode.addChildToBack(node); } reportCodeChange(); break; } return n; }
private Node tryFoldArrayJoin(Node n) { Node callTarget = n.getFirstChild(); if (callTarget == null || !NodeUtil.isGetProp(callTarget)) { return n; } Node right = callTarget.getNext(); if (right != null) { if (right.getNext() != null || !NodeUtil.isImmutableValue(right)) { return n; } } Node arrayNode = callTarget.getFirstChild(); Node functionName = arrayNode.getNext(); if ((arrayNode.getType() != Token.ARRAYLIT) || !functionName.getString().equals("join")) { return n; } if (right != null && right.getType() == Token.STRING && ",".equals(right.getString())) { n.removeChild(right); reportCodeChange(); } String joinString = (right == null) ? "," : NodeUtil.getStringValue(right); List<Node> arrayFoldedChildren = Lists.newLinkedList(); StringBuilder sb = null; int foldedSize = 0; Node prev = null; Node elem = arrayNode.getFirstChild(); while (elem != null) { if (NodeUtil.isImmutableValue(elem) || elem.getType() == Token.EMPTY) { if (sb == null) { sb = new StringBuilder(); } else { sb.append(joinString); } sb.append(NodeUtil.getArrayElementStringValue(elem)); } else { if (sb != null) { Preconditions.checkNotNull(prev); foldedSize += sb.length() + 2; arrayFoldedChildren.add( Node.newString(sb.toString()).copyInformationFrom(prev)); sb = null; } foldedSize += InlineCostEstimator.getCost(elem); arrayFoldedChildren.add(elem); } prev = elem; elem = elem.getNext(); } if (sb != null) { Preconditions.checkNotNull(prev); foldedSize += sb.length() + 2; arrayFoldedChildren.add( Node.newString(sb.toString()).copyInformationFrom(prev)); } foldedSize += arrayFoldedChildren.size() - 1; int originalSize = InlineCostEstimator.getCost(n); switch (arrayFoldedChildren.size()) { case 0: Node emptyStringNode = Node.newString(""); n.getParent().replaceChild(n, emptyStringNode); reportCodeChange(); return emptyStringNode; case 1: Node foldedStringNode = arrayFoldedChildren.remove(0); if (foldedSize > originalSize) { return n; } arrayNode.detachChildren(); if (foldedStringNode.getType() != Token.STRING) { Node replacement = new Node(Token.ADD, Node.newString("").copyInformationFrom(n), foldedStringNode); foldedStringNode = replacement; } n.getParent().replaceChild(n, foldedStringNode); reportCodeChange(); return foldedStringNode; default: if (arrayFoldedChildren.size() == arrayNode.getChildCount()) { return n; } int kJoinOverhead = "[].join()".length(); foldedSize += kJoinOverhead; foldedSize += (right != null) ? InlineCostEstimator.getCost(right) : 0; if (foldedSize > originalSize) { return n; } arrayNode.detachChildren(); for (Node node : arrayFoldedChildren) { arrayNode.addChildToBack(node); } reportCodeChange(); break; } return n; }
Time-19
public int getOffsetFromLocal(long instantLocal) { final int offsetLocal = getOffset(instantLocal); final long instantAdjusted = instantLocal - offsetLocal; final int offsetAdjusted = getOffset(instantAdjusted); if (offsetLocal != offsetAdjusted) { if ((offsetLocal - offsetAdjusted) < 0) { long nextLocal = nextTransition(instantAdjusted); long nextAdjusted = nextTransition(instantLocal - offsetAdjusted); if (nextLocal != nextAdjusted) { return offsetLocal; } } } else if (offsetLocal > 0) { long prev = previousTransition(instantAdjusted); if (prev < instantAdjusted) { int offsetPrev = getOffset(prev); int diff = offsetPrev - offsetLocal; if (instantAdjusted - prev <= diff) { return offsetPrev; } } } return offsetAdjusted; }
public int getOffsetFromLocal(long instantLocal) { final int offsetLocal = getOffset(instantLocal); final long instantAdjusted = instantLocal - offsetLocal; final int offsetAdjusted = getOffset(instantAdjusted); if (offsetLocal != offsetAdjusted) { if ((offsetLocal - offsetAdjusted) < 0) { long nextLocal = nextTransition(instantAdjusted); long nextAdjusted = nextTransition(instantLocal - offsetAdjusted); if (nextLocal != nextAdjusted) { return offsetLocal; } } } else if (offsetLocal >= 0) { long prev = previousTransition(instantAdjusted); if (prev < instantAdjusted) { int offsetPrev = getOffset(prev); int diff = offsetPrev - offsetLocal; if (instantAdjusted - prev <= diff) { return offsetPrev; } } } return offsetAdjusted; }
Math-95
protected double getInitialDomain(double p) { double ret; double d = getDenominatorDegreesOfFreedom(); ret = d / (d - 2.0); return ret; }
protected double getInitialDomain(double p) { double ret = 1.0; double d = getDenominatorDegreesOfFreedom(); if (d > 2.0) { ret = d / (d - 2.0); } return ret; }
JacksonCore-11
private void _verifySharing() { if (_hashShared) { _hashArea = Arrays.copyOf(_hashArea, _hashArea.length); _names = Arrays.copyOf(_names, _names.length); _hashShared = false; } if (_needRehash) { rehash(); } }
private void _verifySharing() { if (_hashShared) { _hashArea = Arrays.copyOf(_hashArea, _hashArea.length); _names = Arrays.copyOf(_names, _names.length); _hashShared = false; _verifyNeedForRehash(); } if (_needRehash) { rehash(); } }
Math-91
public int compareTo(Fraction object) { double nOd = doubleValue(); double dOn = object.doubleValue(); return (nOd < dOn) ? -1 : ((nOd > dOn) ? +1 : 0); }
public int compareTo(Fraction object) { long nOd = ((long) numerator) * object.denominator; long dOn = ((long) denominator) * object.numerator; return (nOd < dOn) ? -1 : ((nOd > dOn) ? +1 : 0); }
Math-73
public double solve(final UnivariateRealFunction f, final double min, final double max, final double initial) throws MaxIterationsExceededException, FunctionEvaluationException { clearResult(); verifySequence(min, initial, max); double yInitial = f.value(initial); if (Math.abs(yInitial) <= functionValueAccuracy) { setResult(initial, 0); return result; } double yMin = f.value(min); if (Math.abs(yMin) <= functionValueAccuracy) { setResult(yMin, 0); return result; } if (yInitial * yMin < 0) { return solve(f, min, yMin, initial, yInitial, min, yMin); } double yMax = f.value(max); if (Math.abs(yMax) <= functionValueAccuracy) { setResult(yMax, 0); return result; } if (yInitial * yMax < 0) { return solve(f, initial, yInitial, max, yMax, initial, yInitial); } return solve(f, min, yMin, max, yMax, initial, yInitial); }
public double solve(final UnivariateRealFunction f, final double min, final double max, final double initial) throws MaxIterationsExceededException, FunctionEvaluationException { clearResult(); verifySequence(min, initial, max); double yInitial = f.value(initial); if (Math.abs(yInitial) <= functionValueAccuracy) { setResult(initial, 0); return result; } double yMin = f.value(min); if (Math.abs(yMin) <= functionValueAccuracy) { setResult(yMin, 0); return result; } if (yInitial * yMin < 0) { return solve(f, min, yMin, initial, yInitial, min, yMin); } double yMax = f.value(max); if (Math.abs(yMax) <= functionValueAccuracy) { setResult(yMax, 0); return result; } if (yInitial * yMax < 0) { return solve(f, initial, yInitial, max, yMax, initial, yInitial); } if (yMin * yMax > 0) { throw MathRuntimeException.createIllegalArgumentException( NON_BRACKETING_MESSAGE, min, max, yMin, yMax); } return solve(f, min, yMin, max, yMax, initial, yInitial); }
Closure-17
private JSType getDeclaredType(String sourceName, JSDocInfo info, Node lValue, @Nullable Node rValue) { if (info != null && info.hasType()) { return getDeclaredTypeInAnnotation(sourceName, lValue, info); } else if (rValue != null && rValue.isFunction() && shouldUseFunctionLiteralType( JSType.toMaybeFunctionType(rValue.getJSType()), info, lValue)) { return rValue.getJSType(); } else if (info != null) { if (info.hasEnumParameterType()) { if (rValue != null && rValue.isObjectLit()) { return rValue.getJSType(); } else { return createEnumTypeFromNodes( rValue, lValue.getQualifiedName(), info, lValue); } } else if (info.isConstructor() || info.isInterface()) { return createFunctionTypeFromNodes( rValue, lValue.getQualifiedName(), info, lValue); } else { if (info.isConstant()) { JSType knownType = null; if (rValue != null) { if (rValue.getJSType() != null && !rValue.getJSType().isUnknownType()) { return rValue.getJSType(); } else if (rValue.isOr()) { Node firstClause = rValue.getFirstChild(); Node secondClause = firstClause.getNext(); boolean namesMatch = firstClause.isName() && lValue.isName() && firstClause.getString().equals(lValue.getString()); if (namesMatch && secondClause.getJSType() != null && !secondClause.getJSType().isUnknownType()) { return secondClause.getJSType(); } } } } } } return getDeclaredTypeInAnnotation(sourceName, lValue, info); }
private JSType getDeclaredType(String sourceName, JSDocInfo info, Node lValue, @Nullable Node rValue) { if (info != null && info.hasType()) { return getDeclaredTypeInAnnotation(sourceName, lValue, info); } else if (rValue != null && rValue.isFunction() && shouldUseFunctionLiteralType( JSType.toMaybeFunctionType(rValue.getJSType()), info, lValue)) { return rValue.getJSType(); } else if (info != null) { if (info.hasEnumParameterType()) { if (rValue != null && rValue.isObjectLit()) { return rValue.getJSType(); } else { return createEnumTypeFromNodes( rValue, lValue.getQualifiedName(), info, lValue); } } else if (info.isConstructor() || info.isInterface()) { return createFunctionTypeFromNodes( rValue, lValue.getQualifiedName(), info, lValue); } else { if (info.isConstant()) { JSType knownType = null; if (rValue != null) { JSDocInfo rValueInfo = rValue.getJSDocInfo(); if (rValueInfo != null && rValueInfo.hasType()) { return rValueInfo.getType().evaluate(scope, typeRegistry); } else if (rValue.getJSType() != null && !rValue.getJSType().isUnknownType()) { return rValue.getJSType(); } else if (rValue.isOr()) { Node firstClause = rValue.getFirstChild(); Node secondClause = firstClause.getNext(); boolean namesMatch = firstClause.isName() && lValue.isName() && firstClause.getString().equals(lValue.getString()); if (namesMatch && secondClause.getJSType() != null && !secondClause.getJSType().isUnknownType()) { return secondClause.getJSType(); } } } } } } return getDeclaredTypeInAnnotation(sourceName, lValue, info); }
Gson-10
private ReflectiveTypeAdapterFactory.BoundField createBoundField( final Gson context, final Field field, final String name, final TypeToken<?> fieldType, boolean serialize, boolean deserialize) { final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType()); JsonAdapter annotation = field.getAnnotation(JsonAdapter.class); TypeAdapter<?> mapped = null; if (annotation != null) { mapped = getTypeAdapter(constructorConstructor, context, fieldType, annotation); } final boolean jsonAdapterPresent = mapped != null; if (mapped == null) mapped = context.getAdapter(fieldType); final TypeAdapter<?> typeAdapter = mapped; return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) { @SuppressWarnings({"unchecked", "rawtypes"}) @Override void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException { Object fieldValue = field.get(value); TypeAdapter t = new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType()); t.write(writer, fieldValue); } @Override void read(JsonReader reader, Object value) throws IOException, IllegalAccessException { Object fieldValue = typeAdapter.read(reader); if (fieldValue != null || !isPrimitive) { field.set(value, fieldValue); } } @Override public boolean writeField(Object value) throws IOException, IllegalAccessException { if (!serialized) return false; Object fieldValue = field.get(value); return fieldValue != value; } }; }
private ReflectiveTypeAdapterFactory.BoundField createBoundField( final Gson context, final Field field, final String name, final TypeToken<?> fieldType, boolean serialize, boolean deserialize) { final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType()); JsonAdapter annotation = field.getAnnotation(JsonAdapter.class); TypeAdapter<?> mapped = null; if (annotation != null) { mapped = getTypeAdapter(constructorConstructor, context, fieldType, annotation); } final boolean jsonAdapterPresent = mapped != null; if (mapped == null) mapped = context.getAdapter(fieldType); final TypeAdapter<?> typeAdapter = mapped; return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) { @SuppressWarnings({"unchecked", "rawtypes"}) @Override void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException { Object fieldValue = field.get(value); TypeAdapter t = jsonAdapterPresent ? typeAdapter : new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType()); t.write(writer, fieldValue); } @Override void read(JsonReader reader, Object value) throws IOException, IllegalAccessException { Object fieldValue = typeAdapter.read(reader); if (fieldValue != null || !isPrimitive) { field.set(value, fieldValue); } } @Override public boolean writeField(Object value) throws IOException, IllegalAccessException { if (!serialized) return false; Object fieldValue = field.get(value); return fieldValue != value; } }; }
JacksonDatabind-33
public PropertyName findNameForSerialization(Annotated a) { String name = null; JsonGetter jg = _findAnnotation(a, JsonGetter.class); if (jg != null) { name = jg.value(); } else { JsonProperty pann = _findAnnotation(a, JsonProperty.class); if (pann != null) { name = pann.value(); } else if (_hasAnnotation(a, JsonSerialize.class) || _hasAnnotation(a, JsonView.class) || _hasAnnotation(a, JsonRawValue.class)) { name = ""; } else { return null; } } return PropertyName.construct(name); }
public PropertyName findNameForSerialization(Annotated a) { String name = null; JsonGetter jg = _findAnnotation(a, JsonGetter.class); if (jg != null) { name = jg.value(); } else { JsonProperty pann = _findAnnotation(a, JsonProperty.class); if (pann != null) { name = pann.value(); } else if (_hasAnnotation(a, JsonSerialize.class) || _hasAnnotation(a, JsonView.class) || _hasAnnotation(a, JsonRawValue.class) || _hasAnnotation(a, JsonUnwrapped.class) || _hasAnnotation(a, JsonBackReference.class) || _hasAnnotation(a, JsonManagedReference.class)) { name = ""; } else { return null; } } return PropertyName.construct(name); }
Closure-104
JSType meet(JSType that) { UnionTypeBuilder builder = new UnionTypeBuilder(registry); for (JSType alternate : alternates) { if (alternate.isSubtype(that)) { builder.addAlternate(alternate); } } if (that instanceof UnionType) { for (JSType otherAlternate : ((UnionType) that).alternates) { if (otherAlternate.isSubtype(this)) { builder.addAlternate(otherAlternate); } } } else if (that.isSubtype(this)) { builder.addAlternate(that); } JSType result = builder.build(); if (result != null) { return result; } else if (this.isObject() && that.isObject()) { return getNativeType(JSTypeNative.NO_OBJECT_TYPE); } else { return getNativeType(JSTypeNative.NO_TYPE); } }
JSType meet(JSType that) { UnionTypeBuilder builder = new UnionTypeBuilder(registry); for (JSType alternate : alternates) { if (alternate.isSubtype(that)) { builder.addAlternate(alternate); } } if (that instanceof UnionType) { for (JSType otherAlternate : ((UnionType) that).alternates) { if (otherAlternate.isSubtype(this)) { builder.addAlternate(otherAlternate); } } } else if (that.isSubtype(this)) { builder.addAlternate(that); } JSType result = builder.build(); if (!result.isNoType()) { return result; } else if (this.isObject() && that.isObject()) { return getNativeType(JSTypeNative.NO_OBJECT_TYPE); } else { return getNativeType(JSTypeNative.NO_TYPE); } }
JacksonDatabind-42
protected Object _deserializeFromEmptyString() throws IOException { if (_kind == STD_URI) { return URI.create(""); } return super._deserializeFromEmptyString(); }
protected Object _deserializeFromEmptyString() throws IOException { if (_kind == STD_URI) { return URI.create(""); } if (_kind == STD_LOCALE) { return Locale.ROOT; } return super._deserializeFromEmptyString(); }
Math-9
public Line revert() { final Line reverted = new Line(zero, zero.subtract(direction)); return reverted; }
public Line revert() { final Line reverted = new Line(this); reverted.direction = reverted.direction.negate(); return reverted; }
JacksonDatabind-96
protected void _addExplicitAnyCreator(DeserializationContext ctxt, BeanDescription beanDesc, CreatorCollector creators, CreatorCandidate candidate) throws JsonMappingException { if (1 != candidate.paramCount()) { int oneNotInjected = candidate.findOnlyParamWithoutInjection(); if (oneNotInjected >= 0) { if (candidate.paramName(oneNotInjected) == null) { _addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate); return; } } _addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate); return; } AnnotatedParameter param = candidate.parameter(0); JacksonInject.Value injectId = candidate.injection(0); PropertyName paramName = candidate.explicitParamName(0); BeanPropertyDefinition paramDef = candidate.propertyDef(0); boolean useProps = (paramName != null) || (injectId != null); if (!useProps && (paramDef != null)) { paramName = candidate.findImplicitParamName(0); useProps = (paramName != null) && paramDef.couldSerialize(); } if (useProps) { SettableBeanProperty[] properties = new SettableBeanProperty[] { constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId) }; creators.addPropertyCreator(candidate.creator(), true, properties); return; } _handleSingleArgumentCreator(creators, candidate.creator(), true, true); if (paramDef != null) { ((POJOPropertyBuilder) paramDef).removeConstructors(); } }
protected void _addExplicitAnyCreator(DeserializationContext ctxt, BeanDescription beanDesc, CreatorCollector creators, CreatorCandidate candidate) throws JsonMappingException { if (1 != candidate.paramCount()) { int oneNotInjected = candidate.findOnlyParamWithoutInjection(); if (oneNotInjected >= 0) { if (candidate.paramName(oneNotInjected) == null) { _addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate); return; } } _addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate); return; } AnnotatedParameter param = candidate.parameter(0); JacksonInject.Value injectId = candidate.injection(0); PropertyName paramName = candidate.explicitParamName(0); BeanPropertyDefinition paramDef = candidate.propertyDef(0); boolean useProps = (paramName != null) || (injectId != null); if (!useProps && (paramDef != null)) { paramName = candidate.paramName(0); useProps = (paramName != null) && paramDef.couldSerialize(); } if (useProps) { SettableBeanProperty[] properties = new SettableBeanProperty[] { constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId) }; creators.addPropertyCreator(candidate.creator(), true, properties); return; } _handleSingleArgumentCreator(creators, candidate.creator(), true, true); if (paramDef != null) { ((POJOPropertyBuilder) paramDef).removeConstructors(); } }
Cli-11
private static void appendOption(final StringBuffer buff, final Option option, final boolean required) { if (!required) { buff.append("["); } if (option.getOpt() != null) { buff.append("-").append(option.getOpt()); } else { buff.append("--").append(option.getLongOpt()); } if (option.hasArg() && (option.getArgName() != null)) { buff.append(" <").append(option.getArgName()).append(">"); } if (!required) { buff.append("]"); } }
private static void appendOption(final StringBuffer buff, final Option option, final boolean required) { if (!required) { buff.append("["); } if (option.getOpt() != null) { buff.append("-").append(option.getOpt()); } else { buff.append("--").append(option.getLongOpt()); } if (option.hasArg() && option.hasArgName()) { buff.append(" <").append(option.getArgName()).append(">"); } if (!required) { buff.append("]"); } }
Closure-2
private void checkInterfaceConflictProperties(NodeTraversal t, Node n, String functionName, HashMap<String, ObjectType> properties, HashMap<String, ObjectType> currentProperties, ObjectType interfaceType) { ObjectType implicitProto = interfaceType.getImplicitPrototype(); Set<String> currentPropertyNames; currentPropertyNames = implicitProto.getOwnPropertyNames(); for (String name : currentPropertyNames) { ObjectType oType = properties.get(name); if (oType != null) { if (!interfaceType.getPropertyType(name).isEquivalentTo( oType.getPropertyType(name))) { compiler.report( t.makeError(n, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE, functionName, name, oType.toString(), interfaceType.toString())); } } currentProperties.put(name, interfaceType); } for (ObjectType iType : interfaceType.getCtorExtendedInterfaces()) { checkInterfaceConflictProperties(t, n, functionName, properties, currentProperties, iType); } }
private void checkInterfaceConflictProperties(NodeTraversal t, Node n, String functionName, HashMap<String, ObjectType> properties, HashMap<String, ObjectType> currentProperties, ObjectType interfaceType) { ObjectType implicitProto = interfaceType.getImplicitPrototype(); Set<String> currentPropertyNames; if (implicitProto == null) { currentPropertyNames = ImmutableSet.of(); } else { currentPropertyNames = implicitProto.getOwnPropertyNames(); } for (String name : currentPropertyNames) { ObjectType oType = properties.get(name); if (oType != null) { if (!interfaceType.getPropertyType(name).isEquivalentTo( oType.getPropertyType(name))) { compiler.report( t.makeError(n, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE, functionName, name, oType.toString(), interfaceType.toString())); } } currentProperties.put(name, interfaceType); } for (ObjectType iType : interfaceType.getCtorExtendedInterfaces()) { checkInterfaceConflictProperties(t, n, functionName, properties, currentProperties, iType); } }
Math-21
public RectangularCholeskyDecomposition(RealMatrix matrix, double small) throws NonPositiveDefiniteMatrixException { final int order = matrix.getRowDimension(); final double[][] c = matrix.getData(); final double[][] b = new double[order][order]; int[] swap = new int[order]; int[] index = new int[order]; for (int i = 0; i < order; ++i) { index[i] = i; } int r = 0; for (boolean loop = true; loop;) { swap[r] = r; for (int i = r + 1; i < order; ++i) { int ii = index[i]; int isi = index[swap[i]]; if (c[ii][ii] > c[isi][isi]) { swap[r] = i; } } if (swap[r] != r) { int tmp = index[r]; index[r] = index[swap[r]]; index[swap[r]] = tmp; } int ir = index[r]; if (c[ir][ir] < small) { if (r == 0) { throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small); } for (int i = r; i < order; ++i) { if (c[index[i]][index[i]] < -small) { throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small); } } ++r; loop = false; } else { final double sqrt = FastMath.sqrt(c[ir][ir]); b[r][r] = sqrt; final double inverse = 1 / sqrt; for (int i = r + 1; i < order; ++i) { final int ii = index[i]; final double e = inverse * c[ii][ir]; b[i][r] = e; c[ii][ii] -= e * e; for (int j = r + 1; j < i; ++j) { final int ij = index[j]; final double f = c[ii][ij] - e * b[j][r]; c[ii][ij] = f; c[ij][ii] = f; } } loop = ++r < order; } } rank = r; root = MatrixUtils.createRealMatrix(order, r); for (int i = 0; i < order; ++i) { for (int j = 0; j < r; ++j) { root.setEntry(index[i], j, b[i][j]); } } }
public RectangularCholeskyDecomposition(RealMatrix matrix, double small) throws NonPositiveDefiniteMatrixException { final int order = matrix.getRowDimension(); final double[][] c = matrix.getData(); final double[][] b = new double[order][order]; int[] index = new int[order]; for (int i = 0; i < order; ++i) { index[i] = i; } int r = 0; for (boolean loop = true; loop;) { int swapR = r; for (int i = r + 1; i < order; ++i) { int ii = index[i]; int isr = index[swapR]; if (c[ii][ii] > c[isr][isr]) { swapR = i; } } if (swapR != r) { final int tmpIndex = index[r]; index[r] = index[swapR]; index[swapR] = tmpIndex; final double[] tmpRow = b[r]; b[r] = b[swapR]; b[swapR] = tmpRow; } int ir = index[r]; if (c[ir][ir] < small) { if (r == 0) { throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small); } for (int i = r; i < order; ++i) { if (c[index[i]][index[i]] < -small) { throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small); } } ++r; loop = false; } else { final double sqrt = FastMath.sqrt(c[ir][ir]); b[r][r] = sqrt; final double inverse = 1 / sqrt; final double inverse2 = 1 / c[ir][ir]; for (int i = r + 1; i < order; ++i) { final int ii = index[i]; final double e = inverse * c[ii][ir]; b[i][r] = e; c[ii][ii] -= c[ii][ir] * c[ii][ir] * inverse2; for (int j = r + 1; j < i; ++j) { final int ij = index[j]; final double f = c[ii][ij] - e * b[j][r]; c[ii][ij] = f; c[ij][ii] = f; } } loop = ++r < order; } } rank = r; root = MatrixUtils.createRealMatrix(order, r); for (int i = 0; i < order; ++i) { for (int j = 0; j < r; ++j) { root.setEntry(index[i], j, b[i][j]); } } }
Jsoup-10
public String absUrl(String attributeKey) { Validate.notEmpty(attributeKey); String relUrl = attr(attributeKey); if (!hasAttr(attributeKey)) { return ""; } else { URL base; try { try { base = new URL(baseUri); } catch (MalformedURLException e) { URL abs = new URL(relUrl); return abs.toExternalForm(); } URL abs = new URL(base, relUrl); return abs.toExternalForm(); } catch (MalformedURLException e) { return ""; } } }
public String absUrl(String attributeKey) { Validate.notEmpty(attributeKey); String relUrl = attr(attributeKey); if (!hasAttr(attributeKey)) { return ""; } else { URL base; try { try { base = new URL(baseUri); } catch (MalformedURLException e) { URL abs = new URL(relUrl); return abs.toExternalForm(); } if (relUrl.startsWith("?")) relUrl = base.getPath() + relUrl; URL abs = new URL(base, relUrl); return abs.toExternalForm(); } catch (MalformedURLException e) { return ""; } } }
Math-101
public Complex parse(String source, ParsePosition pos) { int initialIndex = pos.getIndex(); parseAndIgnoreWhitespace(source, pos); Number re = parseNumber(source, getRealFormat(), pos); if (re == null) { pos.setIndex(initialIndex); return null; } int startIndex = pos.getIndex(); char c = parseNextCharacter(source, pos); int sign = 0; switch (c) { case 0 : return new Complex(re.doubleValue(), 0.0); case '-' : sign = -1; break; case '+' : sign = 1; break; default : pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } parseAndIgnoreWhitespace(source, pos); Number im = parseNumber(source, getRealFormat(), pos); if (im == null) { pos.setIndex(initialIndex); return null; } int n = getImaginaryCharacter().length(); startIndex = pos.getIndex(); int endIndex = startIndex + n; if ( source.substring(startIndex, endIndex).compareTo( getImaginaryCharacter()) != 0) { pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } pos.setIndex(endIndex); return new Complex(re.doubleValue(), im.doubleValue() * sign); }
public Complex parse(String source, ParsePosition pos) { int initialIndex = pos.getIndex(); parseAndIgnoreWhitespace(source, pos); Number re = parseNumber(source, getRealFormat(), pos); if (re == null) { pos.setIndex(initialIndex); return null; } int startIndex = pos.getIndex(); char c = parseNextCharacter(source, pos); int sign = 0; switch (c) { case 0 : return new Complex(re.doubleValue(), 0.0); case '-' : sign = -1; break; case '+' : sign = 1; break; default : pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } parseAndIgnoreWhitespace(source, pos); Number im = parseNumber(source, getRealFormat(), pos); if (im == null) { pos.setIndex(initialIndex); return null; } int n = getImaginaryCharacter().length(); startIndex = pos.getIndex(); int endIndex = startIndex + n; if ((startIndex >= source.length()) || (endIndex > source.length()) || source.substring(startIndex, endIndex).compareTo( getImaginaryCharacter()) != 0) { pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } pos.setIndex(endIndex); return new Complex(re.doubleValue(), im.doubleValue() * sign); }
Codec-10
public String caverphone(String txt) { if( txt == null || txt.length() == 0 ) { return "1111111111"; } txt = txt.toLowerCase(java.util.Locale.ENGLISH); txt = txt.replaceAll("[^a-z]", ""); txt = txt.replaceAll("e$", ""); txt = txt.replaceAll("^cough", "cou2f"); txt = txt.replaceAll("^rough", "rou2f"); txt = txt.replaceAll("^tough", "tou2f"); txt = txt.replaceAll("^enough", "enou2f"); txt = txt.replaceAll("^trough", "trou2f"); txt = txt.replaceAll("^gn", "2n"); txt = txt.replaceAll("^mb", "m2"); txt = txt.replaceAll("cq", "2q"); txt = txt.replaceAll("ci", "si"); txt = txt.replaceAll("ce", "se"); txt = txt.replaceAll("cy", "sy"); txt = txt.replaceAll("tch", "2ch"); txt = txt.replaceAll("c", "k"); txt = txt.replaceAll("q", "k"); txt = txt.replaceAll("x", "k"); txt = txt.replaceAll("v", "f"); txt = txt.replaceAll("dg", "2g"); txt = txt.replaceAll("tio", "sio"); txt = txt.replaceAll("tia", "sia"); txt = txt.replaceAll("d", "t"); txt = txt.replaceAll("ph", "fh"); txt = txt.replaceAll("b", "p"); txt = txt.replaceAll("sh", "s2"); txt = txt.replaceAll("z", "s"); txt = txt.replaceAll("^[aeiou]", "A"); txt = txt.replaceAll("[aeiou]", "3"); txt = txt.replaceAll("j", "y"); txt = txt.replaceAll("^y3", "Y3"); txt = txt.replaceAll("^y", "A"); txt = txt.replaceAll("y", "3"); txt = txt.replaceAll("3gh3", "3kh3"); txt = txt.replaceAll("gh", "22"); txt = txt.replaceAll("g", "k"); txt = txt.replaceAll("s+", "S"); txt = txt.replaceAll("t+", "T"); txt = txt.replaceAll("p+", "P"); txt = txt.replaceAll("k+", "K"); txt = txt.replaceAll("f+", "F"); txt = txt.replaceAll("m+", "M"); txt = txt.replaceAll("n+", "N"); txt = txt.replaceAll("w3", "W3"); txt = txt.replaceAll("wh3", "Wh3"); txt = txt.replaceAll("w$", "3"); txt = txt.replaceAll("w", "2"); txt = txt.replaceAll("^h", "A"); txt = txt.replaceAll("h", "2"); txt = txt.replaceAll("r3", "R3"); txt = txt.replaceAll("r$", "3"); txt = txt.replaceAll("r", "2"); txt = txt.replaceAll("l3", "L3"); txt = txt.replaceAll("l$", "3"); txt = txt.replaceAll("l", "2"); txt = txt.replaceAll("2", ""); txt = txt.replaceAll("3$", "A"); txt = txt.replaceAll("3", ""); txt = txt + "111111" + "1111"; return txt.substring(0, 10); }
public String caverphone(String txt) { if( txt == null || txt.length() == 0 ) { return "1111111111"; } txt = txt.toLowerCase(java.util.Locale.ENGLISH); txt = txt.replaceAll("[^a-z]", ""); txt = txt.replaceAll("e$", ""); txt = txt.replaceAll("^cough", "cou2f"); txt = txt.replaceAll("^rough", "rou2f"); txt = txt.replaceAll("^tough", "tou2f"); txt = txt.replaceAll("^enough", "enou2f"); txt = txt.replaceAll("^trough", "trou2f"); txt = txt.replaceAll("^gn", "2n"); txt = txt.replaceAll("mb$", "m2"); txt = txt.replaceAll("cq", "2q"); txt = txt.replaceAll("ci", "si"); txt = txt.replaceAll("ce", "se"); txt = txt.replaceAll("cy", "sy"); txt = txt.replaceAll("tch", "2ch"); txt = txt.replaceAll("c", "k"); txt = txt.replaceAll("q", "k"); txt = txt.replaceAll("x", "k"); txt = txt.replaceAll("v", "f"); txt = txt.replaceAll("dg", "2g"); txt = txt.replaceAll("tio", "sio"); txt = txt.replaceAll("tia", "sia"); txt = txt.replaceAll("d", "t"); txt = txt.replaceAll("ph", "fh"); txt = txt.replaceAll("b", "p"); txt = txt.replaceAll("sh", "s2"); txt = txt.replaceAll("z", "s"); txt = txt.replaceAll("^[aeiou]", "A"); txt = txt.replaceAll("[aeiou]", "3"); txt = txt.replaceAll("j", "y"); txt = txt.replaceAll("^y3", "Y3"); txt = txt.replaceAll("^y", "A"); txt = txt.replaceAll("y", "3"); txt = txt.replaceAll("3gh3", "3kh3"); txt = txt.replaceAll("gh", "22"); txt = txt.replaceAll("g", "k"); txt = txt.replaceAll("s+", "S"); txt = txt.replaceAll("t+", "T"); txt = txt.replaceAll("p+", "P"); txt = txt.replaceAll("k+", "K"); txt = txt.replaceAll("f+", "F"); txt = txt.replaceAll("m+", "M"); txt = txt.replaceAll("n+", "N"); txt = txt.replaceAll("w3", "W3"); txt = txt.replaceAll("wh3", "Wh3"); txt = txt.replaceAll("w$", "3"); txt = txt.replaceAll("w", "2"); txt = txt.replaceAll("^h", "A"); txt = txt.replaceAll("h", "2"); txt = txt.replaceAll("r3", "R3"); txt = txt.replaceAll("r$", "3"); txt = txt.replaceAll("r", "2"); txt = txt.replaceAll("l3", "L3"); txt = txt.replaceAll("l$", "3"); txt = txt.replaceAll("l", "2"); txt = txt.replaceAll("2", ""); txt = txt.replaceAll("3$", "A"); txt = txt.replaceAll("3", ""); txt = txt + "111111" + "1111"; return txt.substring(0, 10); }
Compress-30
public int read(final byte[] dest, final int offs, final int len) throws IOException { if (offs < 0) { throw new IndexOutOfBoundsException("offs(" + offs + ") < 0."); } if (len < 0) { throw new IndexOutOfBoundsException("len(" + len + ") < 0."); } if (offs + len > dest.length) { throw new IndexOutOfBoundsException("offs(" + offs + ") + len(" + len + ") > dest.length(" + dest.length + ")."); } if (this.in == null) { throw new IOException("stream closed"); } final int hi = offs + len; int destOffs = offs; int b; while (destOffs < hi && ((b = read0()) >= 0)) { dest[destOffs++] = (byte) b; count(1); } int c = (destOffs == offs) ? -1 : (destOffs - offs); return c; }
public int read(final byte[] dest, final int offs, final int len) throws IOException { if (offs < 0) { throw new IndexOutOfBoundsException("offs(" + offs + ") < 0."); } if (len < 0) { throw new IndexOutOfBoundsException("len(" + len + ") < 0."); } if (offs + len > dest.length) { throw new IndexOutOfBoundsException("offs(" + offs + ") + len(" + len + ") > dest.length(" + dest.length + ")."); } if (this.in == null) { throw new IOException("stream closed"); } if (len == 0) { return 0; } final int hi = offs + len; int destOffs = offs; int b; while (destOffs < hi && ((b = read0()) >= 0)) { dest[destOffs++] = (byte) b; count(1); } int c = (destOffs == offs) ? -1 : (destOffs - offs); return c; }
Math-5
public Complex reciprocal() { if (isNaN) { return NaN; } if (real == 0.0 && imaginary == 0.0) { return NaN; } if (isInfinite) { return ZERO; } if (FastMath.abs(real) < FastMath.abs(imaginary)) { double q = real / imaginary; double scale = 1. / (real * q + imaginary); return createComplex(scale * q, -scale); } else { double q = imaginary / real; double scale = 1. / (imaginary * q + real); return createComplex(scale, -scale * q); } }
public Complex reciprocal() { if (isNaN) { return NaN; } if (real == 0.0 && imaginary == 0.0) { return INF; } if (isInfinite) { return ZERO; } if (FastMath.abs(real) < FastMath.abs(imaginary)) { double q = real / imaginary; double scale = 1. / (real * q + imaginary); return createComplex(scale * q, -scale); } else { double q = imaginary / real; double scale = 1. / (imaginary * q + real); return createComplex(scale, -scale * q); } }
Closure-55
private static boolean isReduceableFunctionExpression(Node n) { return NodeUtil.isFunctionExpression(n); }
private static boolean isReduceableFunctionExpression(Node n) { return NodeUtil.isFunctionExpression(n) && !NodeUtil.isGetOrSetKey(n.getParent()); }
Closure-67
private boolean isPrototypePropertyAssign(Node assign) { Node n = assign.getFirstChild(); if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign) && n.getType() == Token.GETPROP ) { boolean isChainedProperty = n.getFirstChild().getType() == Token.GETPROP; if (isChainedProperty) { Node child = n.getFirstChild().getFirstChild().getNext(); if (child.getType() == Token.STRING && child.getString().equals("prototype")) { return true; } } } return false; }
private boolean isPrototypePropertyAssign(Node assign) { Node n = assign.getFirstChild(); if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign) && n.getType() == Token.GETPROP && assign.getParent().getType() == Token.EXPR_RESULT) { boolean isChainedProperty = n.getFirstChild().getType() == Token.GETPROP; if (isChainedProperty) { Node child = n.getFirstChild().getFirstChild().getNext(); if (child.getType() == Token.STRING && child.getString().equals("prototype")) { return true; } } } return false; }
Closure-168
@Override public void visit(NodeTraversal t, Node n, Node parent) { if (t.inGlobalScope()) { return; } if (n.isReturn() && n.getFirstChild() != null) { data.get(t.getScopeRoot()).recordNonEmptyReturn(); } if (t.getScopeDepth() <= 2) { return; } if (n.isName() && NodeUtil.isLValue(n) && !NodeUtil.isBleedingFunctionName(n)) { String name = n.getString(); Scope scope = t.getScope(); Var var = scope.getVar(name); if (var != null) { Scope ownerScope = var.getScope(); if (ownerScope.isLocal()) { data.get(ownerScope.getRootNode()).recordAssignedName(name); } if (scope != ownerScope && ownerScope.isLocal()) { data.get(ownerScope.getRootNode()).recordEscapedVarName(name); } } } else if (n.isGetProp() && n.isUnscopedQualifiedName() && NodeUtil.isLValue(n)) { String name = NodeUtil.getRootOfQualifiedName(n).getString(); Scope scope = t.getScope(); Var var = scope.getVar(name); if (var != null) { Scope ownerScope = var.getScope(); if (scope != ownerScope && ownerScope.isLocal()) { data.get(ownerScope.getRootNode()) .recordEscapedQualifiedName(n.getQualifiedName()); } } } }
@Override public void visit(NodeTraversal t, Node n, Node parent) { if (t.inGlobalScope()) { return; } if (n.isReturn() && n.getFirstChild() != null) { data.get(t.getScopeRoot()).recordNonEmptyReturn(); } if (t.getScopeDepth() <= 1) { return; } if (n.isName() && NodeUtil.isLValue(n) && !NodeUtil.isBleedingFunctionName(n)) { String name = n.getString(); Scope scope = t.getScope(); Var var = scope.getVar(name); if (var != null) { Scope ownerScope = var.getScope(); if (ownerScope.isLocal()) { data.get(ownerScope.getRootNode()).recordAssignedName(name); } if (scope != ownerScope && ownerScope.isLocal()) { data.get(ownerScope.getRootNode()).recordEscapedVarName(name); } } } else if (n.isGetProp() && n.isUnscopedQualifiedName() && NodeUtil.isLValue(n)) { String name = NodeUtil.getRootOfQualifiedName(n).getString(); Scope scope = t.getScope(); Var var = scope.getVar(name); if (var != null) { Scope ownerScope = var.getScope(); if (scope != ownerScope && ownerScope.isLocal()) { data.get(ownerScope.getRootNode()) .recordEscapedQualifiedName(n.getQualifiedName()); } } } }
Closure-39
String toStringHelper(boolean forAnnotations) { if (hasReferenceName()) { return getReferenceName(); } else if (prettyPrint) { prettyPrint = false; Set<String> propertyNames = Sets.newTreeSet(); for (ObjectType current = this; current != null && !current.isNativeObjectType() && propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES; current = current.getImplicitPrototype()) { propertyNames.addAll(current.getOwnPropertyNames()); } StringBuilder sb = new StringBuilder(); sb.append("{"); int i = 0; for (String property : propertyNames) { if (i > 0) { sb.append(", "); } sb.append(property); sb.append(": "); sb.append(getPropertyType(property).toString()); ++i; if (i == MAX_PRETTY_PRINTED_PROPERTIES) { sb.append(", ..."); break; } } sb.append("}"); prettyPrint = true; return sb.toString(); } else { return "{...}"; } }
String toStringHelper(boolean forAnnotations) { if (hasReferenceName()) { return getReferenceName(); } else if (prettyPrint) { prettyPrint = false; Set<String> propertyNames = Sets.newTreeSet(); for (ObjectType current = this; current != null && !current.isNativeObjectType() && propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES; current = current.getImplicitPrototype()) { propertyNames.addAll(current.getOwnPropertyNames()); } StringBuilder sb = new StringBuilder(); sb.append("{"); int i = 0; for (String property : propertyNames) { if (i > 0) { sb.append(", "); } sb.append(property); sb.append(": "); sb.append(getPropertyType(property).toStringHelper(forAnnotations)); ++i; if (!forAnnotations && i == MAX_PRETTY_PRINTED_PROPERTIES) { sb.append(", ..."); break; } } sb.append("}"); prettyPrint = true; return sb.toString(); } else { return forAnnotations ? "?" : "{...}"; } }
Lang-53
private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } if (field == Calendar.MILLISECOND) { return; } Date date = val.getTime(); long time = date.getTime(); boolean done = false; int millisecs = val.get(Calendar.MILLISECOND); if (!round || millisecs < 500) { time = time - millisecs; if (field == Calendar.SECOND) { done = true; } } int seconds = val.get(Calendar.SECOND); if (!done && (!round || seconds < 30)) { time = time - (seconds * 1000L); if (field == Calendar.MINUTE) { done = true; } } int minutes = val.get(Calendar.MINUTE); if (!done && (!round || minutes < 30)) { time = time - (minutes * 60000L); } if (date.getTime() != time) { date.setTime(time); val.setTime(date); } boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { if (round && roundUp) { if (field == DateUtils.SEMI_MONTH) { if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { val.add(fields[i][0], 1); } } return; } } int offset = 0; boolean offsetSet = false; switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { offset = val.get(Calendar.DATE) - 1; if (offset >= 15) { offset -= 15; } roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); offset = val.get(fields[i][0]) - min; roundUp = offset > ((max - min) / 2); } if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); }
private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } if (field == Calendar.MILLISECOND) { return; } Date date = val.getTime(); long time = date.getTime(); boolean done = false; int millisecs = val.get(Calendar.MILLISECOND); if (!round || millisecs < 500) { time = time - millisecs; } if (field == Calendar.SECOND) { done = true; } int seconds = val.get(Calendar.SECOND); if (!done && (!round || seconds < 30)) { time = time - (seconds * 1000L); } if (field == Calendar.MINUTE) { done = true; } int minutes = val.get(Calendar.MINUTE); if (!done && (!round || minutes < 30)) { time = time - (minutes * 60000L); } if (date.getTime() != time) { date.setTime(time); val.setTime(date); } boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { if (round && roundUp) { if (field == DateUtils.SEMI_MONTH) { if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { val.add(fields[i][0], 1); } } return; } } int offset = 0; boolean offsetSet = false; switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { offset = val.get(Calendar.DATE) - 1; if (offset >= 15) { offset -= 15; } roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); offset = val.get(fields[i][0]) - min; roundUp = offset > ((max - min) / 2); } if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); }
Csv-1
public int read() throws IOException { int current = super.read(); if (current == '\n') { lineCounter++; } lastChar = current; return lastChar; }
public int read() throws IOException { int current = super.read(); if (current == '\r' || (current == '\n' && lastChar != '\r')) { lineCounter++; } lastChar = current; return lastChar; }
JacksonDatabind-35
private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (p.canReadTypeId()) { Object typeId = p.getTypeId(); if (typeId != null) { return _deserializeWithNativeTypeId(p, ctxt, typeId); } } if (p.getCurrentToken() != JsonToken.START_OBJECT) { throw ctxt.wrongTokenException(p, JsonToken.START_OBJECT, "need JSON Object to contain As.WRAPPER_OBJECT type information for class "+baseTypeName()); } if (p.nextToken() != JsonToken.FIELD_NAME) { throw ctxt.wrongTokenException(p, JsonToken.FIELD_NAME, "need JSON String that contains type id (for subtype of "+baseTypeName()+")"); } final String typeId = p.getText(); JsonDeserializer<Object> deser = _findDeserializer(ctxt, typeId); p.nextToken(); if (_typeIdVisible && p.getCurrentToken() == JsonToken.START_OBJECT) { TokenBuffer tb = new TokenBuffer(null, false); tb.writeStartObject(); tb.writeFieldName(_typePropertyName); tb.writeString(typeId); p = JsonParserSequence.createFlattened(tb.asParser(p), p); p.nextToken(); } Object value = deser.deserialize(p, ctxt); if (p.nextToken() != JsonToken.END_OBJECT) { throw ctxt.wrongTokenException(p, JsonToken.END_OBJECT, "expected closing END_OBJECT after type information and deserialized value"); } return value; }
private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (p.canReadTypeId()) { Object typeId = p.getTypeId(); if (typeId != null) { return _deserializeWithNativeTypeId(p, ctxt, typeId); } } JsonToken t = p.getCurrentToken(); if (t == JsonToken.START_OBJECT) { if (p.nextToken() != JsonToken.FIELD_NAME) { throw ctxt.wrongTokenException(p, JsonToken.FIELD_NAME, "need JSON String that contains type id (for subtype of "+baseTypeName()+")"); } } else if (t != JsonToken.FIELD_NAME) { throw ctxt.wrongTokenException(p, JsonToken.START_OBJECT, "need JSON Object to contain As.WRAPPER_OBJECT type information for class "+baseTypeName()); } final String typeId = p.getText(); JsonDeserializer<Object> deser = _findDeserializer(ctxt, typeId); p.nextToken(); if (_typeIdVisible && p.getCurrentToken() == JsonToken.START_OBJECT) { TokenBuffer tb = new TokenBuffer(null, false); tb.writeStartObject(); tb.writeFieldName(_typePropertyName); tb.writeString(typeId); p = JsonParserSequence.createFlattened(tb.asParser(p), p); p.nextToken(); } Object value = deser.deserialize(p, ctxt); if (p.nextToken() != JsonToken.END_OBJECT) { throw ctxt.wrongTokenException(p, JsonToken.END_OBJECT, "expected closing END_OBJECT after type information and deserialized value"); } return value; }
JacksonDatabind-64
protected BeanPropertyWriter buildWriter(SerializerProvider prov, BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer<?> ser, TypeSerializer typeSer, TypeSerializer contentTypeSer, AnnotatedMember am, boolean defaultUseStaticTyping) throws JsonMappingException { JavaType serializationType; try { serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType); } catch (JsonMappingException e) { return prov.reportBadPropertyDefinition(_beanDesc, propDef, e.getMessage()); } if (contentTypeSer != null) { if (serializationType == null) { serializationType = declaredType; } JavaType ct = serializationType.getContentType(); if (ct == null) { prov.reportBadPropertyDefinition(_beanDesc, propDef, "serialization type "+serializationType+" has no content"); } serializationType = serializationType.withContentTypeHandler(contentTypeSer); ct = serializationType.getContentType(); } Object valueToSuppress = null; boolean suppressNulls = false; JavaType actualType = (serializationType == null) ? declaredType : serializationType; JsonInclude.Value inclV = _config.getDefaultPropertyInclusion(actualType.getRawClass(), _defaultInclusion); inclV = inclV.withOverrides(propDef.findInclusion()); JsonInclude.Include inclusion = inclV.getValueInclusion(); if (inclusion == JsonInclude.Include.USE_DEFAULTS) { inclusion = JsonInclude.Include.ALWAYS; } switch (inclusion) { case NON_DEFAULT: if (_useRealPropertyDefaults) { if (prov.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) { am.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS)); } valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType); } else { valueToSuppress = getDefaultValue(actualType); suppressNulls = true; } if (valueToSuppress == null) { suppressNulls = true; } else { if (valueToSuppress.getClass().isArray()) { valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress); } } break; case NON_ABSENT: suppressNulls = true; if (actualType.isReferenceType()) { valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; } break; case NON_EMPTY: suppressNulls = true; valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; break; case NON_NULL: suppressNulls = true; case ALWAYS: default: if (actualType.isContainerType() && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) { valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; } break; } BeanPropertyWriter bpw = new BeanPropertyWriter(propDef, am, _beanDesc.getClassAnnotations(), declaredType, ser, typeSer, serializationType, suppressNulls, valueToSuppress); Object serDef = _annotationIntrospector.findNullSerializer(am); if (serDef != null) { bpw.assignNullSerializer(prov.serializerInstance(am, serDef)); } NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am); if (unwrapper != null) { bpw = bpw.unwrappingWriter(unwrapper); } return bpw; }
protected BeanPropertyWriter buildWriter(SerializerProvider prov, BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer<?> ser, TypeSerializer typeSer, TypeSerializer contentTypeSer, AnnotatedMember am, boolean defaultUseStaticTyping) throws JsonMappingException { JavaType serializationType; try { serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType); } catch (JsonMappingException e) { return prov.reportBadPropertyDefinition(_beanDesc, propDef, e.getMessage()); } if (contentTypeSer != null) { if (serializationType == null) { serializationType = declaredType; } JavaType ct = serializationType.getContentType(); if (ct == null) { prov.reportBadPropertyDefinition(_beanDesc, propDef, "serialization type "+serializationType+" has no content"); } serializationType = serializationType.withContentTypeHandler(contentTypeSer); ct = serializationType.getContentType(); } Object valueToSuppress = null; boolean suppressNulls = false; JavaType actualType = (serializationType == null) ? declaredType : serializationType; JsonInclude.Value inclV = _config.getDefaultPropertyInclusion(actualType.getRawClass(), _defaultInclusion); inclV = inclV.withOverrides(propDef.findInclusion()); JsonInclude.Include inclusion = inclV.getValueInclusion(); if (inclusion == JsonInclude.Include.USE_DEFAULTS) { inclusion = JsonInclude.Include.ALWAYS; } switch (inclusion) { case NON_DEFAULT: Object defaultBean; if (_useRealPropertyDefaults && (defaultBean = getDefaultBean()) != null) { if (prov.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) { am.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS)); } try { valueToSuppress = am.getValue(defaultBean); } catch (Exception e) { _throwWrapped(e, propDef.getName(), defaultBean); } } else { valueToSuppress = getDefaultValue(actualType); suppressNulls = true; } if (valueToSuppress == null) { suppressNulls = true; } else { if (valueToSuppress.getClass().isArray()) { valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress); } } break; case NON_ABSENT: suppressNulls = true; if (actualType.isReferenceType()) { valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; } break; case NON_EMPTY: suppressNulls = true; valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; break; case NON_NULL: suppressNulls = true; case ALWAYS: default: if (actualType.isContainerType() && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) { valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; } break; } BeanPropertyWriter bpw = new BeanPropertyWriter(propDef, am, _beanDesc.getClassAnnotations(), declaredType, ser, typeSer, serializationType, suppressNulls, valueToSuppress); Object serDef = _annotationIntrospector.findNullSerializer(am); if (serDef != null) { bpw.assignNullSerializer(prov.serializerInstance(am, serDef)); } NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am); if (unwrapper != null) { bpw = bpw.unwrappingWriter(unwrapper); } return bpw; }
Closure-15
public boolean apply(Node n) { if (n == null) { return false; } if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) { return true; } if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) { return true; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) { return true; } } return false; }
public boolean apply(Node n) { if (n == null) { return false; } if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) { return true; } if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) { return true; } if (n.isDelProp()) { return true; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) { return true; } } return false; }
Math-75
public double getPct(Object v) { return getCumPct((Comparable<?>) v); }
public double getPct(Object v) { return getPct((Comparable<?>) v); }
Jsoup-33
Element insert(Token.StartTag startTag) { if (startTag.isSelfClosing()) { Element el = insertEmpty(startTag); stack.add(el); tokeniser.emit(new Token.EndTag(el.tagName())); return el; } Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes); insert(el); return el; }
Element insert(Token.StartTag startTag) { if (startTag.isSelfClosing()) { Element el = insertEmpty(startTag); stack.add(el); tokeniser.transition(TokeniserState.Data); tokeniser.emit(new Token.EndTag(el.tagName())); return el; } Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes); insert(el); return el; }
Mockito-24
public Object answer(InvocationOnMock invocation) { if (methodsGuru.isToString(invocation.getMethod())) { Object mock = invocation.getMock(); MockName name = mockUtil.getMockName(mock); if (name.isDefault()) { return "Mock for " + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode(); } else { return name.toString(); } } else if (methodsGuru.isCompareToMethod(invocation.getMethod())) { return 1; } Class<?> returnType = invocation.getMethod().getReturnType(); return returnValueFor(returnType); }
public Object answer(InvocationOnMock invocation) { if (methodsGuru.isToString(invocation.getMethod())) { Object mock = invocation.getMock(); MockName name = mockUtil.getMockName(mock); if (name.isDefault()) { return "Mock for " + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode(); } else { return name.toString(); } } else if (methodsGuru.isCompareToMethod(invocation.getMethod())) { return invocation.getMock() == invocation.getArguments()[0] ? 0 : 1; } Class<?> returnType = invocation.getMethod().getReturnType(); return returnValueFor(returnType); }
JacksonDatabind-11
protected JavaType _fromVariable(TypeVariable<?> type, TypeBindings context) { final String name = type.getName(); if (context == null) { return _unknownType(); } else { JavaType actualType = context.findType(name); if (actualType != null) { return actualType; } } Type[] bounds = type.getBounds(); context._addPlaceholder(name); return _constructType(bounds[0], context); }
protected JavaType _fromVariable(TypeVariable<?> type, TypeBindings context) { final String name = type.getName(); if (context == null) { context = new TypeBindings(this, (Class<?>) null); } else { JavaType actualType = context.findType(name, false); if (actualType != null) { return actualType; } } Type[] bounds = type.getBounds(); context._addPlaceholder(name); return _constructType(bounds[0], context); }
Closure-94
static boolean isValidDefineValue(Node val, Set<String> defines) { switch (val.getType()) { case Token.STRING: case Token.NUMBER: case Token.TRUE: case Token.FALSE: return true; case Token.BITAND: case Token.BITNOT: case Token.BITOR: case Token.BITXOR: case Token.NOT: case Token.NEG: return isValidDefineValue(val.getFirstChild(), defines); case Token.NAME: case Token.GETPROP: if (val.isQualifiedName()) { return defines.contains(val.getQualifiedName()); } } return false; }
static boolean isValidDefineValue(Node val, Set<String> defines) { switch (val.getType()) { case Token.STRING: case Token.NUMBER: case Token.TRUE: case Token.FALSE: return true; case Token.ADD: case Token.BITAND: case Token.BITNOT: case Token.BITOR: case Token.BITXOR: case Token.DIV: case Token.EQ: case Token.GE: case Token.GT: case Token.LE: case Token.LSH: case Token.LT: case Token.MOD: case Token.MUL: case Token.NE: case Token.RSH: case Token.SHEQ: case Token.SHNE: case Token.SUB: case Token.URSH: return isValidDefineValue(val.getFirstChild(), defines) && isValidDefineValue(val.getLastChild(), defines); case Token.NOT: case Token.NEG: case Token.POS: return isValidDefineValue(val.getFirstChild(), defines); case Token.NAME: case Token.GETPROP: if (val.isQualifiedName()) { return defines.contains(val.getQualifiedName()); } } return false; }
Jsoup-20
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) { String docData; Document doc = null; if (charsetName == null) { docData = Charset.forName(defaultCharset).decode(byteData).toString(); doc = parser.parseInput(docData, baseUri); Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first(); if (meta != null) { String foundCharset = meta.hasAttr("http-equiv") ? getCharsetFromContentType(meta.attr("content")) : meta.attr("charset"); if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { charsetName = foundCharset; byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); doc = null; } } } else { Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); } if (doc == null) { doc = parser.parseInput(docData, baseUri); doc.outputSettings().charset(charsetName); } return doc; }
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) { String docData; Document doc = null; if (charsetName == null) { docData = Charset.forName(defaultCharset).decode(byteData).toString(); doc = parser.parseInput(docData, baseUri); Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first(); if (meta != null) { String foundCharset = meta.hasAttr("http-equiv") ? getCharsetFromContentType(meta.attr("content")) : meta.attr("charset"); if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { charsetName = foundCharset; byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); doc = null; } } } else { Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); } if (doc == null) { if (docData.charAt(0) == 65279) docData = docData.substring(1); doc = parser.parseInput(docData, baseUri); doc.outputSettings().charset(charsetName); } return doc; }
Cli-9
protected void checkRequiredOptions() throws MissingOptionException { if (getRequiredOptions().size() > 0) { Iterator iter = getRequiredOptions().iterator(); StringBuffer buff = new StringBuffer("Missing required option"); buff.append(getRequiredOptions().size() == 1 ? "" : "s"); buff.append(": "); while (iter.hasNext()) { buff.append(iter.next()); } throw new MissingOptionException(buff.toString()); } }
protected void checkRequiredOptions() throws MissingOptionException { if (getRequiredOptions().size() > 0) { Iterator iter = getRequiredOptions().iterator(); StringBuffer buff = new StringBuffer("Missing required option"); buff.append(getRequiredOptions().size() == 1 ? "" : "s"); buff.append(": "); while (iter.hasNext()) { buff.append(iter.next()); buff.append(", "); } throw new MissingOptionException(buff.substring(0, buff.length() - 2)); } }
Time-25
public int getOffsetFromLocal(long instantLocal) { final int offsetLocal = getOffset(instantLocal); final long instantAdjusted = instantLocal - offsetLocal; final int offsetAdjusted = getOffset(instantAdjusted); if (offsetLocal != offsetAdjusted) { if ((offsetLocal - offsetAdjusted) < 0) { long nextLocal = nextTransition(instantAdjusted); long nextAdjusted = nextTransition(instantLocal - offsetAdjusted); if (nextLocal != nextAdjusted) { return offsetLocal; } } } return offsetAdjusted; }
public int getOffsetFromLocal(long instantLocal) { final int offsetLocal = getOffset(instantLocal); final long instantAdjusted = instantLocal - offsetLocal; final int offsetAdjusted = getOffset(instantAdjusted); if (offsetLocal != offsetAdjusted) { if ((offsetLocal - offsetAdjusted) < 0) { long nextLocal = nextTransition(instantAdjusted); long nextAdjusted = nextTransition(instantLocal - offsetAdjusted); if (nextLocal != nextAdjusted) { return offsetLocal; } } } else if (offsetLocal > 0) { long prev = previousTransition(instantAdjusted); if (prev < instantAdjusted) { int offsetPrev = getOffset(prev); int diff = offsetPrev - offsetLocal; if (instantAdjusted - prev <= diff) { return offsetPrev; } } } return offsetAdjusted; }
Math-25
private void guessAOmega() { double sx2 = 0; double sy2 = 0; double sxy = 0; double sxz = 0; double syz = 0; double currentX = observations[0].getX(); double currentY = observations[0].getY(); double f2Integral = 0; double fPrime2Integral = 0; final double startX = currentX; for (int i = 1; i < observations.length; ++i) { final double previousX = currentX; final double previousY = currentY; currentX = observations[i].getX(); currentY = observations[i].getY(); final double dx = currentX - previousX; final double dy = currentY - previousY; final double f2StepIntegral = dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3; final double fPrime2StepIntegral = dy * dy / dx; final double x = currentX - startX; f2Integral += f2StepIntegral; fPrime2Integral += fPrime2StepIntegral; sx2 += x * x; sy2 += f2Integral * f2Integral; sxy += x * f2Integral; sxz += x * fPrime2Integral; syz += f2Integral * fPrime2Integral; } double c1 = sy2 * sxz - sxy * syz; double c2 = sxy * sxz - sx2 * syz; double c3 = sx2 * sy2 - sxy * sxy; if ((c1 / c2 < 0) || (c2 / c3 < 0)) { final int last = observations.length - 1; final double xRange = observations[last].getX() - observations[0].getX(); if (xRange == 0) { throw new ZeroException(); } omega = 2 * Math.PI / xRange; double yMin = Double.POSITIVE_INFINITY; double yMax = Double.NEGATIVE_INFINITY; for (int i = 1; i < observations.length; ++i) { final double y = observations[i].getY(); if (y < yMin) { yMin = y; } if (y > yMax) { yMax = y; } } a = 0.5 * (yMax - yMin); } else { a = FastMath.sqrt(c1 / c2); omega = FastMath.sqrt(c2 / c3); } }
private void guessAOmega() { double sx2 = 0; double sy2 = 0; double sxy = 0; double sxz = 0; double syz = 0; double currentX = observations[0].getX(); double currentY = observations[0].getY(); double f2Integral = 0; double fPrime2Integral = 0; final double startX = currentX; for (int i = 1; i < observations.length; ++i) { final double previousX = currentX; final double previousY = currentY; currentX = observations[i].getX(); currentY = observations[i].getY(); final double dx = currentX - previousX; final double dy = currentY - previousY; final double f2StepIntegral = dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3; final double fPrime2StepIntegral = dy * dy / dx; final double x = currentX - startX; f2Integral += f2StepIntegral; fPrime2Integral += fPrime2StepIntegral; sx2 += x * x; sy2 += f2Integral * f2Integral; sxy += x * f2Integral; sxz += x * fPrime2Integral; syz += f2Integral * fPrime2Integral; } double c1 = sy2 * sxz - sxy * syz; double c2 = sxy * sxz - sx2 * syz; double c3 = sx2 * sy2 - sxy * sxy; if ((c1 / c2 < 0) || (c2 / c3 < 0)) { final int last = observations.length - 1; final double xRange = observations[last].getX() - observations[0].getX(); if (xRange == 0) { throw new ZeroException(); } omega = 2 * Math.PI / xRange; double yMin = Double.POSITIVE_INFINITY; double yMax = Double.NEGATIVE_INFINITY; for (int i = 1; i < observations.length; ++i) { final double y = observations[i].getY(); if (y < yMin) { yMin = y; } if (y > yMax) { yMax = y; } } a = 0.5 * (yMax - yMin); } else { if (c2 == 0) { throw new MathIllegalStateException(LocalizedFormats.ZERO_DENOMINATOR); } a = FastMath.sqrt(c1 / c2); omega = FastMath.sqrt(c2 / c3); } }
Mockito-27
public <T> void resetMock(T mock) { MockHandlerInterface<T> oldMockHandler = getMockHandler(mock); MockHandler<T> newMockHandler = new MockHandler<T>(oldMockHandler); MethodInterceptorFilter newFilter = new MethodInterceptorFilter(newMockHandler, (MockSettingsImpl) org.mockito.Mockito.withSettings().defaultAnswer(org.mockito.Mockito.RETURNS_DEFAULTS)); ((Factory) mock).setCallback(0, newFilter); }
public <T> void resetMock(T mock) { MockHandlerInterface<T> oldMockHandler = getMockHandler(mock); MethodInterceptorFilter newFilter = newMethodInterceptorFilter(oldMockHandler.getMockSettings()); ((Factory) mock).setCallback(0, newFilter); }
JacksonDatabind-7
public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { copyCurrentStructure(jp); return this; }
public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { if (jp.getCurrentTokenId() != JsonToken.FIELD_NAME.id()) { copyCurrentStructure(jp); return this; } JsonToken t; writeStartObject(); do { copyCurrentStructure(jp); } while ((t = jp.nextToken()) == JsonToken.FIELD_NAME); if (t != JsonToken.END_OBJECT) { throw ctxt.mappingException("Expected END_OBJECT after copying contents of a JsonParser into TokenBuffer, got "+t); } writeEndObject(); return this; }
Jsoup-57
public void removeIgnoreCase(String key) { Validate.notEmpty(key); if (attributes == null) return; for (Iterator<String> it = attributes.keySet().iterator(); it.hasNext(); ) { String attrKey = it.next(); if (attrKey.equalsIgnoreCase(key)) attributes.remove(attrKey); } }
public void removeIgnoreCase(String key) { Validate.notEmpty(key); if (attributes == null) return; for (Iterator<String> it = attributes.keySet().iterator(); it.hasNext(); ) { String attrKey = it.next(); if (attrKey.equalsIgnoreCase(key)) it.remove(); } }
Lang-27
public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { } default : throw new NumberFormatException(str + " is not a valid number."); } } else { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { try { return createInteger(str); } catch (NumberFormatException nfe) { } try { return createLong(str); } catch (NumberFormatException nfe) { } return createBigInteger(str); } else { boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } return createBigDecimal(str); } } }
public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { } default : throw new NumberFormatException(str + " is not a valid number."); } } else { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { try { return createInteger(str); } catch (NumberFormatException nfe) { } try { return createLong(str); } catch (NumberFormatException nfe) { } return createBigInteger(str); } else { boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } return createBigDecimal(str); } } }
Lang-22
private static int greatestCommonDivisor(int u, int v) { if (Math.abs(u) <= 1 || Math.abs(v) <= 1) { return 1; } if (u>0) { u=-u; } if (v>0) { v=-v; } int k=0; while ((u&1)==0 && (v&1)==0 && k<31) { u/=2; v/=2; k++; } if (k==31) { throw new ArithmeticException("overflow: gcd is 2^31"); } int t = ((u&1)==1) ? v : -(u/2); do { while ((t&1)==0) { t/=2; } if (t>0) { u = -t; } else { v = t; } t = (v - u)/2; } while (t!=0); return -u*(1<<k); }
private static int greatestCommonDivisor(int u, int v) { if ((u == 0) || (v == 0)) { if ((u == Integer.MIN_VALUE) || (v == Integer.MIN_VALUE)) { throw new ArithmeticException("overflow: gcd is 2^31"); } return Math.abs(u) + Math.abs(v); } if (Math.abs(u) == 1 || Math.abs(v) == 1) { return 1; } if (u>0) { u=-u; } if (v>0) { v=-v; } int k=0; while ((u&1)==0 && (v&1)==0 && k<31) { u/=2; v/=2; k++; } if (k==31) { throw new ArithmeticException("overflow: gcd is 2^31"); } int t = ((u&1)==1) ? v : -(u/2); do { while ((t&1)==0) { t/=2; } if (t>0) { u = -t; } else { v = t; } t = (v - u)/2; } while (t!=0); return -u*(1<<k); }
Cli-5
static String stripLeadingHyphens(String str) { if (str.startsWith("--")) { return str.substring(2, str.length()); } else if (str.startsWith("-")) { return str.substring(1, str.length()); } return str; }
static String stripLeadingHyphens(String str) { if (str == null) { return null; } if (str.startsWith("--")) { return str.substring(2, str.length()); } else if (str.startsWith("-")) { return str.substring(1, str.length()); } return str; }
Codec-6
public int read(byte b[], int offset, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (offset < 0 || len < 0) { throw new IndexOutOfBoundsException(); } else if (offset > b.length || offset + len > b.length) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } else { if (!base64.hasData()) { byte[] buf = new byte[doEncode ? 4096 : 8192]; int c = in.read(buf); if (c > 0 && b.length == len) { base64.setInitialBuffer(b, offset, len); } if (doEncode) { base64.encode(buf, 0, c); } else { base64.decode(buf, 0, c); } } return base64.readResults(b, offset, len); } }
public int read(byte b[], int offset, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (offset < 0 || len < 0) { throw new IndexOutOfBoundsException(); } else if (offset > b.length || offset + len > b.length) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } else { int readLen = 0; while (readLen == 0) { if (!base64.hasData()) { byte[] buf = new byte[doEncode ? 4096 : 8192]; int c = in.read(buf); if (c > 0 && b.length == len) { base64.setInitialBuffer(b, offset, len); } if (doEncode) { base64.encode(buf, 0, c); } else { base64.decode(buf, 0, c); } } readLen = base64.readResults(b, offset, len); } return readLen; } }
Math-50
protected final double doSolve() { double x0 = getMin(); double x1 = getMax(); double f0 = computeObjectiveValue(x0); double f1 = computeObjectiveValue(x1); if (f0 == 0.0) { return x0; } if (f1 == 0.0) { return x1; } verifyBracketing(x0, x1); final double ftol = getFunctionValueAccuracy(); final double atol = getAbsoluteAccuracy(); final double rtol = getRelativeAccuracy(); boolean inverted = false; while (true) { final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0)); final double fx = computeObjectiveValue(x); if (fx == 0.0) { return x; } if (f1 * fx < 0) { x0 = x1; f0 = f1; inverted = !inverted; } else { switch (method) { case ILLINOIS: f0 *= 0.5; break; case PEGASUS: f0 *= f1 / (f1 + fx); break; case REGULA_FALSI: if (x == x1) { x0 = 0.5 * (x0 + x1 - FastMath.max(rtol * FastMath.abs(x1), atol)); f0 = computeObjectiveValue(x0); } break; default: throw new MathInternalError(); } } x1 = x; f1 = fx; if (FastMath.abs(f1) <= ftol) { switch (allowed) { case ANY_SIDE: return x1; case LEFT_SIDE: if (inverted) { return x1; } break; case RIGHT_SIDE: if (!inverted) { return x1; } break; case BELOW_SIDE: if (f1 <= 0) { return x1; } break; case ABOVE_SIDE: if (f1 >= 0) { return x1; } break; default: throw new MathInternalError(); } } if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1), atol)) { switch (allowed) { case ANY_SIDE: return x1; case LEFT_SIDE: return inverted ? x1 : x0; case RIGHT_SIDE: return inverted ? x0 : x1; case BELOW_SIDE: return (f1 <= 0) ? x1 : x0; case ABOVE_SIDE: return (f1 >= 0) ? x1 : x0; default: throw new MathInternalError(); } } } }
protected final double doSolve() { double x0 = getMin(); double x1 = getMax(); double f0 = computeObjectiveValue(x0); double f1 = computeObjectiveValue(x1); if (f0 == 0.0) { return x0; } if (f1 == 0.0) { return x1; } verifyBracketing(x0, x1); final double ftol = getFunctionValueAccuracy(); final double atol = getAbsoluteAccuracy(); final double rtol = getRelativeAccuracy(); boolean inverted = false; while (true) { final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0)); final double fx = computeObjectiveValue(x); if (fx == 0.0) { return x; } if (f1 * fx < 0) { x0 = x1; f0 = f1; inverted = !inverted; } else { switch (method) { case ILLINOIS: f0 *= 0.5; break; case PEGASUS: f0 *= f1 / (f1 + fx); break; case REGULA_FALSI: break; default: throw new MathInternalError(); } } x1 = x; f1 = fx; if (FastMath.abs(f1) <= ftol) { switch (allowed) { case ANY_SIDE: return x1; case LEFT_SIDE: if (inverted) { return x1; } break; case RIGHT_SIDE: if (!inverted) { return x1; } break; case BELOW_SIDE: if (f1 <= 0) { return x1; } break; case ABOVE_SIDE: if (f1 >= 0) { return x1; } break; default: throw new MathInternalError(); } } if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1), atol)) { switch (allowed) { case ANY_SIDE: return x1; case LEFT_SIDE: return inverted ? x1 : x0; case RIGHT_SIDE: return inverted ? x0 : x1; case BELOW_SIDE: return (f1 <= 0) ? x1 : x0; case ABOVE_SIDE: return (f1 >= 0) ? x1 : x0; default: throw new MathInternalError(); } } } }
Math-39
public void integrate(final ExpandableStatefulODE equations, final double t) throws MathIllegalStateException, MathIllegalArgumentException { sanityChecks(equations, t); setEquations(equations); final boolean forward = t > equations.getTime(); final double[] y0 = equations.getCompleteState(); final double[] y = y0.clone(); final int stages = c.length + 1; final double[][] yDotK = new double[stages][y.length]; final double[] yTmp = y0.clone(); final double[] yDotTmp = new double[y.length]; final RungeKuttaStepInterpolator interpolator = (RungeKuttaStepInterpolator) prototype.copy(); interpolator.reinitialize(this, yTmp, yDotK, forward, equations.getPrimaryMapper(), equations.getSecondaryMappers()); interpolator.storeTime(equations.getTime()); stepStart = equations.getTime(); double hNew = 0; boolean firstTime = true; initIntegration(equations.getTime(), y0, t); isLastStep = false; do { interpolator.shift(); double error = 10; while (error >= 1.0) { if (firstTime || !fsal) { computeDerivatives(stepStart, y, yDotK[0]); } if (firstTime) { final double[] scale = new double[mainSetDimension]; if (vecAbsoluteTolerance == null) { for (int i = 0; i < scale.length; ++i) { scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * FastMath.abs(y[i]); } } else { for (int i = 0; i < scale.length; ++i) { scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * FastMath.abs(y[i]); } } hNew = initializeStep(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) { final double factor = FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp))); hNew = filterStep(stepSize * factor, forward, false); } } interpolator.storeTime(stepStart + stepSize); System.arraycopy(yTmp, 0, y, 0, y0.length); System.arraycopy(yDotK[stages - 1], 0, yDotTmp, 0, y0.length); stepStart = acceptStep(interpolator, y, yDotTmp, t); System.arraycopy(y, 0, yTmp, 0, y.length); if (!isLastStep) { interpolator.storeTime(stepStart); if (fsal) { System.arraycopy(yDotTmp, 0, yDotK[0], 0, y0.length); } final double factor = FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.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 filteredNextT = stepStart + hNew; final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t); if (filteredNextIsLast) { hNew = t - stepStart; } } } while (!isLastStep); equations.setTime(stepStart); equations.setCompleteState(y); resetInternalState(); }
public void integrate(final ExpandableStatefulODE equations, final double t) throws MathIllegalStateException, MathIllegalArgumentException { sanityChecks(equations, t); setEquations(equations); final boolean forward = t > equations.getTime(); final double[] y0 = equations.getCompleteState(); final double[] y = y0.clone(); final int stages = c.length + 1; final double[][] yDotK = new double[stages][y.length]; final double[] yTmp = y0.clone(); final double[] yDotTmp = new double[y.length]; final RungeKuttaStepInterpolator interpolator = (RungeKuttaStepInterpolator) prototype.copy(); interpolator.reinitialize(this, yTmp, yDotK, forward, equations.getPrimaryMapper(), equations.getSecondaryMappers()); interpolator.storeTime(equations.getTime()); stepStart = equations.getTime(); double hNew = 0; boolean firstTime = true; initIntegration(equations.getTime(), y0, t); isLastStep = false; do { interpolator.shift(); double error = 10; while (error >= 1.0) { if (firstTime || !fsal) { computeDerivatives(stepStart, y, yDotK[0]); } if (firstTime) { final double[] scale = new double[mainSetDimension]; if (vecAbsoluteTolerance == null) { for (int i = 0; i < scale.length; ++i) { scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * FastMath.abs(y[i]); } } else { for (int i = 0; i < scale.length; ++i) { scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * FastMath.abs(y[i]); } } hNew = initializeStep(forward, getOrder(), scale, stepStart, y, yDotK[0], yTmp, yDotK[1]); firstTime = false; } stepSize = hNew; if (forward) { if (stepStart + stepSize >= t) { stepSize = t - stepStart; } } else { if (stepStart + stepSize <= t) { stepSize = t - stepStart; } } 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) { final double factor = FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp))); hNew = filterStep(stepSize * factor, forward, false); } } interpolator.storeTime(stepStart + stepSize); System.arraycopy(yTmp, 0, y, 0, y0.length); System.arraycopy(yDotK[stages - 1], 0, yDotTmp, 0, y0.length); stepStart = acceptStep(interpolator, y, yDotTmp, t); System.arraycopy(y, 0, yTmp, 0, y.length); if (!isLastStep) { interpolator.storeTime(stepStart); if (fsal) { System.arraycopy(yDotTmp, 0, yDotK[0], 0, y0.length); } final double factor = FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.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 filteredNextT = stepStart + hNew; final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t); if (filteredNextIsLast) { hNew = t - stepStart; } } } while (!isLastStep); equations.setTime(stepStart); equations.setCompleteState(y); resetInternalState(); }
JacksonDatabind-5
protected void _addMethodMixIns(Class<?> targetClass, AnnotatedMethodMap methods, Class<?> mixInCls, AnnotatedMethodMap mixIns) { List<Class<?>> parents = new ArrayList<Class<?>>(); parents.add(mixInCls); ClassUtil.findSuperTypes(mixInCls, targetClass, parents); for (Class<?> mixin : parents) { for (Method m : mixin.getDeclaredMethods()) { if (!_isIncludableMemberMethod(m)) { continue; } AnnotatedMethod am = methods.find(m); if (am != null) { _addMixUnders(m, am); } else { mixIns.add(_constructMethod(m)); } } } }
protected void _addMethodMixIns(Class<?> targetClass, AnnotatedMethodMap methods, Class<?> mixInCls, AnnotatedMethodMap mixIns) { List<Class<?>> parents = new ArrayList<Class<?>>(); parents.add(mixInCls); ClassUtil.findSuperTypes(mixInCls, targetClass, parents); for (Class<?> mixin : parents) { for (Method m : mixin.getDeclaredMethods()) { if (!_isIncludableMemberMethod(m)) { continue; } AnnotatedMethod am = methods.find(m); if (am != null) { _addMixUnders(m, am); } else { am = mixIns.find(m); if (am != null) { _addMixUnders(m, am); } else { mixIns.add(_constructMethod(m)); } } } } }
Closure-69
private void visitCall(NodeTraversal t, Node n) { Node child = n.getFirstChild(); JSType childType = getJSType(child).restrictByNotNullOrUndefined(); if (!childType.canBeCalled()) { report(t, n, NOT_CALLABLE, childType.toString()); ensureTyped(t, n); return; } if (childType instanceof FunctionType) { FunctionType functionType = (FunctionType) childType; boolean isExtern = false; JSDocInfo functionJSDocInfo = functionType.getJSDocInfo(); if(functionJSDocInfo != null) { String sourceName = functionJSDocInfo.getSourceName(); CompilerInput functionSource = compiler.getInput(sourceName); isExtern = functionSource.isExtern(); } if (functionType.isConstructor() && !functionType.isNativeObjectType() && (functionType.getReturnType().isUnknownType() || functionType.getReturnType().isVoidType() || !isExtern)) { report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString()); } visitParameterList(t, n, functionType); ensureTyped(t, n, functionType.getReturnType()); } else { ensureTyped(t, n); } }
private void visitCall(NodeTraversal t, Node n) { Node child = n.getFirstChild(); JSType childType = getJSType(child).restrictByNotNullOrUndefined(); if (!childType.canBeCalled()) { report(t, n, NOT_CALLABLE, childType.toString()); ensureTyped(t, n); return; } if (childType instanceof FunctionType) { FunctionType functionType = (FunctionType) childType; boolean isExtern = false; JSDocInfo functionJSDocInfo = functionType.getJSDocInfo(); if(functionJSDocInfo != null) { String sourceName = functionJSDocInfo.getSourceName(); CompilerInput functionSource = compiler.getInput(sourceName); isExtern = functionSource.isExtern(); } if (functionType.isConstructor() && !functionType.isNativeObjectType() && (functionType.getReturnType().isUnknownType() || functionType.getReturnType().isVoidType() || !isExtern)) { report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString()); } if (functionType.isOrdinaryFunction() && !functionType.getTypeOfThis().isUnknownType() && !functionType.getTypeOfThis().isNativeObjectType() && !(child.getType() == Token.GETELEM || child.getType() == Token.GETPROP)) { report(t, n, EXPECTED_THIS_TYPE, functionType.toString()); } visitParameterList(t, n, functionType); ensureTyped(t, n, functionType.getReturnType()); } else { ensureTyped(t, n); } }
Jsoup-27
static String getCharsetFromContentType(String contentType) { if (contentType == null) return null; Matcher m = charsetPattern.matcher(contentType); if (m.find()) { String charset = m.group(1).trim(); charset = charset.toUpperCase(Locale.ENGLISH); return charset; } return null; }
static String getCharsetFromContentType(String contentType) { if (contentType == null) return null; Matcher m = charsetPattern.matcher(contentType); if (m.find()) { String charset = m.group(1).trim(); if (Charset.isSupported(charset)) return charset; charset = charset.toUpperCase(Locale.ENGLISH); if (Charset.isSupported(charset)) return charset; } return null; }
Gson-6
static TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson, TypeToken<?> fieldType, JsonAdapter annotation) { Class<?> value = annotation.value(); TypeAdapter<?> typeAdapter; if (TypeAdapter.class.isAssignableFrom(value)) { Class<TypeAdapter<?>> typeAdapterClass = (Class<TypeAdapter<?>>) value; typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterClass)).construct(); } else if (TypeAdapterFactory.class.isAssignableFrom(value)) { Class<TypeAdapterFactory> typeAdapterFactory = (Class<TypeAdapterFactory>) value; typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterFactory)) .construct() .create(gson, fieldType); } else { throw new IllegalArgumentException( "@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference."); } typeAdapter = typeAdapter.nullSafe(); return typeAdapter; }
static TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson, TypeToken<?> fieldType, JsonAdapter annotation) { Class<?> value = annotation.value(); TypeAdapter<?> typeAdapter; if (TypeAdapter.class.isAssignableFrom(value)) { Class<TypeAdapter<?>> typeAdapterClass = (Class<TypeAdapter<?>>) value; typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterClass)).construct(); } else if (TypeAdapterFactory.class.isAssignableFrom(value)) { Class<TypeAdapterFactory> typeAdapterFactory = (Class<TypeAdapterFactory>) value; typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterFactory)) .construct() .create(gson, fieldType); } else { throw new IllegalArgumentException( "@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference."); } if (typeAdapter != null) { typeAdapter = typeAdapter.nullSafe(); } return typeAdapter; }
Lang-38
public StringBuffer format(Calendar calendar, StringBuffer buf) { if (mTimeZoneForced) { calendar = (Calendar) calendar.clone(); calendar.setTimeZone(mTimeZone); } return applyRules(calendar, buf); }
public StringBuffer format(Calendar calendar, StringBuffer buf) { if (mTimeZoneForced) { calendar.getTime(); calendar = (Calendar) calendar.clone(); calendar.setTimeZone(mTimeZone); } return applyRules(calendar, buf); }
Mockito-38
private boolean toStringEquals(Matcher m, Object arg) { return StringDescription.toString(m).equals(arg.toString()); }
private boolean toStringEquals(Matcher m, Object arg) { return StringDescription.toString(m).equals(arg == null? "null" : arg.toString()); }
JacksonXml-4
protected void _serializeXmlNull(JsonGenerator jgen) throws IOException { if (jgen instanceof ToXmlGenerator) { _initWithRootName((ToXmlGenerator) jgen, ROOT_NAME_FOR_NULL); } super.serializeValue(jgen, null); }
protected void _serializeXmlNull(JsonGenerator jgen) throws IOException { QName rootName = _rootNameFromConfig(); if (rootName == null) { rootName = ROOT_NAME_FOR_NULL; } if (jgen instanceof ToXmlGenerator) { _initWithRootName((ToXmlGenerator) jgen, rootName); } super.serializeValue(jgen, null); }
JacksonDatabind-67
public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt, JavaType type) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); KeyDeserializer deser = null; if (_factoryConfig.hasKeyDeserializers()) { BeanDescription beanDesc = config.introspectClassAnnotations(type.getRawClass()); for (KeyDeserializers d : _factoryConfig.keyDeserializers()) { deser = d.findKeyDeserializer(type, config, beanDesc); if (deser != null) { break; } } } if (deser == null) { if (type.isEnumType()) { return _createEnumKeyDeserializer(ctxt, type); } deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type); } if (deser != null) { if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { deser = mod.modifyKeyDeserializer(config, type, deser); } } } return deser; }
public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt, JavaType type) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); KeyDeserializer deser = null; if (_factoryConfig.hasKeyDeserializers()) { BeanDescription beanDesc = config.introspectClassAnnotations(type.getRawClass()); for (KeyDeserializers d : _factoryConfig.keyDeserializers()) { deser = d.findKeyDeserializer(type, config, beanDesc); if (deser != null) { break; } } } if (deser == null) { if (type.isEnumType()) { deser = _createEnumKeyDeserializer(ctxt, type); } else { deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type); } } if (deser != null) { if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { deser = mod.modifyKeyDeserializer(config, type, deser); } } } return deser; }
Closure-13
private void traverse(Node node) { if (!shouldVisit(node)) { return; } int visits = 0; do { Node c = node.getFirstChild(); while(c != null) { traverse(c); Node next = c.getNext(); c = next; } visit(node); visits++; Preconditions.checkState(visits < 10000, "too many interations"); } while (shouldRetraverse(node)); exitNode(node); }
private void traverse(Node node) { if (!shouldVisit(node)) { return; } int visits = 0; do { Node c = node.getFirstChild(); while(c != null) { Node next = c.getNext(); traverse(c); c = next; } visit(node); visits++; Preconditions.checkState(visits < 10000, "too many interations"); } while (shouldRetraverse(node)); exitNode(node); }
Csv-5
public void println() throws IOException { final String recordSeparator = format.getRecordSeparator(); out.append(recordSeparator); newRecord = true; }
public void println() throws IOException { final String recordSeparator = format.getRecordSeparator(); if (recordSeparator != null) { out.append(recordSeparator); } newRecord = true; }
Csv-6
<M extends Map<String, String>> M putIn(final M map) { for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); map.put(entry.getKey(), values[col]); } return map; }
<M extends Map<String, String>> M putIn(final M map) { for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); if (col < values.length) { map.put(entry.getKey(), values[col]); } } return map; }
Chart-1
public LegendItemCollection getLegendItems() { LegendItemCollection result = new LegendItemCollection(); if (this.plot == null) { return result; } int index = this.plot.getIndexOf(this); CategoryDataset dataset = this.plot.getDataset(index); if (dataset != null) { return result; } int seriesCount = dataset.getRowCount(); if (plot.getRowRenderingOrder().equals(SortOrder.ASCENDING)) { for (int i = 0; i < seriesCount; i++) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } else { for (int i = seriesCount - 1; i >= 0; i--) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } return result; }
public LegendItemCollection getLegendItems() { LegendItemCollection result = new LegendItemCollection(); if (this.plot == null) { return result; } int index = this.plot.getIndexOf(this); CategoryDataset dataset = this.plot.getDataset(index); if (dataset == null) { return result; } int seriesCount = dataset.getRowCount(); if (plot.getRowRenderingOrder().equals(SortOrder.ASCENDING)) { for (int i = 0; i < seriesCount; i++) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } else { for (int i = seriesCount - 1; i >= 0; i--) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } return result; }
Math-97
public double solve(double min, double max) throws MaxIterationsExceededException, FunctionEvaluationException { clearResult(); verifyInterval(min, max); double ret = Double.NaN; double yMin = f.value(min); double yMax = f.value(max); double sign = yMin * yMax; if (sign >= 0) { throw new IllegalArgumentException ("Function values at endpoints do not have different signs." + " Endpoints: [" + min + "," + max + "]" + " Values: [" + yMin + "," + yMax + "]"); } else { ret = solve(min, yMin, max, yMax, min, yMin); } return ret; }
public double solve(double min, double max) throws MaxIterationsExceededException, FunctionEvaluationException { clearResult(); verifyInterval(min, max); double ret = Double.NaN; double yMin = f.value(min); double yMax = f.value(max); double sign = yMin * yMax; if (sign > 0) { if (Math.abs(yMin) <= functionValueAccuracy) { setResult(min, 0); ret = min; } else if (Math.abs(yMax) <= functionValueAccuracy) { setResult(max, 0); ret = max; } else { throw new IllegalArgumentException ("Function values at endpoints do not have different signs." + " Endpoints: [" + min + "," + max + "]" + " Values: [" + yMin + "," + yMax + "]"); } } else if (sign < 0){ ret = solve(min, yMin, max, yMax, min, yMin); } else { if (yMin == 0.0) { ret = min; } else { ret = max; } } return ret; }
Math-10
public void atan2(final double[] y, final int yOffset, final double[] x, final int xOffset, final double[] result, final int resultOffset) { double[] tmp1 = new double[getSize()]; multiply(x, xOffset, x, xOffset, tmp1, 0); double[] tmp2 = new double[getSize()]; multiply(y, yOffset, y, yOffset, tmp2, 0); add(tmp1, 0, tmp2, 0, tmp2, 0); rootN(tmp2, 0, 2, tmp1, 0); if (x[xOffset] >= 0) { add(tmp1, 0, x, xOffset, tmp2, 0); divide(y, yOffset, tmp2, 0, tmp1, 0); atan(tmp1, 0, tmp2, 0); for (int i = 0; i < tmp2.length; ++i) { result[resultOffset + i] = 2 * tmp2[i]; } } else { subtract(tmp1, 0, x, xOffset, tmp2, 0); divide(y, yOffset, tmp2, 0, tmp1, 0); atan(tmp1, 0, tmp2, 0); result[resultOffset] = ((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; for (int i = 1; i < tmp2.length; ++i) { result[resultOffset + i] = -2 * tmp2[i]; } } }
public void atan2(final double[] y, final int yOffset, final double[] x, final int xOffset, final double[] result, final int resultOffset) { double[] tmp1 = new double[getSize()]; multiply(x, xOffset, x, xOffset, tmp1, 0); double[] tmp2 = new double[getSize()]; multiply(y, yOffset, y, yOffset, tmp2, 0); add(tmp1, 0, tmp2, 0, tmp2, 0); rootN(tmp2, 0, 2, tmp1, 0); if (x[xOffset] >= 0) { add(tmp1, 0, x, xOffset, tmp2, 0); divide(y, yOffset, tmp2, 0, tmp1, 0); atan(tmp1, 0, tmp2, 0); for (int i = 0; i < tmp2.length; ++i) { result[resultOffset + i] = 2 * tmp2[i]; } } else { subtract(tmp1, 0, x, xOffset, tmp2, 0); divide(y, yOffset, tmp2, 0, tmp1, 0); atan(tmp1, 0, tmp2, 0); result[resultOffset] = ((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; for (int i = 1; i < tmp2.length; ++i) { result[resultOffset + i] = -2 * tmp2[i]; } } result[resultOffset] = FastMath.atan2(y[yOffset], x[xOffset]); }
Cli-14
public void validate(final WriteableCommandLine commandLine) throws OptionException { int present = 0; Option unexpected = null; for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); boolean validate = option.isRequired() || option instanceof Group; if (validate) { option.validate(commandLine); } if (commandLine.hasOption(option)) { if (++present > maximum) { unexpected = option; break; } option.validate(commandLine); } } if (unexpected != null) { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, unexpected.getPreferredName()); } if (present < minimum) { throw new OptionException(this, ResourceConstants.MISSING_OPTION); } for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.validate(commandLine); } }
public void validate(final WriteableCommandLine commandLine) throws OptionException { int present = 0; Option unexpected = null; for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); boolean validate = option.isRequired() || option instanceof Group; if (commandLine.hasOption(option)) { if (++present > maximum) { unexpected = option; break; } validate = true; } if (validate) { option.validate(commandLine); } } if (unexpected != null) { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, unexpected.getPreferredName()); } if (present < minimum) { throw new OptionException(this, ResourceConstants.MISSING_OPTION); } for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.validate(commandLine); } }
JxPath-21
public int getLength() { return ValueUtils.getLength(getBaseValue()); }
public int getLength() { Object baseValue = getBaseValue(); return baseValue == null ? 1 : ValueUtils.getLength(baseValue); }
Jsoup-72
private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) { if (count > maxStringCacheLen) return new String(charBuf, start, count); int hash = 0; int offset = start; for (int i = 0; i < count; i++) { hash = 31 * hash + charBuf[offset++]; } final int index = hash & stringCache.length - 1; String cached = stringCache[index]; if (cached == null) { cached = new String(charBuf, start, count); stringCache[index] = cached; } else { if (rangeEquals(charBuf, start, count, cached)) { return cached; } else { cached = new String(charBuf, start, count); stringCache[index] = cached; } } return cached; }
private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) { if (count > maxStringCacheLen) return new String(charBuf, start, count); if (count < 1) return ""; int hash = 0; int offset = start; for (int i = 0; i < count; i++) { hash = 31 * hash + charBuf[offset++]; } final int index = hash & stringCache.length - 1; String cached = stringCache[index]; if (cached == null) { cached = new String(charBuf, start, count); stringCache[index] = cached; } else { if (rangeEquals(charBuf, start, count, cached)) { return cached; } else { cached = new String(charBuf, start, count); stringCache[index] = cached; } } return cached; }
Closure-48
void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info, Node n, Node parent, Node rhsValue) { Node ownerNode = n.getFirstChild(); String ownerName = ownerNode.getQualifiedName(); String qName = n.getQualifiedName(); String propName = n.getLastChild().getString(); Preconditions.checkArgument(qName != null && ownerName != null); JSType valueType = getDeclaredType(t.getSourceName(), info, n, rhsValue); if (valueType == null && rhsValue != null) { valueType = rhsValue.getJSType(); } if ("prototype".equals(propName)) { Var qVar = scope.getVar(qName); if (qVar != null) { ObjectType qVarType = ObjectType.cast(qVar.getType()); if (qVarType != null && rhsValue != null && rhsValue.isObjectLit()) { typeRegistry.resetImplicitPrototype( rhsValue.getJSType(), qVarType.getImplicitPrototype()); } else if (!qVar.isTypeInferred()) { return; } if (qVar.getScope() == scope) { scope.undeclare(qVar); } } } if (valueType == null) { if (parent.isExprResult()) { stubDeclarations.add(new StubDeclaration( n, t.getInput() != null && t.getInput().isExtern(), ownerName)); } return; } boolean inferred = true; if (info != null) { inferred = !(info.hasType() || info.hasEnumParameterType() || (info.isConstant() && valueType != null && !valueType.isUnknownType()) || FunctionTypeBuilder.isFunctionTypeDeclaration(info)); } if (inferred) { inferred = !(rhsValue != null && rhsValue.isFunction() && (info != null || !scope.isDeclared(qName, false))); } if (!inferred) { ObjectType ownerType = getObjectSlot(ownerName); if (ownerType != null) { boolean isExtern = t.getInput() != null && t.getInput().isExtern(); if ((!ownerType.hasOwnProperty(propName) || ownerType.isPropertyTypeInferred(propName)) && ((isExtern && !ownerType.isNativeObjectType()) || !ownerType.isInstanceType())) { ownerType.defineDeclaredProperty(propName, valueType, n); } } defineSlot(n, parent, valueType, inferred); } else if (rhsValue != null && rhsValue.isTrue()) { FunctionType ownerType = JSType.toMaybeFunctionType(getObjectSlot(ownerName)); if (ownerType != null) { JSType ownerTypeOfThis = ownerType.getTypeOfThis(); String delegateName = codingConvention.getDelegateSuperclassName(); JSType delegateType = delegateName == null ? null : typeRegistry.getType(delegateName); if (delegateType != null && ownerTypeOfThis.isSubtype(delegateType)) { defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true); } } } }
void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info, Node n, Node parent, Node rhsValue) { Node ownerNode = n.getFirstChild(); String ownerName = ownerNode.getQualifiedName(); String qName = n.getQualifiedName(); String propName = n.getLastChild().getString(); Preconditions.checkArgument(qName != null && ownerName != null); JSType valueType = getDeclaredType(t.getSourceName(), info, n, rhsValue); if (valueType == null && rhsValue != null) { valueType = rhsValue.getJSType(); } if ("prototype".equals(propName)) { Var qVar = scope.getVar(qName); if (qVar != null) { ObjectType qVarType = ObjectType.cast(qVar.getType()); if (qVarType != null && rhsValue != null && rhsValue.isObjectLit()) { typeRegistry.resetImplicitPrototype( rhsValue.getJSType(), qVarType.getImplicitPrototype()); } else if (!qVar.isTypeInferred()) { return; } if (qVar.getScope() == scope) { scope.undeclare(qVar); } } } if (valueType == null) { if (parent.isExprResult()) { stubDeclarations.add(new StubDeclaration( n, t.getInput() != null && t.getInput().isExtern(), ownerName)); } return; } boolean inferred = true; if (info != null) { inferred = !(info.hasType() || info.hasEnumParameterType() || (info.isConstant() && valueType != null && !valueType.isUnknownType()) || FunctionTypeBuilder.isFunctionTypeDeclaration(info)); } if (inferred && rhsValue != null && rhsValue.isFunction()) { if (info != null) { inferred = false; } else if (!scope.isDeclared(qName, false) && n.isUnscopedQualifiedName()) { inferred = false; } } if (!inferred) { ObjectType ownerType = getObjectSlot(ownerName); if (ownerType != null) { boolean isExtern = t.getInput() != null && t.getInput().isExtern(); if ((!ownerType.hasOwnProperty(propName) || ownerType.isPropertyTypeInferred(propName)) && ((isExtern && !ownerType.isNativeObjectType()) || !ownerType.isInstanceType())) { ownerType.defineDeclaredProperty(propName, valueType, n); } } defineSlot(n, parent, valueType, inferred); } else if (rhsValue != null && rhsValue.isTrue()) { FunctionType ownerType = JSType.toMaybeFunctionType(getObjectSlot(ownerName)); if (ownerType != null) { JSType ownerTypeOfThis = ownerType.getTypeOfThis(); String delegateName = codingConvention.getDelegateSuperclassName(); JSType delegateType = delegateName == null ? null : typeRegistry.getType(delegateName); if (delegateType != null && ownerTypeOfThis.isSubtype(delegateType)) { defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true); } } } }
JacksonDatabind-54
protected BeanPropertyWriter buildWriter(SerializerProvider prov, BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer<?> ser, TypeSerializer typeSer, TypeSerializer contentTypeSer, AnnotatedMember am, boolean defaultUseStaticTyping) throws JsonMappingException { JavaType serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType); if (contentTypeSer != null) { if (serializationType == null) { serializationType = declaredType; } JavaType ct = serializationType.getContentType(); if (ct == null) { throw new IllegalStateException("Problem trying to create BeanPropertyWriter for property '" +propDef.getName()+"' (of type "+_beanDesc.getType()+"); serialization type "+serializationType+" has no content"); } serializationType = serializationType.withContentTypeHandler(contentTypeSer); ct = serializationType.getContentType(); } Object valueToSuppress = null; boolean suppressNulls = false; JsonInclude.Value inclV = _defaultInclusion.withOverrides(propDef.findInclusion()); JsonInclude.Include inclusion = inclV.getValueInclusion(); if (inclusion == JsonInclude.Include.USE_DEFAULTS) { inclusion = JsonInclude.Include.ALWAYS; } JavaType actualType = (serializationType == null) ? declaredType : serializationType; switch (inclusion) { case NON_DEFAULT: if (_defaultInclusion.getValueInclusion() == JsonInclude.Include.NON_DEFAULT) { valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType); } else { valueToSuppress = getDefaultValue(actualType); } if (valueToSuppress == null) { suppressNulls = true; } else { if (valueToSuppress.getClass().isArray()) { valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress); } } break; case NON_ABSENT: suppressNulls = true; if (declaredType.isReferenceType()) { valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; } break; case NON_EMPTY: suppressNulls = true; valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; break; case NON_NULL: suppressNulls = true; case ALWAYS: default: if (declaredType.isContainerType() && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) { valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; } break; } BeanPropertyWriter bpw = new BeanPropertyWriter(propDef, am, _beanDesc.getClassAnnotations(), declaredType, ser, typeSer, serializationType, suppressNulls, valueToSuppress); Object serDef = _annotationIntrospector.findNullSerializer(am); if (serDef != null) { bpw.assignNullSerializer(prov.serializerInstance(am, serDef)); } NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am); if (unwrapper != null) { bpw = bpw.unwrappingWriter(unwrapper); } return bpw; }
protected BeanPropertyWriter buildWriter(SerializerProvider prov, BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer<?> ser, TypeSerializer typeSer, TypeSerializer contentTypeSer, AnnotatedMember am, boolean defaultUseStaticTyping) throws JsonMappingException { JavaType serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType); if (contentTypeSer != null) { if (serializationType == null) { serializationType = declaredType; } JavaType ct = serializationType.getContentType(); if (ct == null) { throw new IllegalStateException("Problem trying to create BeanPropertyWriter for property '" +propDef.getName()+"' (of type "+_beanDesc.getType()+"); serialization type "+serializationType+" has no content"); } serializationType = serializationType.withContentTypeHandler(contentTypeSer); ct = serializationType.getContentType(); } Object valueToSuppress = null; boolean suppressNulls = false; JsonInclude.Value inclV = _defaultInclusion.withOverrides(propDef.findInclusion()); JsonInclude.Include inclusion = inclV.getValueInclusion(); if (inclusion == JsonInclude.Include.USE_DEFAULTS) { inclusion = JsonInclude.Include.ALWAYS; } JavaType actualType = (serializationType == null) ? declaredType : serializationType; switch (inclusion) { case NON_DEFAULT: if (_defaultInclusion.getValueInclusion() == JsonInclude.Include.NON_DEFAULT) { valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType); } else { valueToSuppress = getDefaultValue(actualType); } if (valueToSuppress == null) { suppressNulls = true; } else { if (valueToSuppress.getClass().isArray()) { valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress); } } break; case NON_ABSENT: suppressNulls = true; if (actualType.isReferenceType()) { valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; } break; case NON_EMPTY: suppressNulls = true; valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; break; case NON_NULL: suppressNulls = true; case ALWAYS: default: if (actualType.isContainerType() && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) { valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY; } break; } BeanPropertyWriter bpw = new BeanPropertyWriter(propDef, am, _beanDesc.getClassAnnotations(), declaredType, ser, typeSer, serializationType, suppressNulls, valueToSuppress); Object serDef = _annotationIntrospector.findNullSerializer(am); if (serDef != null) { bpw.assignNullSerializer(prov.serializerInstance(am, serDef)); } NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am); if (unwrapper != null) { bpw = bpw.unwrappingWriter(unwrapper); } return bpw; }
Lang-9
private void init() { thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR); nameValues= new ConcurrentHashMap<Integer, KeyValue[]>(); StringBuilder regex= new StringBuilder(); List<Strategy> collector = new ArrayList<Strategy>(); Matcher patternMatcher= formatPattern.matcher(pattern); if(!patternMatcher.lookingAt()) { throw new IllegalArgumentException("Invalid pattern"); } currentFormatField= patternMatcher.group(); Strategy currentStrategy= getStrategy(currentFormatField); for(;;) { patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd()); if(!patternMatcher.lookingAt()) { nextStrategy = null; break; } String nextFormatField= patternMatcher.group(); nextStrategy = getStrategy(nextFormatField); if(currentStrategy.addRegex(this, regex)) { collector.add(currentStrategy); } currentFormatField= nextFormatField; currentStrategy= nextStrategy; } if(currentStrategy.addRegex(this, regex)) { collector.add(currentStrategy); } currentFormatField= null; strategies= collector.toArray(new Strategy[collector.size()]); parsePattern= Pattern.compile(regex.toString()); }
private void init() { thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR); nameValues= new ConcurrentHashMap<Integer, KeyValue[]>(); StringBuilder regex= new StringBuilder(); List<Strategy> collector = new ArrayList<Strategy>(); Matcher patternMatcher= formatPattern.matcher(pattern); if(!patternMatcher.lookingAt()) { throw new IllegalArgumentException("Invalid pattern"); } currentFormatField= patternMatcher.group(); Strategy currentStrategy= getStrategy(currentFormatField); for(;;) { patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd()); if(!patternMatcher.lookingAt()) { nextStrategy = null; break; } String nextFormatField= patternMatcher.group(); nextStrategy = getStrategy(nextFormatField); if(currentStrategy.addRegex(this, regex)) { collector.add(currentStrategy); } currentFormatField= nextFormatField; currentStrategy= nextStrategy; } if (patternMatcher.regionStart() != patternMatcher.regionEnd()) { throw new IllegalArgumentException("Failed to parse \""+pattern+"\" ; gave up at index "+patternMatcher.regionStart()); } if(currentStrategy.addRegex(this, regex)) { collector.add(currentStrategy); } currentFormatField= null; strategies= collector.toArray(new Strategy[collector.size()]); parsePattern= Pattern.compile(regex.toString()); }
Lang-54
public static Locale toLocale(String str) { if (str == null) { return null; } int len = str.length(); if (len != 2 && len != 5 && len < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch0 = str.charAt(0); char ch1 = str.charAt(1); if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 2) { return new Locale(str, ""); } else { if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch3 = str.charAt(3); char ch4 = str.charAt(4); if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } else { 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(String str) { if (str == null) { return null; } int len = str.length(); if (len != 2 && len != 5 && len < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch0 = str.charAt(0); char ch1 = str.charAt(1); if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 2) { return new Locale(str, ""); } else { if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch3 = str.charAt(3); if (ch3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); } char ch4 = str.charAt(4); if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } else { 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)); } } }
JacksonDatabind-9
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { String str; if (value instanceof Date) { provider.defaultSerializeDateKey((Date) value, jgen); return; } else { str = value.toString(); } jgen.writeFieldName(str); }
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { String str; Class<?> cls = value.getClass(); if (cls == String.class) { str = (String) value; } else if (Date.class.isAssignableFrom(cls)) { provider.defaultSerializeDateKey((Date) value, jgen); return; } else if (cls == Class.class) { str = ((Class<?>) value).getName(); } else { str = value.toString(); } jgen.writeFieldName(str); }
Closure-107
protected CompilerOptions createOptions() { CompilerOptions options = new CompilerOptions(); if (flags.processJqueryPrimitives) { options.setCodingConvention(new JqueryCodingConvention()); } else { options.setCodingConvention(new ClosureCodingConvention()); } options.setExtraAnnotationNames(flags.extraAnnotationName); CompilationLevel level = flags.compilationLevel; level.setOptionsForCompilationLevel(options); if (flags.debug) { level.setDebugOptionsForCompilationLevel(options); } if (flags.useTypesForOptimization) { level.setTypeBasedOptimizationOptions(options); } if (flags.generateExports) { options.setGenerateExports(flags.generateExports); } WarningLevel wLevel = flags.warningLevel; wLevel.setOptionsForWarningLevel(options); for (FormattingOption formattingOption : flags.formatting) { formattingOption.applyToOptions(options); } options.closurePass = flags.processClosurePrimitives; options.jqueryPass = CompilationLevel.ADVANCED_OPTIMIZATIONS == level && flags.processJqueryPrimitives; options.angularPass = flags.angularPass; if (!flags.translationsFile.isEmpty()) { try { options.messageBundle = new XtbMessageBundle( new FileInputStream(flags.translationsFile), flags.translationsProject); } catch (IOException e) { throw new RuntimeException("Reading XTB file", e); } } else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) { options.messageBundle = new EmptyMessageBundle(); } return options; }
protected CompilerOptions createOptions() { CompilerOptions options = new CompilerOptions(); if (flags.processJqueryPrimitives) { options.setCodingConvention(new JqueryCodingConvention()); } else { options.setCodingConvention(new ClosureCodingConvention()); } options.setExtraAnnotationNames(flags.extraAnnotationName); CompilationLevel level = flags.compilationLevel; level.setOptionsForCompilationLevel(options); if (flags.debug) { level.setDebugOptionsForCompilationLevel(options); } if (flags.useTypesForOptimization) { level.setTypeBasedOptimizationOptions(options); } if (flags.generateExports) { options.setGenerateExports(flags.generateExports); } WarningLevel wLevel = flags.warningLevel; wLevel.setOptionsForWarningLevel(options); for (FormattingOption formattingOption : flags.formatting) { formattingOption.applyToOptions(options); } options.closurePass = flags.processClosurePrimitives; options.jqueryPass = CompilationLevel.ADVANCED_OPTIMIZATIONS == level && flags.processJqueryPrimitives; options.angularPass = flags.angularPass; if (!flags.translationsFile.isEmpty()) { try { options.messageBundle = new XtbMessageBundle( new FileInputStream(flags.translationsFile), flags.translationsProject); } catch (IOException e) { throw new RuntimeException("Reading XTB file", e); } } else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) { options.messageBundle = new EmptyMessageBundle(); options.setWarningLevel(JsMessageVisitor.MSG_CONVENTIONS, CheckLevel.OFF); } return options; }
Closure-1
private void removeUnreferencedFunctionArgs(Scope fnScope) { Node function = fnScope.getRootNode(); Preconditions.checkState(function.isFunction()); if (NodeUtil.isGetOrSetKey(function.getParent())) { return; } Node argList = getFunctionArgList(function); boolean modifyCallers = modifyCallSites && callSiteOptimizer.canModifyCallers(function); if (!modifyCallers) { Node lastArg; while ((lastArg = argList.getLastChild()) != null) { Var var = fnScope.getVar(lastArg.getString()); if (!referenced.contains(var)) { argList.removeChild(lastArg); compiler.reportCodeChange(); } else { break; } } } else { callSiteOptimizer.optimize(fnScope, referenced); } }
private void removeUnreferencedFunctionArgs(Scope fnScope) { if (!removeGlobals) { return; } Node function = fnScope.getRootNode(); Preconditions.checkState(function.isFunction()); if (NodeUtil.isGetOrSetKey(function.getParent())) { return; } Node argList = getFunctionArgList(function); boolean modifyCallers = modifyCallSites && callSiteOptimizer.canModifyCallers(function); if (!modifyCallers) { Node lastArg; while ((lastArg = argList.getLastChild()) != null) { Var var = fnScope.getVar(lastArg.getString()); if (!referenced.contains(var)) { argList.removeChild(lastArg); compiler.reportCodeChange(); } else { break; } } } else { callSiteOptimizer.optimize(fnScope, referenced); } }
Closure-120
boolean isAssignedOnceInLifetime() { Reference ref = getOneAndOnlyAssignment(); if (ref == null) { return false; } for (BasicBlock block = ref.getBasicBlock(); block != null; block = block.getParent()) { if (block.isFunction) { break; } else if (block.isLoop) { return false; } } return true; }
boolean isAssignedOnceInLifetime() { Reference ref = getOneAndOnlyAssignment(); if (ref == null) { return false; } for (BasicBlock block = ref.getBasicBlock(); block != null; block = block.getParent()) { if (block.isFunction) { if (ref.getSymbol().getScope() != ref.scope) { return false; } break; } else if (block.isLoop) { return false; } } return true; }
Compress-28
public int read(byte[] buf, int offset, int numToRead) throws IOException { int totalRead = 0; if (hasHitEOF || entryOffset >= entrySize) { return -1; } if (currEntry == null) { throw new IllegalStateException("No current tar entry"); } numToRead = Math.min(numToRead, available()); totalRead = is.read(buf, offset, numToRead); count(totalRead); if (totalRead == -1) { hasHitEOF = true; } else { entryOffset += totalRead; } return totalRead; }
public int read(byte[] buf, int offset, int numToRead) throws IOException { int totalRead = 0; if (hasHitEOF || entryOffset >= entrySize) { return -1; } if (currEntry == null) { throw new IllegalStateException("No current tar entry"); } numToRead = Math.min(numToRead, available()); totalRead = is.read(buf, offset, numToRead); if (totalRead == -1) { if (numToRead > 0) { throw new IOException("Truncated TAR archive"); } hasHitEOF = true; } else { count(totalRead); entryOffset += totalRead; } return totalRead; }
Math-102
public double chiSquare(double[] expected, long[] observed) throws IllegalArgumentException { if ((expected.length < 2) || (expected.length != observed.length)) { throw new IllegalArgumentException( "observed, expected array lengths incorrect"); } if (!isPositive(expected) || !isNonNegative(observed)) { throw new IllegalArgumentException( "observed counts must be non-negative and expected counts must be postive"); } double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i < observed.length; i++) { dev = ((double) observed[i] - expected[i]); sumSq += dev * dev / expected[i]; } return sumSq; }
public double chiSquare(double[] expected, long[] observed) throws IllegalArgumentException { if ((expected.length < 2) || (expected.length != observed.length)) { throw new IllegalArgumentException( "observed, expected array lengths incorrect"); } if (!isPositive(expected) || !isNonNegative(observed)) { throw new IllegalArgumentException( "observed counts must be non-negative and expected counts must be postive"); } double sumExpected = 0d; double sumObserved = 0d; for (int i = 0; i < observed.length; i++) { sumExpected += expected[i]; sumObserved += observed[i]; } double ratio = 1.0d; boolean rescale = false; if (Math.abs(sumExpected - sumObserved) > 10E-6) { ratio = sumObserved / sumExpected; rescale = true; } double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i < observed.length; i++) { if (rescale) { dev = ((double) observed[i] - ratio * expected[i]); sumSq += dev * dev / (ratio * expected[i]); } else { dev = ((double) observed[i] - expected[i]); sumSq += dev * dev / expected[i]; } } return sumSq; }
Closure-82
public final boolean isEmptyType() { return isNoType() || isNoObjectType() || isNoResolvedType(); }
public final boolean isEmptyType() { return isNoType() || isNoObjectType() || isNoResolvedType() || (registry.getNativeFunctionType( JSTypeNative.LEAST_FUNCTION_TYPE) == this); }
Lang-42
public void escape(Writer writer, String str) throws IOException { int len = str.length(); for (int i = 0; i < len; i++) { char c = str.charAt(i); String entityName = this.entityName(c); if (entityName == null) { if (c > 0x7F) { writer.write("&#"); writer.write(Integer.toString(c, 10)); writer.write(';'); } else { writer.write(c); } } else { writer.write('&'); writer.write(entityName); writer.write(';'); } } }
public void escape(Writer writer, String str) throws IOException { int len = str.length(); for (int i = 0; i < len; i++) { int c = Character.codePointAt(str, i); String entityName = this.entityName(c); if (entityName == null) { if (c >= 0x010000 && i < len - 1) { writer.write("&#"); writer.write(Integer.toString(c, 10)); writer.write(';'); i++; } else if (c > 0x7F) { writer.write("&#"); writer.write(Integer.toString(c, 10)); writer.write(';'); } else { writer.write(c); } } else { writer.write('&'); writer.write(entityName); writer.write(';'); } } }
Lang-61
public int indexOf(String str, int startIndex) { startIndex = (startIndex < 0 ? 0 : startIndex); if (str == null || startIndex >= size) { return -1; } int strLen = str.length(); if (strLen == 1) { return indexOf(str.charAt(0), startIndex); } if (strLen == 0) { return startIndex; } if (strLen > size) { return -1; } char[] thisBuf = buffer; int len = thisBuf.length - strLen; outer: for (int i = startIndex; i < len; i++) { for (int j = 0; j < strLen; j++) { if (str.charAt(j) != thisBuf[i + j]) { continue outer; } } return i; } return -1; }
public int indexOf(String str, int startIndex) { startIndex = (startIndex < 0 ? 0 : startIndex); if (str == null || startIndex >= size) { return -1; } int strLen = str.length(); if (strLen == 1) { return indexOf(str.charAt(0), startIndex); } if (strLen == 0) { return startIndex; } if (strLen > size) { return -1; } char[] thisBuf = buffer; int len = size - strLen + 1; outer: for (int i = startIndex; i < len; i++) { for (int j = 0; j < strLen; j++) { if (str.charAt(j) != thisBuf[i + j]) { continue outer; } } return i; } return -1; }
Closure-33
public void matchConstraint(ObjectType constraintObj) { if (constraintObj.isRecordType()) { for (String prop : constraintObj.getOwnPropertyNames()) { JSType propType = constraintObj.getPropertyType(prop); if (!isPropertyTypeDeclared(prop)) { JSType typeToInfer = propType; if (!hasProperty(prop)) { typeToInfer = getNativeType(JSTypeNative.VOID_TYPE) .getLeastSupertype(propType); } defineInferredProperty(prop, typeToInfer, null); } } } }
public void matchConstraint(ObjectType constraintObj) { if (hasReferenceName()) { return; } if (constraintObj.isRecordType()) { for (String prop : constraintObj.getOwnPropertyNames()) { JSType propType = constraintObj.getPropertyType(prop); if (!isPropertyTypeDeclared(prop)) { JSType typeToInfer = propType; if (!hasProperty(prop)) { typeToInfer = getNativeType(JSTypeNative.VOID_TYPE) .getLeastSupertype(propType); } defineInferredProperty(prop, typeToInfer, null); } } } }
JacksonDatabind-102
public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException { if (property == null) { return this; } JsonFormat.Value format = findFormatOverrides(serializers, property, handledType()); if (format == null) { return this; } JsonFormat.Shape shape = format.getShape(); if (shape.isNumeric()) { return withFormat(Boolean.TRUE, null); } if (format.hasPattern()) { final Locale loc = format.hasLocale() ? format.getLocale() : serializers.getLocale(); SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc); TimeZone tz = format.hasTimeZone() ? format.getTimeZone() : serializers.getTimeZone(); df.setTimeZone(tz); return withFormat(Boolean.FALSE, df); } final boolean hasLocale = format.hasLocale(); final boolean hasTZ = format.hasTimeZone(); final boolean asString = (shape == JsonFormat.Shape.STRING); if (!hasLocale && !hasTZ && !asString) { return this; } DateFormat df0 = serializers.getConfig().getDateFormat(); if (df0 instanceof StdDateFormat) { StdDateFormat std = (StdDateFormat) df0; if (format.hasLocale()) { std = std.withLocale(format.getLocale()); } if (format.hasTimeZone()) { std = std.withTimeZone(format.getTimeZone()); } return withFormat(Boolean.FALSE, std); } if (!(df0 instanceof SimpleDateFormat)) { serializers.reportBadDefinition(handledType(), String.format( "Configured `DateFormat` (%s) not a `SimpleDateFormat`; cannot configure `Locale` or `TimeZone`", df0.getClass().getName())); } SimpleDateFormat df = (SimpleDateFormat) df0; if (hasLocale) { df = new SimpleDateFormat(df.toPattern(), format.getLocale()); } else { df = (SimpleDateFormat) df.clone(); } TimeZone newTz = format.getTimeZone(); boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone()); if (changeTZ) { df.setTimeZone(newTz); } return withFormat(Boolean.FALSE, df); }
public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException { JsonFormat.Value format = findFormatOverrides(serializers, property, handledType()); if (format == null) { return this; } JsonFormat.Shape shape = format.getShape(); if (shape.isNumeric()) { return withFormat(Boolean.TRUE, null); } if (format.hasPattern()) { final Locale loc = format.hasLocale() ? format.getLocale() : serializers.getLocale(); SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc); TimeZone tz = format.hasTimeZone() ? format.getTimeZone() : serializers.getTimeZone(); df.setTimeZone(tz); return withFormat(Boolean.FALSE, df); } final boolean hasLocale = format.hasLocale(); final boolean hasTZ = format.hasTimeZone(); final boolean asString = (shape == JsonFormat.Shape.STRING); if (!hasLocale && !hasTZ && !asString) { return this; } DateFormat df0 = serializers.getConfig().getDateFormat(); if (df0 instanceof StdDateFormat) { StdDateFormat std = (StdDateFormat) df0; if (format.hasLocale()) { std = std.withLocale(format.getLocale()); } if (format.hasTimeZone()) { std = std.withTimeZone(format.getTimeZone()); } return withFormat(Boolean.FALSE, std); } if (!(df0 instanceof SimpleDateFormat)) { serializers.reportBadDefinition(handledType(), String.format( "Configured `DateFormat` (%s) not a `SimpleDateFormat`; cannot configure `Locale` or `TimeZone`", df0.getClass().getName())); } SimpleDateFormat df = (SimpleDateFormat) df0; if (hasLocale) { df = new SimpleDateFormat(df.toPattern(), format.getLocale()); } else { df = (SimpleDateFormat) df.clone(); } TimeZone newTz = format.getTimeZone(); boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone()); if (changeTZ) { df.setTimeZone(newTz); } return withFormat(Boolean.FALSE, df); }
Compress-36
private InputStream getCurrentStream() throws IOException { if (deferredBlockStreams.isEmpty()) { throw new IllegalStateException("No current 7z entry (call getNextEntry() first)."); } while (deferredBlockStreams.size() > 1) { final InputStream stream = deferredBlockStreams.remove(0); IOUtils.skip(stream, Long.MAX_VALUE); stream.close(); } return deferredBlockStreams.get(0); }
private InputStream getCurrentStream() throws IOException { if (archive.files[currentEntryIndex].getSize() == 0) { return new ByteArrayInputStream(new byte[0]); } if (deferredBlockStreams.isEmpty()) { throw new IllegalStateException("No current 7z entry (call getNextEntry() first)."); } while (deferredBlockStreams.size() > 1) { final InputStream stream = deferredBlockStreams.remove(0); IOUtils.skip(stream, Long.MAX_VALUE); stream.close(); } return deferredBlockStreams.get(0); }
Chart-3
public TimeSeries createCopy(int start, int end) throws CloneNotSupportedException { if (start < 0) { throw new IllegalArgumentException("Requires start >= 0."); } if (end < start) { throw new IllegalArgumentException("Requires start <= end."); } TimeSeries copy = (TimeSeries) super.clone(); copy.data = new java.util.ArrayList(); if (this.data.size() > 0) { for (int index = start; index <= end; index++) { TimeSeriesDataItem item = (TimeSeriesDataItem) this.data.get(index); TimeSeriesDataItem clone = (TimeSeriesDataItem) item.clone(); try { copy.add(clone); } catch (SeriesException e) { e.printStackTrace(); } } } return copy; }
public TimeSeries createCopy(int start, int end) throws CloneNotSupportedException { if (start < 0) { throw new IllegalArgumentException("Requires start >= 0."); } if (end < start) { throw new IllegalArgumentException("Requires start <= end."); } TimeSeries copy = (TimeSeries) super.clone(); copy.minY = Double.NaN; copy.maxY = Double.NaN; copy.data = new java.util.ArrayList(); if (this.data.size() > 0) { for (int index = start; index <= end; index++) { TimeSeriesDataItem item = (TimeSeriesDataItem) this.data.get(index); TimeSeriesDataItem clone = (TimeSeriesDataItem) item.clone(); try { copy.add(clone); } catch (SeriesException e) { e.printStackTrace(); } } } return copy; }
Cli-37
private boolean isShortOption(String token) { return token.startsWith("-") && token.length() >= 2 && options.hasShortOption(token.substring(1, 2)); }
private boolean isShortOption(String token) { if (!token.startsWith("-") || token.length() == 1) { return false; } int pos = token.indexOf("="); String optName = pos == -1 ? token.substring(1) : token.substring(1, pos); return options.hasShortOption(optName); }
Math-44
protected double acceptStep(final AbstractStepInterpolator interpolator, final double[] y, final double[] yDot, final double tEnd) throws MathIllegalStateException { double previousT = interpolator.getGlobalPreviousTime(); final double currentT = interpolator.getGlobalCurrentTime(); resetOccurred = false; if (! statesInitialized) { for (EventState state : eventsStates) { state.reinitializeBegin(interpolator); } statesInitialized = true; } final int orderingSign = interpolator.isForward() ? +1 : -1; SortedSet<EventState> occuringEvents = new TreeSet<EventState>(new Comparator<EventState>() { public int compare(EventState es0, EventState es1) { return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime()); } }); for (final EventState state : eventsStates) { if (state.evaluateStep(interpolator)) { occuringEvents.add(state); } } while (!occuringEvents.isEmpty()) { final Iterator<EventState> iterator = occuringEvents.iterator(); final EventState currentEvent = iterator.next(); iterator.remove(); final double eventT = currentEvent.getEventTime(); interpolator.setSoftPreviousTime(previousT); interpolator.setSoftCurrentTime(eventT); interpolator.setInterpolatedTime(eventT); final double[] eventY = interpolator.getInterpolatedState(); currentEvent.stepAccepted(eventT, eventY); isLastStep = currentEvent.stop(); for (final StepHandler handler : stepHandlers) { handler.handleStep(interpolator, isLastStep); } if (isLastStep) { System.arraycopy(eventY, 0, y, 0, y.length); return eventT; } if (currentEvent.reset(eventT, eventY)) { System.arraycopy(eventY, 0, y, 0, y.length); computeDerivatives(eventT, y, yDot); resetOccurred = true; return eventT; } previousT = eventT; interpolator.setSoftPreviousTime(eventT); interpolator.setSoftCurrentTime(currentT); if (currentEvent.evaluateStep(interpolator)) { occuringEvents.add(currentEvent); } } interpolator.setInterpolatedTime(currentT); final double[] currentY = interpolator.getInterpolatedState(); for (final EventState state : eventsStates) { state.stepAccepted(currentT, currentY); isLastStep = isLastStep || state.stop(); } isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1); for (StepHandler handler : stepHandlers) { handler.handleStep(interpolator, isLastStep); } return currentT; }
protected double acceptStep(final AbstractStepInterpolator interpolator, final double[] y, final double[] yDot, final double tEnd) throws MathIllegalStateException { double previousT = interpolator.getGlobalPreviousTime(); final double currentT = interpolator.getGlobalCurrentTime(); if (! statesInitialized) { for (EventState state : eventsStates) { state.reinitializeBegin(interpolator); } statesInitialized = true; } final int orderingSign = interpolator.isForward() ? +1 : -1; SortedSet<EventState> occuringEvents = new TreeSet<EventState>(new Comparator<EventState>() { public int compare(EventState es0, EventState es1) { return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime()); } }); for (final EventState state : eventsStates) { if (state.evaluateStep(interpolator)) { occuringEvents.add(state); } } while (!occuringEvents.isEmpty()) { final Iterator<EventState> iterator = occuringEvents.iterator(); final EventState currentEvent = iterator.next(); iterator.remove(); final double eventT = currentEvent.getEventTime(); interpolator.setSoftPreviousTime(previousT); interpolator.setSoftCurrentTime(eventT); interpolator.setInterpolatedTime(eventT); final double[] eventY = interpolator.getInterpolatedState(); currentEvent.stepAccepted(eventT, eventY); isLastStep = currentEvent.stop(); for (final StepHandler handler : stepHandlers) { handler.handleStep(interpolator, isLastStep); } if (isLastStep) { System.arraycopy(eventY, 0, y, 0, y.length); for (final EventState remaining : occuringEvents) { remaining.stepAccepted(eventT, eventY); } return eventT; } if (currentEvent.reset(eventT, eventY)) { System.arraycopy(eventY, 0, y, 0, y.length); computeDerivatives(eventT, y, yDot); resetOccurred = true; for (final EventState remaining : occuringEvents) { remaining.stepAccepted(eventT, eventY); } return eventT; } previousT = eventT; interpolator.setSoftPreviousTime(eventT); interpolator.setSoftCurrentTime(currentT); if (currentEvent.evaluateStep(interpolator)) { occuringEvents.add(currentEvent); } } interpolator.setInterpolatedTime(currentT); final double[] currentY = interpolator.getInterpolatedState(); for (final EventState state : eventsStates) { state.stepAccepted(currentT, currentY); isLastStep = isLastStep || state.stop(); } isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1); for (StepHandler handler : stepHandlers) { handler.handleStep(interpolator, isLastStep); } return currentT; }
Csv-9
<M extends Map<String, String>> M putIn(final M map) { for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); if (col < values.length) { map.put(entry.getKey(), values[col]); } } return map; }
<M extends Map<String, String>> M putIn(final M map) { if (mapping == null) { return map; } for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); if (col < values.length) { map.put(entry.getKey(), values[col]); } } return map; }