repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
before/quality-check | modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java | ConditionalCheck.stateIsTrue | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, RuntimeInstantiationException.class })
public static void stateIsTrue(final boolean condition, final boolean expression, final Class<? extends RuntimeException> clazz) {
if (condition) {
Check.stateIsTrue(expression, clazz);
}
} | java | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, RuntimeInstantiationException.class })
public static void stateIsTrue(final boolean condition, final boolean expression, final Class<? extends RuntimeException> clazz) {
if (condition) {
Check.stateIsTrue(expression, clazz);
}
} | [
"@",
"ArgumentsChecked",
"@",
"Throws",
"(",
"{",
"IllegalNullArgumentException",
".",
"class",
",",
"RuntimeInstantiationException",
".",
"class",
"}",
")",
"public",
"static",
"void",
"stateIsTrue",
"(",
"final",
"boolean",
"condition",
",",
"final",
"boolean",
... | Ensures that a given state is {@code true} and allows to specify the class of exception which is thrown in case
the state is not {@code true}.
@param condition
condition must be {@code true}^ so that the check will be performed
@param expression
an expression that must be {@code true} to indicate a valid state
@param clazz
an subclass of {@link RuntimeException} which will be thrown if the given state is not valid
@throws clazz
a new instance of {@code clazz} if the given arguments caused an invalid state
@throws RuntimeInstantiationException
<strong>Attention</strong>: Be aware, that a {@code RuntimeInstantiationException} can be thrown when
the given {@code clazz} cannot be instantiated | [
"Ensures",
"that",
"a",
"given",
"state",
"is",
"{",
"@code",
"true",
"}",
"and",
"allows",
"to",
"specify",
"the",
"class",
"of",
"exception",
"which",
"is",
"thrown",
"in",
"case",
"the",
"state",
"is",
"not",
"{",
"@code",
"true",
"}",
"."
] | train | https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java#L2163-L2170 |
badamowicz/sonar-hla | sonar-hla/src/main/java/com/github/badamowicz/sonar/hla/impl/ProjectAggregated.java | ProjectAggregated.isNoMeasureAvailable | private boolean isNoMeasureAvailable(HLAMeasure measure, IProject project) {
return !project.getMeasures().contains(measure) || project.getMeasureValue(measure, false) == Project.VALUE_NOT_AVAILABLE;
} | java | private boolean isNoMeasureAvailable(HLAMeasure measure, IProject project) {
return !project.getMeasures().contains(measure) || project.getMeasureValue(measure, false) == Project.VALUE_NOT_AVAILABLE;
} | [
"private",
"boolean",
"isNoMeasureAvailable",
"(",
"HLAMeasure",
"measure",
",",
"IProject",
"project",
")",
"{",
"return",
"!",
"project",
".",
"getMeasures",
"(",
")",
".",
"contains",
"(",
"measure",
")",
"||",
"project",
".",
"getMeasureValue",
"(",
"measu... | Check if the given measure is available inside the project <b>and</b> if it contains a value.
@param measure The measure to be checked.
@param project The project to be checked.
@return true, if <b>no</b> measure is available. | [
"Check",
"if",
"the",
"given",
"measure",
"is",
"available",
"inside",
"the",
"project",
"<b",
">",
"and<",
"/",
"b",
">",
"if",
"it",
"contains",
"a",
"value",
"."
] | train | https://github.com/badamowicz/sonar-hla/blob/21bd8a853d81966b47e96b518430abbc07ccd5f3/sonar-hla/src/main/java/com/github/badamowicz/sonar/hla/impl/ProjectAggregated.java#L188-L191 |
radkovo/jStyleParser | src/main/java/cz/vutbr/web/domassign/Variator.java | Variator.assignDefaults | public void assignDefaults(Map<String, CSSProperty> properties, Map<String, Term<?>> values) {
SupportedCSS css = CSSFactory.getSupportedCSS();
for (String name : names) {
CSSProperty dp = css.getDefaultProperty(name);
if (dp != null)
properties.put(name, dp);
Term<?> dv = css.getDefaultValue(name);
if (dv != null)
values.put(name, dv);
}
} | java | public void assignDefaults(Map<String, CSSProperty> properties, Map<String, Term<?>> values) {
SupportedCSS css = CSSFactory.getSupportedCSS();
for (String name : names) {
CSSProperty dp = css.getDefaultProperty(name);
if (dp != null)
properties.put(name, dp);
Term<?> dv = css.getDefaultValue(name);
if (dv != null)
values.put(name, dv);
}
} | [
"public",
"void",
"assignDefaults",
"(",
"Map",
"<",
"String",
",",
"CSSProperty",
">",
"properties",
",",
"Map",
"<",
"String",
",",
"Term",
"<",
"?",
">",
">",
"values",
")",
"{",
"SupportedCSS",
"css",
"=",
"CSSFactory",
".",
"getSupportedCSS",
"(",
"... | Assigns the default values to all the properties.
@param properties
@param values | [
"Assigns",
"the",
"default",
"values",
"to",
"all",
"the",
"properties",
"."
] | train | https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/domassign/Variator.java#L348-L358 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java | DistortImageOps.boundBox_F32 | public static RectangleLength2D_F32 boundBox_F32( int srcWidth , int srcHeight ,
PixelTransform<Point2D_F32> transform ,
Point2D_F32 transformed )
{
ImageRectangle_F32 r=new ImageRectangle_F32();
r.x0=r.y0=Float.MAX_VALUE;
r.x1=r.y1=-Float.MAX_VALUE;
for( int y = 0; y < srcHeight; y++ ) {
transform.compute(0, y, transformed);
updateBoundBox(transformed, r);
transform.compute(srcWidth, y, transformed);
updateBoundBox(transformed, r);
}
for( int x = 0; x < srcWidth; x++ ) {
transform.compute(x, 0, transformed);
updateBoundBox(transformed, r);
transform.compute(x, srcHeight, transformed);
updateBoundBox(transformed, r);
}
return new RectangleLength2D_F32(r.x0,r.y0,r.x1-r.x0,r.y1-r.y0);
} | java | public static RectangleLength2D_F32 boundBox_F32( int srcWidth , int srcHeight ,
PixelTransform<Point2D_F32> transform ,
Point2D_F32 transformed )
{
ImageRectangle_F32 r=new ImageRectangle_F32();
r.x0=r.y0=Float.MAX_VALUE;
r.x1=r.y1=-Float.MAX_VALUE;
for( int y = 0; y < srcHeight; y++ ) {
transform.compute(0, y, transformed);
updateBoundBox(transformed, r);
transform.compute(srcWidth, y, transformed);
updateBoundBox(transformed, r);
}
for( int x = 0; x < srcWidth; x++ ) {
transform.compute(x, 0, transformed);
updateBoundBox(transformed, r);
transform.compute(x, srcHeight, transformed);
updateBoundBox(transformed, r);
}
return new RectangleLength2D_F32(r.x0,r.y0,r.x1-r.x0,r.y1-r.y0);
} | [
"public",
"static",
"RectangleLength2D_F32",
"boundBox_F32",
"(",
"int",
"srcWidth",
",",
"int",
"srcHeight",
",",
"PixelTransform",
"<",
"Point2D_F32",
">",
"transform",
",",
"Point2D_F32",
"transformed",
")",
"{",
"ImageRectangle_F32",
"r",
"=",
"new",
"ImageRecta... | Finds an axis-aligned bounding box which would contain a image after it has been transformed.
The returned bounding box can be larger then the original image.
@param srcWidth Width of the source image
@param srcHeight Height of the source image
@param transform Transform being applied to the image
@return Bounding box | [
"Finds",
"an",
"axis",
"-",
"aligned",
"bounding",
"box",
"which",
"would",
"contain",
"a",
"image",
"after",
"it",
"has",
"been",
"transformed",
".",
"The",
"returned",
"bounding",
"box",
"can",
"be",
"larger",
"then",
"the",
"original",
"image",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/distort/DistortImageOps.java#L358-L382 |
UrielCh/ovh-java-sdk | ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java | ApiOvhDomain.serviceName_configurations_obfuscatedEmails_refresh_POST | public void serviceName_configurations_obfuscatedEmails_refresh_POST(String serviceName, OvhContactAllTypesEnum[] contacts) throws IOException {
String qPath = "/domain/{serviceName}/configurations/obfuscatedEmails/refresh";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "contacts", contacts);
exec(qPath, "POST", sb.toString(), o);
} | java | public void serviceName_configurations_obfuscatedEmails_refresh_POST(String serviceName, OvhContactAllTypesEnum[] contacts) throws IOException {
String qPath = "/domain/{serviceName}/configurations/obfuscatedEmails/refresh";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "contacts", contacts);
exec(qPath, "POST", sb.toString(), o);
} | [
"public",
"void",
"serviceName_configurations_obfuscatedEmails_refresh_POST",
"(",
"String",
"serviceName",
",",
"OvhContactAllTypesEnum",
"[",
"]",
"contacts",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/domain/{serviceName}/configurations/obfuscatedEmails/ref... | Refresh an obfuscated emails configuration
REST: POST /domain/{serviceName}/configurations/obfuscatedEmails/refresh
@param contacts [required] Contact types where obfuscated emails will be refreshed
@param serviceName [required] The internal name of your domain | [
"Refresh",
"an",
"obfuscated",
"emails",
"configuration"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java#L1607-L1613 |
rwl/CSparseJ | src/main/java/edu/emory/mathcs/csparsej/tdouble/Dcs_lusol.java | Dcs_lusol.cs_lusol | public static boolean cs_lusol(int order, Dcs A, double[] b, double tol) {
double[] x;
Dcss S;
Dcsn N;
int n;
boolean ok;
if (!Dcs_util.CS_CSC(A) || b == null)
return (false); /* check inputs */
n = A.n;
S = Dcs_sqr.cs_sqr(order, A, false); /* ordering and symbolic analysis */
N = Dcs_lu.cs_lu(A, S, tol); /* numeric LU factorization */
x = new double[n]; /* get workspace */
ok = (S != null && N != null);
if (ok) {
Dcs_ipvec.cs_ipvec(N.pinv, b, x, n); /* x = b(p) */
Dcs_lsolve.cs_lsolve(N.L, x); /* x = L\x */
Dcs_usolve.cs_usolve(N.U, x); /* x = U\x */
Dcs_ipvec.cs_ipvec(S.q, x, b, n); /* b(q) = x */
}
return (ok);
} | java | public static boolean cs_lusol(int order, Dcs A, double[] b, double tol) {
double[] x;
Dcss S;
Dcsn N;
int n;
boolean ok;
if (!Dcs_util.CS_CSC(A) || b == null)
return (false); /* check inputs */
n = A.n;
S = Dcs_sqr.cs_sqr(order, A, false); /* ordering and symbolic analysis */
N = Dcs_lu.cs_lu(A, S, tol); /* numeric LU factorization */
x = new double[n]; /* get workspace */
ok = (S != null && N != null);
if (ok) {
Dcs_ipvec.cs_ipvec(N.pinv, b, x, n); /* x = b(p) */
Dcs_lsolve.cs_lsolve(N.L, x); /* x = L\x */
Dcs_usolve.cs_usolve(N.U, x); /* x = U\x */
Dcs_ipvec.cs_ipvec(S.q, x, b, n); /* b(q) = x */
}
return (ok);
} | [
"public",
"static",
"boolean",
"cs_lusol",
"(",
"int",
"order",
",",
"Dcs",
"A",
",",
"double",
"[",
"]",
"b",
",",
"double",
"tol",
")",
"{",
"double",
"[",
"]",
"x",
";",
"Dcss",
"S",
";",
"Dcsn",
"N",
";",
"int",
"n",
";",
"boolean",
"ok",
"... | Solves Ax=b, where A is square and nonsingular. b overwritten with
solution. Partial pivoting if tol = 1.
@param order
ordering method to use (0 to 3)
@param A
column-compressed matrix
@param b
size n, b on input, x on output
@param tol
partial pivoting tolerance
@return true if successful, false on error | [
"Solves",
"Ax",
"=",
"b",
"where",
"A",
"is",
"square",
"and",
"nonsingular",
".",
"b",
"overwritten",
"with",
"solution",
".",
"Partial",
"pivoting",
"if",
"tol",
"=",
"1",
"."
] | train | https://github.com/rwl/CSparseJ/blob/6a6f66bccce1558156a961494358952603b0ac84/src/main/java/edu/emory/mathcs/csparsej/tdouble/Dcs_lusol.java#L53-L73 |
katharsis-project/katharsis-framework | katharsis-jpa/src/main/java/io/katharsis/jpa/internal/query/AnyUtils.java | AnyUtils.setValue | public static void setValue(MetaLookup metaLookup, AnyTypeObject dataObject, Object value) {
MetaDataObject meta = metaLookup.getMeta(dataObject.getClass()).asDataObject();
if (value == null) {
for (MetaAttribute attr : meta.getAttributes()) {
attr.setValue(dataObject, null);
}
}
else {
boolean found = false;
for (MetaAttribute attr : meta.getAttributes()) {
if (attr.getType().getImplementationClass().isAssignableFrom(value.getClass())) {
attr.setValue(dataObject, value);
found = true;
}
else {
attr.setValue(dataObject, null);
}
}
if (!found) {
throw new IllegalStateException("cannot assign " + value + " to " + dataObject);
}
}
} | java | public static void setValue(MetaLookup metaLookup, AnyTypeObject dataObject, Object value) {
MetaDataObject meta = metaLookup.getMeta(dataObject.getClass()).asDataObject();
if (value == null) {
for (MetaAttribute attr : meta.getAttributes()) {
attr.setValue(dataObject, null);
}
}
else {
boolean found = false;
for (MetaAttribute attr : meta.getAttributes()) {
if (attr.getType().getImplementationClass().isAssignableFrom(value.getClass())) {
attr.setValue(dataObject, value);
found = true;
}
else {
attr.setValue(dataObject, null);
}
}
if (!found) {
throw new IllegalStateException("cannot assign " + value + " to " + dataObject);
}
}
} | [
"public",
"static",
"void",
"setValue",
"(",
"MetaLookup",
"metaLookup",
",",
"AnyTypeObject",
"dataObject",
",",
"Object",
"value",
")",
"{",
"MetaDataObject",
"meta",
"=",
"metaLookup",
".",
"getMeta",
"(",
"dataObject",
".",
"getClass",
"(",
")",
")",
".",
... | Sets the value of the given anytype.
@param metaLookup to use to retrieve information
@param dataObject the anytype for which the value is set.
@param value the new value | [
"Sets",
"the",
"value",
"of",
"the",
"given",
"anytype",
"."
] | train | https://github.com/katharsis-project/katharsis-framework/blob/73d1a8763c49c5cf4643d43e2dbfedb647630c46/katharsis-jpa/src/main/java/io/katharsis/jpa/internal/query/AnyUtils.java#L20-L42 |
Netflix/governator | governator-legacy/src/main/java/com/netflix/governator/configuration/ColumnPrinter.java | ColumnPrinter.addValue | void addValue(int columnIndex, String value)
{
if ( (columnIndex < 0) || (columnIndex >= data.size()) )
{
throw new IllegalArgumentException();
}
List<String> stringList = data.get(columnIndex);
stringList.add(value);
} | java | void addValue(int columnIndex, String value)
{
if ( (columnIndex < 0) || (columnIndex >= data.size()) )
{
throw new IllegalArgumentException();
}
List<String> stringList = data.get(columnIndex);
stringList.add(value);
} | [
"void",
"addValue",
"(",
"int",
"columnIndex",
",",
"String",
"value",
")",
"{",
"if",
"(",
"(",
"columnIndex",
"<",
"0",
")",
"||",
"(",
"columnIndex",
">=",
"data",
".",
"size",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"("... | Add a value to the nth column
@param columnIndex n
@param value value to add | [
"Add",
"a",
"value",
"to",
"the",
"nth",
"column"
] | train | https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/configuration/ColumnPrinter.java#L71-L80 |
OpenTSDB/opentsdb | src/meta/TSUIDQuery.java | TSUIDQuery.setQuery | public void setQuery(final String metric, final Map<String, String> tags) {
this.metric = metric;
this.tags = tags;
metric_uid = tsdb.getUID(UniqueIdType.METRIC, metric);
tag_uids = Tags.resolveAll(tsdb, tags);
} | java | public void setQuery(final String metric, final Map<String, String> tags) {
this.metric = metric;
this.tags = tags;
metric_uid = tsdb.getUID(UniqueIdType.METRIC, metric);
tag_uids = Tags.resolveAll(tsdb, tags);
} | [
"public",
"void",
"setQuery",
"(",
"final",
"String",
"metric",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"this",
".",
"metric",
"=",
"metric",
";",
"this",
".",
"tags",
"=",
"tags",
";",
"metric_uid",
"=",
"tsdb",
"."... | Sets the query to perform
@param metric Name of the metric to search for
@param tags A map of tag value pairs or simply an empty map
@throws NoSuchUniqueName if the metric or any of the tag names/values did
not exist
@deprecated Please use one of the constructors instead. Will be removed in 2.3 | [
"Sets",
"the",
"query",
"to",
"perform"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/meta/TSUIDQuery.java#L227-L232 |
WiQuery/wiquery | wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/themes/ThemeUiHelper.java | ThemeUiHelper.iconComponent | public static void iconComponent(Component component, UiIcon icon)
{
component.add(AttributeModifier.append("class", "ui-icon " + icon.getCssClass()));
} | java | public static void iconComponent(Component component, UiIcon icon)
{
component.add(AttributeModifier.append("class", "ui-icon " + icon.getCssClass()));
} | [
"public",
"static",
"void",
"iconComponent",
"(",
"Component",
"component",
",",
"UiIcon",
"icon",
")",
"{",
"component",
".",
"add",
"(",
"AttributeModifier",
".",
"append",
"(",
"\"class\"",
",",
"\"ui-icon \"",
"+",
"icon",
".",
"getCssClass",
"(",
")",
"... | Method to display your composant as an icon
@param component
Wicket component
@param icon
Icon to display | [
"Method",
"to",
"display",
"your",
"composant",
"as",
"an",
"icon"
] | train | https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/themes/ThemeUiHelper.java#L358-L361 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/config/JawrConfig.java | JawrConfig.getProperty | public String getProperty(String key, String defaultValue) {
String property = configProperties.getProperty(key, defaultValue);
if (property != null) {
property = property.trim();
}
return property;
} | java | public String getProperty(String key, String defaultValue) {
String property = configProperties.getProperty(key, defaultValue);
if (property != null) {
property = property.trim();
}
return property;
} | [
"public",
"String",
"getProperty",
"(",
"String",
"key",
",",
"String",
"defaultValue",
")",
"{",
"String",
"property",
"=",
"configProperties",
".",
"getProperty",
"(",
"key",
",",
"defaultValue",
")",
";",
"if",
"(",
"property",
"!=",
"null",
")",
"{",
"... | Returns the value of the property associated to the key passed in
parameter
@param key
the key of the property
@param defaultValue
the default value
@return the value of the property | [
"Returns",
"the",
"value",
"of",
"the",
"property",
"associated",
"to",
"the",
"key",
"passed",
"in",
"parameter"
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/config/JawrConfig.java#L1358-L1365 |
saxsys/SynchronizeFX | transmitter/websocket-transmitter/src/main/java/de/saxsys/synchronizefx/websocket/SychronizeFXWebsocketServer.java | SychronizeFXWebsocketServer.newChannel | public SynchronizeFxServer newChannel(final Object root, final String channelName, final ServerCallback callback) {
return newChannel(root, channelName, null, callback);
} | java | public SynchronizeFxServer newChannel(final Object root, final String channelName, final ServerCallback callback) {
return newChannel(root, channelName, null, callback);
} | [
"public",
"SynchronizeFxServer",
"newChannel",
"(",
"final",
"Object",
"root",
",",
"final",
"String",
"channelName",
",",
"final",
"ServerCallback",
"callback",
")",
"{",
"return",
"newChannel",
"(",
"root",
",",
"channelName",
",",
"null",
",",
"callback",
")"... | Like {@link #newChannel(Object, String, Executor, ServerCallback)} but with a default model change executor.
@see #newChannel(Object, String, Executor, ServerCallback)
@param root see {@link #newChannel(Object, String, Executor, ServerCallback)}
@param channelName see {@link #newChannel(Object, String, Executor, ServerCallback)}
@param callback see {@link #newChannel(Object, String, Executor, ServerCallback)}
@return see {@link #newChannel(Object, String, Executor, ServerCallback)} | [
"Like",
"{",
"@link",
"#newChannel",
"(",
"Object",
"String",
"Executor",
"ServerCallback",
")",
"}",
"but",
"with",
"a",
"default",
"model",
"change",
"executor",
"."
] | train | https://github.com/saxsys/SynchronizeFX/blob/f3683020e4749110b38514eb5bc73a247998b579/transmitter/websocket-transmitter/src/main/java/de/saxsys/synchronizefx/websocket/SychronizeFXWebsocketServer.java#L141-L143 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/routing/handlers/AuthorizationHandler.java | AuthorizationHandler.isNotBlank | private boolean isNotBlank(String subject, String resource, String operation) {
return StringUtils.isNotBlank(subject) && StringUtils.isNotBlank(resource) && StringUtils.isNotBlank(operation);
} | java | private boolean isNotBlank(String subject, String resource, String operation) {
return StringUtils.isNotBlank(subject) && StringUtils.isNotBlank(resource) && StringUtils.isNotBlank(operation);
} | [
"private",
"boolean",
"isNotBlank",
"(",
"String",
"subject",
",",
"String",
"resource",
",",
"String",
"operation",
")",
"{",
"return",
"StringUtils",
".",
"isNotBlank",
"(",
"subject",
")",
"&&",
"StringUtils",
".",
"isNotBlank",
"(",
"resource",
")",
"&&",
... | Checks if any of the given strings is blank
@param subject The subject to validate
@param resource The resource to validate
@param operation The operation to validate
@return True if all strings are not blank, false otherwise | [
"Checks",
"if",
"any",
"of",
"the",
"given",
"strings",
"is",
"blank"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/handlers/AuthorizationHandler.java#L67-L69 |
auth0/Lock.Android | lib/src/main/java/com/auth0/android/lock/views/PasswordlessFormLayout.java | PasswordlessFormLayout.onCountryCodeSelected | public void onCountryCodeSelected(String country, String dialCode) {
if (passwordlessRequestCodeLayout != null) {
passwordlessRequestCodeLayout.onCountryCodeSelected(country, dialCode);
}
} | java | public void onCountryCodeSelected(String country, String dialCode) {
if (passwordlessRequestCodeLayout != null) {
passwordlessRequestCodeLayout.onCountryCodeSelected(country, dialCode);
}
} | [
"public",
"void",
"onCountryCodeSelected",
"(",
"String",
"country",
",",
"String",
"dialCode",
")",
"{",
"if",
"(",
"passwordlessRequestCodeLayout",
"!=",
"null",
")",
"{",
"passwordlessRequestCodeLayout",
".",
"onCountryCodeSelected",
"(",
"country",
",",
"dialCode"... | Notifies the form that a new country code was selected by the user.
@param country the selected country iso code (2 chars).
@param dialCode the dial code for this country | [
"Notifies",
"the",
"form",
"that",
"a",
"new",
"country",
"code",
"was",
"selected",
"by",
"the",
"user",
"."
] | train | https://github.com/auth0/Lock.Android/blob/8eb2a979048d2eb6cf0ec631e82e6c3fe6e7d220/lib/src/main/java/com/auth0/android/lock/views/PasswordlessFormLayout.java#L209-L213 |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/security/J2EESecurityManager.java | J2EESecurityManager.hasRole | protected Boolean hasRole(ActionBean bean, Method handler, String role)
{
return bean.getContext().getRequest().isUserInRole(role);
} | java | protected Boolean hasRole(ActionBean bean, Method handler, String role)
{
return bean.getContext().getRequest().isUserInRole(role);
} | [
"protected",
"Boolean",
"hasRole",
"(",
"ActionBean",
"bean",
",",
"Method",
"handler",
",",
"String",
"role",
")",
"{",
"return",
"bean",
".",
"getContext",
"(",
")",
".",
"getRequest",
"(",
")",
".",
"isUserInRole",
"(",
"role",
")",
";",
"}"
] | Determine if the current user has the specified role.
Note that '*' is a special role that resolves to any role (see the servlet spec. v2.4, section 12.8).
@param bean the current action bean
@param handler the current event handler
@param role the role to check
@return {@code true} if the user has the role, and {@code false} otherwise | [
"Determine",
"if",
"the",
"current",
"user",
"has",
"the",
"specified",
"role",
".",
"Note",
"that",
"*",
"is",
"a",
"special",
"role",
"that",
"resolves",
"to",
"any",
"role",
"(",
"see",
"the",
"servlet",
"spec",
".",
"v2",
".",
"4",
"section",
"12",... | train | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/security/J2EESecurityManager.java#L164-L167 |
apache/flink | flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/rank/AbstractTopNFunction.java | AbstractTopNFunction.delete | protected void delete(Collector<BaseRow> out, BaseRow inputRow) {
BaseRowUtil.setRetract(inputRow);
out.collect(inputRow);
} | java | protected void delete(Collector<BaseRow> out, BaseRow inputRow) {
BaseRowUtil.setRetract(inputRow);
out.collect(inputRow);
} | [
"protected",
"void",
"delete",
"(",
"Collector",
"<",
"BaseRow",
">",
"out",
",",
"BaseRow",
"inputRow",
")",
"{",
"BaseRowUtil",
".",
"setRetract",
"(",
"inputRow",
")",
";",
"out",
".",
"collect",
"(",
"inputRow",
")",
";",
"}"
] | This is similar to [[retract()]] but always send retraction message regardless of generateRetraction is true or
not. | [
"This",
"is",
"similar",
"to",
"[[",
"retract",
"()",
"]]",
"but",
"always",
"send",
"retraction",
"message",
"regardless",
"of",
"generateRetraction",
"is",
"true",
"or",
"not",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/rank/AbstractTopNFunction.java#L252-L255 |
aws/aws-sdk-java | aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/CreateInputRequest.java | CreateInputRequest.withTags | public CreateInputRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | java | public CreateInputRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"CreateInputRequest",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | A collection of key-value pairs.
@param tags
A collection of key-value pairs.
@return Returns a reference to this object so that method calls can be chained together. | [
"A",
"collection",
"of",
"key",
"-",
"value",
"pairs",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/CreateInputRequest.java#L464-L467 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/marshal/AbstractType.java | AbstractType.compareCollectionMembers | public int compareCollectionMembers(ByteBuffer v1, ByteBuffer v2, ByteBuffer collectionName)
{
return compare(v1, v2);
} | java | public int compareCollectionMembers(ByteBuffer v1, ByteBuffer v2, ByteBuffer collectionName)
{
return compare(v1, v2);
} | [
"public",
"int",
"compareCollectionMembers",
"(",
"ByteBuffer",
"v1",
",",
"ByteBuffer",
"v2",
",",
"ByteBuffer",
"collectionName",
")",
"{",
"return",
"compare",
"(",
"v1",
",",
"v2",
")",
";",
"}"
] | An alternative comparison function used by CollectionsType in conjunction with CompositeType.
This comparator is only called to compare components of a CompositeType. It gets the value of the
previous component as argument (or null if it's the first component of the composite).
Unless you're doing something very similar to CollectionsType, you shouldn't override this. | [
"An",
"alternative",
"comparison",
"function",
"used",
"by",
"CollectionsType",
"in",
"conjunction",
"with",
"CompositeType",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/marshal/AbstractType.java#L208-L211 |
IBM/ibm-cos-sdk-java | ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/EncryptRequest.java | EncryptRequest.getEncryptionContext | public java.util.Map<String, String> getEncryptionContext() {
if (encryptionContext == null) {
encryptionContext = new com.ibm.cloud.objectstorage.internal.SdkInternalMap<String, String>();
}
return encryptionContext;
} | java | public java.util.Map<String, String> getEncryptionContext() {
if (encryptionContext == null) {
encryptionContext = new com.ibm.cloud.objectstorage.internal.SdkInternalMap<String, String>();
}
return encryptionContext;
} | [
"public",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"getEncryptionContext",
"(",
")",
"{",
"if",
"(",
"encryptionContext",
"==",
"null",
")",
"{",
"encryptionContext",
"=",
"new",
"com",
".",
"ibm",
".",
"cloud",
".",
"objectsto... | <p>
Name-value pair that specifies the encryption context to be used for authenticated encryption. If used here, the
same value must be supplied to the <code>Decrypt</code> API or decryption will fail. For more information, see <a
href="http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html">Encryption Context</a>.
</p>
@return Name-value pair that specifies the encryption context to be used for authenticated encryption. If used
here, the same value must be supplied to the <code>Decrypt</code> API or decryption will fail. For more
information, see <a
href="http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html">Encryption
Context</a>. | [
"<p",
">",
"Name",
"-",
"value",
"pair",
"that",
"specifies",
"the",
"encryption",
"context",
"to",
"be",
"used",
"for",
"authenticated",
"encryption",
".",
"If",
"used",
"here",
"the",
"same",
"value",
"must",
"be",
"supplied",
"to",
"the",
"<code",
">",
... | train | https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/EncryptRequest.java#L338-L343 |
gallandarakhneorg/afc | core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java | XMLUtil.iterate | @Pure
public static Iterator<Node> iterate(Node parent, String nodeName) {
assert parent != null : AssertMessages.notNullParameter(0);
assert nodeName != null && !nodeName.isEmpty() : AssertMessages.notNullParameter(0);
return new NameBasedIterator(parent, nodeName);
} | java | @Pure
public static Iterator<Node> iterate(Node parent, String nodeName) {
assert parent != null : AssertMessages.notNullParameter(0);
assert nodeName != null && !nodeName.isEmpty() : AssertMessages.notNullParameter(0);
return new NameBasedIterator(parent, nodeName);
} | [
"@",
"Pure",
"public",
"static",
"Iterator",
"<",
"Node",
">",
"iterate",
"(",
"Node",
"parent",
",",
"String",
"nodeName",
")",
"{",
"assert",
"parent",
"!=",
"null",
":",
"AssertMessages",
".",
"notNullParameter",
"(",
"0",
")",
";",
"assert",
"nodeName"... | Replies an iterator on nodes that have the specified node name.
@param parent is the node from which the children must be extracted.
@param nodeName is the name of the extracted nodes
@return the iterator on the parents. | [
"Replies",
"an",
"iterator",
"on",
"nodes",
"that",
"have",
"the",
"specified",
"node",
"name",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L1702-L1707 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/grasslegacy/io/GrassRasterReader.java | GrassRasterReader.readNullValueAtRowCol | private boolean readNullValueAtRowCol( int currentfilerow, int currentfilecol ) throws IOException {
/*
* If the null file doesn't exist and the map is an integer, than it is an old integer-map
* format, where the novalues are the cells that contain the values 0
*/
if (nullFile != null) {
long byteperrow = (long) Math.ceil(fileWindow.getCols() / 8.0); // in the
// null
// map of
// cell_misc
long currentByte = (long) Math.ceil((currentfilecol + 1) / 8.0); // in the
// null
// map
// currentfilerow starts from 0, so it is the row before the one we
// need
long byteToRead = (byteperrow * currentfilerow) + currentByte;
nullFile.seek(byteToRead - 1);
int bitposition = (currentfilecol) % 8;
byte[] thetmp = new byte[1];
thetmp[0] = nullFile.readByte();
BitSet tmp = FileUtilities.fromByteArray(thetmp);
boolean theBit = tmp.get(7 - bitposition);
/*
* if (theBit) { System.out.println("1 at position: " + (7-bitposition) + " due to
* bitposition: " + bitposition); } else { System.out.println("0 at position: " +
* (7-bitposition) + " due to bitposition: " + bitposition); }
*/
return theBit;
}
// else
// {
// /* There is no null file around */
// if (rasterMapType > 0)
// {
// // isOldIntegerMap = true;
// return false;
// }
// else
// {
// //throw some exception
// return false;
// }
//
// }
return false;
} | java | private boolean readNullValueAtRowCol( int currentfilerow, int currentfilecol ) throws IOException {
/*
* If the null file doesn't exist and the map is an integer, than it is an old integer-map
* format, where the novalues are the cells that contain the values 0
*/
if (nullFile != null) {
long byteperrow = (long) Math.ceil(fileWindow.getCols() / 8.0); // in the
// null
// map of
// cell_misc
long currentByte = (long) Math.ceil((currentfilecol + 1) / 8.0); // in the
// null
// map
// currentfilerow starts from 0, so it is the row before the one we
// need
long byteToRead = (byteperrow * currentfilerow) + currentByte;
nullFile.seek(byteToRead - 1);
int bitposition = (currentfilecol) % 8;
byte[] thetmp = new byte[1];
thetmp[0] = nullFile.readByte();
BitSet tmp = FileUtilities.fromByteArray(thetmp);
boolean theBit = tmp.get(7 - bitposition);
/*
* if (theBit) { System.out.println("1 at position: " + (7-bitposition) + " due to
* bitposition: " + bitposition); } else { System.out.println("0 at position: " +
* (7-bitposition) + " due to bitposition: " + bitposition); }
*/
return theBit;
}
// else
// {
// /* There is no null file around */
// if (rasterMapType > 0)
// {
// // isOldIntegerMap = true;
// return false;
// }
// else
// {
// //throw some exception
// return false;
// }
//
// }
return false;
} | [
"private",
"boolean",
"readNullValueAtRowCol",
"(",
"int",
"currentfilerow",
",",
"int",
"currentfilecol",
")",
"throws",
"IOException",
"{",
"/*\n * If the null file doesn't exist and the map is an integer, than it is an old integer-map\n * format, where the novalues are t... | read the null value from the null file (if it exists) and returns the information about the
particular cell (true if it is novalue, false if it is not a novalue
@param currentfilerow
@param currentfilecol
@return | [
"read",
"the",
"null",
"value",
"from",
"the",
"null",
"file",
"(",
"if",
"it",
"exists",
")",
"and",
"returns",
"the",
"information",
"about",
"the",
"particular",
"cell",
"(",
"true",
"if",
"it",
"is",
"novalue",
"false",
"if",
"it",
"is",
"not",
"a"... | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/grasslegacy/io/GrassRasterReader.java#L1265-L1317 |
jayantk/jklol | src/com/jayantkrish/jklol/ccg/CcgUnaryRule.java | CcgUnaryRule.parseFrom | public static CcgUnaryRule parseFrom(String line) {
String[] chunks = new CsvParser(CsvParser.DEFAULT_SEPARATOR,
CsvParser.DEFAULT_QUOTE, CsvParser.NULL_ESCAPE).parseLine(line.trim());
Preconditions.checkArgument(chunks.length >= 1, "Illegal unary rule string: %s", line);
String[] syntacticParts = chunks[0].split(" ");
Preconditions.checkArgument(syntacticParts.length == 2, "Illegal unary rule string: %s", line);
HeadedSyntacticCategory inputSyntax = HeadedSyntacticCategory.parseFrom(syntacticParts[0]);
HeadedSyntacticCategory returnSyntax = HeadedSyntacticCategory.parseFrom(syntacticParts[1]);
// Ensure that the return syntactic type is in canonical form.
HeadedSyntacticCategory returnCanonical = returnSyntax.getCanonicalForm();
int[] originalToCanonical = returnSyntax.unifyVariables(returnSyntax.getUniqueVariables(), returnCanonical, new int[0]);
int[] inputVars = inputSyntax.getUniqueVariables();
int[] inputRelabeling = new int[inputVars.length];
int[] returnOriginalVars = returnSyntax.getUniqueVariables();
int nextUnassignedVar = Ints.max(returnCanonical.getUniqueVariables()) + 1;
for (int i = 0; i < inputVars.length; i++) {
int index = Ints.indexOf(returnOriginalVars, inputVars[i]);
if (index != -1) {
inputRelabeling[i] = originalToCanonical[index];
} else {
inputRelabeling[i] = nextUnassignedVar;
nextUnassignedVar++;
}
}
HeadedSyntacticCategory relabeledInput = inputSyntax.relabelVariables(inputVars, inputRelabeling);
Expression2 logicalForm = null;
if (chunks.length >= 2 && chunks[1].trim().length() > 0) {
logicalForm = ExpressionParser.expression2().parse(chunks[1]);
}
if (chunks.length >= 3) {
throw new UnsupportedOperationException(
"Using unfilled dependencies with unary CCG rules is not yet implemented");
/*
* String[] newDeps = chunks[4].split(" ");
* Preconditions.checkArgument(newDeps.length == 3); long
* subjectNum = Long.parseLong(newDeps[0].substring(1)); long
* argNum = Long.parseLong(newDeps[1]); long objectNum =
* Long.parseLong(newDeps[2].substring(1)); unfilledDeps = new
* long[1];
*
* unfilledDeps[0] =
* CcgParser.marshalUnfilledDependency(objectNum, argNum,
* subjectNum, 0, 0);
*/
}
return new CcgUnaryRule(relabeledInput, returnCanonical, logicalForm);
} | java | public static CcgUnaryRule parseFrom(String line) {
String[] chunks = new CsvParser(CsvParser.DEFAULT_SEPARATOR,
CsvParser.DEFAULT_QUOTE, CsvParser.NULL_ESCAPE).parseLine(line.trim());
Preconditions.checkArgument(chunks.length >= 1, "Illegal unary rule string: %s", line);
String[] syntacticParts = chunks[0].split(" ");
Preconditions.checkArgument(syntacticParts.length == 2, "Illegal unary rule string: %s", line);
HeadedSyntacticCategory inputSyntax = HeadedSyntacticCategory.parseFrom(syntacticParts[0]);
HeadedSyntacticCategory returnSyntax = HeadedSyntacticCategory.parseFrom(syntacticParts[1]);
// Ensure that the return syntactic type is in canonical form.
HeadedSyntacticCategory returnCanonical = returnSyntax.getCanonicalForm();
int[] originalToCanonical = returnSyntax.unifyVariables(returnSyntax.getUniqueVariables(), returnCanonical, new int[0]);
int[] inputVars = inputSyntax.getUniqueVariables();
int[] inputRelabeling = new int[inputVars.length];
int[] returnOriginalVars = returnSyntax.getUniqueVariables();
int nextUnassignedVar = Ints.max(returnCanonical.getUniqueVariables()) + 1;
for (int i = 0; i < inputVars.length; i++) {
int index = Ints.indexOf(returnOriginalVars, inputVars[i]);
if (index != -1) {
inputRelabeling[i] = originalToCanonical[index];
} else {
inputRelabeling[i] = nextUnassignedVar;
nextUnassignedVar++;
}
}
HeadedSyntacticCategory relabeledInput = inputSyntax.relabelVariables(inputVars, inputRelabeling);
Expression2 logicalForm = null;
if (chunks.length >= 2 && chunks[1].trim().length() > 0) {
logicalForm = ExpressionParser.expression2().parse(chunks[1]);
}
if (chunks.length >= 3) {
throw new UnsupportedOperationException(
"Using unfilled dependencies with unary CCG rules is not yet implemented");
/*
* String[] newDeps = chunks[4].split(" ");
* Preconditions.checkArgument(newDeps.length == 3); long
* subjectNum = Long.parseLong(newDeps[0].substring(1)); long
* argNum = Long.parseLong(newDeps[1]); long objectNum =
* Long.parseLong(newDeps[2].substring(1)); unfilledDeps = new
* long[1];
*
* unfilledDeps[0] =
* CcgParser.marshalUnfilledDependency(objectNum, argNum,
* subjectNum, 0, 0);
*/
}
return new CcgUnaryRule(relabeledInput, returnCanonical, logicalForm);
} | [
"public",
"static",
"CcgUnaryRule",
"parseFrom",
"(",
"String",
"line",
")",
"{",
"String",
"[",
"]",
"chunks",
"=",
"new",
"CsvParser",
"(",
"CsvParser",
".",
"DEFAULT_SEPARATOR",
",",
"CsvParser",
".",
"DEFAULT_QUOTE",
",",
"CsvParser",
".",
"NULL_ESCAPE",
"... | Parses a unary rule from a line in comma-separated format. The
expected fields, in order, are:
<ul>
<li>The headed syntactic categories to combine and return:
<code>(input syntax) (return syntax)</code>
<li>(optional) Additional unfilled dependencies, in standard
format:
<code>(predicate) (argument number) (argument variable)</code>
</ul>
For example, "NP{0} S{1}/(S{1}\NP{0}){1}" is a unary type-raising
rule that allows an NP to combine with an adjacent verb.
@param line
@return | [
"Parses",
"a",
"unary",
"rule",
"from",
"a",
"line",
"in",
"comma",
"-",
"separated",
"format",
".",
"The",
"expected",
"fields",
"in",
"order",
"are",
":",
"<ul",
">",
"<li",
">",
"The",
"headed",
"syntactic",
"categories",
"to",
"combine",
"and",
"retu... | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/CcgUnaryRule.java#L53-L104 |
j-a-w-r/jawr-main-repo | jawr-dwr3.x/jawr-dwr3.x-webapp-sample/src/main/java/org/getahead/dwrdemo/asmg/Generator.java | Generator.generateAntiSpamMailto | public String generateAntiSpamMailto(String name, String email)
{
StringTokenizer st = new StringTokenizer(email, "@");
if (Security.containsXssRiskyCharacters(email) || st.countTokens() != 2)
{
throw new IllegalArgumentException("Invalid email address: " + email);
}
String before = st.nextToken();
String after = st.nextToken();
StringBuffer buffer = new StringBuffer();
buffer.append("Contact ");
buffer.append(Security.replaceXmlCharacters(name));
buffer.append(" using: <span id=\"asmgLink\"></span>\n");
buffer.append("<script type='text/javascript'>\n");
buffer.append("var before = '");
buffer.append(before);
buffer.append("';\n");
buffer.append("var after = '");
buffer.append(after);
buffer.append("';\n");
buffer.append("var link = \"<a href='mail\" + \"to:\" + before + '@' + after + \"'>\" + before + '@' + after + \"</a>\";\n");
buffer.append("document.getElementById(\"asmgLink\").innerHTML = link;\n");
buffer.append("</script>\n");
buffer.append("<noscript>[");
buffer.append(before);
buffer.append(" at ");
buffer.append(after);
buffer.append("]</noscript>\n");
return buffer.toString();
} | java | public String generateAntiSpamMailto(String name, String email)
{
StringTokenizer st = new StringTokenizer(email, "@");
if (Security.containsXssRiskyCharacters(email) || st.countTokens() != 2)
{
throw new IllegalArgumentException("Invalid email address: " + email);
}
String before = st.nextToken();
String after = st.nextToken();
StringBuffer buffer = new StringBuffer();
buffer.append("Contact ");
buffer.append(Security.replaceXmlCharacters(name));
buffer.append(" using: <span id=\"asmgLink\"></span>\n");
buffer.append("<script type='text/javascript'>\n");
buffer.append("var before = '");
buffer.append(before);
buffer.append("';\n");
buffer.append("var after = '");
buffer.append(after);
buffer.append("';\n");
buffer.append("var link = \"<a href='mail\" + \"to:\" + before + '@' + after + \"'>\" + before + '@' + after + \"</a>\";\n");
buffer.append("document.getElementById(\"asmgLink\").innerHTML = link;\n");
buffer.append("</script>\n");
buffer.append("<noscript>[");
buffer.append(before);
buffer.append(" at ");
buffer.append(after);
buffer.append("]</noscript>\n");
return buffer.toString();
} | [
"public",
"String",
"generateAntiSpamMailto",
"(",
"String",
"name",
",",
"String",
"email",
")",
"{",
"StringTokenizer",
"st",
"=",
"new",
"StringTokenizer",
"(",
"email",
",",
"\"@\"",
")",
";",
"if",
"(",
"Security",
".",
"containsXssRiskyCharacters",
"(",
... | Generate an anti-spam mailto link from an email address
@param name The person to contact
@param email The address to generate a link from
@return The HTML snippet | [
"Generate",
"an",
"anti",
"-",
"spam",
"mailto",
"link",
"from",
"an",
"email",
"address"
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr-dwr3.x/jawr-dwr3.x-webapp-sample/src/main/java/org/getahead/dwrdemo/asmg/Generator.java#L44-L81 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java | SyncGroupsInner.beginUpdate | public SyncGroupInner beginUpdate(String resourceGroupName, String serverName, String databaseName, String syncGroupName, SyncGroupInner parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName, parameters).toBlocking().single().body();
} | java | public SyncGroupInner beginUpdate(String resourceGroupName, String serverName, String databaseName, String syncGroupName, SyncGroupInner parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName, parameters).toBlocking().single().body();
} | [
"public",
"SyncGroupInner",
"beginUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"String",
"syncGroupName",
",",
"SyncGroupInner",
"parameters",
")",
"{",
"return",
"beginUpdateWithServiceResponseAsync",
"(",
... | Updates a sync group.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database on which the sync group is hosted.
@param syncGroupName The name of the sync group.
@param parameters The requested sync group resource state.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the SyncGroupInner object if successful. | [
"Updates",
"a",
"sync",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java#L1691-L1693 |
thorntail/thorntail | plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java | GradleDependencyResolutionHelper.asDescriptor | private static DependencyDescriptor asDescriptor(String scope, ResolvedArtifact artifact) {
ModuleVersionIdentifier id = artifact.getModuleVersion().getId();
return new DefaultDependencyDescriptor(scope, id.getGroup(), id.getName(), id.getVersion(),
artifact.getType(), artifact.getClassifier(), artifact.getFile());
} | java | private static DependencyDescriptor asDescriptor(String scope, ResolvedArtifact artifact) {
ModuleVersionIdentifier id = artifact.getModuleVersion().getId();
return new DefaultDependencyDescriptor(scope, id.getGroup(), id.getName(), id.getVersion(),
artifact.getType(), artifact.getClassifier(), artifact.getFile());
} | [
"private",
"static",
"DependencyDescriptor",
"asDescriptor",
"(",
"String",
"scope",
",",
"ResolvedArtifact",
"artifact",
")",
"{",
"ModuleVersionIdentifier",
"id",
"=",
"artifact",
".",
"getModuleVersion",
"(",
")",
".",
"getId",
"(",
")",
";",
"return",
"new",
... | Translate the given {@link ResolvedArtifact resolved artifact} in to a {@link DependencyDescriptor} reference.
@param scope the scope to assign to the descriptor.
@param artifact the resolved artifact reference.
@return an instance of {@link DependencyDescriptor}. | [
"Translate",
"the",
"given",
"{",
"@link",
"ResolvedArtifact",
"resolved",
"artifact",
"}",
"in",
"to",
"a",
"{",
"@link",
"DependencyDescriptor",
"}",
"reference",
"."
] | train | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L291-L295 |
groupon/odo | proxylib/src/main/java/com/groupon/odo/proxylib/OverrideService.java | OverrideService.updateResponseCode | public void updateResponseCode(int overrideId, int pathId, Integer ordinal, String responseCode, String clientUUID) {
if (ordinal == null) {
ordinal = 1;
}
try {
// get ID of the ordinal
int enabledId = getEnabledEndpoint(pathId, overrideId, ordinal, clientUUID).getId();
updateResponseCode(enabledId, responseCode);
} catch (Exception e) {
e.printStackTrace();
}
} | java | public void updateResponseCode(int overrideId, int pathId, Integer ordinal, String responseCode, String clientUUID) {
if (ordinal == null) {
ordinal = 1;
}
try {
// get ID of the ordinal
int enabledId = getEnabledEndpoint(pathId, overrideId, ordinal, clientUUID).getId();
updateResponseCode(enabledId, responseCode);
} catch (Exception e) {
e.printStackTrace();
}
} | [
"public",
"void",
"updateResponseCode",
"(",
"int",
"overrideId",
",",
"int",
"pathId",
",",
"Integer",
"ordinal",
",",
"String",
"responseCode",
",",
"String",
"clientUUID",
")",
"{",
"if",
"(",
"ordinal",
"==",
"null",
")",
"{",
"ordinal",
"=",
"1",
";",... | Update the response code for a given enabled override
@param overrideId - override ID to update
@param pathId - path ID to update
@param ordinal - can be null, Index of the enabled override to edit if multiple of the same are enabled
@param responseCode - response code for the given response
@param clientUUID - clientUUID | [
"Update",
"the",
"response",
"code",
"for",
"a",
"given",
"enabled",
"override"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/OverrideService.java#L240-L252 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-logging/src/main/java/com/google/cloud/logging/v2/ConfigClient.java | ConfigClient.updateSink | public final LogSink updateSink(String sinkName, LogSink sink) {
UpdateSinkRequest request =
UpdateSinkRequest.newBuilder().setSinkName(sinkName).setSink(sink).build();
return updateSink(request);
} | java | public final LogSink updateSink(String sinkName, LogSink sink) {
UpdateSinkRequest request =
UpdateSinkRequest.newBuilder().setSinkName(sinkName).setSink(sink).build();
return updateSink(request);
} | [
"public",
"final",
"LogSink",
"updateSink",
"(",
"String",
"sinkName",
",",
"LogSink",
"sink",
")",
"{",
"UpdateSinkRequest",
"request",
"=",
"UpdateSinkRequest",
".",
"newBuilder",
"(",
")",
".",
"setSinkName",
"(",
"sinkName",
")",
".",
"setSink",
"(",
"sink... | Updates a sink. This method replaces the following fields in the existing sink with values from
the new sink: `destination`, and `filter`. The updated sink might also have a new
`writer_identity`; see the `unique_writer_identity` field.
<p>Sample code:
<pre><code>
try (ConfigClient configClient = ConfigClient.create()) {
SinkName sinkName = ProjectSinkName.of("[PROJECT]", "[SINK]");
LogSink sink = LogSink.newBuilder().build();
LogSink response = configClient.updateSink(sinkName.toString(), sink);
}
</code></pre>
@param sinkName Required. The full resource name of the sink to update, including the parent
resource and the sink identifier:
<p>"projects/[PROJECT_ID]/sinks/[SINK_ID]"
"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
"billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
"folders/[FOLDER_ID]/sinks/[SINK_ID]"
<p>Example: `"projects/my-project-id/sinks/my-sink-id"`.
@param sink Required. The updated sink, whose name is the same identifier that appears as part
of `sink_name`.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Updates",
"a",
"sink",
".",
"This",
"method",
"replaces",
"the",
"following",
"fields",
"in",
"the",
"existing",
"sink",
"with",
"values",
"from",
"the",
"new",
"sink",
":",
"destination",
"and",
"filter",
".",
"The",
"updated",
"sink",
"might",
"also",
"... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-logging/src/main/java/com/google/cloud/logging/v2/ConfigClient.java#L688-L693 |
inkstand-io/scribble | scribble-file/src/main/java/io/inkstand/scribble/rules/builder/ZipFileBuilder.java | ZipFileBuilder.addResource | public ZipFileBuilder addResource(String zipEntryPath, URL resource) {
this.entryMap.put(zipEntryPath, resource);
return this;
} | java | public ZipFileBuilder addResource(String zipEntryPath, URL resource) {
this.entryMap.put(zipEntryPath, resource);
return this;
} | [
"public",
"ZipFileBuilder",
"addResource",
"(",
"String",
"zipEntryPath",
",",
"URL",
"resource",
")",
"{",
"this",
".",
"entryMap",
".",
"put",
"(",
"zipEntryPath",
",",
"resource",
")",
";",
"return",
"this",
";",
"}"
] | Adds a resource to the Zip File under the path specified.
@param zipEntryPath
the path to the entry in the zip file
@param resource
the resource providing the content for the path. If an empty directory should be added, this value must
@return this builder | [
"Adds",
"a",
"resource",
"to",
"the",
"Zip",
"File",
"under",
"the",
"path",
"specified",
"."
] | train | https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-file/src/main/java/io/inkstand/scribble/rules/builder/ZipFileBuilder.java#L86-L90 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/FileOutputFormat.java | FileOutputFormat.getUniqueName | public static String getUniqueName(JobConf conf, String name) {
int partition = conf.getInt("mapred.task.partition", -1);
if (partition == -1) {
throw new IllegalArgumentException(
"This method can only be called from within a Job");
}
String taskType = (conf.getBoolean("mapred.task.is.map", true)) ? "m" : "r";
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMinimumIntegerDigits(5);
numberFormat.setGroupingUsed(false);
return name + "-" + taskType + "-" + numberFormat.format(partition);
} | java | public static String getUniqueName(JobConf conf, String name) {
int partition = conf.getInt("mapred.task.partition", -1);
if (partition == -1) {
throw new IllegalArgumentException(
"This method can only be called from within a Job");
}
String taskType = (conf.getBoolean("mapred.task.is.map", true)) ? "m" : "r";
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMinimumIntegerDigits(5);
numberFormat.setGroupingUsed(false);
return name + "-" + taskType + "-" + numberFormat.format(partition);
} | [
"public",
"static",
"String",
"getUniqueName",
"(",
"JobConf",
"conf",
",",
"String",
"name",
")",
"{",
"int",
"partition",
"=",
"conf",
".",
"getInt",
"(",
"\"mapred.task.partition\"",
",",
"-",
"1",
")",
";",
"if",
"(",
"partition",
"==",
"-",
"1",
")"... | Helper function to generate a name that is unique for the task.
<p>The generated name can be used to create custom files from within the
different tasks for the job, the names for different tasks will not collide
with each other.</p>
<p>The given name is postfixed with the task type, 'm' for maps, 'r' for
reduces and the task partition number. For example, give a name 'test'
running on the first map o the job the generated name will be
'test-m-00000'.</p>
@param conf the configuration for the job.
@param name the name to make unique.
@return a unique name accross all tasks of the job. | [
"Helper",
"function",
"to",
"generate",
"a",
"name",
"that",
"is",
"unique",
"for",
"the",
"task",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/FileOutputFormat.java#L268-L282 |
alibaba/jstorm | jstorm-core/src/main/java/backtype/storm/topology/base/BaseWindowedBolt.java | BaseWindowedBolt.withWindow | public BaseWindowedBolt withWindow(Count windowLength, Duration slidingInterval) {
return withWindowLength(windowLength).withSlidingInterval(slidingInterval);
} | java | public BaseWindowedBolt withWindow(Count windowLength, Duration slidingInterval) {
return withWindowLength(windowLength).withSlidingInterval(slidingInterval);
} | [
"public",
"BaseWindowedBolt",
"withWindow",
"(",
"Count",
"windowLength",
",",
"Duration",
"slidingInterval",
")",
"{",
"return",
"withWindowLength",
"(",
"windowLength",
")",
".",
"withSlidingInterval",
"(",
"slidingInterval",
")",
";",
"}"
] | Tuple count and time duration based sliding window configuration.
@param windowLength the number of tuples in the window
@param slidingInterval the time duration after which the window slides | [
"Tuple",
"count",
"and",
"time",
"duration",
"based",
"sliding",
"window",
"configuration",
"."
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/base/BaseWindowedBolt.java#L100-L102 |
spring-projects/spring-android | spring-android-rest-template/src/main/java/org/springframework/http/HttpHeaders.java | HttpHeaders.setDate | public void setDate(String headerName, long date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMATS[0], Locale.US);
dateFormat.setTimeZone(GMT);
set(headerName, dateFormat.format(new Date(date)));
} | java | public void setDate(String headerName, long date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMATS[0], Locale.US);
dateFormat.setTimeZone(GMT);
set(headerName, dateFormat.format(new Date(date)));
} | [
"public",
"void",
"setDate",
"(",
"String",
"headerName",
",",
"long",
"date",
")",
"{",
"SimpleDateFormat",
"dateFormat",
"=",
"new",
"SimpleDateFormat",
"(",
"DATE_FORMATS",
"[",
"0",
"]",
",",
"Locale",
".",
"US",
")",
";",
"dateFormat",
".",
"setTimeZone... | Set the given date under the given header name after formatting it as a string
using the pattern {@code "EEE, dd MMM yyyy HH:mm:ss zzz"}. The equivalent of
{@link #set(String, String)} but for date headers. | [
"Set",
"the",
"given",
"date",
"under",
"the",
"given",
"header",
"name",
"after",
"formatting",
"it",
"as",
"a",
"string",
"using",
"the",
"pattern",
"{"
] | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-rest-template/src/main/java/org/springframework/http/HttpHeaders.java#L910-L914 |
Wolfgang-Schuetzelhofer/jcypher | src/main/java/iot/jcypher/graph/Graph.java | Graph.createRelation | public GrRelation createRelation(String type, GrNode startNode, GrNode endNode) {
return this.resultHandler.getLocalElements().createRelation(type, startNode, endNode);
} | java | public GrRelation createRelation(String type, GrNode startNode, GrNode endNode) {
return this.resultHandler.getLocalElements().createRelation(type, startNode, endNode);
} | [
"public",
"GrRelation",
"createRelation",
"(",
"String",
"type",
",",
"GrNode",
"startNode",
",",
"GrNode",
"endNode",
")",
"{",
"return",
"this",
".",
"resultHandler",
".",
"getLocalElements",
"(",
")",
".",
"createRelation",
"(",
"type",
",",
"startNode",
",... | create a relation in the graph
@param type
@param startNode
@param endNode
@return a GrRelation | [
"create",
"a",
"relation",
"in",
"the",
"graph"
] | train | https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/graph/Graph.java#L77-L79 |
lecousin/java-framework-core | net.lecousin.core/src/main/java/net/lecousin/framework/concurrent/synch/JoinPoint.java | JoinPoint.listenInline | public static void listenInline(Runnable listener, ISynchronizationPoint<?>... synchPoints) {
JoinPoint<Exception> jp = new JoinPoint<>();
for (int i = 0; i < synchPoints.length; ++i)
if (synchPoints[i] != null)
jp.addToJoin(synchPoints[i]);
jp.start();
jp.listenInline(listener);
} | java | public static void listenInline(Runnable listener, ISynchronizationPoint<?>... synchPoints) {
JoinPoint<Exception> jp = new JoinPoint<>();
for (int i = 0; i < synchPoints.length; ++i)
if (synchPoints[i] != null)
jp.addToJoin(synchPoints[i]);
jp.start();
jp.listenInline(listener);
} | [
"public",
"static",
"void",
"listenInline",
"(",
"Runnable",
"listener",
",",
"ISynchronizationPoint",
"<",
"?",
">",
"...",
"synchPoints",
")",
"{",
"JoinPoint",
"<",
"Exception",
">",
"jp",
"=",
"new",
"JoinPoint",
"<>",
"(",
")",
";",
"for",
"(",
"int",... | Shortcut method to create a JoinPoint waiting for the given synchronization points, start the JoinPoint,
and add the given listener to be called when the JoinPoint is unblocked.
If any synchronization point has an error or is cancelled, the JoinPoint is immediately unblocked.
If some given synchronization points are null, they are just skipped. | [
"Shortcut",
"method",
"to",
"create",
"a",
"JoinPoint",
"waiting",
"for",
"the",
"given",
"synchronization",
"points",
"start",
"the",
"JoinPoint",
"and",
"add",
"the",
"given",
"listener",
"to",
"be",
"called",
"when",
"the",
"JoinPoint",
"is",
"unblocked",
"... | train | https://github.com/lecousin/java-framework-core/blob/b0c893b44bfde2c03f90ea846a49ef5749d598f3/net.lecousin.core/src/main/java/net/lecousin/framework/concurrent/synch/JoinPoint.java#L275-L282 |
jOOQ/jOOL | jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java | Unchecked.doubleFunction | public static <R> DoubleFunction<R> doubleFunction(CheckedDoubleFunction<R> function, Consumer<Throwable> handler) {
return t -> {
try {
return function.apply(t);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
}
};
} | java | public static <R> DoubleFunction<R> doubleFunction(CheckedDoubleFunction<R> function, Consumer<Throwable> handler) {
return t -> {
try {
return function.apply(t);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
}
};
} | [
"public",
"static",
"<",
"R",
">",
"DoubleFunction",
"<",
"R",
">",
"doubleFunction",
"(",
"CheckedDoubleFunction",
"<",
"R",
">",
"function",
",",
"Consumer",
"<",
"Throwable",
">",
"handler",
")",
"{",
"return",
"t",
"->",
"{",
"try",
"{",
"return",
"f... | Wrap a {@link CheckedDoubleFunction} in a {@link DoubleFunction} with a custom handler for checked exceptions.
<p>
Example:
<code><pre>
DoubleStream.of(1.0, 2.0, 3.0).mapToObj(Unchecked.doubleFunction(
d -> {
if (d < 0.0)
throw new Exception("Only positive numbers allowed");
return "" + d;
},
e -> {
throw new IllegalStateException(e);
}
));
</pre></code> | [
"Wrap",
"a",
"{",
"@link",
"CheckedDoubleFunction",
"}",
"in",
"a",
"{",
"@link",
"DoubleFunction",
"}",
"with",
"a",
"custom",
"handler",
"for",
"checked",
"exceptions",
".",
"<p",
">",
"Example",
":",
"<code",
">",
"<pre",
">",
"DoubleStream",
".",
"of",... | train | https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1355-L1366 |
census-instrumentation/opencensus-java | api/src/main/java/io/opencensus/internal/Utils.java | Utils.checkMapElementNotNull | public static <K /*>>> extends @NonNull Object*/, V /*>>> extends @NonNull Object*/>
void checkMapElementNotNull(Map<K, V> map, @javax.annotation.Nullable Object errorMessage) {
for (Map.Entry<K, V> entry : map.entrySet()) {
if (entry.getKey() == null || entry.getValue() == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
}
} | java | public static <K /*>>> extends @NonNull Object*/, V /*>>> extends @NonNull Object*/>
void checkMapElementNotNull(Map<K, V> map, @javax.annotation.Nullable Object errorMessage) {
for (Map.Entry<K, V> entry : map.entrySet()) {
if (entry.getKey() == null || entry.getValue() == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
}
} | [
"public",
"static",
"<",
"K",
"/*>>> extends @NonNull Object*/",
",",
"V",
"/*>>> extends @NonNull Object*/",
">",
"void",
"checkMapElementNotNull",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"map",
",",
"@",
"javax",
".",
"annotation",
".",
"Nullable",
"Object",
"err... | Throws a {@link NullPointerException} if any of the map elements is null.
@param map the argument map to check for null.
@param errorMessage the message to use for the exception. Will be converted to a string using
{@link String#valueOf(Object)}. | [
"Throws",
"a",
"{",
"@link",
"NullPointerException",
"}",
"if",
"any",
"of",
"the",
"map",
"elements",
"is",
"null",
"."
] | train | https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/internal/Utils.java#L143-L150 |
WASdev/standards.jsr352.jbatch | com.ibm.jbatch.container/src/main/java/com/ibm/jbatch/container/impl/BatchKernelImpl.java | BatchKernelImpl.buildOnRestartParallelPartitions | @Override
public List<BatchPartitionWorkUnit> buildOnRestartParallelPartitions(PartitionsBuilderConfig config) throws JobRestartException, JobExecutionAlreadyCompleteException, JobExecutionNotMostRecentException {
List<JSLJob> jobModels = config.getJobModels();
Properties[] partitionProperties = config.getPartitionProperties();
List<BatchPartitionWorkUnit> batchWorkUnits = new ArrayList<BatchPartitionWorkUnit>(jobModels.size());
//for now let always use a Properties array. We can add some more convenience methods later for null properties and what not
int instance = 0;
for (JSLJob parallelJob : jobModels){
Properties partitionProps = (partitionProperties == null) ? null : partitionProperties[instance];
try {
long execId = getMostRecentSubJobExecutionId(parallelJob);
RuntimeJobExecution jobExecution = null;
try {
jobExecution = JobExecutionHelper.restartPartition(execId, parallelJob, partitionProps);
jobExecution.setPartitionInstance(instance);
} catch (NoSuchJobExecutionException e) {
String errorMsg = "Caught NoSuchJobExecutionException but this is an internal JobExecution so this shouldn't have happened: execId =" + execId;
logger.severe(errorMsg);
throw new IllegalStateException(errorMsg, e);
}
if (logger.isLoggable(Level.FINE)) {
logger.fine("JobExecution constructed: " + jobExecution);
}
BatchPartitionWorkUnit batchWork = new BatchPartitionWorkUnit(this, jobExecution, config);
registerCurrentInstanceAndExecution(jobExecution, batchWork.getController());
batchWorkUnits.add(batchWork);
} catch (JobExecutionAlreadyCompleteException e) {
logger.fine("This execution already completed: " + parallelJob.getId());
}
instance++;
}
return batchWorkUnits;
} | java | @Override
public List<BatchPartitionWorkUnit> buildOnRestartParallelPartitions(PartitionsBuilderConfig config) throws JobRestartException, JobExecutionAlreadyCompleteException, JobExecutionNotMostRecentException {
List<JSLJob> jobModels = config.getJobModels();
Properties[] partitionProperties = config.getPartitionProperties();
List<BatchPartitionWorkUnit> batchWorkUnits = new ArrayList<BatchPartitionWorkUnit>(jobModels.size());
//for now let always use a Properties array. We can add some more convenience methods later for null properties and what not
int instance = 0;
for (JSLJob parallelJob : jobModels){
Properties partitionProps = (partitionProperties == null) ? null : partitionProperties[instance];
try {
long execId = getMostRecentSubJobExecutionId(parallelJob);
RuntimeJobExecution jobExecution = null;
try {
jobExecution = JobExecutionHelper.restartPartition(execId, parallelJob, partitionProps);
jobExecution.setPartitionInstance(instance);
} catch (NoSuchJobExecutionException e) {
String errorMsg = "Caught NoSuchJobExecutionException but this is an internal JobExecution so this shouldn't have happened: execId =" + execId;
logger.severe(errorMsg);
throw new IllegalStateException(errorMsg, e);
}
if (logger.isLoggable(Level.FINE)) {
logger.fine("JobExecution constructed: " + jobExecution);
}
BatchPartitionWorkUnit batchWork = new BatchPartitionWorkUnit(this, jobExecution, config);
registerCurrentInstanceAndExecution(jobExecution, batchWork.getController());
batchWorkUnits.add(batchWork);
} catch (JobExecutionAlreadyCompleteException e) {
logger.fine("This execution already completed: " + parallelJob.getId());
}
instance++;
}
return batchWorkUnits;
} | [
"@",
"Override",
"public",
"List",
"<",
"BatchPartitionWorkUnit",
">",
"buildOnRestartParallelPartitions",
"(",
"PartitionsBuilderConfig",
"config",
")",
"throws",
"JobRestartException",
",",
"JobExecutionAlreadyCompleteException",
",",
"JobExecutionNotMostRecentException",
"{",
... | /*
There are some assumptions that all partition subjobs have associated DB entries | [
"/",
"*",
"There",
"are",
"some",
"assumptions",
"that",
"all",
"partition",
"subjobs",
"have",
"associated",
"DB",
"entries"
] | train | https://github.com/WASdev/standards.jsr352.jbatch/blob/e267e79dccd4f0bd4bf9c2abc41a8a47b65be28f/com.ibm.jbatch.container/src/main/java/com/ibm/jbatch/container/impl/BatchKernelImpl.java#L304-L348 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java | RSAUtils.decryptWithPrivateKey | public static byte[] decryptWithPrivateKey(String base64PrivateKeyData, byte[] encryptedData,
String cipherTransformation)
throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
RSAPrivateKey privateKey = buildPrivateKey(base64PrivateKeyData);
return decrypt(privateKey, encryptedData, cipherTransformation);
} | java | public static byte[] decryptWithPrivateKey(String base64PrivateKeyData, byte[] encryptedData,
String cipherTransformation)
throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
RSAPrivateKey privateKey = buildPrivateKey(base64PrivateKeyData);
return decrypt(privateKey, encryptedData, cipherTransformation);
} | [
"public",
"static",
"byte",
"[",
"]",
"decryptWithPrivateKey",
"(",
"String",
"base64PrivateKeyData",
",",
"byte",
"[",
"]",
"encryptedData",
",",
"String",
"cipherTransformation",
")",
"throws",
"NoSuchAlgorithmException",
",",
"InvalidKeySpecException",
",",
"InvalidK... | Decrypt encrypted data with RSA private key.
<p>
Note: if long data was encrypted using
{@link #encryptWithPublicKey(String, byte[], String, int)}, it will be correctly decrypted.
</p>
@param base64PrivateKeyData
RSA private key in base64 (base64 of {@link RSAPrivateKey#getEncoded()})
@param encryptedData
@param cipherTransformation
cipher-transformation to use. If empty, {@link #DEFAULT_CIPHER_TRANSFORMATION}
will be used
@return
@throws NoSuchAlgorithmException
@throws InvalidKeySpecException
@throws InvalidKeyException
@throws NoSuchPaddingException
@throws IllegalBlockSizeException
@throws BadPaddingException
@throws IOException | [
"Decrypt",
"encrypted",
"data",
"with",
"RSA",
"private",
"key",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java#L750-L756 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/learning/legacy/AdaGrad.java | AdaGrad.getGradient | public INDArray getGradient(INDArray gradient, int iteration) {
if (historicalGradient == null)
throw new IllegalStateException("Updater has not been initialized with view state");
historicalGradient.addi(gradient.mul(gradient));
INDArray sqrtHistory = sqrt(historicalGradient.dup(gradientReshapeOrder), false).addi(epsilon);
// lr * gradient / (sqrt(sumSquaredGradients) + epsilon)
INDArray ret = gradient.muli(sqrtHistory.rdivi(learningRate));
numIterations++;
return ret;
} | java | public INDArray getGradient(INDArray gradient, int iteration) {
if (historicalGradient == null)
throw new IllegalStateException("Updater has not been initialized with view state");
historicalGradient.addi(gradient.mul(gradient));
INDArray sqrtHistory = sqrt(historicalGradient.dup(gradientReshapeOrder), false).addi(epsilon);
// lr * gradient / (sqrt(sumSquaredGradients) + epsilon)
INDArray ret = gradient.muli(sqrtHistory.rdivi(learningRate));
numIterations++;
return ret;
} | [
"public",
"INDArray",
"getGradient",
"(",
"INDArray",
"gradient",
",",
"int",
"iteration",
")",
"{",
"if",
"(",
"historicalGradient",
"==",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Updater has not been initialized with view state\"",
")",
";",
"hi... | Gets feature specific learning rates
Adagrad keeps a history of gradients being passed in.
Note that each gradient passed in becomes adapted over time, hence
the opName adagrad
@param gradient the gradient to get learning rates for
@param iteration
@return the feature specific learning rates | [
"Gets",
"feature",
"specific",
"learning",
"rates",
"Adagrad",
"keeps",
"a",
"history",
"of",
"gradients",
"being",
"passed",
"in",
".",
"Note",
"that",
"each",
"gradient",
"passed",
"in",
"becomes",
"adapted",
"over",
"time",
"hence",
"the",
"opName",
"adagra... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/learning/legacy/AdaGrad.java#L114-L125 |
mapbox/mapbox-navigation-android | libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/instruction/InstructionView.java | InstructionView.initializeInstructionListRecyclerView | private void initializeInstructionListRecyclerView() {
RouteUtils routeUtils = new RouteUtils();
instructionListAdapter = new InstructionListAdapter(routeUtils, distanceFormatter);
rvInstructions.setAdapter(instructionListAdapter);
rvInstructions.setHasFixedSize(true);
rvInstructions.setLayoutManager(new LinearLayoutManager(getContext()));
} | java | private void initializeInstructionListRecyclerView() {
RouteUtils routeUtils = new RouteUtils();
instructionListAdapter = new InstructionListAdapter(routeUtils, distanceFormatter);
rvInstructions.setAdapter(instructionListAdapter);
rvInstructions.setHasFixedSize(true);
rvInstructions.setLayoutManager(new LinearLayoutManager(getContext()));
} | [
"private",
"void",
"initializeInstructionListRecyclerView",
"(",
")",
"{",
"RouteUtils",
"routeUtils",
"=",
"new",
"RouteUtils",
"(",
")",
";",
"instructionListAdapter",
"=",
"new",
"InstructionListAdapter",
"(",
"routeUtils",
",",
"distanceFormatter",
")",
";",
"rvIn... | Sets up the {@link RecyclerView} that is used to display the list of instructions. | [
"Sets",
"up",
"the",
"{"
] | train | https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/instruction/InstructionView.java#L470-L476 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/RestServerEndpointConfiguration.java | RestServerEndpointConfiguration.fromConfiguration | public static RestServerEndpointConfiguration fromConfiguration(Configuration config) throws ConfigurationException {
Preconditions.checkNotNull(config);
final String restAddress = Preconditions.checkNotNull(config.getString(RestOptions.ADDRESS),
"%s must be set",
RestOptions.ADDRESS.key());
final String restBindAddress = config.getString(RestOptions.BIND_ADDRESS);
final String portRangeDefinition = config.getString(RestOptions.BIND_PORT);
final SSLHandlerFactory sslHandlerFactory;
if (SSLUtils.isRestSSLEnabled(config)) {
try {
sslHandlerFactory = SSLUtils.createRestServerSSLEngineFactory(config);
} catch (Exception e) {
throw new ConfigurationException("Failed to initialize SSLEngineFactory for REST server endpoint.", e);
}
} else {
sslHandlerFactory = null;
}
final Path uploadDir = Paths.get(
config.getString(WebOptions.UPLOAD_DIR, config.getString(WebOptions.TMP_DIR)),
"flink-web-upload");
final int maxContentLength = config.getInteger(RestOptions.SERVER_MAX_CONTENT_LENGTH);
final Map<String, String> responseHeaders = Collections.singletonMap(
HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN,
config.getString(WebOptions.ACCESS_CONTROL_ALLOW_ORIGIN));
return new RestServerEndpointConfiguration(
restAddress,
restBindAddress,
portRangeDefinition,
sslHandlerFactory,
uploadDir,
maxContentLength,
responseHeaders);
} | java | public static RestServerEndpointConfiguration fromConfiguration(Configuration config) throws ConfigurationException {
Preconditions.checkNotNull(config);
final String restAddress = Preconditions.checkNotNull(config.getString(RestOptions.ADDRESS),
"%s must be set",
RestOptions.ADDRESS.key());
final String restBindAddress = config.getString(RestOptions.BIND_ADDRESS);
final String portRangeDefinition = config.getString(RestOptions.BIND_PORT);
final SSLHandlerFactory sslHandlerFactory;
if (SSLUtils.isRestSSLEnabled(config)) {
try {
sslHandlerFactory = SSLUtils.createRestServerSSLEngineFactory(config);
} catch (Exception e) {
throw new ConfigurationException("Failed to initialize SSLEngineFactory for REST server endpoint.", e);
}
} else {
sslHandlerFactory = null;
}
final Path uploadDir = Paths.get(
config.getString(WebOptions.UPLOAD_DIR, config.getString(WebOptions.TMP_DIR)),
"flink-web-upload");
final int maxContentLength = config.getInteger(RestOptions.SERVER_MAX_CONTENT_LENGTH);
final Map<String, String> responseHeaders = Collections.singletonMap(
HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN,
config.getString(WebOptions.ACCESS_CONTROL_ALLOW_ORIGIN));
return new RestServerEndpointConfiguration(
restAddress,
restBindAddress,
portRangeDefinition,
sslHandlerFactory,
uploadDir,
maxContentLength,
responseHeaders);
} | [
"public",
"static",
"RestServerEndpointConfiguration",
"fromConfiguration",
"(",
"Configuration",
"config",
")",
"throws",
"ConfigurationException",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"config",
")",
";",
"final",
"String",
"restAddress",
"=",
"Preconditions",... | Creates and returns a new {@link RestServerEndpointConfiguration} from the given {@link Configuration}.
@param config configuration from which the REST server endpoint configuration should be created from
@return REST server endpoint configuration
@throws ConfigurationException if SSL was configured incorrectly | [
"Creates",
"and",
"returns",
"a",
"new",
"{",
"@link",
"RestServerEndpointConfiguration",
"}",
"from",
"the",
"given",
"{",
"@link",
"Configuration",
"}",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/rest/RestServerEndpointConfiguration.java#L147-L186 |
percolate/caffeine | caffeine/src/main/java/com/percolate/caffeine/ViewUtils.java | ViewUtils.hideView | public static void hideView(Activity context, int id) {
if (context != null) {
View view = context.findViewById(id);
if (view != null) {
view.setVisibility(View.GONE);
} else {
Log.e("Caffeine", "View does not exist. Could not hide it.");
}
}
} | java | public static void hideView(Activity context, int id) {
if (context != null) {
View view = context.findViewById(id);
if (view != null) {
view.setVisibility(View.GONE);
} else {
Log.e("Caffeine", "View does not exist. Could not hide it.");
}
}
} | [
"public",
"static",
"void",
"hideView",
"(",
"Activity",
"context",
",",
"int",
"id",
")",
"{",
"if",
"(",
"context",
"!=",
"null",
")",
"{",
"View",
"view",
"=",
"context",
".",
"findViewById",
"(",
"id",
")",
";",
"if",
"(",
"view",
"!=",
"null",
... | Sets visibility of the given view to <code>View.GONE</code>.
@param context The current Context or Activity that this method is called from.
@param id R.id.xxxx value for the view to hide"expected textView to throw a ClassCastException" + textView. | [
"Sets",
"visibility",
"of",
"the",
"given",
"view",
"to",
"<code",
">",
"View",
".",
"GONE<",
"/",
"code",
">",
"."
] | train | https://github.com/percolate/caffeine/blob/e2265cab474a6397f4d75b1ed928c356a7b9672e/caffeine/src/main/java/com/percolate/caffeine/ViewUtils.java#L232-L241 |
podio/podio-java | src/main/java/com/podio/tag/TagAPI.java | TagAPI.removeTag | public void removeTag(Reference reference, String tag) {
getResourceFactory()
.getApiResource("/tag/" + reference.toURLFragment())
.queryParam("text", tag).delete();
} | java | public void removeTag(Reference reference, String tag) {
getResourceFactory()
.getApiResource("/tag/" + reference.toURLFragment())
.queryParam("text", tag).delete();
} | [
"public",
"void",
"removeTag",
"(",
"Reference",
"reference",
",",
"String",
"tag",
")",
"{",
"getResourceFactory",
"(",
")",
".",
"getApiResource",
"(",
"\"/tag/\"",
"+",
"reference",
".",
"toURLFragment",
"(",
")",
")",
".",
"queryParam",
"(",
"\"text\"",
... | Removes a single tag from an object.
@param reference
The object the tag should be removed from
@param tag
The tag to remove | [
"Removes",
"a",
"single",
"tag",
"from",
"an",
"object",
"."
] | train | https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/tag/TagAPI.java#L91-L95 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/util/ItemUtils.java | ItemUtils.areItemStacksStackable | public static boolean areItemStacksStackable(ItemStack stack1, ItemStack stack2)
{
return !(stack1.isEmpty() || stack2.isEmpty()) && stack1.isStackable() && stack1.getItem() == stack2.getItem()
&& (!stack2.getHasSubtypes() || stack2.getMetadata() == stack1.getMetadata())
&& ItemStack.areItemStackTagsEqual(stack2, stack1);
} | java | public static boolean areItemStacksStackable(ItemStack stack1, ItemStack stack2)
{
return !(stack1.isEmpty() || stack2.isEmpty()) && stack1.isStackable() && stack1.getItem() == stack2.getItem()
&& (!stack2.getHasSubtypes() || stack2.getMetadata() == stack1.getMetadata())
&& ItemStack.areItemStackTagsEqual(stack2, stack1);
} | [
"public",
"static",
"boolean",
"areItemStacksStackable",
"(",
"ItemStack",
"stack1",
",",
"ItemStack",
"stack2",
")",
"{",
"return",
"!",
"(",
"stack1",
".",
"isEmpty",
"(",
")",
"||",
"stack2",
".",
"isEmpty",
"(",
")",
")",
"&&",
"stack1",
".",
"isStacka... | Checks whether two {@link ItemStack itemStacks} can be stacked together
@param stack1 first itemStack
@param stack2 second itemStack
@return true, if the itemStack can be stacked, false otherwise | [
"Checks",
"whether",
"two",
"{",
"@link",
"ItemStack",
"itemStacks",
"}",
"can",
"be",
"stacked",
"together"
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/ItemUtils.java#L232-L238 |
google/error-prone | check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java | ASTHelpers.hasAnnotation | public static boolean hasAnnotation(Symbol sym, String annotationClass, VisitorState state) {
if (sym == null) {
return false;
}
// normalize to non-binary names
annotationClass = annotationClass.replace('$', '.');
Name annotationName = state.getName(annotationClass);
if (hasAttribute(sym, annotationName)) {
return true;
}
if (isInherited(state, annotationClass)) {
while (sym instanceof ClassSymbol) {
if (hasAttribute(sym, annotationName)) {
return true;
}
sym = ((ClassSymbol) sym).getSuperclass().tsym;
}
}
return false;
} | java | public static boolean hasAnnotation(Symbol sym, String annotationClass, VisitorState state) {
if (sym == null) {
return false;
}
// normalize to non-binary names
annotationClass = annotationClass.replace('$', '.');
Name annotationName = state.getName(annotationClass);
if (hasAttribute(sym, annotationName)) {
return true;
}
if (isInherited(state, annotationClass)) {
while (sym instanceof ClassSymbol) {
if (hasAttribute(sym, annotationName)) {
return true;
}
sym = ((ClassSymbol) sym).getSuperclass().tsym;
}
}
return false;
} | [
"public",
"static",
"boolean",
"hasAnnotation",
"(",
"Symbol",
"sym",
",",
"String",
"annotationClass",
",",
"VisitorState",
"state",
")",
"{",
"if",
"(",
"sym",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"// normalize to non-binary names",
"annotation... | Determines whether a symbol has an annotation of the given type. This includes annotations
inherited from superclasses due to {@code @Inherited}.
@param annotationClass the binary class name of the annotation (e.g.
"javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName")
@return true if the symbol is annotated with given type. | [
"Determines",
"whether",
"a",
"symbol",
"has",
"an",
"annotation",
"of",
"the",
"given",
"type",
".",
"This",
"includes",
"annotations",
"inherited",
"from",
"superclasses",
"due",
"to",
"{",
"@code",
"@Inherited",
"}",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L659-L678 |
craftercms/deployer | src/main/java/org/craftercms/deployer/utils/ConfigUtils.java | ConfigUtils.loadYamlConfiguration | public static YamlConfiguration loadYamlConfiguration(File file) throws DeployerConfigurationException {
try {
try (Reader reader = new BufferedReader(new FileReader(file))) {
return doLoadYamlConfiguration(reader);
}
} catch (Exception e) {
throw new DeployerConfigurationException("Failed to load YAML configuration at " + file, e);
}
} | java | public static YamlConfiguration loadYamlConfiguration(File file) throws DeployerConfigurationException {
try {
try (Reader reader = new BufferedReader(new FileReader(file))) {
return doLoadYamlConfiguration(reader);
}
} catch (Exception e) {
throw new DeployerConfigurationException("Failed to load YAML configuration at " + file, e);
}
} | [
"public",
"static",
"YamlConfiguration",
"loadYamlConfiguration",
"(",
"File",
"file",
")",
"throws",
"DeployerConfigurationException",
"{",
"try",
"{",
"try",
"(",
"Reader",
"reader",
"=",
"new",
"BufferedReader",
"(",
"new",
"FileReader",
"(",
"file",
")",
")",
... | Loads the specified file as {@link YamlConfiguration}.
@param file the YAML configuration file to load
@return the YAML configuration
@throws DeployerConfigurationException if an error occurred | [
"Loads",
"the",
"specified",
"file",
"as",
"{",
"@link",
"YamlConfiguration",
"}",
"."
] | train | https://github.com/craftercms/deployer/blob/3ed446e3cc8af1055de2de6f871907f90ef27f63/src/main/java/org/craftercms/deployer/utils/ConfigUtils.java#L55-L63 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java | RoaringArray.appendCopiesUntil | protected void appendCopiesUntil(RoaringArray sourceArray, short stoppingKey) {
int stopKey = Util.toIntUnsigned(stoppingKey);
for (int i = 0; i < sourceArray.size; ++i) {
if (Util.toIntUnsigned(sourceArray.keys[i]) >= stopKey) {
break;
}
extendArray(1);
this.keys[this.size] = sourceArray.keys[i];
this.values[this.size] = sourceArray.values[i].clone();
this.size++;
}
} | java | protected void appendCopiesUntil(RoaringArray sourceArray, short stoppingKey) {
int stopKey = Util.toIntUnsigned(stoppingKey);
for (int i = 0; i < sourceArray.size; ++i) {
if (Util.toIntUnsigned(sourceArray.keys[i]) >= stopKey) {
break;
}
extendArray(1);
this.keys[this.size] = sourceArray.keys[i];
this.values[this.size] = sourceArray.values[i].clone();
this.size++;
}
} | [
"protected",
"void",
"appendCopiesUntil",
"(",
"RoaringArray",
"sourceArray",
",",
"short",
"stoppingKey",
")",
"{",
"int",
"stopKey",
"=",
"Util",
".",
"toIntUnsigned",
"(",
"stoppingKey",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"source... | Append copies of the values from another array, from the start
@param sourceArray The array to copy from
@param stoppingKey any equal or larger key in other array will terminate copying | [
"Append",
"copies",
"of",
"the",
"values",
"from",
"another",
"array",
"from",
"the",
"start"
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java#L175-L186 |
CODAIT/stocator | src/main/java/com/ibm/stocator/fs/cos/COSInputStream.java | COSInputStream.lazySeek | private void lazySeek(long targetPos, long len) throws IOException {
//For lazy seek
seekInStream(targetPos, len);
//re-open at specific location if needed
if (wrappedStream == null) {
reopen("read from new offset", targetPos, len);
}
} | java | private void lazySeek(long targetPos, long len) throws IOException {
//For lazy seek
seekInStream(targetPos, len);
//re-open at specific location if needed
if (wrappedStream == null) {
reopen("read from new offset", targetPos, len);
}
} | [
"private",
"void",
"lazySeek",
"(",
"long",
"targetPos",
",",
"long",
"len",
")",
"throws",
"IOException",
"{",
"//For lazy seek",
"seekInStream",
"(",
"targetPos",
",",
"len",
")",
";",
"//re-open at specific location if needed",
"if",
"(",
"wrappedStream",
"==",
... | Perform lazy seek and adjust stream to correct position for reading.
@param targetPos position from where data should be read
@param len length of the content that needs to be read | [
"Perform",
"lazy",
"seek",
"and",
"adjust",
"stream",
"to",
"correct",
"position",
"for",
"reading",
"."
] | train | https://github.com/CODAIT/stocator/blob/35969cadd2e8faa6fdac45e8bec1799fdd3d8299/src/main/java/com/ibm/stocator/fs/cos/COSInputStream.java#L245-L253 |
tvesalainen/util | util/src/main/java/org/vesalainen/ui/Scaler.java | Scaler.getLevelFor | public ScaleLevel getLevelFor(Font font, boolean horizontal, double xy)
{
return getLevelFor(font, DEFAULT_FONTRENDERCONTEXT, horizontal, xy);
} | java | public ScaleLevel getLevelFor(Font font, boolean horizontal, double xy)
{
return getLevelFor(font, DEFAULT_FONTRENDERCONTEXT, horizontal, xy);
} | [
"public",
"ScaleLevel",
"getLevelFor",
"(",
"Font",
"font",
",",
"boolean",
"horizontal",
",",
"double",
"xy",
")",
"{",
"return",
"getLevelFor",
"(",
"font",
",",
"DEFAULT_FONTRENDERCONTEXT",
",",
"horizontal",
",",
"xy",
")",
";",
"}"
] | Returns highest level where drawn labels don't overlap using identity
transformer and FontRenderContext with identity AffineTransform, no
anti-aliasing and fractional metrics
@param font
@param horizontal
@param xy Lines constant value
@return | [
"Returns",
"highest",
"level",
"where",
"drawn",
"labels",
"don",
"t",
"overlap",
"using",
"identity",
"transformer",
"and",
"FontRenderContext",
"with",
"identity",
"AffineTransform",
"no",
"anti",
"-",
"aliasing",
"and",
"fractional",
"metrics"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/ui/Scaler.java#L110-L113 |
blackfizz/EazeGraph | EazeGraphLibrary/src/main/java/org/eazegraph/lib/charts/BarChart.java | BarChart.calculateBounds | protected void calculateBounds(float _Width, float _Margin) {
float maxValue = 0;
int last = 0;
for (BarModel model : mData) {
if(model.getValue() > maxValue) {
maxValue = model.getValue();
}
}
int valuePadding = mShowValues ? (int) mValuePaint.getTextSize() + mValueDistance : 0;
float heightMultiplier = (mGraphHeight - valuePadding) / maxValue;
for (BarModel model : mData) {
float height = model.getValue() * heightMultiplier;
last += _Margin / 2;
model.setBarBounds(new RectF(last, mGraphHeight - height, last + _Width, mGraphHeight));
model.setLegendBounds(new RectF(last, 0, last + _Width, mLegendHeight));
last += _Width + (_Margin / 2);
}
Utils.calculateLegendInformation(mData, 0, mContentRect.width(), mLegendPaint);
} | java | protected void calculateBounds(float _Width, float _Margin) {
float maxValue = 0;
int last = 0;
for (BarModel model : mData) {
if(model.getValue() > maxValue) {
maxValue = model.getValue();
}
}
int valuePadding = mShowValues ? (int) mValuePaint.getTextSize() + mValueDistance : 0;
float heightMultiplier = (mGraphHeight - valuePadding) / maxValue;
for (BarModel model : mData) {
float height = model.getValue() * heightMultiplier;
last += _Margin / 2;
model.setBarBounds(new RectF(last, mGraphHeight - height, last + _Width, mGraphHeight));
model.setLegendBounds(new RectF(last, 0, last + _Width, mLegendHeight));
last += _Width + (_Margin / 2);
}
Utils.calculateLegendInformation(mData, 0, mContentRect.width(), mLegendPaint);
} | [
"protected",
"void",
"calculateBounds",
"(",
"float",
"_Width",
",",
"float",
"_Margin",
")",
"{",
"float",
"maxValue",
"=",
"0",
";",
"int",
"last",
"=",
"0",
";",
"for",
"(",
"BarModel",
"model",
":",
"mData",
")",
"{",
"if",
"(",
"model",
".",
"ge... | Calculates the bar boundaries based on the bar width and bar margin.
@param _Width Calculated bar width
@param _Margin Calculated bar margin | [
"Calculates",
"the",
"bar",
"boundaries",
"based",
"on",
"the",
"bar",
"width",
"and",
"bar",
"margin",
"."
] | train | https://github.com/blackfizz/EazeGraph/blob/ce5e68ecc70e154f83bbb2fcce1a970db125c1e6/EazeGraphLibrary/src/main/java/org/eazegraph/lib/charts/BarChart.java#L175-L198 |
graknlabs/grakn | server/src/server/kb/Validator.java | Validator.validateRule | private void validateRule(TransactionOLTP graph, Rule rule) {
Set<String> labelErrors = ValidateGlobalRules.validateRuleSchemaConceptExist(graph, rule);
errorsFound.addAll(labelErrors);
if (labelErrors.isEmpty()) {
Set<String> ontologicalErrors = ValidateGlobalRules.validateRuleOntologically(graph, rule);
errorsFound.addAll(ontologicalErrors);
if (ontologicalErrors.isEmpty()) {
errorsFound.addAll(ValidateGlobalRules.validateRuleIsValidClause(graph, rule));
}
}
} | java | private void validateRule(TransactionOLTP graph, Rule rule) {
Set<String> labelErrors = ValidateGlobalRules.validateRuleSchemaConceptExist(graph, rule);
errorsFound.addAll(labelErrors);
if (labelErrors.isEmpty()) {
Set<String> ontologicalErrors = ValidateGlobalRules.validateRuleOntologically(graph, rule);
errorsFound.addAll(ontologicalErrors);
if (ontologicalErrors.isEmpty()) {
errorsFound.addAll(ValidateGlobalRules.validateRuleIsValidClause(graph, rule));
}
}
} | [
"private",
"void",
"validateRule",
"(",
"TransactionOLTP",
"graph",
",",
"Rule",
"rule",
")",
"{",
"Set",
"<",
"String",
">",
"labelErrors",
"=",
"ValidateGlobalRules",
".",
"validateRuleSchemaConceptExist",
"(",
"graph",
",",
"rule",
")",
";",
"errorsFound",
".... | Validation rules exclusive to rules
the precedence of validation is: labelValidation -> ontologicalValidation -> clauseValidation
each of the validation happens only if the preceding validation yields no errors
@param graph the graph to query against
@param rule the rule which needs to be validated | [
"Validation",
"rules",
"exclusive",
"to",
"rules",
"the",
"precedence",
"of",
"validation",
"is",
":",
"labelValidation",
"-",
">",
"ontologicalValidation",
"-",
">",
"clauseValidation",
"each",
"of",
"the",
"validation",
"happens",
"only",
"if",
"the",
"preceding... | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/Validator.java#L90-L100 |
xiaosunzhu/resource-utils | src/main/java/net/sunyijun/resource/config/Configs.java | Configs.getSystemConfigDecimal | public static BigDecimal getSystemConfigDecimal(String keyPrefix, IConfigKey key) {
return systemConfigs.getDecimalConfig(keyPrefix, key);
} | java | public static BigDecimal getSystemConfigDecimal(String keyPrefix, IConfigKey key) {
return systemConfigs.getDecimalConfig(keyPrefix, key);
} | [
"public",
"static",
"BigDecimal",
"getSystemConfigDecimal",
"(",
"String",
"keyPrefix",
",",
"IConfigKey",
"key",
")",
"{",
"return",
"systemConfigs",
".",
"getDecimalConfig",
"(",
"keyPrefix",
",",
"key",
")",
";",
"}"
] | Get system config decimal. Config key include prefix.
Example:<br>
If key.getKeyString() is "test", <br>
getSystemConfigDecimal("1.", key); will return "1.test" config value in system config file.
@param keyPrefix config key prefix
@param key config key
@return config BigDecimal value. Return null if not config in
system config file "{@value #DEFAULT_SYSTEM_CONFIG_ABSOLUTE_CLASS_PATH}" or self define system config path.
@see #setSystemConfigs(String, OneProperties) | [
"Get",
"system",
"config",
"decimal",
".",
"Config",
"key",
"include",
"prefix",
".",
"Example",
":",
"<br",
">",
"If",
"key",
".",
"getKeyString",
"()",
"is",
"test",
"<br",
">",
"getSystemConfigDecimal",
"(",
"1",
".",
"key",
")",
";",
"will",
"return"... | train | https://github.com/xiaosunzhu/resource-utils/blob/4f2bf3f36df10195a978f122ed682ba1eb0462b5/src/main/java/net/sunyijun/resource/config/Configs.java#L156-L158 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/BaseFont.java | BaseFont.getWidthPointKerned | public float getWidthPointKerned(String text, float fontSize) {
float size = getWidth(text) * 0.001f * fontSize;
if (!hasKernPairs())
return size;
int len = text.length() - 1;
int kern = 0;
char c[] = text.toCharArray();
for (int k = 0; k < len; ++k) {
kern += getKerning(c[k], c[k + 1]);
}
return size + kern * 0.001f * fontSize;
} | java | public float getWidthPointKerned(String text, float fontSize) {
float size = getWidth(text) * 0.001f * fontSize;
if (!hasKernPairs())
return size;
int len = text.length() - 1;
int kern = 0;
char c[] = text.toCharArray();
for (int k = 0; k < len; ++k) {
kern += getKerning(c[k], c[k + 1]);
}
return size + kern * 0.001f * fontSize;
} | [
"public",
"float",
"getWidthPointKerned",
"(",
"String",
"text",
",",
"float",
"fontSize",
")",
"{",
"float",
"size",
"=",
"getWidth",
"(",
"text",
")",
"*",
"0.001f",
"*",
"fontSize",
";",
"if",
"(",
"!",
"hasKernPairs",
"(",
")",
")",
"return",
"size",... | Gets the width of a <CODE>String</CODE> in points taking kerning
into account.
@param text the <CODE>String</CODE> to get the width of
@param fontSize the font size
@return the width in points | [
"Gets",
"the",
"width",
"of",
"a",
"<CODE",
">",
"String<",
"/",
"CODE",
">",
"in",
"points",
"taking",
"kerning",
"into",
"account",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/BaseFont.java#L968-L979 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/TitlePaneIconifyButtonPainter.java | TitlePaneIconifyButtonPainter.paintRestoreHover | private void paintRestoreHover(Graphics2D g, JComponent c, int width, int height) {
restorePainter.paintHover(g, c, width, height);
} | java | private void paintRestoreHover(Graphics2D g, JComponent c, int width, int height) {
restorePainter.paintHover(g, c, width, height);
} | [
"private",
"void",
"paintRestoreHover",
"(",
"Graphics2D",
"g",
",",
"JComponent",
"c",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"restorePainter",
".",
"paintHover",
"(",
"g",
",",
"c",
",",
"width",
",",
"height",
")",
";",
"}"
] | Paint the foreground restore button mouse-over state.
@param g the Graphics2D context to paint with.
@param c the component.
@param width the width of the component.
@param height the height of the component. | [
"Paint",
"the",
"foreground",
"restore",
"button",
"mouse",
"-",
"over",
"state",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/TitlePaneIconifyButtonPainter.java#L219-L221 |
tango-controls/JTango | client/src/main/java/org/tango/client/database/DatabaseFactory.java | DatabaseFactory.setDbFile | public static void setDbFile(final File dbFile, final String[] devices, final String className) throws DevFailed {
DatabaseFactory.useDb = false;
DatabaseFactory.fileDatabase = new FileTangoDB(dbFile, Arrays.copyOf(devices, devices.length), className);
} | java | public static void setDbFile(final File dbFile, final String[] devices, final String className) throws DevFailed {
DatabaseFactory.useDb = false;
DatabaseFactory.fileDatabase = new FileTangoDB(dbFile, Arrays.copyOf(devices, devices.length), className);
} | [
"public",
"static",
"void",
"setDbFile",
"(",
"final",
"File",
"dbFile",
",",
"final",
"String",
"[",
"]",
"devices",
",",
"final",
"String",
"className",
")",
"throws",
"DevFailed",
"{",
"DatabaseFactory",
".",
"useDb",
"=",
"false",
";",
"DatabaseFactory",
... | Build a mock tango db with a file containing the properties
@param dbFile
@param devices
@param classes
@throws DevFailed | [
"Build",
"a",
"mock",
"tango",
"db",
"with",
"a",
"file",
"containing",
"the",
"properties"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/client/src/main/java/org/tango/client/database/DatabaseFactory.java#L105-L108 |
BioPAX/Paxtools | sbgn-converter/src/main/java/org/biopax/paxtools/io/sbgn/L3ToSBGNPDConverter.java | L3ToSBGNPDConverter.writeSBGN | public void writeSBGN(Model model, String file) {
// Create the model
Sbgn sbgn = createSBGN(model);
// Write in file
try {
SbgnUtil.writeToFile(sbgn, new File(file));
}
catch (JAXBException e) {
throw new RuntimeException("writeSBGN, SbgnUtil.writeToFile failed", e);
}
} | java | public void writeSBGN(Model model, String file) {
// Create the model
Sbgn sbgn = createSBGN(model);
// Write in file
try {
SbgnUtil.writeToFile(sbgn, new File(file));
}
catch (JAXBException e) {
throw new RuntimeException("writeSBGN, SbgnUtil.writeToFile failed", e);
}
} | [
"public",
"void",
"writeSBGN",
"(",
"Model",
"model",
",",
"String",
"file",
")",
"{",
"// Create the model",
"Sbgn",
"sbgn",
"=",
"createSBGN",
"(",
"model",
")",
";",
"// Write in file",
"try",
"{",
"SbgnUtil",
".",
"writeToFile",
"(",
"sbgn",
",",
"new",
... | Converts the given model to SBGN, and writes in the specified file.
@param model model to convert
@param file file to write | [
"Converts",
"the",
"given",
"model",
"to",
"SBGN",
"and",
"writes",
"in",
"the",
"specified",
"file",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/sbgn-converter/src/main/java/org/biopax/paxtools/io/sbgn/L3ToSBGNPDConverter.java#L224-L235 |
biojava/biojava | biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java | Utils.cleanSequence | public final static String cleanSequence(String sequence, Set<Character> cSet){
Set<Character> invalidCharSet = new HashSet<Character>();
StringBuilder cleanSeq = new StringBuilder();
if(cSet == null) cSet = PeptideProperties.standardAASet;
for(char c:sequence.toCharArray()){
if(!cSet.contains(c)){
cleanSeq.append("-");
invalidCharSet.add(c);
}else{
cleanSeq.append(c);
}
}
// TODO: Should be StringJoiner once JDK8 used
StringBuilder stringBuilder = new StringBuilder();
for(char c: invalidCharSet){
stringBuilder.append("\'" + c + "\'");
}
stringBuilder.deleteCharAt(stringBuilder.length()-1);
stringBuilder.append(" are being replaced with '-'");
logger.warn(stringBuilder.toString());
return cleanSeq.toString();
} | java | public final static String cleanSequence(String sequence, Set<Character> cSet){
Set<Character> invalidCharSet = new HashSet<Character>();
StringBuilder cleanSeq = new StringBuilder();
if(cSet == null) cSet = PeptideProperties.standardAASet;
for(char c:sequence.toCharArray()){
if(!cSet.contains(c)){
cleanSeq.append("-");
invalidCharSet.add(c);
}else{
cleanSeq.append(c);
}
}
// TODO: Should be StringJoiner once JDK8 used
StringBuilder stringBuilder = new StringBuilder();
for(char c: invalidCharSet){
stringBuilder.append("\'" + c + "\'");
}
stringBuilder.deleteCharAt(stringBuilder.length()-1);
stringBuilder.append(" are being replaced with '-'");
logger.warn(stringBuilder.toString());
return cleanSeq.toString();
} | [
"public",
"final",
"static",
"String",
"cleanSequence",
"(",
"String",
"sequence",
",",
"Set",
"<",
"Character",
">",
"cSet",
")",
"{",
"Set",
"<",
"Character",
">",
"invalidCharSet",
"=",
"new",
"HashSet",
"<",
"Character",
">",
"(",
")",
";",
"StringBuil... | Returns a new sequence with all invalid characters being replaced by '-'.
Note that any character outside of the 20 standard protein amino acid codes are considered as invalid.
@param sequence
protein sequence to be clean
@param cSet
user defined characters that are valid. Can be null. If null, then 20 standard protein amino acid codes will be considered as valid.
@return
a new sequence with all invalid characters being replaced by '-'. | [
"Returns",
"a",
"new",
"sequence",
"with",
"all",
"invalid",
"characters",
"being",
"replaced",
"by",
"-",
".",
"Note",
"that",
"any",
"character",
"outside",
"of",
"the",
"20",
"standard",
"protein",
"amino",
"acid",
"codes",
"are",
"considered",
"as",
"inv... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java#L112-L135 |
relayrides/pushy | dropwizard-metrics-listener/src/main/java/com/turo/pushy/apns/metrics/dropwizard/DropwizardApnsClientMetricsListener.java | DropwizardApnsClientMetricsListener.handleNotificationSent | @Override
public void handleNotificationSent(final ApnsClient apnsClient, final long notificationId) {
this.sentNotifications.mark();
this.notificationTimerContexts.put(notificationId, this.notificationTimer.time());
} | java | @Override
public void handleNotificationSent(final ApnsClient apnsClient, final long notificationId) {
this.sentNotifications.mark();
this.notificationTimerContexts.put(notificationId, this.notificationTimer.time());
} | [
"@",
"Override",
"public",
"void",
"handleNotificationSent",
"(",
"final",
"ApnsClient",
"apnsClient",
",",
"final",
"long",
"notificationId",
")",
"{",
"this",
".",
"sentNotifications",
".",
"mark",
"(",
")",
";",
"this",
".",
"notificationTimerContexts",
".",
... | Records a successful attempt to send a notification and updates metrics accordingly.
@param apnsClient the client that sent the notification; note that this is ignored by
{@code DropwizardApnsClientMetricsListener} instances, which should always be used for exactly one client
@param notificationId an opaque, unique identifier for the notification that was sent | [
"Records",
"a",
"successful",
"attempt",
"to",
"send",
"a",
"notification",
"and",
"updates",
"metrics",
"accordingly",
"."
] | train | https://github.com/relayrides/pushy/blob/1f6f9a0e07d785c815d74c2320a8d87c80231d36/dropwizard-metrics-listener/src/main/java/com/turo/pushy/apns/metrics/dropwizard/DropwizardApnsClientMetricsListener.java#L185-L189 |
k3po/k3po | specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java | Functions.getClientToken | @Function
public static byte[] getClientToken(GSSContext context) {
byte[] initialToken = new byte[0];
if (!context.isEstablished()) {
try {
// token is ignored on the first call
initialToken = context.initSecContext(initialToken, 0, initialToken.length);
return getTokenWithLengthPrefix(initialToken);
} catch (GSSException ex) {
throw new RuntimeException("Exception getting client token", ex);
}
}
return null;
} | java | @Function
public static byte[] getClientToken(GSSContext context) {
byte[] initialToken = new byte[0];
if (!context.isEstablished()) {
try {
// token is ignored on the first call
initialToken = context.initSecContext(initialToken, 0, initialToken.length);
return getTokenWithLengthPrefix(initialToken);
} catch (GSSException ex) {
throw new RuntimeException("Exception getting client token", ex);
}
}
return null;
} | [
"@",
"Function",
"public",
"static",
"byte",
"[",
"]",
"getClientToken",
"(",
"GSSContext",
"context",
")",
"{",
"byte",
"[",
"]",
"initialToken",
"=",
"new",
"byte",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"context",
".",
"isEstablished",
"(",
")",
")",
... | Create a token, from a clients point of view, for establishing a secure
communication channel. This is a client side token so it needs to bootstrap
the token creation.
@param context GSSContext for which a connection has been established to the remote peer
@return a byte[] that represents the token a client can send to a server for
establishing a secure communication channel. | [
"Create",
"a",
"token",
"from",
"a",
"clients",
"point",
"of",
"view",
"for",
"establishing",
"a",
"secure",
"communication",
"channel",
".",
"This",
"is",
"a",
"client",
"side",
"token",
"so",
"it",
"needs",
"to",
"bootstrap",
"the",
"token",
"creation",
... | train | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L96-L113 |
Netflix/ribbon | ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/DynamicServerListLoadBalancer.java | DynamicServerListLoadBalancer.updateAllServerList | protected void updateAllServerList(List<T> ls) {
// other threads might be doing this - in which case, we pass
if (serverListUpdateInProgress.compareAndSet(false, true)) {
try {
for (T s : ls) {
s.setAlive(true); // set so that clients can start using these
// servers right away instead
// of having to wait out the ping cycle.
}
setServersList(ls);
super.forceQuickPing();
} finally {
serverListUpdateInProgress.set(false);
}
}
} | java | protected void updateAllServerList(List<T> ls) {
// other threads might be doing this - in which case, we pass
if (serverListUpdateInProgress.compareAndSet(false, true)) {
try {
for (T s : ls) {
s.setAlive(true); // set so that clients can start using these
// servers right away instead
// of having to wait out the ping cycle.
}
setServersList(ls);
super.forceQuickPing();
} finally {
serverListUpdateInProgress.set(false);
}
}
} | [
"protected",
"void",
"updateAllServerList",
"(",
"List",
"<",
"T",
">",
"ls",
")",
"{",
"// other threads might be doing this - in which case, we pass",
"if",
"(",
"serverListUpdateInProgress",
".",
"compareAndSet",
"(",
"false",
",",
"true",
")",
")",
"{",
"try",
"... | Update the AllServer list in the LoadBalancer if necessary and enabled
@param ls | [
"Update",
"the",
"AllServer",
"list",
"in",
"the",
"LoadBalancer",
"if",
"necessary",
"and",
"enabled"
] | train | https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/DynamicServerListLoadBalancer.java#L257-L272 |
phax/ph-oton | ph-oton-security/src/main/java/com/helger/photon/security/role/RoleManager.java | RoleManager.createNewRole | @Nonnull
public IRole createNewRole (@Nonnull @Nonempty final String sName,
@Nullable final String sDescription,
@Nullable final Map <String, String> aCustomAttrs)
{
// Create role
final Role aRole = new Role (sName, sDescription, aCustomAttrs);
m_aRWLock.writeLocked ( () -> {
// Store
internalCreateItem (aRole);
});
AuditHelper.onAuditCreateSuccess (Role.OT, aRole.getID (), sName);
// Execute callback as the very last action
m_aCallbacks.forEach (aCB -> aCB.onRoleCreated (aRole, false));
return aRole;
} | java | @Nonnull
public IRole createNewRole (@Nonnull @Nonempty final String sName,
@Nullable final String sDescription,
@Nullable final Map <String, String> aCustomAttrs)
{
// Create role
final Role aRole = new Role (sName, sDescription, aCustomAttrs);
m_aRWLock.writeLocked ( () -> {
// Store
internalCreateItem (aRole);
});
AuditHelper.onAuditCreateSuccess (Role.OT, aRole.getID (), sName);
// Execute callback as the very last action
m_aCallbacks.forEach (aCB -> aCB.onRoleCreated (aRole, false));
return aRole;
} | [
"@",
"Nonnull",
"public",
"IRole",
"createNewRole",
"(",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sName",
",",
"@",
"Nullable",
"final",
"String",
"sDescription",
",",
"@",
"Nullable",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"aCustomAt... | Create a new role.
@param sName
The name of the new role. May neither be <code>null</code> nor
empty.
@param sDescription
Optional description text. May be <code>null</code>.
@param aCustomAttrs
A set of custom attributes. May be <code>null</code>.
@return The created role and never <code>null</code>. | [
"Create",
"a",
"new",
"role",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-security/src/main/java/com/helger/photon/security/role/RoleManager.java#L85-L103 |
apache/groovy | subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java | Sql.executeUpdate | public int executeUpdate(String sql, List<Object> params) throws SQLException {
Connection connection = createConnection();
PreparedStatement statement = null;
try {
statement = getPreparedStatement(connection, sql, params);
this.updateCount = statement.executeUpdate();
return this.updateCount;
} catch (SQLException e) {
LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
throw e;
} finally {
closeResources(connection, statement);
}
} | java | public int executeUpdate(String sql, List<Object> params) throws SQLException {
Connection connection = createConnection();
PreparedStatement statement = null;
try {
statement = getPreparedStatement(connection, sql, params);
this.updateCount = statement.executeUpdate();
return this.updateCount;
} catch (SQLException e) {
LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
throw e;
} finally {
closeResources(connection, statement);
}
} | [
"public",
"int",
"executeUpdate",
"(",
"String",
"sql",
",",
"List",
"<",
"Object",
">",
"params",
")",
"throws",
"SQLException",
"{",
"Connection",
"connection",
"=",
"createConnection",
"(",
")",
";",
"PreparedStatement",
"statement",
"=",
"null",
";",
"try"... | Executes the given SQL update with parameters.
<p>
This method supports named and named ordinal parameters.
See the class Javadoc for more details.
<p>
Resource handling is performed automatically where appropriate.
@param sql the SQL statement
@param params a list of parameters
@return the number of rows updated or 0 for SQL statements that return nothing
@throws SQLException if a database access error occurs | [
"Executes",
"the",
"given",
"SQL",
"update",
"with",
"parameters",
".",
"<p",
">",
"This",
"method",
"supports",
"named",
"and",
"named",
"ordinal",
"parameters",
".",
"See",
"the",
"class",
"Javadoc",
"for",
"more",
"details",
".",
"<p",
">",
"Resource",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L2919-L2932 |
alipay/sofa-rpc | core/common/src/main/java/com/alipay/sofa/rpc/common/utils/ClassUtils.java | ClassUtils.forName | public static Class forName(String className, boolean initialize) {
try {
return Class.forName(className, initialize, getCurrentClassLoader());
} catch (Exception e) {
throw new SofaRpcRuntimeException(e);
}
} | java | public static Class forName(String className, boolean initialize) {
try {
return Class.forName(className, initialize, getCurrentClassLoader());
} catch (Exception e) {
throw new SofaRpcRuntimeException(e);
}
} | [
"public",
"static",
"Class",
"forName",
"(",
"String",
"className",
",",
"boolean",
"initialize",
")",
"{",
"try",
"{",
"return",
"Class",
".",
"forName",
"(",
"className",
",",
"initialize",
",",
"getCurrentClassLoader",
"(",
")",
")",
";",
"}",
"catch",
... | 根据类名加载Class
@param className 类名
@param initialize 是否初始化
@return Class | [
"根据类名加载Class"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/common/src/main/java/com/alipay/sofa/rpc/common/utils/ClassUtils.java#L55-L61 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.createPropertyDefinition | public CmsPropertyDefinition createPropertyDefinition(CmsDbContext dbc, String name) throws CmsException {
CmsPropertyDefinition propertyDefinition = null;
name = name.trim();
// validate the property name
CmsPropertyDefinition.checkPropertyName(name);
// TODO: make the type a parameter
try {
try {
propertyDefinition = getVfsDriver(dbc).readPropertyDefinition(
dbc,
name,
dbc.currentProject().getUuid());
} catch (CmsException e) {
propertyDefinition = getVfsDriver(dbc).createPropertyDefinition(
dbc,
dbc.currentProject().getUuid(),
name,
CmsPropertyDefinition.TYPE_NORMAL);
}
try {
getVfsDriver(dbc).readPropertyDefinition(dbc, name, CmsProject.ONLINE_PROJECT_ID);
} catch (CmsException e) {
getVfsDriver(dbc).createPropertyDefinition(
dbc,
CmsProject.ONLINE_PROJECT_ID,
name,
CmsPropertyDefinition.TYPE_NORMAL);
}
try {
getHistoryDriver(dbc).readPropertyDefinition(dbc, name);
} catch (CmsException e) {
getHistoryDriver(dbc).createPropertyDefinition(dbc, name, CmsPropertyDefinition.TYPE_NORMAL);
}
} finally {
// fire an event that a property of a resource has been deleted
OpenCms.fireCmsEvent(
new CmsEvent(
I_CmsEventListener.EVENT_PROPERTY_DEFINITION_CREATED,
Collections.<String, Object> singletonMap("propertyDefinition", propertyDefinition)));
}
return propertyDefinition;
} | java | public CmsPropertyDefinition createPropertyDefinition(CmsDbContext dbc, String name) throws CmsException {
CmsPropertyDefinition propertyDefinition = null;
name = name.trim();
// validate the property name
CmsPropertyDefinition.checkPropertyName(name);
// TODO: make the type a parameter
try {
try {
propertyDefinition = getVfsDriver(dbc).readPropertyDefinition(
dbc,
name,
dbc.currentProject().getUuid());
} catch (CmsException e) {
propertyDefinition = getVfsDriver(dbc).createPropertyDefinition(
dbc,
dbc.currentProject().getUuid(),
name,
CmsPropertyDefinition.TYPE_NORMAL);
}
try {
getVfsDriver(dbc).readPropertyDefinition(dbc, name, CmsProject.ONLINE_PROJECT_ID);
} catch (CmsException e) {
getVfsDriver(dbc).createPropertyDefinition(
dbc,
CmsProject.ONLINE_PROJECT_ID,
name,
CmsPropertyDefinition.TYPE_NORMAL);
}
try {
getHistoryDriver(dbc).readPropertyDefinition(dbc, name);
} catch (CmsException e) {
getHistoryDriver(dbc).createPropertyDefinition(dbc, name, CmsPropertyDefinition.TYPE_NORMAL);
}
} finally {
// fire an event that a property of a resource has been deleted
OpenCms.fireCmsEvent(
new CmsEvent(
I_CmsEventListener.EVENT_PROPERTY_DEFINITION_CREATED,
Collections.<String, Object> singletonMap("propertyDefinition", propertyDefinition)));
}
return propertyDefinition;
} | [
"public",
"CmsPropertyDefinition",
"createPropertyDefinition",
"(",
"CmsDbContext",
"dbc",
",",
"String",
"name",
")",
"throws",
"CmsException",
"{",
"CmsPropertyDefinition",
"propertyDefinition",
"=",
"null",
";",
"name",
"=",
"name",
".",
"trim",
"(",
")",
";",
... | Creates a property definition.<p>
Property definitions are valid for all resource types.<p>
@param dbc the current database context
@param name the name of the property definition to create
@return the created property definition
@throws CmsException if something goes wrong | [
"Creates",
"a",
"property",
"definition",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L1530-L1578 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/experimental/CollectSink.java | CollectSink.open | @Override
public void open(Configuration parameters) throws Exception {
try {
client = new Socket(hostIp, port);
outputStream = client.getOutputStream();
streamWriter = new DataOutputViewStreamWrapper(outputStream);
}
catch (IOException e) {
throw new IOException("Cannot connect to the client to send back the stream", e);
}
} | java | @Override
public void open(Configuration parameters) throws Exception {
try {
client = new Socket(hostIp, port);
outputStream = client.getOutputStream();
streamWriter = new DataOutputViewStreamWrapper(outputStream);
}
catch (IOException e) {
throw new IOException("Cannot connect to the client to send back the stream", e);
}
} | [
"@",
"Override",
"public",
"void",
"open",
"(",
"Configuration",
"parameters",
")",
"throws",
"Exception",
"{",
"try",
"{",
"client",
"=",
"new",
"Socket",
"(",
"hostIp",
",",
"port",
")",
";",
"outputStream",
"=",
"client",
".",
"getOutputStream",
"(",
")... | Initialize the connection with the Socket in the server.
@param parameters Configuration. | [
"Initialize",
"the",
"connection",
"with",
"the",
"Socket",
"in",
"the",
"server",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/experimental/CollectSink.java#L77-L87 |
sarl/sarl | main/coreplugins/io.sarl.m2e/src/io/sarl/m2e/wizards/importproject/MavenImportUtils.java | MavenImportUtils.restorePom | static void restorePom(File projectDir, IProgressMonitor monitor) throws IOException {
final File pomFile = new File(projectDir, POM_FILE);
final File savedPomFile = new File(projectDir, POM_BACKUP_FILE);
if (savedPomFile.exists()) {
if (pomFile.exists()) {
pomFile.delete();
}
Files.copy(savedPomFile, pomFile);
savedPomFile.delete();
}
monitor.worked(1);
} | java | static void restorePom(File projectDir, IProgressMonitor monitor) throws IOException {
final File pomFile = new File(projectDir, POM_FILE);
final File savedPomFile = new File(projectDir, POM_BACKUP_FILE);
if (savedPomFile.exists()) {
if (pomFile.exists()) {
pomFile.delete();
}
Files.copy(savedPomFile, pomFile);
savedPomFile.delete();
}
monitor.worked(1);
} | [
"static",
"void",
"restorePom",
"(",
"File",
"projectDir",
",",
"IProgressMonitor",
"monitor",
")",
"throws",
"IOException",
"{",
"final",
"File",
"pomFile",
"=",
"new",
"File",
"(",
"projectDir",
",",
"POM_FILE",
")",
";",
"final",
"File",
"savedPomFile",
"="... | Restore the original pom file.
@param projectDir the folder in which the pom file is located.
@param monitor the progress monitor.
@throws IOException if the pom file cannot be changed. | [
"Restore",
"the",
"original",
"pom",
"file",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.m2e/src/io/sarl/m2e/wizards/importproject/MavenImportUtils.java#L245-L256 |
code4everything/util | src/main/java/com/zhazhapan/util/NetUtils.java | NetUtils.addCookie | public static boolean addCookie(HttpServletResponse response, String name, String value, int expiry, String uri) {
Cookie cookie = new Cookie(name, value);
if (expiry > 0) {
cookie.setMaxAge(expiry);
}
if (Checker.isNotEmpty(uri)) {
cookie.setPath(uri);
}
return addCookie(cookie, response);
} | java | public static boolean addCookie(HttpServletResponse response, String name, String value, int expiry, String uri) {
Cookie cookie = new Cookie(name, value);
if (expiry > 0) {
cookie.setMaxAge(expiry);
}
if (Checker.isNotEmpty(uri)) {
cookie.setPath(uri);
}
return addCookie(cookie, response);
} | [
"public",
"static",
"boolean",
"addCookie",
"(",
"HttpServletResponse",
"response",
",",
"String",
"name",
",",
"String",
"value",
",",
"int",
"expiry",
",",
"String",
"uri",
")",
"{",
"Cookie",
"cookie",
"=",
"new",
"Cookie",
"(",
"name",
",",
"value",
")... | 添加Cookie
@param response {@link HttpServletResponse}
@param name Cookie名
@param value Cookie值
@param expiry 有效期
@param uri 路径
@return {@link Boolean}
@since 1.0.8 | [
"添加Cookie"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/NetUtils.java#L608-L617 |
OpenTSDB/opentsdb | src/core/TSDB.java | TSDB.newBatch | public WritableDataPoints newBatch(String metric, Map<String, String> tags) {
return new BatchedDataPoints(this, metric, tags);
} | java | public WritableDataPoints newBatch(String metric, Map<String, String> tags) {
return new BatchedDataPoints(this, metric, tags);
} | [
"public",
"WritableDataPoints",
"newBatch",
"(",
"String",
"metric",
",",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"return",
"new",
"BatchedDataPoints",
"(",
"this",
",",
"metric",
",",
"tags",
")",
";",
"}"
] | Returns a new {@link BatchedDataPoints} instance suitable for this TSDB.
@param metric Every data point that gets appended must be associated to this metric.
@param tags The associated tags for all data points being added.
@return data structure which can have data points appended. | [
"Returns",
"a",
"new",
"{",
"@link",
"BatchedDataPoints",
"}",
"instance",
"suitable",
"for",
"this",
"TSDB",
"."
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/TSDB.java#L976-L978 |
crawljax/crawljax | core/src/main/java/com/crawljax/forms/FormInputValueHelper.java | FormInputValueHelper.deserializeFormInputs | public static List<FormInput> deserializeFormInputs(File dir) {
List<FormInput> deserialized = new ArrayList<>();
final File in = new File(dir, FORMS_JSON_FILE);
if (in.exists()) {
LOGGER.info("Reading trained form inputs from " + in.getAbsolutePath());
Gson gson = new GsonBuilder().create();
try {
deserialized =
gson.fromJson(FileUtils.readFileToString(in, Charset.defaultCharset()),
new TypeToken<List<FormInput>>() {
}.getType());
} catch (JsonSyntaxException | IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
return deserialized;
} | java | public static List<FormInput> deserializeFormInputs(File dir) {
List<FormInput> deserialized = new ArrayList<>();
final File in = new File(dir, FORMS_JSON_FILE);
if (in.exists()) {
LOGGER.info("Reading trained form inputs from " + in.getAbsolutePath());
Gson gson = new GsonBuilder().create();
try {
deserialized =
gson.fromJson(FileUtils.readFileToString(in, Charset.defaultCharset()),
new TypeToken<List<FormInput>>() {
}.getType());
} catch (JsonSyntaxException | IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
return deserialized;
} | [
"public",
"static",
"List",
"<",
"FormInput",
">",
"deserializeFormInputs",
"(",
"File",
"dir",
")",
"{",
"List",
"<",
"FormInput",
">",
"deserialized",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"File",
"in",
"=",
"new",
"File",
"(",
"dir",
... | Serializes form inputs and writes the data to the output directory to be used by future
non-training crawls.
@param dir The output directory for the form input data.
@return The list of inputs | [
"Serializes",
"form",
"inputs",
"and",
"writes",
"the",
"data",
"to",
"the",
"output",
"directory",
"to",
"be",
"used",
"by",
"future",
"non",
"-",
"training",
"crawls",
"."
] | train | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/forms/FormInputValueHelper.java#L384-L406 |
Bandwidth/java-bandwidth | src/main/java/com/bandwidth/sdk/BandwidthClient.java | BandwidthClient.getUserResourceInstanceUri | public String getUserResourceInstanceUri(final String path, final String instanceId){
if(StringUtils.isEmpty(path) || StringUtils.isEmpty(instanceId)) {
throw new IllegalArgumentException("Path and Instance Id cannot be null");
}
return getUserResourceUri(path) + "/" + instanceId;
} | java | public String getUserResourceInstanceUri(final String path, final String instanceId){
if(StringUtils.isEmpty(path) || StringUtils.isEmpty(instanceId)) {
throw new IllegalArgumentException("Path and Instance Id cannot be null");
}
return getUserResourceUri(path) + "/" + instanceId;
} | [
"public",
"String",
"getUserResourceInstanceUri",
"(",
"final",
"String",
"path",
",",
"final",
"String",
"instanceId",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"path",
")",
"||",
"StringUtils",
".",
"isEmpty",
"(",
"instanceId",
")",
")",
"{... | Convenience method that returns the resource instance uri. E.g.
@param path the path.
@param instanceId the instance id.
@return The user Instance URI. | [
"Convenience",
"method",
"that",
"returns",
"the",
"resource",
"instance",
"uri",
".",
"E",
".",
"g",
"."
] | train | https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/BandwidthClient.java#L278-L283 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/PublishingScopeUrl.java | PublishingScopeUrl.getPublishSetUrl | public static MozuUrl getPublishSetUrl(String publishSetCode, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/publishing/publishsets/{publishSetCode}?responseFields={responseFields}");
formatter.formatUrl("publishSetCode", publishSetCode);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl getPublishSetUrl(String publishSetCode, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/publishing/publishsets/{publishSetCode}?responseFields={responseFields}");
formatter.formatUrl("publishSetCode", publishSetCode);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"getPublishSetUrl",
"(",
"String",
"publishSetCode",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/catalog/admin/publishing/publishsets/{publishSetCode}?responseFields={resp... | Get Resource Url for GetPublishSet
@param publishSetCode The unique identifier of the publish set.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"GetPublishSet"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/PublishingScopeUrl.java#L22-L28 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/model/SQLiteDatabaseSchema.java | SQLiteDatabaseSchema.fillClazz | private String fillClazz(String configClazz, String clazz) {
if (!clazz.equals(configClazz)) {
return configClazz;
} else {
return null;
}
} | java | private String fillClazz(String configClazz, String clazz) {
if (!clazz.equals(configClazz)) {
return configClazz;
} else {
return null;
}
} | [
"private",
"String",
"fillClazz",
"(",
"String",
"configClazz",
",",
"String",
"clazz",
")",
"{",
"if",
"(",
"!",
"clazz",
".",
"equals",
"(",
"configClazz",
")",
")",
"{",
"return",
"configClazz",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"... | Fill clazz.
@param configClazz
the config clazz
@param clazz
the clazz
@return the string | [
"Fill",
"clazz",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/model/SQLiteDatabaseSchema.java#L337-L343 |
MKLab-ITI/multimedia-indexing | src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java | IVFPQ.computeNearestProductIndex | private int computeNearestProductIndex(double[] subvector, int subQuantizerIndex) {
int centroidIndex = -1;
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < numProductCentroids; i++) {
double distance = 0;
for (int j = 0; j < subVectorLength; j++) {
distance += (productQuantizer[subQuantizerIndex][i][j] - subvector[j])
* (productQuantizer[subQuantizerIndex][i][j] - subvector[j]);
if (distance >= minDistance) {
break;
}
}
if (distance < minDistance) {
minDistance = distance;
centroidIndex = i;
}
}
return centroidIndex;
} | java | private int computeNearestProductIndex(double[] subvector, int subQuantizerIndex) {
int centroidIndex = -1;
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < numProductCentroids; i++) {
double distance = 0;
for (int j = 0; j < subVectorLength; j++) {
distance += (productQuantizer[subQuantizerIndex][i][j] - subvector[j])
* (productQuantizer[subQuantizerIndex][i][j] - subvector[j]);
if (distance >= minDistance) {
break;
}
}
if (distance < minDistance) {
minDistance = distance;
centroidIndex = i;
}
}
return centroidIndex;
} | [
"private",
"int",
"computeNearestProductIndex",
"(",
"double",
"[",
"]",
"subvector",
",",
"int",
"subQuantizerIndex",
")",
"{",
"int",
"centroidIndex",
"=",
"-",
"1",
";",
"double",
"minDistance",
"=",
"Double",
".",
"MAX_VALUE",
";",
"for",
"(",
"int",
"i"... | Finds and returns the index of the centroid of the subquantizer with the given index which is closer to
the given subvector.
@param subvector
The subvector
@param subQuantizerIndex
The index of the the subquantizer
@return The index of the nearest centroid | [
"Finds",
"and",
"returns",
"the",
"index",
"of",
"the",
"centroid",
"of",
"the",
"subquantizer",
"with",
"the",
"given",
"index",
"which",
"is",
"closer",
"to",
"the",
"given",
"subvector",
"."
] | train | https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L613-L631 |
kaazing/gateway | service/amqp/src/main/java/org/kaazing/gateway/service/amqp/amqp091/codec/AmqpMessageDecoder.java | AmqpMessageDecoder.getObjectOfType | private static Object getObjectOfType(IoBufferEx buffer, AmqpType type)
throws ProtocolDecoderException {
Object value;
switch (type)
{
case BIT:
value = getBit(buffer);
break;
case SHORTSTRING:
value = getShortString(buffer);
break;
case LONGSTRING:
value = getLongString(buffer);
break;
case FIELDTABLE:
value = getFieldTable(buffer);
break;
case TABLE:
value = getTable(buffer);
break;
case INT:
value = buffer.getInt();
break;
case UNSIGNEDINT:
value = getUnsignedInt(buffer);
break;
case UNSIGNEDSHORT:
value = getUnsignedShort(buffer);
break;
case UNSIGNED:
value = buffer.getUnsigned();
break;
case SHORT:
value = getUnsignedShort(buffer);
break;
case LONG:
value = getUnsignedInt(buffer);
break;
case OCTET:
value = buffer.getUnsigned();
break;
case LONGLONG:
value = getUnsignedLong(buffer);
break;
case TIMESTAMP:
long millis = getMilliseconds(buffer);
value = new Timestamp(millis);
break;
case VOID:
value = null;
break;
default:
String s = "Invalid type: '" + type;
throw new ProtocolDecoderException(s);
}
return value;
} | java | private static Object getObjectOfType(IoBufferEx buffer, AmqpType type)
throws ProtocolDecoderException {
Object value;
switch (type)
{
case BIT:
value = getBit(buffer);
break;
case SHORTSTRING:
value = getShortString(buffer);
break;
case LONGSTRING:
value = getLongString(buffer);
break;
case FIELDTABLE:
value = getFieldTable(buffer);
break;
case TABLE:
value = getTable(buffer);
break;
case INT:
value = buffer.getInt();
break;
case UNSIGNEDINT:
value = getUnsignedInt(buffer);
break;
case UNSIGNEDSHORT:
value = getUnsignedShort(buffer);
break;
case UNSIGNED:
value = buffer.getUnsigned();
break;
case SHORT:
value = getUnsignedShort(buffer);
break;
case LONG:
value = getUnsignedInt(buffer);
break;
case OCTET:
value = buffer.getUnsigned();
break;
case LONGLONG:
value = getUnsignedLong(buffer);
break;
case TIMESTAMP:
long millis = getMilliseconds(buffer);
value = new Timestamp(millis);
break;
case VOID:
value = null;
break;
default:
String s = "Invalid type: '" + type;
throw new ProtocolDecoderException(s);
}
return value;
} | [
"private",
"static",
"Object",
"getObjectOfType",
"(",
"IoBufferEx",
"buffer",
",",
"AmqpType",
"type",
")",
"throws",
"ProtocolDecoderException",
"{",
"Object",
"value",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"BIT",
":",
"value",
"=",
"getBit",
"(",
... | /*
private FrameHeader getFrameHeader()
{
int frameType = this.getUnsigned();
int channel = this.getUnsignedShort();
long size = this.getUnsignedInt();
FrameHeader header = new FrameHeader();
header.frameType = frameType;
header.size = size;
header.channel = channel;
return header;
} | [
"/",
"*",
"private",
"FrameHeader",
"getFrameHeader",
"()",
"{",
"int",
"frameType",
"=",
"this",
".",
"getUnsigned",
"()",
";",
"int",
"channel",
"=",
"this",
".",
"getUnsignedShort",
"()",
";",
"long",
"size",
"=",
"this",
".",
"getUnsignedInt",
"()",
";... | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/service/amqp/src/main/java/org/kaazing/gateway/service/amqp/amqp091/codec/AmqpMessageDecoder.java#L868-L924 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java | ApiOvhEmailexchange.organizationName_service_exchangeService_sharedAccountQuota_GET | public OvhSharedAccountQuota organizationName_service_exchangeService_sharedAccountQuota_GET(String organizationName, String exchangeService) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/sharedAccountQuota";
StringBuilder sb = path(qPath, organizationName, exchangeService);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhSharedAccountQuota.class);
} | java | public OvhSharedAccountQuota organizationName_service_exchangeService_sharedAccountQuota_GET(String organizationName, String exchangeService) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/sharedAccountQuota";
StringBuilder sb = path(qPath, organizationName, exchangeService);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhSharedAccountQuota.class);
} | [
"public",
"OvhSharedAccountQuota",
"organizationName_service_exchangeService_sharedAccountQuota_GET",
"(",
"String",
"organizationName",
",",
"String",
"exchangeService",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/exchange/{organizationName}/service/{exchang... | Get shared account quota usage in total available space
REST: GET /email/exchange/{organizationName}/service/{exchangeService}/sharedAccountQuota
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service | [
"Get",
"shared",
"account",
"quota",
"usage",
"in",
"total",
"available",
"space"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L2371-L2376 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java | TreeScanner.visitMemberSelect | @Override
public R visitMemberSelect(MemberSelectTree node, P p) {
return scan(node.getExpression(), p);
} | java | @Override
public R visitMemberSelect(MemberSelectTree node, P p) {
return scan(node.getExpression(), p);
} | [
"@",
"Override",
"public",
"R",
"visitMemberSelect",
"(",
"MemberSelectTree",
"node",
",",
"P",
"p",
")",
"{",
"return",
"scan",
"(",
"node",
".",
"getExpression",
"(",
")",
",",
"p",
")",
";",
"}"
] | {@inheritDoc} This implementation scans the children in left to right order.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"scans",
"the",
"children",
"in",
"left",
"to",
"right",
"order",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java#L678-L681 |
Wadpam/guja | guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java | GeneratedDContactDaoImpl.queryByUpdatedDate | public Iterable<DContact> queryByUpdatedDate(Object parent, java.util.Date updatedDate) {
return queryByField(parent, DContactMapper.Field.UPDATEDDATE.getFieldName(), updatedDate);
} | java | public Iterable<DContact> queryByUpdatedDate(Object parent, java.util.Date updatedDate) {
return queryByField(parent, DContactMapper.Field.UPDATEDDATE.getFieldName(), updatedDate);
} | [
"public",
"Iterable",
"<",
"DContact",
">",
"queryByUpdatedDate",
"(",
"Object",
"parent",
",",
"java",
".",
"util",
".",
"Date",
"updatedDate",
")",
"{",
"return",
"queryByField",
"(",
"parent",
",",
"DContactMapper",
".",
"Field",
".",
"UPDATEDDATE",
".",
... | query-by method for field updatedDate
@param updatedDate the specified attribute
@return an Iterable of DContacts for the specified updatedDate | [
"query",
"-",
"by",
"method",
"for",
"field",
"updatedDate"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java#L304-L306 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.getClosedListEntityRolesAsync | public Observable<List<EntityRole>> getClosedListEntityRolesAsync(UUID appId, String versionId, UUID entityId) {
return getClosedListEntityRolesWithServiceResponseAsync(appId, versionId, entityId).map(new Func1<ServiceResponse<List<EntityRole>>, List<EntityRole>>() {
@Override
public List<EntityRole> call(ServiceResponse<List<EntityRole>> response) {
return response.body();
}
});
} | java | public Observable<List<EntityRole>> getClosedListEntityRolesAsync(UUID appId, String versionId, UUID entityId) {
return getClosedListEntityRolesWithServiceResponseAsync(appId, versionId, entityId).map(new Func1<ServiceResponse<List<EntityRole>>, List<EntityRole>>() {
@Override
public List<EntityRole> call(ServiceResponse<List<EntityRole>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"List",
"<",
"EntityRole",
">",
">",
"getClosedListEntityRolesAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
")",
"{",
"return",
"getClosedListEntityRolesWithServiceResponseAsync",
"(",
"appId",
",",
"... | Get All Entity Roles for a given entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId entity Id
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<EntityRole> object | [
"Get",
"All",
"Entity",
"Roles",
"for",
"a",
"given",
"entity",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L8246-L8253 |
spotbugs/spotbugs | eclipsePlugin/src/de/tobject/findbugs/FindbugsPlugin.java | FindbugsPlugin.getBugCollection | public static SortedBugCollection getBugCollection(IProject project, IProgressMonitor monitor)
throws CoreException {
SortedBugCollection bugCollection = (SortedBugCollection) project.getSessionProperty(SESSION_PROPERTY_BUG_COLLECTION);
if (bugCollection == null) {
try {
readBugCollectionAndProject(project, monitor);
bugCollection = (SortedBugCollection) project.getSessionProperty(SESSION_PROPERTY_BUG_COLLECTION);
} catch (IOException e) {
FindbugsPlugin.getDefault().logException(e, "Could not read bug collection for project");
bugCollection = createDefaultEmptyBugCollection(project);
} catch (DocumentException e) {
FindbugsPlugin.getDefault().logException(e, "Could not read bug collection for project");
bugCollection = createDefaultEmptyBugCollection(project);
}
}
return bugCollection;
} | java | public static SortedBugCollection getBugCollection(IProject project, IProgressMonitor monitor)
throws CoreException {
SortedBugCollection bugCollection = (SortedBugCollection) project.getSessionProperty(SESSION_PROPERTY_BUG_COLLECTION);
if (bugCollection == null) {
try {
readBugCollectionAndProject(project, monitor);
bugCollection = (SortedBugCollection) project.getSessionProperty(SESSION_PROPERTY_BUG_COLLECTION);
} catch (IOException e) {
FindbugsPlugin.getDefault().logException(e, "Could not read bug collection for project");
bugCollection = createDefaultEmptyBugCollection(project);
} catch (DocumentException e) {
FindbugsPlugin.getDefault().logException(e, "Could not read bug collection for project");
bugCollection = createDefaultEmptyBugCollection(project);
}
}
return bugCollection;
} | [
"public",
"static",
"SortedBugCollection",
"getBugCollection",
"(",
"IProject",
"project",
",",
"IProgressMonitor",
"monitor",
")",
"throws",
"CoreException",
"{",
"SortedBugCollection",
"bugCollection",
"=",
"(",
"SortedBugCollection",
")",
"project",
".",
"getSessionPro... | Get the stored BugCollection for project. If there is no stored bug
collection for the project, or if an error occurs reading the stored bug
collection, a default empty collection is created and returned.
@param project
the eclipse project
@param monitor
a progress monitor
@return the stored BugCollection, never null
@throws CoreException | [
"Get",
"the",
"stored",
"BugCollection",
"for",
"project",
".",
"If",
"there",
"is",
"no",
"stored",
"bug",
"collection",
"for",
"the",
"project",
"or",
"if",
"an",
"error",
"occurs",
"reading",
"the",
"stored",
"bug",
"collection",
"a",
"default",
"empty",
... | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/FindbugsPlugin.java#L653-L669 |
finmath/finmath-lib | src/main/java6/net/finmath/marketdata/model/curves/HazardCurve.java | HazardCurve.createHazardCurveFromHazardRate | public static HazardCurve createHazardCurveFromHazardRate(
String name, LocalDate referenceDate,
double[] times, double[] givenHazardRates, boolean[] isParameter,
InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity){
double[] givenSurvivalProbabilities = new double[givenHazardRates.length];
if(givenHazardRates[0]<0) {
throw new IllegalArgumentException("First hazard rate is not positive");
}
//initialize the term structure
givenSurvivalProbabilities[0] = Math.exp(- givenHazardRates[0] * times[0]);
/*
* Construct the hazard curve by numerically integrating the hazard rates.
* At each step check if the input hazard rate is positive.
*/
for(int timeIndex=1; timeIndex<times.length;timeIndex++) {
if(givenHazardRates[timeIndex]<0) {
throw new IllegalArgumentException("The " + timeIndex + "-th hazard rate is not positive");
}
givenSurvivalProbabilities[timeIndex] = givenSurvivalProbabilities[timeIndex-1] * Math.exp(- givenHazardRates[timeIndex] * (times[timeIndex]-times[timeIndex-1]));
}
return createHazardCurveFromSurvivalProbabilities(name, referenceDate, times, givenSurvivalProbabilities, isParameter, interpolationMethod, extrapolationMethod, interpolationEntity);
} | java | public static HazardCurve createHazardCurveFromHazardRate(
String name, LocalDate referenceDate,
double[] times, double[] givenHazardRates, boolean[] isParameter,
InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity){
double[] givenSurvivalProbabilities = new double[givenHazardRates.length];
if(givenHazardRates[0]<0) {
throw new IllegalArgumentException("First hazard rate is not positive");
}
//initialize the term structure
givenSurvivalProbabilities[0] = Math.exp(- givenHazardRates[0] * times[0]);
/*
* Construct the hazard curve by numerically integrating the hazard rates.
* At each step check if the input hazard rate is positive.
*/
for(int timeIndex=1; timeIndex<times.length;timeIndex++) {
if(givenHazardRates[timeIndex]<0) {
throw new IllegalArgumentException("The " + timeIndex + "-th hazard rate is not positive");
}
givenSurvivalProbabilities[timeIndex] = givenSurvivalProbabilities[timeIndex-1] * Math.exp(- givenHazardRates[timeIndex] * (times[timeIndex]-times[timeIndex-1]));
}
return createHazardCurveFromSurvivalProbabilities(name, referenceDate, times, givenSurvivalProbabilities, isParameter, interpolationMethod, extrapolationMethod, interpolationEntity);
} | [
"public",
"static",
"HazardCurve",
"createHazardCurveFromHazardRate",
"(",
"String",
"name",
",",
"LocalDate",
"referenceDate",
",",
"double",
"[",
"]",
"times",
",",
"double",
"[",
"]",
"givenHazardRates",
",",
"boolean",
"[",
"]",
"isParameter",
",",
"Interpolat... | Create a hazard curve from given times and given hazard rates using given interpolation and extrapolation methods.
The discount factor is determined by
<code>
givenSurvivalProbabilities[timeIndex] = givenSurvivalProbabilities[timeIndex-1] * Math.exp(- givenHazardRates[timeIndex] * (times[timeIndex]-times[timeIndex-1]));
</code>
@param name The name of this hazard curve.
@param referenceDate The reference date for this curve, i.e., the date which defined t=0.
@param times Array of times as doubles.
@param givenHazardRates Array of corresponding hazard rates.
@param isParameter Array of booleans specifying whether this point is served "as as parameter", e.g., whether it is calibrates (e.g. using CalibratedCurves).
@param interpolationMethod The interpolation method used for the curve.
@param extrapolationMethod The extrapolation method used for the curve.
@param interpolationEntity The entity interpolated/extrapolated.
@return A new discount factor object. | [
"Create",
"a",
"hazard",
"curve",
"from",
"given",
"times",
"and",
"given",
"hazard",
"rates",
"using",
"given",
"interpolation",
"and",
"extrapolation",
"methods",
".",
"The",
"discount",
"factor",
"is",
"determined",
"by",
"<code",
">",
"givenSurvivalProbabiliti... | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/model/curves/HazardCurve.java#L179-L207 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/builder/EqualsBuilder.java | EqualsBuilder.isRegistered | static boolean isRegistered(final Object lhs, final Object rhs) {
final Set<Pair<IDKey, IDKey>> registry = getRegistry();
final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
final Pair<IDKey, IDKey> swappedPair = new Pair<IDKey, IDKey>(pair.getKey(), pair.getValue());
return registry != null
&& (registry.contains(pair) || registry.contains(swappedPair));
} | java | static boolean isRegistered(final Object lhs, final Object rhs) {
final Set<Pair<IDKey, IDKey>> registry = getRegistry();
final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
final Pair<IDKey, IDKey> swappedPair = new Pair<IDKey, IDKey>(pair.getKey(), pair.getValue());
return registry != null
&& (registry.contains(pair) || registry.contains(swappedPair));
} | [
"static",
"boolean",
"isRegistered",
"(",
"final",
"Object",
"lhs",
",",
"final",
"Object",
"rhs",
")",
"{",
"final",
"Set",
"<",
"Pair",
"<",
"IDKey",
",",
"IDKey",
">",
">",
"registry",
"=",
"getRegistry",
"(",
")",
";",
"final",
"Pair",
"<",
"IDKey"... | <p>
Returns <code>true</code> if the registry contains the given object pair.
Used by the reflection methods to avoid infinite loops.
Objects might be swapped therefore a check is needed if the object pair
is registered in given or swapped order.
</p>
@param lhs <code>this</code> object to lookup in registry
@param rhs the other object to lookup on registry
@return boolean <code>true</code> if the registry contains the given object.
@since 3.0 | [
"<p",
">",
"Returns",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"the",
"registry",
"contains",
"the",
"given",
"object",
"pair",
".",
"Used",
"by",
"the",
"reflection",
"methods",
"to",
"avoid",
"infinite",
"loops",
".",
"Objects",
"might",
"be",
"s... | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/builder/EqualsBuilder.java#L138-L145 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java | FieldUtils.readField | public static Object readField(final Object target, final String fieldName) throws IllegalAccessException {
return readField(target, fieldName, false);
} | java | public static Object readField(final Object target, final String fieldName) throws IllegalAccessException {
return readField(target, fieldName, false);
} | [
"public",
"static",
"Object",
"readField",
"(",
"final",
"Object",
"target",
",",
"final",
"String",
"fieldName",
")",
"throws",
"IllegalAccessException",
"{",
"return",
"readField",
"(",
"target",
",",
"fieldName",
",",
"false",
")",
";",
"}"
] | Reads the named {@code public} {@link Field}. Superclasses will be considered.
@param target
the object to reflect, must not be {@code null}
@param fieldName
the field name to obtain
@return the value of the field
@throws IllegalArgumentException
if the class is {@code null}, or the field name is blank or empty or could not be found
@throws IllegalAccessException
if the named field is not {@code public} | [
"Reads",
"the",
"named",
"{",
"@code",
"public",
"}",
"{",
"@link",
"Field",
"}",
".",
"Superclasses",
"will",
"be",
"considered",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java#L445-L447 |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitorAssistantForMsgs.java | GenJsCodeVisitorAssistantForMsgs.generateMsgGroupVariable | private Expression generateMsgGroupVariable(MsgFallbackGroupNode node, String tmpVarName) {
checkState(node.numChildren() == 2);
// Generate the goog.getMsg calls for all children.
GoogMsgCodeGenInfo primaryCodeGenInfo =
genGoogGetMsgCallHelper(buildGoogMsgVarNameHelper(node.getChild(0)), node.getChild(0));
GoogMsgCodeGenInfo fallbackCodeGenInfo =
genGoogGetMsgCallHelper(buildGoogMsgVarNameHelper(node.getChild(1)), node.getChild(1));
// Declare a temporary variable to hold the getMsgWithFallback() call so that we can apply any
// MessageFormats from any of the fallbacks. This is also the variable name that we return to
// the caller.
Expression selectedMsg =
VariableDeclaration.builder(tmpVarName)
.setRhs(
Expression.dottedIdNoRequire("goog.getMsgWithFallback")
.call(primaryCodeGenInfo.googMsgVar, fallbackCodeGenInfo.googMsgVar))
.build()
.ref();
// We use id() here instead of using the corresponding code chunks because the stupid
// jscodebuilder system causes us to regenerate the msg vars multiple times because it doesn't
// detect that they were already generated.
// TODO(b/33382980): clean this up
Expression isPrimaryMsgInUse =
Expression.id(tmpVarName).doubleEquals(Expression.id(primaryCodeGenInfo.googMsgVarName));
translationContext.soyToJsVariableMappings().setIsPrimaryMsgInUse(node, isPrimaryMsgInUse);
if (primaryCodeGenInfo.placeholders == null && fallbackCodeGenInfo.placeholders == null) {
// all placeholders have already been substituted, just return
return selectedMsg;
}
// Generate the goog.i18n.MessageFormat calls for child plural/select messages (if any), each
// wrapped in an if-block that will only execute if that child is the chosen message.
Statement condition;
if (primaryCodeGenInfo.placeholders != null) {
ConditionalBuilder builder =
Statement.ifStatement(
selectedMsg.doubleEquals(primaryCodeGenInfo.googMsgVar),
selectedMsg.assign(getMessageFormatCall(primaryCodeGenInfo)).asStatement());
if (fallbackCodeGenInfo.placeholders != null) {
builder.setElse(
selectedMsg.assign(getMessageFormatCall(fallbackCodeGenInfo)).asStatement());
}
condition = builder.build();
} else {
condition =
Statement.ifStatement(
selectedMsg.doubleEquals(fallbackCodeGenInfo.googMsgVar),
selectedMsg.assign(getMessageFormatCall(fallbackCodeGenInfo)).asStatement())
.build();
}
return Expression.id(tmpVarName).withInitialStatement(condition);
} | java | private Expression generateMsgGroupVariable(MsgFallbackGroupNode node, String tmpVarName) {
checkState(node.numChildren() == 2);
// Generate the goog.getMsg calls for all children.
GoogMsgCodeGenInfo primaryCodeGenInfo =
genGoogGetMsgCallHelper(buildGoogMsgVarNameHelper(node.getChild(0)), node.getChild(0));
GoogMsgCodeGenInfo fallbackCodeGenInfo =
genGoogGetMsgCallHelper(buildGoogMsgVarNameHelper(node.getChild(1)), node.getChild(1));
// Declare a temporary variable to hold the getMsgWithFallback() call so that we can apply any
// MessageFormats from any of the fallbacks. This is also the variable name that we return to
// the caller.
Expression selectedMsg =
VariableDeclaration.builder(tmpVarName)
.setRhs(
Expression.dottedIdNoRequire("goog.getMsgWithFallback")
.call(primaryCodeGenInfo.googMsgVar, fallbackCodeGenInfo.googMsgVar))
.build()
.ref();
// We use id() here instead of using the corresponding code chunks because the stupid
// jscodebuilder system causes us to regenerate the msg vars multiple times because it doesn't
// detect that they were already generated.
// TODO(b/33382980): clean this up
Expression isPrimaryMsgInUse =
Expression.id(tmpVarName).doubleEquals(Expression.id(primaryCodeGenInfo.googMsgVarName));
translationContext.soyToJsVariableMappings().setIsPrimaryMsgInUse(node, isPrimaryMsgInUse);
if (primaryCodeGenInfo.placeholders == null && fallbackCodeGenInfo.placeholders == null) {
// all placeholders have already been substituted, just return
return selectedMsg;
}
// Generate the goog.i18n.MessageFormat calls for child plural/select messages (if any), each
// wrapped in an if-block that will only execute if that child is the chosen message.
Statement condition;
if (primaryCodeGenInfo.placeholders != null) {
ConditionalBuilder builder =
Statement.ifStatement(
selectedMsg.doubleEquals(primaryCodeGenInfo.googMsgVar),
selectedMsg.assign(getMessageFormatCall(primaryCodeGenInfo)).asStatement());
if (fallbackCodeGenInfo.placeholders != null) {
builder.setElse(
selectedMsg.assign(getMessageFormatCall(fallbackCodeGenInfo)).asStatement());
}
condition = builder.build();
} else {
condition =
Statement.ifStatement(
selectedMsg.doubleEquals(fallbackCodeGenInfo.googMsgVar),
selectedMsg.assign(getMessageFormatCall(fallbackCodeGenInfo)).asStatement())
.build();
}
return Expression.id(tmpVarName).withInitialStatement(condition);
} | [
"private",
"Expression",
"generateMsgGroupVariable",
"(",
"MsgFallbackGroupNode",
"node",
",",
"String",
"tmpVarName",
")",
"{",
"checkState",
"(",
"node",
".",
"numChildren",
"(",
")",
"==",
"2",
")",
";",
"// Generate the goog.getMsg calls for all children.",
"GoogMsg... | Returns a code chunk representing a variable declaration for an {@link MsgFallbackGroupNode}
that contains fallback(s). | [
"Returns",
"a",
"code",
"chunk",
"representing",
"a",
"variable",
"declaration",
"for",
"an",
"{"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitorAssistantForMsgs.java#L210-L262 |
czyzby/gdx-lml | lml/src/main/java/com/github/czyzby/lml/parser/impl/DefaultLmlParser.java | DefaultLmlParser.processArgument | private void processArgument() {
final StringBuilder argumentBuilder = new StringBuilder();
while (templateReader.hasNextCharacter()) {
final char argumentCharacter = templateReader.nextCharacter();
if (argumentCharacter == syntax.getArgumentClosing()) {
final String argument = argumentBuilder.toString().trim(); // Getting actual argument name.
if (Strings.startsWith(argument, syntax.getEquationMarker())) {
// Starts with an equation sign. Evaluating.
final String equation = LmlUtilities.stripMarker(argument);
templateReader.append(newEquation().getResult(equation), equation + " equation");
} else if (Strings.startsWith(argument, syntax.getConditionMarker())) {
// Condition/ternary operator. Evaluating.
processConditionArgument(argument, argumentBuilder);
} else { // Regular argument. Looking for value mapped to the selected key.
templateReader.append(Nullables.toString(data.getArgument(argument)), argument + " argument");
}
return;
}
argumentBuilder.append(argumentCharacter);
}
} | java | private void processArgument() {
final StringBuilder argumentBuilder = new StringBuilder();
while (templateReader.hasNextCharacter()) {
final char argumentCharacter = templateReader.nextCharacter();
if (argumentCharacter == syntax.getArgumentClosing()) {
final String argument = argumentBuilder.toString().trim(); // Getting actual argument name.
if (Strings.startsWith(argument, syntax.getEquationMarker())) {
// Starts with an equation sign. Evaluating.
final String equation = LmlUtilities.stripMarker(argument);
templateReader.append(newEquation().getResult(equation), equation + " equation");
} else if (Strings.startsWith(argument, syntax.getConditionMarker())) {
// Condition/ternary operator. Evaluating.
processConditionArgument(argument, argumentBuilder);
} else { // Regular argument. Looking for value mapped to the selected key.
templateReader.append(Nullables.toString(data.getArgument(argument)), argument + " argument");
}
return;
}
argumentBuilder.append(argumentCharacter);
}
} | [
"private",
"void",
"processArgument",
"(",
")",
"{",
"final",
"StringBuilder",
"argumentBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"while",
"(",
"templateReader",
".",
"hasNextCharacter",
"(",
")",
")",
"{",
"final",
"char",
"argumentCharacter",
"=",
... | Found an argument opening sign. Have to find argument's name and replace it in the template. | [
"Found",
"an",
"argument",
"opening",
"sign",
".",
"Have",
"to",
"find",
"argument",
"s",
"name",
"and",
"replace",
"it",
"in",
"the",
"template",
"."
] | train | https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/lml/src/main/java/com/github/czyzby/lml/parser/impl/DefaultLmlParser.java#L152-L172 |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/impl/FileDescriptorLimit.java | FileDescriptorLimit.getUlimit | @edu.umd.cs.findbugs.annotations.SuppressWarnings({"DM_DEFAULT_ENCODING", "OS_OPEN_STREAM"})
private static void getUlimit(PrintWriter writer) throws IOException {
// TODO should first check whether /bin/bash even exists
InputStream is = new ProcessBuilder("bash", "-c", "ulimit -a").start().getInputStream();
try {
// this is reading from the process so platform encoding is correct
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = bufferedReader.readLine()) != null) {
writer.println(line);
}
} finally {
is.close();
}
} | java | @edu.umd.cs.findbugs.annotations.SuppressWarnings({"DM_DEFAULT_ENCODING", "OS_OPEN_STREAM"})
private static void getUlimit(PrintWriter writer) throws IOException {
// TODO should first check whether /bin/bash even exists
InputStream is = new ProcessBuilder("bash", "-c", "ulimit -a").start().getInputStream();
try {
// this is reading from the process so platform encoding is correct
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = bufferedReader.readLine()) != null) {
writer.println(line);
}
} finally {
is.close();
}
} | [
"@",
"edu",
".",
"umd",
".",
"cs",
".",
"findbugs",
".",
"annotations",
".",
"SuppressWarnings",
"(",
"{",
"\"DM_DEFAULT_ENCODING\"",
",",
"\"OS_OPEN_STREAM\"",
"}",
")",
"private",
"static",
"void",
"getUlimit",
"(",
"PrintWriter",
"writer",
")",
"throws",
"I... | This method executes the command "bash -c ulimit -a" on the machine. | [
"This",
"method",
"executes",
"the",
"command",
"bash",
"-",
"c",
"ulimit",
"-",
"a",
"on",
"the",
"machine",
"."
] | train | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/impl/FileDescriptorLimit.java#L188-L202 |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/googleanalytics/GoogleAnalyticsController.java | GoogleAnalyticsController.isMember | private boolean isMember(IGroupMember groupMember, String groupName) {
try {
IEntityGroup group = GroupService.findGroup(groupName);
if (group != null) {
return groupMember.isDeepMemberOf(group);
}
final EntityIdentifier[] results =
GroupService.searchForGroups(
groupName, GroupService.SearchMethod.DISCRETE, IPerson.class);
if (results == null || results.length == 0) {
this.logger.warn(
"No portal group found for '{}' no users will be placed in that group for analytics",
groupName);
return false;
}
if (results.length > 1) {
this.logger.warn(
"{} groups were found for groupName '{}'. The first result will be used.",
results.length,
groupName);
}
group = (IEntityGroup) GroupService.getGroupMember(results[0]);
return groupMember.isDeepMemberOf(group);
} catch (Exception e) {
this.logger.warn(
"Failed to determine if {} is a member of {}, returning false",
groupMember,
groupName,
e);
return false;
}
} | java | private boolean isMember(IGroupMember groupMember, String groupName) {
try {
IEntityGroup group = GroupService.findGroup(groupName);
if (group != null) {
return groupMember.isDeepMemberOf(group);
}
final EntityIdentifier[] results =
GroupService.searchForGroups(
groupName, GroupService.SearchMethod.DISCRETE, IPerson.class);
if (results == null || results.length == 0) {
this.logger.warn(
"No portal group found for '{}' no users will be placed in that group for analytics",
groupName);
return false;
}
if (results.length > 1) {
this.logger.warn(
"{} groups were found for groupName '{}'. The first result will be used.",
results.length,
groupName);
}
group = (IEntityGroup) GroupService.getGroupMember(results[0]);
return groupMember.isDeepMemberOf(group);
} catch (Exception e) {
this.logger.warn(
"Failed to determine if {} is a member of {}, returning false",
groupMember,
groupName,
e);
return false;
}
} | [
"private",
"boolean",
"isMember",
"(",
"IGroupMember",
"groupMember",
",",
"String",
"groupName",
")",
"{",
"try",
"{",
"IEntityGroup",
"group",
"=",
"GroupService",
".",
"findGroup",
"(",
"groupName",
")",
";",
"if",
"(",
"group",
"!=",
"null",
")",
"{",
... | Check if the user is a member of the specified group name
<p>Internal search, thus case sensitive. | [
"Check",
"if",
"the",
"user",
"is",
"a",
"member",
"of",
"the",
"specified",
"group",
"name"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/googleanalytics/GoogleAnalyticsController.java#L132-L166 |
phax/ph-web | ph-web/src/main/java/com/helger/web/multipart/MultipartStream.java | MultipartStream.readBoundary | public boolean readBoundary () throws MultipartMalformedStreamException
{
final byte [] marker = new byte [2];
boolean bNextChunk = false;
m_nHead += m_nBoundaryLength;
try
{
marker[0] = readByte ();
if (marker[0] == LF)
{
// Work around IE5 Mac bug with input type=image.
// Because the boundary delimiter, not including the trailing
// CRLF, must not appear within any file (RFC 2046, section
// 5.1.1), we know the missing CR is due to a buggy browser
// rather than a file containing something similar to a
// boundary.
return true;
}
marker[1] = readByte ();
if (ArrayHelper.startsWith (marker, STREAM_TERMINATOR))
bNextChunk = false;
else
if (ArrayHelper.startsWith (marker, FIELD_SEPARATOR))
bNextChunk = true;
else
throw new MultipartMalformedStreamException ("Unexpected characters follow a boundary");
}
catch (final IOException ex)
{
throw new MultipartMalformedStreamException ("Stream ended unexpectedly", ex);
}
return bNextChunk;
} | java | public boolean readBoundary () throws MultipartMalformedStreamException
{
final byte [] marker = new byte [2];
boolean bNextChunk = false;
m_nHead += m_nBoundaryLength;
try
{
marker[0] = readByte ();
if (marker[0] == LF)
{
// Work around IE5 Mac bug with input type=image.
// Because the boundary delimiter, not including the trailing
// CRLF, must not appear within any file (RFC 2046, section
// 5.1.1), we know the missing CR is due to a buggy browser
// rather than a file containing something similar to a
// boundary.
return true;
}
marker[1] = readByte ();
if (ArrayHelper.startsWith (marker, STREAM_TERMINATOR))
bNextChunk = false;
else
if (ArrayHelper.startsWith (marker, FIELD_SEPARATOR))
bNextChunk = true;
else
throw new MultipartMalformedStreamException ("Unexpected characters follow a boundary");
}
catch (final IOException ex)
{
throw new MultipartMalformedStreamException ("Stream ended unexpectedly", ex);
}
return bNextChunk;
} | [
"public",
"boolean",
"readBoundary",
"(",
")",
"throws",
"MultipartMalformedStreamException",
"{",
"final",
"byte",
"[",
"]",
"marker",
"=",
"new",
"byte",
"[",
"2",
"]",
";",
"boolean",
"bNextChunk",
"=",
"false",
";",
"m_nHead",
"+=",
"m_nBoundaryLength",
";... | Skips a <code>boundary</code> token, and checks whether more
<code>encapsulations</code> are contained in the stream.
@return <code>true</code> if there are more encapsulations in this stream;
<code>false</code> otherwise.
@throws MultipartMalformedStreamException
if the stream ends unexpectedly or fails to follow required syntax. | [
"Skips",
"a",
"<code",
">",
"boundary<",
"/",
"code",
">",
"token",
"and",
"checks",
"whether",
"more",
"<code",
">",
"encapsulations<",
"/",
"code",
">",
"are",
"contained",
"in",
"the",
"stream",
"."
] | train | https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-web/src/main/java/com/helger/web/multipart/MultipartStream.java#L327-L361 |
mgm-tp/jfunk | jfunk-data/src/main/java/com/mgmtp/jfunk/data/source/BaseDataSource.java | BaseDataSource.setFixedValue | @Override
public void setFixedValue(final String dataSetKey, final String entryKey, final String value) {
Map<String, String> map = fixedValues.get(dataSetKey);
if (map == null) {
map = Maps.newHashMap();
fixedValues.put(dataSetKey, map);
}
map.put(entryKey, value);
DataSet dataSet = getCurrentDataSet(dataSetKey);
if (dataSet != null) {
dataSet.setFixedValue(entryKey, value);
}
} | java | @Override
public void setFixedValue(final String dataSetKey, final String entryKey, final String value) {
Map<String, String> map = fixedValues.get(dataSetKey);
if (map == null) {
map = Maps.newHashMap();
fixedValues.put(dataSetKey, map);
}
map.put(entryKey, value);
DataSet dataSet = getCurrentDataSet(dataSetKey);
if (dataSet != null) {
dataSet.setFixedValue(entryKey, value);
}
} | [
"@",
"Override",
"public",
"void",
"setFixedValue",
"(",
"final",
"String",
"dataSetKey",
",",
"final",
"String",
"entryKey",
",",
"final",
"String",
"value",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"fixedValues",
".",
"get",
"(",
... | Sets a fixed value.
@param dataSetKey
The {@link DataSet} key.
@param entryKey
The entry key.
@param value
The fixed value. | [
"Sets",
"a",
"fixed",
"value",
"."
] | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data/src/main/java/com/mgmtp/jfunk/data/source/BaseDataSource.java#L204-L217 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/CertificateOperations.java | CertificateOperations.deleteCertificate | public void deleteCertificate(String thumbprintAlgorithm, String thumbprint) throws BatchErrorException, IOException {
deleteCertificate(thumbprintAlgorithm, thumbprint, null);
} | java | public void deleteCertificate(String thumbprintAlgorithm, String thumbprint) throws BatchErrorException, IOException {
deleteCertificate(thumbprintAlgorithm, thumbprint, null);
} | [
"public",
"void",
"deleteCertificate",
"(",
"String",
"thumbprintAlgorithm",
",",
"String",
"thumbprint",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"deleteCertificate",
"(",
"thumbprintAlgorithm",
",",
"thumbprint",
",",
"null",
")",
";",
"}"
] | Deletes the certificate from the Batch account.
<p>The delete operation requests that the certificate be deleted. The request puts the certificate in the {@link com.microsoft.azure.batch.protocol.models.CertificateState#DELETING Deleting} state.
The Batch service will perform the actual certificate deletion without any further client action.</p>
<p>You cannot delete a certificate if a resource (pool or compute node) is using it. Before you can delete a certificate, you must therefore make sure that:</p>
<ul>
<li>The certificate is not associated with any pools.</li>
<li>The certificate is not installed on any compute nodes. (Even if you remove a certificate from a pool, it is not removed from existing compute nodes in that pool until they restart.)</li>
</ul>
<p>If you try to delete a certificate that is in use, the deletion fails. The certificate state changes to {@link com.microsoft.azure.batch.protocol.models.CertificateState#DELETE_FAILED Delete Failed}.
You can use {@link #cancelDeleteCertificate(String, String)} to set the status back to Active if you decide that you want to continue using the certificate.</p>
@param thumbprintAlgorithm The algorithm used to derive the thumbprint parameter. This must be sha1.
@param thumbprint The thumbprint of the certificate to delete.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. | [
"Deletes",
"the",
"certificate",
"from",
"the",
"Batch",
"account",
".",
"<p",
">",
"The",
"delete",
"operation",
"requests",
"that",
"the",
"certificate",
"be",
"deleted",
".",
"The",
"request",
"puts",
"the",
"certificate",
"in",
"the",
"{",
"@link",
"com"... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/CertificateOperations.java#L205-L207 |
LMAX-Exchange/disruptor | src/main/java/com/lmax/disruptor/dsl/Disruptor.java | Disruptor.publishEvent | public <A, B, C> void publishEvent(final EventTranslatorThreeArg<T, A, B, C> eventTranslator, final A arg0, final B arg1, final C arg2)
{
ringBuffer.publishEvent(eventTranslator, arg0, arg1, arg2);
} | java | public <A, B, C> void publishEvent(final EventTranslatorThreeArg<T, A, B, C> eventTranslator, final A arg0, final B arg1, final C arg2)
{
ringBuffer.publishEvent(eventTranslator, arg0, arg1, arg2);
} | [
"public",
"<",
"A",
",",
"B",
",",
"C",
">",
"void",
"publishEvent",
"(",
"final",
"EventTranslatorThreeArg",
"<",
"T",
",",
"A",
",",
"B",
",",
"C",
">",
"eventTranslator",
",",
"final",
"A",
"arg0",
",",
"final",
"B",
"arg1",
",",
"final",
"C",
"... | Publish an event to the ring buffer.
@param eventTranslator the translator that will load data into the event.
@param <A> Class of the user supplied argument.
@param <B> Class of the user supplied argument.
@param <C> Class of the user supplied argument.
@param arg0 The first argument to load into the event
@param arg1 The second argument to load into the event
@param arg2 The third argument to load into the event | [
"Publish",
"an",
"event",
"to",
"the",
"ring",
"buffer",
"."
] | train | https://github.com/LMAX-Exchange/disruptor/blob/4266d00c5250190313446fdd7c8aa7a4edb5c818/src/main/java/com/lmax/disruptor/dsl/Disruptor.java#L383-L386 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Hierarchy.java | Hierarchy.findExactMethod | public static JavaClassAndMethod findExactMethod(InvokeInstruction inv, ConstantPoolGen cpg) throws ClassNotFoundException {
return findExactMethod(inv, cpg, ANY_METHOD);
} | java | public static JavaClassAndMethod findExactMethod(InvokeInstruction inv, ConstantPoolGen cpg) throws ClassNotFoundException {
return findExactMethod(inv, cpg, ANY_METHOD);
} | [
"public",
"static",
"JavaClassAndMethod",
"findExactMethod",
"(",
"InvokeInstruction",
"inv",
",",
"ConstantPoolGen",
"cpg",
")",
"throws",
"ClassNotFoundException",
"{",
"return",
"findExactMethod",
"(",
"inv",
",",
"cpg",
",",
"ANY_METHOD",
")",
";",
"}"
] | Look up the method referenced by given InvokeInstruction. This method
does <em>not</em> look for implementations in super or subclasses
according to the virtual dispatch rules.
@param inv
the InvokeInstruction
@param cpg
the ConstantPoolGen used by the class the InvokeInstruction
belongs to
@return the JavaClassAndMethod, or null if no such method is defined in
the class | [
"Look",
"up",
"the",
"method",
"referenced",
"by",
"given",
"InvokeInstruction",
".",
"This",
"method",
"does",
"<em",
">",
"not<",
"/",
"em",
">",
"look",
"for",
"implementations",
"in",
"super",
"or",
"subclasses",
"according",
"to",
"the",
"virtual",
"dis... | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Hierarchy.java#L232-L234 |
jenkinsci/jenkins | core/src/main/java/hudson/diagnosis/OldDataMonitor.java | OldDataMonitor.doUpgrade | @RequirePOST
public HttpResponse doUpgrade(StaplerRequest req, StaplerResponse rsp) {
final String thruVerParam = req.getParameter("thruVer");
final VersionNumber thruVer = thruVerParam.equals("all") ? null : new VersionNumber(thruVerParam);
saveAndRemoveEntries(new Predicate<Map.Entry<SaveableReference, VersionRange>>() {
@Override
public boolean apply(Map.Entry<SaveableReference, VersionRange> entry) {
VersionNumber version = entry.getValue().max;
return version != null && (thruVer == null || !version.isNewerThan(thruVer));
}
});
return HttpResponses.forwardToPreviousPage();
} | java | @RequirePOST
public HttpResponse doUpgrade(StaplerRequest req, StaplerResponse rsp) {
final String thruVerParam = req.getParameter("thruVer");
final VersionNumber thruVer = thruVerParam.equals("all") ? null : new VersionNumber(thruVerParam);
saveAndRemoveEntries(new Predicate<Map.Entry<SaveableReference, VersionRange>>() {
@Override
public boolean apply(Map.Entry<SaveableReference, VersionRange> entry) {
VersionNumber version = entry.getValue().max;
return version != null && (thruVer == null || !version.isNewerThan(thruVer));
}
});
return HttpResponses.forwardToPreviousPage();
} | [
"@",
"RequirePOST",
"public",
"HttpResponse",
"doUpgrade",
"(",
"StaplerRequest",
"req",
",",
"StaplerResponse",
"rsp",
")",
"{",
"final",
"String",
"thruVerParam",
"=",
"req",
".",
"getParameter",
"(",
"\"thruVer\"",
")",
";",
"final",
"VersionNumber",
"thruVer",... | Save all or some of the files to persist data in the new forms.
Remove those items from the data map. | [
"Save",
"all",
"or",
"some",
"of",
"the",
"files",
"to",
"persist",
"data",
"in",
"the",
"new",
"forms",
".",
"Remove",
"those",
"items",
"from",
"the",
"data",
"map",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/diagnosis/OldDataMonitor.java#L323-L337 |
toddfast/typeconverter | src/main/java/com/toddfast/util/convert/TypeConverter.java | TypeConverter.asInt | public static int asInt(Object value, int nullValue) {
value=convert(Integer.class,value);
if (value!=null) {
return ((Integer)value).intValue();
}
else {
return nullValue;
}
} | java | public static int asInt(Object value, int nullValue) {
value=convert(Integer.class,value);
if (value!=null) {
return ((Integer)value).intValue();
}
else {
return nullValue;
}
} | [
"public",
"static",
"int",
"asInt",
"(",
"Object",
"value",
",",
"int",
"nullValue",
")",
"{",
"value",
"=",
"convert",
"(",
"Integer",
".",
"class",
",",
"value",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"return",
"(",
"(",
"Integer",
... | Return the value converted to an int
or the specified alternate value if the original value is null. Note,
this method still throws {@link IllegalArgumentException} if the value
is not null and could not be converted.
@param value
The value to be converted
@param nullValue
The value to be returned if {@link value} is null. Note, this
value will not be returned if the conversion fails otherwise.
@throws IllegalArgumentException
If the value cannot be converted | [
"Return",
"the",
"value",
"converted",
"to",
"an",
"int",
"or",
"the",
"specified",
"alternate",
"value",
"if",
"the",
"original",
"value",
"is",
"null",
".",
"Note",
"this",
"method",
"still",
"throws",
"{",
"@link",
"IllegalArgumentException",
"}",
"if",
"... | train | https://github.com/toddfast/typeconverter/blob/44efa352254faa49edaba5c5935389705aa12b90/src/main/java/com/toddfast/util/convert/TypeConverter.java#L525-L533 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/matchspace/selector/impl/MatchParserImpl.java | MatchParserImpl.BetweenPredicate | final public Selector BetweenPredicate() throws ParseException {
Selector expr1, expr2, expr3; boolean neg=false;
expr1 = Expression();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case NOT:
jj_consume_token(NOT);
neg = true;
break;
default:
jj_la1[16] = jj_gen;
;
}
jj_consume_token(BETWEEN);
expr2 = Expression();
jj_consume_token(AND);
expr3 = Expression();
Selector ans = ParseUtil.convertRange(expr1, expr2, expr3);
if (neg) {if (true) return new OperatorImpl(Operator.NOT, ans);}
else {if (true) return ans;}
throw new Error("Missing return statement in function");
} | java | final public Selector BetweenPredicate() throws ParseException {
Selector expr1, expr2, expr3; boolean neg=false;
expr1 = Expression();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case NOT:
jj_consume_token(NOT);
neg = true;
break;
default:
jj_la1[16] = jj_gen;
;
}
jj_consume_token(BETWEEN);
expr2 = Expression();
jj_consume_token(AND);
expr3 = Expression();
Selector ans = ParseUtil.convertRange(expr1, expr2, expr3);
if (neg) {if (true) return new OperatorImpl(Operator.NOT, ans);}
else {if (true) return ans;}
throw new Error("Missing return statement in function");
} | [
"final",
"public",
"Selector",
"BetweenPredicate",
"(",
")",
"throws",
"ParseException",
"{",
"Selector",
"expr1",
",",
"expr2",
",",
"expr3",
";",
"boolean",
"neg",
"=",
"false",
";",
"expr1",
"=",
"Expression",
"(",
")",
";",
"switch",
"(",
"(",
"jj_ntk"... | BetweenPredicate ::= Expression ( <NOT> )? <BETWEEN> Expression <AND> Expression | [
"BetweenPredicate",
"::",
"=",
"Expression",
"(",
"<NOT",
">",
")",
"?",
"<BETWEEN",
">",
"Expression",
"<AND",
">",
"Expression"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/matchspace/selector/impl/MatchParserImpl.java#L521-L541 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/StringUtils.java | StringUtils.replacePattern | public static String replacePattern(final String source, final String regex, final String replacement) {
if (source == null || regex == null || replacement == null) {
return source;
}
RegExp compile = RegExp.compile(regex, "gm");
String resultString = source.replace('\n', (char) 0x2675);
resultString = compile.replace(resultString, replacement);
return resultString.replace((char) 0x2675, '\n');
} | java | public static String replacePattern(final String source, final String regex, final String replacement) {
if (source == null || regex == null || replacement == null) {
return source;
}
RegExp compile = RegExp.compile(regex, "gm");
String resultString = source.replace('\n', (char) 0x2675);
resultString = compile.replace(resultString, replacement);
return resultString.replace((char) 0x2675, '\n');
} | [
"public",
"static",
"String",
"replacePattern",
"(",
"final",
"String",
"source",
",",
"final",
"String",
"regex",
",",
"final",
"String",
"replacement",
")",
"{",
"if",
"(",
"source",
"==",
"null",
"||",
"regex",
"==",
"null",
"||",
"replacement",
"==",
"... | <p>Replaces each substring of the source String that matches the given regular expression with the given
replacement using the {@link Pattern#DOTALL} option. DOTALL is also known as single-line mode in Perl.</p>
This call is a {@code null} safe equivalent to:
<ul>
<li>{@code source.replaceAll("(?s)" + regex, replacement)}</li>
<li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement)}</li>
</ul>
<p>A {@code null} reference passed to this method is a no-op.</p>
<pre>
StringUtils.replacePattern(null, *, *) = null
StringUtils.replacePattern("any", null, *) = "any"
StringUtils.replacePattern("any", *, null) = "any"
StringUtils.replacePattern("", "", "zzz") = "zzz"
StringUtils.replacePattern("", ".*", "zzz") = "zzz"
StringUtils.replacePattern("", ".+", "zzz") = ""
StringUtils.replacePattern("<__>\n<__>", "<.*>", "z") = "z"
StringUtils.replacePattern("ABCabc123", "[a-z]", "_") = "ABC___123"
StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123"
StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123"
StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit"
</pre>
@param source
the source string
@param regex
the regular expression to which this string is to be matched
@param replacement
the string to be substituted for each match
@return The resulting {@code String}
@see #replaceAll(String, String, String)
@see String#replaceAll(String, String)
@see Pattern#DOTALL
@since 3.2
@since 3.5 Changed {@code null} reference passed to this method is a no-op. | [
"<p",
">",
"Replaces",
"each",
"substring",
"of",
"the",
"source",
"String",
"that",
"matches",
"the",
"given",
"regular",
"expression",
"with",
"the",
"given",
"replacement",
"using",
"the",
"{",
"@link",
"Pattern#DOTALL",
"}",
"option",
".",
"DOTALL",
"is",
... | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L5238-L5246 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/locale/message/MessageBundleScriptCreator.java | MessageBundleScriptCreator.updateProperties | public void updateProperties(ResourceBundle bundle, Properties props, Charset charset) {
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if (matchesFilter(key)) {
String value = bundle.getString(key);
props.put(key, value);
}
}
} | java | public void updateProperties(ResourceBundle bundle, Properties props, Charset charset) {
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if (matchesFilter(key)) {
String value = bundle.getString(key);
props.put(key, value);
}
}
} | [
"public",
"void",
"updateProperties",
"(",
"ResourceBundle",
"bundle",
",",
"Properties",
"props",
",",
"Charset",
"charset",
")",
"{",
"Enumeration",
"<",
"String",
">",
"keys",
"=",
"bundle",
".",
"getKeys",
"(",
")",
";",
"while",
"(",
"keys",
".",
"has... | Loads the message resource bundles specified and uses a
BundleStringJasonifier to generate the properties.
@param bundle
the bundle
@param props
the properties
@param charset
the charset | [
"Loads",
"the",
"message",
"resource",
"bundles",
"specified",
"and",
"uses",
"a",
"BundleStringJasonifier",
"to",
"generate",
"the",
"properties",
"."
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/locale/message/MessageBundleScriptCreator.java#L234-L246 |
sonyxperiadev/gerrit-events | src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritHandler.java | GerritHandler.notifyListener | private void notifyListener(GerritEventListener listener, GerritEvent event) {
logger.trace("Notifying listener {} of event {}", listener, event);
try {
logger.trace("Reflecting closest method");
Method method = listener.getClass().getMethod("gerritEvent", event.getClass());
method.invoke(listener, event);
} catch (IllegalAccessException ex) {
logger.debug("Not allowed to invoke the reflected method. Calling default.", ex);
listener.gerritEvent(event);
} catch (IllegalArgumentException ex) {
logger.debug("Not allowed to invoke the reflected method with specified parameter (REFLECTION BUG). "
+ "Calling default.", ex);
listener.gerritEvent(event);
} catch (InvocationTargetException ex) {
logger.error("When notifying listener: {} about event: {}", listener, event);
logger.error("Exception thrown during event handling.", ex);
} catch (NoSuchMethodException ex) {
logger.debug("No apropriate method found during reflection. Calling default.", ex);
listener.gerritEvent(event);
} catch (SecurityException ex) {
logger.debug("Not allowed to reflect/invoke a method on this listener (DESIGN BUG). Calling default", ex);
listener.gerritEvent(event);
}
} | java | private void notifyListener(GerritEventListener listener, GerritEvent event) {
logger.trace("Notifying listener {} of event {}", listener, event);
try {
logger.trace("Reflecting closest method");
Method method = listener.getClass().getMethod("gerritEvent", event.getClass());
method.invoke(listener, event);
} catch (IllegalAccessException ex) {
logger.debug("Not allowed to invoke the reflected method. Calling default.", ex);
listener.gerritEvent(event);
} catch (IllegalArgumentException ex) {
logger.debug("Not allowed to invoke the reflected method with specified parameter (REFLECTION BUG). "
+ "Calling default.", ex);
listener.gerritEvent(event);
} catch (InvocationTargetException ex) {
logger.error("When notifying listener: {} about event: {}", listener, event);
logger.error("Exception thrown during event handling.", ex);
} catch (NoSuchMethodException ex) {
logger.debug("No apropriate method found during reflection. Calling default.", ex);
listener.gerritEvent(event);
} catch (SecurityException ex) {
logger.debug("Not allowed to reflect/invoke a method on this listener (DESIGN BUG). Calling default", ex);
listener.gerritEvent(event);
}
} | [
"private",
"void",
"notifyListener",
"(",
"GerritEventListener",
"listener",
",",
"GerritEvent",
"event",
")",
"{",
"logger",
".",
"trace",
"(",
"\"Notifying listener {} of event {}\"",
",",
"listener",
",",
"event",
")",
";",
"try",
"{",
"logger",
".",
"trace",
... | Sub method of {@link #notifyListeners(com.sonymobile.tools.gerrit.gerritevents.dto.GerritEvent) }.
This is where most of the reflection magic in the event notification is done.
@param listener the listener to notify
@param event the event. | [
"Sub",
"method",
"of",
"{",
"@link",
"#notifyListeners",
"(",
"com",
".",
"sonymobile",
".",
"tools",
".",
"gerrit",
".",
"gerritevents",
".",
"dto",
".",
"GerritEvent",
")",
"}",
".",
"This",
"is",
"where",
"most",
"of",
"the",
"reflection",
"magic",
"i... | train | https://github.com/sonyxperiadev/gerrit-events/blob/9a443d13dded85cc4709136ac33989f2bbb34fe2/src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritHandler.java#L491-L514 |
Polidea/RxAndroidBle | sample/src/main/java/com/polidea/rxandroidble2/sample/util/ScanExceptionHandler.java | ScanExceptionHandler.handleException | public static void handleException(final Activity context, final BleScanException exception) {
final String text;
final int reason = exception.getReason();
// Special case, as there might or might not be a retry date suggestion
if (reason == BleScanException.UNDOCUMENTED_SCAN_THROTTLE) {
text = getUndocumentedScanThrottleErrorMessage(context, exception.getRetryDateSuggestion());
} else {
// Handle all other possible errors
final Integer resId = ERROR_MESSAGES.get(reason);
if (resId != null) {
text = context.getString(resId);
} else {
// unknown error - return default message
Log.w("Scanning", String.format("No message found for reason=%d. Consider adding one.", reason));
text = context.getString(R.string.error_unknown_error);
}
}
Log.w("Scanning", text, exception);
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
} | java | public static void handleException(final Activity context, final BleScanException exception) {
final String text;
final int reason = exception.getReason();
// Special case, as there might or might not be a retry date suggestion
if (reason == BleScanException.UNDOCUMENTED_SCAN_THROTTLE) {
text = getUndocumentedScanThrottleErrorMessage(context, exception.getRetryDateSuggestion());
} else {
// Handle all other possible errors
final Integer resId = ERROR_MESSAGES.get(reason);
if (resId != null) {
text = context.getString(resId);
} else {
// unknown error - return default message
Log.w("Scanning", String.format("No message found for reason=%d. Consider adding one.", reason));
text = context.getString(R.string.error_unknown_error);
}
}
Log.w("Scanning", text, exception);
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
} | [
"public",
"static",
"void",
"handleException",
"(",
"final",
"Activity",
"context",
",",
"final",
"BleScanException",
"exception",
")",
"{",
"final",
"String",
"text",
";",
"final",
"int",
"reason",
"=",
"exception",
".",
"getReason",
"(",
")",
";",
"// Specia... | Show toast with error message appropriate to exception reason.
@param context current Activity context
@param exception BleScanException to show error message for | [
"Show",
"toast",
"with",
"error",
"message",
"appropriate",
"to",
"exception",
"reason",
"."
] | train | https://github.com/Polidea/RxAndroidBle/blob/c6e4a9753c834d710e255306bb290e9244cdbc10/sample/src/main/java/com/polidea/rxandroidble2/sample/util/ScanExceptionHandler.java#L63-L84 |
jmurty/java-xmlbuilder | src/main/java/com/jamesmurty/utils/BaseXMLBuilder.java | BaseXMLBuilder.xpathQuery | public Object xpathQuery(String xpath, QName type, NamespaceContext nsContext)
throws XPathExpressionException {
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xPath = xpathFactory.newXPath();
if (nsContext != null) {
xPath.setNamespaceContext(nsContext);
}
XPathExpression xpathExp = xPath.compile(xpath);
try {
return xpathExp.evaluate(this.xmlNode, type);
} catch (IllegalArgumentException e) {
// Thrown if item found does not match expected type
return null;
}
} | java | public Object xpathQuery(String xpath, QName type, NamespaceContext nsContext)
throws XPathExpressionException {
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xPath = xpathFactory.newXPath();
if (nsContext != null) {
xPath.setNamespaceContext(nsContext);
}
XPathExpression xpathExp = xPath.compile(xpath);
try {
return xpathExp.evaluate(this.xmlNode, type);
} catch (IllegalArgumentException e) {
// Thrown if item found does not match expected type
return null;
}
} | [
"public",
"Object",
"xpathQuery",
"(",
"String",
"xpath",
",",
"QName",
"type",
",",
"NamespaceContext",
"nsContext",
")",
"throws",
"XPathExpressionException",
"{",
"XPathFactory",
"xpathFactory",
"=",
"XPathFactory",
".",
"newInstance",
"(",
")",
";",
"XPath",
"... | Return the result of evaluating an XPath query on the builder's DOM
using the given namespace. Returns null if the query finds nothing,
or finds a node that does not match the type specified by returnType.
@param xpath
an XPath expression
@param type
the type the XPath is expected to resolve to, e.g:
{@link XPathConstants#NODE}, {@link XPathConstants#NODESET},
{@link XPathConstants#STRING}.
@param nsContext
a mapping of prefixes to namespace URIs that allows the XPath expression
to use namespaces, or null for a non-namespaced document.
@return
a builder node representing the first Element that matches the
XPath expression.
@throws XPathExpressionException
If the XPath is invalid, or if does not resolve to at least one
{@link Node#ELEMENT_NODE}. | [
"Return",
"the",
"result",
"of",
"evaluating",
"an",
"XPath",
"query",
"on",
"the",
"builder",
"s",
"DOM",
"using",
"the",
"given",
"namespace",
".",
"Returns",
"null",
"if",
"the",
"query",
"finds",
"nothing",
"or",
"finds",
"a",
"node",
"that",
"does",
... | train | https://github.com/jmurty/java-xmlbuilder/blob/7c224b8e8ed79808509322cb141dab5a88dd3cec/src/main/java/com/jamesmurty/utils/BaseXMLBuilder.java#L398-L412 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemLiteralResult.java | ElemLiteralResult.excludeResultNSDecl | private boolean excludeResultNSDecl(String prefix, String uri)
throws TransformerException
{
if (null != m_excludeResultPrefixes)
{
return containsExcludeResultPrefix(prefix, uri);
}
return false;
} | java | private boolean excludeResultNSDecl(String prefix, String uri)
throws TransformerException
{
if (null != m_excludeResultPrefixes)
{
return containsExcludeResultPrefix(prefix, uri);
}
return false;
} | [
"private",
"boolean",
"excludeResultNSDecl",
"(",
"String",
"prefix",
",",
"String",
"uri",
")",
"throws",
"TransformerException",
"{",
"if",
"(",
"null",
"!=",
"m_excludeResultPrefixes",
")",
"{",
"return",
"containsExcludeResultPrefix",
"(",
"prefix",
",",
"uri",
... | Tell if the result namespace decl should be excluded. Should be called before
namespace aliasing (I think).
@param prefix Prefix of namespace to check
@param uri URI of namespace to check
@return True if the given namespace should be excluded
@throws TransformerException | [
"Tell",
"if",
"the",
"result",
"namespace",
"decl",
"should",
"be",
"excluded",
".",
"Should",
"be",
"called",
"before",
"namespace",
"aliasing",
"(",
"I",
"think",
")",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemLiteralResult.java#L1278-L1288 |
UrielCh/ovh-java-sdk | ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java | ApiOvhPrice.xdsl_installation_offer_GET | public OvhPrice xdsl_installation_offer_GET(net.minidev.ovh.api.price.xdsl.OvhInstallationEnum offer) throws IOException {
String qPath = "/price/xdsl/installation/{offer}";
StringBuilder sb = path(qPath, offer);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | java | public OvhPrice xdsl_installation_offer_GET(net.minidev.ovh.api.price.xdsl.OvhInstallationEnum offer) throws IOException {
String qPath = "/price/xdsl/installation/{offer}";
StringBuilder sb = path(qPath, offer);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | [
"public",
"OvhPrice",
"xdsl_installation_offer_GET",
"(",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"price",
".",
"xdsl",
".",
"OvhInstallationEnum",
"offer",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/price/xdsl/installation/{offer}\""... | Get the price of options installation fee
REST: GET /price/xdsl/installation/{offer}
@param offer [required] The offer | [
"Get",
"the",
"price",
"of",
"options",
"installation",
"fee"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java#L89-L94 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.