repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
ZieIony/Carbon | carbon/src/main/java/carbon/widget/AutoCompleteEditText.java | AutoCompleteEditText.performCompletion | public void performCompletion(String s) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
if (selStart != selEnd)
return;
Editable text = getText();
HintSpan[] spans = text.getSpans(0, length(), HintSpan.class);
if (spans.length > 1)
throw new IllegalStateException("more than one HintSpan");
Word word = getCurrentWord();
if (word == null)
throw new IllegalStateException("no word to complete");
autoCompleting = true;
//for (HintSpan span : spans)
// text.delete(text.getSpanStart(span), text.getSpanEnd(span));
text.delete(selStart, selStart + word.postCursor.length());
text.delete(selStart - word.preCursor.length(), selStart);
text.insert(selStart - word.preCursor.length(), s);
setSelection(selStart - word.preCursor.length() + s.length());
fireOnFilterEvent(null);
super.setImeOptions(prevOptions);
autoCompleting = false;
} | java | public void performCompletion(String s) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
if (selStart != selEnd)
return;
Editable text = getText();
HintSpan[] spans = text.getSpans(0, length(), HintSpan.class);
if (spans.length > 1)
throw new IllegalStateException("more than one HintSpan");
Word word = getCurrentWord();
if (word == null)
throw new IllegalStateException("no word to complete");
autoCompleting = true;
//for (HintSpan span : spans)
// text.delete(text.getSpanStart(span), text.getSpanEnd(span));
text.delete(selStart, selStart + word.postCursor.length());
text.delete(selStart - word.preCursor.length(), selStart);
text.insert(selStart - word.preCursor.length(), s);
setSelection(selStart - word.preCursor.length() + s.length());
fireOnFilterEvent(null);
super.setImeOptions(prevOptions);
autoCompleting = false;
} | [
"public",
"void",
"performCompletion",
"(",
"String",
"s",
")",
"{",
"int",
"selStart",
"=",
"getSelectionStart",
"(",
")",
";",
"int",
"selEnd",
"=",
"getSelectionEnd",
"(",
")",
";",
"if",
"(",
"selStart",
"!=",
"selEnd",
")",
"return",
";",
"Editable",
... | Replaces the current word with s. Used by Adapter to set the selected item as text.
@param s text to replace with | [
"Replaces",
"the",
"current",
"word",
"with",
"s",
".",
"Used",
"by",
"Adapter",
"to",
"set",
"the",
"selected",
"item",
"as",
"text",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/widget/AutoCompleteEditText.java#L362-L384 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/internal/WeakHashSet.java | WeakHashSet.iterator | public Iterator iterator() {
// remove garbage collected elements
processQueue();
// get an iterator of the superclass WeakHashSet
final Iterator i = super.iterator();
return new Iterator() {
public boolean hasNext() {
return i.hasNext();
}
public Object next() {
// unwrap the element
return getReferenceObject((WeakReference) i.next());
}
public void remove() {
// remove the element from the HashSet
i.remove();
}
};
} | java | public Iterator iterator() {
// remove garbage collected elements
processQueue();
// get an iterator of the superclass WeakHashSet
final Iterator i = super.iterator();
return new Iterator() {
public boolean hasNext() {
return i.hasNext();
}
public Object next() {
// unwrap the element
return getReferenceObject((WeakReference) i.next());
}
public void remove() {
// remove the element from the HashSet
i.remove();
}
};
} | [
"public",
"Iterator",
"iterator",
"(",
")",
"{",
"// remove garbage collected elements",
"processQueue",
"(",
")",
";",
"// get an iterator of the superclass WeakHashSet",
"final",
"Iterator",
"i",
"=",
"super",
".",
"iterator",
"(",
")",
";",
"return",
"new",
"Iterat... | Returns an iterator over the elements in this set. The elements are returned in no
particular order.
@return an Iterator over the elements in this set. | [
"Returns",
"an",
"iterator",
"over",
"the",
"elements",
"in",
"this",
"set",
".",
"The",
"elements",
"are",
"returned",
"in",
"no",
"particular",
"order",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/internal/WeakHashSet.java#L63-L85 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LollipopDrawable.java | LollipopDrawable.inflate | public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)
throws XmlPullParserException, IOException {
} | java | public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)
throws XmlPullParserException, IOException {
} | [
"public",
"void",
"inflate",
"(",
"Resources",
"r",
",",
"XmlPullParser",
"parser",
",",
"AttributeSet",
"attrs",
",",
"Resources",
".",
"Theme",
"theme",
")",
"throws",
"XmlPullParserException",
",",
"IOException",
"{",
"}"
] | Inflate this Drawable from an XML resource optionally styled by a theme.
@param r Resources used to resolve attribute values
@param parser XML parser from which to inflate this Drawable
@param attrs Base set of attribute values
@param theme Theme to apply, may be null
@throws XmlPullParserException
@throws IOException | [
"Inflate",
"this",
"Drawable",
"from",
"an",
"XML",
"resource",
"optionally",
"styled",
"by",
"a",
"theme",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LollipopDrawable.java#L30-L32 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/RippleForeground.java | RippleForeground.getBounds | public void getBounds(Rect bounds) {
final int outerX = (int) mTargetX;
final int outerY = (int) mTargetY;
final int r = (int) mTargetRadius + 1;
bounds.set(outerX - r, outerY - r, outerX + r, outerY + r);
} | java | public void getBounds(Rect bounds) {
final int outerX = (int) mTargetX;
final int outerY = (int) mTargetY;
final int r = (int) mTargetRadius + 1;
bounds.set(outerX - r, outerY - r, outerX + r, outerY + r);
} | [
"public",
"void",
"getBounds",
"(",
"Rect",
"bounds",
")",
"{",
"final",
"int",
"outerX",
"=",
"(",
"int",
")",
"mTargetX",
";",
"final",
"int",
"outerY",
"=",
"(",
"int",
")",
"mTargetY",
";",
"final",
"int",
"r",
"=",
"(",
"int",
")",
"mTargetRadiu... | Returns the maximum bounds of the ripple relative to the ripple center. | [
"Returns",
"the",
"maximum",
"bounds",
"of",
"the",
"ripple",
"relative",
"to",
"the",
"ripple",
"center",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/RippleForeground.java#L113-L118 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/RippleForeground.java | RippleForeground.computeBoundedTargetValues | private void computeBoundedTargetValues() {
mTargetX = (mClampedStartingX - mBounds.exactCenterX()) * .7f;
mTargetY = (mClampedStartingY - mBounds.exactCenterY()) * .7f;
mTargetRadius = mBoundedRadius;
} | java | private void computeBoundedTargetValues() {
mTargetX = (mClampedStartingX - mBounds.exactCenterX()) * .7f;
mTargetY = (mClampedStartingY - mBounds.exactCenterY()) * .7f;
mTargetRadius = mBoundedRadius;
} | [
"private",
"void",
"computeBoundedTargetValues",
"(",
")",
"{",
"mTargetX",
"=",
"(",
"mClampedStartingX",
"-",
"mBounds",
".",
"exactCenterX",
"(",
")",
")",
"*",
".7f",
";",
"mTargetY",
"=",
"(",
"mClampedStartingY",
"-",
"mBounds",
".",
"exactCenterY",
"(",... | Compute target values that are dependent on bounding. | [
"Compute",
"target",
"values",
"that",
"are",
"dependent",
"on",
"bounding",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/RippleForeground.java#L199-L203 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/RippleForeground.java | RippleForeground.clampStartingPosition | private void clampStartingPosition() {
final float cX = mBounds.exactCenterX();
final float cY = mBounds.exactCenterY();
final float dX = mStartingX - cX;
final float dY = mStartingY - cY;
final float r = mTargetRadius;
if (dX * dX + dY * dY > r * r) {
// Point is outside the circle, clamp to the perimeter.
final double angle = Math.atan2(dY, dX);
mClampedStartingX = cX + (float) (Math.cos(angle) * r);
mClampedStartingY = cY + (float) (Math.sin(angle) * r);
} else {
mClampedStartingX = mStartingX;
mClampedStartingY = mStartingY;
}
} | java | private void clampStartingPosition() {
final float cX = mBounds.exactCenterX();
final float cY = mBounds.exactCenterY();
final float dX = mStartingX - cX;
final float dY = mStartingY - cY;
final float r = mTargetRadius;
if (dX * dX + dY * dY > r * r) {
// Point is outside the circle, clamp to the perimeter.
final double angle = Math.atan2(dY, dX);
mClampedStartingX = cX + (float) (Math.cos(angle) * r);
mClampedStartingY = cY + (float) (Math.sin(angle) * r);
} else {
mClampedStartingX = mStartingX;
mClampedStartingY = mStartingY;
}
} | [
"private",
"void",
"clampStartingPosition",
"(",
")",
"{",
"final",
"float",
"cX",
"=",
"mBounds",
".",
"exactCenterX",
"(",
")",
";",
"final",
"float",
"cY",
"=",
"mBounds",
".",
"exactCenterY",
"(",
")",
";",
"final",
"float",
"dX",
"=",
"mStartingX",
... | Clamps the starting position to fit within the ripple bounds. | [
"Clamps",
"the",
"starting",
"position",
"to",
"fit",
"within",
"the",
"ripple",
"bounds",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/RippleForeground.java#L258-L273 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java | ShapeAppearanceModel.setAllCorners | public void setAllCorners(CornerTreatment cornerTreatment) {
topLeftCorner = cornerTreatment.clone();
topRightCorner = cornerTreatment.clone();
bottomRightCorner = cornerTreatment.clone();
bottomLeftCorner = cornerTreatment.clone();
} | java | public void setAllCorners(CornerTreatment cornerTreatment) {
topLeftCorner = cornerTreatment.clone();
topRightCorner = cornerTreatment.clone();
bottomRightCorner = cornerTreatment.clone();
bottomLeftCorner = cornerTreatment.clone();
} | [
"public",
"void",
"setAllCorners",
"(",
"CornerTreatment",
"cornerTreatment",
")",
"{",
"topLeftCorner",
"=",
"cornerTreatment",
".",
"clone",
"(",
")",
";",
"topRightCorner",
"=",
"cornerTreatment",
".",
"clone",
"(",
")",
";",
"bottomRightCorner",
"=",
"cornerTr... | Sets all corner treatments.
@param cornerTreatment the corner treatment to use for all four corners. | [
"Sets",
"all",
"corner",
"treatments",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java#L147-L152 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java | ShapeAppearanceModel.setAllEdges | public void setAllEdges(EdgeTreatment edgeTreatment) {
leftEdge = edgeTreatment.clone();
topEdge = edgeTreatment.clone();
rightEdge = edgeTreatment.clone();
bottomEdge = edgeTreatment.clone();
} | java | public void setAllEdges(EdgeTreatment edgeTreatment) {
leftEdge = edgeTreatment.clone();
topEdge = edgeTreatment.clone();
rightEdge = edgeTreatment.clone();
bottomEdge = edgeTreatment.clone();
} | [
"public",
"void",
"setAllEdges",
"(",
"EdgeTreatment",
"edgeTreatment",
")",
"{",
"leftEdge",
"=",
"edgeTreatment",
".",
"clone",
"(",
")",
";",
"topEdge",
"=",
"edgeTreatment",
".",
"clone",
"(",
")",
";",
"rightEdge",
"=",
"edgeTreatment",
".",
"clone",
"(... | Sets all edge treatments.
@param edgeTreatment the edge treatment to use for all four edges. | [
"Sets",
"all",
"edge",
"treatments",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java#L181-L186 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java | ShapeAppearanceModel.setCornerTreatments | public void setCornerTreatments(
CornerTreatment topLeftCorner,
CornerTreatment topRightCorner,
CornerTreatment bottomRightCorner,
CornerTreatment bottomLeftCorner) {
this.topLeftCorner = topLeftCorner;
this.topRightCorner = topRightCorner;
this.bottomRightCorner = bottomRightCorner;
this.bottomLeftCorner = bottomLeftCorner;
} | java | public void setCornerTreatments(
CornerTreatment topLeftCorner,
CornerTreatment topRightCorner,
CornerTreatment bottomRightCorner,
CornerTreatment bottomLeftCorner) {
this.topLeftCorner = topLeftCorner;
this.topRightCorner = topRightCorner;
this.bottomRightCorner = bottomRightCorner;
this.bottomLeftCorner = bottomLeftCorner;
} | [
"public",
"void",
"setCornerTreatments",
"(",
"CornerTreatment",
"topLeftCorner",
",",
"CornerTreatment",
"topRightCorner",
",",
"CornerTreatment",
"bottomRightCorner",
",",
"CornerTreatment",
"bottomLeftCorner",
")",
"{",
"this",
".",
"topLeftCorner",
"=",
"topLeftCorner",... | Sets corner treatments.
@param topLeftCorner the corner treatment to use in the top-left corner.
@param topRightCorner the corner treatment to use in the top-right corner.
@param bottomRightCorner the corner treatment to use in the bottom-right corner.
@param bottomLeftCorner the corner treatment to use in the bottom-left corner. | [
"Sets",
"corner",
"treatments",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java#L196-L205 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java | ShapeAppearanceModel.setEdgeTreatments | public void setEdgeTreatments(
EdgeTreatment leftEdge,
EdgeTreatment topEdge,
EdgeTreatment rightEdge,
EdgeTreatment bottomEdge) {
this.leftEdge = leftEdge;
this.topEdge = topEdge;
this.rightEdge = rightEdge;
this.bottomEdge = bottomEdge;
} | java | public void setEdgeTreatments(
EdgeTreatment leftEdge,
EdgeTreatment topEdge,
EdgeTreatment rightEdge,
EdgeTreatment bottomEdge) {
this.leftEdge = leftEdge;
this.topEdge = topEdge;
this.rightEdge = rightEdge;
this.bottomEdge = bottomEdge;
} | [
"public",
"void",
"setEdgeTreatments",
"(",
"EdgeTreatment",
"leftEdge",
",",
"EdgeTreatment",
"topEdge",
",",
"EdgeTreatment",
"rightEdge",
",",
"EdgeTreatment",
"bottomEdge",
")",
"{",
"this",
".",
"leftEdge",
"=",
"leftEdge",
";",
"this",
".",
"topEdge",
"=",
... | Sets edge treatments.
@param leftEdge the edge treatment to use on the left edge.
@param topEdge the edge treatment to use on the top edge.
@param rightEdge the edge treatment to use on the right edge.
@param bottomEdge the edge treatment to use on the bottom edge. | [
"Sets",
"edge",
"treatments",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java#L215-L224 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/recycler/ItemTouchHelper.java | ItemTouchHelper.scrollIfNecessary | boolean scrollIfNecessary() {
if (mSelected == null) {
mDragScrollStartTimeInMs = Long.MIN_VALUE;
return false;
}
final long now = System.currentTimeMillis();
final long scrollDuration = mDragScrollStartTimeInMs
== Long.MIN_VALUE ? 0 : now - mDragScrollStartTimeInMs;
RecyclerView.LayoutManager lm = mRecyclerView.getLayoutManager();
if (mTmpRect == null) {
mTmpRect = new Rect();
}
int scrollX = 0;
int scrollY = 0;
lm.calculateItemDecorationsForChild(mSelected.itemView, mTmpRect);
if (lm.canScrollHorizontally()) {
int curX = (int) (mSelectedStartX + mDx);
final int leftDiff = curX - mTmpRect.left - mRecyclerView.getPaddingLeft();
if (mDx < 0 && leftDiff < 0) {
scrollX = leftDiff;
} else if (mDx > 0) {
final int rightDiff =
curX + mSelected.itemView.getWidth() + mTmpRect.right
- (mRecyclerView.getWidth() - mRecyclerView.getPaddingRight());
if (rightDiff > 0) {
scrollX = rightDiff;
}
}
}
if (lm.canScrollVertically()) {
int curY = (int) (mSelectedStartY + mDy);
final int topDiff = curY - mTmpRect.top - mRecyclerView.getPaddingTop();
if (mDy < 0 && topDiff < 0) {
scrollY = topDiff;
} else if (mDy > 0) {
final int bottomDiff = curY + mSelected.itemView.getHeight() + mTmpRect.bottom
- (mRecyclerView.getHeight() - mRecyclerView.getPaddingBottom());
if (bottomDiff > 0) {
scrollY = bottomDiff;
}
}
}
if (scrollX != 0) {
scrollX = mCallback.interpolateOutOfBoundsScroll(mRecyclerView,
mSelected.itemView.getWidth(), scrollX,
mRecyclerView.getWidth(), scrollDuration);
}
if (scrollY != 0) {
scrollY = mCallback.interpolateOutOfBoundsScroll(mRecyclerView,
mSelected.itemView.getHeight(), scrollY,
mRecyclerView.getHeight(), scrollDuration);
}
if (scrollX != 0 || scrollY != 0) {
if (mDragScrollStartTimeInMs == Long.MIN_VALUE) {
mDragScrollStartTimeInMs = now;
}
mRecyclerView.scrollBy(scrollX, scrollY);
return true;
}
mDragScrollStartTimeInMs = Long.MIN_VALUE;
return false;
} | java | boolean scrollIfNecessary() {
if (mSelected == null) {
mDragScrollStartTimeInMs = Long.MIN_VALUE;
return false;
}
final long now = System.currentTimeMillis();
final long scrollDuration = mDragScrollStartTimeInMs
== Long.MIN_VALUE ? 0 : now - mDragScrollStartTimeInMs;
RecyclerView.LayoutManager lm = mRecyclerView.getLayoutManager();
if (mTmpRect == null) {
mTmpRect = new Rect();
}
int scrollX = 0;
int scrollY = 0;
lm.calculateItemDecorationsForChild(mSelected.itemView, mTmpRect);
if (lm.canScrollHorizontally()) {
int curX = (int) (mSelectedStartX + mDx);
final int leftDiff = curX - mTmpRect.left - mRecyclerView.getPaddingLeft();
if (mDx < 0 && leftDiff < 0) {
scrollX = leftDiff;
} else if (mDx > 0) {
final int rightDiff =
curX + mSelected.itemView.getWidth() + mTmpRect.right
- (mRecyclerView.getWidth() - mRecyclerView.getPaddingRight());
if (rightDiff > 0) {
scrollX = rightDiff;
}
}
}
if (lm.canScrollVertically()) {
int curY = (int) (mSelectedStartY + mDy);
final int topDiff = curY - mTmpRect.top - mRecyclerView.getPaddingTop();
if (mDy < 0 && topDiff < 0) {
scrollY = topDiff;
} else if (mDy > 0) {
final int bottomDiff = curY + mSelected.itemView.getHeight() + mTmpRect.bottom
- (mRecyclerView.getHeight() - mRecyclerView.getPaddingBottom());
if (bottomDiff > 0) {
scrollY = bottomDiff;
}
}
}
if (scrollX != 0) {
scrollX = mCallback.interpolateOutOfBoundsScroll(mRecyclerView,
mSelected.itemView.getWidth(), scrollX,
mRecyclerView.getWidth(), scrollDuration);
}
if (scrollY != 0) {
scrollY = mCallback.interpolateOutOfBoundsScroll(mRecyclerView,
mSelected.itemView.getHeight(), scrollY,
mRecyclerView.getHeight(), scrollDuration);
}
if (scrollX != 0 || scrollY != 0) {
if (mDragScrollStartTimeInMs == Long.MIN_VALUE) {
mDragScrollStartTimeInMs = now;
}
mRecyclerView.scrollBy(scrollX, scrollY);
return true;
}
mDragScrollStartTimeInMs = Long.MIN_VALUE;
return false;
} | [
"boolean",
"scrollIfNecessary",
"(",
")",
"{",
"if",
"(",
"mSelected",
"==",
"null",
")",
"{",
"mDragScrollStartTimeInMs",
"=",
"Long",
".",
"MIN_VALUE",
";",
"return",
"false",
";",
"}",
"final",
"long",
"now",
"=",
"System",
".",
"currentTimeMillis",
"(",
... | If user drags the view to the edge, trigger a scroll if necessary. | [
"If",
"user",
"drags",
"the",
"view",
"to",
"the",
"edge",
"trigger",
"a",
"scroll",
"if",
"necessary",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/recycler/ItemTouchHelper.java#L658-L719 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/recycler/ItemTouchHelper.java | ItemTouchHelper.endRecoverAnimation | int endRecoverAnimation(ViewHolder viewHolder, boolean override) {
final int recoverAnimSize = mRecoverAnimations.size();
for (int i = recoverAnimSize - 1; i >= 0; i--) {
final RecoverAnimation anim = mRecoverAnimations.get(i);
if (anim.mViewHolder == viewHolder) {
anim.mOverridden |= override;
if (!anim.mEnded) {
anim.cancel();
}
mRecoverAnimations.remove(i);
return anim.mAnimationType;
}
}
return 0;
} | java | int endRecoverAnimation(ViewHolder viewHolder, boolean override) {
final int recoverAnimSize = mRecoverAnimations.size();
for (int i = recoverAnimSize - 1; i >= 0; i--) {
final RecoverAnimation anim = mRecoverAnimations.get(i);
if (anim.mViewHolder == viewHolder) {
anim.mOverridden |= override;
if (!anim.mEnded) {
anim.cancel();
}
mRecoverAnimations.remove(i);
return anim.mAnimationType;
}
}
return 0;
} | [
"int",
"endRecoverAnimation",
"(",
"ViewHolder",
"viewHolder",
",",
"boolean",
"override",
")",
"{",
"final",
"int",
"recoverAnimSize",
"=",
"mRecoverAnimations",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"recoverAnimSize",
"-",
"1",
";",
"i",... | Returns the animation type or 0 if cannot be found. | [
"Returns",
"the",
"animation",
"type",
"or",
"0",
"if",
"cannot",
"be",
"found",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/recycler/ItemTouchHelper.java#L831-L845 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/recycler/ItemTouchHelper.java | ItemTouchHelper.checkSelectForSwipe | boolean checkSelectForSwipe(int action, MotionEvent motionEvent, int pointerIndex) {
if (mSelected != null || action != MotionEvent.ACTION_MOVE
|| mActionState == ACTION_STATE_DRAG || !mCallback.isItemViewSwipeEnabled()) {
return false;
}
if (mRecyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
return false;
}
final ViewHolder vh = findSwipedView(motionEvent);
if (vh == null) {
return false;
}
final int movementFlags = mCallback.getAbsoluteMovementFlags(mRecyclerView, vh);
final int swipeFlags = (movementFlags & ACTION_MODE_SWIPE_MASK)
>> (DIRECTION_FLAG_COUNT * ACTION_STATE_SWIPE);
if (swipeFlags == 0) {
return false;
}
// mDx and mDy are only set in allowed directions. We use custom x/y here instead of
// updateDxDy to avoid swiping if user moves more in the other direction
final float x = motionEvent.getX(pointerIndex);
final float y = motionEvent.getY(pointerIndex);
// Calculate the distance moved
final float dx = x - mInitialTouchX;
final float dy = y - mInitialTouchY;
// swipe target is chose w/o applying flags so it does not really check if swiping in that
// direction is allowed. This why here, we use mDx mDy to check slope value again.
final float absDx = Math.abs(dx);
final float absDy = Math.abs(dy);
if (absDx < mSlop && absDy < mSlop) {
return false;
}
if (absDx > absDy) {
if (dx < 0 && (swipeFlags & LEFT) == 0) {
return false;
}
if (dx > 0 && (swipeFlags & RIGHT) == 0) {
return false;
}
} else {
if (dy < 0 && (swipeFlags & UP) == 0) {
return false;
}
if (dy > 0 && (swipeFlags & DOWN) == 0) {
return false;
}
}
mDx = mDy = 0f;
mActivePointerId = motionEvent.getPointerId(0);
select(vh, ACTION_STATE_SWIPE);
return true;
} | java | boolean checkSelectForSwipe(int action, MotionEvent motionEvent, int pointerIndex) {
if (mSelected != null || action != MotionEvent.ACTION_MOVE
|| mActionState == ACTION_STATE_DRAG || !mCallback.isItemViewSwipeEnabled()) {
return false;
}
if (mRecyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
return false;
}
final ViewHolder vh = findSwipedView(motionEvent);
if (vh == null) {
return false;
}
final int movementFlags = mCallback.getAbsoluteMovementFlags(mRecyclerView, vh);
final int swipeFlags = (movementFlags & ACTION_MODE_SWIPE_MASK)
>> (DIRECTION_FLAG_COUNT * ACTION_STATE_SWIPE);
if (swipeFlags == 0) {
return false;
}
// mDx and mDy are only set in allowed directions. We use custom x/y here instead of
// updateDxDy to avoid swiping if user moves more in the other direction
final float x = motionEvent.getX(pointerIndex);
final float y = motionEvent.getY(pointerIndex);
// Calculate the distance moved
final float dx = x - mInitialTouchX;
final float dy = y - mInitialTouchY;
// swipe target is chose w/o applying flags so it does not really check if swiping in that
// direction is allowed. This why here, we use mDx mDy to check slope value again.
final float absDx = Math.abs(dx);
final float absDy = Math.abs(dy);
if (absDx < mSlop && absDy < mSlop) {
return false;
}
if (absDx > absDy) {
if (dx < 0 && (swipeFlags & LEFT) == 0) {
return false;
}
if (dx > 0 && (swipeFlags & RIGHT) == 0) {
return false;
}
} else {
if (dy < 0 && (swipeFlags & UP) == 0) {
return false;
}
if (dy > 0 && (swipeFlags & DOWN) == 0) {
return false;
}
}
mDx = mDy = 0f;
mActivePointerId = motionEvent.getPointerId(0);
select(vh, ACTION_STATE_SWIPE);
return true;
} | [
"boolean",
"checkSelectForSwipe",
"(",
"int",
"action",
",",
"MotionEvent",
"motionEvent",
",",
"int",
"pointerIndex",
")",
"{",
"if",
"(",
"mSelected",
"!=",
"null",
"||",
"action",
"!=",
"MotionEvent",
".",
"ACTION_MOVE",
"||",
"mActionState",
"==",
"ACTION_ST... | Checks whether we should select a View for swiping. | [
"Checks",
"whether",
"we",
"should",
"select",
"a",
"View",
"for",
"swiping",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/recycler/ItemTouchHelper.java#L895-L946 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.inflateLayers | private void inflateLayers(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)
throws XmlPullParserException, IOException {
final LayerState state = mLayerState;
final int innerDepth = parser.getDepth() + 1;
int type;
int depth;
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) {
if (type != XmlPullParser.START_TAG) {
continue;
}
if (depth > innerDepth || !parser.getName().equals("item")) {
continue;
}
final ChildDrawable layer = new ChildDrawable();
final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.LayerDrawableItem);
updateLayerFromTypedArray(layer, a);
a.recycle();
// If the layer doesn't have a drawable or unresolved theme
// attribute for a drawable, attempt to parse one from the child
// element.
if (layer.mDrawable == null && (layer.mThemeAttrs == null ||
layer.mThemeAttrs[R.styleable.LayerDrawableItem_android_drawable] == 0)) {
while ((type = parser.next()) == XmlPullParser.TEXT) {
}
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException(parser.getPositionDescription()
+ ": <item> tag requires a 'drawable' attribute or "
+ "child tag defining a drawable");
}
layer.mDrawable = LollipopDrawablesCompat.createFromXmlInner(r, parser, attrs, theme);
}
if (layer.mDrawable != null) {
state.mChildrenChangingConfigurations |=
layer.mDrawable.getChangingConfigurations();
layer.mDrawable.setCallback(this);
}
addLayer(layer);
}
} | java | private void inflateLayers(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)
throws XmlPullParserException, IOException {
final LayerState state = mLayerState;
final int innerDepth = parser.getDepth() + 1;
int type;
int depth;
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) {
if (type != XmlPullParser.START_TAG) {
continue;
}
if (depth > innerDepth || !parser.getName().equals("item")) {
continue;
}
final ChildDrawable layer = new ChildDrawable();
final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.LayerDrawableItem);
updateLayerFromTypedArray(layer, a);
a.recycle();
// If the layer doesn't have a drawable or unresolved theme
// attribute for a drawable, attempt to parse one from the child
// element.
if (layer.mDrawable == null && (layer.mThemeAttrs == null ||
layer.mThemeAttrs[R.styleable.LayerDrawableItem_android_drawable] == 0)) {
while ((type = parser.next()) == XmlPullParser.TEXT) {
}
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException(parser.getPositionDescription()
+ ": <item> tag requires a 'drawable' attribute or "
+ "child tag defining a drawable");
}
layer.mDrawable = LollipopDrawablesCompat.createFromXmlInner(r, parser, attrs, theme);
}
if (layer.mDrawable != null) {
state.mChildrenChangingConfigurations |=
layer.mDrawable.getChangingConfigurations();
layer.mDrawable.setCallback(this);
}
addLayer(layer);
}
} | [
"private",
"void",
"inflateLayers",
"(",
"Resources",
"r",
",",
"XmlPullParser",
"parser",
",",
"AttributeSet",
"attrs",
",",
"Resources",
".",
"Theme",
"theme",
")",
"throws",
"XmlPullParserException",
",",
"IOException",
"{",
"final",
"LayerState",
"state",
"=",... | Inflates child layers using the specified parser. | [
"Inflates",
"child",
"layers",
"using",
"the",
"specified",
"parser",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L196-L241 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.addLayer | int addLayer(ChildDrawable layer) {
final LayerState st = mLayerState;
final int N = st.mChildren != null ? st.mChildren.length : 0;
final int i = st.mNum;
if (i >= N) {
final ChildDrawable[] nu = new ChildDrawable[N + 10];
if (i > 0) {
System.arraycopy(st.mChildren, 0, nu, 0, i);
}
st.mChildren = nu;
}
st.mChildren[i] = layer;
st.mNum++;
st.invalidateCache();
return i;
} | java | int addLayer(ChildDrawable layer) {
final LayerState st = mLayerState;
final int N = st.mChildren != null ? st.mChildren.length : 0;
final int i = st.mNum;
if (i >= N) {
final ChildDrawable[] nu = new ChildDrawable[N + 10];
if (i > 0) {
System.arraycopy(st.mChildren, 0, nu, 0, i);
}
st.mChildren = nu;
}
st.mChildren[i] = layer;
st.mNum++;
st.invalidateCache();
return i;
} | [
"int",
"addLayer",
"(",
"ChildDrawable",
"layer",
")",
"{",
"final",
"LayerState",
"st",
"=",
"mLayerState",
";",
"final",
"int",
"N",
"=",
"st",
".",
"mChildren",
"!=",
"null",
"?",
"st",
".",
"mChildren",
".",
"length",
":",
"0",
";",
"final",
"int",... | Adds a new layer at the end of list of layers and returns its index.
@param layer The layer to add.
@return The index of the layer. | [
"Adds",
"a",
"new",
"layer",
"at",
"the",
"end",
"of",
"list",
"of",
"layers",
"and",
"returns",
"its",
"index",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L346-L363 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.addLayer | ChildDrawable addLayer(Drawable dr, int[] themeAttrs, int id,
int left, int top, int right, int bottom) {
final ChildDrawable childDrawable = createLayer(dr);
childDrawable.mId = id;
childDrawable.mThemeAttrs = themeAttrs;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
childDrawable.mDrawable.setAutoMirrored(isAutoMirrored());
childDrawable.mInsetL = left;
childDrawable.mInsetT = top;
childDrawable.mInsetR = right;
childDrawable.mInsetB = bottom;
addLayer(childDrawable);
mLayerState.mChildrenChangingConfigurations |= dr.getChangingConfigurations();
dr.setCallback(this);
return childDrawable;
} | java | ChildDrawable addLayer(Drawable dr, int[] themeAttrs, int id,
int left, int top, int right, int bottom) {
final ChildDrawable childDrawable = createLayer(dr);
childDrawable.mId = id;
childDrawable.mThemeAttrs = themeAttrs;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
childDrawable.mDrawable.setAutoMirrored(isAutoMirrored());
childDrawable.mInsetL = left;
childDrawable.mInsetT = top;
childDrawable.mInsetR = right;
childDrawable.mInsetB = bottom;
addLayer(childDrawable);
mLayerState.mChildrenChangingConfigurations |= dr.getChangingConfigurations();
dr.setCallback(this);
return childDrawable;
} | [
"ChildDrawable",
"addLayer",
"(",
"Drawable",
"dr",
",",
"int",
"[",
"]",
"themeAttrs",
",",
"int",
"id",
",",
"int",
"left",
",",
"int",
"top",
",",
"int",
"right",
",",
"int",
"bottom",
")",
"{",
"final",
"ChildDrawable",
"childDrawable",
"=",
"createL... | Add a new layer to this drawable. The new layer is identified by an id.
@param dr The drawable to add as a layer.
@param themeAttrs Theme attributes extracted from the layer.
@param id The id of the new layer.
@param left The left padding of the new layer.
@param top The top padding of the new layer.
@param right The right padding of the new layer.
@param bottom The bottom padding of the new layer. | [
"Add",
"a",
"new",
"layer",
"to",
"this",
"drawable",
".",
"The",
"new",
"layer",
"is",
"identified",
"by",
"an",
"id",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L376-L394 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.getId | public int getId(int index) {
if (index >= mLayerState.mNum) {
throw new IndexOutOfBoundsException();
}
return mLayerState.mChildren[index].mId;
} | java | public int getId(int index) {
if (index >= mLayerState.mNum) {
throw new IndexOutOfBoundsException();
}
return mLayerState.mChildren[index].mId;
} | [
"public",
"int",
"getId",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"index",
">=",
"mLayerState",
".",
"mNum",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"return",
"mLayerState",
".",
"mChildren",
"[",
"index",
"]",
".",
... | Returns the ID of the specified layer.
@param index The index of the layer, must be in the range {@code 0...getNumberOfLayers()-1}.
@return The id of the layer or {@link android.view.View#NO_ID} if the layer has no id.
@attr ref android.R.styleable#LayerDrawableItem_id
@see #setId(int, int) | [
"Returns",
"the",
"ID",
"of",
"the",
"specified",
"layer",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L459-L464 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.setDrawable | public void setDrawable(int index, Drawable drawable) {
if (index >= mLayerState.mNum) {
throw new IndexOutOfBoundsException();
}
final ChildDrawable[] layers = mLayerState.mChildren;
final ChildDrawable childDrawable = layers[index];
if (childDrawable.mDrawable != null) {
if (drawable != null) {
final Rect bounds = childDrawable.mDrawable.getBounds();
drawable.setBounds(bounds);
}
childDrawable.mDrawable.setCallback(null);
}
if (drawable != null) {
drawable.setCallback(this);
}
childDrawable.mDrawable = drawable;
mLayerState.invalidateCache();
refreshChildPadding(index, childDrawable);
} | java | public void setDrawable(int index, Drawable drawable) {
if (index >= mLayerState.mNum) {
throw new IndexOutOfBoundsException();
}
final ChildDrawable[] layers = mLayerState.mChildren;
final ChildDrawable childDrawable = layers[index];
if (childDrawable.mDrawable != null) {
if (drawable != null) {
final Rect bounds = childDrawable.mDrawable.getBounds();
drawable.setBounds(bounds);
}
childDrawable.mDrawable.setCallback(null);
}
if (drawable != null) {
drawable.setCallback(this);
}
childDrawable.mDrawable = drawable;
mLayerState.invalidateCache();
refreshChildPadding(index, childDrawable);
} | [
"public",
"void",
"setDrawable",
"(",
"int",
"index",
",",
"Drawable",
"drawable",
")",
"{",
"if",
"(",
"index",
">=",
"mLayerState",
".",
"mNum",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"final",
"ChildDrawable",
"[",
"]"... | Sets the drawable for the layer at the specified index.
@param index The index of the layer to modify, must be in the range {@code
0...getNumberOfLayers()-1}.
@param drawable The drawable to set for the layer.
@attr ref android.R.styleable#LayerDrawableItem_drawable
@see #getDrawable(int) | [
"Sets",
"the",
"drawable",
"for",
"the",
"layer",
"at",
"the",
"specified",
"index",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L523-L547 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.getDrawable | public Drawable getDrawable(int index) {
if (index >= mLayerState.mNum) {
throw new IndexOutOfBoundsException();
}
return mLayerState.mChildren[index].mDrawable;
} | java | public Drawable getDrawable(int index) {
if (index >= mLayerState.mNum) {
throw new IndexOutOfBoundsException();
}
return mLayerState.mChildren[index].mDrawable;
} | [
"public",
"Drawable",
"getDrawable",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"index",
">=",
"mLayerState",
".",
"mNum",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"return",
"mLayerState",
".",
"mChildren",
"[",
"index",
"]... | Returns the drawable for the layer at the specified index.
@param index The index of the layer, must be in the range {@code 0...getNumberOfLayers()-1}.
@return The {@link Drawable} at the specified layer index.
@attr ref android.R.styleable#LayerDrawableItem_drawable
@see #setDrawable(int, Drawable) | [
"Returns",
"the",
"drawable",
"for",
"the",
"layer",
"at",
"the",
"specified",
"index",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L557-L562 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.setLayerInset | public void setLayerInset(int index, int l, int t, int r, int b) {
setLayerInsetInternal(index, l, t, r, b, UNDEFINED_INSET, UNDEFINED_INSET);
} | java | public void setLayerInset(int index, int l, int t, int r, int b) {
setLayerInsetInternal(index, l, t, r, b, UNDEFINED_INSET, UNDEFINED_INSET);
} | [
"public",
"void",
"setLayerInset",
"(",
"int",
"index",
",",
"int",
"l",
",",
"int",
"t",
",",
"int",
"r",
",",
"int",
"b",
")",
"{",
"setLayerInsetInternal",
"(",
"index",
",",
"l",
",",
"t",
",",
"r",
",",
"b",
",",
"UNDEFINED_INSET",
",",
"UNDEF... | Specifies the insets in pixels for the drawable at the specified index.
@param index the index of the drawable to adjust
@param l number of pixels to add to the left bound
@param t number of pixels to add to the top bound
@param r number of pixels to subtract from the right bound
@param b number of pixels to subtract from the bottom bound
@attr ref android.R.styleable#LayerDrawableItem_left
@attr ref android.R.styleable#LayerDrawableItem_top
@attr ref android.R.styleable#LayerDrawableItem_right
@attr ref android.R.styleable#LayerDrawableItem_bottom | [
"Specifies",
"the",
"insets",
"in",
"pixels",
"for",
"the",
"drawable",
"at",
"the",
"specified",
"index",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L671-L673 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.setLayerInsetRelative | public void setLayerInsetRelative(int index, int s, int t, int e, int b) {
setLayerInsetInternal(index, 0, t, 0, b, s, e);
} | java | public void setLayerInsetRelative(int index, int s, int t, int e, int b) {
setLayerInsetInternal(index, 0, t, 0, b, s, e);
} | [
"public",
"void",
"setLayerInsetRelative",
"(",
"int",
"index",
",",
"int",
"s",
",",
"int",
"t",
",",
"int",
"e",
",",
"int",
"b",
")",
"{",
"setLayerInsetInternal",
"(",
"index",
",",
"0",
",",
"t",
",",
"0",
",",
"b",
",",
"s",
",",
"e",
")",
... | Specifies the relative insets in pixels for the drawable at the specified index.
@param index the index of the layer to adjust
@param s number of pixels to inset from the start bound
@param t number of pixels to inset from the top bound
@param e number of pixels to inset from the end bound
@param b number of pixels to inset from the bottom bound
@attr ref android.R.styleable#LayerDrawableItem_start
@attr ref android.R.styleable#LayerDrawableItem_top
@attr ref android.R.styleable#LayerDrawableItem_end
@attr ref android.R.styleable#LayerDrawableItem_bottom | [
"Specifies",
"the",
"relative",
"insets",
"in",
"pixels",
"for",
"the",
"drawable",
"at",
"the",
"specified",
"index",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L688-L690 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.refreshChildPadding | private boolean refreshChildPadding(int i, ChildDrawable r) {
if (r.mDrawable != null) {
final Rect rect = mTmpRect;
r.mDrawable.getPadding(rect);
if (rect.left != mPaddingL[i] || rect.top != mPaddingT[i] ||
rect.right != mPaddingR[i] || rect.bottom != mPaddingB[i]) {
mPaddingL[i] = rect.left;
mPaddingT[i] = rect.top;
mPaddingR[i] = rect.right;
mPaddingB[i] = rect.bottom;
return true;
}
}
return false;
} | java | private boolean refreshChildPadding(int i, ChildDrawable r) {
if (r.mDrawable != null) {
final Rect rect = mTmpRect;
r.mDrawable.getPadding(rect);
if (rect.left != mPaddingL[i] || rect.top != mPaddingT[i] ||
rect.right != mPaddingR[i] || rect.bottom != mPaddingB[i]) {
mPaddingL[i] = rect.left;
mPaddingT[i] = rect.top;
mPaddingR[i] = rect.right;
mPaddingB[i] = rect.bottom;
return true;
}
}
return false;
} | [
"private",
"boolean",
"refreshChildPadding",
"(",
"int",
"i",
",",
"ChildDrawable",
"r",
")",
"{",
"if",
"(",
"r",
".",
"mDrawable",
"!=",
"null",
")",
"{",
"final",
"Rect",
"rect",
"=",
"mTmpRect",
";",
"r",
".",
"mDrawable",
".",
"getPadding",
"(",
"... | Refreshes the cached padding values for the specified child.
@return true if the child's padding has changed | [
"Refreshes",
"the",
"cached",
"padding",
"values",
"for",
"the",
"specified",
"child",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L1551-L1565 | train |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java | LayerDrawable.ensurePadding | void ensurePadding() {
final int N = mLayerState.mNum;
if (mPaddingL != null && mPaddingL.length >= N) {
return;
}
mPaddingL = new int[N];
mPaddingT = new int[N];
mPaddingR = new int[N];
mPaddingB = new int[N];
} | java | void ensurePadding() {
final int N = mLayerState.mNum;
if (mPaddingL != null && mPaddingL.length >= N) {
return;
}
mPaddingL = new int[N];
mPaddingT = new int[N];
mPaddingR = new int[N];
mPaddingB = new int[N];
} | [
"void",
"ensurePadding",
"(",
")",
"{",
"final",
"int",
"N",
"=",
"mLayerState",
".",
"mNum",
";",
"if",
"(",
"mPaddingL",
"!=",
"null",
"&&",
"mPaddingL",
".",
"length",
">=",
"N",
")",
"{",
"return",
";",
"}",
"mPaddingL",
"=",
"new",
"int",
"[",
... | Ensures the child padding caches are large enough. | [
"Ensures",
"the",
"child",
"padding",
"caches",
"are",
"large",
"enough",
"."
] | 78b0a432bd49edc7a6a13ce111cab274085d1693 | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L1570-L1580 | train |
killme2008/Metamorphosis | metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java | ResourceUtils.getResourceAsProperties | public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(loader, propfile);
props.load(in);
in.close();
return props;
} | java | public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(loader, propfile);
props.load(in);
in.close();
return props;
} | [
"public",
"static",
"Properties",
"getResourceAsProperties",
"(",
"ClassLoader",
"loader",
",",
"String",
"resource",
")",
"throws",
"IOException",
"{",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"InputStream",
"in",
"=",
"null",
";",
"Strin... | Returns a resource on the classpath as a Properties object
@param loader
The classloader used to load the resource
@param resource
The resource to find
@throws IOException
If the resource cannot be found or read
@return The resource | [
"Returns",
"a",
"resource",
"on",
"the",
"classpath",
"as",
"a",
"Properties",
"object"
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java#L175-L183 | train |
killme2008/Metamorphosis | metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java | ResourceUtils.getResourceAsReader | public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
return new InputStreamReader(getResourceAsStream(loader, resource));
} | java | public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
return new InputStreamReader(getResourceAsStream(loader, resource));
} | [
"public",
"static",
"Reader",
"getResourceAsReader",
"(",
"ClassLoader",
"loader",
",",
"String",
"resource",
")",
"throws",
"IOException",
"{",
"return",
"new",
"InputStreamReader",
"(",
"getResourceAsStream",
"(",
"loader",
",",
"resource",
")",
")",
";",
"}"
] | Returns a resource on the classpath as a Reader object
@param loader
The classloader used to load the resource
@param resource
The resource to find
@throws IOException
If the resource cannot be found or read
@return The resource | [
"Returns",
"a",
"resource",
"on",
"the",
"classpath",
"as",
"a",
"Reader",
"object"
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java#L213-L215 | train |
killme2008/Metamorphosis | metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java | ResourceUtils.getResourceAsFile | public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException {
return new File(getResourceURL(loader, resource).getFile());
} | java | public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException {
return new File(getResourceURL(loader, resource).getFile());
} | [
"public",
"static",
"File",
"getResourceAsFile",
"(",
"ClassLoader",
"loader",
",",
"String",
"resource",
")",
"throws",
"IOException",
"{",
"return",
"new",
"File",
"(",
"getResourceURL",
"(",
"loader",
",",
"resource",
")",
".",
"getFile",
"(",
")",
")",
"... | Returns a resource on the classpath as a File object
@param loader
The classloader used to load the resource
@param resource
The resource to find
@throws IOException
If the resource cannot be found or read
@return The resource | [
"Returns",
"a",
"resource",
"on",
"the",
"classpath",
"as",
"a",
"File",
"object"
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java#L245-L247 | train |
killme2008/Metamorphosis | metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/IdGenerator.java | IdGenerator.generateId | public synchronized String generateId() {
final StringBuilder sb = new StringBuilder(this.length);
sb.append(this.seed);
sb.append(this.sequence.getAndIncrement());
return sb.toString();
} | java | public synchronized String generateId() {
final StringBuilder sb = new StringBuilder(this.length);
sb.append(this.seed);
sb.append(this.sequence.getAndIncrement());
return sb.toString();
} | [
"public",
"synchronized",
"String",
"generateId",
"(",
")",
"{",
"final",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"this",
".",
"length",
")",
";",
"sb",
".",
"append",
"(",
"this",
".",
"seed",
")",
";",
"sb",
".",
"append",
"(",
"this... | Generate a unqiue id
@return a unique id | [
"Generate",
"a",
"unqiue",
"id"
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/IdGenerator.java#L57-L62 | train |
killme2008/Metamorphosis | metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/IdGenerator.java | IdGenerator.generateSanitizedId | public String generateSanitizedId() {
String result = this.generateId();
result = result.replace(':', '-');
result = result.replace('_', '-');
result = result.replace('.', '-');
return result;
} | java | public String generateSanitizedId() {
String result = this.generateId();
result = result.replace(':', '-');
result = result.replace('_', '-');
result = result.replace('.', '-');
return result;
} | [
"public",
"String",
"generateSanitizedId",
"(",
")",
"{",
"String",
"result",
"=",
"this",
".",
"generateId",
"(",
")",
";",
"result",
"=",
"result",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
";",
"result",
"=",
"result",
".",
"replace",
"("... | Generate a unique ID - that is friendly for a URL or file system
@return a unique id | [
"Generate",
"a",
"unique",
"ID",
"-",
"that",
"is",
"friendly",
"for",
"a",
"URL",
"or",
"file",
"system"
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/IdGenerator.java#L70-L76 | train |
killme2008/Metamorphosis | metamorphosis-server-wrapper/src/main/java/com/taobao/metamorphosis/http/processor/MetamorphosisOnJettyProcessor.java | MetamorphosisOnJettyProcessor.doResponseHeaders | protected void doResponseHeaders(final HttpServletResponse response, final String mimeType) {
if (mimeType != null) {
response.setContentType(mimeType);
}
} | java | protected void doResponseHeaders(final HttpServletResponse response, final String mimeType) {
if (mimeType != null) {
response.setContentType(mimeType);
}
} | [
"protected",
"void",
"doResponseHeaders",
"(",
"final",
"HttpServletResponse",
"response",
",",
"final",
"String",
"mimeType",
")",
"{",
"if",
"(",
"mimeType",
"!=",
"null",
")",
"{",
"response",
".",
"setContentType",
"(",
"mimeType",
")",
";",
"}",
"}"
] | Set the response headers. This method is called to set the response
headers such as content type and content length. May be extended to add
additional headers.
@param response
@param resource
@param mimeType | [
"Set",
"the",
"response",
"headers",
".",
"This",
"method",
"is",
"called",
"to",
"set",
"the",
"response",
"headers",
"such",
"as",
"content",
"type",
"and",
"content",
"length",
".",
"May",
"be",
"extended",
"to",
"add",
"additional",
"headers",
"."
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-server-wrapper/src/main/java/com/taobao/metamorphosis/http/processor/MetamorphosisOnJettyProcessor.java#L204-L208 | train |
killme2008/Metamorphosis | metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/extension/spring/MetaqTemplate.java | MetaqTemplate.getOrCreateProducer | public MessageProducer getOrCreateProducer(final String topic) {
if (!this.shareProducer) {
FutureTask<MessageProducer> task = this.producers.get(topic);
if (task == null) {
task = new FutureTask<MessageProducer>(new Callable<MessageProducer>() {
@Override
public MessageProducer call() throws Exception {
MessageProducer producer = MetaqTemplate.this.messageSessionFactory.createProducer();
producer.publish(topic);
if (!StringUtils.isBlank(MetaqTemplate.this.defaultTopic)) {
producer.setDefaultTopic(MetaqTemplate.this.defaultTopic);
}
return producer;
}
});
FutureTask<MessageProducer> oldTask = this.producers.putIfAbsent(topic, task);
if (oldTask != null) {
task = oldTask;
}
else {
task.run();
}
}
try {
MessageProducer producer = task.get();
return producer;
}
catch (ExecutionException e) {
throw ThreadUtils.launderThrowable(e.getCause());
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
else {
if (this.sharedProducer == null) {
synchronized (this) {
if (this.sharedProducer == null) {
this.sharedProducer = this.messageSessionFactory.createProducer();
if (!StringUtils.isBlank(this.defaultTopic)) {
this.sharedProducer.setDefaultTopic(this.defaultTopic);
}
}
}
}
this.sharedProducer.publish(topic);
return this.sharedProducer;
}
throw new IllegalStateException("Could not create producer for topic '" + topic + "'");
} | java | public MessageProducer getOrCreateProducer(final String topic) {
if (!this.shareProducer) {
FutureTask<MessageProducer> task = this.producers.get(topic);
if (task == null) {
task = new FutureTask<MessageProducer>(new Callable<MessageProducer>() {
@Override
public MessageProducer call() throws Exception {
MessageProducer producer = MetaqTemplate.this.messageSessionFactory.createProducer();
producer.publish(topic);
if (!StringUtils.isBlank(MetaqTemplate.this.defaultTopic)) {
producer.setDefaultTopic(MetaqTemplate.this.defaultTopic);
}
return producer;
}
});
FutureTask<MessageProducer> oldTask = this.producers.putIfAbsent(topic, task);
if (oldTask != null) {
task = oldTask;
}
else {
task.run();
}
}
try {
MessageProducer producer = task.get();
return producer;
}
catch (ExecutionException e) {
throw ThreadUtils.launderThrowable(e.getCause());
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
else {
if (this.sharedProducer == null) {
synchronized (this) {
if (this.sharedProducer == null) {
this.sharedProducer = this.messageSessionFactory.createProducer();
if (!StringUtils.isBlank(this.defaultTopic)) {
this.sharedProducer.setDefaultTopic(this.defaultTopic);
}
}
}
}
this.sharedProducer.publish(topic);
return this.sharedProducer;
}
throw new IllegalStateException("Could not create producer for topic '" + topic + "'");
} | [
"public",
"MessageProducer",
"getOrCreateProducer",
"(",
"final",
"String",
"topic",
")",
"{",
"if",
"(",
"!",
"this",
".",
"shareProducer",
")",
"{",
"FutureTask",
"<",
"MessageProducer",
">",
"task",
"=",
"this",
".",
"producers",
".",
"get",
"(",
"topic",... | Returns or create a message producer for topic.
@param topic
@return
@since 1.4.5 | [
"Returns",
"or",
"create",
"a",
"message",
"producer",
"for",
"topic",
"."
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/extension/spring/MetaqTemplate.java#L145-L197 | train |
killme2008/Metamorphosis | metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/extension/spring/MetaqTemplate.java | MetaqTemplate.send | public SendResult send(MessageBuilder builder, long timeout, TimeUnit unit) throws InterruptedException {
Message msg = builder.build(this.messageBodyConverter);
final String topic = msg.getTopic();
MessageProducer producer = this.getOrCreateProducer(topic);
try {
return producer.sendMessage(msg, timeout, unit);
}
catch (MetaClientException e) {
return new SendResult(false, null, -1, ExceptionUtils.getFullStackTrace(e));
}
} | java | public SendResult send(MessageBuilder builder, long timeout, TimeUnit unit) throws InterruptedException {
Message msg = builder.build(this.messageBodyConverter);
final String topic = msg.getTopic();
MessageProducer producer = this.getOrCreateProducer(topic);
try {
return producer.sendMessage(msg, timeout, unit);
}
catch (MetaClientException e) {
return new SendResult(false, null, -1, ExceptionUtils.getFullStackTrace(e));
}
} | [
"public",
"SendResult",
"send",
"(",
"MessageBuilder",
"builder",
",",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"throws",
"InterruptedException",
"{",
"Message",
"msg",
"=",
"builder",
".",
"build",
"(",
"this",
".",
"messageBodyConverter",
")",
";",
"... | Send message built by message builder.Returns the sent result.
@param builder
@return
@throws InterruptedException
@since 1.4.5 | [
"Send",
"message",
"built",
"by",
"message",
"builder",
".",
"Returns",
"the",
"sent",
"result",
"."
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/extension/spring/MetaqTemplate.java#L208-L218 | train |
killme2008/Metamorphosis | metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/extension/spring/MetaqTemplate.java | MetaqTemplate.send | public void send(MessageBuilder builder, SendMessageCallback cb, long timeout, TimeUnit unit) {
Message msg = builder.build(this.messageBodyConverter);
final String topic = msg.getTopic();
MessageProducer producer = this.getOrCreateProducer(topic);
producer.sendMessage(msg, cb, timeout, unit);
} | java | public void send(MessageBuilder builder, SendMessageCallback cb, long timeout, TimeUnit unit) {
Message msg = builder.build(this.messageBodyConverter);
final String topic = msg.getTopic();
MessageProducer producer = this.getOrCreateProducer(topic);
producer.sendMessage(msg, cb, timeout, unit);
} | [
"public",
"void",
"send",
"(",
"MessageBuilder",
"builder",
",",
"SendMessageCallback",
"cb",
",",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"{",
"Message",
"msg",
"=",
"builder",
".",
"build",
"(",
"this",
".",
"messageBodyConverter",
")",
";",
"fina... | Send message asynchronously with callback.
@param builder
@param cb
@param timeout
@param unit
@since 1.4.5 | [
"Send",
"message",
"asynchronously",
"with",
"callback",
"."
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/extension/spring/MetaqTemplate.java#L251-L256 | train |
killme2008/Metamorphosis | metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/extension/spring/MessageBuilder.java | MessageBuilder.build | public <T> Message build(MessageBodyConverter<T> converter) {
if (StringUtils.isBlank(this.topic)) {
throw new IllegalArgumentException("Blank topic");
}
if (this.body == null && this.payload == null) {
throw new IllegalArgumentException("Empty payload");
}
byte[] payload = this.payload;
if (payload == null && converter != null) {
try {
payload = converter.toByteArray((T) this.body);
}
catch (MetaClientException e) {
throw new IllegalStateException("Convert message body failed.", e);
}
}
if (payload == null) {
throw new IllegalArgumentException("Empty payload");
}
return new Message(this.topic, payload, this.attribute);
} | java | public <T> Message build(MessageBodyConverter<T> converter) {
if (StringUtils.isBlank(this.topic)) {
throw new IllegalArgumentException("Blank topic");
}
if (this.body == null && this.payload == null) {
throw new IllegalArgumentException("Empty payload");
}
byte[] payload = this.payload;
if (payload == null && converter != null) {
try {
payload = converter.toByteArray((T) this.body);
}
catch (MetaClientException e) {
throw new IllegalStateException("Convert message body failed.", e);
}
}
if (payload == null) {
throw new IllegalArgumentException("Empty payload");
}
return new Message(this.topic, payload, this.attribute);
} | [
"public",
"<",
"T",
">",
"Message",
"build",
"(",
"MessageBodyConverter",
"<",
"T",
">",
"converter",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"this",
".",
"topic",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Blank to... | Build message by message body converter.
@param converter
@return
@since 1.4.5 | [
"Build",
"message",
"by",
"message",
"body",
"converter",
"."
] | 1884b10620dbd640aaf85102243ca295703fbb4a | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/extension/spring/MessageBuilder.java#L103-L124 | train |
mongobee/mongobee | src/main/java/com/github/mongobee/dao/ChangeEntryDao.java | ChangeEntryDao.acquireProcessLock | public boolean acquireProcessLock() throws MongobeeConnectionException, MongobeeLockException {
verifyDbConnection();
boolean acquired = lockDao.acquireLock(getMongoDatabase());
if (!acquired && waitForLock) {
long timeToGiveUp = new Date().getTime() + (changeLogLockWaitTime * 1000 * 60);
while (!acquired && new Date().getTime() < timeToGiveUp) {
acquired = lockDao.acquireLock(getMongoDatabase());
if (!acquired) {
logger.info("Waiting for changelog lock....");
try {
Thread.sleep(changeLogLockPollRate * 1000);
} catch (InterruptedException e) {
// nothing
}
}
}
}
if (!acquired && throwExceptionIfCannotObtainLock) {
logger.info("Mongobee did not acquire process lock. Throwing exception.");
throw new MongobeeLockException("Could not acquire process lock");
}
return acquired;
} | java | public boolean acquireProcessLock() throws MongobeeConnectionException, MongobeeLockException {
verifyDbConnection();
boolean acquired = lockDao.acquireLock(getMongoDatabase());
if (!acquired && waitForLock) {
long timeToGiveUp = new Date().getTime() + (changeLogLockWaitTime * 1000 * 60);
while (!acquired && new Date().getTime() < timeToGiveUp) {
acquired = lockDao.acquireLock(getMongoDatabase());
if (!acquired) {
logger.info("Waiting for changelog lock....");
try {
Thread.sleep(changeLogLockPollRate * 1000);
} catch (InterruptedException e) {
// nothing
}
}
}
}
if (!acquired && throwExceptionIfCannotObtainLock) {
logger.info("Mongobee did not acquire process lock. Throwing exception.");
throw new MongobeeLockException("Could not acquire process lock");
}
return acquired;
} | [
"public",
"boolean",
"acquireProcessLock",
"(",
")",
"throws",
"MongobeeConnectionException",
",",
"MongobeeLockException",
"{",
"verifyDbConnection",
"(",
")",
";",
"boolean",
"acquired",
"=",
"lockDao",
".",
"acquireLock",
"(",
"getMongoDatabase",
"(",
")",
")",
"... | Try to acquire process lock
@return true if successfully acquired, false otherwise
@throws MongobeeConnectionException exception
@throws MongobeeLockException exception | [
"Try",
"to",
"acquire",
"process",
"lock"
] | 4e1ec5e381121fc9e5ad54881c84029114bafa52 | https://github.com/mongobee/mongobee/blob/4e1ec5e381121fc9e5ad54881c84029114bafa52/src/main/java/com/github/mongobee/dao/ChangeEntryDao.java#L94-L119 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.waitForCompletion | public boolean waitForCompletion(long duration, TimeUnit timeUnit) throws InterruptedException {
synchronized (lock) {
if (!isCompleted()) {
lock.wait(timeUnit.toMillis(duration));
}
return isCompleted();
}
} | java | public boolean waitForCompletion(long duration, TimeUnit timeUnit) throws InterruptedException {
synchronized (lock) {
if (!isCompleted()) {
lock.wait(timeUnit.toMillis(duration));
}
return isCompleted();
}
} | [
"public",
"boolean",
"waitForCompletion",
"(",
"long",
"duration",
",",
"TimeUnit",
"timeUnit",
")",
"throws",
"InterruptedException",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"if",
"(",
"!",
"isCompleted",
"(",
")",
")",
"{",
"lock",
".",
"wait",
"(",
... | Blocks until the task is complete or times out.
@return {@code true} if the task completed (has a result, an error, or was cancelled).
{@code false} otherwise. | [
"Blocks",
"until",
"the",
"task",
"is",
"complete",
"or",
"times",
"out",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L189-L196 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.forResult | @SuppressWarnings("unchecked")
public static <TResult> Task<TResult> forResult(TResult value) {
if (value == null) {
return (Task<TResult>) TASK_NULL;
}
if (value instanceof Boolean) {
return (Task<TResult>) ((Boolean) value ? TASK_TRUE : TASK_FALSE);
}
bolts.TaskCompletionSource<TResult> tcs = new bolts.TaskCompletionSource<>();
tcs.setResult(value);
return tcs.getTask();
} | java | @SuppressWarnings("unchecked")
public static <TResult> Task<TResult> forResult(TResult value) {
if (value == null) {
return (Task<TResult>) TASK_NULL;
}
if (value instanceof Boolean) {
return (Task<TResult>) ((Boolean) value ? TASK_TRUE : TASK_FALSE);
}
bolts.TaskCompletionSource<TResult> tcs = new bolts.TaskCompletionSource<>();
tcs.setResult(value);
return tcs.getTask();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"TResult",
">",
"Task",
"<",
"TResult",
">",
"forResult",
"(",
"TResult",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"(",
"Task",
"<",
"TResult",
... | Creates a completed task with the given value. | [
"Creates",
"a",
"completed",
"task",
"with",
"the",
"given",
"value",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L201-L212 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.forError | public static <TResult> Task<TResult> forError(Exception error) {
bolts.TaskCompletionSource<TResult> tcs = new bolts.TaskCompletionSource<>();
tcs.setError(error);
return tcs.getTask();
} | java | public static <TResult> Task<TResult> forError(Exception error) {
bolts.TaskCompletionSource<TResult> tcs = new bolts.TaskCompletionSource<>();
tcs.setError(error);
return tcs.getTask();
} | [
"public",
"static",
"<",
"TResult",
">",
"Task",
"<",
"TResult",
">",
"forError",
"(",
"Exception",
"error",
")",
"{",
"bolts",
".",
"TaskCompletionSource",
"<",
"TResult",
">",
"tcs",
"=",
"new",
"bolts",
".",
"TaskCompletionSource",
"<>",
"(",
")",
";",
... | Creates a faulted task with the given error. | [
"Creates",
"a",
"faulted",
"task",
"with",
"the",
"given",
"error",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L217-L221 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.delay | public static Task<Void> delay(long delay, CancellationToken cancellationToken) {
return delay(delay, BoltsExecutors.scheduled(), cancellationToken);
} | java | public static Task<Void> delay(long delay, CancellationToken cancellationToken) {
return delay(delay, BoltsExecutors.scheduled(), cancellationToken);
} | [
"public",
"static",
"Task",
"<",
"Void",
">",
"delay",
"(",
"long",
"delay",
",",
"CancellationToken",
"cancellationToken",
")",
"{",
"return",
"delay",
"(",
"delay",
",",
"BoltsExecutors",
".",
"scheduled",
"(",
")",
",",
"cancellationToken",
")",
";",
"}"
... | Creates a task that completes after a time delay.
@param delay The number of milliseconds to wait before completing the returned task. Zero and
negative values are treated as requests for immediate execution.
@param cancellationToken The optional cancellation token that will be checked prior to
completing the returned task. | [
"Creates",
"a",
"task",
"that",
"completes",
"after",
"a",
"time",
"delay",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L249-L251 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.cast | public <TOut> Task<TOut> cast() {
@SuppressWarnings("unchecked")
Task<TOut> task = (Task<TOut>) this;
return task;
} | java | public <TOut> Task<TOut> cast() {
@SuppressWarnings("unchecked")
Task<TOut> task = (Task<TOut>) this;
return task;
} | [
"public",
"<",
"TOut",
">",
"Task",
"<",
"TOut",
">",
"cast",
"(",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Task",
"<",
"TOut",
">",
"task",
"=",
"(",
"Task",
"<",
"TOut",
">",
")",
"this",
";",
"return",
"task",
";",
"}"
] | Makes a fluent cast of a Task's result possible, avoiding an extra continuation just to cast
the type of the result. | [
"Makes",
"a",
"fluent",
"cast",
"of",
"a",
"Task",
"s",
"result",
"possible",
"avoiding",
"an",
"extra",
"continuation",
"just",
"to",
"cast",
"the",
"type",
"of",
"the",
"result",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L287-L291 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.continueWith | public <TContinuationResult> Task<TContinuationResult> continueWith(
Continuation<TResult, TContinuationResult> continuation) {
return continueWith(continuation, IMMEDIATE_EXECUTOR, null);
} | java | public <TContinuationResult> Task<TContinuationResult> continueWith(
Continuation<TResult, TContinuationResult> continuation) {
return continueWith(continuation, IMMEDIATE_EXECUTOR, null);
} | [
"public",
"<",
"TContinuationResult",
">",
"Task",
"<",
"TContinuationResult",
">",
"continueWith",
"(",
"Continuation",
"<",
"TResult",
",",
"TContinuationResult",
">",
"continuation",
")",
"{",
"return",
"continueWith",
"(",
"continuation",
",",
"IMMEDIATE_EXECUTOR"... | Adds a synchronous continuation to this task, returning a new task that completes after the
continuation has finished running. | [
"Adds",
"a",
"synchronous",
"continuation",
"to",
"this",
"task",
"returning",
"a",
"new",
"task",
"that",
"completes",
"after",
"the",
"continuation",
"has",
"finished",
"running",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L667-L670 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.continueWithTask | public <TContinuationResult> Task<TContinuationResult> continueWithTask(
final Continuation<TResult, Task<TContinuationResult>> continuation, final Executor executor,
final CancellationToken ct) {
boolean completed;
final bolts.TaskCompletionSource<TContinuationResult> tcs = new bolts.TaskCompletionSource<>();
synchronized (lock) {
completed = this.isCompleted();
if (!completed) {
this.continuations.add(new Continuation<TResult, Void>() {
@Override
public Void then(Task<TResult> task) {
completeAfterTask(tcs, continuation, task, executor, ct);
return null;
}
});
}
}
if (completed) {
completeAfterTask(tcs, continuation, this, executor, ct);
}
return tcs.getTask();
} | java | public <TContinuationResult> Task<TContinuationResult> continueWithTask(
final Continuation<TResult, Task<TContinuationResult>> continuation, final Executor executor,
final CancellationToken ct) {
boolean completed;
final bolts.TaskCompletionSource<TContinuationResult> tcs = new bolts.TaskCompletionSource<>();
synchronized (lock) {
completed = this.isCompleted();
if (!completed) {
this.continuations.add(new Continuation<TResult, Void>() {
@Override
public Void then(Task<TResult> task) {
completeAfterTask(tcs, continuation, task, executor, ct);
return null;
}
});
}
}
if (completed) {
completeAfterTask(tcs, continuation, this, executor, ct);
}
return tcs.getTask();
} | [
"public",
"<",
"TContinuationResult",
">",
"Task",
"<",
"TContinuationResult",
">",
"continueWithTask",
"(",
"final",
"Continuation",
"<",
"TResult",
",",
"Task",
"<",
"TContinuationResult",
">",
">",
"continuation",
",",
"final",
"Executor",
"executor",
",",
"fin... | Adds an Task-based continuation to this task that will be scheduled using the executor,
returning a new task that completes after the task returned by the continuation has completed. | [
"Adds",
"an",
"Task",
"-",
"based",
"continuation",
"to",
"this",
"task",
"that",
"will",
"be",
"scheduled",
"using",
"the",
"executor",
"returning",
"a",
"new",
"task",
"that",
"completes",
"after",
"the",
"task",
"returned",
"by",
"the",
"continuation",
"h... | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L694-L715 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/Task.java | Task.continueWithTask | public <TContinuationResult> Task<TContinuationResult> continueWithTask(
Continuation<TResult, Task<TContinuationResult>> continuation) {
return continueWithTask(continuation, IMMEDIATE_EXECUTOR, null);
} | java | public <TContinuationResult> Task<TContinuationResult> continueWithTask(
Continuation<TResult, Task<TContinuationResult>> continuation) {
return continueWithTask(continuation, IMMEDIATE_EXECUTOR, null);
} | [
"public",
"<",
"TContinuationResult",
">",
"Task",
"<",
"TContinuationResult",
">",
"continueWithTask",
"(",
"Continuation",
"<",
"TResult",
",",
"Task",
"<",
"TContinuationResult",
">",
">",
"continuation",
")",
"{",
"return",
"continueWithTask",
"(",
"continuation... | Adds an asynchronous continuation to this task, returning a new task that completes after the
task returned by the continuation has completed. | [
"Adds",
"an",
"asynchronous",
"continuation",
"to",
"this",
"task",
"returning",
"a",
"new",
"task",
"that",
"completes",
"after",
"the",
"task",
"returned",
"by",
"the",
"continuation",
"has",
"completed",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L721-L724 | train |
BoltsFramework/Bolts-Android | bolts-applinks/src/main/java/bolts/WebViewAppLinkResolver.java | WebViewAppLinkResolver.parseAlData | private static Map<String, Object> parseAlData(JSONArray dataArray) throws JSONException {
HashMap<String, Object> al = new HashMap<String, Object>();
for (int i = 0; i < dataArray.length(); i++) {
JSONObject tag = dataArray.getJSONObject(i);
String name = tag.getString("property");
String[] nameComponents = name.split(":");
if (!nameComponents[0].equals(META_TAG_PREFIX)) {
continue;
}
Map<String, Object> root = al;
for (int j = 1; j < nameComponents.length; j++) {
@SuppressWarnings("unchecked")
List<Map<String, Object>> children =
(List<Map<String, Object>>) root.get(nameComponents[j]);
if (children == null) {
children = new ArrayList<Map<String, Object>>();
root.put(nameComponents[j], children);
}
Map<String, Object> child = children.size() > 0 ? children.get(children.size() - 1) : null;
if (child == null || j == nameComponents.length - 1) {
child = new HashMap<String, Object>();
children.add(child);
}
root = child;
}
if (tag.has("content")) {
if (tag.isNull("content")) {
root.put(KEY_AL_VALUE, null);
} else {
root.put(KEY_AL_VALUE, tag.getString("content"));
}
}
}
return al;
} | java | private static Map<String, Object> parseAlData(JSONArray dataArray) throws JSONException {
HashMap<String, Object> al = new HashMap<String, Object>();
for (int i = 0; i < dataArray.length(); i++) {
JSONObject tag = dataArray.getJSONObject(i);
String name = tag.getString("property");
String[] nameComponents = name.split(":");
if (!nameComponents[0].equals(META_TAG_PREFIX)) {
continue;
}
Map<String, Object> root = al;
for (int j = 1; j < nameComponents.length; j++) {
@SuppressWarnings("unchecked")
List<Map<String, Object>> children =
(List<Map<String, Object>>) root.get(nameComponents[j]);
if (children == null) {
children = new ArrayList<Map<String, Object>>();
root.put(nameComponents[j], children);
}
Map<String, Object> child = children.size() > 0 ? children.get(children.size() - 1) : null;
if (child == null || j == nameComponents.length - 1) {
child = new HashMap<String, Object>();
children.add(child);
}
root = child;
}
if (tag.has("content")) {
if (tag.isNull("content")) {
root.put(KEY_AL_VALUE, null);
} else {
root.put(KEY_AL_VALUE, tag.getString("content"));
}
}
}
return al;
} | [
"private",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"parseAlData",
"(",
"JSONArray",
"dataArray",
")",
"throws",
"JSONException",
"{",
"HashMap",
"<",
"String",
",",
"Object",
">",
"al",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
... | Builds up a data structure filled with the app link data from the meta tags on a page.
The structure of this object is a dictionary where each key holds an array of app link
data dictionaries. Values are stored in a key called "_value". | [
"Builds",
"up",
"a",
"data",
"structure",
"filled",
"with",
"the",
"app",
"link",
"data",
"from",
"the",
"meta",
"tags",
"on",
"a",
"page",
".",
"The",
"structure",
"of",
"this",
"object",
"is",
"a",
"dictionary",
"where",
"each",
"key",
"holds",
"an",
... | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-applinks/src/main/java/bolts/WebViewAppLinkResolver.java#L190-L224 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/CancellationTokenSource.java | CancellationTokenSource.cancel | public void cancel() {
List<CancellationTokenRegistration> registrations;
synchronized (lock) {
throwIfClosed();
if (cancellationRequested) {
return;
}
cancelScheduledCancellation();
cancellationRequested = true;
registrations = new ArrayList<>(this.registrations);
}
notifyListeners(registrations);
} | java | public void cancel() {
List<CancellationTokenRegistration> registrations;
synchronized (lock) {
throwIfClosed();
if (cancellationRequested) {
return;
}
cancelScheduledCancellation();
cancellationRequested = true;
registrations = new ArrayList<>(this.registrations);
}
notifyListeners(registrations);
} | [
"public",
"void",
"cancel",
"(",
")",
"{",
"List",
"<",
"CancellationTokenRegistration",
">",
"registrations",
";",
"synchronized",
"(",
"lock",
")",
"{",
"throwIfClosed",
"(",
")",
";",
"if",
"(",
"cancellationRequested",
")",
"{",
"return",
";",
"}",
"canc... | Cancels the token if it has not already been cancelled. | [
"Cancels",
"the",
"token",
"if",
"it",
"has",
"not",
"already",
"been",
"cancelled",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/CancellationTokenSource.java#L64-L78 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/CancellationTokenRegistration.java | CancellationTokenRegistration.close | @Override
public void close() {
synchronized (lock) {
if (closed) {
return;
}
closed = true;
tokenSource.unregister(this);
tokenSource = null;
action = null;
}
} | java | @Override
public void close() {
synchronized (lock) {
if (closed) {
return;
}
closed = true;
tokenSource.unregister(this);
tokenSource = null;
action = null;
}
} | [
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"if",
"(",
"closed",
")",
"{",
"return",
";",
"}",
"closed",
"=",
"true",
";",
"tokenSource",
".",
"unregister",
"(",
"this",
")",
";",
"tokenSource",
"... | Unregisters the callback runnable from the cancellation token. | [
"Unregisters",
"the",
"callback",
"runnable",
"from",
"the",
"cancellation",
"token",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/CancellationTokenRegistration.java#L31-L43 | train |
BoltsFramework/Bolts-Android | bolts-tasks/src/main/java/bolts/AndroidExecutors.java | AndroidExecutors.newCachedThreadPool | public static ExecutorService newCachedThreadPool() {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
allowCoreThreadTimeout(executor, true);
return executor;
} | java | public static ExecutorService newCachedThreadPool() {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
allowCoreThreadTimeout(executor, true);
return executor;
} | [
"public",
"static",
"ExecutorService",
"newCachedThreadPool",
"(",
")",
"{",
"ThreadPoolExecutor",
"executor",
"=",
"new",
"ThreadPoolExecutor",
"(",
"CORE_POOL_SIZE",
",",
"MAX_POOL_SIZE",
",",
"KEEP_ALIVE_TIME",
",",
"TimeUnit",
".",
"SECONDS",
",",
"new",
"LinkedBl... | Creates a proper Cached Thread Pool. Tasks will reuse cached threads if available
or create new threads until the core pool is full. tasks will then be queued. If an
task cannot be queued, a new thread will be created unless this would exceed max pool
size, then the task will be rejected. Threads will time out after 1 second.
Core thread timeout is only available on android-9+.
@return the newly created thread pool | [
"Creates",
"a",
"proper",
"Cached",
"Thread",
"Pool",
".",
"Tasks",
"will",
"reuse",
"cached",
"threads",
"if",
"available",
"or",
"create",
"new",
"threads",
"until",
"the",
"core",
"pool",
"is",
"full",
".",
"tasks",
"will",
"then",
"be",
"queued",
".",
... | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/AndroidExecutors.java#L70-L80 | train |
BoltsFramework/Bolts-Android | bolts-applinks/src/main/java/bolts/AppLinks.java | AppLinks.getAppLinkExtras | public static Bundle getAppLinkExtras(Intent intent) {
Bundle appLinkData = getAppLinkData(intent);
if (appLinkData == null) {
return null;
}
return appLinkData.getBundle(KEY_NAME_EXTRAS);
} | java | public static Bundle getAppLinkExtras(Intent intent) {
Bundle appLinkData = getAppLinkData(intent);
if (appLinkData == null) {
return null;
}
return appLinkData.getBundle(KEY_NAME_EXTRAS);
} | [
"public",
"static",
"Bundle",
"getAppLinkExtras",
"(",
"Intent",
"intent",
")",
"{",
"Bundle",
"appLinkData",
"=",
"getAppLinkData",
"(",
"intent",
")",
";",
"if",
"(",
"appLinkData",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"appLinkData... | Gets the App Link extras for an intent, if there is any.
@param intent the incoming intent.
@return a bundle containing the App Link extras for the intent, or {@code null} if none is
specified. | [
"Gets",
"the",
"App",
"Link",
"extras",
"for",
"an",
"intent",
"if",
"there",
"is",
"any",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-applinks/src/main/java/bolts/AppLinks.java#L43-L49 | train |
BoltsFramework/Bolts-Android | bolts-applinks/src/main/java/bolts/AppLinks.java | AppLinks.getTargetUrl | public static Uri getTargetUrl(Intent intent) {
Bundle appLinkData = getAppLinkData(intent);
if (appLinkData != null) {
String targetString = appLinkData.getString(KEY_NAME_TARGET);
if (targetString != null) {
return Uri.parse(targetString);
}
}
return intent.getData();
} | java | public static Uri getTargetUrl(Intent intent) {
Bundle appLinkData = getAppLinkData(intent);
if (appLinkData != null) {
String targetString = appLinkData.getString(KEY_NAME_TARGET);
if (targetString != null) {
return Uri.parse(targetString);
}
}
return intent.getData();
} | [
"public",
"static",
"Uri",
"getTargetUrl",
"(",
"Intent",
"intent",
")",
"{",
"Bundle",
"appLinkData",
"=",
"getAppLinkData",
"(",
"intent",
")",
";",
"if",
"(",
"appLinkData",
"!=",
"null",
")",
"{",
"String",
"targetString",
"=",
"appLinkData",
".",
"getSt... | Gets the target URL for an intent, regardless of whether the intent is from an App Link. If the
intent is from an App Link, this will be the App Link target. Otherwise, it will be the data
Uri from the intent itself.
@param intent the incoming intent.
@return the target URL for the intent. | [
"Gets",
"the",
"target",
"URL",
"for",
"an",
"intent",
"regardless",
"of",
"whether",
"the",
"intent",
"is",
"from",
"an",
"App",
"Link",
".",
"If",
"the",
"intent",
"is",
"from",
"an",
"App",
"Link",
"this",
"will",
"be",
"the",
"App",
"Link",
"target... | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-applinks/src/main/java/bolts/AppLinks.java#L59-L68 | train |
BoltsFramework/Bolts-Android | bolts-applinks/src/main/java/bolts/AppLinks.java | AppLinks.getTargetUrlFromInboundIntent | public static Uri getTargetUrlFromInboundIntent(Context context, Intent intent) {
Bundle appLinkData = getAppLinkData(intent);
if (appLinkData != null) {
String targetString = appLinkData.getString(KEY_NAME_TARGET);
if (targetString != null) {
MeasurementEvent.sendBroadcastEvent(context, MeasurementEvent.APP_LINK_NAVIGATE_IN_EVENT_NAME, intent, null);
return Uri.parse(targetString);
}
}
return null;
} | java | public static Uri getTargetUrlFromInboundIntent(Context context, Intent intent) {
Bundle appLinkData = getAppLinkData(intent);
if (appLinkData != null) {
String targetString = appLinkData.getString(KEY_NAME_TARGET);
if (targetString != null) {
MeasurementEvent.sendBroadcastEvent(context, MeasurementEvent.APP_LINK_NAVIGATE_IN_EVENT_NAME, intent, null);
return Uri.parse(targetString);
}
}
return null;
} | [
"public",
"static",
"Uri",
"getTargetUrlFromInboundIntent",
"(",
"Context",
"context",
",",
"Intent",
"intent",
")",
"{",
"Bundle",
"appLinkData",
"=",
"getAppLinkData",
"(",
"intent",
")",
";",
"if",
"(",
"appLinkData",
"!=",
"null",
")",
"{",
"String",
"targ... | Gets the target URL for an intent. If the intent is from an App Link, this will be the App Link target.
Otherwise, it return null; For app link intent, this function will broadcast APP_LINK_NAVIGATE_IN_EVENT_NAME event.
@param context the context this function is called within.
@param intent the incoming intent.
@return the target URL for the intent if applink intent; null otherwise. | [
"Gets",
"the",
"target",
"URL",
"for",
"an",
"intent",
".",
"If",
"the",
"intent",
"is",
"from",
"an",
"App",
"Link",
"this",
"will",
"be",
"the",
"App",
"Link",
"target",
".",
"Otherwise",
"it",
"return",
"null",
";",
"For",
"app",
"link",
"intent",
... | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-applinks/src/main/java/bolts/AppLinks.java#L78-L88 | train |
BoltsFramework/Bolts-Android | bolts-applinks/src/main/java/bolts/AppLinkNavigation.java | AppLinkNavigation.buildAppLinkDataForNavigation | private Bundle buildAppLinkDataForNavigation(Context context) {
Bundle data = new Bundle();
Bundle refererAppLinkData = new Bundle();
if (context != null) {
String refererAppPackage = context.getPackageName();
if (refererAppPackage != null) {
refererAppLinkData.putString(KEY_NAME_REFERER_APP_LINK_PACKAGE, refererAppPackage);
}
ApplicationInfo appInfo = context.getApplicationInfo();
if (appInfo != null) {
String refererAppName = context.getString(appInfo.labelRes);
if (refererAppName != null) {
refererAppLinkData.putString(KEY_NAME_REFERER_APP_LINK_APP_NAME, refererAppName);
}
}
}
data.putAll(getAppLinkData());
data.putString(AppLinks.KEY_NAME_TARGET, getAppLink().getSourceUrl().toString());
data.putString(KEY_NAME_VERSION, VERSION);
data.putString(KEY_NAME_USER_AGENT, "Bolts Android " + Bolts.VERSION);
data.putBundle(KEY_NAME_REFERER_APP_LINK, refererAppLinkData);
data.putBundle(AppLinks.KEY_NAME_EXTRAS, getExtras());
return data;
} | java | private Bundle buildAppLinkDataForNavigation(Context context) {
Bundle data = new Bundle();
Bundle refererAppLinkData = new Bundle();
if (context != null) {
String refererAppPackage = context.getPackageName();
if (refererAppPackage != null) {
refererAppLinkData.putString(KEY_NAME_REFERER_APP_LINK_PACKAGE, refererAppPackage);
}
ApplicationInfo appInfo = context.getApplicationInfo();
if (appInfo != null) {
String refererAppName = context.getString(appInfo.labelRes);
if (refererAppName != null) {
refererAppLinkData.putString(KEY_NAME_REFERER_APP_LINK_APP_NAME, refererAppName);
}
}
}
data.putAll(getAppLinkData());
data.putString(AppLinks.KEY_NAME_TARGET, getAppLink().getSourceUrl().toString());
data.putString(KEY_NAME_VERSION, VERSION);
data.putString(KEY_NAME_USER_AGENT, "Bolts Android " + Bolts.VERSION);
data.putBundle(KEY_NAME_REFERER_APP_LINK, refererAppLinkData);
data.putBundle(AppLinks.KEY_NAME_EXTRAS, getExtras());
return data;
} | [
"private",
"Bundle",
"buildAppLinkDataForNavigation",
"(",
"Context",
"context",
")",
"{",
"Bundle",
"data",
"=",
"new",
"Bundle",
"(",
")",
";",
"Bundle",
"refererAppLinkData",
"=",
"new",
"Bundle",
"(",
")",
";",
"if",
"(",
"context",
"!=",
"null",
")",
... | Creates a bundle containing the final, constructed App Link data to be used in navigation. | [
"Creates",
"a",
"bundle",
"containing",
"the",
"final",
"constructed",
"App",
"Link",
"data",
"to",
"be",
"used",
"in",
"navigation",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-applinks/src/main/java/bolts/AppLinkNavigation.java#L134-L157 | train |
BoltsFramework/Bolts-Android | bolts-applinks/src/main/java/bolts/AppLinkNavigation.java | AppLinkNavigation.getJSONForBundle | private JSONObject getJSONForBundle(Bundle bundle) throws JSONException {
JSONObject root = new JSONObject();
for (String key : bundle.keySet()) {
root.put(key, getJSONValue(bundle.get(key)));
}
return root;
} | java | private JSONObject getJSONForBundle(Bundle bundle) throws JSONException {
JSONObject root = new JSONObject();
for (String key : bundle.keySet()) {
root.put(key, getJSONValue(bundle.get(key)));
}
return root;
} | [
"private",
"JSONObject",
"getJSONForBundle",
"(",
"Bundle",
"bundle",
")",
"throws",
"JSONException",
"{",
"JSONObject",
"root",
"=",
"new",
"JSONObject",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",
"bundle",
".",
"keySet",
"(",
")",
")",
"{",
"root",... | Gets a JSONObject equivalent to the input bundle for use when falling back to a web navigation. | [
"Gets",
"a",
"JSONObject",
"equivalent",
"to",
"the",
"input",
"bundle",
"for",
"use",
"when",
"falling",
"back",
"to",
"a",
"web",
"navigation",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-applinks/src/main/java/bolts/AppLinkNavigation.java#L251-L257 | train |
BoltsFramework/Bolts-Android | bolts-applinks/src/main/java/bolts/AppLinkNavigation.java | AppLinkNavigation.navigate | public NavigationResult navigate(Context context) {
PackageManager pm = context.getPackageManager();
Bundle finalAppLinkData = buildAppLinkDataForNavigation(context);
Intent eligibleTargetIntent = null;
for (AppLink.Target target : getAppLink().getTargets()) {
Intent targetIntent = new Intent(Intent.ACTION_VIEW);
if (target.getUrl() != null) {
targetIntent.setData(target.getUrl());
} else {
targetIntent.setData(appLink.getSourceUrl());
}
targetIntent.setPackage(target.getPackageName());
if (target.getClassName() != null) {
targetIntent.setClassName(target.getPackageName(), target.getClassName());
}
targetIntent.putExtra(AppLinks.KEY_NAME_APPLINK_DATA, finalAppLinkData);
ResolveInfo resolved = pm.resolveActivity(targetIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (resolved != null) {
eligibleTargetIntent = targetIntent;
break;
}
}
Intent outIntent = null;
NavigationResult result = NavigationResult.FAILED;
if (eligibleTargetIntent != null) {
outIntent = eligibleTargetIntent;
result = NavigationResult.APP;
} else {
// Fall back to the web if it's available
Uri webUrl = getAppLink().getWebUrl();
if (webUrl != null) {
JSONObject appLinkDataJson;
try {
appLinkDataJson = getJSONForBundle(finalAppLinkData);
} catch (JSONException e) {
sendAppLinkNavigateEventBroadcast(context, eligibleTargetIntent, NavigationResult.FAILED, e);
throw new RuntimeException(e);
}
webUrl = webUrl.buildUpon()
.appendQueryParameter(AppLinks.KEY_NAME_APPLINK_DATA, appLinkDataJson.toString())
.build();
outIntent = new Intent(Intent.ACTION_VIEW, webUrl);
result = NavigationResult.WEB;
}
}
sendAppLinkNavigateEventBroadcast(context, outIntent, result, null);
if (outIntent != null) {
context.startActivity(outIntent);
}
return result;
} | java | public NavigationResult navigate(Context context) {
PackageManager pm = context.getPackageManager();
Bundle finalAppLinkData = buildAppLinkDataForNavigation(context);
Intent eligibleTargetIntent = null;
for (AppLink.Target target : getAppLink().getTargets()) {
Intent targetIntent = new Intent(Intent.ACTION_VIEW);
if (target.getUrl() != null) {
targetIntent.setData(target.getUrl());
} else {
targetIntent.setData(appLink.getSourceUrl());
}
targetIntent.setPackage(target.getPackageName());
if (target.getClassName() != null) {
targetIntent.setClassName(target.getPackageName(), target.getClassName());
}
targetIntent.putExtra(AppLinks.KEY_NAME_APPLINK_DATA, finalAppLinkData);
ResolveInfo resolved = pm.resolveActivity(targetIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (resolved != null) {
eligibleTargetIntent = targetIntent;
break;
}
}
Intent outIntent = null;
NavigationResult result = NavigationResult.FAILED;
if (eligibleTargetIntent != null) {
outIntent = eligibleTargetIntent;
result = NavigationResult.APP;
} else {
// Fall back to the web if it's available
Uri webUrl = getAppLink().getWebUrl();
if (webUrl != null) {
JSONObject appLinkDataJson;
try {
appLinkDataJson = getJSONForBundle(finalAppLinkData);
} catch (JSONException e) {
sendAppLinkNavigateEventBroadcast(context, eligibleTargetIntent, NavigationResult.FAILED, e);
throw new RuntimeException(e);
}
webUrl = webUrl.buildUpon()
.appendQueryParameter(AppLinks.KEY_NAME_APPLINK_DATA, appLinkDataJson.toString())
.build();
outIntent = new Intent(Intent.ACTION_VIEW, webUrl);
result = NavigationResult.WEB;
}
}
sendAppLinkNavigateEventBroadcast(context, outIntent, result, null);
if (outIntent != null) {
context.startActivity(outIntent);
}
return result;
} | [
"public",
"NavigationResult",
"navigate",
"(",
"Context",
"context",
")",
"{",
"PackageManager",
"pm",
"=",
"context",
".",
"getPackageManager",
"(",
")",
";",
"Bundle",
"finalAppLinkData",
"=",
"buildAppLinkDataForNavigation",
"(",
"context",
")",
";",
"Intent",
... | Performs the navigation.
@param context the Context from which the navigation should be performed.
@return the {@link NavigationResult} performed by navigating. | [
"Performs",
"the",
"navigation",
"."
] | 54e9cb8bdd4950aa4d418dcbc0ea65414762aef5 | https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-applinks/src/main/java/bolts/AppLinkNavigation.java#L265-L319 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/SpectatorContext.java | SpectatorContext.setRegistry | public static void setRegistry(Registry registry) {
SpectatorContext.registry = registry;
if (registry instanceof NoopRegistry) {
initStacktrace = null;
} else {
Exception cause = initStacktrace;
Exception e = new IllegalStateException(
"called SpectatorContext.setRegistry(" + registry.getClass().getName() + ")",
cause);
e.fillInStackTrace();
initStacktrace = e;
if (cause != null) {
LOGGER.warn("Registry used with Servo's SpectatorContext has been overwritten. This could "
+ "result in missing metrics.", e);
}
}
} | java | public static void setRegistry(Registry registry) {
SpectatorContext.registry = registry;
if (registry instanceof NoopRegistry) {
initStacktrace = null;
} else {
Exception cause = initStacktrace;
Exception e = new IllegalStateException(
"called SpectatorContext.setRegistry(" + registry.getClass().getName() + ")",
cause);
e.fillInStackTrace();
initStacktrace = e;
if (cause != null) {
LOGGER.warn("Registry used with Servo's SpectatorContext has been overwritten. This could "
+ "result in missing metrics.", e);
}
}
} | [
"public",
"static",
"void",
"setRegistry",
"(",
"Registry",
"registry",
")",
"{",
"SpectatorContext",
".",
"registry",
"=",
"registry",
";",
"if",
"(",
"registry",
"instanceof",
"NoopRegistry",
")",
"{",
"initStacktrace",
"=",
"null",
";",
"}",
"else",
"{",
... | Set the registry to use. By default it will use the NoopRegistry. | [
"Set",
"the",
"registry",
"to",
"use",
".",
"By",
"default",
"it",
"will",
"use",
"the",
"NoopRegistry",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/SpectatorContext.java#L79-L95 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/SpectatorContext.java | SpectatorContext.gauge | public static LazyGauge gauge(MonitorConfig config) {
return new LazyGauge(Registry::gauge, registry, createId(config));
} | java | public static LazyGauge gauge(MonitorConfig config) {
return new LazyGauge(Registry::gauge, registry, createId(config));
} | [
"public",
"static",
"LazyGauge",
"gauge",
"(",
"MonitorConfig",
"config",
")",
"{",
"return",
"new",
"LazyGauge",
"(",
"Registry",
"::",
"gauge",
",",
"registry",
",",
"createId",
"(",
"config",
")",
")",
";",
"}"
] | Create a gauge based on the config. | [
"Create",
"a",
"gauge",
"based",
"on",
"the",
"config",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/SpectatorContext.java#L105-L107 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/SpectatorContext.java | SpectatorContext.maxGauge | public static LazyGauge maxGauge(MonitorConfig config) {
return new LazyGauge(Registry::maxGauge, registry, createId(config));
} | java | public static LazyGauge maxGauge(MonitorConfig config) {
return new LazyGauge(Registry::maxGauge, registry, createId(config));
} | [
"public",
"static",
"LazyGauge",
"maxGauge",
"(",
"MonitorConfig",
"config",
")",
"{",
"return",
"new",
"LazyGauge",
"(",
"Registry",
"::",
"maxGauge",
",",
"registry",
",",
"createId",
"(",
"config",
")",
")",
";",
"}"
] | Create a max gauge based on the config. | [
"Create",
"a",
"max",
"gauge",
"based",
"on",
"the",
"config",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/SpectatorContext.java#L110-L112 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/SpectatorContext.java | SpectatorContext.createId | public static Id createId(MonitorConfig config) {
// Need to ensure that Servo type tag is removed to avoid incorrectly reprocessing the
// data in later transforms
Map<String, String> tags = new HashMap<>(config.getTags().asMap());
tags.remove("type");
return registry
.createId(config.getName())
.withTags(tags);
} | java | public static Id createId(MonitorConfig config) {
// Need to ensure that Servo type tag is removed to avoid incorrectly reprocessing the
// data in later transforms
Map<String, String> tags = new HashMap<>(config.getTags().asMap());
tags.remove("type");
return registry
.createId(config.getName())
.withTags(tags);
} | [
"public",
"static",
"Id",
"createId",
"(",
"MonitorConfig",
"config",
")",
"{",
"// Need to ensure that Servo type tag is removed to avoid incorrectly reprocessing the",
"// data in later transforms",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
"=",
"new",
"HashMap",
... | Convert servo config to spectator id. | [
"Convert",
"servo",
"config",
"to",
"spectator",
"id",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/SpectatorContext.java#L130-L138 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/SpectatorContext.java | SpectatorContext.polledGauge | public static PolledMeter.Builder polledGauge(MonitorConfig config) {
long delayMillis = Math.max(Pollers.getPollingIntervals().get(0) - 1000, 5000);
Id id = createId(config);
PolledMeter.remove(registry, id);
return PolledMeter.using(registry)
.withId(id)
.withDelay(Duration.ofMillis(delayMillis))
.scheduleOn(gaugePool());
} | java | public static PolledMeter.Builder polledGauge(MonitorConfig config) {
long delayMillis = Math.max(Pollers.getPollingIntervals().get(0) - 1000, 5000);
Id id = createId(config);
PolledMeter.remove(registry, id);
return PolledMeter.using(registry)
.withId(id)
.withDelay(Duration.ofMillis(delayMillis))
.scheduleOn(gaugePool());
} | [
"public",
"static",
"PolledMeter",
".",
"Builder",
"polledGauge",
"(",
"MonitorConfig",
"config",
")",
"{",
"long",
"delayMillis",
"=",
"Math",
".",
"max",
"(",
"Pollers",
".",
"getPollingIntervals",
"(",
")",
".",
"get",
"(",
"0",
")",
"-",
"1000",
",",
... | Create builder for a polled gauge based on the config. | [
"Create",
"builder",
"for",
"a",
"polled",
"gauge",
"based",
"on",
"the",
"config",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/SpectatorContext.java#L146-L154 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/SpectatorContext.java | SpectatorContext.register | public static void register(Monitor<?> monitor) {
if (monitor instanceof SpectatorMonitor) {
((SpectatorMonitor) monitor).initializeSpectator(BasicTagList.EMPTY);
} else if (!isEmptyComposite(monitor)) {
ServoMeter m = new ServoMeter(monitor);
PolledMeter.remove(registry, m.id());
PolledMeter.monitorMeter(registry, m);
monitorMonitonicValues(monitor);
}
} | java | public static void register(Monitor<?> monitor) {
if (monitor instanceof SpectatorMonitor) {
((SpectatorMonitor) monitor).initializeSpectator(BasicTagList.EMPTY);
} else if (!isEmptyComposite(monitor)) {
ServoMeter m = new ServoMeter(monitor);
PolledMeter.remove(registry, m.id());
PolledMeter.monitorMeter(registry, m);
monitorMonitonicValues(monitor);
}
} | [
"public",
"static",
"void",
"register",
"(",
"Monitor",
"<",
"?",
">",
"monitor",
")",
"{",
"if",
"(",
"monitor",
"instanceof",
"SpectatorMonitor",
")",
"{",
"(",
"(",
"SpectatorMonitor",
")",
"monitor",
")",
".",
"initializeSpectator",
"(",
"BasicTagList",
... | Register a custom monitor. | [
"Register",
"a",
"custom",
"monitor",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/SpectatorContext.java#L157-L166 | train |
Netflix/servo | servo-aws/src/main/java/com/netflix/servo/aws/AwsServiceClients.java | AwsServiceClients.cloudWatch | public static AmazonCloudWatch cloudWatch(AWSCredentialsProvider credentials) {
AmazonCloudWatch client = new AmazonCloudWatchClient(credentials);
client.setEndpoint(System.getProperty(AwsPropertyKeys.AWS_CLOUD_WATCH_END_POINT.getBundle(),
"monitoring.amazonaws.com"));
return client;
} | java | public static AmazonCloudWatch cloudWatch(AWSCredentialsProvider credentials) {
AmazonCloudWatch client = new AmazonCloudWatchClient(credentials);
client.setEndpoint(System.getProperty(AwsPropertyKeys.AWS_CLOUD_WATCH_END_POINT.getBundle(),
"monitoring.amazonaws.com"));
return client;
} | [
"public",
"static",
"AmazonCloudWatch",
"cloudWatch",
"(",
"AWSCredentialsProvider",
"credentials",
")",
"{",
"AmazonCloudWatch",
"client",
"=",
"new",
"AmazonCloudWatchClient",
"(",
"credentials",
")",
";",
"client",
".",
"setEndpoint",
"(",
"System",
".",
"getProper... | Get a CloudWatch client whose endpoint is configured based on properties. | [
"Get",
"a",
"CloudWatch",
"client",
"whose",
"endpoint",
"is",
"configured",
"based",
"on",
"properties",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-aws/src/main/java/com/netflix/servo/aws/AwsServiceClients.java#L36-L41 | train |
Netflix/servo | servo-aws/src/main/java/com/netflix/servo/aws/AwsServiceClients.java | AwsServiceClients.autoScaling | public static AmazonAutoScaling autoScaling(AWSCredentials credentials) {
AmazonAutoScaling client = new AmazonAutoScalingClient(credentials);
client.setEndpoint(System.getProperty(
AwsPropertyKeys.AWS_AUTO_SCALING_END_POINT.getBundle(),
"autoscaling.amazonaws.com"));
return client;
} | java | public static AmazonAutoScaling autoScaling(AWSCredentials credentials) {
AmazonAutoScaling client = new AmazonAutoScalingClient(credentials);
client.setEndpoint(System.getProperty(
AwsPropertyKeys.AWS_AUTO_SCALING_END_POINT.getBundle(),
"autoscaling.amazonaws.com"));
return client;
} | [
"public",
"static",
"AmazonAutoScaling",
"autoScaling",
"(",
"AWSCredentials",
"credentials",
")",
"{",
"AmazonAutoScaling",
"client",
"=",
"new",
"AmazonAutoScalingClient",
"(",
"credentials",
")",
";",
"client",
".",
"setEndpoint",
"(",
"System",
".",
"getProperty",... | Get an AutoScaling client whose endpoint is configured based on properties. | [
"Get",
"an",
"AutoScaling",
"client",
"whose",
"endpoint",
"is",
"configured",
"based",
"on",
"properties",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-aws/src/main/java/com/netflix/servo/aws/AwsServiceClients.java#L46-L52 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java | DynamicTimer.start | public static Stopwatch start(MonitorConfig config, TimeUnit unit) {
return INSTANCE.get(config, unit).start();
} | java | public static Stopwatch start(MonitorConfig config, TimeUnit unit) {
return INSTANCE.get(config, unit).start();
} | [
"public",
"static",
"Stopwatch",
"start",
"(",
"MonitorConfig",
"config",
",",
"TimeUnit",
"unit",
")",
"{",
"return",
"INSTANCE",
".",
"get",
"(",
"config",
",",
"unit",
")",
".",
"start",
"(",
")",
";",
"}"
] | Returns a stopwatch that has been started and will automatically
record its result to the dynamic timer specified by the given config.
@param config Config to identify a particular timer instance to update.
@param unit The unit to use when reporting values to observers. For example if sent to
a typical time series graphing system this would be the unit for the y-axis.
It is generally recommended to use base units for reporting, so
{@link TimeUnit#SECONDS} is the preferred value. | [
"Returns",
"a",
"stopwatch",
"that",
"has",
"been",
"started",
"and",
"will",
"automatically",
"record",
"its",
"result",
"to",
"the",
"dynamic",
"timer",
"specified",
"by",
"the",
"given",
"config",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java#L120-L122 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java | DynamicTimer.start | public static Stopwatch start(MonitorConfig config) {
return INSTANCE.get(config, TimeUnit.MILLISECONDS).start();
} | java | public static Stopwatch start(MonitorConfig config) {
return INSTANCE.get(config, TimeUnit.MILLISECONDS).start();
} | [
"public",
"static",
"Stopwatch",
"start",
"(",
"MonitorConfig",
"config",
")",
"{",
"return",
"INSTANCE",
".",
"get",
"(",
"config",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
".",
"start",
"(",
")",
";",
"}"
] | Returns a stopwatch that has been started and will automatically
record its result to the dynamic timer specified by the given config. The timer
will report the times in milliseconds to observers.
@see #start(MonitorConfig, TimeUnit) | [
"Returns",
"a",
"stopwatch",
"that",
"has",
"been",
"started",
"and",
"will",
"automatically",
"record",
"its",
"result",
"to",
"the",
"dynamic",
"timer",
"specified",
"by",
"the",
"given",
"config",
".",
"The",
"timer",
"will",
"report",
"the",
"times",
"in... | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java#L131-L133 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java | DynamicTimer.record | public static void record(MonitorConfig config, long duration) {
INSTANCE.get(config, TimeUnit.MILLISECONDS).record(duration, TimeUnit.MILLISECONDS);
} | java | public static void record(MonitorConfig config, long duration) {
INSTANCE.get(config, TimeUnit.MILLISECONDS).record(duration, TimeUnit.MILLISECONDS);
} | [
"public",
"static",
"void",
"record",
"(",
"MonitorConfig",
"config",
",",
"long",
"duration",
")",
"{",
"INSTANCE",
".",
"get",
"(",
"config",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
".",
"record",
"(",
"duration",
",",
"TimeUnit",
".",
"MILLISECONDS",
... | Record result to the dynamic timer indicated by the provided config
with a TimeUnit of milliseconds. | [
"Record",
"result",
"to",
"the",
"dynamic",
"timer",
"indicated",
"by",
"the",
"provided",
"config",
"with",
"a",
"TimeUnit",
"of",
"milliseconds",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java#L139-L141 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java | DynamicTimer.record | public static void record(MonitorConfig config, long duration, TimeUnit unit) {
INSTANCE.get(config, unit).record(duration, unit);
} | java | public static void record(MonitorConfig config, long duration, TimeUnit unit) {
INSTANCE.get(config, unit).record(duration, unit);
} | [
"public",
"static",
"void",
"record",
"(",
"MonitorConfig",
"config",
",",
"long",
"duration",
",",
"TimeUnit",
"unit",
")",
"{",
"INSTANCE",
".",
"get",
"(",
"config",
",",
"unit",
")",
".",
"record",
"(",
"duration",
",",
"unit",
")",
";",
"}"
] | Record a duration to the dynamic timer indicated by the provided config.
The units in which the timer is reported and the duration unit are the same.
@deprecated Use {@link DynamicTimer#record(MonitorConfig, java.util.concurrent.TimeUnit,
long, java.util.concurrent.TimeUnit)} instead.
The new method allows you to be specific about the units used for reporting the timer and
the units in which the duration is measured. | [
"Record",
"a",
"duration",
"to",
"the",
"dynamic",
"timer",
"indicated",
"by",
"the",
"provided",
"config",
".",
"The",
"units",
"in",
"which",
"the",
"timer",
"is",
"reported",
"and",
"the",
"duration",
"unit",
"are",
"the",
"same",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java#L152-L154 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java | DynamicTimer.start | public static Stopwatch start(String name, TagList list, TimeUnit unit) {
final MonitorConfig config = new MonitorConfig.Builder(name).withTags(list).build();
return INSTANCE.get(config, unit).start();
} | java | public static Stopwatch start(String name, TagList list, TimeUnit unit) {
final MonitorConfig config = new MonitorConfig.Builder(name).withTags(list).build();
return INSTANCE.get(config, unit).start();
} | [
"public",
"static",
"Stopwatch",
"start",
"(",
"String",
"name",
",",
"TagList",
"list",
",",
"TimeUnit",
"unit",
")",
"{",
"final",
"MonitorConfig",
"config",
"=",
"new",
"MonitorConfig",
".",
"Builder",
"(",
"name",
")",
".",
"withTags",
"(",
"list",
")"... | Returns a stopwatch that has been started and will automatically
record its result to the dynamic timer specified by the given config. The timer
uses a TimeUnit of milliseconds. | [
"Returns",
"a",
"stopwatch",
"that",
"has",
"been",
"started",
"and",
"will",
"automatically",
"record",
"its",
"result",
"to",
"the",
"dynamic",
"timer",
"specified",
"by",
"the",
"given",
"config",
".",
"The",
"timer",
"uses",
"a",
"TimeUnit",
"of",
"milli... | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/DynamicTimer.java#L206-L209 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/BasicStopwatch.java | BasicStopwatch.getDuration | @Override
public long getDuration() {
final long end = running.get() ? System.nanoTime() : endTime.get();
return end - startTime.get();
} | java | @Override
public long getDuration() {
final long end = running.get() ? System.nanoTime() : endTime.get();
return end - startTime.get();
} | [
"@",
"Override",
"public",
"long",
"getDuration",
"(",
")",
"{",
"final",
"long",
"end",
"=",
"running",
".",
"get",
"(",
")",
"?",
"System",
".",
"nanoTime",
"(",
")",
":",
"endTime",
".",
"get",
"(",
")",
";",
"return",
"end",
"-",
"startTime",
"... | Returns the duration in nanoseconds. No checks are performed to ensure that the stopwatch
has been properly started and stopped before executing this method. If called before stop
it will return the current duration. | [
"Returns",
"the",
"duration",
"in",
"nanoseconds",
".",
"No",
"checks",
"are",
"performed",
"to",
"ensure",
"that",
"the",
"stopwatch",
"has",
"been",
"properly",
"started",
"and",
"stopped",
"before",
"executing",
"this",
"method",
".",
"If",
"called",
"befor... | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/BasicStopwatch.java#L71-L75 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/Memoizer.java | Memoizer.create | public static <T> Memoizer<T> create(Callable<T> getter, long duration, TimeUnit unit) {
return new Memoizer<>(getter, duration, unit);
} | java | public static <T> Memoizer<T> create(Callable<T> getter, long duration, TimeUnit unit) {
return new Memoizer<>(getter, duration, unit);
} | [
"public",
"static",
"<",
"T",
">",
"Memoizer",
"<",
"T",
">",
"create",
"(",
"Callable",
"<",
"T",
">",
"getter",
",",
"long",
"duration",
",",
"TimeUnit",
"unit",
")",
"{",
"return",
"new",
"Memoizer",
"<>",
"(",
"getter",
",",
"duration",
",",
"uni... | Create a memoizer that caches the value produced by getter for a given duration.
@param getter A {@link Callable} that returns a new value. This should not throw.
@param duration how long we should keep the cached value before refreshing it.
@param unit unit of time for {@code duration}
@param <T> type of the value produced by the {@code getter}
@return A thread safe memoizer. | [
"Create",
"a",
"memoizer",
"that",
"caches",
"the",
"value",
"produced",
"by",
"getter",
"for",
"a",
"given",
"duration",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/Memoizer.java#L37-L39 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/Memoizer.java | Memoizer.get | public T get() {
long expiration = whenItExpires;
long now = System.nanoTime();
// if uninitialized or expired update value
if (expiration == 0 || now >= expiration) {
synchronized (this) {
// ensure a different thread didn't update it
if (whenItExpires == expiration) {
whenItExpires = now + durationNanos;
try {
value = getter.call();
} catch (Exception e) {
// shouldn't happen
throw Throwables.propagate(e);
}
}
}
}
return value;
} | java | public T get() {
long expiration = whenItExpires;
long now = System.nanoTime();
// if uninitialized or expired update value
if (expiration == 0 || now >= expiration) {
synchronized (this) {
// ensure a different thread didn't update it
if (whenItExpires == expiration) {
whenItExpires = now + durationNanos;
try {
value = getter.call();
} catch (Exception e) {
// shouldn't happen
throw Throwables.propagate(e);
}
}
}
}
return value;
} | [
"public",
"T",
"get",
"(",
")",
"{",
"long",
"expiration",
"=",
"whenItExpires",
";",
"long",
"now",
"=",
"System",
".",
"nanoTime",
"(",
")",
";",
"// if uninitialized or expired update value",
"if",
"(",
"expiration",
"==",
"0",
"||",
"now",
">=",
"expirat... | Get or refresh and return the latest value. | [
"Get",
"or",
"refresh",
"and",
"return",
"the",
"latest",
"value",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/Memoizer.java#L54-L74 | train |
Netflix/servo | servo-atlas/src/main/java/com/netflix/servo/publish/atlas/AtlasMetricObserver.java | AtlasMetricObserver.push | public void push(List<Metric> rawMetrics) {
List<Metric> validMetrics = ValidCharacters.toValidValues(filter(rawMetrics));
List<Metric> metrics = transformMetrics(validMetrics);
LOGGER.debug("Scheduling push of {} metrics", metrics.size());
final UpdateTasks tasks = getUpdateTasks(BasicTagList.EMPTY,
identifyCountersForPush(metrics));
final int maxAttempts = 5;
int attempts = 1;
while (!pushQueue.offer(tasks) && attempts <= maxAttempts) {
++attempts;
final UpdateTasks droppedTasks = pushQueue.remove();
LOGGER.warn("Removing old push task due to queue full. Dropping {} metrics.",
droppedTasks.numMetrics);
numMetricsDroppedQueueFull.increment(droppedTasks.numMetrics);
}
if (attempts >= maxAttempts) {
LOGGER.error("Unable to push update of {}", tasks);
numMetricsDroppedQueueFull.increment(tasks.numMetrics);
} else {
LOGGER.debug("Queued push of {}", tasks);
}
} | java | public void push(List<Metric> rawMetrics) {
List<Metric> validMetrics = ValidCharacters.toValidValues(filter(rawMetrics));
List<Metric> metrics = transformMetrics(validMetrics);
LOGGER.debug("Scheduling push of {} metrics", metrics.size());
final UpdateTasks tasks = getUpdateTasks(BasicTagList.EMPTY,
identifyCountersForPush(metrics));
final int maxAttempts = 5;
int attempts = 1;
while (!pushQueue.offer(tasks) && attempts <= maxAttempts) {
++attempts;
final UpdateTasks droppedTasks = pushQueue.remove();
LOGGER.warn("Removing old push task due to queue full. Dropping {} metrics.",
droppedTasks.numMetrics);
numMetricsDroppedQueueFull.increment(droppedTasks.numMetrics);
}
if (attempts >= maxAttempts) {
LOGGER.error("Unable to push update of {}", tasks);
numMetricsDroppedQueueFull.increment(tasks.numMetrics);
} else {
LOGGER.debug("Queued push of {}", tasks);
}
} | [
"public",
"void",
"push",
"(",
"List",
"<",
"Metric",
">",
"rawMetrics",
")",
"{",
"List",
"<",
"Metric",
">",
"validMetrics",
"=",
"ValidCharacters",
".",
"toValidValues",
"(",
"filter",
"(",
"rawMetrics",
")",
")",
";",
"List",
"<",
"Metric",
">",
"met... | Immediately send metrics to the backend.
@param rawMetrics Metrics to be sent. Names and tags will be sanitized. | [
"Immediately",
"send",
"metrics",
"to",
"the",
"backend",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/AtlasMetricObserver.java#L219-L241 | train |
Netflix/servo | servo-atlas/src/main/java/com/netflix/servo/publish/atlas/AtlasMetricObserver.java | AtlasMetricObserver.withBookkeeping | protected Func1<HttpClientResponse<ByteBuf>, Integer> withBookkeeping(final int batchSize) {
return response -> {
boolean ok = response.getStatus().code() == 200;
if (ok) {
numMetricsSent.increment(batchSize);
} else {
LOGGER.info("Status code: {} - Lost {} metrics",
response.getStatus().code(), batchSize);
numMetricsDroppedHttpErr.increment(batchSize);
}
return batchSize;
};
} | java | protected Func1<HttpClientResponse<ByteBuf>, Integer> withBookkeeping(final int batchSize) {
return response -> {
boolean ok = response.getStatus().code() == 200;
if (ok) {
numMetricsSent.increment(batchSize);
} else {
LOGGER.info("Status code: {} - Lost {} metrics",
response.getStatus().code(), batchSize);
numMetricsDroppedHttpErr.increment(batchSize);
}
return batchSize;
};
} | [
"protected",
"Func1",
"<",
"HttpClientResponse",
"<",
"ByteBuf",
">",
",",
"Integer",
">",
"withBookkeeping",
"(",
"final",
"int",
"batchSize",
")",
"{",
"return",
"response",
"->",
"{",
"boolean",
"ok",
"=",
"response",
".",
"getStatus",
"(",
")",
".",
"c... | Utility function to map an Observable<ByteBuf> to an Observable<Integer> while also
updating our counters for metrics sent and errors. | [
"Utility",
"function",
"to",
"map",
"an",
"Observable<",
";",
"ByteBuf",
">",
"to",
"an",
"Observable<",
";",
"Integer",
">",
"while",
"also",
"updating",
"our",
"counters",
"for",
"metrics",
"sent",
"and",
"errors",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-atlas/src/main/java/com/netflix/servo/publish/atlas/AtlasMetricObserver.java#L372-L385 | train |
Netflix/servo | servo-example/src/main/java/com/netflix/servo/example/Config.java | Config.getAtlasConfig | public static ServoAtlasConfig getAtlasConfig() {
return new ServoAtlasConfig() {
@Override
public String getAtlasUri() {
return getAtlasObserverUri();
}
@Override
public int getPushQueueSize() {
return 1000;
}
@Override
public boolean shouldSendMetrics() {
return isAtlasObserverEnabled();
}
@Override
public int batchSize() {
return 10000;
}
};
} | java | public static ServoAtlasConfig getAtlasConfig() {
return new ServoAtlasConfig() {
@Override
public String getAtlasUri() {
return getAtlasObserverUri();
}
@Override
public int getPushQueueSize() {
return 1000;
}
@Override
public boolean shouldSendMetrics() {
return isAtlasObserverEnabled();
}
@Override
public int batchSize() {
return 10000;
}
};
} | [
"public",
"static",
"ServoAtlasConfig",
"getAtlasConfig",
"(",
")",
"{",
"return",
"new",
"ServoAtlasConfig",
"(",
")",
"{",
"@",
"Override",
"public",
"String",
"getAtlasUri",
"(",
")",
"{",
"return",
"getAtlasObserverUri",
"(",
")",
";",
"}",
"@",
"Override"... | Get config for the atlas observer. | [
"Get",
"config",
"for",
"the",
"atlas",
"observer",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-example/src/main/java/com/netflix/servo/example/Config.java#L105-L127 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/Reflection.java | Reflection.getAllFields | public static Set<Field> getAllFields(Class<?> classs) {
Set<Field> set = new HashSet<>();
Class<?> c = classs;
while (c != null) {
set.addAll(Arrays.asList(c.getDeclaredFields()));
c = c.getSuperclass();
}
return set;
} | java | public static Set<Field> getAllFields(Class<?> classs) {
Set<Field> set = new HashSet<>();
Class<?> c = classs;
while (c != null) {
set.addAll(Arrays.asList(c.getDeclaredFields()));
c = c.getSuperclass();
}
return set;
} | [
"public",
"static",
"Set",
"<",
"Field",
">",
"getAllFields",
"(",
"Class",
"<",
"?",
">",
"classs",
")",
"{",
"Set",
"<",
"Field",
">",
"set",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"Class",
"<",
"?",
">",
"c",
"=",
"classs",
";",
"while",
... | Gets all fields from class and its super classes.
@param classs class to get fields from
@return set of fields | [
"Gets",
"all",
"fields",
"from",
"class",
"and",
"its",
"super",
"classes",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/Reflection.java#L39-L47 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/Reflection.java | Reflection.getAllMethods | public static Set<Method> getAllMethods(Class<?> classs) {
Set<Method> set = new HashSet<>();
Class<?> c = classs;
while (c != null) {
set.addAll(Arrays.asList(c.getDeclaredMethods()));
c = c.getSuperclass();
}
return set;
} | java | public static Set<Method> getAllMethods(Class<?> classs) {
Set<Method> set = new HashSet<>();
Class<?> c = classs;
while (c != null) {
set.addAll(Arrays.asList(c.getDeclaredMethods()));
c = c.getSuperclass();
}
return set;
} | [
"public",
"static",
"Set",
"<",
"Method",
">",
"getAllMethods",
"(",
"Class",
"<",
"?",
">",
"classs",
")",
"{",
"Set",
"<",
"Method",
">",
"set",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"Class",
"<",
"?",
">",
"c",
"=",
"classs",
";",
"while... | Gets all methods from class and its super classes.
@param classs class to get methods from
@return set of methods | [
"Gets",
"all",
"methods",
"from",
"class",
"and",
"its",
"super",
"classes",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/Reflection.java#L55-L63 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/Reflection.java | Reflection.getFieldsAnnotatedBy | public static Set<Field> getFieldsAnnotatedBy(Class<?> classs, Class<? extends Annotation> ann) {
Set<Field> set = new HashSet<>();
for (Field field : getAllFields(classs)) {
if (field.isAnnotationPresent(ann)) {
set.add(field);
}
}
return set;
} | java | public static Set<Field> getFieldsAnnotatedBy(Class<?> classs, Class<? extends Annotation> ann) {
Set<Field> set = new HashSet<>();
for (Field field : getAllFields(classs)) {
if (field.isAnnotationPresent(ann)) {
set.add(field);
}
}
return set;
} | [
"public",
"static",
"Set",
"<",
"Field",
">",
"getFieldsAnnotatedBy",
"(",
"Class",
"<",
"?",
">",
"classs",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"ann",
")",
"{",
"Set",
"<",
"Field",
">",
"set",
"=",
"new",
"HashSet",
"<>",
"(",
")"... | Gets all fields annotated by annotation.
@param classs class to get fields from
@param ann annotation that must be present on the field
@return set of fields | [
"Gets",
"all",
"fields",
"annotated",
"by",
"annotation",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/Reflection.java#L72-L80 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/Reflection.java | Reflection.getMethodsAnnotatedBy | public static Set<Method> getMethodsAnnotatedBy(
Class<?> classs, Class<? extends Annotation> ann) {
Set<Method> set = new HashSet<>();
for (Method method : getAllMethods(classs)) {
if (method.isAnnotationPresent(ann)) {
set.add(method);
}
}
return set;
} | java | public static Set<Method> getMethodsAnnotatedBy(
Class<?> classs, Class<? extends Annotation> ann) {
Set<Method> set = new HashSet<>();
for (Method method : getAllMethods(classs)) {
if (method.isAnnotationPresent(ann)) {
set.add(method);
}
}
return set;
} | [
"public",
"static",
"Set",
"<",
"Method",
">",
"getMethodsAnnotatedBy",
"(",
"Class",
"<",
"?",
">",
"classs",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"ann",
")",
"{",
"Set",
"<",
"Method",
">",
"set",
"=",
"new",
"HashSet",
"<>",
"(",
... | Gets all methods annotated by annotation.
@param classs class to get fields from
@param ann annotation that must be present on the method
@return set of methods | [
"Gets",
"all",
"methods",
"annotated",
"by",
"annotation",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/Reflection.java#L89-L98 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/AbstractContextualMonitor.java | AbstractContextualMonitor.getMonitorForCurrentContext | protected M getMonitorForCurrentContext() {
MonitorConfig contextConfig = getConfig();
M monitor = monitors.get(contextConfig);
if (monitor == null) {
M newMon = newMonitor.apply(contextConfig);
if (newMon instanceof SpectatorMonitor) {
((SpectatorMonitor) newMon).initializeSpectator(spectatorTags);
}
monitor = monitors.putIfAbsent(contextConfig, newMon);
if (monitor == null) {
monitor = newMon;
}
}
return monitor;
} | java | protected M getMonitorForCurrentContext() {
MonitorConfig contextConfig = getConfig();
M monitor = monitors.get(contextConfig);
if (monitor == null) {
M newMon = newMonitor.apply(contextConfig);
if (newMon instanceof SpectatorMonitor) {
((SpectatorMonitor) newMon).initializeSpectator(spectatorTags);
}
monitor = monitors.putIfAbsent(contextConfig, newMon);
if (monitor == null) {
monitor = newMon;
}
}
return monitor;
} | [
"protected",
"M",
"getMonitorForCurrentContext",
"(",
")",
"{",
"MonitorConfig",
"contextConfig",
"=",
"getConfig",
"(",
")",
";",
"M",
"monitor",
"=",
"monitors",
".",
"get",
"(",
"contextConfig",
")",
";",
"if",
"(",
"monitor",
"==",
"null",
")",
"{",
"M... | Returns a monitor instance for the current context. If no monitor exists for the current
context then a new one will be created. | [
"Returns",
"a",
"monitor",
"instance",
"for",
"the",
"current",
"context",
".",
"If",
"no",
"monitor",
"exists",
"for",
"the",
"current",
"context",
"then",
"a",
"new",
"one",
"will",
"be",
"created",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/AbstractContextualMonitor.java#L97-L111 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/tag/Tags.java | Tags.internCustom | static Tag internCustom(Tag t) {
return (t instanceof BasicTag) ? t : newTag(t.getKey(), t.getValue());
} | java | static Tag internCustom(Tag t) {
return (t instanceof BasicTag) ? t : newTag(t.getKey(), t.getValue());
} | [
"static",
"Tag",
"internCustom",
"(",
"Tag",
"t",
")",
"{",
"return",
"(",
"t",
"instanceof",
"BasicTag",
")",
"?",
"t",
":",
"newTag",
"(",
"t",
".",
"getKey",
"(",
")",
",",
"t",
".",
"getValue",
"(",
")",
")",
";",
"}"
] | Interns custom tag types, assumes that basic tags are already interned. This is used to
ensure that we have a common view of tags internally. In particular, different subclasses of
Tag may not be equal even if they have the same key and value. Tag lists should use this to
ensure the equality will work as expected. | [
"Interns",
"custom",
"tag",
"types",
"assumes",
"that",
"basic",
"tags",
"are",
"already",
"interned",
".",
"This",
"is",
"used",
"to",
"ensure",
"that",
"we",
"have",
"a",
"common",
"view",
"of",
"tags",
"internally",
".",
"In",
"particular",
"different",
... | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/tag/Tags.java#L55-L57 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/tag/Tags.java | Tags.newTag | public static Tag newTag(String key, String value) {
Tag newTag = new BasicTag(intern(key), intern(value));
return intern(newTag);
} | java | public static Tag newTag(String key, String value) {
Tag newTag = new BasicTag(intern(key), intern(value));
return intern(newTag);
} | [
"public",
"static",
"Tag",
"newTag",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"Tag",
"newTag",
"=",
"new",
"BasicTag",
"(",
"intern",
"(",
"key",
")",
",",
"intern",
"(",
"value",
")",
")",
";",
"return",
"intern",
"(",
"newTag",
")",
... | Create a new tag instance. | [
"Create",
"a",
"new",
"tag",
"instance",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/tag/Tags.java#L62-L65 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/BucketConfig.java | BucketConfig.getTimeUnitAbbreviation | public String getTimeUnitAbbreviation() {
switch (timeUnit) {
case DAYS:
return "day";
case HOURS:
return "hr";
case MICROSECONDS:
return "\u00B5s";
case MILLISECONDS:
return "ms";
case MINUTES:
return "min";
case NANOSECONDS:
return "ns";
case SECONDS:
return "s";
default:
return "unkwn";
}
} | java | public String getTimeUnitAbbreviation() {
switch (timeUnit) {
case DAYS:
return "day";
case HOURS:
return "hr";
case MICROSECONDS:
return "\u00B5s";
case MILLISECONDS:
return "ms";
case MINUTES:
return "min";
case NANOSECONDS:
return "ns";
case SECONDS:
return "s";
default:
return "unkwn";
}
} | [
"public",
"String",
"getTimeUnitAbbreviation",
"(",
")",
"{",
"switch",
"(",
"timeUnit",
")",
"{",
"case",
"DAYS",
":",
"return",
"\"day\"",
";",
"case",
"HOURS",
":",
"return",
"\"hr\"",
";",
"case",
"MICROSECONDS",
":",
"return",
"\"\\u00B5s\"",
";",
"case... | Returns an abbreviation for the Bucket's TimeUnit. | [
"Returns",
"an",
"abbreviation",
"for",
"the",
"Bucket",
"s",
"TimeUnit",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/BucketConfig.java#L121-L140 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java | ThreadCpuStats.start | public synchronized void start() {
if (!running) {
running = true;
Thread t = new Thread(new CpuStatRunnable(), "ThreadCpuStatsCollector");
t.setDaemon(true);
t.start();
}
} | java | public synchronized void start() {
if (!running) {
running = true;
Thread t = new Thread(new CpuStatRunnable(), "ThreadCpuStatsCollector");
t.setDaemon(true);
t.start();
}
} | [
"public",
"synchronized",
"void",
"start",
"(",
")",
"{",
"if",
"(",
"!",
"running",
")",
"{",
"running",
"=",
"true",
";",
"Thread",
"t",
"=",
"new",
"Thread",
"(",
"new",
"CpuStatRunnable",
"(",
")",
",",
"\"ThreadCpuStatsCollector\"",
")",
";",
"t",
... | Start collecting cpu stats for the threads. | [
"Start",
"collecting",
"cpu",
"stats",
"for",
"the",
"threads",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java#L133-L140 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java | ThreadCpuStats.toDuration | public static String toDuration(long inputTime) {
final long second = 1000000000L;
final long minute = 60 * second;
final long hour = 60 * minute;
final long day = 24 * hour;
final long week = 7 * day;
long time = inputTime;
final StringBuilder buf = new StringBuilder();
buf.append('P');
time = append(buf, 'W', week, time);
time = append(buf, 'D', day, time);
buf.append('T');
time = append(buf, 'H', hour, time);
time = append(buf, 'M', minute, time);
append(buf, 'S', second, time);
return buf.toString();
} | java | public static String toDuration(long inputTime) {
final long second = 1000000000L;
final long minute = 60 * second;
final long hour = 60 * minute;
final long day = 24 * hour;
final long week = 7 * day;
long time = inputTime;
final StringBuilder buf = new StringBuilder();
buf.append('P');
time = append(buf, 'W', week, time);
time = append(buf, 'D', day, time);
buf.append('T');
time = append(buf, 'H', hour, time);
time = append(buf, 'M', minute, time);
append(buf, 'S', second, time);
return buf.toString();
} | [
"public",
"static",
"String",
"toDuration",
"(",
"long",
"inputTime",
")",
"{",
"final",
"long",
"second",
"=",
"1000000000L",
";",
"final",
"long",
"minute",
"=",
"60",
"*",
"second",
";",
"final",
"long",
"hour",
"=",
"60",
"*",
"minute",
";",
"final",... | Convert time in nanoseconds to a duration string. This is used to provide a more human
readable order of magnitude for the duration. We assume standard fixed size quantities for
all units. | [
"Convert",
"time",
"in",
"nanoseconds",
"to",
"a",
"duration",
"string",
".",
"This",
"is",
"used",
"to",
"provide",
"a",
"more",
"human",
"readable",
"order",
"of",
"magnitude",
"for",
"the",
"duration",
".",
"We",
"assume",
"standard",
"fixed",
"size",
"... | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java#L185-L202 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java | ThreadCpuStats.printThreadCpuUsages | public void printThreadCpuUsages(OutputStream out, CpuUsageComparator cmp) {
final PrintWriter writer = getPrintWriter(out);
final Map<String, Object> threadCpuUsages = getThreadCpuUsages(cmp);
writer.printf("Time: %s%n%n", new Date((Long) threadCpuUsages.get(CURRENT_TIME)));
final long uptimeMillis = (Long) threadCpuUsages.get(UPTIME_MS);
final long uptimeNanos = TimeUnit.NANOSECONDS.convert(uptimeMillis, TimeUnit.MILLISECONDS);
writer.printf("Uptime: %s%n%n", toDuration(uptimeNanos));
@SuppressWarnings("unchecked")
final Map<String, Long> jvmUsageTime = (Map<String, Long>)
threadCpuUsages.get(JVM_USAGE_TIME);
writer.println("JVM Usage Time: ");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
writer.printf("%11s %11s %11s %11s %7s %s%n",
toDuration(jvmUsageTime.get(ONE_MIN)),
toDuration(jvmUsageTime.get(FIVE_MIN)),
toDuration(jvmUsageTime.get(FIFTEEN_MIN)),
toDuration(jvmUsageTime.get(OVERALL)),
"-",
"jvm");
writer.println();
@SuppressWarnings("unchecked")
final Map<String, Double> jvmUsagePerc =
(Map<String, Double>) threadCpuUsages.get(JVM_USAGE_PERCENT);
writer.println("JVM Usage Percent: ");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7s %s%n",
jvmUsagePerc.get(ONE_MIN),
jvmUsagePerc.get(FIVE_MIN),
jvmUsagePerc.get(FIFTEEN_MIN),
jvmUsagePerc.get(OVERALL),
"-",
"jvm");
writer.println();
writer.println("Breakdown by thread (100% = total cpu usage for jvm):");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
@SuppressWarnings("unchecked")
List<Map<String, Object>> threads =
(List<Map<String, Object>>) threadCpuUsages.get(THREADS);
for (Map<String, Object> thread : threads) {
writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7d %s%n",
thread.get(ONE_MIN),
thread.get(FIVE_MIN),
thread.get(FIFTEEN_MIN),
thread.get(OVERALL),
thread.get(ID),
thread.get(NAME));
}
writer.println();
writer.flush();
} | java | public void printThreadCpuUsages(OutputStream out, CpuUsageComparator cmp) {
final PrintWriter writer = getPrintWriter(out);
final Map<String, Object> threadCpuUsages = getThreadCpuUsages(cmp);
writer.printf("Time: %s%n%n", new Date((Long) threadCpuUsages.get(CURRENT_TIME)));
final long uptimeMillis = (Long) threadCpuUsages.get(UPTIME_MS);
final long uptimeNanos = TimeUnit.NANOSECONDS.convert(uptimeMillis, TimeUnit.MILLISECONDS);
writer.printf("Uptime: %s%n%n", toDuration(uptimeNanos));
@SuppressWarnings("unchecked")
final Map<String, Long> jvmUsageTime = (Map<String, Long>)
threadCpuUsages.get(JVM_USAGE_TIME);
writer.println("JVM Usage Time: ");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
writer.printf("%11s %11s %11s %11s %7s %s%n",
toDuration(jvmUsageTime.get(ONE_MIN)),
toDuration(jvmUsageTime.get(FIVE_MIN)),
toDuration(jvmUsageTime.get(FIFTEEN_MIN)),
toDuration(jvmUsageTime.get(OVERALL)),
"-",
"jvm");
writer.println();
@SuppressWarnings("unchecked")
final Map<String, Double> jvmUsagePerc =
(Map<String, Double>) threadCpuUsages.get(JVM_USAGE_PERCENT);
writer.println("JVM Usage Percent: ");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7s %s%n",
jvmUsagePerc.get(ONE_MIN),
jvmUsagePerc.get(FIVE_MIN),
jvmUsagePerc.get(FIFTEEN_MIN),
jvmUsagePerc.get(OVERALL),
"-",
"jvm");
writer.println();
writer.println("Breakdown by thread (100% = total cpu usage for jvm):");
writer.printf("%11s %11s %11s %11s %7s %s%n",
"1-min", "5-min", "15-min", "overall", "id", "name");
@SuppressWarnings("unchecked")
List<Map<String, Object>> threads =
(List<Map<String, Object>>) threadCpuUsages.get(THREADS);
for (Map<String, Object> thread : threads) {
writer.printf("%10.2f%% %10.2f%% %10.2f%% %10.2f%% %7d %s%n",
thread.get(ONE_MIN),
thread.get(FIVE_MIN),
thread.get(FIFTEEN_MIN),
thread.get(OVERALL),
thread.get(ID),
thread.get(NAME));
}
writer.println();
writer.flush();
} | [
"public",
"void",
"printThreadCpuUsages",
"(",
"OutputStream",
"out",
",",
"CpuUsageComparator",
"cmp",
")",
"{",
"final",
"PrintWriter",
"writer",
"=",
"getPrintWriter",
"(",
"out",
")",
";",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"threadCpuUsages",... | Utility function that dumps the cpu usages for the threads to stdout. Output will be sorted
based on the 1-minute usage from highest to lowest.
@param out stream where output will be written
@param cmp order to use for the results | [
"Utility",
"function",
"that",
"dumps",
"the",
"cpu",
"usages",
"for",
"the",
"threads",
"to",
"stdout",
".",
"Output",
"will",
"be",
"sorted",
"based",
"on",
"the",
"1",
"-",
"minute",
"usage",
"from",
"highest",
"to",
"lowest",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java#L282-L338 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java | ThreadCpuStats.updateStats | private void updateStats() {
final ThreadMXBean bean = ManagementFactory.getThreadMXBean();
if (bean.isThreadCpuTimeEnabled()) {
// Update stats for all current threads
final long[] ids = bean.getAllThreadIds();
Arrays.sort(ids);
long totalCpuTime = 0L;
for (long id : ids) {
long cpuTime = bean.getThreadCpuTime(id);
if (cpuTime != -1) {
totalCpuTime += cpuTime;
CpuUsage usage = threadCpuUsages.get(id);
if (usage == null) {
final ThreadInfo info = bean.getThreadInfo(id);
usage = new CpuUsage(id, info.getThreadName());
threadCpuUsages.put(id, usage);
}
usage.update(cpuTime);
}
}
// Update jvm cpu usage, if possible we query the operating system mxbean so we get
// an accurate total including any threads that may have been started and stopped
// between sampling. As a fallback we use the sum of the cpu time for all threads found
// in this interval.
//
// Total cpu time can be found in:
// http://docs.oracle.com/javase/7/docs/jre/api/management/extension/\
// com/sun/management/OperatingSystemMXBean.html
//
// We use reflection to avoid direct dependency on com.sun.* classes.
final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
try {
final Method m = osBean.getClass().getMethod("getProcessCpuTime");
final long jvmCpuTime = (Long) m.invoke(osBean);
jvmCpuUsage.update((jvmCpuTime < 0) ? totalCpuTime : jvmCpuTime);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
jvmCpuUsage.update(totalCpuTime);
}
// Handle ids in the map that no longer exist:
// * Remove old entries if the last update time is over AGE_LIMIT
// * Otherwise, update usage so rolling window is correct
final long now = System.currentTimeMillis();
final Iterator<Map.Entry<Long, CpuUsage>> iter = threadCpuUsages.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<Long, CpuUsage> entry = iter.next();
final long id = entry.getKey();
final CpuUsage usage = entry.getValue();
if (now - usage.getLastUpdateTime() > AGE_LIMIT) {
iter.remove();
} else if (Arrays.binarySearch(ids, id) < 0) {
usage.updateNoValue();
}
}
} else {
LOGGER.debug("ThreadMXBean.isThreadCpuTimeEnabled() == false, cannot collect stats");
}
} | java | private void updateStats() {
final ThreadMXBean bean = ManagementFactory.getThreadMXBean();
if (bean.isThreadCpuTimeEnabled()) {
// Update stats for all current threads
final long[] ids = bean.getAllThreadIds();
Arrays.sort(ids);
long totalCpuTime = 0L;
for (long id : ids) {
long cpuTime = bean.getThreadCpuTime(id);
if (cpuTime != -1) {
totalCpuTime += cpuTime;
CpuUsage usage = threadCpuUsages.get(id);
if (usage == null) {
final ThreadInfo info = bean.getThreadInfo(id);
usage = new CpuUsage(id, info.getThreadName());
threadCpuUsages.put(id, usage);
}
usage.update(cpuTime);
}
}
// Update jvm cpu usage, if possible we query the operating system mxbean so we get
// an accurate total including any threads that may have been started and stopped
// between sampling. As a fallback we use the sum of the cpu time for all threads found
// in this interval.
//
// Total cpu time can be found in:
// http://docs.oracle.com/javase/7/docs/jre/api/management/extension/\
// com/sun/management/OperatingSystemMXBean.html
//
// We use reflection to avoid direct dependency on com.sun.* classes.
final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
try {
final Method m = osBean.getClass().getMethod("getProcessCpuTime");
final long jvmCpuTime = (Long) m.invoke(osBean);
jvmCpuUsage.update((jvmCpuTime < 0) ? totalCpuTime : jvmCpuTime);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
jvmCpuUsage.update(totalCpuTime);
}
// Handle ids in the map that no longer exist:
// * Remove old entries if the last update time is over AGE_LIMIT
// * Otherwise, update usage so rolling window is correct
final long now = System.currentTimeMillis();
final Iterator<Map.Entry<Long, CpuUsage>> iter = threadCpuUsages.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<Long, CpuUsage> entry = iter.next();
final long id = entry.getKey();
final CpuUsage usage = entry.getValue();
if (now - usage.getLastUpdateTime() > AGE_LIMIT) {
iter.remove();
} else if (Arrays.binarySearch(ids, id) < 0) {
usage.updateNoValue();
}
}
} else {
LOGGER.debug("ThreadMXBean.isThreadCpuTimeEnabled() == false, cannot collect stats");
}
} | [
"private",
"void",
"updateStats",
"(",
")",
"{",
"final",
"ThreadMXBean",
"bean",
"=",
"ManagementFactory",
".",
"getThreadMXBean",
"(",
")",
";",
"if",
"(",
"bean",
".",
"isThreadCpuTimeEnabled",
"(",
")",
")",
"{",
"// Update stats for all current threads",
"fin... | Update the stats for all threads and the jvm. | [
"Update",
"the",
"stats",
"for",
"all",
"threads",
"and",
"the",
"jvm",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/ThreadCpuStats.java#L349-L407 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/util/TimeLimiter.java | TimeLimiter.callWithTimeout | public <T> T callWithTimeout(Callable<T> callable, long duration, TimeUnit unit)
throws Exception {
Future<T> future = executor.submit(callable);
try {
return future.get(duration, unit);
} catch (InterruptedException e) {
future.cancel(true);
throw e;
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause == null) {
cause = e;
}
if (cause instanceof Exception) {
throw (Exception) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw e;
} catch (TimeoutException e) {
future.cancel(true);
throw new UncheckedTimeoutException(e);
}
} | java | public <T> T callWithTimeout(Callable<T> callable, long duration, TimeUnit unit)
throws Exception {
Future<T> future = executor.submit(callable);
try {
return future.get(duration, unit);
} catch (InterruptedException e) {
future.cancel(true);
throw e;
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause == null) {
cause = e;
}
if (cause instanceof Exception) {
throw (Exception) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw e;
} catch (TimeoutException e) {
future.cancel(true);
throw new UncheckedTimeoutException(e);
}
} | [
"public",
"<",
"T",
">",
"T",
"callWithTimeout",
"(",
"Callable",
"<",
"T",
">",
"callable",
",",
"long",
"duration",
",",
"TimeUnit",
"unit",
")",
"throws",
"Exception",
"{",
"Future",
"<",
"T",
">",
"future",
"=",
"executor",
".",
"submit",
"(",
"cal... | Invokes a specified Callable, timing out after the specified time limit.
If the target method call finished before the limit is reached, the return
value or exception is propagated to the caller exactly as-is. If, on the
other hand, the time limit is reached, we attempt to abort the call to the
Callable and throw an exception. | [
"Invokes",
"a",
"specified",
"Callable",
"timing",
"out",
"after",
"the",
"specified",
"time",
"limit",
".",
"If",
"the",
"target",
"method",
"call",
"finished",
"before",
"the",
"limit",
"is",
"reached",
"the",
"return",
"value",
"or",
"exception",
"is",
"p... | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/util/TimeLimiter.java#L48-L72 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.newTimer | public static Timer newTimer(String name, TimeUnit unit) {
return new BasicTimer(MonitorConfig.builder(name).build(), unit);
} | java | public static Timer newTimer(String name, TimeUnit unit) {
return new BasicTimer(MonitorConfig.builder(name).build(), unit);
} | [
"public",
"static",
"Timer",
"newTimer",
"(",
"String",
"name",
",",
"TimeUnit",
"unit",
")",
"{",
"return",
"new",
"BasicTimer",
"(",
"MonitorConfig",
".",
"builder",
"(",
"name",
")",
".",
"build",
"(",
")",
",",
"unit",
")",
";",
"}"
] | Create a new timer with only the name specified. | [
"Create",
"a",
"new",
"timer",
"with",
"only",
"the",
"name",
"specified",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L97-L99 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.newCounter | public static Counter newCounter(String name, TaggingContext context) {
final MonitorConfig config = MonitorConfig.builder(name).build();
return new ContextualCounter(config, context, COUNTER_FUNCTION);
} | java | public static Counter newCounter(String name, TaggingContext context) {
final MonitorConfig config = MonitorConfig.builder(name).build();
return new ContextualCounter(config, context, COUNTER_FUNCTION);
} | [
"public",
"static",
"Counter",
"newCounter",
"(",
"String",
"name",
",",
"TaggingContext",
"context",
")",
"{",
"final",
"MonitorConfig",
"config",
"=",
"MonitorConfig",
".",
"builder",
"(",
"name",
")",
".",
"build",
"(",
")",
";",
"return",
"new",
"Context... | Create a new counter with a name and context. The returned counter will maintain separate
sub-monitors for each distinct set of tags returned from the context on an update operation. | [
"Create",
"a",
"new",
"counter",
"with",
"a",
"name",
"and",
"context",
".",
"The",
"returned",
"counter",
"will",
"maintain",
"separate",
"sub",
"-",
"monitors",
"for",
"each",
"distinct",
"set",
"of",
"tags",
"returned",
"from",
"the",
"context",
"on",
"... | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L121-L124 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.newObjectMonitor | public static CompositeMonitor<?> newObjectMonitor(String id, Object obj) {
final TagList tags = getMonitorTags(obj);
List<Monitor<?>> monitors = new ArrayList<>();
addMonitors(monitors, id, tags, obj);
final Class<?> c = obj.getClass();
final String objectId = (id == null) ? DEFAULT_ID : id;
return new BasicCompositeMonitor(newObjectConfig(c, objectId, tags), monitors);
} | java | public static CompositeMonitor<?> newObjectMonitor(String id, Object obj) {
final TagList tags = getMonitorTags(obj);
List<Monitor<?>> monitors = new ArrayList<>();
addMonitors(monitors, id, tags, obj);
final Class<?> c = obj.getClass();
final String objectId = (id == null) ? DEFAULT_ID : id;
return new BasicCompositeMonitor(newObjectConfig(c, objectId, tags), monitors);
} | [
"public",
"static",
"CompositeMonitor",
"<",
"?",
">",
"newObjectMonitor",
"(",
"String",
"id",
",",
"Object",
"obj",
")",
"{",
"final",
"TagList",
"tags",
"=",
"getMonitorTags",
"(",
"obj",
")",
";",
"List",
"<",
"Monitor",
"<",
"?",
">",
">",
"monitors... | Helper function to easily create a composite for all monitor fields and
annotated attributes of a given object.
@param id a unique id associated with this particular instance of the
object. If multiple objects of the same class are registered
they will have the same config and conflict unless the id
values are distinct.
@param obj object to search for monitors on. All fields of type
{@link Monitor} and fields/methods with a
{@link com.netflix.servo.annotations.Monitor} annotation
will be extracted and returned using
{@link CompositeMonitor#getMonitors()}.
@return composite monitor based on the fields of the class | [
"Helper",
"function",
"to",
"easily",
"create",
"a",
"composite",
"for",
"all",
"monitor",
"fields",
"and",
"annotated",
"attributes",
"of",
"a",
"given",
"object",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L149-L158 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.newThreadPoolMonitor | public static CompositeMonitor<?> newThreadPoolMonitor(String id, ThreadPoolExecutor pool) {
return newObjectMonitor(id, new MonitoredThreadPool(pool));
} | java | public static CompositeMonitor<?> newThreadPoolMonitor(String id, ThreadPoolExecutor pool) {
return newObjectMonitor(id, new MonitoredThreadPool(pool));
} | [
"public",
"static",
"CompositeMonitor",
"<",
"?",
">",
"newThreadPoolMonitor",
"(",
"String",
"id",
",",
"ThreadPoolExecutor",
"pool",
")",
"{",
"return",
"newObjectMonitor",
"(",
"id",
",",
"new",
"MonitoredThreadPool",
"(",
"pool",
")",
")",
";",
"}"
] | Creates a new monitor for a thread pool with standard metrics for the pool size, queue size,
task counts, etc.
@param id id to differentiate metrics for this pool from others.
@param pool thread pool instance to monitor.
@return composite monitor based on stats provided for the pool | [
"Creates",
"a",
"new",
"monitor",
"for",
"a",
"thread",
"pool",
"with",
"standard",
"metrics",
"for",
"the",
"pool",
"size",
"queue",
"size",
"task",
"counts",
"etc",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L168-L170 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.newCacheMonitor | public static CompositeMonitor<?> newCacheMonitor(String id, Cache<?, ?> cache) {
return newObjectMonitor(id, new MonitoredCache(cache));
} | java | public static CompositeMonitor<?> newCacheMonitor(String id, Cache<?, ?> cache) {
return newObjectMonitor(id, new MonitoredCache(cache));
} | [
"public",
"static",
"CompositeMonitor",
"<",
"?",
">",
"newCacheMonitor",
"(",
"String",
"id",
",",
"Cache",
"<",
"?",
",",
"?",
">",
"cache",
")",
"{",
"return",
"newObjectMonitor",
"(",
"id",
",",
"new",
"MonitoredCache",
"(",
"cache",
")",
")",
";",
... | Creates a new monitor for a cache with standard metrics for the hits, misses, and loads.
@param id id to differentiate metrics for this cache from others.
@param cache cache instance to monitor.
@return composite monitor based on stats provided for the cache | [
"Creates",
"a",
"new",
"monitor",
"for",
"a",
"cache",
"with",
"standard",
"metrics",
"for",
"the",
"hits",
"misses",
"and",
"loads",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L179-L181 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.isObjectRegistered | public static boolean isObjectRegistered(String id, Object obj) {
return DefaultMonitorRegistry.getInstance().isRegistered(newObjectMonitor(id, obj));
} | java | public static boolean isObjectRegistered(String id, Object obj) {
return DefaultMonitorRegistry.getInstance().isRegistered(newObjectMonitor(id, obj));
} | [
"public",
"static",
"boolean",
"isObjectRegistered",
"(",
"String",
"id",
",",
"Object",
"obj",
")",
"{",
"return",
"DefaultMonitorRegistry",
".",
"getInstance",
"(",
")",
".",
"isRegistered",
"(",
"newObjectMonitor",
"(",
"id",
",",
"obj",
")",
")",
";",
"}... | Check whether an object is currently registered with the default registry. | [
"Check",
"whether",
"an",
"object",
"is",
"currently",
"registered",
"with",
"the",
"default",
"registry",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L229-L231 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.wrap | @SuppressWarnings("unchecked")
static <T> Monitor<T> wrap(TagList tags, Monitor<T> monitor) {
Monitor<T> m;
if (monitor instanceof CompositeMonitor<?>) {
m = new CompositeMonitorWrapper<>(tags, (CompositeMonitor<T>) monitor);
} else {
m = MonitorWrapper.create(tags, monitor);
}
return m;
} | java | @SuppressWarnings("unchecked")
static <T> Monitor<T> wrap(TagList tags, Monitor<T> monitor) {
Monitor<T> m;
if (monitor instanceof CompositeMonitor<?>) {
m = new CompositeMonitorWrapper<>(tags, (CompositeMonitor<T>) monitor);
} else {
m = MonitorWrapper.create(tags, monitor);
}
return m;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"static",
"<",
"T",
">",
"Monitor",
"<",
"T",
">",
"wrap",
"(",
"TagList",
"tags",
",",
"Monitor",
"<",
"T",
">",
"monitor",
")",
"{",
"Monitor",
"<",
"T",
">",
"m",
";",
"if",
"(",
"monitor",
"in... | Returns a new monitor that adds the provided tags to the configuration returned by the
wrapped monitor. | [
"Returns",
"a",
"new",
"monitor",
"that",
"adds",
"the",
"provided",
"tags",
"to",
"the",
"configuration",
"returned",
"by",
"the",
"wrapped",
"monitor",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L237-L246 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.addMonitors | static void addMonitors(List<Monitor<?>> monitors, String id, TagList tags, Object obj) {
addMonitorFields(monitors, id, tags, obj);
addAnnotatedFields(monitors, id, tags, obj);
} | java | static void addMonitors(List<Monitor<?>> monitors, String id, TagList tags, Object obj) {
addMonitorFields(monitors, id, tags, obj);
addAnnotatedFields(monitors, id, tags, obj);
} | [
"static",
"void",
"addMonitors",
"(",
"List",
"<",
"Monitor",
"<",
"?",
">",
">",
"monitors",
",",
"String",
"id",
",",
"TagList",
"tags",
",",
"Object",
"obj",
")",
"{",
"addMonitorFields",
"(",
"monitors",
",",
"id",
",",
"tags",
",",
"obj",
")",
"... | Extract all monitors across class hierarchy. | [
"Extract",
"all",
"monitors",
"across",
"class",
"hierarchy",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L251-L254 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.getMonitorTags | private static TagList getMonitorTags(Object obj) {
try {
Set<Field> fields = getFieldsAnnotatedBy(obj.getClass(), MonitorTags.class);
for (Field field : fields) {
field.setAccessible(true);
return (TagList) field.get(obj);
}
Set<Method> methods = getMethodsAnnotatedBy(obj.getClass(), MonitorTags.class);
for (Method method : methods) {
method.setAccessible(true);
return (TagList) method.invoke(obj);
}
} catch (Exception e) {
throw Throwables.propagate(e);
}
return null;
} | java | private static TagList getMonitorTags(Object obj) {
try {
Set<Field> fields = getFieldsAnnotatedBy(obj.getClass(), MonitorTags.class);
for (Field field : fields) {
field.setAccessible(true);
return (TagList) field.get(obj);
}
Set<Method> methods = getMethodsAnnotatedBy(obj.getClass(), MonitorTags.class);
for (Method method : methods) {
method.setAccessible(true);
return (TagList) method.invoke(obj);
}
} catch (Exception e) {
throw Throwables.propagate(e);
}
return null;
} | [
"private",
"static",
"TagList",
"getMonitorTags",
"(",
"Object",
"obj",
")",
"{",
"try",
"{",
"Set",
"<",
"Field",
">",
"fields",
"=",
"getFieldsAnnotatedBy",
"(",
"obj",
".",
"getClass",
"(",
")",
",",
"MonitorTags",
".",
"class",
")",
";",
"for",
"(",
... | Get tags from annotation. | [
"Get",
"tags",
"from",
"annotation",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L338-L356 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.checkType | private static void checkType(
com.netflix.servo.annotations.Monitor anno, Class<?> type, Class<?> container) {
if (!isNumericType(type)) {
final String msg = "annotation of type " + anno.type().name() + " can only be used"
+ " with numeric values, " + anno.name() + " in class " + container.getName()
+ " is applied to a field or method of type " + type.getName();
throw new IllegalArgumentException(msg);
}
} | java | private static void checkType(
com.netflix.servo.annotations.Monitor anno, Class<?> type, Class<?> container) {
if (!isNumericType(type)) {
final String msg = "annotation of type " + anno.type().name() + " can only be used"
+ " with numeric values, " + anno.name() + " in class " + container.getName()
+ " is applied to a field or method of type " + type.getName();
throw new IllegalArgumentException(msg);
}
} | [
"private",
"static",
"void",
"checkType",
"(",
"com",
".",
"netflix",
".",
"servo",
".",
"annotations",
".",
"Monitor",
"anno",
",",
"Class",
"<",
"?",
">",
"type",
",",
"Class",
"<",
"?",
">",
"container",
")",
"{",
"if",
"(",
"!",
"isNumericType",
... | Verify that the type for the annotated field is numeric. | [
"Verify",
"that",
"the",
"type",
"for",
"the",
"annotated",
"field",
"is",
"numeric",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L361-L369 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.newObjectConfig | private static MonitorConfig newObjectConfig(Class<?> c, String id, TagList tags) {
final MonitorConfig.Builder builder = MonitorConfig.builder(id);
final String className = className(c);
if (!className.isEmpty()) {
builder.withTag("class", className);
}
if (tags != null) {
builder.withTags(tags);
}
return builder.build();
} | java | private static MonitorConfig newObjectConfig(Class<?> c, String id, TagList tags) {
final MonitorConfig.Builder builder = MonitorConfig.builder(id);
final String className = className(c);
if (!className.isEmpty()) {
builder.withTag("class", className);
}
if (tags != null) {
builder.withTags(tags);
}
return builder.build();
} | [
"private",
"static",
"MonitorConfig",
"newObjectConfig",
"(",
"Class",
"<",
"?",
">",
"c",
",",
"String",
"id",
",",
"TagList",
"tags",
")",
"{",
"final",
"MonitorConfig",
".",
"Builder",
"builder",
"=",
"MonitorConfig",
".",
"builder",
"(",
"id",
")",
";"... | Creates a monitor config for a composite object. | [
"Creates",
"a",
"monitor",
"config",
"for",
"a",
"composite",
"object",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L394-L405 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.newConfig | private static MonitorConfig newConfig(
Class<?> c,
String defaultName,
String id,
com.netflix.servo.annotations.Monitor anno,
TagList tags) {
String name = anno.name();
if (name.isEmpty()) {
name = defaultName;
}
MonitorConfig.Builder builder = MonitorConfig.builder(name);
builder.withTag("class", className(c));
builder.withTag(anno.type());
builder.withTag(anno.level());
if (tags != null) {
builder.withTags(tags);
}
if (id != null) {
builder.withTag("id", id);
}
return builder.build();
} | java | private static MonitorConfig newConfig(
Class<?> c,
String defaultName,
String id,
com.netflix.servo.annotations.Monitor anno,
TagList tags) {
String name = anno.name();
if (name.isEmpty()) {
name = defaultName;
}
MonitorConfig.Builder builder = MonitorConfig.builder(name);
builder.withTag("class", className(c));
builder.withTag(anno.type());
builder.withTag(anno.level());
if (tags != null) {
builder.withTags(tags);
}
if (id != null) {
builder.withTag("id", id);
}
return builder.build();
} | [
"private",
"static",
"MonitorConfig",
"newConfig",
"(",
"Class",
"<",
"?",
">",
"c",
",",
"String",
"defaultName",
",",
"String",
"id",
",",
"com",
".",
"netflix",
".",
"servo",
".",
"annotations",
".",
"Monitor",
"anno",
",",
"TagList",
"tags",
")",
"{"... | Creates a monitor config based on an annotation. | [
"Creates",
"a",
"monitor",
"config",
"based",
"on",
"an",
"annotation",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L416-L437 | train |
Netflix/servo | servo-graphite/src/main/java/com/netflix/servo/publish/graphite/GraphiteMetricObserver.java | GraphiteMetricObserver.stop | public void stop() {
try {
if (socket != null) {
socket.close();
socket = null;
LOGGER.info("Disconnected from graphite server: {}", graphiteServerURI);
}
} catch (IOException e) {
LOGGER.warn("Error Stopping", e);
}
} | java | public void stop() {
try {
if (socket != null) {
socket.close();
socket = null;
LOGGER.info("Disconnected from graphite server: {}", graphiteServerURI);
}
} catch (IOException e) {
LOGGER.warn("Error Stopping", e);
}
} | [
"public",
"void",
"stop",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"socket",
"!=",
"null",
")",
"{",
"socket",
".",
"close",
"(",
")",
";",
"socket",
"=",
"null",
";",
"LOGGER",
".",
"info",
"(",
"\"Disconnected from graphite server: {}\"",
",",
"graphiteSe... | Stop sending metrics to the graphite server. | [
"Stop",
"sending",
"metrics",
"to",
"the",
"graphite",
"server",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-graphite/src/main/java/com/netflix/servo/publish/graphite/GraphiteMetricObserver.java#L88-L98 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/tag/SmallTagMap.java | SmallTagMap.get | public Tag get(String key) {
int idx = binarySearch(tagArray, key);
if (idx < 0) {
return null;
} else {
return tagArray[idx];
}
} | java | public Tag get(String key) {
int idx = binarySearch(tagArray, key);
if (idx < 0) {
return null;
} else {
return tagArray[idx];
}
} | [
"public",
"Tag",
"get",
"(",
"String",
"key",
")",
"{",
"int",
"idx",
"=",
"binarySearch",
"(",
"tagArray",
",",
"key",
")",
";",
"if",
"(",
"idx",
"<",
"0",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"return",
"tagArray",
"[",
"idx",
"]"... | Get the tag associated with a given key. | [
"Get",
"the",
"tag",
"associated",
"with",
"a",
"given",
"key",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/tag/SmallTagMap.java#L239-L246 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/stats/StatsBuffer.java | StatsBuffer.record | public void record(long n) {
values[Integer.remainderUnsigned(pos++, size)] = n;
if (curSize < size) {
++curSize;
}
} | java | public void record(long n) {
values[Integer.remainderUnsigned(pos++, size)] = n;
if (curSize < size) {
++curSize;
}
} | [
"public",
"void",
"record",
"(",
"long",
"n",
")",
"{",
"values",
"[",
"Integer",
".",
"remainderUnsigned",
"(",
"pos",
"++",
",",
"size",
")",
"]",
"=",
"n",
";",
"if",
"(",
"curSize",
"<",
"size",
")",
"{",
"++",
"curSize",
";",
"}",
"}"
] | Record a new value for this buffer. | [
"Record",
"a",
"new",
"value",
"for",
"this",
"buffer",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/stats/StatsBuffer.java#L95-L100 | train |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/stats/StatsBuffer.java | StatsBuffer.computeStats | public void computeStats() {
if (statsComputed.getAndSet(true)) {
return;
}
if (curSize == 0) {
return;
}
Arrays.sort(values, 0, curSize); // to compute percentileValues
min = values[0];
max = values[curSize - 1];
total = 0L;
double sumSquares = 0.0;
for (int i = 0; i < curSize; ++i) {
total += values[i];
sumSquares += values[i] * values[i];
}
mean = (double) total / curSize;
if (curSize == 1) {
variance = 0d;
} else {
variance = (sumSquares - ((double) total * total / curSize)) / (curSize - 1);
}
stddev = Math.sqrt(variance);
computePercentiles(curSize);
} | java | public void computeStats() {
if (statsComputed.getAndSet(true)) {
return;
}
if (curSize == 0) {
return;
}
Arrays.sort(values, 0, curSize); // to compute percentileValues
min = values[0];
max = values[curSize - 1];
total = 0L;
double sumSquares = 0.0;
for (int i = 0; i < curSize; ++i) {
total += values[i];
sumSquares += values[i] * values[i];
}
mean = (double) total / curSize;
if (curSize == 1) {
variance = 0d;
} else {
variance = (sumSquares - ((double) total * total / curSize)) / (curSize - 1);
}
stddev = Math.sqrt(variance);
computePercentiles(curSize);
} | [
"public",
"void",
"computeStats",
"(",
")",
"{",
"if",
"(",
"statsComputed",
".",
"getAndSet",
"(",
"true",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"curSize",
"==",
"0",
")",
"{",
"return",
";",
"}",
"Arrays",
".",
"sort",
"(",
"values",
",",... | Compute stats for the current set of values. | [
"Compute",
"stats",
"for",
"the",
"current",
"set",
"of",
"values",
"."
] | d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815 | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/stats/StatsBuffer.java#L105-L133 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.