repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 218 | func_name stringlengths 5 140 | whole_func_string stringlengths 79 3.99k | language stringclasses 1
value | func_code_string stringlengths 79 3.99k | func_code_tokens listlengths 20 624 | func_documentation_string stringlengths 61 1.96k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 107 339 |
|---|---|---|---|---|---|---|---|---|---|---|
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/util/CmsDomUtil.java | CmsDomUtil.internalHasClass | private static boolean internalHasClass(String className, Element element) {
boolean hasClass = false;
try {
String elementClass = element.getClassName().trim();
hasClass = elementClass.equals(className);
hasClass |= elementClass.contains(" " + className + " ");
hasClass |= elementClass.startsWith(className + " ");
hasClass |= elementClass.endsWith(" " + className);
} catch (Throwable t) {
// ignore
}
return hasClass;
} | java | private static boolean internalHasClass(String className, Element element) {
boolean hasClass = false;
try {
String elementClass = element.getClassName().trim();
hasClass = elementClass.equals(className);
hasClass |= elementClass.contains(" " + className + " ");
hasClass |= elementClass.startsWith(className + " ");
hasClass |= elementClass.endsWith(" " + className);
} catch (Throwable t) {
// ignore
}
return hasClass;
} | [
"private",
"static",
"boolean",
"internalHasClass",
"(",
"String",
"className",
",",
"Element",
"element",
")",
"{",
"boolean",
"hasClass",
"=",
"false",
";",
"try",
"{",
"String",
"elementClass",
"=",
"element",
".",
"getClassName",
"(",
")",
".",
"trim",
"... | Internal method to indicate if the given element has a CSS class.<p>
@param className the class name to look for
@param element the element
@return <code>true</code> if the element has the given CSS class | [
"Internal",
"method",
"to",
"indicate",
"if",
"the",
"given",
"element",
"has",
"a",
"CSS",
"class",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsDomUtil.java#L2167-L2180 |
square/flow | flow/src/main/java/flow/Flow.java | Flow.setHistory | public void setHistory(@NonNull final History history, @NonNull final Direction direction) {
move(new PendingTraversal() {
@Override void doExecute() {
dispatch(preserveEquivalentPrefix(getHistory(), history), direction);
}
});
} | java | public void setHistory(@NonNull final History history, @NonNull final Direction direction) {
move(new PendingTraversal() {
@Override void doExecute() {
dispatch(preserveEquivalentPrefix(getHistory(), history), direction);
}
});
} | [
"public",
"void",
"setHistory",
"(",
"@",
"NonNull",
"final",
"History",
"history",
",",
"@",
"NonNull",
"final",
"Direction",
"direction",
")",
"{",
"move",
"(",
"new",
"PendingTraversal",
"(",
")",
"{",
"@",
"Override",
"void",
"doExecute",
"(",
")",
"{"... | Replaces the history with the one given and dispatches in the given direction. | [
"Replaces",
"the",
"history",
"with",
"the",
"one",
"given",
"and",
"dispatches",
"in",
"the",
"given",
"direction",
"."
] | train | https://github.com/square/flow/blob/1656288d1cb4a92dfbcff8276f4d7f9e3390419b/flow/src/main/java/flow/Flow.java#L197-L203 |
j256/ormlite-core | src/main/java/com/j256/ormlite/table/TableUtils.java | TableUtils.createTableIfNotExists | public static <T> int createTableIfNotExists(ConnectionSource connectionSource, Class<T> dataClass)
throws SQLException {
Dao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass);
return doCreateTable(dao, true);
} | java | public static <T> int createTableIfNotExists(ConnectionSource connectionSource, Class<T> dataClass)
throws SQLException {
Dao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass);
return doCreateTable(dao, true);
} | [
"public",
"static",
"<",
"T",
">",
"int",
"createTableIfNotExists",
"(",
"ConnectionSource",
"connectionSource",
",",
"Class",
"<",
"T",
">",
"dataClass",
")",
"throws",
"SQLException",
"{",
"Dao",
"<",
"T",
",",
"?",
">",
"dao",
"=",
"DaoManager",
".",
"c... | Create a table if it does not already exist. This is not supported by all databases. | [
"Create",
"a",
"table",
"if",
"it",
"does",
"not",
"already",
"exist",
".",
"This",
"is",
"not",
"supported",
"by",
"all",
"databases",
"."
] | train | https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/table/TableUtils.java#L72-L76 |
ribot/easy-adapter | library/src/main/java/uk/co/ribot/easyadapter/annotations/FieldAnnotationParser.java | FieldAnnotationParser.setViewFields | public static void setViewFields(final Object object, final Activity activity) {
setViewFields(object, new ViewFinder() {
@Override
public View findViewById(int viewId) {
return activity.findViewById(viewId);
}
});
} | java | public static void setViewFields(final Object object, final Activity activity) {
setViewFields(object, new ViewFinder() {
@Override
public View findViewById(int viewId) {
return activity.findViewById(viewId);
}
});
} | [
"public",
"static",
"void",
"setViewFields",
"(",
"final",
"Object",
"object",
",",
"final",
"Activity",
"activity",
")",
"{",
"setViewFields",
"(",
"object",
",",
"new",
"ViewFinder",
"(",
")",
"{",
"@",
"Override",
"public",
"View",
"findViewById",
"(",
"i... | Parse {@link ViewId} annotation and try to assign the view with that id to the annotated field.
It will throw a {@link ClassCastException} if the field and the view with the given ID have different types.
@param object object where the annotation is.
@param activity activity that contains a view with the viewId given in the annotation. | [
"Parse",
"{",
"@link",
"ViewId",
"}",
"annotation",
"and",
"try",
"to",
"assign",
"the",
"view",
"with",
"that",
"id",
"to",
"the",
"annotated",
"field",
".",
"It",
"will",
"throw",
"a",
"{",
"@link",
"ClassCastException",
"}",
"if",
"the",
"field",
"and... | train | https://github.com/ribot/easy-adapter/blob/8cf85023a79c781aa2013e9dc39fd66734fb2019/library/src/main/java/uk/co/ribot/easyadapter/annotations/FieldAnnotationParser.java#L49-L56 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/olap/OLAPService.java | OLAPService.deleteShard | public void deleteShard(ApplicationDefinition appDef, String shard) {
checkServiceState();
m_olap.deleteShard(appDef, shard);
} | java | public void deleteShard(ApplicationDefinition appDef, String shard) {
checkServiceState();
m_olap.deleteShard(appDef, shard);
} | [
"public",
"void",
"deleteShard",
"(",
"ApplicationDefinition",
"appDef",
",",
"String",
"shard",
")",
"{",
"checkServiceState",
"(",
")",
";",
"m_olap",
".",
"deleteShard",
"(",
"appDef",
",",
"shard",
")",
";",
"}"
] | Delete the shard for the given application, including all of its data. This method
is a no-op if the given shard does not exist or has no data.
@param appDef {@link ApplicationDefinition} of application.
@param shard Shard name. | [
"Delete",
"the",
"shard",
"for",
"the",
"given",
"application",
"including",
"all",
"of",
"its",
"data",
".",
"This",
"method",
"is",
"a",
"no",
"-",
"op",
"if",
"the",
"given",
"shard",
"does",
"not",
"exist",
"or",
"has",
"no",
"data",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/olap/OLAPService.java#L249-L252 |
wdullaer/MaterialDateTimePicker | library/src/main/java/com/wdullaer/materialdatetimepicker/time/RadialPickerLayout.java | RadialPickerLayout.reselectSelector | private void reselectSelector(Timepoint newSelection, boolean forceDrawDot, int index) {
switch(index) {
case HOUR_INDEX:
// The selection might have changed, recalculate the degrees and innerCircle values
int hour = newSelection.getHour();
boolean isInnerCircle = isHourInnerCircle(hour);
int degrees = (hour%12)*360/12;
if(!mIs24HourMode) hour = hour%12;
if(!mIs24HourMode && hour == 0) hour += 12;
mHourRadialSelectorView.setSelection(degrees, isInnerCircle, forceDrawDot);
mHourRadialTextsView.setSelection(hour);
// If we rounded the minutes, reposition the minuteSelector too.
if(newSelection.getMinute() != mCurrentTime.getMinute()) {
int minDegrees = newSelection.getMinute() * (360 / 60);
mMinuteRadialSelectorView.setSelection(minDegrees, isInnerCircle, forceDrawDot);
mMinuteRadialTextsView.setSelection(newSelection.getMinute());
}
// If we rounded the seconds, reposition the secondSelector too.
if(newSelection.getSecond() != mCurrentTime.getSecond()) {
int secDegrees = newSelection.getSecond() * (360 / 60);
mSecondRadialSelectorView.setSelection(secDegrees, isInnerCircle, forceDrawDot);
mSecondRadialTextsView.setSelection(newSelection.getSecond());
}
break;
case MINUTE_INDEX:
// The selection might have changed, recalculate the degrees
degrees = newSelection.getMinute() * (360 / 60);
mMinuteRadialSelectorView.setSelection(degrees, false, forceDrawDot);
mMinuteRadialTextsView.setSelection(newSelection.getMinute());
// If we rounded the seconds, reposition the secondSelector too.
if(newSelection.getSecond() != mCurrentTime.getSecond()) {
int secDegrees = newSelection.getSecond()* (360 / 60);
mSecondRadialSelectorView.setSelection(secDegrees, false, forceDrawDot);
mSecondRadialTextsView.setSelection(newSelection.getSecond());
}
break;
case SECOND_INDEX:
// The selection might have changed, recalculate the degrees
degrees = newSelection.getSecond() * (360 / 60);
mSecondRadialSelectorView.setSelection(degrees, false, forceDrawDot);
mSecondRadialTextsView.setSelection(newSelection.getSecond());
}
// Invalidate the currently showing picker to force a redraw
switch(getCurrentItemShowing()) {
case HOUR_INDEX:
mHourRadialSelectorView.invalidate();
mHourRadialTextsView.invalidate();
break;
case MINUTE_INDEX:
mMinuteRadialSelectorView.invalidate();
mMinuteRadialTextsView.invalidate();
break;
case SECOND_INDEX:
mSecondRadialSelectorView.invalidate();
mSecondRadialTextsView.invalidate();
}
} | java | private void reselectSelector(Timepoint newSelection, boolean forceDrawDot, int index) {
switch(index) {
case HOUR_INDEX:
// The selection might have changed, recalculate the degrees and innerCircle values
int hour = newSelection.getHour();
boolean isInnerCircle = isHourInnerCircle(hour);
int degrees = (hour%12)*360/12;
if(!mIs24HourMode) hour = hour%12;
if(!mIs24HourMode && hour == 0) hour += 12;
mHourRadialSelectorView.setSelection(degrees, isInnerCircle, forceDrawDot);
mHourRadialTextsView.setSelection(hour);
// If we rounded the minutes, reposition the minuteSelector too.
if(newSelection.getMinute() != mCurrentTime.getMinute()) {
int minDegrees = newSelection.getMinute() * (360 / 60);
mMinuteRadialSelectorView.setSelection(minDegrees, isInnerCircle, forceDrawDot);
mMinuteRadialTextsView.setSelection(newSelection.getMinute());
}
// If we rounded the seconds, reposition the secondSelector too.
if(newSelection.getSecond() != mCurrentTime.getSecond()) {
int secDegrees = newSelection.getSecond() * (360 / 60);
mSecondRadialSelectorView.setSelection(secDegrees, isInnerCircle, forceDrawDot);
mSecondRadialTextsView.setSelection(newSelection.getSecond());
}
break;
case MINUTE_INDEX:
// The selection might have changed, recalculate the degrees
degrees = newSelection.getMinute() * (360 / 60);
mMinuteRadialSelectorView.setSelection(degrees, false, forceDrawDot);
mMinuteRadialTextsView.setSelection(newSelection.getMinute());
// If we rounded the seconds, reposition the secondSelector too.
if(newSelection.getSecond() != mCurrentTime.getSecond()) {
int secDegrees = newSelection.getSecond()* (360 / 60);
mSecondRadialSelectorView.setSelection(secDegrees, false, forceDrawDot);
mSecondRadialTextsView.setSelection(newSelection.getSecond());
}
break;
case SECOND_INDEX:
// The selection might have changed, recalculate the degrees
degrees = newSelection.getSecond() * (360 / 60);
mSecondRadialSelectorView.setSelection(degrees, false, forceDrawDot);
mSecondRadialTextsView.setSelection(newSelection.getSecond());
}
// Invalidate the currently showing picker to force a redraw
switch(getCurrentItemShowing()) {
case HOUR_INDEX:
mHourRadialSelectorView.invalidate();
mHourRadialTextsView.invalidate();
break;
case MINUTE_INDEX:
mMinuteRadialSelectorView.invalidate();
mMinuteRadialTextsView.invalidate();
break;
case SECOND_INDEX:
mSecondRadialSelectorView.invalidate();
mSecondRadialTextsView.invalidate();
}
} | [
"private",
"void",
"reselectSelector",
"(",
"Timepoint",
"newSelection",
",",
"boolean",
"forceDrawDot",
",",
"int",
"index",
")",
"{",
"switch",
"(",
"index",
")",
"{",
"case",
"HOUR_INDEX",
":",
"// The selection might have changed, recalculate the degrees and innerCirc... | For the currently showing view (either hours, minutes or seconds), re-calculate the position
for the selector, and redraw it at that position. The text representing the currently
selected value will be redrawn if required.
@param newSelection Timpoint - Time which should be selected.
@param forceDrawDot The dot in the circle will generally only be shown when the selection
@param index The picker to use as a reference. Will be getCurrentItemShow() except when AM/PM is changed
is on non-visible values, but use this to force the dot to be shown. | [
"For",
"the",
"currently",
"showing",
"view",
"(",
"either",
"hours",
"minutes",
"or",
"seconds",
")",
"re",
"-",
"calculate",
"the",
"position",
"for",
"the",
"selector",
"and",
"redraw",
"it",
"at",
"that",
"position",
".",
"The",
"text",
"representing",
... | train | https://github.com/wdullaer/MaterialDateTimePicker/blob/0a8fe28f19db4f5a5a6cfc525a852416232873a8/library/src/main/java/com/wdullaer/materialdatetimepicker/time/RadialPickerLayout.java#L458-L517 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/admin/v2/models/ModifyColumnFamiliesRequest.java | ModifyColumnFamiliesRequest.addFamily | public ModifyColumnFamiliesRequest addFamily(String familyId, GCRule gcRule) {
Preconditions.checkNotNull(gcRule);
Modification.Builder modification = Modification.newBuilder().setId(familyId);
modification.getCreateBuilder().setGcRule(gcRule.toProto());
modFamilyRequest.addModifications(modification.build());
return this;
} | java | public ModifyColumnFamiliesRequest addFamily(String familyId, GCRule gcRule) {
Preconditions.checkNotNull(gcRule);
Modification.Builder modification = Modification.newBuilder().setId(familyId);
modification.getCreateBuilder().setGcRule(gcRule.toProto());
modFamilyRequest.addModifications(modification.build());
return this;
} | [
"public",
"ModifyColumnFamiliesRequest",
"addFamily",
"(",
"String",
"familyId",
",",
"GCRule",
"gcRule",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"gcRule",
")",
";",
"Modification",
".",
"Builder",
"modification",
"=",
"Modification",
".",
"newBuilder",... | Configures the name and GcRule of the new ColumnFamily to be created
@param familyId
@param gcRule
@return | [
"Configures",
"the",
"name",
"and",
"GcRule",
"of",
"the",
"new",
"ColumnFamily",
"to",
"be",
"created"
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/admin/v2/models/ModifyColumnFamiliesRequest.java#L72-L78 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ColumnLayoutExample.java | ColumnLayoutExample.addResponsiveExample | private void addResponsiveExample() {
add(new WHeading(HeadingLevel.H2, "Default responsive design"));
add(new ExplanatoryText("This example applies the theme's default responsive design rules for ColumnLayout.\n "
+ "The columns have width and alignment and there is also a hgap and a vgap."));
WPanel panel = new WPanel();
panel.setLayout(new ColumnLayout(new int[]{33, 33, 33},
new Alignment[]{Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT}, 12, 18));
panel.setHtmlClass(HtmlClassProperties.RESPOND);
add(panel);
panel.add(new BoxComponent("Left"));
panel.add(new BoxComponent("Center"));
panel.add(new BoxComponent("Right"));
panel.add(new BoxComponent("Left"));
panel.add(new BoxComponent("Center"));
panel.add(new BoxComponent("Right"));
} | java | private void addResponsiveExample() {
add(new WHeading(HeadingLevel.H2, "Default responsive design"));
add(new ExplanatoryText("This example applies the theme's default responsive design rules for ColumnLayout.\n "
+ "The columns have width and alignment and there is also a hgap and a vgap."));
WPanel panel = new WPanel();
panel.setLayout(new ColumnLayout(new int[]{33, 33, 33},
new Alignment[]{Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT}, 12, 18));
panel.setHtmlClass(HtmlClassProperties.RESPOND);
add(panel);
panel.add(new BoxComponent("Left"));
panel.add(new BoxComponent("Center"));
panel.add(new BoxComponent("Right"));
panel.add(new BoxComponent("Left"));
panel.add(new BoxComponent("Center"));
panel.add(new BoxComponent("Right"));
} | [
"private",
"void",
"addResponsiveExample",
"(",
")",
"{",
"add",
"(",
"new",
"WHeading",
"(",
"HeadingLevel",
".",
"H2",
",",
"\"Default responsive design\"",
")",
")",
";",
"add",
"(",
"new",
"ExplanatoryText",
"(",
"\"This example applies the theme's default respons... | Add a column layout which will change its rendering on small screens. | [
"Add",
"a",
"column",
"layout",
"which",
"will",
"change",
"its",
"rendering",
"on",
"small",
"screens",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ColumnLayoutExample.java#L72-L87 |
unbescape/unbescape | src/main/java/org/unbescape/properties/PropertiesEscape.java | PropertiesEscape.escapePropertiesKeyMinimal | public static void escapePropertiesKeyMinimal(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
escapePropertiesKey(text, offset, len, writer, PropertiesKeyEscapeLevel.LEVEL_1_BASIC_ESCAPE_SET);
} | java | public static void escapePropertiesKeyMinimal(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
escapePropertiesKey(text, offset, len, writer, PropertiesKeyEscapeLevel.LEVEL_1_BASIC_ESCAPE_SET);
} | [
"public",
"static",
"void",
"escapePropertiesKeyMinimal",
"(",
"final",
"char",
"[",
"]",
"text",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"len",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"escapePropertiesKey",
"(",
"text"... | <p>
Perform a Java Properties Key level 1 (only basic set) <strong>escape</strong> operation
on a <tt>char[]</tt> input.
</p>
<p>
<em>Level 1</em> means this method will only escape the Java Properties Key basic escape set:
</p>
<ul>
<li>The <em>Single Escape Characters</em>:
<tt>\t</tt> (<tt>U+0009</tt>),
<tt>\n</tt> (<tt>U+000A</tt>),
<tt>\f</tt> (<tt>U+000C</tt>),
<tt>\r</tt> (<tt>U+000D</tt>),
<tt>\ </tt> (<tt>U+0020</tt>),
<tt>\:</tt> (<tt>U+003A</tt>),
<tt>\=</tt> (<tt>U+003D</tt>) and
<tt>\\</tt> (<tt>U+005C</tt>).
</li>
<li>
Two ranges of non-displayable, control characters (some of which are already part of the
<em>single escape characters</em> list): <tt>U+0000</tt> to <tt>U+001F</tt>
and <tt>U+007F</tt> to <tt>U+009F</tt>.
</li>
</ul>
<p>
This method calls {@link #escapePropertiesKey(char[], int, int, java.io.Writer, PropertiesKeyEscapeLevel)}
with the following preconfigured values:
</p>
<ul>
<li><tt>level</tt>:
{@link PropertiesKeyEscapeLevel#LEVEL_1_BASIC_ESCAPE_SET}</li>
</ul>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>char[]</tt> to be escaped.
@param offset the position in <tt>text</tt> at which the escape operation should start.
@param len the number of characters in <tt>text</tt> that should be escaped.
@param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs | [
"<p",
">",
"Perform",
"a",
"Java",
"Properties",
"Key",
"level",
"1",
"(",
"only",
"basic",
"set",
")",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"char",
"[]",
"<",
"/",
"tt",
">",
"input",
".",
"<",
"/",
... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/properties/PropertiesEscape.java#L1230-L1233 |
diffplug/durian | src/com/diffplug/common/base/TreeComparison.java | TreeComparison.isEqualMappedBy | public boolean isEqualMappedBy(Function<? super E, ?> expectedMapper, Function<? super A, ?> actualMapper) {
return isEqualBasedOn((expected, actual) -> {
return Objects.equals(expectedMapper.apply(expected), actualMapper.apply(actual));
});
} | java | public boolean isEqualMappedBy(Function<? super E, ?> expectedMapper, Function<? super A, ?> actualMapper) {
return isEqualBasedOn((expected, actual) -> {
return Objects.equals(expectedMapper.apply(expected), actualMapper.apply(actual));
});
} | [
"public",
"boolean",
"isEqualMappedBy",
"(",
"Function",
"<",
"?",
"super",
"E",
",",
"?",
">",
"expectedMapper",
",",
"Function",
"<",
"?",
"super",
"A",
",",
"?",
">",
"actualMapper",
")",
"{",
"return",
"isEqualBasedOn",
"(",
"(",
"expected",
",",
"ac... | Returns true if the two trees are equal, by calling {@link Objects#equals(Object, Object)} on the results of both mappers. | [
"Returns",
"true",
"if",
"the",
"two",
"trees",
"are",
"equal",
"by",
"calling",
"{"
] | train | https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/TreeComparison.java#L45-L49 |
finmath/finmath-lib | src/main/java6/net/finmath/marketdata/model/curves/DiscountCurveNelsonSiegelSvensson.java | DiscountCurveNelsonSiegelSvensson.getDiscountFactor | @Override
public double getDiscountFactor(AnalyticModelInterface model, double maturity)
{
// Change time scale
maturity *= timeScaling;
double beta1 = parameter[0];
double beta2 = parameter[1];
double beta3 = parameter[2];
double beta4 = parameter[3];
double tau1 = parameter[4];
double tau2 = parameter[5];
double x1 = tau1 > 0 ? FastMath.exp(-maturity/tau1) : 0.0;
double x2 = tau2 > 0 ? FastMath.exp(-maturity/tau2) : 0.0;
double y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0-x1)/maturity*tau1 : 1.0) : 0.0;
double y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0-x2)/maturity*tau2 : 1.0) : 0.0;
double zeroRate = beta1 + beta2 * y1 + beta3 * (y1-x1) + beta4 * (y2-x2);
return Math.exp(- zeroRate * maturity);
} | java | @Override
public double getDiscountFactor(AnalyticModelInterface model, double maturity)
{
// Change time scale
maturity *= timeScaling;
double beta1 = parameter[0];
double beta2 = parameter[1];
double beta3 = parameter[2];
double beta4 = parameter[3];
double tau1 = parameter[4];
double tau2 = parameter[5];
double x1 = tau1 > 0 ? FastMath.exp(-maturity/tau1) : 0.0;
double x2 = tau2 > 0 ? FastMath.exp(-maturity/tau2) : 0.0;
double y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0-x1)/maturity*tau1 : 1.0) : 0.0;
double y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0-x2)/maturity*tau2 : 1.0) : 0.0;
double zeroRate = beta1 + beta2 * y1 + beta3 * (y1-x1) + beta4 * (y2-x2);
return Math.exp(- zeroRate * maturity);
} | [
"@",
"Override",
"public",
"double",
"getDiscountFactor",
"(",
"AnalyticModelInterface",
"model",
",",
"double",
"maturity",
")",
"{",
"// Change time scale",
"maturity",
"*=",
"timeScaling",
";",
"double",
"beta1",
"=",
"parameter",
"[",
"0",
"]",
";",
"double",
... | Return the discount factor within a given model context for a given maturity.
@param model The model used as a context (not required for this class).
@param maturity The maturity in terms of ACT/365 daycount form this curve reference date. Note that this parameter might get rescaled to a different time parameter.
@see net.finmath.marketdata.model.curves.DiscountCurveInterface#getDiscountFactor(net.finmath.marketdata.model.AnalyticModelInterface, double) | [
"Return",
"the",
"discount",
"factor",
"within",
"a",
"given",
"model",
"context",
"for",
"a",
"given",
"maturity",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/model/curves/DiscountCurveNelsonSiegelSvensson.java#L71-L93 |
CloudSlang/cs-actions | cs-commons/src/main/java/io/cloudslang/content/utils/BooleanUtilities.java | BooleanUtilities.toBoolean | public static boolean toBoolean(@Nullable final String booleanStr, final boolean defaultValue) {
return StringUtils.isNoneEmpty(booleanStr) ? toBoolean(booleanStr) : defaultValue;
} | java | public static boolean toBoolean(@Nullable final String booleanStr, final boolean defaultValue) {
return StringUtils.isNoneEmpty(booleanStr) ? toBoolean(booleanStr) : defaultValue;
} | [
"public",
"static",
"boolean",
"toBoolean",
"(",
"@",
"Nullable",
"final",
"String",
"booleanStr",
",",
"final",
"boolean",
"defaultValue",
")",
"{",
"return",
"StringUtils",
".",
"isNoneEmpty",
"(",
"booleanStr",
")",
"?",
"toBoolean",
"(",
"booleanStr",
")",
... | If the string is null or empty string, it returns the defaultValue otherwise it returns the boolean value (see tooBoolean)
@param booleanStr the string to convert to boolean
@param defaultValue the default value if the string is empty or null
@return true if the booleanStr is 'true', false if it's 'false'
@throws IllegalArgumentException if the booleanStr is not a valid boolean | [
"If",
"the",
"string",
"is",
"null",
"or",
"empty",
"string",
"it",
"returns",
"the",
"defaultValue",
"otherwise",
"it",
"returns",
"the",
"boolean",
"value",
"(",
"see",
"tooBoolean",
")"
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/BooleanUtilities.java#L83-L85 |
alkacon/opencms-core | src/org/opencms/file/CmsResource.java | CmsResource.getPathPart | public static String getPathPart(String resource, int level) {
resource = getFolderPath(resource);
String result = null;
int pos = 0, count = 0;
if (level >= 0) {
// Walk down from the root folder /
while ((count < level) && (pos > -1)) {
count++;
pos = resource.indexOf('/', pos + 1);
}
} else {
// Walk up from the current folder
pos = resource.length();
while ((count > level) && (pos > -1)) {
count--;
pos = resource.lastIndexOf('/', pos - 1);
}
}
if (pos > -1) {
// To many levels walked
result = resource.substring(0, pos + 1);
} else {
// Add trailing slash
result = (level < 0) ? "/" : resource;
}
return result;
} | java | public static String getPathPart(String resource, int level) {
resource = getFolderPath(resource);
String result = null;
int pos = 0, count = 0;
if (level >= 0) {
// Walk down from the root folder /
while ((count < level) && (pos > -1)) {
count++;
pos = resource.indexOf('/', pos + 1);
}
} else {
// Walk up from the current folder
pos = resource.length();
while ((count > level) && (pos > -1)) {
count--;
pos = resource.lastIndexOf('/', pos - 1);
}
}
if (pos > -1) {
// To many levels walked
result = resource.substring(0, pos + 1);
} else {
// Add trailing slash
result = (level < 0) ? "/" : resource;
}
return result;
} | [
"public",
"static",
"String",
"getPathPart",
"(",
"String",
"resource",
",",
"int",
"level",
")",
"{",
"resource",
"=",
"getFolderPath",
"(",
"resource",
")",
";",
"String",
"result",
"=",
"null",
";",
"int",
"pos",
"=",
"0",
",",
"count",
"=",
"0",
";... | Returns the name of a parent folder of the given resource,
that is either minus levels up
from the current folder, or that is plus levels down from the
root folder.<p>
@param resource the name of a resource
@param level of levels to walk up or down
@return the name of a parent folder of the given resource | [
"Returns",
"the",
"name",
"of",
"a",
"parent",
"folder",
"of",
"the",
"given",
"resource",
"that",
"is",
"either",
"minus",
"levels",
"up",
"from",
"the",
"current",
"folder",
"or",
"that",
"is",
"plus",
"levels",
"down",
"from",
"the",
"root",
"folder",
... | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsResource.java#L700-L727 |
lionsoul2014/jcseg | jcseg-core/src/main/java/org/lionsoul/jcseg/util/StringUtil.java | StringUtil.isCJK | public static boolean isCJK(String str, int beginIndex, int endIndex)
{
for ( int j = beginIndex; j < endIndex; j++ ) {
if ( ! isCJKChar(str.charAt(j)) ) {
return false;
}
}
return true;
} | java | public static boolean isCJK(String str, int beginIndex, int endIndex)
{
for ( int j = beginIndex; j < endIndex; j++ ) {
if ( ! isCJKChar(str.charAt(j)) ) {
return false;
}
}
return true;
} | [
"public",
"static",
"boolean",
"isCJK",
"(",
"String",
"str",
",",
"int",
"beginIndex",
",",
"int",
"endIndex",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"beginIndex",
";",
"j",
"<",
"endIndex",
";",
"j",
"++",
")",
"{",
"if",
"(",
"!",
"isCJKChar",
"... | check if the specified string is all CJK chars
@param str
@param beginIndex
@param endIndex
@return boolean | [
"check",
"if",
"the",
"specified",
"string",
"is",
"all",
"CJK",
"chars"
] | train | https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/util/StringUtil.java#L353-L362 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/os/BundleUtils.java | BundleUtils.optSerializable | @Nullable
@SuppressWarnings("unchecked") // Bundle#getSerializable(String) returns Serializable object so it is safe to cast to a type which extends Serializable.
public static <T extends Serializable> T optSerializable(@Nullable Bundle bundle, @Nullable String key) {
return optSerializable(bundle, key, null);
} | java | @Nullable
@SuppressWarnings("unchecked") // Bundle#getSerializable(String) returns Serializable object so it is safe to cast to a type which extends Serializable.
public static <T extends Serializable> T optSerializable(@Nullable Bundle bundle, @Nullable String key) {
return optSerializable(bundle, key, null);
} | [
"@",
"Nullable",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"// Bundle#getSerializable(String) returns Serializable object so it is safe to cast to a type which extends Serializable.",
"public",
"static",
"<",
"T",
"extends",
"Serializable",
">",
"T",
"optSerializable",
"(... | Returns a optional {@link java.io.Serializable}. In other words, returns the value mapped by key if it exists and is a {@link java.io.Serializable}.
The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null.
@param bundle a bundle. If the bundle is null, this method will return null.
@param key a key for the value.
@return a {@link java.io.Serializable} {@link java.util.ArrayList} value if exists, null otherwise.
@see android.os.Bundle#getSerializable(String) | [
"Returns",
"a",
"optional",
"{"
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L781-L785 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/MfpDiagnostics.java | MfpDiagnostics.dumpJmfSlices | private void dumpJmfSlices(IncidentStream is, List<DataSlice> slices) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "dumpJmfSlices");
if (slices != null) {
try {
is.writeLine("JMF data slices", SibTr.formatSlices(slices, getDiagnosticDataLimitInt()));
}
catch (Exception e) {
// No FFDC code needed - we are FFDCing!
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "dumpJmfSlices failed: " + e);
}
}
else {
is.writeLine("No JMF DataSlices available", "");
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "dumpJmfSlices");
} | java | private void dumpJmfSlices(IncidentStream is, List<DataSlice> slices) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "dumpJmfSlices");
if (slices != null) {
try {
is.writeLine("JMF data slices", SibTr.formatSlices(slices, getDiagnosticDataLimitInt()));
}
catch (Exception e) {
// No FFDC code needed - we are FFDCing!
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "dumpJmfSlices failed: " + e);
}
}
else {
is.writeLine("No JMF DataSlices available", "");
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "dumpJmfSlices");
} | [
"private",
"void",
"dumpJmfSlices",
"(",
"IncidentStream",
"is",
",",
"List",
"<",
"DataSlice",
">",
"slices",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"ent... | user data - so we only dump at most the first 4K bytes of each slice. | [
"user",
"data",
"-",
"so",
"we",
"only",
"dump",
"at",
"most",
"the",
"first",
"4K",
"bytes",
"of",
"each",
"slice",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/MfpDiagnostics.java#L230-L247 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/db/entitymanager/operation/DbOperationManager.java | DbOperationManager.addSortedModifications | protected void addSortedModifications(List<DbOperation> flush) {
// calculate sorted set of all modified entity types
SortedSet<Class<?>> modifiedEntityTypes = new TreeSet<Class<?>>(MODIFICATION_TYPE_COMPARATOR);
modifiedEntityTypes.addAll(updates.keySet());
modifiedEntityTypes.addAll(deletes.keySet());
modifiedEntityTypes.addAll(bulkOperations.keySet());
for (Class<?> type : modifiedEntityTypes) {
// first perform entity UPDATES
addSortedModificationsForType(type, updates.get(type), flush);
// next perform entity DELETES
addSortedModificationsForType(type, deletes.get(type), flush);
// last perform bulk operations
SortedSet<DbBulkOperation> bulkOperationsForType = bulkOperations.get(type);
if(bulkOperationsForType != null) {
flush.addAll(bulkOperationsForType);
}
}
//the very last perform bulk operations for which the order is important
if(bulkOperationsInsertionOrder != null) {
flush.addAll(bulkOperationsInsertionOrder);
}
} | java | protected void addSortedModifications(List<DbOperation> flush) {
// calculate sorted set of all modified entity types
SortedSet<Class<?>> modifiedEntityTypes = new TreeSet<Class<?>>(MODIFICATION_TYPE_COMPARATOR);
modifiedEntityTypes.addAll(updates.keySet());
modifiedEntityTypes.addAll(deletes.keySet());
modifiedEntityTypes.addAll(bulkOperations.keySet());
for (Class<?> type : modifiedEntityTypes) {
// first perform entity UPDATES
addSortedModificationsForType(type, updates.get(type), flush);
// next perform entity DELETES
addSortedModificationsForType(type, deletes.get(type), flush);
// last perform bulk operations
SortedSet<DbBulkOperation> bulkOperationsForType = bulkOperations.get(type);
if(bulkOperationsForType != null) {
flush.addAll(bulkOperationsForType);
}
}
//the very last perform bulk operations for which the order is important
if(bulkOperationsInsertionOrder != null) {
flush.addAll(bulkOperationsInsertionOrder);
}
} | [
"protected",
"void",
"addSortedModifications",
"(",
"List",
"<",
"DbOperation",
">",
"flush",
")",
"{",
"// calculate sorted set of all modified entity types",
"SortedSet",
"<",
"Class",
"<",
"?",
">",
">",
"modifiedEntityTypes",
"=",
"new",
"TreeSet",
"<",
"Class",
... | Adds a correctly ordered list of UPDATE and DELETE operations to the flush.
@param flush | [
"Adds",
"a",
"correctly",
"ordered",
"list",
"of",
"UPDATE",
"and",
"DELETE",
"operations",
"to",
"the",
"flush",
"."
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/db/entitymanager/operation/DbOperationManager.java#L156-L180 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/AssertKripton.java | AssertKripton.assertTrueOrInvalidMethodSignException | public static void assertTrueOrInvalidMethodSignException(boolean expression, SQLiteModelMethod method,
String messageFormat, Object... args) {
if (!expression)
throw (new InvalidMethodSignException(method, String.format(messageFormat, args)));
} | java | public static void assertTrueOrInvalidMethodSignException(boolean expression, SQLiteModelMethod method,
String messageFormat, Object... args) {
if (!expression)
throw (new InvalidMethodSignException(method, String.format(messageFormat, args)));
} | [
"public",
"static",
"void",
"assertTrueOrInvalidMethodSignException",
"(",
"boolean",
"expression",
",",
"SQLiteModelMethod",
"method",
",",
"String",
"messageFormat",
",",
"Object",
"...",
"args",
")",
"{",
"if",
"(",
"!",
"expression",
")",
"throw",
"(",
"new",
... | Assert true or invalid method sign exception.
@param expression
the expression
@param method
the method
@param messageFormat
the message format
@param args
the args | [
"Assert",
"true",
"or",
"invalid",
"method",
"sign",
"exception",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/AssertKripton.java#L87-L91 |
apereo/cas | support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/util/OAuth20Utils.java | OAuth20Utils.produceErrorView | public static ModelAndView produceErrorView(final Exception e) {
return new ModelAndView(OAuth20Constants.ERROR_VIEW, CollectionUtils.wrap("rootCauseException", e));
} | java | public static ModelAndView produceErrorView(final Exception e) {
return new ModelAndView(OAuth20Constants.ERROR_VIEW, CollectionUtils.wrap("rootCauseException", e));
} | [
"public",
"static",
"ModelAndView",
"produceErrorView",
"(",
"final",
"Exception",
"e",
")",
"{",
"return",
"new",
"ModelAndView",
"(",
"OAuth20Constants",
".",
"ERROR_VIEW",
",",
"CollectionUtils",
".",
"wrap",
"(",
"\"rootCauseException\"",
",",
"e",
")",
")",
... | Produce error view model and view.
@param e the e
@return the model and view | [
"Produce",
"error",
"view",
"model",
"and",
"view",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/util/OAuth20Utils.java#L164-L166 |
spring-projects/spring-loaded | springloaded/src/main/java/org/springsource/loaded/ConstantPoolScanner.java | ConstantPoolScanner.accessUtf8 | private String accessUtf8(int cpIndex) {
Object object = cpdata[cpIndex];
if (object instanceof String) {
return (String) object;
}
int[] ptrAndLen = (int[]) object;
String value;
try {
value = new String(classbytes, ptrAndLen[0], ptrAndLen[1], "UTF8");
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Bad data found at constant pool position " + cpIndex + " offset="
+ ptrAndLen[0] + " length=" + ptrAndLen[1], e);
}
cpdata[cpIndex] = value;
return value;
} | java | private String accessUtf8(int cpIndex) {
Object object = cpdata[cpIndex];
if (object instanceof String) {
return (String) object;
}
int[] ptrAndLen = (int[]) object;
String value;
try {
value = new String(classbytes, ptrAndLen[0], ptrAndLen[1], "UTF8");
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Bad data found at constant pool position " + cpIndex + " offset="
+ ptrAndLen[0] + " length=" + ptrAndLen[1], e);
}
cpdata[cpIndex] = value;
return value;
} | [
"private",
"String",
"accessUtf8",
"(",
"int",
"cpIndex",
")",
"{",
"Object",
"object",
"=",
"cpdata",
"[",
"cpIndex",
"]",
";",
"if",
"(",
"object",
"instanceof",
"String",
")",
"{",
"return",
"(",
"String",
")",
"object",
";",
"}",
"int",
"[",
"]",
... | Return the UTF8 at the specified index in the constant pool. The data found at the constant pool for that index
may not have been unpacked yet if this is the first access of the string. If not unpacked the constant pool entry
is a pair of ints in an array representing the offset and length within the classbytes where the UTF8 string is
encoded. Once decoded the constant pool entry is flipped from an int array to a String for future fast access.
@param cpIndex constant pool index
@return UTF8 string at that constant pool index | [
"Return",
"the",
"UTF8",
"at",
"the",
"specified",
"index",
"in",
"the",
"constant",
"pool",
".",
"The",
"data",
"found",
"at",
"the",
"constant",
"pool",
"for",
"that",
"index",
"may",
"not",
"have",
"been",
"unpacked",
"yet",
"if",
"this",
"is",
"the",... | train | https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ConstantPoolScanner.java#L157-L173 |
kstateome/canvas-api | src/main/java/edu/ksu/canvas/impl/ExternalToolImpl.java | ExternalToolImpl.ensureToolValidForCreation | private void ensureToolValidForCreation(ExternalTool tool) {
//check for the unconditionally required fields
if(StringUtils.isAnyBlank(tool.getName(), tool.getPrivacyLevel(), tool.getConsumerKey(), tool.getSharedSecret())) {
throw new IllegalArgumentException("External tool requires all of the following for creation: name, privacy level, consumer key, shared secret");
}
//check that there is either a URL or a domain. One or the other is required
if(StringUtils.isBlank(tool.getUrl()) && StringUtils.isBlank(tool.getDomain())) {
throw new IllegalArgumentException("External tool requires either a URL or domain for creation");
}
} | java | private void ensureToolValidForCreation(ExternalTool tool) {
//check for the unconditionally required fields
if(StringUtils.isAnyBlank(tool.getName(), tool.getPrivacyLevel(), tool.getConsumerKey(), tool.getSharedSecret())) {
throw new IllegalArgumentException("External tool requires all of the following for creation: name, privacy level, consumer key, shared secret");
}
//check that there is either a URL or a domain. One or the other is required
if(StringUtils.isBlank(tool.getUrl()) && StringUtils.isBlank(tool.getDomain())) {
throw new IllegalArgumentException("External tool requires either a URL or domain for creation");
}
} | [
"private",
"void",
"ensureToolValidForCreation",
"(",
"ExternalTool",
"tool",
")",
"{",
"//check for the unconditionally required fields",
"if",
"(",
"StringUtils",
".",
"isAnyBlank",
"(",
"tool",
".",
"getName",
"(",
")",
",",
"tool",
".",
"getPrivacyLevel",
"(",
"... | Ensure that a tool object is valid for creation. The API requires certain fields to be filled out.
Throws an IllegalArgumentException if the conditions are not met.
@param tool The external tool object we are trying to create | [
"Ensure",
"that",
"a",
"tool",
"object",
"is",
"valid",
"for",
"creation",
".",
"The",
"API",
"requires",
"certain",
"fields",
"to",
"be",
"filled",
"out",
".",
"Throws",
"an",
"IllegalArgumentException",
"if",
"the",
"conditions",
"are",
"not",
"met",
"."
] | train | https://github.com/kstateome/canvas-api/blob/426bf403a8fd7aca3f170348005feda25b374e5a/src/main/java/edu/ksu/canvas/impl/ExternalToolImpl.java#L139-L148 |
anotheria/moskito | moskito-core/src/main/java/net/anotheria/moskito/core/util/MBeanUtil.java | MBeanUtil.registerMBean | public String registerMBean(Object bean, String name, boolean replace)
throws MalformedObjectNameException, NotCompliantMBeanException, MBeanRegistrationException{
synchronized (mBeanServer) {
ObjectName newBeanName = null;
try {
newBeanName = new ObjectName(name);
beansNames.add(newBeanName); // Saving bean name for possible later cleanups
mBeanServer.registerMBean(bean, newBeanName);
return name;
} catch (InstanceAlreadyExistsException e) {
beansNames.remove(newBeanName); // Bean not registered, it name is not required for cleanup
if (replace) {
unregisterMBean(name);
return registerMBean(bean, name, true);
} else
return registerMBean(bean, resolveDuplicateName(name));
}
}
} | java | public String registerMBean(Object bean, String name, boolean replace)
throws MalformedObjectNameException, NotCompliantMBeanException, MBeanRegistrationException{
synchronized (mBeanServer) {
ObjectName newBeanName = null;
try {
newBeanName = new ObjectName(name);
beansNames.add(newBeanName); // Saving bean name for possible later cleanups
mBeanServer.registerMBean(bean, newBeanName);
return name;
} catch (InstanceAlreadyExistsException e) {
beansNames.remove(newBeanName); // Bean not registered, it name is not required for cleanup
if (replace) {
unregisterMBean(name);
return registerMBean(bean, name, true);
} else
return registerMBean(bean, resolveDuplicateName(name));
}
}
} | [
"public",
"String",
"registerMBean",
"(",
"Object",
"bean",
",",
"String",
"name",
",",
"boolean",
"replace",
")",
"throws",
"MalformedObjectNameException",
",",
"NotCompliantMBeanException",
",",
"MBeanRegistrationException",
"{",
"synchronized",
"(",
"mBeanServer",
")... | Registers MBean in local MBean server.
Method has mechanism to resolve bean name duplication
depends on `replace` parameter of ths method.
If true - old bean be replaced by new one.
If false - prefix been added to bean name from method parameter
Prefix format:
copy{$number}.{$originalName}
where:
$number - bean copy number (1 for first copy)
$originalName - original bean name passed to this method
@param bean MBean object
@param name MBean name
@param replace controls resolving of bean name duplication.
true - old bean be replaced by new one.
false - prefix be added to bean name.
@return name of MBean string
@throws MalformedObjectNameException name from parameter is unacceptable as object name
@throws NotCompliantMBeanException thrown by MBeanServer
@throws MBeanRegistrationException thrown by MBeanServer | [
"Registers",
"MBean",
"in",
"local",
"MBean",
"server",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/util/MBeanUtil.java#L131-L157 |
UrielCh/ovh-java-sdk | ovh-java-sdk-horizonView/src/main/java/net/minidev/ovh/api/ApiOvhHorizonView.java | ApiOvhHorizonView.serviceName_customerNetwork_POST | public ArrayList<OvhTask> serviceName_customerNetwork_POST(String serviceName, String name, String network) throws IOException {
String qPath = "/horizonView/{serviceName}/customerNetwork";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "name", name);
addBody(o, "network", network);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, t2);
} | java | public ArrayList<OvhTask> serviceName_customerNetwork_POST(String serviceName, String name, String network) throws IOException {
String qPath = "/horizonView/{serviceName}/customerNetwork";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "name", name);
addBody(o, "network", network);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, t2);
} | [
"public",
"ArrayList",
"<",
"OvhTask",
">",
"serviceName_customerNetwork_POST",
"(",
"String",
"serviceName",
",",
"String",
"name",
",",
"String",
"network",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/horizonView/{serviceName}/customerNetwork\"",
";... | Add a new network
REST: POST /horizonView/{serviceName}/customerNetwork
@param network [required] The private network you want to reach.
@param name [required] Name your network
@param serviceName [required] Domain of the service | [
"Add",
"a",
"new",
"network"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-horizonView/src/main/java/net/minidev/ovh/api/ApiOvhHorizonView.java#L414-L422 |
code4everything/util | src/main/java/com/zhazhapan/util/ReflectUtils.java | ReflectUtils.invokeMethod | public static Object invokeMethod(Object object, String methodName, Object[] parameters) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
return invokeMethod(object, methodName, getTypes(parameters), parameters);
} | java | public static Object invokeMethod(Object object, String methodName, Object[] parameters) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
return invokeMethod(object, methodName, getTypes(parameters), parameters);
} | [
"public",
"static",
"Object",
"invokeMethod",
"(",
"Object",
"object",
",",
"String",
"methodName",
",",
"Object",
"[",
"]",
"parameters",
")",
"throws",
"NoSuchMethodException",
",",
"InvocationTargetException",
",",
"IllegalAccessException",
"{",
"return",
"invokeMe... | 调用方法
@param object 对象
@param methodName 方法名
@param parameters 参数
@return 方法返回的结果
@throws NoSuchMethodException 异常
@throws InvocationTargetException 异常
@throws IllegalAccessException 异常 | [
"调用方法"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/ReflectUtils.java#L101-L103 |
igniterealtime/REST-API-Client | src/main/java/org/igniterealtime/restclient/RestClient.java | RestClient.createSLLClient | private Client createSLLClient(ClientConfig clientConfig)
throws KeyManagementException, NoSuchAlgorithmException {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
ClientBuilder.newClient(clientConfig);
Client client = ClientBuilder.newBuilder()
.sslContext(sc)
.hostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
})
.withConfig(clientConfig).build();
return client;
} | java | private Client createSLLClient(ClientConfig clientConfig)
throws KeyManagementException, NoSuchAlgorithmException {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
ClientBuilder.newClient(clientConfig);
Client client = ClientBuilder.newBuilder()
.sslContext(sc)
.hostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
})
.withConfig(clientConfig).build();
return client;
} | [
"private",
"Client",
"createSLLClient",
"(",
"ClientConfig",
"clientConfig",
")",
"throws",
"KeyManagementException",
",",
"NoSuchAlgorithmException",
"{",
"TrustManager",
"[",
"]",
"trustAllCerts",
"=",
"new",
"TrustManager",
"[",
"]",
"{",
"new",
"X509TrustManager",
... | Creates the sll client.
@param clientConfig
the client config
@return the client config
@throws KeyManagementException
the key management exception
@throws NoSuchAlgorithmException
the no such algorithm exception | [
"Creates",
"the",
"sll",
"client",
"."
] | train | https://github.com/igniterealtime/REST-API-Client/blob/fd544dd770ec2ababa47fef51579522ddce09f05/src/main/java/org/igniterealtime/restclient/RestClient.java#L292-L322 |
spockframework/spock | spock-core/src/main/java/org/spockframework/compiler/SpecRewriter.java | SpecRewriter.visitCleanupBlock | @Override
public void visitCleanupBlock(CleanupBlock block) {
for (Block b : method.getBlocks()) {
if (b == block) break;
moveVariableDeclarations(b.getAst(), method.getStatements());
}
VariableExpression featureThrowableVar =
new VariableExpression("$spock_feature_throwable", nodeCache.Throwable);
method.getStatements().add(createVariableDeclarationStatement(featureThrowableVar));
List<Statement> featureStats = new ArrayList<>();
for (Block b : method.getBlocks()) {
if (b == block) break;
featureStats.addAll(b.getAst());
}
CatchStatement featureCatchStat = createThrowableAssignmentAndRethrowCatchStatement(featureThrowableVar);
List<Statement> cleanupStats = Collections.<Statement>singletonList(
createCleanupTryCatch(block, featureThrowableVar));
TryCatchStatement tryFinally =
new TryCatchStatement(
new BlockStatement(featureStats, new VariableScope()),
new BlockStatement(cleanupStats, new VariableScope()));
tryFinally.addCatch(featureCatchStat);
method.getStatements().add(tryFinally);
// a cleanup-block may only be followed by a where-block, whose
// statements are copied to newly generated methods rather than
// the original method
movedStatsBackToMethod = true;
} | java | @Override
public void visitCleanupBlock(CleanupBlock block) {
for (Block b : method.getBlocks()) {
if (b == block) break;
moveVariableDeclarations(b.getAst(), method.getStatements());
}
VariableExpression featureThrowableVar =
new VariableExpression("$spock_feature_throwable", nodeCache.Throwable);
method.getStatements().add(createVariableDeclarationStatement(featureThrowableVar));
List<Statement> featureStats = new ArrayList<>();
for (Block b : method.getBlocks()) {
if (b == block) break;
featureStats.addAll(b.getAst());
}
CatchStatement featureCatchStat = createThrowableAssignmentAndRethrowCatchStatement(featureThrowableVar);
List<Statement> cleanupStats = Collections.<Statement>singletonList(
createCleanupTryCatch(block, featureThrowableVar));
TryCatchStatement tryFinally =
new TryCatchStatement(
new BlockStatement(featureStats, new VariableScope()),
new BlockStatement(cleanupStats, new VariableScope()));
tryFinally.addCatch(featureCatchStat);
method.getStatements().add(tryFinally);
// a cleanup-block may only be followed by a where-block, whose
// statements are copied to newly generated methods rather than
// the original method
movedStatsBackToMethod = true;
} | [
"@",
"Override",
"public",
"void",
"visitCleanupBlock",
"(",
"CleanupBlock",
"block",
")",
"{",
"for",
"(",
"Block",
"b",
":",
"method",
".",
"getBlocks",
"(",
")",
")",
"{",
"if",
"(",
"b",
"==",
"block",
")",
"break",
";",
"moveVariableDeclarations",
"... | /*
This emulates Java 7 try-with-resources exception handling
Throwable $spock_feature_throwable = null;
try {
feature statements (setup, when/then, expect, etc. blocks)
} catch (Throwable $spock_tmp_throwable) {
$spock_feature_throwable = $spock_tmp_throwable;
throw $spock_tmp_throwable;
} finally {
try {
feature cleanup statements (cleanup block)
} catch (Throwable $spock_tmp_throwable) {
if($spock_feature_throwable != null) {
$spock_feature_throwable.addSuppressed($spock_tmp_throwable);
} else {
throw $spock_tmp_throwable;
}
}
} | [
"/",
"*",
"This",
"emulates",
"Java",
"7",
"try",
"-",
"with",
"-",
"resources",
"exception",
"handling"
] | train | https://github.com/spockframework/spock/blob/d751a0abd8d5a2ec5338aa10bc2d19371b3b3ad9/spock-core/src/main/java/org/spockframework/compiler/SpecRewriter.java#L392-L426 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java | SDBaseOps.zerosLike | public SDVariable zerosLike(String name, @NonNull SDVariable input) {
SDVariable ret = f().zerosLike(name, input);
return updateVariableNameAndReference(ret, name);
} | java | public SDVariable zerosLike(String name, @NonNull SDVariable input) {
SDVariable ret = f().zerosLike(name, input);
return updateVariableNameAndReference(ret, name);
} | [
"public",
"SDVariable",
"zerosLike",
"(",
"String",
"name",
",",
"@",
"NonNull",
"SDVariable",
"input",
")",
"{",
"SDVariable",
"ret",
"=",
"f",
"(",
")",
".",
"zerosLike",
"(",
"name",
",",
"input",
")",
";",
"return",
"updateVariableNameAndReference",
"(",... | Return a variable of all 0s, with the same shape as the input variable. Note that this is dynamic:
if the input shape changes in later execution, the returned variable's shape will also be updated
@param name Name of the new SDVariable
@param input Input SDVariable
@return A new SDVariable with the same (dynamic) shape as the input | [
"Return",
"a",
"variable",
"of",
"all",
"0s",
"with",
"the",
"same",
"shape",
"as",
"the",
"input",
"variable",
".",
"Note",
"that",
"this",
"is",
"dynamic",
":",
"if",
"the",
"input",
"shape",
"changes",
"in",
"later",
"execution",
"the",
"returned",
"v... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L3095-L3098 |
Javacord/Javacord | javacord-api/src/main/java/org/javacord/api/entity/server/ServerUpdater.java | ServerUpdater.setNickname | public ServerUpdater setNickname(User user, String nickname) {
delegate.setNickname(user, nickname);
return this;
} | java | public ServerUpdater setNickname(User user, String nickname) {
delegate.setNickname(user, nickname);
return this;
} | [
"public",
"ServerUpdater",
"setNickname",
"(",
"User",
"user",
",",
"String",
"nickname",
")",
"{",
"delegate",
".",
"setNickname",
"(",
"user",
",",
"nickname",
")",
";",
"return",
"this",
";",
"}"
] | Queues a user's nickname to be updated.
@param user The user whose nickname should be updated.
@param nickname The new nickname of the user.
@return The current instance in order to chain call methods. | [
"Queues",
"a",
"user",
"s",
"nickname",
"to",
"be",
"updated",
"."
] | train | https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/server/ServerUpdater.java#L408-L411 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_GeomFromWKB.java | ST_GeomFromWKB.toGeometry | public static Geometry toGeometry(byte[] bytes, int srid) throws SQLException{
if(bytes==null) {
return null;
}
WKBReader wkbReader = new WKBReader();
try {
Geometry geometry = wkbReader.read(bytes);
geometry.setSRID(srid);
return geometry;
} catch (ParseException ex) {
throw new SQLException("Cannot parse the input bytes",ex);
}
} | java | public static Geometry toGeometry(byte[] bytes, int srid) throws SQLException{
if(bytes==null) {
return null;
}
WKBReader wkbReader = new WKBReader();
try {
Geometry geometry = wkbReader.read(bytes);
geometry.setSRID(srid);
return geometry;
} catch (ParseException ex) {
throw new SQLException("Cannot parse the input bytes",ex);
}
} | [
"public",
"static",
"Geometry",
"toGeometry",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"srid",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"bytes",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"WKBReader",
"wkbReader",
"=",
"new",
"WKBReader... | Convert a WKB representation to a geometry
@param bytes the input WKB object
@param srid the input SRID
@return
@throws SQLException | [
"Convert",
"a",
"WKB",
"representation",
"to",
"a",
"geometry"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_GeomFromWKB.java#L54-L66 |
Baidu-AIP/java-sdk | src/main/java/com/baidu/aip/face/AipFace.java | AipFace.userCopy | public JSONObject userCopy(String userId, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("user_id", userId);
if (options != null) {
request.addBody(options);
}
request.setUri(FaceConsts.USER_COPY);
request.setBodyFormat(EBodyFormat.RAW_JSON);
postOperation(request);
return requestServer(request);
} | java | public JSONObject userCopy(String userId, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("user_id", userId);
if (options != null) {
request.addBody(options);
}
request.setUri(FaceConsts.USER_COPY);
request.setBodyFormat(EBodyFormat.RAW_JSON);
postOperation(request);
return requestServer(request);
} | [
"public",
"JSONObject",
"userCopy",
"(",
"String",
"userId",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"options",
")",
"{",
"AipRequest",
"request",
"=",
"new",
"AipRequest",
"(",
")",
";",
"preOperation",
"(",
"request",
")",
";",
"request",
".",... | 复制用户接口
@param userId - 用户id(由数字、字母、下划线组成),长度限制128B
@param options - 可选参数对象,key: value都为string类型
options - options列表:
src_group_id 从指定组里复制信息
dst_group_id 需要添加用户的组id
@return JSONObject | [
"复制用户接口"
] | train | https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/face/AipFace.java#L275-L287 |
google/error-prone | check_api/src/main/java/com/google/errorprone/matchers/Matchers.java | Matchers.ignoreParens | public static Matcher<ExpressionTree> ignoreParens(final Matcher<ExpressionTree> innerMatcher) {
return new Matcher<ExpressionTree>() {
@Override
public boolean matches(ExpressionTree expressionTree, VisitorState state) {
return innerMatcher.matches((ExpressionTree) stripParentheses(expressionTree), state);
}
};
} | java | public static Matcher<ExpressionTree> ignoreParens(final Matcher<ExpressionTree> innerMatcher) {
return new Matcher<ExpressionTree>() {
@Override
public boolean matches(ExpressionTree expressionTree, VisitorState state) {
return innerMatcher.matches((ExpressionTree) stripParentheses(expressionTree), state);
}
};
} | [
"public",
"static",
"Matcher",
"<",
"ExpressionTree",
">",
"ignoreParens",
"(",
"final",
"Matcher",
"<",
"ExpressionTree",
">",
"innerMatcher",
")",
"{",
"return",
"new",
"Matcher",
"<",
"ExpressionTree",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean... | Ignores any number of parenthesis wrapping an expression and then applies the passed matcher to
that expression. For example, the passed matcher would be applied to {@code value} in {@code
(((value)))}. | [
"Ignores",
"any",
"number",
"of",
"parenthesis",
"wrapping",
"an",
"expression",
"and",
"then",
"applies",
"the",
"passed",
"matcher",
"to",
"that",
"expression",
".",
"For",
"example",
"the",
"passed",
"matcher",
"would",
"be",
"applied",
"to",
"{"
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L675-L682 |
fcrepo4-exts/fcrepo-camel-toolbox | fcrepo-ldpath/src/main/java/org/fcrepo/camel/ldpath/ClientFactory.java | ClientFactory.createClient | public static ClientConfiguration createClient(final DataProvider provider) {
return createClient(null, null, emptyList(), singletonList(provider));
} | java | public static ClientConfiguration createClient(final DataProvider provider) {
return createClient(null, null, emptyList(), singletonList(provider));
} | [
"public",
"static",
"ClientConfiguration",
"createClient",
"(",
"final",
"DataProvider",
"provider",
")",
"{",
"return",
"createClient",
"(",
"null",
",",
"null",
",",
"emptyList",
"(",
")",
",",
"singletonList",
"(",
"provider",
")",
")",
";",
"}"
] | Configure a linked data client suitable for use with a Fedora Repository.
@param provider Provider to enable on the client
@return a configuration for use with an LDClient | [
"Configure",
"a",
"linked",
"data",
"client",
"suitable",
"for",
"use",
"with",
"a",
"Fedora",
"Repository",
"."
] | train | https://github.com/fcrepo4-exts/fcrepo-camel-toolbox/blob/9e0cf220937b2d5c050e0e071f0cdc4c7a084c0f/fcrepo-ldpath/src/main/java/org/fcrepo/camel/ldpath/ClientFactory.java#L61-L63 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/InterfaceEndpointsInner.java | InterfaceEndpointsInner.createOrUpdateAsync | public Observable<InterfaceEndpointInner> createOrUpdateAsync(String resourceGroupName, String interfaceEndpointName, InterfaceEndpointInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, interfaceEndpointName, parameters).map(new Func1<ServiceResponse<InterfaceEndpointInner>, InterfaceEndpointInner>() {
@Override
public InterfaceEndpointInner call(ServiceResponse<InterfaceEndpointInner> response) {
return response.body();
}
});
} | java | public Observable<InterfaceEndpointInner> createOrUpdateAsync(String resourceGroupName, String interfaceEndpointName, InterfaceEndpointInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, interfaceEndpointName, parameters).map(new Func1<ServiceResponse<InterfaceEndpointInner>, InterfaceEndpointInner>() {
@Override
public InterfaceEndpointInner call(ServiceResponse<InterfaceEndpointInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"InterfaceEndpointInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"interfaceEndpointName",
",",
"InterfaceEndpointInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"reso... | Creates or updates an interface endpoint in the specified resource group.
@param resourceGroupName The name of the resource group.
@param interfaceEndpointName The name of the interface endpoint.
@param parameters Parameters supplied to the create or update interface endpoint operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"an",
"interface",
"endpoint",
"in",
"the",
"specified",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/InterfaceEndpointsInner.java#L460-L467 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/config/xml/ReceiveMessageActionParser.java | ReceiveMessageActionParser.addSchemaInformationToValidationContext | private void addSchemaInformationToValidationContext(Element messageElement, SchemaValidationContext context) {
String schemaValidation = messageElement.getAttribute("schema-validation");
if (StringUtils.hasText(schemaValidation)) {
context.setSchemaValidation(Boolean.valueOf(schemaValidation));
}
String schema = messageElement.getAttribute("schema");
if (StringUtils.hasText(schema)) {
context.setSchema(schema);
}
String schemaRepository = messageElement.getAttribute("schema-repository");
if (StringUtils.hasText(schemaRepository)) {
context.setSchemaRepository(schemaRepository);
}
} | java | private void addSchemaInformationToValidationContext(Element messageElement, SchemaValidationContext context) {
String schemaValidation = messageElement.getAttribute("schema-validation");
if (StringUtils.hasText(schemaValidation)) {
context.setSchemaValidation(Boolean.valueOf(schemaValidation));
}
String schema = messageElement.getAttribute("schema");
if (StringUtils.hasText(schema)) {
context.setSchema(schema);
}
String schemaRepository = messageElement.getAttribute("schema-repository");
if (StringUtils.hasText(schemaRepository)) {
context.setSchemaRepository(schemaRepository);
}
} | [
"private",
"void",
"addSchemaInformationToValidationContext",
"(",
"Element",
"messageElement",
",",
"SchemaValidationContext",
"context",
")",
"{",
"String",
"schemaValidation",
"=",
"messageElement",
".",
"getAttribute",
"(",
"\"schema-validation\"",
")",
";",
"if",
"("... | Adds information about the validation of the message against a certain schema to the context
@param messageElement The message element to get the configuration from
@param context The context to set the schema validation configuration to | [
"Adds",
"information",
"about",
"the",
"validation",
"of",
"the",
"message",
"against",
"a",
"certain",
"schema",
"to",
"the",
"context"
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/xml/ReceiveMessageActionParser.java#L263-L278 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/stats/Counters.java | Counters.printCounterComparison | public static <E> void printCounterComparison(Counter<E> a, Counter<E> b, PrintWriter out) {
if (a.equals(b)) {
out.println("Counters are equal.");
return;
}
for (E key : a.keySet()) {
double aCount = a.getCount(key);
double bCount = b.getCount(key);
if (Math.abs(aCount - bCount) > 1e-5) {
out.println("Counters differ on key " + key + '\t' + a.getCount(key) + " vs. " + b.getCount(key));
}
}
// left overs
Set<E> rest = new HashSet<E>(b.keySet());
rest.removeAll(a.keySet());
for (E key : rest) {
double aCount = a.getCount(key);
double bCount = b.getCount(key);
if (Math.abs(aCount - bCount) > 1e-5) {
out.println("Counters differ on key " + key + '\t' + a.getCount(key) + " vs. " + b.getCount(key));
}
}
} | java | public static <E> void printCounterComparison(Counter<E> a, Counter<E> b, PrintWriter out) {
if (a.equals(b)) {
out.println("Counters are equal.");
return;
}
for (E key : a.keySet()) {
double aCount = a.getCount(key);
double bCount = b.getCount(key);
if (Math.abs(aCount - bCount) > 1e-5) {
out.println("Counters differ on key " + key + '\t' + a.getCount(key) + " vs. " + b.getCount(key));
}
}
// left overs
Set<E> rest = new HashSet<E>(b.keySet());
rest.removeAll(a.keySet());
for (E key : rest) {
double aCount = a.getCount(key);
double bCount = b.getCount(key);
if (Math.abs(aCount - bCount) > 1e-5) {
out.println("Counters differ on key " + key + '\t' + a.getCount(key) + " vs. " + b.getCount(key));
}
}
} | [
"public",
"static",
"<",
"E",
">",
"void",
"printCounterComparison",
"(",
"Counter",
"<",
"E",
">",
"a",
",",
"Counter",
"<",
"E",
">",
"b",
",",
"PrintWriter",
"out",
")",
"{",
"if",
"(",
"a",
".",
"equals",
"(",
"b",
")",
")",
"{",
"out",
".",
... | Prints one or more lines (with a newline at the end) describing the
difference between the two Counters. Great for debugging. | [
"Prints",
"one",
"or",
"more",
"lines",
"(",
"with",
"a",
"newline",
"at",
"the",
"end",
")",
"describing",
"the",
"difference",
"between",
"the",
"two",
"Counters",
".",
"Great",
"for",
"debugging",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L1487-L1510 |
recommenders/rival | rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java | NDCG.getValueAt | @Override
public double getValueAt(final U user, final int at) {
if (userDcgAtCutoff.containsKey(at) && userDcgAtCutoff.get(at).containsKey(user)
&& userIdcgAtCutoff.containsKey(at) && userIdcgAtCutoff.get(at).containsKey(user)) {
double idcg = userIdcgAtCutoff.get(at).get(user);
double dcg = userDcgAtCutoff.get(at).get(user);
return dcg / idcg;
}
return Double.NaN;
} | java | @Override
public double getValueAt(final U user, final int at) {
if (userDcgAtCutoff.containsKey(at) && userDcgAtCutoff.get(at).containsKey(user)
&& userIdcgAtCutoff.containsKey(at) && userIdcgAtCutoff.get(at).containsKey(user)) {
double idcg = userIdcgAtCutoff.get(at).get(user);
double dcg = userDcgAtCutoff.get(at).get(user);
return dcg / idcg;
}
return Double.NaN;
} | [
"@",
"Override",
"public",
"double",
"getValueAt",
"(",
"final",
"U",
"user",
",",
"final",
"int",
"at",
")",
"{",
"if",
"(",
"userDcgAtCutoff",
".",
"containsKey",
"(",
"at",
")",
"&&",
"userDcgAtCutoff",
".",
"get",
"(",
"at",
")",
".",
"containsKey",
... | Method to return the NDCG value at a particular cutoff level for a given
user.
@param user the user
@param at cutoff level
@return the NDCG corresponding to the requested user at the cutoff level | [
"Method",
"to",
"return",
"the",
"NDCG",
"value",
"at",
"a",
"particular",
"cutoff",
"level",
"for",
"a",
"given",
"user",
"."
] | train | https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java#L280-L289 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/blas/SparseCpuLevel1.java | SparseCpuLevel1.daxpyi | @Override
protected void daxpyi(long N, double alpha, INDArray X, DataBuffer pointers, INDArray Y){
cblas_daxpyi((int) N, alpha, (DoublePointer) X.data().addressPointer(), (IntPointer) pointers.addressPointer(),
(DoublePointer) Y.data().addressPointer());
} | java | @Override
protected void daxpyi(long N, double alpha, INDArray X, DataBuffer pointers, INDArray Y){
cblas_daxpyi((int) N, alpha, (DoublePointer) X.data().addressPointer(), (IntPointer) pointers.addressPointer(),
(DoublePointer) Y.data().addressPointer());
} | [
"@",
"Override",
"protected",
"void",
"daxpyi",
"(",
"long",
"N",
",",
"double",
"alpha",
",",
"INDArray",
"X",
",",
"DataBuffer",
"pointers",
",",
"INDArray",
"Y",
")",
"{",
"cblas_daxpyi",
"(",
"(",
"int",
")",
"N",
",",
"alpha",
",",
"(",
"DoublePoi... | Adds a scalar multiple of double compressed sparse vector to a full-storage vector.
@param N The number of elements in vector X
@param alpha
@param X a sparse vector
@param pointers A DataBuffer that specifies the indices for the elements of x.
@param Y a dense vector | [
"Adds",
"a",
"scalar",
"multiple",
"of",
"double",
"compressed",
"sparse",
"vector",
"to",
"a",
"full",
"-",
"storage",
"vector",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/blas/SparseCpuLevel1.java#L195-L199 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/utils/FBUtilities.java | FBUtilities.getProtectedField | public static Field getProtectedField(Class klass, String fieldName)
{
Field field;
try
{
field = klass.getDeclaredField(fieldName);
field.setAccessible(true);
}
catch (Exception e)
{
throw new AssertionError(e);
}
return field;
} | java | public static Field getProtectedField(Class klass, String fieldName)
{
Field field;
try
{
field = klass.getDeclaredField(fieldName);
field.setAccessible(true);
}
catch (Exception e)
{
throw new AssertionError(e);
}
return field;
} | [
"public",
"static",
"Field",
"getProtectedField",
"(",
"Class",
"klass",
",",
"String",
"fieldName",
")",
"{",
"Field",
"field",
";",
"try",
"{",
"field",
"=",
"klass",
".",
"getDeclaredField",
"(",
"fieldName",
")",
";",
"field",
".",
"setAccessible",
"(",
... | Used to get access to protected/private field of the specified class
@param klass - name of the class
@param fieldName - name of the field
@return Field or null on error | [
"Used",
"to",
"get",
"access",
"to",
"protected",
"/",
"private",
"field",
"of",
"the",
"specified",
"class"
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/FBUtilities.java#L515-L530 |
apache/spark | common/network-common/src/main/java/org/apache/spark/network/TransportContext.java | TransportContext.createServer | public TransportServer createServer(int port, List<TransportServerBootstrap> bootstraps) {
return new TransportServer(this, null, port, rpcHandler, bootstraps);
} | java | public TransportServer createServer(int port, List<TransportServerBootstrap> bootstraps) {
return new TransportServer(this, null, port, rpcHandler, bootstraps);
} | [
"public",
"TransportServer",
"createServer",
"(",
"int",
"port",
",",
"List",
"<",
"TransportServerBootstrap",
">",
"bootstraps",
")",
"{",
"return",
"new",
"TransportServer",
"(",
"this",
",",
"null",
",",
"port",
",",
"rpcHandler",
",",
"bootstraps",
")",
";... | Create a server which will attempt to bind to a specific port. | [
"Create",
"a",
"server",
"which",
"will",
"attempt",
"to",
"bind",
"to",
"a",
"specific",
"port",
"."
] | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-common/src/main/java/org/apache/spark/network/TransportContext.java#L150-L152 |
ckpoint/CheckPoint | src/main/java/hsim/checkpoint/core/store/ValidationDataGroup.java | ValidationDataGroup.initDataGroup | public void initDataGroup(ParamType paramType, List<ValidationData> lists) {
this.paramType = paramType;
lists.forEach(vd -> {
this.addRule(vd);
});
} | java | public void initDataGroup(ParamType paramType, List<ValidationData> lists) {
this.paramType = paramType;
lists.forEach(vd -> {
this.addRule(vd);
});
} | [
"public",
"void",
"initDataGroup",
"(",
"ParamType",
"paramType",
",",
"List",
"<",
"ValidationData",
">",
"lists",
")",
"{",
"this",
".",
"paramType",
"=",
"paramType",
";",
"lists",
".",
"forEach",
"(",
"vd",
"->",
"{",
"this",
".",
"addRule",
"(",
"vd... | Init data group.
@param paramType the param type
@param lists the lists | [
"Init",
"data",
"group",
"."
] | train | https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/core/store/ValidationDataGroup.java#L46-L53 |
apereo/cas | support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/util/OAuth20Utils.java | OAuth20Utils.checkClientSecret | public static boolean checkClientSecret(final OAuthRegisteredService registeredService, final String clientSecret) {
LOGGER.debug("Found: [{}] in secret check", registeredService);
if (StringUtils.isBlank(registeredService.getClientSecret())) {
LOGGER.debug("The client secret is not defined for the registered service [{}]", registeredService.getName());
return true;
}
if (!StringUtils.equals(registeredService.getClientSecret(), clientSecret)) {
LOGGER.error("Wrong client secret for service: [{}]", registeredService.getServiceId());
return false;
}
return true;
} | java | public static boolean checkClientSecret(final OAuthRegisteredService registeredService, final String clientSecret) {
LOGGER.debug("Found: [{}] in secret check", registeredService);
if (StringUtils.isBlank(registeredService.getClientSecret())) {
LOGGER.debug("The client secret is not defined for the registered service [{}]", registeredService.getName());
return true;
}
if (!StringUtils.equals(registeredService.getClientSecret(), clientSecret)) {
LOGGER.error("Wrong client secret for service: [{}]", registeredService.getServiceId());
return false;
}
return true;
} | [
"public",
"static",
"boolean",
"checkClientSecret",
"(",
"final",
"OAuthRegisteredService",
"registeredService",
",",
"final",
"String",
"clientSecret",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Found: [{}] in secret check\"",
",",
"registeredService",
")",
";",
"if",
... | Check the client secret.
@param registeredService the registered service
@param clientSecret the client secret
@return whether the secret is valid | [
"Check",
"the",
"client",
"secret",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/util/OAuth20Utils.java#L386-L397 |
census-instrumentation/opencensus-java | contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardMetrics.java | DropWizardMetrics.collectHistogram | private Metric collectHistogram(MetricName dropwizardMetric, Histogram histogram) {
String metricName =
DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "histogram");
String metricDescription =
DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), histogram);
final AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels =
DropWizardUtils.generateLabels(dropwizardMetric);
return collectSnapshotAndCount(
metricName,
metricDescription,
labels.getKey(),
labels.getValue(),
DEFAULT_UNIT,
histogram.getSnapshot(),
histogram.getCount());
} | java | private Metric collectHistogram(MetricName dropwizardMetric, Histogram histogram) {
String metricName =
DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "histogram");
String metricDescription =
DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), histogram);
final AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels =
DropWizardUtils.generateLabels(dropwizardMetric);
return collectSnapshotAndCount(
metricName,
metricDescription,
labels.getKey(),
labels.getValue(),
DEFAULT_UNIT,
histogram.getSnapshot(),
histogram.getCount());
} | [
"private",
"Metric",
"collectHistogram",
"(",
"MetricName",
"dropwizardMetric",
",",
"Histogram",
"histogram",
")",
"{",
"String",
"metricName",
"=",
"DropWizardUtils",
".",
"generateFullMetricName",
"(",
"dropwizardMetric",
".",
"getKey",
"(",
")",
",",
"\"histogram\... | Returns a {@code Metric} collected from {@link Histogram}.
@param dropwizardMetric the metric name.
@param histogram the histogram object to collect
@return a {@code Metric}. | [
"Returns",
"a",
"{",
"@code",
"Metric",
"}",
"collected",
"from",
"{",
"@link",
"Histogram",
"}",
"."
] | train | https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardMetrics.java#L197-L213 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/slim/web/SeleniumDriverSetup.java | SeleniumDriverSetup.startDriverForWithProfile | public boolean startDriverForWithProfile(String browser, Map<String, Object> profile) throws Exception {
if (OVERRIDE_ACTIVE) {
return true;
}
DriverFactory driverFactory = new ProjectDriverFactoryFactory().create(browser, profile);
WebDriver driver = setAndUseDriverFactory(driverFactory);
return driver != null;
} | java | public boolean startDriverForWithProfile(String browser, Map<String, Object> profile) throws Exception {
if (OVERRIDE_ACTIVE) {
return true;
}
DriverFactory driverFactory = new ProjectDriverFactoryFactory().create(browser, profile);
WebDriver driver = setAndUseDriverFactory(driverFactory);
return driver != null;
} | [
"public",
"boolean",
"startDriverForWithProfile",
"(",
"String",
"browser",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"profile",
")",
"throws",
"Exception",
"{",
"if",
"(",
"OVERRIDE_ACTIVE",
")",
"{",
"return",
"true",
";",
"}",
"DriverFactory",
"driverF... | Starts a local instance of the selenium driver for the specified browser
(using defaults to determine the correct class and configuration properties).
and injects it into SeleniumHelper, so other fixtures can use it.
@param browser name of browser to connect to.
@param profile setting of the browser (for firefox, chrome mobile and IE only for now)
@return true if instance was created and injected into SeleniumHelper.
@throws Exception if no instance could be created. | [
"Starts",
"a",
"local",
"instance",
"of",
"the",
"selenium",
"driver",
"for",
"the",
"specified",
"browser",
"(",
"using",
"defaults",
"to",
"determine",
"the",
"correct",
"class",
"and",
"configuration",
"properties",
")",
".",
"and",
"injects",
"it",
"into",... | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/slim/web/SeleniumDriverSetup.java#L90-L98 |
anotheria/moskito | moskito-web/src/main/java/net/anotheria/moskito/web/filters/JSTalkBackFilter.java | JSTalkBackFilter.getValueOrDefault | private String getValueOrDefault(HttpServletRequest req, String paramName, String defaultValue) {
final String value = req.getParameter(paramName);
return StringUtils.isEmpty(value) ? defaultValue : value;
} | java | private String getValueOrDefault(HttpServletRequest req, String paramName, String defaultValue) {
final String value = req.getParameter(paramName);
return StringUtils.isEmpty(value) ? defaultValue : value;
} | [
"private",
"String",
"getValueOrDefault",
"(",
"HttpServletRequest",
"req",
",",
"String",
"paramName",
",",
"String",
"defaultValue",
")",
"{",
"final",
"String",
"value",
"=",
"req",
".",
"getParameter",
"(",
"paramName",
")",
";",
"return",
"StringUtils",
"."... | Returns parameter value from request if exists, otherwise - default value.
@param req {@link HttpServletRequest}
@param paramName name of the parameter
@param defaultValue parameter default value
@return request parameter value | [
"Returns",
"parameter",
"value",
"from",
"request",
"if",
"exists",
"otherwise",
"-",
"default",
"value",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-web/src/main/java/net/anotheria/moskito/web/filters/JSTalkBackFilter.java#L139-L142 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/GeometryCoordinateDimension.java | GeometryCoordinateDimension.convert | public static GeometryCollection convert(GeometryCollection gc, int dimension) {
int nb = gc.getNumGeometries();
final Geometry[] geometries = new Geometry[nb];
for (int i = 0; i < nb; i++) {
geometries[i]=force(gc.getGeometryN(i),dimension);
}
return gf.createGeometryCollection(geometries);
} | java | public static GeometryCollection convert(GeometryCollection gc, int dimension) {
int nb = gc.getNumGeometries();
final Geometry[] geometries = new Geometry[nb];
for (int i = 0; i < nb; i++) {
geometries[i]=force(gc.getGeometryN(i),dimension);
}
return gf.createGeometryCollection(geometries);
} | [
"public",
"static",
"GeometryCollection",
"convert",
"(",
"GeometryCollection",
"gc",
",",
"int",
"dimension",
")",
"{",
"int",
"nb",
"=",
"gc",
".",
"getNumGeometries",
"(",
")",
";",
"final",
"Geometry",
"[",
"]",
"geometries",
"=",
"new",
"Geometry",
"[",... | Force the dimension of the GeometryCollection and update correctly the coordinate
dimension
@param gc
@param dimension
@return | [
"Force",
"the",
"dimension",
"of",
"the",
"GeometryCollection",
"and",
"update",
"correctly",
"the",
"coordinate",
"dimension"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/GeometryCoordinateDimension.java#L78-L85 |
janus-project/guava.janusproject.io | guava/src/com/google/common/primitives/UnsignedLong.java | UnsignedLong.valueOf | public static UnsignedLong valueOf(String string, int radix) {
return fromLongBits(UnsignedLongs.parseUnsignedLong(string, radix));
} | java | public static UnsignedLong valueOf(String string, int radix) {
return fromLongBits(UnsignedLongs.parseUnsignedLong(string, radix));
} | [
"public",
"static",
"UnsignedLong",
"valueOf",
"(",
"String",
"string",
",",
"int",
"radix",
")",
"{",
"return",
"fromLongBits",
"(",
"UnsignedLongs",
".",
"parseUnsignedLong",
"(",
"string",
",",
"radix",
")",
")",
";",
"}"
] | Returns an {@code UnsignedLong} holding the value of the specified {@code String}, parsed as
an unsigned {@code long} value in the specified radix.
@throws NumberFormatException if the string does not contain a parsable unsigned {@code long}
value, or {@code radix} is not between {@link Character#MIN_RADIX} and
{@link Character#MAX_RADIX} | [
"Returns",
"an",
"{",
"@code",
"UnsignedLong",
"}",
"holding",
"the",
"value",
"of",
"the",
"specified",
"{",
"@code",
"String",
"}",
"parsed",
"as",
"an",
"unsigned",
"{",
"@code",
"long",
"}",
"value",
"in",
"the",
"specified",
"radix",
"."
] | train | https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/primitives/UnsignedLong.java#L119-L121 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java | ParagraphVectors.nearestLabels | public Collection<String> nearestLabels(@NonNull String rawText, int topN) {
List<String> tokens = tokenizerFactory.create(rawText).getTokens();
List<VocabWord> document = new ArrayList<>();
for (String token : tokens) {
if (vocab.containsWord(token)) {
document.add(vocab.wordFor(token));
}
}
// we're returning empty collection for empty document
if (document.isEmpty()) {
log.info("Document passed to nearestLabels() has no matches in model vocabulary");
return new ArrayList<>();
}
return nearestLabels(document, topN);
} | java | public Collection<String> nearestLabels(@NonNull String rawText, int topN) {
List<String> tokens = tokenizerFactory.create(rawText).getTokens();
List<VocabWord> document = new ArrayList<>();
for (String token : tokens) {
if (vocab.containsWord(token)) {
document.add(vocab.wordFor(token));
}
}
// we're returning empty collection for empty document
if (document.isEmpty()) {
log.info("Document passed to nearestLabels() has no matches in model vocabulary");
return new ArrayList<>();
}
return nearestLabels(document, topN);
} | [
"public",
"Collection",
"<",
"String",
">",
"nearestLabels",
"(",
"@",
"NonNull",
"String",
"rawText",
",",
"int",
"topN",
")",
"{",
"List",
"<",
"String",
">",
"tokens",
"=",
"tokenizerFactory",
".",
"create",
"(",
"rawText",
")",
".",
"getTokens",
"(",
... | This method returns top N labels nearest to specified text
@param rawText
@param topN
@return | [
"This",
"method",
"returns",
"top",
"N",
"labels",
"nearest",
"to",
"specified",
"text"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java#L533-L549 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfCell.java | PdfCell.processActions | protected void processActions(Element element, PdfAction action, ArrayList allActions) {
if (element.type() == Element.ANCHOR) {
String url = ((Anchor) element).getReference();
if (url != null) {
action = new PdfAction(url);
}
}
Iterator i;
switch (element.type()) {
case Element.PHRASE:
case Element.SECTION:
case Element.ANCHOR:
case Element.CHAPTER:
case Element.LISTITEM:
case Element.PARAGRAPH:
for (i = ((ArrayList) element).iterator(); i.hasNext();) {
processActions((Element) i.next(), action, allActions);
}
break;
case Element.CHUNK:
allActions.add(action);
break;
case Element.LIST:
for (i = ((List) element).getItems().iterator(); i.hasNext();) {
processActions((Element) i.next(), action, allActions);
}
break;
default:
int n = element.getChunks().size();
while (n-- > 0)
allActions.add(action);
break;
}
} | java | protected void processActions(Element element, PdfAction action, ArrayList allActions) {
if (element.type() == Element.ANCHOR) {
String url = ((Anchor) element).getReference();
if (url != null) {
action = new PdfAction(url);
}
}
Iterator i;
switch (element.type()) {
case Element.PHRASE:
case Element.SECTION:
case Element.ANCHOR:
case Element.CHAPTER:
case Element.LISTITEM:
case Element.PARAGRAPH:
for (i = ((ArrayList) element).iterator(); i.hasNext();) {
processActions((Element) i.next(), action, allActions);
}
break;
case Element.CHUNK:
allActions.add(action);
break;
case Element.LIST:
for (i = ((List) element).getItems().iterator(); i.hasNext();) {
processActions((Element) i.next(), action, allActions);
}
break;
default:
int n = element.getChunks().size();
while (n-- > 0)
allActions.add(action);
break;
}
} | [
"protected",
"void",
"processActions",
"(",
"Element",
"element",
",",
"PdfAction",
"action",
",",
"ArrayList",
"allActions",
")",
"{",
"if",
"(",
"element",
".",
"type",
"(",
")",
"==",
"Element",
".",
"ANCHOR",
")",
"{",
"String",
"url",
"=",
"(",
"(",... | Processes all actions contained in the cell.
@param element an element in the cell
@param action an action that should be coupled to the cell
@param allActions | [
"Processes",
"all",
"actions",
"contained",
"in",
"the",
"cell",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfCell.java#L781-L814 |
virgo47/javasimon | core/src/main/java/org/javasimon/callback/logging/LogTemplates.java | LogTemplates.whenSplitLongerThanMilliseconds | public static SplitThresholdLogTemplate whenSplitLongerThanMilliseconds(LogTemplate<Split> delegateLogger, long threshold) {
return whenSplitLongerThanNanoseconds(delegateLogger, threshold * SimonClock.NANOS_IN_MILLIS);
} | java | public static SplitThresholdLogTemplate whenSplitLongerThanMilliseconds(LogTemplate<Split> delegateLogger, long threshold) {
return whenSplitLongerThanNanoseconds(delegateLogger, threshold * SimonClock.NANOS_IN_MILLIS);
} | [
"public",
"static",
"SplitThresholdLogTemplate",
"whenSplitLongerThanMilliseconds",
"(",
"LogTemplate",
"<",
"Split",
">",
"delegateLogger",
",",
"long",
"threshold",
")",
"{",
"return",
"whenSplitLongerThanNanoseconds",
"(",
"delegateLogger",
",",
"threshold",
"*",
"Simo... | Produces a log template which logs something when stopwatch split is longer than threshold.
@param delegateLogger Concrete log template
@param threshold Threshold (in milliseconds), above which logging is enabled
@return Logger | [
"Produces",
"a",
"log",
"template",
"which",
"logs",
"something",
"when",
"stopwatch",
"split",
"is",
"longer",
"than",
"threshold",
"."
] | train | https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/callback/logging/LogTemplates.java#L125-L127 |
FasterXML/jackson-jr | jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/JSONObjectException.java | JSONObjectException.wrapWithPath | public static JSONObjectException wrapWithPath(Throwable src, Object refFrom,
String refFieldName)
{
return wrapWithPath(src, new Reference(refFrom, refFieldName));
} | java | public static JSONObjectException wrapWithPath(Throwable src, Object refFrom,
String refFieldName)
{
return wrapWithPath(src, new Reference(refFrom, refFieldName));
} | [
"public",
"static",
"JSONObjectException",
"wrapWithPath",
"(",
"Throwable",
"src",
",",
"Object",
"refFrom",
",",
"String",
"refFieldName",
")",
"{",
"return",
"wrapWithPath",
"(",
"src",
",",
"new",
"Reference",
"(",
"refFrom",
",",
"refFieldName",
")",
")",
... | Method that can be called to either create a new JsonMappingException
(if underlying exception is not a JsonMappingException), or augment
given exception with given path/reference information.
This version of method is called when the reference is through a
non-indexed object, such as a Map or POJO/bean. | [
"Method",
"that",
"can",
"be",
"called",
"to",
"either",
"create",
"a",
"new",
"JsonMappingException",
"(",
"if",
"underlying",
"exception",
"is",
"not",
"a",
"JsonMappingException",
")",
"or",
"augment",
"given",
"exception",
"with",
"given",
"path",
"/",
"re... | train | https://github.com/FasterXML/jackson-jr/blob/62ca7a82bd90a9be77028e0b62364307d7532837/jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/JSONObjectException.java#L201-L205 |
httl/httl | httl/src/main/java/httl/spi/codecs/json/JSONObject.java | JSONObject.putAll | public void putAll(String[] names, Object[] values) {
for (int i = 0, len = Math.min(names.length, values.length); i < len; i++)
objectMap.put(names[i], values[i]);
} | java | public void putAll(String[] names, Object[] values) {
for (int i = 0, len = Math.min(names.length, values.length); i < len; i++)
objectMap.put(names[i], values[i]);
} | [
"public",
"void",
"putAll",
"(",
"String",
"[",
"]",
"names",
",",
"Object",
"[",
"]",
"values",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"len",
"=",
"Math",
".",
"min",
"(",
"names",
".",
"length",
",",
"values",
".",
"length",
")",
";... | put all.
@param names name array.
@param values value array. | [
"put",
"all",
"."
] | train | https://github.com/httl/httl/blob/e13e00f4ab41252a8f53d6dafd4a6610be9dcaad/httl/src/main/java/httl/spi/codecs/json/JSONObject.java#L178-L181 |
spring-projects/spring-ldap | core/src/main/java/org/springframework/ldap/core/LdapRdnComponent.java | LdapRdnComponent.encodeUrl | public String encodeUrl() {
// Use the URI class to properly URL encode the value.
try {
URI valueUri = new URI(null, null, value, null);
return key + "=" + valueUri.toString();
}
catch (URISyntaxException e) {
// This should really never happen...
return key + "=" + "value";
}
} | java | public String encodeUrl() {
// Use the URI class to properly URL encode the value.
try {
URI valueUri = new URI(null, null, value, null);
return key + "=" + valueUri.toString();
}
catch (URISyntaxException e) {
// This should really never happen...
return key + "=" + "value";
}
} | [
"public",
"String",
"encodeUrl",
"(",
")",
"{",
"// Use the URI class to properly URL encode the value.",
"try",
"{",
"URI",
"valueUri",
"=",
"new",
"URI",
"(",
"null",
",",
"null",
",",
"value",
",",
"null",
")",
";",
"return",
"key",
"+",
"\"=\"",
"+",
"va... | Get a String representation of this instance for use in URLs.
@return a properly URL encoded representation of this instancs. | [
"Get",
"a",
"String",
"representation",
"of",
"this",
"instance",
"for",
"use",
"in",
"URLs",
"."
] | train | https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/core/LdapRdnComponent.java#L176-L186 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/auth/policy/conditions/ConditionFactory.java | ConditionFactory.newUserAgentCondition | public static Condition newUserAgentCondition(StringComparisonType comparisonType, String value) {
return new StringCondition(comparisonType, USER_AGENT_CONDITION_KEY, value);
} | java | public static Condition newUserAgentCondition(StringComparisonType comparisonType, String value) {
return new StringCondition(comparisonType, USER_AGENT_CONDITION_KEY, value);
} | [
"public",
"static",
"Condition",
"newUserAgentCondition",
"(",
"StringComparisonType",
"comparisonType",
",",
"String",
"value",
")",
"{",
"return",
"new",
"StringCondition",
"(",
"comparisonType",
",",
"USER_AGENT_CONDITION_KEY",
",",
"value",
")",
";",
"}"
] | Constructs a new access control policy condition that tests the incoming
request's user agent field against the specified value, using the
specified comparison type. This condition can be used to allow or deny
access to a resource based on what user agent is specified in the
request.
@param comparisonType
The type of string comparison to perform when testing an
incoming request's user agent field with the specified value.
@param value
The value against which to compare the incoming request's user
agent.
@return A new access control policy condition that tests an incoming
request's user agent field. | [
"Constructs",
"a",
"new",
"access",
"control",
"policy",
"condition",
"that",
"tests",
"the",
"incoming",
"request",
"s",
"user",
"agent",
"field",
"against",
"the",
"specified",
"value",
"using",
"the",
"specified",
"comparison",
"type",
".",
"This",
"condition... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/auth/policy/conditions/ConditionFactory.java#L152-L154 |
perwendel/spark | src/main/java/spark/utils/GzipUtils.java | GzipUtils.checkAndWrap | public static OutputStream checkAndWrap(HttpServletRequest httpRequest,
HttpServletResponse httpResponse,
boolean requireWantsHeader) throws
IOException {
OutputStream responseStream = httpResponse.getOutputStream();
// GZIP Support handled here. First we must ensure that we want to use gzip, and that the client supports gzip
boolean acceptsGzip = Collections.list(httpRequest.getHeaders(ACCEPT_ENCODING)).stream().anyMatch(STRING_MATCH);
boolean wantGzip = httpResponse.getHeaders(CONTENT_ENCODING).contains(GZIP);
if (acceptsGzip) {
if (!requireWantsHeader || wantGzip) {
responseStream = new GZIPOutputStream(responseStream, true);
addContentEncodingHeaderIfMissing(httpResponse, wantGzip);
}
}
return responseStream;
} | java | public static OutputStream checkAndWrap(HttpServletRequest httpRequest,
HttpServletResponse httpResponse,
boolean requireWantsHeader) throws
IOException {
OutputStream responseStream = httpResponse.getOutputStream();
// GZIP Support handled here. First we must ensure that we want to use gzip, and that the client supports gzip
boolean acceptsGzip = Collections.list(httpRequest.getHeaders(ACCEPT_ENCODING)).stream().anyMatch(STRING_MATCH);
boolean wantGzip = httpResponse.getHeaders(CONTENT_ENCODING).contains(GZIP);
if (acceptsGzip) {
if (!requireWantsHeader || wantGzip) {
responseStream = new GZIPOutputStream(responseStream, true);
addContentEncodingHeaderIfMissing(httpResponse, wantGzip);
}
}
return responseStream;
} | [
"public",
"static",
"OutputStream",
"checkAndWrap",
"(",
"HttpServletRequest",
"httpRequest",
",",
"HttpServletResponse",
"httpResponse",
",",
"boolean",
"requireWantsHeader",
")",
"throws",
"IOException",
"{",
"OutputStream",
"responseStream",
"=",
"httpResponse",
".",
"... | Checks if the HTTP request/response accepts and wants GZIP and i that case wraps the response output stream in a
{@link java.util.zip.GZIPOutputStream}.
@param httpRequest the HTTP servlet request.
@param httpResponse the HTTP servlet response.
@param requireWantsHeader if wants header is required
@return if accepted and wanted a {@link java.util.zip.GZIPOutputStream} otherwise the unchanged response
output stream.
@throws IOException in case of IO error. | [
"Checks",
"if",
"the",
"HTTP",
"request",
"/",
"response",
"accepts",
"and",
"wants",
"GZIP",
"and",
"i",
"that",
"case",
"wraps",
"the",
"response",
"output",
"stream",
"in",
"a",
"{",
"@link",
"java",
".",
"util",
".",
"zip",
".",
"GZIPOutputStream",
"... | train | https://github.com/perwendel/spark/blob/080fb1f9d6e580f6742e9589044c7420d3157b8b/src/main/java/spark/utils/GzipUtils.java#L59-L77 |
alkacon/opencms-core | src/org/opencms/ui/components/CmsToolBar.java | CmsToolBar.createDropDown | public static Component createDropDown(FontIcon icon, Component content, String title) {
return createDropDown(getDropDownButtonHtml(icon), content, title);
} | java | public static Component createDropDown(FontIcon icon, Component content, String title) {
return createDropDown(getDropDownButtonHtml(icon), content, title);
} | [
"public",
"static",
"Component",
"createDropDown",
"(",
"FontIcon",
"icon",
",",
"Component",
"content",
",",
"String",
"title",
")",
"{",
"return",
"createDropDown",
"(",
"getDropDownButtonHtml",
"(",
"icon",
")",
",",
"content",
",",
"title",
")",
";",
"}"
] | Creates a drop down menu.<p>
@param icon the button icon
@param content the drop down content
@param title the drop down title
@return the component | [
"Creates",
"a",
"drop",
"down",
"menu",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsToolBar.java#L266-L269 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/linear/ALMA2.java | ALMA2.setAlpha | public void setAlpha(double alpha)
{
if(alpha <= 0 || alpha > 1 || Double.isNaN(alpha))
throw new ArithmeticException("alpha must be in (0, 1], not " + alpha);
this.alpha = alpha;
setB(1.0/alpha);
} | java | public void setAlpha(double alpha)
{
if(alpha <= 0 || alpha > 1 || Double.isNaN(alpha))
throw new ArithmeticException("alpha must be in (0, 1], not " + alpha);
this.alpha = alpha;
setB(1.0/alpha);
} | [
"public",
"void",
"setAlpha",
"(",
"double",
"alpha",
")",
"{",
"if",
"(",
"alpha",
"<=",
"0",
"||",
"alpha",
">",
"1",
"||",
"Double",
".",
"isNaN",
"(",
"alpha",
")",
")",
"throw",
"new",
"ArithmeticException",
"(",
"\"alpha must be in (0, 1], not \"",
"... | Alpha controls the approximation of the large margin formed by ALMA,
with larger values causing more updates. A value of 1.0 will update only
on mistakes, while smaller values update if the error was not far enough
away from the margin.
<br><br>
NOTE: Whenever alpha is set, the value of {@link #setB(double) B} will
also be set to an appropriate value. This is not the only possible value
that will lead to convergence, and can be set manually after alpha is set
to another value.
@param alpha the approximation scale in (0.0, 1.0] | [
"Alpha",
"controls",
"the",
"approximation",
"of",
"the",
"large",
"margin",
"formed",
"by",
"ALMA",
"with",
"larger",
"values",
"causing",
"more",
"updates",
".",
"A",
"value",
"of",
"1",
".",
"0",
"will",
"update",
"only",
"on",
"mistakes",
"while",
"sma... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/ALMA2.java#L94-L100 |
rometools/rome | rome-propono/src/main/java/com/rometools/propono/atom/server/impl/FileBasedCollection.java | FileBasedCollection.saveMediaFile | private void saveMediaFile(final String name, final String contentType, final long size, final InputStream is) throws AtomException {
final byte[] buffer = new byte[8192];
int bytesRead = 0;
final File dirPath = new File(getEntryMediaPath(name));
if (!dirPath.getParentFile().exists()) {
dirPath.getParentFile().mkdirs();
}
OutputStream bos = null;
try {
bos = new FileOutputStream(dirPath.getAbsolutePath());
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
} catch (final Exception e) {
throw new AtomException("ERROR uploading file", e);
} finally {
try {
bos.flush();
bos.close();
} catch (final Exception ignored) {
}
}
} | java | private void saveMediaFile(final String name, final String contentType, final long size, final InputStream is) throws AtomException {
final byte[] buffer = new byte[8192];
int bytesRead = 0;
final File dirPath = new File(getEntryMediaPath(name));
if (!dirPath.getParentFile().exists()) {
dirPath.getParentFile().mkdirs();
}
OutputStream bos = null;
try {
bos = new FileOutputStream(dirPath.getAbsolutePath());
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
} catch (final Exception e) {
throw new AtomException("ERROR uploading file", e);
} finally {
try {
bos.flush();
bos.close();
} catch (final Exception ignored) {
}
}
} | [
"private",
"void",
"saveMediaFile",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"contentType",
",",
"final",
"long",
"size",
",",
"final",
"InputStream",
"is",
")",
"throws",
"AtomException",
"{",
"final",
"byte",
"[",
"]",
"buffer",
"=",
"new",
... | Save file to website's resource directory.
@param handle Weblog handle to save to
@param name Name of file to save
@param size Size of file to be saved
@param is Read file from input stream | [
"Save",
"file",
"to",
"website",
"s",
"resource",
"directory",
"."
] | train | https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome-propono/src/main/java/com/rometools/propono/atom/server/impl/FileBasedCollection.java#L650-L675 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/extralanguage/validator/AbstractExtraLanguageValidator.java | AbstractExtraLanguageValidator.handleInvocationTargetException | @SuppressWarnings("static-method")
protected void handleInvocationTargetException(Throwable targetException, Context context) {
// ignore NullPointerException, as not having to check for NPEs all the time is a convenience feature
if (!(targetException instanceof NullPointerException)) {
Exceptions.throwUncheckedException(targetException);
}
} | java | @SuppressWarnings("static-method")
protected void handleInvocationTargetException(Throwable targetException, Context context) {
// ignore NullPointerException, as not having to check for NPEs all the time is a convenience feature
if (!(targetException instanceof NullPointerException)) {
Exceptions.throwUncheckedException(targetException);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"static-method\"",
")",
"protected",
"void",
"handleInvocationTargetException",
"(",
"Throwable",
"targetException",
",",
"Context",
"context",
")",
"{",
"// ignore NullPointerException, as not having to check for NPEs all the time is a convenience fea... | Handle an exception.
@param targetException the exception.
@param context the context. | [
"Handle",
"an",
"exception",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/extralanguage/validator/AbstractExtraLanguageValidator.java#L488-L494 |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/chatroom/ChatRoomClient.java | ChatRoomClient.updateChatRoomInfo | public ResponseWrapper updateChatRoomInfo(long roomId, String ownerUsername, String name, String desc)
throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(roomId > 0, "room id is invalid");
StringUtils.checkUsername(ownerUsername);
Preconditions.checkArgument(null != name, "Chat room name is null");
Preconditions.checkArgument(null != desc, "Description is null");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(ChatRoomPayload.OWNER, ownerUsername);
jsonObject.addProperty(ChatRoomPayload.NAME, name);
jsonObject.addProperty(ChatRoomPayload.DESC, desc);
return _httpClient.sendPut(_baseUrl + mChatRoomPath + "/" + roomId, _gson.toJson(jsonObject));
} | java | public ResponseWrapper updateChatRoomInfo(long roomId, String ownerUsername, String name, String desc)
throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(roomId > 0, "room id is invalid");
StringUtils.checkUsername(ownerUsername);
Preconditions.checkArgument(null != name, "Chat room name is null");
Preconditions.checkArgument(null != desc, "Description is null");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(ChatRoomPayload.OWNER, ownerUsername);
jsonObject.addProperty(ChatRoomPayload.NAME, name);
jsonObject.addProperty(ChatRoomPayload.DESC, desc);
return _httpClient.sendPut(_baseUrl + mChatRoomPath + "/" + roomId, _gson.toJson(jsonObject));
} | [
"public",
"ResponseWrapper",
"updateChatRoomInfo",
"(",
"long",
"roomId",
",",
"String",
"ownerUsername",
",",
"String",
"name",
",",
"String",
"desc",
")",
"throws",
"APIConnectionException",
",",
"APIRequestException",
"{",
"Preconditions",
".",
"checkArgument",
"("... | Update chat room info
@param roomId room id
@param ownerUsername owner username
@param name new chat room name
@param desc chat room description
@return No content
@throws APIConnectionException connect exception
@throws APIRequestException request exception | [
"Update",
"chat",
"room",
"info"
] | train | https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/chatroom/ChatRoomClient.java#L118-L129 |
sebastiangraf/treetank | coremodules/core/src/main/java/org/treetank/io/IOUtils.java | IOUtils.createFolderStructure | public static boolean createFolderStructure(final File pFile, IConfigurationPath[] pPaths)
throws TTIOException {
boolean returnVal = true;
pFile.mkdirs();
// creation of folder structure
for (IConfigurationPath paths : pPaths) {
final File toCreate = new File(pFile, paths.getFile().getName());
if (paths.isFolder()) {
returnVal = toCreate.mkdir();
} else {
try {
returnVal = toCreate.createNewFile();
} catch (final IOException exc) {
throw new TTIOException(exc);
}
}
if (!returnVal) {
break;
}
}
return returnVal;
} | java | public static boolean createFolderStructure(final File pFile, IConfigurationPath[] pPaths)
throws TTIOException {
boolean returnVal = true;
pFile.mkdirs();
// creation of folder structure
for (IConfigurationPath paths : pPaths) {
final File toCreate = new File(pFile, paths.getFile().getName());
if (paths.isFolder()) {
returnVal = toCreate.mkdir();
} else {
try {
returnVal = toCreate.createNewFile();
} catch (final IOException exc) {
throw new TTIOException(exc);
}
}
if (!returnVal) {
break;
}
}
return returnVal;
} | [
"public",
"static",
"boolean",
"createFolderStructure",
"(",
"final",
"File",
"pFile",
",",
"IConfigurationPath",
"[",
"]",
"pPaths",
")",
"throws",
"TTIOException",
"{",
"boolean",
"returnVal",
"=",
"true",
";",
"pFile",
".",
"mkdirs",
"(",
")",
";",
"// crea... | Creating a folder structure based on a set of paths given as parameter and returning a boolean
determining the success.
@param pFile
the root folder where the configuration should be created to.
@param pPaths
to be created
@return true if creations was successful, false otherwise.
@throws TTIOException | [
"Creating",
"a",
"folder",
"structure",
"based",
"on",
"a",
"set",
"of",
"paths",
"given",
"as",
"parameter",
"and",
"returning",
"a",
"boolean",
"determining",
"the",
"success",
"."
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/coremodules/core/src/main/java/org/treetank/io/IOUtils.java#L32-L53 |
tvesalainen/util | util/src/main/java/org/vesalainen/ui/LineDrawer.java | LineDrawer.drawLine | public static void drawLine(Point p1, Point p2, PlotOperator plot)
{
drawLine(p1.x, p1.y, p2.x, p2.y, plot);
} | java | public static void drawLine(Point p1, Point p2, PlotOperator plot)
{
drawLine(p1.x, p1.y, p2.x, p2.y, plot);
} | [
"public",
"static",
"void",
"drawLine",
"(",
"Point",
"p1",
",",
"Point",
"p2",
",",
"PlotOperator",
"plot",
")",
"{",
"drawLine",
"(",
"p1",
".",
"x",
",",
"p1",
".",
"y",
",",
"p2",
".",
"x",
",",
"p2",
".",
"y",
",",
"plot",
")",
";",
"}"
] | Draws line (p1, p2) by plotting points using plot
@param p1
@param p2
@param plot
@param color | [
"Draws",
"line",
"(",
"p1",
"p2",
")",
"by",
"plotting",
"points",
"using",
"plot"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/ui/LineDrawer.java#L71-L74 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/BaseProfile.java | BaseProfile.generateAntIvyXml | void generateAntIvyXml(Definition def, String outputDir)
{
try
{
FileWriter antfw = Utils.createFile("build.xml", outputDir);
BuildIvyXmlGen bxGen = new BuildIvyXmlGen();
bxGen.generate(def, antfw);
antfw.close();
FileWriter ivyfw = Utils.createFile("ivy.xml", outputDir);
IvyXmlGen ixGen = new IvyXmlGen();
ixGen.generate(def, ivyfw);
ivyfw.close();
FileWriter ivySettingsfw = Utils.createFile("ivy.settings.xml", outputDir);
IvySettingsXmlGen isxGen = new IvySettingsXmlGen();
isxGen.generate(def, ivySettingsfw);
ivySettingsfw.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
} | java | void generateAntIvyXml(Definition def, String outputDir)
{
try
{
FileWriter antfw = Utils.createFile("build.xml", outputDir);
BuildIvyXmlGen bxGen = new BuildIvyXmlGen();
bxGen.generate(def, antfw);
antfw.close();
FileWriter ivyfw = Utils.createFile("ivy.xml", outputDir);
IvyXmlGen ixGen = new IvyXmlGen();
ixGen.generate(def, ivyfw);
ivyfw.close();
FileWriter ivySettingsfw = Utils.createFile("ivy.settings.xml", outputDir);
IvySettingsXmlGen isxGen = new IvySettingsXmlGen();
isxGen.generate(def, ivySettingsfw);
ivySettingsfw.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
} | [
"void",
"generateAntIvyXml",
"(",
"Definition",
"def",
",",
"String",
"outputDir",
")",
"{",
"try",
"{",
"FileWriter",
"antfw",
"=",
"Utils",
".",
"createFile",
"(",
"\"build.xml\"",
",",
"outputDir",
")",
";",
"BuildIvyXmlGen",
"bxGen",
"=",
"new",
"BuildIvyX... | generate ant + ivy build.xml and ivy files
@param def Definition
@param outputDir output directory | [
"generate",
"ant",
"+",
"ivy",
"build",
".",
"xml",
"and",
"ivy",
"files"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/BaseProfile.java#L358-L381 |
mcxiaoke/Android-Next | core/src/main/java/com/mcxiaoke/next/collection/WeakFastHashMap.java | WeakFastHashMap.putAll | @Override
public void putAll(Map<? extends K, ? extends V> in) {
if (fast) {
synchronized (this) {
Map<K, V> temp = cloneMap(map);
temp.putAll(in);
map = temp;
}
} else {
synchronized (map) {
map.putAll(in);
}
}
} | java | @Override
public void putAll(Map<? extends K, ? extends V> in) {
if (fast) {
synchronized (this) {
Map<K, V> temp = cloneMap(map);
temp.putAll(in);
map = temp;
}
} else {
synchronized (map) {
map.putAll(in);
}
}
} | [
"@",
"Override",
"public",
"void",
"putAll",
"(",
"Map",
"<",
"?",
"extends",
"K",
",",
"?",
"extends",
"V",
">",
"in",
")",
"{",
"if",
"(",
"fast",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"Map",
"<",
"K",
",",
"V",
">",
"temp",
"=",
... | Copy all of the mappings from the specified map to this one, replacing
any mappings with the same keys.
@param in the map whose mappings are to be copied | [
"Copy",
"all",
"of",
"the",
"mappings",
"from",
"the",
"specified",
"map",
"to",
"this",
"one",
"replacing",
"any",
"mappings",
"with",
"the",
"same",
"keys",
"."
] | train | https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/core/src/main/java/com/mcxiaoke/next/collection/WeakFastHashMap.java#L382-L395 |
intendia-oss/rxjava-gwt | src/main/modified/io/reactivex/super/io/reactivex/Flowable.java | Flowable.toMap | @CheckReturnValue
@BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
@SchedulerSupport(SchedulerSupport.NONE)
public final <K, V> Single<Map<K, V>> toMap(final Function<? super T, ? extends K> keySelector, final Function<? super T, ? extends V> valueSelector) {
ObjectHelper.requireNonNull(keySelector, "keySelector is null");
ObjectHelper.requireNonNull(valueSelector, "valueSelector is null");
return collect(HashMapSupplier.<K, V>asCallable(), Functions.toMapKeyValueSelector(keySelector, valueSelector));
} | java | @CheckReturnValue
@BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
@SchedulerSupport(SchedulerSupport.NONE)
public final <K, V> Single<Map<K, V>> toMap(final Function<? super T, ? extends K> keySelector, final Function<? super T, ? extends V> valueSelector) {
ObjectHelper.requireNonNull(keySelector, "keySelector is null");
ObjectHelper.requireNonNull(valueSelector, "valueSelector is null");
return collect(HashMapSupplier.<K, V>asCallable(), Functions.toMapKeyValueSelector(keySelector, valueSelector));
} | [
"@",
"CheckReturnValue",
"@",
"BackpressureSupport",
"(",
"BackpressureKind",
".",
"UNBOUNDED_IN",
")",
"@",
"SchedulerSupport",
"(",
"SchedulerSupport",
".",
"NONE",
")",
"public",
"final",
"<",
"K",
",",
"V",
">",
"Single",
"<",
"Map",
"<",
"K",
",",
"V",
... | Returns a Single that emits a single HashMap containing values corresponding to items emitted by the
finite source Publisher, mapped by the keys returned by a specified {@code keySelector} function.
<p>
<img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toMap.png" alt="">
<p>
If more than one source item maps to the same key, the HashMap will contain a single entry that
corresponds to the latest of those items.
<p>
Note that this operator requires the upstream to signal {@code onComplete} for the accumulated map to
be emitted. Sources that are infinite and never complete will never emit anything through this
operator and an infinite source may lead to a fatal {@code OutOfMemoryError}.
<dl>
<dt><b>Backpressure:</b></dt>
<dd>The operator honors backpressure from downstream and consumes the source {@code Publisher} in an
unbounded manner (i.e., without applying backpressure to it).</dd>
<dt><b>Scheduler:</b></dt>
<dd>{@code toMap} does not operate by default on a particular {@link Scheduler}.</dd>
</dl>
@param <K> the key type of the Map
@param <V> the value type of the Map
@param keySelector
the function that extracts the key from a source item to be used in the HashMap
@param valueSelector
the function that extracts the value from a source item to be used in the HashMap
@return a Single that emits a single item: a HashMap containing the mapped items from the source
Publisher
@see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> | [
"Returns",
"a",
"Single",
"that",
"emits",
"a",
"single",
"HashMap",
"containing",
"values",
"corresponding",
"to",
"items",
"emitted",
"by",
"the",
"finite",
"source",
"Publisher",
"mapped",
"by",
"the",
"keys",
"returned",
"by",
"a",
"specified",
"{",
"@code... | train | https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Flowable.java#L16610-L16617 |
alkacon/opencms-core | src/org/opencms/jsp/search/result/CmsSearchResultWrapper.java | CmsSearchResultWrapper.convertSearchResults | protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) {
m_foundResources = new ArrayList<I_CmsSearchResourceBean>();
for (final CmsSearchResource searchResult : searchResults) {
m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject));
}
} | java | protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) {
m_foundResources = new ArrayList<I_CmsSearchResourceBean>();
for (final CmsSearchResource searchResult : searchResults) {
m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject));
}
} | [
"protected",
"void",
"convertSearchResults",
"(",
"final",
"Collection",
"<",
"CmsSearchResource",
">",
"searchResults",
")",
"{",
"m_foundResources",
"=",
"new",
"ArrayList",
"<",
"I_CmsSearchResourceBean",
">",
"(",
")",
";",
"for",
"(",
"final",
"CmsSearchResourc... | Converts the search results from CmsSearchResource to CmsSearchResourceBean.
@param searchResults The collection of search results to transform. | [
"Converts",
"the",
"search",
"results",
"from",
"CmsSearchResource",
"to",
"CmsSearchResourceBean",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/search/result/CmsSearchResultWrapper.java#L487-L493 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java | MetadataFinder.deliverCacheUpdate | private void deliverCacheUpdate(SlotReference slot, MetadataCache cache) {
for (final MetadataCacheListener listener : getCacheListeners()) {
try {
if (cache == null) {
listener.cacheDetached(slot);
} else {
listener.cacheAttached(slot, cache);
}
} catch (Throwable t) {
logger.warn("Problem delivering metadata cache update to listener", t);
}
}
} | java | private void deliverCacheUpdate(SlotReference slot, MetadataCache cache) {
for (final MetadataCacheListener listener : getCacheListeners()) {
try {
if (cache == null) {
listener.cacheDetached(slot);
} else {
listener.cacheAttached(slot, cache);
}
} catch (Throwable t) {
logger.warn("Problem delivering metadata cache update to listener", t);
}
}
} | [
"private",
"void",
"deliverCacheUpdate",
"(",
"SlotReference",
"slot",
",",
"MetadataCache",
"cache",
")",
"{",
"for",
"(",
"final",
"MetadataCacheListener",
"listener",
":",
"getCacheListeners",
"(",
")",
")",
"{",
"try",
"{",
"if",
"(",
"cache",
"==",
"null"... | Send a metadata cache update announcement to all registered listeners.
@param slot the media slot whose cache status has changed
@param cache the cache which has been attached, or, if {@code null}, the previous cache has been detached | [
"Send",
"a",
"metadata",
"cache",
"update",
"announcement",
"to",
"all",
"registered",
"listeners",
"."
] | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java#L952-L964 |
dwdyer/watchmaker | framework/src/java/main/org/uncommons/watchmaker/framework/operators/StringMutation.java | StringMutation.mutateString | private String mutateString(String s, Random rng)
{
StringBuilder buffer = new StringBuilder(s);
for (int i = 0; i < buffer.length(); i++)
{
if (mutationProbability.nextValue().nextEvent(rng))
{
buffer.setCharAt(i, alphabet[rng.nextInt(alphabet.length)]);
}
}
return buffer.toString();
} | java | private String mutateString(String s, Random rng)
{
StringBuilder buffer = new StringBuilder(s);
for (int i = 0; i < buffer.length(); i++)
{
if (mutationProbability.nextValue().nextEvent(rng))
{
buffer.setCharAt(i, alphabet[rng.nextInt(alphabet.length)]);
}
}
return buffer.toString();
} | [
"private",
"String",
"mutateString",
"(",
"String",
"s",
",",
"Random",
"rng",
")",
"{",
"StringBuilder",
"buffer",
"=",
"new",
"StringBuilder",
"(",
"s",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"buffer",
".",
"length",
"(",
")",
... | Mutate a single string. Zero or more characters may be modified. The
probability of any given character being modified is governed by the
probability generator configured for this mutation operator.
@param s The string to mutate.
@param rng A source of randomness.
@return The mutated string. | [
"Mutate",
"a",
"single",
"string",
".",
"Zero",
"or",
"more",
"characters",
"may",
"be",
"modified",
".",
"The",
"probability",
"of",
"any",
"given",
"character",
"being",
"modified",
"is",
"governed",
"by",
"the",
"probability",
"generator",
"configured",
"fo... | train | https://github.com/dwdyer/watchmaker/blob/33d942350e6bf7d9a17b9262a4f898158530247e/framework/src/java/main/org/uncommons/watchmaker/framework/operators/StringMutation.java#L83-L94 |
qubole/qds-sdk-java | examples/src/main/java/com/qubole/qds/sdk/java/examples/SparkCommandExample.java | SparkCommandExample.submitScalaProgram | private static void submitScalaProgram(QdsClient client) throws Exception {
String sampleProgram = "println(\"hello world\")";
SparkCommandBuilder sparkBuilder = client.command().spark();
// Give a name to the command. (Optional)
sparkBuilder.name("spark-scala-test");
//Setting the program here
sparkBuilder.program(sampleProgram);
//setting the language here
sparkBuilder.language("scala");
CommandResponse commandResponse = sparkBuilder.invoke().get();
ResultLatch resultLatch = new ResultLatch(client, commandResponse.getId());
ResultValue resultValue = resultLatch.awaitResult();
System.out.println(resultValue.getResults());
String s = client.command().logs("" + commandResponse.getId()).invoke().get();
System.err.println(s);
} | java | private static void submitScalaProgram(QdsClient client) throws Exception {
String sampleProgram = "println(\"hello world\")";
SparkCommandBuilder sparkBuilder = client.command().spark();
// Give a name to the command. (Optional)
sparkBuilder.name("spark-scala-test");
//Setting the program here
sparkBuilder.program(sampleProgram);
//setting the language here
sparkBuilder.language("scala");
CommandResponse commandResponse = sparkBuilder.invoke().get();
ResultLatch resultLatch = new ResultLatch(client, commandResponse.getId());
ResultValue resultValue = resultLatch.awaitResult();
System.out.println(resultValue.getResults());
String s = client.command().logs("" + commandResponse.getId()).invoke().get();
System.err.println(s);
} | [
"private",
"static",
"void",
"submitScalaProgram",
"(",
"QdsClient",
"client",
")",
"throws",
"Exception",
"{",
"String",
"sampleProgram",
"=",
"\"println(\\\"hello world\\\")\"",
";",
"SparkCommandBuilder",
"sparkBuilder",
"=",
"client",
".",
"command",
"(",
")",
"."... | An Example of submitting Spark Command as a Scala program.
Similarly, we can submit Spark Command as a SQL query, R program
and Java program. | [
"An",
"Example",
"of",
"submitting",
"Spark",
"Command",
"as",
"a",
"Scala",
"program",
".",
"Similarly",
"we",
"can",
"submit",
"Spark",
"Command",
"as",
"a",
"SQL",
"query",
"R",
"program",
"and",
"Java",
"program",
"."
] | train | https://github.com/qubole/qds-sdk-java/blob/c652374075c7b72071f73db960f5f3a43f922afd/examples/src/main/java/com/qubole/qds/sdk/java/examples/SparkCommandExample.java#L51-L72 |
QSFT/Doradus | doradus-common/src/main/java/com/dell/doradus/management/MBeanProxyFactory.java | MBeanProxyFactory.createStorageManagerProxy | public StorageManagerMXBean createStorageManagerProxy() throws IOException {
String beanName = StorageManagerMXBean.JMX_DOMAIN_NAME + ":type=" + StorageManagerMXBean.JMX_TYPE_NAME;
return createMXBeanProxy(beanName, StorageManagerMXBean.class);
} | java | public StorageManagerMXBean createStorageManagerProxy() throws IOException {
String beanName = StorageManagerMXBean.JMX_DOMAIN_NAME + ":type=" + StorageManagerMXBean.JMX_TYPE_NAME;
return createMXBeanProxy(beanName, StorageManagerMXBean.class);
} | [
"public",
"StorageManagerMXBean",
"createStorageManagerProxy",
"(",
")",
"throws",
"IOException",
"{",
"String",
"beanName",
"=",
"StorageManagerMXBean",
".",
"JMX_DOMAIN_NAME",
"+",
"\":type=\"",
"+",
"StorageManagerMXBean",
".",
"JMX_TYPE_NAME",
";",
"return",
"createMX... | Makes the proxy for StorageManagerMXBean.
@return A StorageManagerMXBean object.
@throws IOException | [
"Makes",
"the",
"proxy",
"for",
"StorageManagerMXBean",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/management/MBeanProxyFactory.java#L89-L92 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/ModeUtils.java | ModeUtils.applyDirectoryUMask | public static Mode applyDirectoryUMask(Mode mode, String authUmask) {
return applyUMask(mode, getUMask(authUmask));
} | java | public static Mode applyDirectoryUMask(Mode mode, String authUmask) {
return applyUMask(mode, getUMask(authUmask));
} | [
"public",
"static",
"Mode",
"applyDirectoryUMask",
"(",
"Mode",
"mode",
",",
"String",
"authUmask",
")",
"{",
"return",
"applyUMask",
"(",
"mode",
",",
"getUMask",
"(",
"authUmask",
")",
")",
";",
"}"
] | Applies the default umask for newly created directories to this mode.
@param mode the mode to update
@param authUmask the umask to apply on the directory
@return the updated object | [
"Applies",
"the",
"default",
"umask",
"for",
"newly",
"created",
"directories",
"to",
"this",
"mode",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/ModeUtils.java#L52-L54 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/storage/SimpleDOWriter.java | SimpleDOWriter.addDatastream | public void addDatastream(Datastream datastream, boolean addNewVersion)
throws ServerException {
assertNotInvalidated();
assertNotPendingRemoval();
// use this call to handle versionable
m_obj.addDatastreamVersion(datastream, addNewVersion);
} | java | public void addDatastream(Datastream datastream, boolean addNewVersion)
throws ServerException {
assertNotInvalidated();
assertNotPendingRemoval();
// use this call to handle versionable
m_obj.addDatastreamVersion(datastream, addNewVersion);
} | [
"public",
"void",
"addDatastream",
"(",
"Datastream",
"datastream",
",",
"boolean",
"addNewVersion",
")",
"throws",
"ServerException",
"{",
"assertNotInvalidated",
"(",
")",
";",
"assertNotPendingRemoval",
"(",
")",
";",
"// use this call to handle versionable",
"m_obj",
... | Adds a datastream to the object.
@param datastream
The datastream.
@throws ServerException
If any type of error occurred fulfilling the request. | [
"Adds",
"a",
"datastream",
"to",
"the",
"object",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/storage/SimpleDOWriter.java#L167-L173 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/json/JsonWrite.java | JsonWrite.writeGeoJson | public static void writeGeoJson(Connection connection, String fileName, String tableReference, String encoding) throws IOException, SQLException {
JsonDriverFunction jsonDriver = new JsonDriverFunction();
jsonDriver.exportTable(connection,tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor(),encoding);
} | java | public static void writeGeoJson(Connection connection, String fileName, String tableReference, String encoding) throws IOException, SQLException {
JsonDriverFunction jsonDriver = new JsonDriverFunction();
jsonDriver.exportTable(connection,tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor(),encoding);
} | [
"public",
"static",
"void",
"writeGeoJson",
"(",
"Connection",
"connection",
",",
"String",
"fileName",
",",
"String",
"tableReference",
",",
"String",
"encoding",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"JsonDriverFunction",
"jsonDriver",
"=",
"new"... | Write the JSON file.
@param connection
@param fileName
@param tableReference
@param encoding
@throws IOException
@throws SQLException | [
"Write",
"the",
"JSON",
"file",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/json/JsonWrite.java#L57-L60 |
Blazebit/blaze-utils | blaze-common-utils/src/main/java/com/blazebit/reflection/ReflectionUtils.java | ReflectionUtils.resolveTypeVariable | public static Class<?> resolveTypeVariable(Class<?> concreteClass, TypeVariable<?> typeVariable) {
Type resolvedType = resolveTypeVariableType(concreteClass, typeVariable);
return resolveType(concreteClass, resolvedType);
} | java | public static Class<?> resolveTypeVariable(Class<?> concreteClass, TypeVariable<?> typeVariable) {
Type resolvedType = resolveTypeVariableType(concreteClass, typeVariable);
return resolveType(concreteClass, resolvedType);
} | [
"public",
"static",
"Class",
"<",
"?",
">",
"resolveTypeVariable",
"(",
"Class",
"<",
"?",
">",
"concreteClass",
",",
"TypeVariable",
"<",
"?",
">",
"typeVariable",
")",
"{",
"Type",
"resolvedType",
"=",
"resolveTypeVariableType",
"(",
"concreteClass",
",",
"t... | Tries to resolve the type variable against the concrete class. The
concrete class has to be a subtype of the type in which the type variable
has been declared. This method tries to resolve the given type variable
by inspecting the subclasses of the class in which the type variable was
declared and as soon as the resolved type is instance of java.lang.Class
it stops and returns that class.
@param concreteClass The class which is used to resolve the type. The type for the
type variable must be bound in this class or a superclass.
@param typeVariable The type variable to resolve.
@return The resolved type as class
@throws IllegalArgumentException Is thrown when the concrete class is not a subtype of the
class in which the type variable has been declared. | [
"Tries",
"to",
"resolve",
"the",
"type",
"variable",
"against",
"the",
"concrete",
"class",
".",
"The",
"concrete",
"class",
"has",
"to",
"be",
"a",
"subtype",
"of",
"the",
"type",
"in",
"which",
"the",
"type",
"variable",
"has",
"been",
"declared",
".",
... | train | https://github.com/Blazebit/blaze-utils/blob/3e35a694a8f71d515aad066196acd523994d6aaa/blaze-common-utils/src/main/java/com/blazebit/reflection/ReflectionUtils.java#L462-L465 |
google/closure-compiler | src/com/google/javascript/jscomp/gwt/linker/MinimalLinker.java | MinimalLinker.formatOutput | private static String formatOutput(String js, boolean export) {
StringBuilder output = new StringBuilder();
// Shadow window so that non-browser environments can pass their own global object here.
output.append("(function(window){");
// If $wnd is set to this, then JSInterop's normal export will run, and pollute the global
// namespace. If export is false, fake out $wnd with an empty object.
// (We also add Error to work around StackTraceCreator using it in a static block).
output.append("var $wnd=").append(export ? "this" : "{'Error':{}}").append(";");
// Shadow $doc, $moduleName and $moduleBase.
output.append("var $doc={},$moduleName,$moduleBase;");
// Append output JS.
output.append(js);
// 1. Export $gwtExport, needed for transpile.js
// 2. Reset $wnd (nb. this occurs after jscompiler's JS has run)
// 3. Call gwtOnLoad, if defined: this invokes onModuleLoad for all loaded modules.
output.append("this['$gwtExport']=$wnd;$wnd=this;typeof gwtOnLoad==='function'&&gwtOnLoad()");
// Overspecify the global object, to capture Node and browser environments.
String globalObject = "this&&this.self||"
+ "(typeof window!=='undefined'?window:(typeof global!=='undefined'?global:this))";
// Call the outer function with the global object as this and its first argument, so that we
// fake window in Node environments, allowing our code to do things like "window.console(...)".
output.append("}).call(").append(globalObject).append(",").append(globalObject).append(");");
return output.toString();
} | java | private static String formatOutput(String js, boolean export) {
StringBuilder output = new StringBuilder();
// Shadow window so that non-browser environments can pass their own global object here.
output.append("(function(window){");
// If $wnd is set to this, then JSInterop's normal export will run, and pollute the global
// namespace. If export is false, fake out $wnd with an empty object.
// (We also add Error to work around StackTraceCreator using it in a static block).
output.append("var $wnd=").append(export ? "this" : "{'Error':{}}").append(";");
// Shadow $doc, $moduleName and $moduleBase.
output.append("var $doc={},$moduleName,$moduleBase;");
// Append output JS.
output.append(js);
// 1. Export $gwtExport, needed for transpile.js
// 2. Reset $wnd (nb. this occurs after jscompiler's JS has run)
// 3. Call gwtOnLoad, if defined: this invokes onModuleLoad for all loaded modules.
output.append("this['$gwtExport']=$wnd;$wnd=this;typeof gwtOnLoad==='function'&&gwtOnLoad()");
// Overspecify the global object, to capture Node and browser environments.
String globalObject = "this&&this.self||"
+ "(typeof window!=='undefined'?window:(typeof global!=='undefined'?global:this))";
// Call the outer function with the global object as this and its first argument, so that we
// fake window in Node environments, allowing our code to do things like "window.console(...)".
output.append("}).call(").append(globalObject).append(",").append(globalObject).append(");");
return output.toString();
} | [
"private",
"static",
"String",
"formatOutput",
"(",
"String",
"js",
",",
"boolean",
"export",
")",
"{",
"StringBuilder",
"output",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"// Shadow window so that non-browser environments can pass their own global object here.",
"output... | Formats the application's JS code for output.
@param js Code to format.
@param export Whether to export via JSInterop.
@return Formatted, linked code. | [
"Formats",
"the",
"application",
"s",
"JS",
"code",
"for",
"output",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/gwt/linker/MinimalLinker.java#L67-L98 |
phax/ph-commons | ph-cli/src/main/java/com/helger/cli/HelpFormatter.java | HelpFormatter.printUsage | public void printUsage (@Nonnull final PrintWriter aPW,
final int nWidth,
final String sAppName,
final Options aOptions)
{
// initialise the string buffer
final StringBuilder aSB = new StringBuilder (getSyntaxPrefix ()).append (sAppName).append (' ');
// create a list for processed option groups
final ICommonsSet <OptionGroup> aProcessedGroups = new CommonsHashSet <> ();
final ICommonsList <Option> aOptList = aOptions.getAllResolvedOptions ();
if (m_aOptionComparator != null)
aOptList.sort (m_aOptionComparator);
// iterate over the options
for (final Iterator <Option> aIt = aOptList.iterator (); aIt.hasNext ();)
{
// get the next Option
final Option aOption = aIt.next ();
// check if the option is part of an OptionGroup
final OptionGroup group = aOptions.getOptionGroup (aOption);
// if the option is part of a group
if (group != null)
{
// and if the group has not already been processed
if (aProcessedGroups.add (group))
{
// add the usage clause
_appendOptionGroup (aSB, group);
}
// otherwise the option was displayed in the group
// previously so ignore it.
}
else
{
// if the Option is not part of an OptionGroup
_appendOption (aSB, aOption, aOption.isRequired ());
}
if (aIt.hasNext ())
aSB.append (' ');
}
// call printWrapped
printWrapped (aPW, nWidth, aSB.toString ().indexOf (' ') + 1, aSB.toString ());
} | java | public void printUsage (@Nonnull final PrintWriter aPW,
final int nWidth,
final String sAppName,
final Options aOptions)
{
// initialise the string buffer
final StringBuilder aSB = new StringBuilder (getSyntaxPrefix ()).append (sAppName).append (' ');
// create a list for processed option groups
final ICommonsSet <OptionGroup> aProcessedGroups = new CommonsHashSet <> ();
final ICommonsList <Option> aOptList = aOptions.getAllResolvedOptions ();
if (m_aOptionComparator != null)
aOptList.sort (m_aOptionComparator);
// iterate over the options
for (final Iterator <Option> aIt = aOptList.iterator (); aIt.hasNext ();)
{
// get the next Option
final Option aOption = aIt.next ();
// check if the option is part of an OptionGroup
final OptionGroup group = aOptions.getOptionGroup (aOption);
// if the option is part of a group
if (group != null)
{
// and if the group has not already been processed
if (aProcessedGroups.add (group))
{
// add the usage clause
_appendOptionGroup (aSB, group);
}
// otherwise the option was displayed in the group
// previously so ignore it.
}
else
{
// if the Option is not part of an OptionGroup
_appendOption (aSB, aOption, aOption.isRequired ());
}
if (aIt.hasNext ())
aSB.append (' ');
}
// call printWrapped
printWrapped (aPW, nWidth, aSB.toString ().indexOf (' ') + 1, aSB.toString ());
} | [
"public",
"void",
"printUsage",
"(",
"@",
"Nonnull",
"final",
"PrintWriter",
"aPW",
",",
"final",
"int",
"nWidth",
",",
"final",
"String",
"sAppName",
",",
"final",
"Options",
"aOptions",
")",
"{",
"// initialise the string buffer",
"final",
"StringBuilder",
"aSB"... | Prints the usage statement for the specified application.
@param aPW
The PrintWriter to print the usage statement
@param nWidth
The number of characters to display per line
@param sAppName
The application name
@param aOptions
The command line Options | [
"Prints",
"the",
"usage",
"statement",
"for",
"the",
"specified",
"application",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-cli/src/main/java/com/helger/cli/HelpFormatter.java#L626-L675 |
mongodb/stitch-android-sdk | core/sdk/src/main/java/com/mongodb/stitch/core/auth/internal/CoreStitchAuth.java | CoreStitchAuth.doAuthenticatedRequest | public <T> T doAuthenticatedRequest(final StitchAuthRequest stitchReq,
final Decoder<T> resultDecoder) {
final Response response = doAuthenticatedRequest(stitchReq);
try {
final String bodyStr = IoUtils.readAllToString(response.getBody());
final JsonReader bsonReader = new JsonReader(bodyStr);
// We must check this condition because the decoder will throw trying to decode null
if (bsonReader.readBsonType() == BsonType.NULL) {
return null;
}
return resultDecoder.decode(bsonReader, DecoderContext.builder().build());
} catch (final Exception e) {
throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR);
}
} | java | public <T> T doAuthenticatedRequest(final StitchAuthRequest stitchReq,
final Decoder<T> resultDecoder) {
final Response response = doAuthenticatedRequest(stitchReq);
try {
final String bodyStr = IoUtils.readAllToString(response.getBody());
final JsonReader bsonReader = new JsonReader(bodyStr);
// We must check this condition because the decoder will throw trying to decode null
if (bsonReader.readBsonType() == BsonType.NULL) {
return null;
}
return resultDecoder.decode(bsonReader, DecoderContext.builder().build());
} catch (final Exception e) {
throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR);
}
} | [
"public",
"<",
"T",
">",
"T",
"doAuthenticatedRequest",
"(",
"final",
"StitchAuthRequest",
"stitchReq",
",",
"final",
"Decoder",
"<",
"T",
">",
"resultDecoder",
")",
"{",
"final",
"Response",
"response",
"=",
"doAuthenticatedRequest",
"(",
"stitchReq",
")",
";",... | Performs a request against Stitch using the provided {@link StitchAuthRequest} object,
and decodes the response using the provided result decoder.
@param stitchReq The request to perform.
@return The response to the request, successful or not. | [
"Performs",
"a",
"request",
"against",
"Stitch",
"using",
"the",
"provided",
"{",
"@link",
"StitchAuthRequest",
"}",
"object",
"and",
"decodes",
"the",
"response",
"using",
"the",
"provided",
"result",
"decoder",
"."
] | train | https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/sdk/src/main/java/com/mongodb/stitch/core/auth/internal/CoreStitchAuth.java#L252-L267 |
kohsuke/args4j | args4j/src/org/kohsuke/args4j/spi/MapOptionHandler.java | MapOptionHandler.addToMap | protected void addToMap(Map m, String key, String value) {
m.put(key,value);
} | java | protected void addToMap(Map m, String key, String value) {
m.put(key,value);
} | [
"protected",
"void",
"addToMap",
"(",
"Map",
"m",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"m",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}"
] | This is the opportunity to convert values to some typed objects. | [
"This",
"is",
"the",
"opportunity",
"to",
"convert",
"values",
"to",
"some",
"typed",
"objects",
"."
] | train | https://github.com/kohsuke/args4j/blob/dc2e7e265caf15a1a146e3389c1f16a8781f06cf/args4j/src/org/kohsuke/args4j/spi/MapOptionHandler.java#L91-L93 |
google/closure-compiler | src/com/google/javascript/jscomp/AstFactory.java | AstFactory.createJSCompMakeAsyncIteratorCall | Node createJSCompMakeAsyncIteratorCall(Node iterable, Scope scope) {
Node makeIteratorAsyncName = createQName(scope, "$jscomp.makeAsyncIterator");
// Since createCall (currently) doesn't handle templated functions, fill in the template types
// of makeIteratorName manually.
if (isAddingTypes() && !makeIteratorAsyncName.getJSType().isUnknownType()) {
// if makeIteratorName has the unknown type, we must have not injected the required runtime
// libraries - hopefully because this is in a test using NonInjectingCompiler.
// e.g get `number` from `AsyncIterable<number>`
JSType asyncIterableType =
JsIterables.maybeBoxIterableOrAsyncIterable(iterable.getJSType(), registry)
.orElse(unknownType);
JSType makeAsyncIteratorType = makeIteratorAsyncName.getJSType();
// e.g. replace
// function(AsyncIterable<T>): AsyncIterator<T>
// with
// function(AsyncIterable<number>): AsyncIterator<number>
TemplateTypeMap typeMap =
registry.createTemplateTypeMap(
makeAsyncIteratorType.getTemplateTypeMap().getTemplateKeys(),
ImmutableList.of(asyncIterableType));
TemplateTypeMapReplacer replacer = new TemplateTypeMapReplacer(registry, typeMap);
makeIteratorAsyncName.setJSType(makeAsyncIteratorType.visit(replacer));
}
return createCall(makeIteratorAsyncName, iterable);
} | java | Node createJSCompMakeAsyncIteratorCall(Node iterable, Scope scope) {
Node makeIteratorAsyncName = createQName(scope, "$jscomp.makeAsyncIterator");
// Since createCall (currently) doesn't handle templated functions, fill in the template types
// of makeIteratorName manually.
if (isAddingTypes() && !makeIteratorAsyncName.getJSType().isUnknownType()) {
// if makeIteratorName has the unknown type, we must have not injected the required runtime
// libraries - hopefully because this is in a test using NonInjectingCompiler.
// e.g get `number` from `AsyncIterable<number>`
JSType asyncIterableType =
JsIterables.maybeBoxIterableOrAsyncIterable(iterable.getJSType(), registry)
.orElse(unknownType);
JSType makeAsyncIteratorType = makeIteratorAsyncName.getJSType();
// e.g. replace
// function(AsyncIterable<T>): AsyncIterator<T>
// with
// function(AsyncIterable<number>): AsyncIterator<number>
TemplateTypeMap typeMap =
registry.createTemplateTypeMap(
makeAsyncIteratorType.getTemplateTypeMap().getTemplateKeys(),
ImmutableList.of(asyncIterableType));
TemplateTypeMapReplacer replacer = new TemplateTypeMapReplacer(registry, typeMap);
makeIteratorAsyncName.setJSType(makeAsyncIteratorType.visit(replacer));
}
return createCall(makeIteratorAsyncName, iterable);
} | [
"Node",
"createJSCompMakeAsyncIteratorCall",
"(",
"Node",
"iterable",
",",
"Scope",
"scope",
")",
"{",
"Node",
"makeIteratorAsyncName",
"=",
"createQName",
"(",
"scope",
",",
"\"$jscomp.makeAsyncIterator\"",
")",
";",
"// Since createCall (currently) doesn't handle templated ... | Given an iterable like {@code rhs} in
<pre>{@code
for await (lhs of rhs) { block(); }
}</pre>
<p>returns a call node for the {@code rhs} wrapped in a {@code $jscomp.makeAsyncIterator} call.
<pre>{@code
$jscomp.makeAsyncIterator(rhs)
}</pre> | [
"Given",
"an",
"iterable",
"like",
"{",
"@code",
"rhs",
"}",
"in"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L861-L886 |
dkmfbk/knowledgestore | ks-server-hbase/src/main/java/eu/fbk/knowledgestore/datastore/hbase/HBaseDataStore.java | HBaseDataStore.checkAndCreateTable | private void checkAndCreateTable(final String tabName, final String colFamName)
throws IOException
{
hbaseUtils.checkAndCreateTable(tabName, colFamName);
} | java | private void checkAndCreateTable(final String tabName, final String colFamName)
throws IOException
{
hbaseUtils.checkAndCreateTable(tabName, colFamName);
} | [
"private",
"void",
"checkAndCreateTable",
"(",
"final",
"String",
"tabName",
",",
"final",
"String",
"colFamName",
")",
"throws",
"IOException",
"{",
"hbaseUtils",
".",
"checkAndCreateTable",
"(",
"tabName",
",",
"colFamName",
")",
";",
"}"
] | Verifies the existence of tables.
@param tableName to be verified
@param columnFamilyName of the table
@throws IOException | [
"Verifies",
"the",
"existence",
"of",
"tables",
"."
] | train | https://github.com/dkmfbk/knowledgestore/blob/a548101b1dd67fcf72a1ec6f838ea7539bdbbe7a/ks-server-hbase/src/main/java/eu/fbk/knowledgestore/datastore/hbase/HBaseDataStore.java#L132-L136 |
carewebframework/carewebframework-vista | org.carewebframework.vista.api-parent/org.carewebframework.vista.api.core/src/main/java/org/carewebframework/vista/api/property/PropertyCollection.java | PropertyCollection.getValue | public String getValue(String name, String dflt) {
Property prop = getProperty(name);
return prop == null ? dflt : prop.getValue();
} | java | public String getValue(String name, String dflt) {
Property prop = getProperty(name);
return prop == null ? dflt : prop.getValue();
} | [
"public",
"String",
"getValue",
"(",
"String",
"name",
",",
"String",
"dflt",
")",
"{",
"Property",
"prop",
"=",
"getProperty",
"(",
"name",
")",
";",
"return",
"prop",
"==",
"null",
"?",
"dflt",
":",
"prop",
".",
"getValue",
"(",
")",
";",
"}"
] | Returns a string property value.
@param name Property name.
@param dflt Default value if a property value is not found.
@return Property value or default value if property value not found. | [
"Returns",
"a",
"string",
"property",
"value",
"."
] | train | https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.api-parent/org.carewebframework.vista.api.core/src/main/java/org/carewebframework/vista/api/property/PropertyCollection.java#L177-L180 |
amaembo/streamex | src/main/java/one/util/streamex/StreamEx.java | StreamEx.ofTree | @SuppressWarnings("unchecked")
public static <T, TT extends T> StreamEx<T> ofTree(T root, Class<TT> collectionClass, Function<TT, Stream<T>> mapper) {
return ofTree(root, t -> collectionClass.isInstance(t) ? mapper.apply((TT) t) : null);
} | java | @SuppressWarnings("unchecked")
public static <T, TT extends T> StreamEx<T> ofTree(T root, Class<TT> collectionClass, Function<TT, Stream<T>> mapper) {
return ofTree(root, t -> collectionClass.isInstance(t) ? mapper.apply((TT) t) : null);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
",",
"TT",
"extends",
"T",
">",
"StreamEx",
"<",
"T",
">",
"ofTree",
"(",
"T",
"root",
",",
"Class",
"<",
"TT",
">",
"collectionClass",
",",
"Function",
"<",
"TT",
",",
... | Return a new {@link StreamEx} containing all the nodes of tree-like data
structure in depth-first order.
<p>
The streams created by mapper may be automatically
{@link java.util.stream.BaseStream#close() closed} after its contents
already consumed and unnecessary anymore. It's not guaranteed that all
created streams will be closed during the stream terminal operation. If
it's necessary to close all the created streams, call the {@code close()}
method of the resulting stream returned by {@code ofTree()}.
@param <T> the base type of tree nodes
@param <TT> the sub-type of composite tree nodes which may have children
@param root root node of the tree
@param collectionClass a class representing the composite tree node
@param mapper a non-interfering, stateless function to apply to each
composite tree node which returns stream of direct children. May
return null if the given node has no children.
@return the new sequential ordered stream
@since 0.2.2
@see EntryStream#ofTree(Object, Class, BiFunction)
@see #ofTree(Object, Function) | [
"Return",
"a",
"new",
"{",
"@link",
"StreamEx",
"}",
"containing",
"all",
"the",
"nodes",
"of",
"tree",
"-",
"like",
"data",
"structure",
"in",
"depth",
"-",
"first",
"order",
"."
] | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L2993-L2996 |
elvishew/xLog | sample/src/main/java/com/elvishew/xlogsample/MainActivity.java | MainActivity.showChangeTagDialog | private void showChangeTagDialog() {
View view = getLayoutInflater().inflate(R.layout.dialog_change_tag, null, false);
final EditText tagEditText = (EditText) view.findViewById(R.id.tag);
tagEditText.setText(tagView.getText());
new AlertDialog.Builder(this)
.setTitle(R.string.change_tag)
.setView(view)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String tag = tagEditText.getText().toString().trim();
if (!tag.isEmpty()) {
tagView.setText(tag);
}
}
})
.show();
} | java | private void showChangeTagDialog() {
View view = getLayoutInflater().inflate(R.layout.dialog_change_tag, null, false);
final EditText tagEditText = (EditText) view.findViewById(R.id.tag);
tagEditText.setText(tagView.getText());
new AlertDialog.Builder(this)
.setTitle(R.string.change_tag)
.setView(view)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String tag = tagEditText.getText().toString().trim();
if (!tag.isEmpty()) {
tagView.setText(tag);
}
}
})
.show();
} | [
"private",
"void",
"showChangeTagDialog",
"(",
")",
"{",
"View",
"view",
"=",
"getLayoutInflater",
"(",
")",
".",
"inflate",
"(",
"R",
".",
"layout",
".",
"dialog_change_tag",
",",
"null",
",",
"false",
")",
";",
"final",
"EditText",
"tagEditText",
"=",
"(... | Show a dialog for user to change the tag, empty text is not allowed. | [
"Show",
"a",
"dialog",
"for",
"user",
"to",
"change",
"the",
"tag",
"empty",
"text",
"is",
"not",
"allowed",
"."
] | train | https://github.com/elvishew/xLog/blob/c6fb95555ce619d3e527f5ba6c45d4d247c5a838/sample/src/main/java/com/elvishew/xlogsample/MainActivity.java#L223-L242 |
radkovo/SwingBox | src/main/java/org/fit/cssbox/swingbox/view/DelegateView.java | DelegateView.setSize | @Override
public void setSize(float width, float height)
{
if (view != null)
{
view.setSize(width, height);
}
} | java | @Override
public void setSize(float width, float height)
{
if (view != null)
{
view.setSize(width, height);
}
} | [
"@",
"Override",
"public",
"void",
"setSize",
"(",
"float",
"width",
",",
"float",
"height",
")",
"{",
"if",
"(",
"view",
"!=",
"null",
")",
"{",
"view",
".",
"setSize",
"(",
"width",
",",
"height",
")",
";",
"}",
"}"
] | Sets the view size.
@param width
the width
@param height
the height | [
"Sets",
"the",
"view",
"size",
"."
] | train | https://github.com/radkovo/SwingBox/blob/ff370f3dc54d248e4c8852c17513618c83c25984/src/main/java/org/fit/cssbox/swingbox/view/DelegateView.java#L523-L530 |
alkacon/opencms-core | src/org/opencms/webdav/CmsWebdavServlet.java | CmsWebdavServlet.sendReport | private void sendReport(HttpServletRequest req, HttpServletResponse resp, Map<String, Integer> errors)
throws IOException {
resp.setStatus(CmsWebdavStatus.SC_MULTI_STATUS);
String absoluteUri = req.getRequestURI();
String relativePath = getRelativePath(req);
Document doc = DocumentHelper.createDocument();
Element multiStatusElem = doc.addElement(new QName(TAG_MULTISTATUS, Namespace.get(DEFAULT_NAMESPACE)));
Iterator<Entry<String, Integer>> it = errors.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Integer> e = it.next();
String errorPath = e.getKey();
int errorCode = e.getValue().intValue();
Element responseElem = addElement(multiStatusElem, TAG_RESPONSE);
String toAppend = errorPath.substring(relativePath.length());
if (!toAppend.startsWith("/")) {
toAppend = "/" + toAppend;
}
addElement(responseElem, TAG_HREF).addText(absoluteUri + toAppend);
addElement(responseElem, TAG_STATUS).addText(
"HTTP/1.1 " + errorCode + " " + CmsWebdavStatus.getStatusText(errorCode));
}
Writer writer = resp.getWriter();
doc.write(writer);
writer.close();
} | java | private void sendReport(HttpServletRequest req, HttpServletResponse resp, Map<String, Integer> errors)
throws IOException {
resp.setStatus(CmsWebdavStatus.SC_MULTI_STATUS);
String absoluteUri = req.getRequestURI();
String relativePath = getRelativePath(req);
Document doc = DocumentHelper.createDocument();
Element multiStatusElem = doc.addElement(new QName(TAG_MULTISTATUS, Namespace.get(DEFAULT_NAMESPACE)));
Iterator<Entry<String, Integer>> it = errors.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Integer> e = it.next();
String errorPath = e.getKey();
int errorCode = e.getValue().intValue();
Element responseElem = addElement(multiStatusElem, TAG_RESPONSE);
String toAppend = errorPath.substring(relativePath.length());
if (!toAppend.startsWith("/")) {
toAppend = "/" + toAppend;
}
addElement(responseElem, TAG_HREF).addText(absoluteUri + toAppend);
addElement(responseElem, TAG_STATUS).addText(
"HTTP/1.1 " + errorCode + " " + CmsWebdavStatus.getStatusText(errorCode));
}
Writer writer = resp.getWriter();
doc.write(writer);
writer.close();
} | [
"private",
"void",
"sendReport",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"Map",
"<",
"String",
",",
"Integer",
">",
"errors",
")",
"throws",
"IOException",
"{",
"resp",
".",
"setStatus",
"(",
"CmsWebdavStatus",
".",
"SC_MULTI_S... | Send a multistatus element containing a complete error report to the
client.<p>
@param req the servlet request we are processing
@param resp the servlet response we are processing
@param errors the errors to be displayed
@throws IOException if errors while writing to response occurs | [
"Send",
"a",
"multistatus",
"element",
"containing",
"a",
"complete",
"error",
"report",
"to",
"the",
"client",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/webdav/CmsWebdavServlet.java#L3584-L3615 |
hageldave/ImagingKit | ImagingKit_Core/src/main/java/hageldave/imagingkit/core/Pixel.java | Pixel.setARGB | public void setARGB(int a, int r, int g, int b){
setValue(Pixel.argb(a, r, g, b));
} | java | public void setARGB(int a, int r, int g, int b){
setValue(Pixel.argb(a, r, g, b));
} | [
"public",
"void",
"setARGB",
"(",
"int",
"a",
",",
"int",
"r",
",",
"int",
"g",
",",
"int",
"b",
")",
"{",
"setValue",
"(",
"Pixel",
".",
"argb",
"(",
"a",
",",
"r",
",",
"g",
",",
"b",
")",
")",
";",
"}"
] | Sets an ARGB value at the position currently referenced by this Pixel.
Each channel value is assumed to be 8bit and otherwise truncated.
@param a alpha
@param r red
@param g green
@param b blue
@throws ArrayIndexOutOfBoundsException if this Pixel's index is not in
range of the Img's data array.
@see #setRGB(int, int, int)
@see #setRGB_preserveAlpha(int, int, int)
@see #argb(int, int, int, int)
@see #argb_bounded(int, int, int, int)
@see #argb_fast(int, int, int, int)
@see #setValue(int)
@since 1.0 | [
"Sets",
"an",
"ARGB",
"value",
"at",
"the",
"position",
"currently",
"referenced",
"by",
"this",
"Pixel",
".",
"Each",
"channel",
"value",
"is",
"assumed",
"to",
"be",
"8bit",
"and",
"otherwise",
"truncated",
"."
] | train | https://github.com/hageldave/ImagingKit/blob/3837c7d550a12cf4dc5718b644ced94b97f52668/ImagingKit_Core/src/main/java/hageldave/imagingkit/core/Pixel.java#L346-L348 |
lessthanoptimal/BoofCV | integration/boofcv-swing/src/main/java/boofcv/gui/binary/VisualizeBinaryData.java | VisualizeBinaryData.renderBinary | public static BufferedImage renderBinary(GrayU8 binaryImage, boolean invert, BufferedImage out) {
if( out == null || ( out.getWidth() != binaryImage.width || out.getHeight() != binaryImage.height) ) {
out = new BufferedImage(binaryImage.getWidth(),binaryImage.getHeight(),BufferedImage.TYPE_BYTE_GRAY);
}
try {
WritableRaster raster = out.getRaster();
DataBuffer buffer = raster.getDataBuffer();
if( buffer.getDataType() == DataBuffer.TYPE_BYTE ) {
renderBinary(binaryImage, invert, (DataBufferByte)buffer, raster);
} else if( buffer.getDataType() == DataBuffer.TYPE_INT ) {
renderBinary(binaryImage, invert, (DataBufferInt)buffer, raster);
} else {
_renderBinary(binaryImage, invert, out);
}
} catch( SecurityException e ) {
_renderBinary(binaryImage, invert, out);
}
// hack so that it knows the buffer has been modified
out.setRGB(0,0,out.getRGB(0,0));
return out;
} | java | public static BufferedImage renderBinary(GrayU8 binaryImage, boolean invert, BufferedImage out) {
if( out == null || ( out.getWidth() != binaryImage.width || out.getHeight() != binaryImage.height) ) {
out = new BufferedImage(binaryImage.getWidth(),binaryImage.getHeight(),BufferedImage.TYPE_BYTE_GRAY);
}
try {
WritableRaster raster = out.getRaster();
DataBuffer buffer = raster.getDataBuffer();
if( buffer.getDataType() == DataBuffer.TYPE_BYTE ) {
renderBinary(binaryImage, invert, (DataBufferByte)buffer, raster);
} else if( buffer.getDataType() == DataBuffer.TYPE_INT ) {
renderBinary(binaryImage, invert, (DataBufferInt)buffer, raster);
} else {
_renderBinary(binaryImage, invert, out);
}
} catch( SecurityException e ) {
_renderBinary(binaryImage, invert, out);
}
// hack so that it knows the buffer has been modified
out.setRGB(0,0,out.getRGB(0,0));
return out;
} | [
"public",
"static",
"BufferedImage",
"renderBinary",
"(",
"GrayU8",
"binaryImage",
",",
"boolean",
"invert",
",",
"BufferedImage",
"out",
")",
"{",
"if",
"(",
"out",
"==",
"null",
"||",
"(",
"out",
".",
"getWidth",
"(",
")",
"!=",
"binaryImage",
".",
"widt... | Renders a binary image. 0 = black and 1 = white.
@param binaryImage (Input) Input binary image.
@param invert (Input) if true it will invert the image on output
@param out (Output) optional storage for output image
@return Output rendered binary image | [
"Renders",
"a",
"binary",
"image",
".",
"0",
"=",
"black",
"and",
"1",
"=",
"white",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-swing/src/main/java/boofcv/gui/binary/VisualizeBinaryData.java#L382-L404 |
iig-uni-freiburg/SEWOL | ext/org/deckfour/xes/info/impl/XLogInfoImpl.java | XLogInfoImpl.registerAttributes | protected void registerAttributes(XAttributeInfoImpl attributeInfo, XAttributable attributable) {
if (attributable.hasAttributes()) {
for(XAttribute attribute : attributable.getAttributes().values()) {
// register attribute in appropriate map
attributeInfo.register(attribute);
// register meta-attributes globally
registerAttributes(metaAttributeInfo, attribute);
}
}
} | java | protected void registerAttributes(XAttributeInfoImpl attributeInfo, XAttributable attributable) {
if (attributable.hasAttributes()) {
for(XAttribute attribute : attributable.getAttributes().values()) {
// register attribute in appropriate map
attributeInfo.register(attribute);
// register meta-attributes globally
registerAttributes(metaAttributeInfo, attribute);
}
}
} | [
"protected",
"void",
"registerAttributes",
"(",
"XAttributeInfoImpl",
"attributeInfo",
",",
"XAttributable",
"attributable",
")",
"{",
"if",
"(",
"attributable",
".",
"hasAttributes",
"(",
")",
")",
"{",
"for",
"(",
"XAttribute",
"attribute",
":",
"attributable",
... | Registers all attributes of a given attributable, i.e.
model type hierarchy element, in the given attribute info registry.
@param attributeInfo Attribute info registry to use for registration.
@param attributable Attributable whose attributes to register. | [
"Registers",
"all",
"attributes",
"of",
"a",
"given",
"attributable",
"i",
".",
"e",
".",
"model",
"type",
"hierarchy",
"element",
"in",
"the",
"given",
"attribute",
"info",
"registry",
"."
] | train | https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/info/impl/XLogInfoImpl.java#L262-L271 |
JadiraOrg/jadira | cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java | UnsafeOperations.putShort | public final void putShort(Object parent, long offset, short value) {
THE_UNSAFE.putShort(parent, offset, value);
} | java | public final void putShort(Object parent, long offset, short value) {
THE_UNSAFE.putShort(parent, offset, value);
} | [
"public",
"final",
"void",
"putShort",
"(",
"Object",
"parent",
",",
"long",
"offset",
",",
"short",
"value",
")",
"{",
"THE_UNSAFE",
".",
"putShort",
"(",
"parent",
",",
"offset",
",",
"value",
")",
";",
"}"
] | Puts the value at the given offset of the supplied parent object
@param parent The Object's parent
@param offset The offset
@param value short to be put | [
"Puts",
"the",
"value",
"at",
"the",
"given",
"offset",
"of",
"the",
"supplied",
"parent",
"object"
] | train | https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java#L973-L975 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/math/RoundHelper.java | RoundHelper.getRoundedUpFix | public static double getRoundedUpFix (final double dValue, @Nonnegative final int nScale)
{
return getRounded (dValue, nScale, RoundingMode.HALF_UP, EDecimalType.FIX);
} | java | public static double getRoundedUpFix (final double dValue, @Nonnegative final int nScale)
{
return getRounded (dValue, nScale, RoundingMode.HALF_UP, EDecimalType.FIX);
} | [
"public",
"static",
"double",
"getRoundedUpFix",
"(",
"final",
"double",
"dValue",
",",
"@",
"Nonnegative",
"final",
"int",
"nScale",
")",
"{",
"return",
"getRounded",
"(",
"dValue",
",",
"nScale",
",",
"RoundingMode",
".",
"HALF_UP",
",",
"EDecimalType",
".",... | Round using the {@link RoundingMode#HALF_UP} mode and fix representation
@param dValue
The value to be rounded
@param nScale
The precision scale
@return the rounded value | [
"Round",
"using",
"the",
"{",
"@link",
"RoundingMode#HALF_UP",
"}",
"mode",
"and",
"fix",
"representation"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/math/RoundHelper.java#L116-L119 |
DependencyWatcher/agent | src/main/java/com/dependencywatcher/client/DependencyWatcherClient.java | DependencyWatcherClient.uploadRepository | public void uploadRepository(String name, File archive)
throws ClientException {
HttpPut putMethod = new HttpPut(baseUri + "/repository/"
+ encodeURIComponent(name));
HttpEntity httpEntity = MultipartEntityBuilder
.create()
.addBinaryBody("file", archive,
ContentType.create("application/zip"),
archive.getName()).build();
putMethod.setEntity(httpEntity);
try {
CloseableHttpResponse result = httpClient.execute(putMethod);
try {
StatusLine status = result.getStatusLine();
if (status.getStatusCode() != HttpStatus.SC_CREATED) {
throw new APICallException(EntityUtils.toString(result
.getEntity()), status.getStatusCode());
}
} finally {
result.close();
}
} catch (HttpResponseException e) {
throw new APICallException(e.getMessage(), e.getStatusCode());
} catch (IOException e) {
throw new NotAvailableException(e);
}
} | java | public void uploadRepository(String name, File archive)
throws ClientException {
HttpPut putMethod = new HttpPut(baseUri + "/repository/"
+ encodeURIComponent(name));
HttpEntity httpEntity = MultipartEntityBuilder
.create()
.addBinaryBody("file", archive,
ContentType.create("application/zip"),
archive.getName()).build();
putMethod.setEntity(httpEntity);
try {
CloseableHttpResponse result = httpClient.execute(putMethod);
try {
StatusLine status = result.getStatusLine();
if (status.getStatusCode() != HttpStatus.SC_CREATED) {
throw new APICallException(EntityUtils.toString(result
.getEntity()), status.getStatusCode());
}
} finally {
result.close();
}
} catch (HttpResponseException e) {
throw new APICallException(e.getMessage(), e.getStatusCode());
} catch (IOException e) {
throw new NotAvailableException(e);
}
} | [
"public",
"void",
"uploadRepository",
"(",
"String",
"name",
",",
"File",
"archive",
")",
"throws",
"ClientException",
"{",
"HttpPut",
"putMethod",
"=",
"new",
"HttpPut",
"(",
"baseUri",
"+",
"\"/repository/\"",
"+",
"encodeURIComponent",
"(",
"name",
")",
")",
... | Creates or updates repository by the given name
@param name
Repository name
@param archive
Archive containing repository data
@throws ClientException | [
"Creates",
"or",
"updates",
"repository",
"by",
"the",
"given",
"name"
] | train | https://github.com/DependencyWatcher/agent/blob/6a082650275f9555993f5607d1f0bbe7aceceee1/src/main/java/com/dependencywatcher/client/DependencyWatcherClient.java#L76-L107 |
powermock/powermock | powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java | PowerMockito.verifyPrivate | public static PrivateMethodVerification verifyPrivate(Class<?> clazz, VerificationMode verificationMode) {
return verifyPrivate((Object) clazz, verificationMode);
} | java | public static PrivateMethodVerification verifyPrivate(Class<?> clazz, VerificationMode verificationMode) {
return verifyPrivate((Object) clazz, verificationMode);
} | [
"public",
"static",
"PrivateMethodVerification",
"verifyPrivate",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"VerificationMode",
"verificationMode",
")",
"{",
"return",
"verifyPrivate",
"(",
"(",
"Object",
")",
"clazz",
",",
"verificationMode",
")",
";",
"}"
] | Verify a private method invocation for a class with a given verification
mode.
@see Mockito#verify(Object) | [
"Verify",
"a",
"private",
"method",
"invocation",
"for",
"a",
"class",
"with",
"a",
"given",
"verification",
"mode",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java#L301-L303 |
jlinn/quartz-redis-jobstore | src/main/java/net/joelinn/quartz/jobstore/RedisClusterStorage.java | RedisClusterStorage.resumeTriggers | @Override
public Collection<String> resumeTriggers(GroupMatcher<TriggerKey> matcher, JedisCluster jedis) throws JobPersistenceException {
Set<String> resumedTriggerGroups = new HashSet<>();
if (matcher.getCompareWithOperator() == StringMatcher.StringOperatorName.EQUALS) {
final String triggerGroupSetKey = redisSchema.triggerGroupSetKey(new TriggerKey("", matcher.getCompareToValue()));
jedis.srem(redisSchema.pausedJobGroupsSet(), triggerGroupSetKey);
Set<String> triggerHashKeysResponse = jedis.smembers(triggerGroupSetKey);
for (String triggerHashKey : triggerHashKeysResponse) {
OperableTrigger trigger = retrieveTrigger(redisSchema.triggerKey(triggerHashKey), jedis);
resumeTrigger(trigger.getKey(), jedis);
resumedTriggerGroups.add(trigger.getKey().getGroup());
}
} else {
for (final String triggerGroupSetKey : jedis.smembers(redisSchema.triggerGroupsSet())) {
if (matcher.getCompareWithOperator().evaluate(redisSchema.triggerGroup(triggerGroupSetKey), matcher.getCompareToValue())) {
resumedTriggerGroups.addAll(resumeTriggers(GroupMatcher.triggerGroupEquals(redisSchema.triggerGroup(triggerGroupSetKey)), jedis));
}
}
}
return resumedTriggerGroups;
} | java | @Override
public Collection<String> resumeTriggers(GroupMatcher<TriggerKey> matcher, JedisCluster jedis) throws JobPersistenceException {
Set<String> resumedTriggerGroups = new HashSet<>();
if (matcher.getCompareWithOperator() == StringMatcher.StringOperatorName.EQUALS) {
final String triggerGroupSetKey = redisSchema.triggerGroupSetKey(new TriggerKey("", matcher.getCompareToValue()));
jedis.srem(redisSchema.pausedJobGroupsSet(), triggerGroupSetKey);
Set<String> triggerHashKeysResponse = jedis.smembers(triggerGroupSetKey);
for (String triggerHashKey : triggerHashKeysResponse) {
OperableTrigger trigger = retrieveTrigger(redisSchema.triggerKey(triggerHashKey), jedis);
resumeTrigger(trigger.getKey(), jedis);
resumedTriggerGroups.add(trigger.getKey().getGroup());
}
} else {
for (final String triggerGroupSetKey : jedis.smembers(redisSchema.triggerGroupsSet())) {
if (matcher.getCompareWithOperator().evaluate(redisSchema.triggerGroup(triggerGroupSetKey), matcher.getCompareToValue())) {
resumedTriggerGroups.addAll(resumeTriggers(GroupMatcher.triggerGroupEquals(redisSchema.triggerGroup(triggerGroupSetKey)), jedis));
}
}
}
return resumedTriggerGroups;
} | [
"@",
"Override",
"public",
"Collection",
"<",
"String",
">",
"resumeTriggers",
"(",
"GroupMatcher",
"<",
"TriggerKey",
">",
"matcher",
",",
"JedisCluster",
"jedis",
")",
"throws",
"JobPersistenceException",
"{",
"Set",
"<",
"String",
">",
"resumedTriggerGroups",
"... | Resume (un-pause) all of the <code>{@link Trigger}s</code> in the given group.
@param matcher matcher for the trigger groups to be resumed
@param jedis a thread-safe Redis connection
@return the names of trigger groups which were resumed | [
"Resume",
"(",
"un",
"-",
"pause",
")",
"all",
"of",
"the",
"<code",
">",
"{",
"@link",
"Trigger",
"}",
"s<",
"/",
"code",
">",
"in",
"the",
"given",
"group",
"."
] | train | https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/RedisClusterStorage.java#L568-L588 |
primefaces-extensions/core | src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java | SheetRenderer.encodeColHeaders | protected void encodeColHeaders(final FacesContext context, final Sheet sheet, final WidgetBuilder wb)
throws IOException {
final JavascriptVarBuilder vb = new JavascriptVarBuilder(null, false);
for (final SheetColumn column : sheet.getColumns()) {
if (!column.isRendered()) {
continue;
}
vb.appendArrayValue(column.getHeaderText(), true);
}
wb.nativeAttr("colHeaders", vb.closeVar().toString());
} | java | protected void encodeColHeaders(final FacesContext context, final Sheet sheet, final WidgetBuilder wb)
throws IOException {
final JavascriptVarBuilder vb = new JavascriptVarBuilder(null, false);
for (final SheetColumn column : sheet.getColumns()) {
if (!column.isRendered()) {
continue;
}
vb.appendArrayValue(column.getHeaderText(), true);
}
wb.nativeAttr("colHeaders", vb.closeVar().toString());
} | [
"protected",
"void",
"encodeColHeaders",
"(",
"final",
"FacesContext",
"context",
",",
"final",
"Sheet",
"sheet",
",",
"final",
"WidgetBuilder",
"wb",
")",
"throws",
"IOException",
"{",
"final",
"JavascriptVarBuilder",
"vb",
"=",
"new",
"JavascriptVarBuilder",
"(",
... | Encode the column headers
@param context
@param sheet
@param wb
@throws IOException | [
"Encode",
"the",
"column",
"headers"
] | train | https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java#L261-L271 |
Sciss/abc4j | abc/src/main/java/abc/ui/swing/ScoreTemplate.java | ScoreTemplate.getFieldsAtPosition | public byte[] getFieldsAtPosition(byte vert, byte horiz) {
Position p = new Position(vert, horiz);
if (m_fieldsPosition.get(p) != null) {
Vector v = (Vector) m_fieldsPosition.get(p);
Vector ret = new Vector(v.size());
for (Object aV : v) {
byte field = (Byte) aV;
if (isVisible(field))
ret.add(field);
}
byte[] ret2 = new byte[ret.size()];
for (int i = 0; i < ret2.length; i++) {
ret2[i] = (Byte) ret.get(i);
}
return ret2;
}
return new byte[0];
} | java | public byte[] getFieldsAtPosition(byte vert, byte horiz) {
Position p = new Position(vert, horiz);
if (m_fieldsPosition.get(p) != null) {
Vector v = (Vector) m_fieldsPosition.get(p);
Vector ret = new Vector(v.size());
for (Object aV : v) {
byte field = (Byte) aV;
if (isVisible(field))
ret.add(field);
}
byte[] ret2 = new byte[ret.size()];
for (int i = 0; i < ret2.length; i++) {
ret2[i] = (Byte) ret.get(i);
}
return ret2;
}
return new byte[0];
} | [
"public",
"byte",
"[",
"]",
"getFieldsAtPosition",
"(",
"byte",
"vert",
",",
"byte",
"horiz",
")",
"{",
"Position",
"p",
"=",
"new",
"Position",
"(",
"vert",
",",
"horiz",
")",
";",
"if",
"(",
"m_fieldsPosition",
".",
"get",
"(",
"p",
")",
"!=",
"nul... | Returns the list of visible fields at the given position
@param vert
one of {@link VerticalPosition} constants
@param horiz
one of {@link HorizontalPosition} constants
@return array of {@link ScoreElements} constants | [
"Returns",
"the",
"list",
"of",
"visible",
"fields",
"at",
"the",
"given",
"position"
] | train | https://github.com/Sciss/abc4j/blob/117b405642c84a7bfca4e3e13668838258b90ca7/abc/src/main/java/abc/ui/swing/ScoreTemplate.java#L425-L442 |
sdl/odata | odata_api/src/main/java/com/sdl/odata/util/edm/EntityDataModelUtil.java | EntityDataModelUtil.getStructuralProperty | public static StructuralProperty getStructuralProperty(EntityDataModel entityDataModel,
StructuredType structuredType, String propertyName) {
StructuralProperty structuralProperty = structuredType.getStructuralProperty(propertyName);
if (structuralProperty != null) {
return structuralProperty;
} else {
// Look up recursively in the 'base type'
String baseTypeName = structuredType.getBaseTypeName();
if (!isNullOrEmpty(baseTypeName)) {
Type baseType = entityDataModel.getType(baseTypeName);
if (baseType != null && baseType instanceof StructuredType) {
return getStructuralProperty(entityDataModel, (StructuredType) baseType, propertyName);
}
}
}
return null;
} | java | public static StructuralProperty getStructuralProperty(EntityDataModel entityDataModel,
StructuredType structuredType, String propertyName) {
StructuralProperty structuralProperty = structuredType.getStructuralProperty(propertyName);
if (structuralProperty != null) {
return structuralProperty;
} else {
// Look up recursively in the 'base type'
String baseTypeName = structuredType.getBaseTypeName();
if (!isNullOrEmpty(baseTypeName)) {
Type baseType = entityDataModel.getType(baseTypeName);
if (baseType != null && baseType instanceof StructuredType) {
return getStructuralProperty(entityDataModel, (StructuredType) baseType, propertyName);
}
}
}
return null;
} | [
"public",
"static",
"StructuralProperty",
"getStructuralProperty",
"(",
"EntityDataModel",
"entityDataModel",
",",
"StructuredType",
"structuredType",
",",
"String",
"propertyName",
")",
"{",
"StructuralProperty",
"structuralProperty",
"=",
"structuredType",
".",
"getStructur... | Get the 'Structural Property' from the given 'Entity Data Model' and 'Structured Type' looking up all the base
types recursively.
@param entityDataModel The given 'Entity Data Model'.
@param structuredType The given 'Structured Type'.
@param propertyName The name of the property to look up.
@return The 'Structural Property' or {@code null} if not found. | [
"Get",
"the",
"Structural",
"Property",
"from",
"the",
"given",
"Entity",
"Data",
"Model",
"and",
"Structured",
"Type",
"looking",
"up",
"all",
"the",
"base",
"types",
"recursively",
"."
] | train | https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_api/src/main/java/com/sdl/odata/util/edm/EntityDataModelUtil.java#L391-L408 |
jayantk/jklol | src/com/jayantkrish/jklol/tensor/DenseTensor.java | DenseTensor.fastInnerProductRightAligned | private DenseTensor fastInnerProductRightAligned(Tensor other, long maxKeyNum, long keyNumIncrement,
int[] newDims, int[] newSizes) {
DenseTensorBuilder resultBuilder = new DenseTensorBuilder(newDims, newSizes);
int otherSize = other.size();
double[] otherValues = other.getValues();
// Iterate over the keys of this, then (hopefully sparsely) iterate over the
// keys of {@code other},
double innerProd;
int otherIndex;
int finalIndex = (int) (maxKeyNum / keyNumIncrement);
long myKeyNum;
for (int i = 0; i < finalIndex; i++) {
myKeyNum = i * keyNumIncrement;
innerProd = 0.0;
for (otherIndex = 0; otherIndex < otherSize; otherIndex++) {
long otherKeyNum = other.indexToKeyNum(otherIndex);
double otherValue = otherValues[otherIndex];
innerProd += values[(int) (myKeyNum + otherKeyNum)] * otherValue;
}
resultBuilder.putByKeyNum(i, innerProd);
}
return resultBuilder.buildNoCopy();
} | java | private DenseTensor fastInnerProductRightAligned(Tensor other, long maxKeyNum, long keyNumIncrement,
int[] newDims, int[] newSizes) {
DenseTensorBuilder resultBuilder = new DenseTensorBuilder(newDims, newSizes);
int otherSize = other.size();
double[] otherValues = other.getValues();
// Iterate over the keys of this, then (hopefully sparsely) iterate over the
// keys of {@code other},
double innerProd;
int otherIndex;
int finalIndex = (int) (maxKeyNum / keyNumIncrement);
long myKeyNum;
for (int i = 0; i < finalIndex; i++) {
myKeyNum = i * keyNumIncrement;
innerProd = 0.0;
for (otherIndex = 0; otherIndex < otherSize; otherIndex++) {
long otherKeyNum = other.indexToKeyNum(otherIndex);
double otherValue = otherValues[otherIndex];
innerProd += values[(int) (myKeyNum + otherKeyNum)] * otherValue;
}
resultBuilder.putByKeyNum(i, innerProd);
}
return resultBuilder.buildNoCopy();
} | [
"private",
"DenseTensor",
"fastInnerProductRightAligned",
"(",
"Tensor",
"other",
",",
"long",
"maxKeyNum",
",",
"long",
"keyNumIncrement",
",",
"int",
"[",
"]",
"newDims",
",",
"int",
"[",
"]",
"newSizes",
")",
"{",
"DenseTensorBuilder",
"resultBuilder",
"=",
"... | Fast implementation of inner product that takes advantage of potential
sparsity in {@code other}. Requires alignment between the dimensions of
{@code this} and {@code other}.
@param other
@return | [
"Fast",
"implementation",
"of",
"inner",
"product",
"that",
"takes",
"advantage",
"of",
"potential",
"sparsity",
"in",
"{",
"@code",
"other",
"}",
".",
"Requires",
"alignment",
"between",
"the",
"dimensions",
"of",
"{",
"@code",
"this",
"}",
"and",
"{",
"@co... | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/tensor/DenseTensor.java#L267-L289 |
google/error-prone-javac | src/jdk.jshell/share/classes/jdk/jshell/MemoryFileManager.java | MemoryFileManager.isSameFile | @Override
public boolean isSameFile(FileObject a, FileObject b) {
return stdFileManager.isSameFile(b, b);
} | java | @Override
public boolean isSameFile(FileObject a, FileObject b) {
return stdFileManager.isSameFile(b, b);
} | [
"@",
"Override",
"public",
"boolean",
"isSameFile",
"(",
"FileObject",
"a",
",",
"FileObject",
"b",
")",
"{",
"return",
"stdFileManager",
".",
"isSameFile",
"(",
"b",
",",
"b",
")",
";",
"}"
] | Compares two file objects and return true if they represent the
same underlying object.
@param a a file object
@param b a file object
@return true if the given file objects represent the same
underlying object
@throws IllegalArgumentException if either of the arguments
were created with another file manager and this file manager
does not support foreign file objects | [
"Compares",
"two",
"file",
"objects",
"and",
"return",
"true",
"if",
"they",
"represent",
"the",
"same",
"underlying",
"object",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/jshell/MemoryFileManager.java#L306-L309 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java | PhotosApi.setContentType | public Response setContentType(String photoId, JinxConstants.ContentType contentType) throws JinxException {
JinxUtils.validateParams(photoId, contentType);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.setContentType");
params.put("photo_id", photoId);
params.put("content_type", Integer.toString(JinxUtils.contentTypeToFlickrContentTypeId(contentType)));
return jinx.flickrPost(params, Response.class);
} | java | public Response setContentType(String photoId, JinxConstants.ContentType contentType) throws JinxException {
JinxUtils.validateParams(photoId, contentType);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.setContentType");
params.put("photo_id", photoId);
params.put("content_type", Integer.toString(JinxUtils.contentTypeToFlickrContentTypeId(contentType)));
return jinx.flickrPost(params, Response.class);
} | [
"public",
"Response",
"setContentType",
"(",
"String",
"photoId",
",",
"JinxConstants",
".",
"ContentType",
"contentType",
")",
"throws",
"JinxException",
"{",
"JinxUtils",
".",
"validateParams",
"(",
"photoId",
",",
"contentType",
")",
";",
"Map",
"<",
"String",
... | Set the content type of a photo.
<br>
This method requires authentication with 'write' permission.
@param photoId Required. The id of the photo to set the content of.
@param contentType Required. Content type of the photo.
@return response object with the result of the requested operation.
@throws JinxException if required parameters are null or empty, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.photos.setContentType.html">flickr.photos.setContentType</a> | [
"Set",
"the",
"content",
"type",
"of",
"a",
"photo",
".",
"<br",
">",
"This",
"method",
"requires",
"authentication",
"with",
"write",
"permission",
"."
] | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java#L886-L893 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/trees/EnglishGrammaticalRelations.java | EnglishGrammaticalRelations.getConj | public static GrammaticalRelation getConj(String conjunctionString) {
GrammaticalRelation result = conjs.get(conjunctionString);
if (result == null) {
synchronized(conjs) {
result = conjs.get(conjunctionString);
if (result == null) {
result = new GrammaticalRelation(Language.English, "conj", "conj_collapsed", null, CONJUNCT, conjunctionString);
conjs.put(conjunctionString, result);
threadSafeAddRelation(result);
}
}
}
return result;
} | java | public static GrammaticalRelation getConj(String conjunctionString) {
GrammaticalRelation result = conjs.get(conjunctionString);
if (result == null) {
synchronized(conjs) {
result = conjs.get(conjunctionString);
if (result == null) {
result = new GrammaticalRelation(Language.English, "conj", "conj_collapsed", null, CONJUNCT, conjunctionString);
conjs.put(conjunctionString, result);
threadSafeAddRelation(result);
}
}
}
return result;
} | [
"public",
"static",
"GrammaticalRelation",
"getConj",
"(",
"String",
"conjunctionString",
")",
"{",
"GrammaticalRelation",
"result",
"=",
"conjs",
".",
"get",
"(",
"conjunctionString",
")",
";",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"synchronized",
"(",
... | The "conj" grammatical relation. Used to collapse conjunct relations.
They will be turned into conj_word, where "word" is a conjunction.
NOTE: Because these relations lack associated GrammaticalRelationAnnotations,
they cannot be arcs of a TreeGraphNode.
@param conjunctionString The conjunction to make a GrammaticalRelation out of
@return A grammatical relation for this conjunction | [
"The",
"conj",
"grammatical",
"relation",
".",
"Used",
"to",
"collapse",
"conjunct",
"relations",
".",
"They",
"will",
"be",
"turned",
"into",
"conj_word",
"where",
"word",
"is",
"a",
"conjunction",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/trees/EnglishGrammaticalRelations.java#L1589-L1602 |
geomajas/geomajas-project-client-gwt2 | impl/src/main/java/org/geomajas/gwt2/client/gfx/VectorTileObject.java | VectorTileObject.setInnerSvg | public static void setInnerSvg(Element element, String svg) {
if (Dom.isFireFox()) {
setFireFoxInnerHTML(element,
"<g xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" + svg
+ "</g>");
} else if (Dom.isWebkit()) {
setWebkitInnerHTML(element,
"<g xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" + svg
+ "</g>");
}
} | java | public static void setInnerSvg(Element element, String svg) {
if (Dom.isFireFox()) {
setFireFoxInnerHTML(element,
"<g xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" + svg
+ "</g>");
} else if (Dom.isWebkit()) {
setWebkitInnerHTML(element,
"<g xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" + svg
+ "</g>");
}
} | [
"public",
"static",
"void",
"setInnerSvg",
"(",
"Element",
"element",
",",
"String",
"svg",
")",
"{",
"if",
"(",
"Dom",
".",
"isFireFox",
"(",
")",
")",
"{",
"setFireFoxInnerHTML",
"(",
"element",
",",
"\"<g xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"h... | Similar method to the "setInnerHTML", but specified for setting SVG. Using the regular setInnerHTML, it is not
possible to set a string of SVG on an object. This method can do that. On the other hand, this method is better
not used for setting normal HTML as an element's innerHTML.
@param element
The element onto which to set the SVG string.
@param svg
The string of SVG to set on the element. | [
"Similar",
"method",
"to",
"the",
"setInnerHTML",
"but",
"specified",
"for",
"setting",
"SVG",
".",
"Using",
"the",
"regular",
"setInnerHTML",
"it",
"is",
"not",
"possible",
"to",
"set",
"a",
"string",
"of",
"SVG",
"on",
"an",
"object",
".",
"This",
"metho... | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/gfx/VectorTileObject.java#L59-L69 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.