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 |
|---|---|---|---|---|---|---|---|---|---|---|
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java | CassandraSchemaManager.setProperties | private void setProperties(KsDef ksDef, Map<String, String> strategy_options)
{
Schema schema = CassandraPropertyReader.csmd.getSchema(databaseName);
if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName)
&& schema.getSchemaProperties() != null)
{
setKeyspaceProperties(ksDef, schema.getSchemaProperties(), strategy_options, schema.getDataCenters());
}
else
{
setDefaultReplicationFactor(strategy_options);
}
} | java | private void setProperties(KsDef ksDef, Map<String, String> strategy_options)
{
Schema schema = CassandraPropertyReader.csmd.getSchema(databaseName);
if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName)
&& schema.getSchemaProperties() != null)
{
setKeyspaceProperties(ksDef, schema.getSchemaProperties(), strategy_options, schema.getDataCenters());
}
else
{
setDefaultReplicationFactor(strategy_options);
}
} | [
"private",
"void",
"setProperties",
"(",
"KsDef",
"ksDef",
",",
"Map",
"<",
"String",
",",
"String",
">",
"strategy_options",
")",
"{",
"Schema",
"schema",
"=",
"CassandraPropertyReader",
".",
"csmd",
".",
"getSchema",
"(",
"databaseName",
")",
";",
"if",
"(... | Sets the properties.
@param ksDef
the ks def
@param strategy_options
the strategy_options | [
"Sets",
"the",
"properties",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java#L2157-L2169 |
apache/incubator-gobblin | gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java | BaseEnvelopeSchemaConverter.getFieldSchema | protected Schema getFieldSchema(GenericRecord record, String schemaIdLocation) throws Exception {
Optional<Object> schemaIdValue = AvroUtils.getFieldValue(record, schemaIdLocation);
if (!schemaIdValue.isPresent()) {
throw new Exception("Schema id with key " + schemaIdLocation + " not found in the record");
}
String schemaKey = String.valueOf(schemaIdValue.get());
return (Schema) registry.getSchemaByKey(schemaKey);
} | java | protected Schema getFieldSchema(GenericRecord record, String schemaIdLocation) throws Exception {
Optional<Object> schemaIdValue = AvroUtils.getFieldValue(record, schemaIdLocation);
if (!schemaIdValue.isPresent()) {
throw new Exception("Schema id with key " + schemaIdLocation + " not found in the record");
}
String schemaKey = String.valueOf(schemaIdValue.get());
return (Schema) registry.getSchemaByKey(schemaKey);
} | [
"protected",
"Schema",
"getFieldSchema",
"(",
"GenericRecord",
"record",
",",
"String",
"schemaIdLocation",
")",
"throws",
"Exception",
"{",
"Optional",
"<",
"Object",
">",
"schemaIdValue",
"=",
"AvroUtils",
".",
"getFieldValue",
"(",
"record",
",",
"schemaIdLocatio... | Get the schema of a field
@param record the input record which has the schema id
@param schemaIdLocation a dot separated location string the schema id
@return a schema referenced by the schema id | [
"Get",
"the",
"schema",
"of",
"a",
"field"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java#L101-L108 |
real-logic/agrona | agrona/src/main/java/org/agrona/collections/Object2IntHashMap.java | Object2IntHashMap.computeIfAbsent | public int computeIfAbsent(final K key, final ToIntFunction<? super K> mappingFunction)
{
int value = getValue(key);
if (value == missingValue)
{
value = mappingFunction.applyAsInt(key);
if (value != missingValue)
{
put(key, value);
}
}
return value;
} | java | public int computeIfAbsent(final K key, final ToIntFunction<? super K> mappingFunction)
{
int value = getValue(key);
if (value == missingValue)
{
value = mappingFunction.applyAsInt(key);
if (value != missingValue)
{
put(key, value);
}
}
return value;
} | [
"public",
"int",
"computeIfAbsent",
"(",
"final",
"K",
"key",
",",
"final",
"ToIntFunction",
"<",
"?",
"super",
"K",
">",
"mappingFunction",
")",
"{",
"int",
"value",
"=",
"getValue",
"(",
"key",
")",
";",
"if",
"(",
"value",
"==",
"missingValue",
")",
... | Get a value for a given key, or if it does not exist then default the value via a
{@link java.util.function.IntFunction} and put it in the map.
<p>
Primitive specialized version of {@link java.util.Map#computeIfAbsent}.
@param key to search on.
@param mappingFunction to provide a value if the get returns missingValue.
@return the value if found otherwise the default. | [
"Get",
"a",
"value",
"for",
"a",
"given",
"key",
"or",
"if",
"it",
"does",
"not",
"exist",
"then",
"default",
"the",
"value",
"via",
"a",
"{",
"@link",
"java",
".",
"util",
".",
"function",
".",
"IntFunction",
"}",
"and",
"put",
"it",
"in",
"the",
... | train | https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/Object2IntHashMap.java#L278-L291 |
davetcc/tcMenu | tcMenuGenerator/src/main/java/com/thecoderscorner/menu/editorui/controller/OSXAdapter.java | OSXAdapter.setAboutHandler | public static boolean setAboutHandler(Object target, Method aboutHandler) {
boolean enableAboutMenu = (target != null && aboutHandler != null);
if (enableAboutMenu) {
setHandler(new OSXAdapter("handleAbout", target, aboutHandler));
}
// If we're setting a handler, enable the About menu item by calling
// com.apple.eawt.Application reflectively
try {
Method enableAboutMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledAboutMenu", new Class[] { boolean.class });
enableAboutMethod.invoke(macOSXApplication, new Object[] { Boolean.valueOf(enableAboutMenu) });
return true;
} catch (Exception ex) {
System.err.println("OSXAdapter could not access the About Menu");
ex.printStackTrace();
return false;
}
} | java | public static boolean setAboutHandler(Object target, Method aboutHandler) {
boolean enableAboutMenu = (target != null && aboutHandler != null);
if (enableAboutMenu) {
setHandler(new OSXAdapter("handleAbout", target, aboutHandler));
}
// If we're setting a handler, enable the About menu item by calling
// com.apple.eawt.Application reflectively
try {
Method enableAboutMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledAboutMenu", new Class[] { boolean.class });
enableAboutMethod.invoke(macOSXApplication, new Object[] { Boolean.valueOf(enableAboutMenu) });
return true;
} catch (Exception ex) {
System.err.println("OSXAdapter could not access the About Menu");
ex.printStackTrace();
return false;
}
} | [
"public",
"static",
"boolean",
"setAboutHandler",
"(",
"Object",
"target",
",",
"Method",
"aboutHandler",
")",
"{",
"boolean",
"enableAboutMenu",
"=",
"(",
"target",
"!=",
"null",
"&&",
"aboutHandler",
"!=",
"null",
")",
";",
"if",
"(",
"enableAboutMenu",
")",... | They will be called when the About menu item is selected from the application menu | [
"They",
"will",
"be",
"called",
"when",
"the",
"About",
"menu",
"item",
"is",
"selected",
"from",
"the",
"application",
"menu"
] | train | https://github.com/davetcc/tcMenu/blob/61546e4b982b25ceaff384073fe9ec1fff55e64a/tcMenuGenerator/src/main/java/com/thecoderscorner/menu/editorui/controller/OSXAdapter.java#L89-L105 |
elki-project/elki | elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/clique/CLIQUEUnit.java | CLIQUEUnit.checkDimensions | private boolean checkDimensions(CLIQUEUnit other, int e) {
for(int i = 0, j = 0; i < e; i++, j += 2) {
if(dims[i] != other.dims[i] || bounds[j] != other.bounds[j] || bounds[j + 1] != bounds[j + 1]) {
return false;
}
}
return true;
} | java | private boolean checkDimensions(CLIQUEUnit other, int e) {
for(int i = 0, j = 0; i < e; i++, j += 2) {
if(dims[i] != other.dims[i] || bounds[j] != other.bounds[j] || bounds[j + 1] != bounds[j + 1]) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"checkDimensions",
"(",
"CLIQUEUnit",
"other",
",",
"int",
"e",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"j",
"=",
"0",
";",
"i",
"<",
"e",
";",
"i",
"++",
",",
"j",
"+=",
"2",
")",
"{",
"if",
"(",
"dims",
"[",
... | Check that the first e dimensions agree.
@param other Other unit
@param e Number of dimensions to check
@return {@code true} if the first e dimensions are the same (index and
bounds) | [
"Check",
"that",
"the",
"first",
"e",
"dimensions",
"agree",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/clique/CLIQUEUnit.java#L256-L263 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpd/MPDUtility.java | MPDUtility.fileDump | public static final void fileDump(String fileName, byte[] data)
{
try
{
FileOutputStream os = new FileOutputStream(fileName);
os.write(data);
os.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
} | java | public static final void fileDump(String fileName, byte[] data)
{
try
{
FileOutputStream os = new FileOutputStream(fileName);
os.write(data);
os.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
} | [
"public",
"static",
"final",
"void",
"fileDump",
"(",
"String",
"fileName",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"try",
"{",
"FileOutputStream",
"os",
"=",
"new",
"FileOutputStream",
"(",
"fileName",
")",
";",
"os",
".",
"write",
"(",
"data",
")",
... | Writes a large byte array to a file.
@param fileName output file name
@param data target data | [
"Writes",
"a",
"large",
"byte",
"array",
"to",
"a",
"file",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpd/MPDUtility.java#L509-L522 |
livetribe/livetribe-slp | core/src/main/java/org/livetribe/slp/da/StandardDirectoryAgentServer.java | StandardDirectoryAgentServer.handleTCPSrvReg | protected void handleTCPSrvReg(SrvReg srvReg, Socket socket)
{
try
{
boolean update = srvReg.isUpdating();
ServiceInfo service = ServiceInfo.from(srvReg);
cacheService(service, update);
tcpSrvAck.perform(socket, srvReg, SLPError.NO_ERROR);
}
catch (ServiceLocationException x)
{
tcpSrvAck.perform(socket, srvReg, x.getSLPError());
}
} | java | protected void handleTCPSrvReg(SrvReg srvReg, Socket socket)
{
try
{
boolean update = srvReg.isUpdating();
ServiceInfo service = ServiceInfo.from(srvReg);
cacheService(service, update);
tcpSrvAck.perform(socket, srvReg, SLPError.NO_ERROR);
}
catch (ServiceLocationException x)
{
tcpSrvAck.perform(socket, srvReg, x.getSLPError());
}
} | [
"protected",
"void",
"handleTCPSrvReg",
"(",
"SrvReg",
"srvReg",
",",
"Socket",
"socket",
")",
"{",
"try",
"{",
"boolean",
"update",
"=",
"srvReg",
".",
"isUpdating",
"(",
")",
";",
"ServiceInfo",
"service",
"=",
"ServiceInfo",
".",
"from",
"(",
"srvReg",
... | Handles a unicast TCP SrvReg message arrived to this directory agent.
<br />
This directory agent will reply with an acknowledge containing the result of the registration.
@param srvReg the SrvReg message to handle
@param socket the socket connected to th client where to write the reply | [
"Handles",
"a",
"unicast",
"TCP",
"SrvReg",
"message",
"arrived",
"to",
"this",
"directory",
"agent",
".",
"<br",
"/",
">",
"This",
"directory",
"agent",
"will",
"reply",
"with",
"an",
"acknowledge",
"containing",
"the",
"result",
"of",
"the",
"registration",
... | train | https://github.com/livetribe/livetribe-slp/blob/6cc13dbe81feab133fe3dd291ca081cbc6e1f591/core/src/main/java/org/livetribe/slp/da/StandardDirectoryAgentServer.java#L547-L560 |
apiman/apiman | gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultPluginRegistry.java | DefaultPluginRegistry.downloadFromMavenRepo | protected void downloadFromMavenRepo(PluginCoordinates coordinates, URI mavenRepoUrl, IAsyncResultHandler<File> handler) {
String artifactSubPath = PluginUtils.getMavenPath(coordinates);
try {
File tempArtifactFile = File.createTempFile("_plugin", "dwn"); //$NON-NLS-1$ //$NON-NLS-2$
URL artifactUrl = new URL(mavenRepoUrl.toURL(), artifactSubPath);
downloadArtifactTo(artifactUrl, tempArtifactFile, handler);
} catch (Exception e) {
handler.handle(AsyncResultImpl.<File>create(e));
}
} | java | protected void downloadFromMavenRepo(PluginCoordinates coordinates, URI mavenRepoUrl, IAsyncResultHandler<File> handler) {
String artifactSubPath = PluginUtils.getMavenPath(coordinates);
try {
File tempArtifactFile = File.createTempFile("_plugin", "dwn"); //$NON-NLS-1$ //$NON-NLS-2$
URL artifactUrl = new URL(mavenRepoUrl.toURL(), artifactSubPath);
downloadArtifactTo(artifactUrl, tempArtifactFile, handler);
} catch (Exception e) {
handler.handle(AsyncResultImpl.<File>create(e));
}
} | [
"protected",
"void",
"downloadFromMavenRepo",
"(",
"PluginCoordinates",
"coordinates",
",",
"URI",
"mavenRepoUrl",
",",
"IAsyncResultHandler",
"<",
"File",
">",
"handler",
")",
"{",
"String",
"artifactSubPath",
"=",
"PluginUtils",
".",
"getMavenPath",
"(",
"coordinate... | Tries to download the plugin from the given remote maven repository. | [
"Tries",
"to",
"download",
"the",
"plugin",
"from",
"the",
"given",
"remote",
"maven",
"repository",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultPluginRegistry.java#L360-L369 |
rzwitserloot/lombok | src/core/lombok/javac/HandlerLibrary.java | HandlerLibrary.loadVisitorHandlers | private static void loadVisitorHandlers(HandlerLibrary lib, Trees trees) throws IOException {
//No, that seemingly superfluous reference to JavacASTVisitor's classloader is not in fact superfluous!
for (JavacASTVisitor visitor : SpiLoadUtil.findServices(JavacASTVisitor.class, JavacASTVisitor.class.getClassLoader())) {
visitor.setTrees(trees);
lib.visitorHandlers.add(new VisitorContainer(visitor));
}
} | java | private static void loadVisitorHandlers(HandlerLibrary lib, Trees trees) throws IOException {
//No, that seemingly superfluous reference to JavacASTVisitor's classloader is not in fact superfluous!
for (JavacASTVisitor visitor : SpiLoadUtil.findServices(JavacASTVisitor.class, JavacASTVisitor.class.getClassLoader())) {
visitor.setTrees(trees);
lib.visitorHandlers.add(new VisitorContainer(visitor));
}
} | [
"private",
"static",
"void",
"loadVisitorHandlers",
"(",
"HandlerLibrary",
"lib",
",",
"Trees",
"trees",
")",
"throws",
"IOException",
"{",
"//No, that seemingly superfluous reference to JavacASTVisitor's classloader is not in fact superfluous!",
"for",
"(",
"JavacASTVisitor",
"v... | Uses SPI Discovery to find implementations of {@link JavacASTVisitor}. | [
"Uses",
"SPI",
"Discovery",
"to",
"find",
"implementations",
"of",
"{"
] | train | https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/HandlerLibrary.java#L194-L200 |
hsiafan/requests | src/main/java/net/dongliu/requests/RawResponse.java | RawResponse.decompressBody | private InputStream decompressBody() {
if (!decompress) {
return body;
}
// if has no body, some server still set content-encoding header,
// GZIPInputStream wrap empty input stream will cause exception. we should check this
if (method.equals(Methods.HEAD)
|| (statusCode >= 100 && statusCode < 200) || statusCode == NOT_MODIFIED || statusCode == NO_CONTENT) {
return body;
}
String contentEncoding = headers.getHeader(NAME_CONTENT_ENCODING);
if (contentEncoding == null) {
return body;
}
//we should remove the content-encoding header here?
switch (contentEncoding) {
case "gzip":
try {
return new GZIPInputStream(body);
} catch (IOException e) {
Closeables.closeQuietly(body);
throw new RequestsException(e);
}
case "deflate":
// Note: deflate implements may or may not wrap in zlib due to rfc confusing.
// here deal with deflate without zlib header
return new InflaterInputStream(body, new Inflater(true));
case "identity":
case "compress": //historic; deprecated in most applications and replaced by gzip or deflate
default:
return body;
}
} | java | private InputStream decompressBody() {
if (!decompress) {
return body;
}
// if has no body, some server still set content-encoding header,
// GZIPInputStream wrap empty input stream will cause exception. we should check this
if (method.equals(Methods.HEAD)
|| (statusCode >= 100 && statusCode < 200) || statusCode == NOT_MODIFIED || statusCode == NO_CONTENT) {
return body;
}
String contentEncoding = headers.getHeader(NAME_CONTENT_ENCODING);
if (contentEncoding == null) {
return body;
}
//we should remove the content-encoding header here?
switch (contentEncoding) {
case "gzip":
try {
return new GZIPInputStream(body);
} catch (IOException e) {
Closeables.closeQuietly(body);
throw new RequestsException(e);
}
case "deflate":
// Note: deflate implements may or may not wrap in zlib due to rfc confusing.
// here deal with deflate without zlib header
return new InflaterInputStream(body, new Inflater(true));
case "identity":
case "compress": //historic; deprecated in most applications and replaced by gzip or deflate
default:
return body;
}
} | [
"private",
"InputStream",
"decompressBody",
"(",
")",
"{",
"if",
"(",
"!",
"decompress",
")",
"{",
"return",
"body",
";",
"}",
"// if has no body, some server still set content-encoding header,",
"// GZIPInputStream wrap empty input stream will cause exception. we should check this... | Wrap response input stream if it is compressed, return input its self if not use compress | [
"Wrap",
"response",
"input",
"stream",
"if",
"it",
"is",
"compressed",
"return",
"input",
"its",
"self",
"if",
"not",
"use",
"compress"
] | train | https://github.com/hsiafan/requests/blob/a6cc6f8293e808cc937d3789aec2616a8383dee0/src/main/java/net/dongliu/requests/RawResponse.java#L378-L412 |
samskivert/samskivert | src/main/java/com/samskivert/swing/GroupLayout.java | GroupLayout.makeVBox | public static JPanel makeVBox (Policy policy, Justification justification)
{
return new JPanel(new VGroupLayout(policy, justification));
} | java | public static JPanel makeVBox (Policy policy, Justification justification)
{
return new JPanel(new VGroupLayout(policy, justification));
} | [
"public",
"static",
"JPanel",
"makeVBox",
"(",
"Policy",
"policy",
",",
"Justification",
"justification",
")",
"{",
"return",
"new",
"JPanel",
"(",
"new",
"VGroupLayout",
"(",
"policy",
",",
"justification",
")",
")",
";",
"}"
] | Creates a {@link JPanel} that is configured with an {@link
VGroupLayout} with the specified on-axis policy and justification
(default configuration otherwise). | [
"Creates",
"a",
"{"
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/GroupLayout.java#L405-L408 |
apache/flink | flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/history/HistoryServerArchiveFetcher.java | HistoryServerArchiveFetcher.updateJobOverview | private static void updateJobOverview(File webOverviewDir, File webDir) {
try (JsonGenerator gen = jacksonFactory.createGenerator(HistoryServer.createOrGetFile(webDir, JobsOverviewHeaders.URL))) {
File[] overviews = new File(webOverviewDir.getPath()).listFiles();
if (overviews != null) {
Collection<JobDetails> allJobs = new ArrayList<>(overviews.length);
for (File overview : overviews) {
MultipleJobsDetails subJobs = mapper.readValue(overview, MultipleJobsDetails.class);
allJobs.addAll(subJobs.getJobs());
}
mapper.writeValue(gen, new MultipleJobsDetails(allJobs));
}
} catch (IOException ioe) {
LOG.error("Failed to update job overview.", ioe);
}
} | java | private static void updateJobOverview(File webOverviewDir, File webDir) {
try (JsonGenerator gen = jacksonFactory.createGenerator(HistoryServer.createOrGetFile(webDir, JobsOverviewHeaders.URL))) {
File[] overviews = new File(webOverviewDir.getPath()).listFiles();
if (overviews != null) {
Collection<JobDetails> allJobs = new ArrayList<>(overviews.length);
for (File overview : overviews) {
MultipleJobsDetails subJobs = mapper.readValue(overview, MultipleJobsDetails.class);
allJobs.addAll(subJobs.getJobs());
}
mapper.writeValue(gen, new MultipleJobsDetails(allJobs));
}
} catch (IOException ioe) {
LOG.error("Failed to update job overview.", ioe);
}
} | [
"private",
"static",
"void",
"updateJobOverview",
"(",
"File",
"webOverviewDir",
",",
"File",
"webDir",
")",
"{",
"try",
"(",
"JsonGenerator",
"gen",
"=",
"jacksonFactory",
".",
"createGenerator",
"(",
"HistoryServer",
".",
"createOrGetFile",
"(",
"webDir",
",",
... | This method replicates the JSON response that would be given by the JobsOverviewHandler when
listing both running and finished jobs.
<p>Every job archive contains a joboverview.json file containing the same structure. Since jobs are archived on
their own however the list of finished jobs only contains a single job.
<p>For the display in the HistoryServer WebFrontend we have to combine these overviews. | [
"This",
"method",
"replicates",
"the",
"JSON",
"response",
"that",
"would",
"be",
"given",
"by",
"the",
"JobsOverviewHandler",
"when",
"listing",
"both",
"running",
"and",
"finished",
"jobs",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/history/HistoryServerArchiveFetcher.java#L285-L299 |
synchronoss/cpo-api | cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java | CassandraCpoAdapter.insertObject | @Override
public <T> long insertObject(String name, T obj) throws CpoException {
return processUpdateGroup(obj, CpoAdapter.CREATE_GROUP, name, null, null, null);
} | java | @Override
public <T> long insertObject(String name, T obj) throws CpoException {
return processUpdateGroup(obj, CpoAdapter.CREATE_GROUP, name, null, null, null);
} | [
"@",
"Override",
"public",
"<",
"T",
">",
"long",
"insertObject",
"(",
"String",
"name",
",",
"T",
"obj",
")",
"throws",
"CpoException",
"{",
"return",
"processUpdateGroup",
"(",
"obj",
",",
"CpoAdapter",
".",
"CREATE_GROUP",
",",
"name",
",",
"null",
",",... | Creates the Object in the datasource. The assumption is that the object does not exist in the datasource. This
method creates and stores the object in the datasource
<p/>
<pre>Example:
<code>
<p/>
class SomeObject so = new SomeObject();
class CpoAdapter cpo = null;
<p/>
try {
cpo = new CpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false));
} catch (CpoException ce) {
// Handle the error
cpo = null;
}
<p/>
if (cpo!=null) {
so.setId(1);
so.setName("SomeName");
try{
cpo.insertObject("IDNameInsert",so);
} catch (CpoException ce) {
// Handle the error
}
}
</code>
</pre>
@param name The String name of the CREATE Function Group that will be used to create the object in the datasource.
null signifies that the default rules will be used which is equivalent to insertObject(Object obj);
@param obj This is an object that has been defined within the metadata of the datasource. If the class is not
defined an exception will be thrown.
@return The number of objects created in the datasource
@throws CpoException Thrown if there are errors accessing the datasource | [
"Creates",
"the",
"Object",
"in",
"the",
"datasource",
".",
"The",
"assumption",
"is",
"that",
"the",
"object",
"does",
"not",
"exist",
"in",
"the",
"datasource",
".",
"This",
"method",
"creates",
"and",
"stores",
"the",
"object",
"in",
"the",
"datasource",
... | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L198-L201 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareGraph.java | SquareGraph.almostParallel | public boolean almostParallel(SquareNode a , int sideA , SquareNode b , int sideB ) {
double selected = acuteAngle(a,sideA,b,sideB);
if( selected > parallelThreshold )
return false;
// see if the two sides are about parallel too
// double left = acuteAngle(a,add(sideA,-1),b,add(sideB,1));
// double right = acuteAngle(a,add(sideA,1),b,add(sideB,-1));
//
// if( left > selected+parallelThreshold || right > selected+parallelThreshold )
// return false;
// if( selected > acuteAngle(a,sideA,b,add(sideB,1)) || selected > acuteAngle(a,sideA,b,add(sideB,-1)) )
// return false;
//
// if( selected > acuteAngle(a,add(sideA,1),b,sideB) || selected > acuteAngle(a,add(sideA,-1),b,sideB) )
// return false;
return true;
} | java | public boolean almostParallel(SquareNode a , int sideA , SquareNode b , int sideB ) {
double selected = acuteAngle(a,sideA,b,sideB);
if( selected > parallelThreshold )
return false;
// see if the two sides are about parallel too
// double left = acuteAngle(a,add(sideA,-1),b,add(sideB,1));
// double right = acuteAngle(a,add(sideA,1),b,add(sideB,-1));
//
// if( left > selected+parallelThreshold || right > selected+parallelThreshold )
// return false;
// if( selected > acuteAngle(a,sideA,b,add(sideB,1)) || selected > acuteAngle(a,sideA,b,add(sideB,-1)) )
// return false;
//
// if( selected > acuteAngle(a,add(sideA,1),b,sideB) || selected > acuteAngle(a,add(sideA,-1),b,sideB) )
// return false;
return true;
} | [
"public",
"boolean",
"almostParallel",
"(",
"SquareNode",
"a",
",",
"int",
"sideA",
",",
"SquareNode",
"b",
",",
"int",
"sideB",
")",
"{",
"double",
"selected",
"=",
"acuteAngle",
"(",
"a",
",",
"sideA",
",",
"b",
",",
"sideB",
")",
";",
"if",
"(",
"... | Checks to see if the two sides are almost parallel to each other by looking at their acute
angle. | [
"Checks",
"to",
"see",
"if",
"the",
"two",
"sides",
"are",
"almost",
"parallel",
"to",
"each",
"other",
"by",
"looking",
"at",
"their",
"acute",
"angle",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/squares/SquareGraph.java#L139-L160 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java | Types.rewriteQuantifiers | private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
return new Rewriter(high, rewriteTypeVars).visit(t);
} | java | private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
return new Rewriter(high, rewriteTypeVars).visit(t);
} | [
"private",
"Type",
"rewriteQuantifiers",
"(",
"Type",
"t",
",",
"boolean",
"high",
",",
"boolean",
"rewriteTypeVars",
")",
"{",
"return",
"new",
"Rewriter",
"(",
"high",
",",
"rewriteTypeVars",
")",
".",
"visit",
"(",
"t",
")",
";",
"}"
] | Rewrite all type variables (universal quantifiers) in the given
type to wildcards (existential quantifiers). This is used to
determine if a cast is allowed. For example, if high is true
and {@code T <: Number}, then {@code List<T>} is rewritten to
{@code List<? extends Number>}. Since {@code List<Integer> <:
List<? extends Number>} a {@code List<T>} can be cast to {@code
List<Integer>} with a warning.
@param t a type
@param high if true return an upper bound; otherwise a lower
bound
@param rewriteTypeVars only rewrite captured wildcards if false;
otherwise rewrite all type variables
@return the type rewritten with wildcards (existential
quantifiers) only | [
"Rewrite",
"all",
"type",
"variables",
"(",
"universal",
"quantifiers",
")",
"in",
"the",
"given",
"type",
"to",
"wildcards",
"(",
"existential",
"quantifiers",
")",
".",
"This",
"is",
"used",
"to",
"determine",
"if",
"a",
"cast",
"is",
"allowed",
".",
"Fo... | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java#L4434-L4436 |
amaembo/streamex | src/main/java/one/util/streamex/StreamEx.java | StreamEx.cartesianPower | public static <T, U> StreamEx<U> cartesianPower(int n, Collection<T> source, U identity,
BiFunction<U, ? super T, U> accumulator) {
if (n == 0)
return of(identity);
return of(new CrossSpliterator.Reducing<>(Collections.nCopies(n, source), identity, accumulator));
} | java | public static <T, U> StreamEx<U> cartesianPower(int n, Collection<T> source, U identity,
BiFunction<U, ? super T, U> accumulator) {
if (n == 0)
return of(identity);
return of(new CrossSpliterator.Reducing<>(Collections.nCopies(n, source), identity, accumulator));
} | [
"public",
"static",
"<",
"T",
",",
"U",
">",
"StreamEx",
"<",
"U",
">",
"cartesianPower",
"(",
"int",
"n",
",",
"Collection",
"<",
"T",
">",
"source",
",",
"U",
"identity",
",",
"BiFunction",
"<",
"U",
",",
"?",
"super",
"T",
",",
"U",
">",
"accu... | Returns a new {@code StreamEx} which elements are results of reduction of
all possible n-tuples composed from the elements of supplied collections.
The whole stream forms an n-fold Cartesian product of input collection
with itself or n-ary Cartesian power of the input collection.
<p>
The reduction is performed using the provided identity object and the
accumulator function which is capable to accumulate new element. The
accumulator function must not modify the previous accumulated value, but
must produce new value instead. That's because partially accumulated
values are reused for subsequent elements.
<p>
This method is equivalent to the following:
<pre>
{@code StreamEx.cartesianPower(n, source).map(list -> StreamEx.of(list).foldLeft(identity, accumulator))}
</pre>
<p>
However it may perform much faster as partial reduction results are
reused.
<p>
The supplied collection is assumed to be unchanged during the operation.
@param <T> the type of the input elements
@param <U> the type of the elements of the resulting stream
@param n the number of elements to incorporate into single element of the
resulting stream.
@param source the input collection of collections which is used to
generate the Cartesian power.
@param identity the identity value
@param accumulator a <a
href="package-summary.html#NonInterference">non-interfering </a>,
<a href="package-summary.html#Statelessness">stateless</a>
function for incorporating an additional element from source
collection into a stream element.
@return the new stream.
@see #cartesianProduct(Collection, Object, BiFunction)
@see #cartesianPower(int, Collection)
@since 0.4.0 | [
"Returns",
"a",
"new",
"{",
"@code",
"StreamEx",
"}",
"which",
"elements",
"are",
"results",
"of",
"reduction",
"of",
"all",
"possible",
"n",
"-",
"tuples",
"composed",
"from",
"the",
"elements",
"of",
"supplied",
"collections",
".",
"The",
"whole",
"stream"... | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L3223-L3228 |
libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/sched/PriorityScheduler.java | PriorityScheduler.addWithAutomaticPhasing | public void addWithAutomaticPhasing (Schedulable schedulable, int frequency, float priority) {
// Calculate the phase and add the schedulable to the list
add(schedulable, frequency, calculatePhase(frequency), priority);
} | java | public void addWithAutomaticPhasing (Schedulable schedulable, int frequency, float priority) {
// Calculate the phase and add the schedulable to the list
add(schedulable, frequency, calculatePhase(frequency), priority);
} | [
"public",
"void",
"addWithAutomaticPhasing",
"(",
"Schedulable",
"schedulable",
",",
"int",
"frequency",
",",
"float",
"priority",
")",
"{",
"// Calculate the phase and add the schedulable to the list",
"add",
"(",
"schedulable",
",",
"frequency",
",",
"calculatePhase",
"... | Adds the {@code schedulable} to the list using the given {@code frequency} and {@code priority} while the phase is
calculated by a dry run of the scheduler.
@param schedulable the task to schedule
@param frequency the frequency
@param priority the priority | [
"Adds",
"the",
"{"
] | train | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/sched/PriorityScheduler.java#L97-L100 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/CharInfo.java | CharInfo.getCharInfo | static CharInfo getCharInfo(String entitiesFileName, String method)
{
CharInfo charInfo = (CharInfo) m_getCharInfoCache.get(entitiesFileName);
if (charInfo != null) {
return mutableCopyOf(charInfo);
}
// try to load it internally - cache
try {
charInfo = getCharInfoBasedOnPrivilege(entitiesFileName,
method, true);
// Put the common copy of charInfo in the cache, but return
// a copy of it.
m_getCharInfoCache.put(entitiesFileName, charInfo);
return mutableCopyOf(charInfo);
} catch (Exception e) {}
// try to load it externally - do not cache
try {
return getCharInfoBasedOnPrivilege(entitiesFileName,
method, false);
} catch (Exception e) {}
String absoluteEntitiesFileName;
if (entitiesFileName.indexOf(':') < 0) {
absoluteEntitiesFileName =
SystemIDResolver.getAbsoluteURIFromRelative(entitiesFileName);
} else {
try {
absoluteEntitiesFileName =
SystemIDResolver.getAbsoluteURI(entitiesFileName, null);
} catch (TransformerException te) {
throw new WrappedRuntimeException(te);
}
}
return getCharInfoBasedOnPrivilege(entitiesFileName,
method, false);
} | java | static CharInfo getCharInfo(String entitiesFileName, String method)
{
CharInfo charInfo = (CharInfo) m_getCharInfoCache.get(entitiesFileName);
if (charInfo != null) {
return mutableCopyOf(charInfo);
}
// try to load it internally - cache
try {
charInfo = getCharInfoBasedOnPrivilege(entitiesFileName,
method, true);
// Put the common copy of charInfo in the cache, but return
// a copy of it.
m_getCharInfoCache.put(entitiesFileName, charInfo);
return mutableCopyOf(charInfo);
} catch (Exception e) {}
// try to load it externally - do not cache
try {
return getCharInfoBasedOnPrivilege(entitiesFileName,
method, false);
} catch (Exception e) {}
String absoluteEntitiesFileName;
if (entitiesFileName.indexOf(':') < 0) {
absoluteEntitiesFileName =
SystemIDResolver.getAbsoluteURIFromRelative(entitiesFileName);
} else {
try {
absoluteEntitiesFileName =
SystemIDResolver.getAbsoluteURI(entitiesFileName, null);
} catch (TransformerException te) {
throw new WrappedRuntimeException(te);
}
}
return getCharInfoBasedOnPrivilege(entitiesFileName,
method, false);
} | [
"static",
"CharInfo",
"getCharInfo",
"(",
"String",
"entitiesFileName",
",",
"String",
"method",
")",
"{",
"CharInfo",
"charInfo",
"=",
"(",
"CharInfo",
")",
"m_getCharInfoCache",
".",
"get",
"(",
"entitiesFileName",
")",
";",
"if",
"(",
"charInfo",
"!=",
"nul... | Factory that reads in a resource file that describes the mapping of
characters to entity references.
Resource files must be encoded in UTF-8 and have a format like:
<pre>
# First char # is a comment
Entity numericValue
quot 34
amp 38
</pre>
(Note: Why don't we just switch to .properties files? Oct-01 -sc)
@param entitiesResource Name of entities resource file that should
be loaded, which describes that mapping of characters to entity references.
@param method the output method type, which should be one of "xml", "html", "text"...
@xsl.usage internal | [
"Factory",
"that",
"reads",
"in",
"a",
"resource",
"file",
"that",
"describes",
"the",
"mapping",
"of",
"characters",
"to",
"entity",
"references",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/CharInfo.java#L498-L537 |
glyptodon/guacamole-client | extensions/guacamole-auth-totp/src/main/java/org/apache/guacamole/auth/totp/user/UserVerificationService.java | UserVerificationService.setKey | private boolean setKey(UserContext context, UserTOTPKey key)
throws GuacamoleException {
// Get mutable set of attributes
User self = context.self();
Map<String, String> attributes = new HashMap<String, String>();
// Set/overwrite current TOTP key state
attributes.put(TOTPUser.TOTP_KEY_SECRET_ATTRIBUTE_NAME, BASE32.encode(key.getSecret()));
attributes.put(TOTPUser.TOTP_KEY_CONFIRMED_ATTRIBUTE_NAME, key.isConfirmed() ? "true" : "false");
self.setAttributes(attributes);
// Confirm that attributes have actually been set
Map<String, String> setAttributes = self.getAttributes();
if (!setAttributes.containsKey(TOTPUser.TOTP_KEY_SECRET_ATTRIBUTE_NAME)
|| !setAttributes.containsKey(TOTPUser.TOTP_KEY_CONFIRMED_ATTRIBUTE_NAME))
return false;
// Update user object
try {
context.getUserDirectory().update(self);
}
catch (GuacamoleSecurityException e) {
logger.info("User \"{}\" cannot store their TOTP key as they "
+ "lack permission to update their own account. TOTP "
+ "will be disabled for this user.",
self.getIdentifier());
logger.debug("Permission denied to set TOTP key of user "
+ "account.", e);
return false;
}
catch (GuacamoleUnsupportedException e) {
logger.debug("Extension storage for user is explicitly read-only. "
+ "Cannot update attributes to store TOTP key.", e);
return false;
}
// TOTP key successfully stored/updated
return true;
} | java | private boolean setKey(UserContext context, UserTOTPKey key)
throws GuacamoleException {
// Get mutable set of attributes
User self = context.self();
Map<String, String> attributes = new HashMap<String, String>();
// Set/overwrite current TOTP key state
attributes.put(TOTPUser.TOTP_KEY_SECRET_ATTRIBUTE_NAME, BASE32.encode(key.getSecret()));
attributes.put(TOTPUser.TOTP_KEY_CONFIRMED_ATTRIBUTE_NAME, key.isConfirmed() ? "true" : "false");
self.setAttributes(attributes);
// Confirm that attributes have actually been set
Map<String, String> setAttributes = self.getAttributes();
if (!setAttributes.containsKey(TOTPUser.TOTP_KEY_SECRET_ATTRIBUTE_NAME)
|| !setAttributes.containsKey(TOTPUser.TOTP_KEY_CONFIRMED_ATTRIBUTE_NAME))
return false;
// Update user object
try {
context.getUserDirectory().update(self);
}
catch (GuacamoleSecurityException e) {
logger.info("User \"{}\" cannot store their TOTP key as they "
+ "lack permission to update their own account. TOTP "
+ "will be disabled for this user.",
self.getIdentifier());
logger.debug("Permission denied to set TOTP key of user "
+ "account.", e);
return false;
}
catch (GuacamoleUnsupportedException e) {
logger.debug("Extension storage for user is explicitly read-only. "
+ "Cannot update attributes to store TOTP key.", e);
return false;
}
// TOTP key successfully stored/updated
return true;
} | [
"private",
"boolean",
"setKey",
"(",
"UserContext",
"context",
",",
"UserTOTPKey",
"key",
")",
"throws",
"GuacamoleException",
"{",
"// Get mutable set of attributes",
"User",
"self",
"=",
"context",
".",
"self",
"(",
")",
";",
"Map",
"<",
"String",
",",
"String... | Attempts to store the given TOTP key within the user account of the user
having the given UserContext. As not all extensions will support storage
of arbitrary attributes, this operation may fail.
@param context
The UserContext associated with the user whose TOTP key is to be
stored.
@param key
The TOTP key to store.
@return
true if the TOTP key was successfully stored, false if the extension
handling storage does not support storage of the key.
@throws GuacamoleException
If the extension handling storage fails internally while attempting
to update the user. | [
"Attempts",
"to",
"store",
"the",
"given",
"TOTP",
"key",
"within",
"the",
"user",
"account",
"of",
"the",
"user",
"having",
"the",
"given",
"UserContext",
".",
"As",
"not",
"all",
"extensions",
"will",
"support",
"storage",
"of",
"arbitrary",
"attributes",
... | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/extensions/guacamole-auth-totp/src/main/java/org/apache/guacamole/auth/totp/user/UserVerificationService.java#L164-L204 |
jbundle/jbundle | base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBasePanel.java | XBasePanel.printControlEndForm | public void printControlEndForm(PrintWriter out, int iPrintOptions)
{
if (((iPrintOptions & HtmlConstants.HEADING_SCREEN) == HtmlConstants.HEADING_SCREEN)
|| ((iPrintOptions & HtmlConstants.FOOTING_SCREEN) == HtmlConstants.FOOTING_SCREEN)
|| ((iPrintOptions & HtmlConstants.DETAIL_SCREEN) == HtmlConstants.DETAIL_SCREEN))
return; // Don't need on nested forms
//? out.println(" </instance>");
out.println("</xform>");
//? if (bFieldsFound)
if (!this.getScreenField().isToolbar())
this.printZmlToolbarControls(out, iPrintOptions | HtmlConstants.DETAIL_SCREEN); // Print this screen's toolbars
else
this.printToolbarControl(true, out, iPrintOptions); // Print this toolbar's controls
super.printControlEndForm(out, iPrintOptions);
} | java | public void printControlEndForm(PrintWriter out, int iPrintOptions)
{
if (((iPrintOptions & HtmlConstants.HEADING_SCREEN) == HtmlConstants.HEADING_SCREEN)
|| ((iPrintOptions & HtmlConstants.FOOTING_SCREEN) == HtmlConstants.FOOTING_SCREEN)
|| ((iPrintOptions & HtmlConstants.DETAIL_SCREEN) == HtmlConstants.DETAIL_SCREEN))
return; // Don't need on nested forms
//? out.println(" </instance>");
out.println("</xform>");
//? if (bFieldsFound)
if (!this.getScreenField().isToolbar())
this.printZmlToolbarControls(out, iPrintOptions | HtmlConstants.DETAIL_SCREEN); // Print this screen's toolbars
else
this.printToolbarControl(true, out, iPrintOptions); // Print this toolbar's controls
super.printControlEndForm(out, iPrintOptions);
} | [
"public",
"void",
"printControlEndForm",
"(",
"PrintWriter",
"out",
",",
"int",
"iPrintOptions",
")",
"{",
"if",
"(",
"(",
"(",
"iPrintOptions",
"&",
"HtmlConstants",
".",
"HEADING_SCREEN",
")",
"==",
"HtmlConstants",
".",
"HEADING_SCREEN",
")",
"||",
"(",
"("... | Display the start form in input format.
@param out The out stream.
@param iPrintOptions The view specific attributes. | [
"Display",
"the",
"start",
"form",
"in",
"input",
"format",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XBasePanel.java#L416-L430 |
UrielCh/ovh-java-sdk | ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java | ApiOvhIp.loadBalancing_serviceName_backend_backend_PUT | public void loadBalancing_serviceName_backend_backend_PUT(String serviceName, String backend, OvhLoadBalancingBackendIp body) throws IOException {
String qPath = "/ip/loadBalancing/{serviceName}/backend/{backend}";
StringBuilder sb = path(qPath, serviceName, backend);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void loadBalancing_serviceName_backend_backend_PUT(String serviceName, String backend, OvhLoadBalancingBackendIp body) throws IOException {
String qPath = "/ip/loadBalancing/{serviceName}/backend/{backend}";
StringBuilder sb = path(qPath, serviceName, backend);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"loadBalancing_serviceName_backend_backend_PUT",
"(",
"String",
"serviceName",
",",
"String",
"backend",
",",
"OvhLoadBalancingBackendIp",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/ip/loadBalancing/{serviceName}/backend/{backend}\"... | Alter this object properties
REST: PUT /ip/loadBalancing/{serviceName}/backend/{backend}
@param body [required] New object properties
@param serviceName [required] The internal name of your IP load balancing
@param backend [required] IP of your backend | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java#L1413-L1417 |
cdk/cdk | storage/pdb/src/main/java/org/openscience/cdk/protein/data/PDBStrand.java | PDBStrand.addAtom | @Override
public void addAtom(IAtom oAtom, IMonomer oMonomer) {
super.addAtom(oAtom, oMonomer);
if (!sequentialListOfMonomers.contains(oMonomer.getMonomerName()))
sequentialListOfMonomers.add(oMonomer.getMonomerName());
} | java | @Override
public void addAtom(IAtom oAtom, IMonomer oMonomer) {
super.addAtom(oAtom, oMonomer);
if (!sequentialListOfMonomers.contains(oMonomer.getMonomerName()))
sequentialListOfMonomers.add(oMonomer.getMonomerName());
} | [
"@",
"Override",
"public",
"void",
"addAtom",
"(",
"IAtom",
"oAtom",
",",
"IMonomer",
"oMonomer",
")",
"{",
"super",
".",
"addAtom",
"(",
"oAtom",
",",
"oMonomer",
")",
";",
"if",
"(",
"!",
"sequentialListOfMonomers",
".",
"contains",
"(",
"oMonomer",
".",... | Adds the atom oAtom to a specified Monomer. Additionally, it keeps
record of the iCode.
@param oAtom The atom to add
@param oMonomer The monomer the atom belongs to | [
"Adds",
"the",
"atom",
"oAtom",
"to",
"a",
"specified",
"Monomer",
".",
"Additionally",
"it",
"keeps",
"record",
"of",
"the",
"iCode",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/storage/pdb/src/main/java/org/openscience/cdk/protein/data/PDBStrand.java#L66-L71 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Transliterator.java | Transliterator.getBasicInstance | static Transliterator getBasicInstance(String id, String canonID) {
StringBuffer s = new StringBuffer();
Transliterator t = registry.get(id, s);
if (s.length() != 0) {
// assert(t==0);
// Instantiate an alias
t = getInstance(s.toString(), FORWARD);
}
if (t != null && canonID != null) {
t.setID(canonID);
}
return t;
} | java | static Transliterator getBasicInstance(String id, String canonID) {
StringBuffer s = new StringBuffer();
Transliterator t = registry.get(id, s);
if (s.length() != 0) {
// assert(t==0);
// Instantiate an alias
t = getInstance(s.toString(), FORWARD);
}
if (t != null && canonID != null) {
t.setID(canonID);
}
return t;
} | [
"static",
"Transliterator",
"getBasicInstance",
"(",
"String",
"id",
",",
"String",
"canonID",
")",
"{",
"StringBuffer",
"s",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"Transliterator",
"t",
"=",
"registry",
".",
"get",
"(",
"id",
",",
"s",
")",
";",
"i... | Create a transliterator from a basic ID. This is an ID
containing only the forward direction source, target, and
variant.
@param id a basic ID of the form S-T or S-T/V.
@param canonID canonical ID to apply to the result, or
null to leave the ID unchanged
@return a newly created Transliterator or null if the ID is
invalid. | [
"Create",
"a",
"transliterator",
"from",
"a",
"basic",
"ID",
".",
"This",
"is",
"an",
"ID",
"containing",
"only",
"the",
"forward",
"direction",
"source",
"target",
"and",
"variant",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Transliterator.java#L1357-L1369 |
Appendium/objectlabkit | utils/src/main/java/net/objectlab/kit/util/ObjectUtil.java | ObjectUtil.equalsValue | public static boolean equalsValue(final BigDecimal bd1, final BigDecimal bd2) {
if (bd1 == null) {
return bd2 == null;
}
return BigDecimalUtil.isSameValue(bd1, bd2);
} | java | public static boolean equalsValue(final BigDecimal bd1, final BigDecimal bd2) {
if (bd1 == null) {
return bd2 == null;
}
return BigDecimalUtil.isSameValue(bd1, bd2);
} | [
"public",
"static",
"boolean",
"equalsValue",
"(",
"final",
"BigDecimal",
"bd1",
",",
"final",
"BigDecimal",
"bd2",
")",
"{",
"if",
"(",
"bd1",
"==",
"null",
")",
"{",
"return",
"bd2",
"==",
"null",
";",
"}",
"return",
"BigDecimalUtil",
".",
"isSameValue",... | Return true if bd1 has the same value (according to
{@link BigDecimalUtil#isSameValue(BigDecimal, BigDecimal)}, which takes care of different scales)
as bd2.
Also returns true if bd1 is null and bd2 is null! Is safe on either bd1 or bd2 being null. | [
"Return",
"true",
"if",
"bd1",
"has",
"the",
"same",
"value",
"(",
"according",
"to",
"{"
] | train | https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/util/ObjectUtil.java#L58-L63 |
fuinorg/objects4j | src/main/java/org/fuin/objects4j/vo/HourRange.java | HourRange.isValid | public static boolean isValid(@Nullable final String hourRange) {
if (hourRange == null) {
return true;
}
final int p = hourRange.indexOf('-');
if (p != 5) {
return false;
}
final String fromStr = hourRange.substring(0, 5);
final String toStr = hourRange.substring(6);
if (!(Hour.isValid(fromStr) && Hour.isValid(toStr))) {
return false;
}
final Hour from = new Hour(fromStr);
final Hour to = new Hour(toStr);
if (from.equals(to)) {
return false;
}
if (from.equals(new Hour(24, 0))) {
return false;
}
return !to.equals(new Hour(0, 0));
} | java | public static boolean isValid(@Nullable final String hourRange) {
if (hourRange == null) {
return true;
}
final int p = hourRange.indexOf('-');
if (p != 5) {
return false;
}
final String fromStr = hourRange.substring(0, 5);
final String toStr = hourRange.substring(6);
if (!(Hour.isValid(fromStr) && Hour.isValid(toStr))) {
return false;
}
final Hour from = new Hour(fromStr);
final Hour to = new Hour(toStr);
if (from.equals(to)) {
return false;
}
if (from.equals(new Hour(24, 0))) {
return false;
}
return !to.equals(new Hour(0, 0));
} | [
"public",
"static",
"boolean",
"isValid",
"(",
"@",
"Nullable",
"final",
"String",
"hourRange",
")",
"{",
"if",
"(",
"hourRange",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"final",
"int",
"p",
"=",
"hourRange",
".",
"indexOf",
"(",
"'",
"'",
... | Verifies if the string is a valid hour range.
@param hourRange
Hour range string to test.
@return {@literal true} if the string is a valid range, else {@literal false}. | [
"Verifies",
"if",
"the",
"string",
"is",
"a",
"valid",
"hour",
"range",
"."
] | train | https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/vo/HourRange.java#L266-L288 |
JOML-CI/JOML | src/org/joml/Matrix4f.java | Matrix4f.rotateLocal | public Matrix4f rotateLocal(float ang, float x, float y, float z) {
return rotateLocal(ang, x, y, z, thisOrNew());
} | java | public Matrix4f rotateLocal(float ang, float x, float y, float z) {
return rotateLocal(ang, x, y, z, thisOrNew());
} | [
"public",
"Matrix4f",
"rotateLocal",
"(",
"float",
"ang",
",",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
")",
"{",
"return",
"rotateLocal",
"(",
"ang",
",",
"x",
",",
"y",
",",
"z",
",",
"thisOrNew",
"(",
")",
")",
";",
"}"
] | Pre-multiply a rotation to this matrix by rotating the given amount of radians
about the specified <code>(x, y, z)</code> axis.
<p>
The axis described by the three components needs to be a unit vector.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix,
then the new matrix will be <code>R * M</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the
rotation will be applied last!
<p>
In order to set the matrix to a rotation matrix without pre-multiplying the rotation
transformation, use {@link #rotation(float, float, float, float) rotation()}.
<p>
Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a>
@see #rotation(float, float, float, float)
@param ang
the angle in radians
@param x
the x component of the axis
@param y
the y component of the axis
@param z
the z component of the axis
@return a matrix holding the result | [
"Pre",
"-",
"multiply",
"a",
"rotation",
"to",
"this",
"matrix",
"by",
"rotating",
"the",
"given",
"amount",
"of",
"radians",
"about",
"the",
"specified",
"<code",
">",
"(",
"x",
"y",
"z",
")",
"<",
"/",
"code",
">",
"axis",
".",
"<p",
">",
"The",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L6254-L6256 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/RecommendationsInner.java | RecommendationsInner.listRecommendedRulesForWebAppWithServiceResponseAsync | public Observable<ServiceResponse<Page<RecommendationInner>>> listRecommendedRulesForWebAppWithServiceResponseAsync(final String resourceGroupName, final String siteName, final Boolean featured, final String filter) {
return listRecommendedRulesForWebAppSinglePageAsync(resourceGroupName, siteName, featured, filter)
.concatMap(new Func1<ServiceResponse<Page<RecommendationInner>>, Observable<ServiceResponse<Page<RecommendationInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RecommendationInner>>> call(ServiceResponse<Page<RecommendationInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listRecommendedRulesForWebAppNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<RecommendationInner>>> listRecommendedRulesForWebAppWithServiceResponseAsync(final String resourceGroupName, final String siteName, final Boolean featured, final String filter) {
return listRecommendedRulesForWebAppSinglePageAsync(resourceGroupName, siteName, featured, filter)
.concatMap(new Func1<ServiceResponse<Page<RecommendationInner>>, Observable<ServiceResponse<Page<RecommendationInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RecommendationInner>>> call(ServiceResponse<Page<RecommendationInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listRecommendedRulesForWebAppNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"RecommendationInner",
">",
">",
">",
"listRecommendedRulesForWebAppWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"siteName",
",",
"final",
"Boolean",
"fe... | Get all recommendations for an app.
Get all recommendations for an app.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Name of the app.
@param featured Specify <code>true</code> to return only the most critical recommendations. The default is <code>false</code>, which returns all recommendations.
@param filter Return only channels specified in the filter. Filter is specified by using OData syntax. Example: $filter=channels eq 'Api' or channel eq 'Notification'
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<RecommendationInner> object | [
"Get",
"all",
"recommendations",
"for",
"an",
"app",
".",
"Get",
"all",
"recommendations",
"for",
"an",
"app",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/RecommendationsInner.java#L961-L973 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/MapTransitionExtractor.java | MapTransitionExtractor.getTransitionTwoGroups | private static Transition getTransitionTwoGroups(Collection<String> neighborGroups)
{
final Iterator<String> iterator = new HashSet<>(neighborGroups).iterator();
final String groupIn = iterator.next();
final String groupOut = iterator.next();
final TransitionType type = getTransitionType(groupIn, neighborGroups);
return new Transition(type, groupIn, groupOut);
} | java | private static Transition getTransitionTwoGroups(Collection<String> neighborGroups)
{
final Iterator<String> iterator = new HashSet<>(neighborGroups).iterator();
final String groupIn = iterator.next();
final String groupOut = iterator.next();
final TransitionType type = getTransitionType(groupIn, neighborGroups);
return new Transition(type, groupIn, groupOut);
} | [
"private",
"static",
"Transition",
"getTransitionTwoGroups",
"(",
"Collection",
"<",
"String",
">",
"neighborGroups",
")",
"{",
"final",
"Iterator",
"<",
"String",
">",
"iterator",
"=",
"new",
"HashSet",
"<>",
"(",
"neighborGroups",
")",
".",
"iterator",
"(",
... | Get the tile transition between two groups.
@param neighborGroups The neighbor groups (must contain two groups).
@return The tile transition. | [
"Get",
"the",
"tile",
"transition",
"between",
"two",
"groups",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/MapTransitionExtractor.java#L56-L64 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/config/resilience/DefaultResilienceStrategyProviderConfiguration.java | DefaultResilienceStrategyProviderConfiguration.setDefaultLoaderWriterResilienceStrategy | @SuppressWarnings("rawtypes")
public DefaultResilienceStrategyProviderConfiguration setDefaultLoaderWriterResilienceStrategy(Class<? extends ResilienceStrategy> clazz, Object... arguments) {
this.defaultLoaderWriterConfiguration = new DefaultResilienceStrategyConfiguration(clazz, arguments);
return this;
} | java | @SuppressWarnings("rawtypes")
public DefaultResilienceStrategyProviderConfiguration setDefaultLoaderWriterResilienceStrategy(Class<? extends ResilienceStrategy> clazz, Object... arguments) {
this.defaultLoaderWriterConfiguration = new DefaultResilienceStrategyConfiguration(clazz, arguments);
return this;
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"DefaultResilienceStrategyProviderConfiguration",
"setDefaultLoaderWriterResilienceStrategy",
"(",
"Class",
"<",
"?",
"extends",
"ResilienceStrategy",
">",
"clazz",
",",
"Object",
"...",
"arguments",
")",
"{",
"... | Sets the default {@link ResilienceStrategy} class and associated constructor arguments to be used for caches with
a loader writer.
<p>
The provided class must have a constructor compatible with the supplied arguments followed by the cache's
{@code RecoveryStore} and {@code CacheLoaderWriter}.
@param clazz the resilience strategy class
@param arguments the constructor arguments
@return this configuration instance | [
"Sets",
"the",
"default",
"{",
"@link",
"ResilienceStrategy",
"}",
"class",
"and",
"associated",
"constructor",
"arguments",
"to",
"be",
"used",
"for",
"caches",
"with",
"a",
"loader",
"writer",
".",
"<p",
">",
"The",
"provided",
"class",
"must",
"have",
"a"... | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/config/resilience/DefaultResilienceStrategyProviderConfiguration.java#L108-L112 |
zamrokk/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/shim/Handler.java | Handler.enterTransactionState | public void enterTransactionState(Event event) {
ChaincodeMessage message = messageHelper(event);
logger.debug(String.format("[%s]Received %s, invoking transaction on chaincode(src:%s, dst:%s)",
shortID(message), message.getType().toString(), event.src, event.dst));
if (message.getType() == TRANSACTION) {
// Call the chaincode's Run function to invoke transaction
handleTransaction(message);
}
} | java | public void enterTransactionState(Event event) {
ChaincodeMessage message = messageHelper(event);
logger.debug(String.format("[%s]Received %s, invoking transaction on chaincode(src:%s, dst:%s)",
shortID(message), message.getType().toString(), event.src, event.dst));
if (message.getType() == TRANSACTION) {
// Call the chaincode's Run function to invoke transaction
handleTransaction(message);
}
} | [
"public",
"void",
"enterTransactionState",
"(",
"Event",
"event",
")",
"{",
"ChaincodeMessage",
"message",
"=",
"messageHelper",
"(",
"event",
")",
";",
"logger",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"[%s]Received %s, invoking transaction on chaincode(sr... | enterTransactionState will execute chaincode's Run if coming from a TRANSACTION event. | [
"enterTransactionState",
"will",
"execute",
"chaincode",
"s",
"Run",
"if",
"coming",
"from",
"a",
"TRANSACTION",
"event",
"."
] | train | https://github.com/zamrokk/fabric-sdk-java/blob/d4993ca602f72d412cd682e1b92e805e48b27afa/src/main/java/org/hyperledger/fabric/sdk/shim/Handler.java#L414-L422 |
networknt/light-4j | security/src/main/java/com/networknt/security/JwtIssuer.java | JwtIssuer.getPrivateKey | private static PrivateKey getPrivateKey(String filename, String password, String key) {
if(logger.isDebugEnabled()) logger.debug("filename = " + filename + " key = " + key);
PrivateKey privateKey = null;
try {
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(Config.getInstance().getInputStreamFromFile(filename),
password.toCharArray());
privateKey = (PrivateKey) keystore.getKey(key,
password.toCharArray());
} catch (Exception e) {
logger.error("Exception:", e);
}
if (privateKey == null) {
logger.error("Failed to retrieve private key from keystore");
}
return privateKey;
} | java | private static PrivateKey getPrivateKey(String filename, String password, String key) {
if(logger.isDebugEnabled()) logger.debug("filename = " + filename + " key = " + key);
PrivateKey privateKey = null;
try {
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(Config.getInstance().getInputStreamFromFile(filename),
password.toCharArray());
privateKey = (PrivateKey) keystore.getKey(key,
password.toCharArray());
} catch (Exception e) {
logger.error("Exception:", e);
}
if (privateKey == null) {
logger.error("Failed to retrieve private key from keystore");
}
return privateKey;
} | [
"private",
"static",
"PrivateKey",
"getPrivateKey",
"(",
"String",
"filename",
",",
"String",
"password",
",",
"String",
"key",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"logger",
".",
"debug",
"(",
"\"filename = \"",
"+",
"filenam... | Get private key from java key store
@param filename Key store file name
@param password Key store password
@param key key name in keystore
@return A PrivateKey object | [
"Get",
"private",
"key",
"from",
"java",
"key",
"store"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/security/src/main/java/com/networknt/security/JwtIssuer.java#L141-L161 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java | ServletUtil.getClientIP | public static String getClientIP(HttpServletRequest request, String... otherHeaderNames) {
String[] headers = { "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR" };
if (ArrayUtil.isNotEmpty(otherHeaderNames)) {
headers = ArrayUtil.addAll(headers, otherHeaderNames);
}
return getClientIPByHeader(request, headers);
} | java | public static String getClientIP(HttpServletRequest request, String... otherHeaderNames) {
String[] headers = { "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR" };
if (ArrayUtil.isNotEmpty(otherHeaderNames)) {
headers = ArrayUtil.addAll(headers, otherHeaderNames);
}
return getClientIPByHeader(request, headers);
} | [
"public",
"static",
"String",
"getClientIP",
"(",
"HttpServletRequest",
"request",
",",
"String",
"...",
"otherHeaderNames",
")",
"{",
"String",
"[",
"]",
"headers",
"=",
"{",
"\"X-Forwarded-For\"",
",",
"\"X-Real-IP\"",
",",
"\"Proxy-Client-IP\"",
",",
"\"WL-Proxy-... | 获取客户端IP
<p>
默认检测的Header:
<pre>
1、X-Forwarded-For
2、X-Real-IP
3、Proxy-Client-IP
4、WL-Proxy-Client-IP
</pre>
</p>
<p>
otherHeaderNames参数用于自定义检测的Header<br>
需要注意的是,使用此方法获取的客户IP地址必须在Http服务器(例如Nginx)中配置头信息,否则容易造成IP伪造。
</p>
@param request 请求对象{@link HttpServletRequest}
@param otherHeaderNames 其他自定义头文件,通常在Http服务器(例如Nginx)中配置
@return IP地址 | [
"获取客户端IP"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java#L200-L207 |
symphonyoss/messageml-utils | src/main/java/org/symphonyoss/symphony/entityjson/EntityJsonParser.java | EntityJsonParser.parseStructuredObject | public StructuredObject parseStructuredObject(Object instanceSource, ObjectNode instance) throws SchemaValidationException
{
try
{
return new StructuredObject(validate(STRUCTURED_OBJECT_SCHEMA_URL, instanceSource, instance));
}
catch (NoSchemaException | InvalidSchemaException e)
{
// In theory this cannot happen
throw new RuntimeException(e);
}
} | java | public StructuredObject parseStructuredObject(Object instanceSource, ObjectNode instance) throws SchemaValidationException
{
try
{
return new StructuredObject(validate(STRUCTURED_OBJECT_SCHEMA_URL, instanceSource, instance));
}
catch (NoSchemaException | InvalidSchemaException e)
{
// In theory this cannot happen
throw new RuntimeException(e);
}
} | [
"public",
"StructuredObject",
"parseStructuredObject",
"(",
"Object",
"instanceSource",
",",
"ObjectNode",
"instance",
")",
"throws",
"SchemaValidationException",
"{",
"try",
"{",
"return",
"new",
"StructuredObject",
"(",
"validate",
"(",
"STRUCTURED_OBJECT_SCHEMA_URL",
"... | Parse a single StructuredObject instance from the given URL.
Callers may prefer to catch EntityJSONException and treat all failures in the same way.
@param instanceSource An object describing the source of the instance, typically an instance
of java.net.URL or java.io.File.
@param instance A JSON ObjectNode containing the JSON representation of a single StructuredObject instance.
@return An StructuredObject instance.
@throws SchemaValidationException If the given instance does not meet the general EntityJSON schema.
@throws InvalidInstanceException If the given instance is structurally invalid. | [
"Parse",
"a",
"single",
"StructuredObject",
"instance",
"from",
"the",
"given",
"URL",
"."
] | train | https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/entityjson/EntityJsonParser.java#L241-L252 |
nextreports/nextreports-engine | src/ro/nextreports/engine/util/ReportUtil.java | ReportUtil.compareVersions | public static int compareVersions(String v1, String v2) {
String[] v1a = v1.split("\\.");
String[] v2a = v2.split("\\.");
Integer v1M = Integer.parseInt(v1a[0]);
Integer v2M = Integer.parseInt(v2a[0]);
if (v1M < v2M) {
return -1;
} else if (v1M > v2M) {
return 1;
} else {
Integer v1min = Integer.parseInt(v1a[1]);
Integer v2min = Integer.parseInt(v2a[1]);
if (v1min < v2min) {
return -1;
} else if (v1min > v2min) {
return 1;
} else {
return 0;
}
}
} | java | public static int compareVersions(String v1, String v2) {
String[] v1a = v1.split("\\.");
String[] v2a = v2.split("\\.");
Integer v1M = Integer.parseInt(v1a[0]);
Integer v2M = Integer.parseInt(v2a[0]);
if (v1M < v2M) {
return -1;
} else if (v1M > v2M) {
return 1;
} else {
Integer v1min = Integer.parseInt(v1a[1]);
Integer v2min = Integer.parseInt(v2a[1]);
if (v1min < v2min) {
return -1;
} else if (v1min > v2min) {
return 1;
} else {
return 0;
}
}
} | [
"public",
"static",
"int",
"compareVersions",
"(",
"String",
"v1",
",",
"String",
"v2",
")",
"{",
"String",
"[",
"]",
"v1a",
"=",
"v1",
".",
"split",
"(",
"\"\\\\.\"",
")",
";",
"String",
"[",
"]",
"v2a",
"=",
"v2",
".",
"split",
"(",
"\"\\\\.\"",
... | Compare two report versions strings
@param v1
first version string
@param v2
second version string
@return -1 if v1 less than v2, 0 if v1 equals v2, 1 if v1 greater than v2 | [
"Compare",
"two",
"report",
"versions",
"strings"
] | train | https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/util/ReportUtil.java#L367-L387 |
amzn/ion-java | src/com/amazon/ion/Timestamp.java | Timestamp.addMillisForPrecision | private Timestamp addMillisForPrecision(long amount, Precision precision, boolean millisecondsPrecision) {
// When millisecondsPrecision is true, the caller must do its own short-circuiting because it must
// check the fractional precision.
if (!millisecondsPrecision && amount == 0 && _precision == precision) return this;
// This strips off the local offset, expressing our fields as if they
// were UTC.
BigDecimal millis = make_localtime().getDecimalMillis();
millis = millis.add(BigDecimal.valueOf(amount));
Precision newPrecision = _precision.includes(precision) ? _precision : precision;
Timestamp ts = new Timestamp(millis, newPrecision, _offset);
// Anything with courser-than-millis precision will have been extended
// to 3 decimal places due to use of getDecimalMillis(). Compensate for
// that by setting the scale such that it is never extended unless
// milliseconds precision is being added and the fraction does not yet
// have milliseconds precision.
int newScale = millisecondsPrecision ? 3 : 0;
if (_fraction != null) {
newScale = Math.max(newScale, _fraction.scale());
}
if (ts._fraction != null) {
ts._fraction = newScale == 0 ? null : ts._fraction.setScale(newScale, RoundingMode.FLOOR);
}
if (_offset != null && _offset != 0)
{
ts.apply_offset(_offset);
}
return ts;
} | java | private Timestamp addMillisForPrecision(long amount, Precision precision, boolean millisecondsPrecision) {
// When millisecondsPrecision is true, the caller must do its own short-circuiting because it must
// check the fractional precision.
if (!millisecondsPrecision && amount == 0 && _precision == precision) return this;
// This strips off the local offset, expressing our fields as if they
// were UTC.
BigDecimal millis = make_localtime().getDecimalMillis();
millis = millis.add(BigDecimal.valueOf(amount));
Precision newPrecision = _precision.includes(precision) ? _precision : precision;
Timestamp ts = new Timestamp(millis, newPrecision, _offset);
// Anything with courser-than-millis precision will have been extended
// to 3 decimal places due to use of getDecimalMillis(). Compensate for
// that by setting the scale such that it is never extended unless
// milliseconds precision is being added and the fraction does not yet
// have milliseconds precision.
int newScale = millisecondsPrecision ? 3 : 0;
if (_fraction != null) {
newScale = Math.max(newScale, _fraction.scale());
}
if (ts._fraction != null) {
ts._fraction = newScale == 0 ? null : ts._fraction.setScale(newScale, RoundingMode.FLOOR);
}
if (_offset != null && _offset != 0)
{
ts.apply_offset(_offset);
}
return ts;
} | [
"private",
"Timestamp",
"addMillisForPrecision",
"(",
"long",
"amount",
",",
"Precision",
"precision",
",",
"boolean",
"millisecondsPrecision",
")",
"{",
"// When millisecondsPrecision is true, the caller must do its own short-circuiting because it must",
"// check the fractional preci... | Adds the given number of milliseconds, extending (if necessary) the resulting Timestamp to the given
precision.
@param amount the number of milliseconds to add.
@param precision the precision that the Timestamp will be extended to, if it does not already include that
precision.
@param millisecondsPrecision true if and only if the `amount` includes milliseconds precision. If true, the
resulting timestamp's fraction will have precision at least to the millisecond.
@return a new Timestamp. | [
"Adds",
"the",
"given",
"number",
"of",
"milliseconds",
"extending",
"(",
"if",
"necessary",
")",
"the",
"resulting",
"Timestamp",
"to",
"the",
"given",
"precision",
"."
] | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/Timestamp.java#L2269-L2298 |
threerings/nenya | core/src/main/java/com/threerings/util/DirectionUtil.java | DirectionUtil.getFineDirection | public static int getFineDirection (int ax, int ay, int bx, int by)
{
return getFineDirection(Math.atan2(by-ay, bx-ax));
} | java | public static int getFineDirection (int ax, int ay, int bx, int by)
{
return getFineDirection(Math.atan2(by-ay, bx-ax));
} | [
"public",
"static",
"int",
"getFineDirection",
"(",
"int",
"ax",
",",
"int",
"ay",
",",
"int",
"bx",
",",
"int",
"by",
")",
"{",
"return",
"getFineDirection",
"(",
"Math",
".",
"atan2",
"(",
"by",
"-",
"ay",
",",
"bx",
"-",
"ax",
")",
")",
";",
"... | Returns which of the sixteen compass directions that point <code>b</code> lies in from
point <code>a</code> as one of the {@link DirectionCodes} direction constants.
<em>Note:</em> that the coordinates supplied are assumed to be logical (screen) rather than
cartesian coordinates and <code>NORTH</code> is considered to point toward the top of the
screen. | [
"Returns",
"which",
"of",
"the",
"sixteen",
"compass",
"directions",
"that",
"point",
"<code",
">",
"b<",
"/",
"code",
">",
"lies",
"in",
"from",
"point",
"<code",
">",
"a<",
"/",
"code",
">",
"as",
"one",
"of",
"the",
"{"
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/util/DirectionUtil.java#L242-L245 |
rythmengine/rythmengine | src/main/java/org/rythmengine/template/TemplateBase.java | TemplateBase.__getRenderPropertyAs | protected final <T> T __getRenderPropertyAs(String name, T def) {
Object o = __getRenderProperty(name, def);
return null == o ? def : (T) o;
} | java | protected final <T> T __getRenderPropertyAs(String name, T def) {
Object o = __getRenderProperty(name, def);
return null == o ? def : (T) o;
} | [
"protected",
"final",
"<",
"T",
">",
"T",
"__getRenderPropertyAs",
"(",
"String",
"name",
",",
"T",
"def",
")",
"{",
"Object",
"o",
"=",
"__getRenderProperty",
"(",
"name",
",",
"def",
")",
";",
"return",
"null",
"==",
"o",
"?",
"def",
":",
"(",
"T",... | Get render property by name and do type cast to the specified default value.
If the render property cannot be found by name, then return the default value
@param name
@param def
@param <T>
@return a render property
@see #__getRenderProperty(String) | [
"Get",
"render",
"property",
"by",
"name",
"and",
"do",
"type",
"cast",
"to",
"the",
"specified",
"default",
"value",
".",
"If",
"the",
"render",
"property",
"cannot",
"be",
"found",
"by",
"name",
"then",
"return",
"the",
"default",
"value"
] | train | https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/template/TemplateBase.java#L1108-L1111 |
forge/furnace | container/src/main/java/org/jboss/forge/furnace/impl/util/Files.java | Files.doCopyFile | private static void doCopyFile(File srcFile, File destFile) throws IOException
{
if (destFile.exists() && destFile.isDirectory())
{
throw new IOException("Destination '" + destFile + "' exists but is a directory");
}
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel input = null;
FileChannel output = null;
try
{
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
input = fis.getChannel();
output = fos.getChannel();
long size = input.size();
long pos = 0;
long count = 0;
while (pos < size)
{
count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
pos += output.transferFrom(input, pos, count);
}
}
finally
{
Streams.closeQuietly(output);
Streams.closeQuietly(fos);
Streams.closeQuietly(input);
Streams.closeQuietly(fis);
}
if (srcFile.length() != destFile.length())
{
throw new IOException("Failed to copy full contents from '" +
srcFile + "' to '" + destFile + "'");
}
} | java | private static void doCopyFile(File srcFile, File destFile) throws IOException
{
if (destFile.exists() && destFile.isDirectory())
{
throw new IOException("Destination '" + destFile + "' exists but is a directory");
}
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel input = null;
FileChannel output = null;
try
{
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
input = fis.getChannel();
output = fos.getChannel();
long size = input.size();
long pos = 0;
long count = 0;
while (pos < size)
{
count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
pos += output.transferFrom(input, pos, count);
}
}
finally
{
Streams.closeQuietly(output);
Streams.closeQuietly(fos);
Streams.closeQuietly(input);
Streams.closeQuietly(fis);
}
if (srcFile.length() != destFile.length())
{
throw new IOException("Failed to copy full contents from '" +
srcFile + "' to '" + destFile + "'");
}
} | [
"private",
"static",
"void",
"doCopyFile",
"(",
"File",
"srcFile",
",",
"File",
"destFile",
")",
"throws",
"IOException",
"{",
"if",
"(",
"destFile",
".",
"exists",
"(",
")",
"&&",
"destFile",
".",
"isDirectory",
"(",
")",
")",
"{",
"throw",
"new",
"IOEx... | Internal copy file method.
@param srcFile the validated source file, must not be <code>null</code>
@param destFile the validated destination file, must not be <code>null</code>
@throws IOException if an error occurs | [
"Internal",
"copy",
"file",
"method",
"."
] | train | https://github.com/forge/furnace/blob/bbe6deaa3c0d85ba43daa3e2f7d486f2dad21e0a/container/src/main/java/org/jboss/forge/furnace/impl/util/Files.java#L237-L276 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java | HawkbitCommonUtil.getArtifactUploadPopupWidth | public static float getArtifactUploadPopupWidth(final float newBrowserWidth, final int minPopupWidth) {
final float extraWidth = findRequiredSwModuleExtraWidth(newBrowserWidth);
if (extraWidth + minPopupWidth > SPUIDefinitions.MAX_UPLOAD_CONFIRMATION_POPUP_WIDTH) {
return SPUIDefinitions.MAX_UPLOAD_CONFIRMATION_POPUP_WIDTH;
}
return extraWidth + minPopupWidth;
} | java | public static float getArtifactUploadPopupWidth(final float newBrowserWidth, final int minPopupWidth) {
final float extraWidth = findRequiredSwModuleExtraWidth(newBrowserWidth);
if (extraWidth + minPopupWidth > SPUIDefinitions.MAX_UPLOAD_CONFIRMATION_POPUP_WIDTH) {
return SPUIDefinitions.MAX_UPLOAD_CONFIRMATION_POPUP_WIDTH;
}
return extraWidth + minPopupWidth;
} | [
"public",
"static",
"float",
"getArtifactUploadPopupWidth",
"(",
"final",
"float",
"newBrowserWidth",
",",
"final",
"int",
"minPopupWidth",
")",
"{",
"final",
"float",
"extraWidth",
"=",
"findRequiredSwModuleExtraWidth",
"(",
"newBrowserWidth",
")",
";",
"if",
"(",
... | Get artifact upload pop up width.
@param newBrowserWidth
new browser width
@param minPopupWidth
minimum popup width
@return float new pop up width | [
"Get",
"artifact",
"upload",
"pop",
"up",
"width",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java#L202-L208 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureByFactorization.java | ProjectiveStructureByFactorization.getCameraMatrix | public void getCameraMatrix(int view , DMatrixRMaj cameraMatrix ) {
cameraMatrix.reshape(3,4);
CommonOps_DDRM.extract(P,view*3,0,cameraMatrix);
for (int col = 0; col < 4; col++) {
cameraMatrix.data[cameraMatrix.getIndex(0,col)] *= pixelScale;
cameraMatrix.data[cameraMatrix.getIndex(1,col)] *= pixelScale;
}
} | java | public void getCameraMatrix(int view , DMatrixRMaj cameraMatrix ) {
cameraMatrix.reshape(3,4);
CommonOps_DDRM.extract(P,view*3,0,cameraMatrix);
for (int col = 0; col < 4; col++) {
cameraMatrix.data[cameraMatrix.getIndex(0,col)] *= pixelScale;
cameraMatrix.data[cameraMatrix.getIndex(1,col)] *= pixelScale;
}
} | [
"public",
"void",
"getCameraMatrix",
"(",
"int",
"view",
",",
"DMatrixRMaj",
"cameraMatrix",
")",
"{",
"cameraMatrix",
".",
"reshape",
"(",
"3",
",",
"4",
")",
";",
"CommonOps_DDRM",
".",
"extract",
"(",
"P",
",",
"view",
"*",
"3",
",",
"0",
",",
"came... | Used to get found camera matrix for a view
@param view Which view
@param cameraMatrix storage for 3x4 projective camera matrix | [
"Used",
"to",
"get",
"found",
"camera",
"matrix",
"for",
"a",
"view"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureByFactorization.java#L219-L227 |
MTDdk/jawn | jawn-core-new/src/main/java/net/javapla/jawn/core/util/ConvertUtil.java | ConvertUtil.toInteger | public static Integer toInteger(Object value, Integer defaultValue) {
try {
return toInteger(value);
} catch (Exception e) {
return defaultValue;
}
} | java | public static Integer toInteger(Object value, Integer defaultValue) {
try {
return toInteger(value);
} catch (Exception e) {
return defaultValue;
}
} | [
"public",
"static",
"Integer",
"toInteger",
"(",
"Object",
"value",
",",
"Integer",
"defaultValue",
")",
"{",
"try",
"{",
"return",
"toInteger",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"return",
"defaultValue",
";",
"}",
"}... | Same as {@linkplain ConvertUtil#toInteger(Object)} but does not throw an exception
if the conversion could not be done.
@param value
@param defaultValue
@return | [
"Same",
"as",
"{",
"@linkplain",
"ConvertUtil#toInteger",
"(",
"Object",
")",
"}",
"but",
"does",
"not",
"throw",
"an",
"exception",
"if",
"the",
"conversion",
"could",
"not",
"be",
"done",
"."
] | train | https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-core-new/src/main/java/net/javapla/jawn/core/util/ConvertUtil.java#L53-L59 |
amzn/ion-java | src/com/amazon/ion/util/IonTextUtils.java | IonTextUtils.printSymbolCodePoint | public static void printSymbolCodePoint(Appendable out, int codePoint)
throws IOException
{
printCodePoint(out, codePoint, EscapeMode.ION_SYMBOL);
} | java | public static void printSymbolCodePoint(Appendable out, int codePoint)
throws IOException
{
printCodePoint(out, codePoint, EscapeMode.ION_SYMBOL);
} | [
"public",
"static",
"void",
"printSymbolCodePoint",
"(",
"Appendable",
"out",
",",
"int",
"codePoint",
")",
"throws",
"IOException",
"{",
"printCodePoint",
"(",
"out",
",",
"codePoint",
",",
"EscapeMode",
".",
"ION_SYMBOL",
")",
";",
"}"
] | Prints a single Unicode code point for use in an ASCII-safe Ion symbol.
@param out the stream to receive the data.
@param codePoint a Unicode code point. | [
"Prints",
"a",
"single",
"Unicode",
"code",
"point",
"for",
"use",
"in",
"an",
"ASCII",
"-",
"safe",
"Ion",
"symbol",
"."
] | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/util/IonTextUtils.java#L212-L216 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreException.java | DatastoreException.throwInvalidRequest | static DatastoreException throwInvalidRequest(String massage, Object... params) {
throw new DatastoreException(
UNKNOWN_CODE, String.format(massage, params), "FAILED_PRECONDITION");
} | java | static DatastoreException throwInvalidRequest(String massage, Object... params) {
throw new DatastoreException(
UNKNOWN_CODE, String.format(massage, params), "FAILED_PRECONDITION");
} | [
"static",
"DatastoreException",
"throwInvalidRequest",
"(",
"String",
"massage",
",",
"Object",
"...",
"params",
")",
"{",
"throw",
"new",
"DatastoreException",
"(",
"UNKNOWN_CODE",
",",
"String",
".",
"format",
"(",
"massage",
",",
"params",
")",
",",
"\"FAILED... | Throw a DatastoreException with {@code FAILED_PRECONDITION} reason and the {@code message} in a
nested exception.
@throws DatastoreException every time | [
"Throw",
"a",
"DatastoreException",
"with",
"{",
"@code",
"FAILED_PRECONDITION",
"}",
"reason",
"and",
"the",
"{",
"@code",
"message",
"}",
"in",
"a",
"nested",
"exception",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreException.java#L76-L79 |
mokies/ratelimitj | ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java | ConcurrentLimitRule.of | public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) {
requireNonNull(timeOutUnit, "time out unit can not be null");
return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut));
} | java | public static ConcurrentLimitRule of(int concurrentLimit, TimeUnit timeOutUnit, long timeOut) {
requireNonNull(timeOutUnit, "time out unit can not be null");
return new ConcurrentLimitRule(concurrentLimit, timeOutUnit.toMillis(timeOut));
} | [
"public",
"static",
"ConcurrentLimitRule",
"of",
"(",
"int",
"concurrentLimit",
",",
"TimeUnit",
"timeOutUnit",
",",
"long",
"timeOut",
")",
"{",
"requireNonNull",
"(",
"timeOutUnit",
",",
"\"time out unit can not be null\"",
")",
";",
"return",
"new",
"ConcurrentLimi... | Initialise a concurrent rate limit.
@param concurrentLimit The concurrent limit.
@param timeOutUnit The time unit.
@param timeOut A timeOut for the checkout baton.
@return A concurrent limit rule. | [
"Initialise",
"a",
"concurrent",
"rate",
"limit",
"."
] | train | https://github.com/mokies/ratelimitj/blob/eb15ec42055c46b2b3f6f84131d86f570e489c32/ratelimitj-core/src/main/java/es/moki/ratelimitj/core/limiter/concurrent/ConcurrentLimitRule.java#L35-L38 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/EvaluationUtils.java | EvaluationUtils.falsePositiveRate | public static double falsePositiveRate(long fpCount, long tnCount, double edgeCase) {
//Edge case
if (fpCount == 0 && tnCount == 0) {
return edgeCase;
}
return fpCount / (double) (fpCount + tnCount);
} | java | public static double falsePositiveRate(long fpCount, long tnCount, double edgeCase) {
//Edge case
if (fpCount == 0 && tnCount == 0) {
return edgeCase;
}
return fpCount / (double) (fpCount + tnCount);
} | [
"public",
"static",
"double",
"falsePositiveRate",
"(",
"long",
"fpCount",
",",
"long",
"tnCount",
",",
"double",
"edgeCase",
")",
"{",
"//Edge case",
"if",
"(",
"fpCount",
"==",
"0",
"&&",
"tnCount",
"==",
"0",
")",
"{",
"return",
"edgeCase",
";",
"}",
... | Calculate the false positive rate from the false positive count and true negative count
@param fpCount False positive count
@param tnCount True negative count
@param edgeCase Edge case values are used to avoid 0/0
@return False positive rate | [
"Calculate",
"the",
"false",
"positive",
"rate",
"from",
"the",
"false",
"positive",
"count",
"and",
"true",
"negative",
"count"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/EvaluationUtils.java#L75-L81 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getPvPRankInfo | public void getPvPRankInfo(int[] ids, Callback<List<PvPRank>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getPvPRankInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | java | public void getPvPRankInfo(int[] ids, Callback<List<PvPRank>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getPvPRankInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | [
"public",
"void",
"getPvPRankInfo",
"(",
"int",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"PvPRank",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ids",... | For more info on pvp ranks API go <a href="https://wiki.guildwars2.com/wiki/API:2/pvp/ranks">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of PvP rank id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see PvPRank PvP rank info | [
"For",
"more",
"info",
"on",
"pvp",
"ranks",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"pvp",
"/",
"ranks",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L2112-L2115 |
alexcojocaru/elasticsearch-maven-plugin | src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/util/FilesystemUtil.java | FilesystemUtil.copyRecursively | public static void copyRecursively(Path source, Path destination) throws IOException {
if (Files.isDirectory(source))
{
Files.createDirectories(destination);
final Set<Path> sources = listFiles(source);
for (Path srcFile : sources)
{
Path destFile = destination.resolve(srcFile.getFileName());
copyRecursively(srcFile, destFile);
}
}
else
{
Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
}
} | java | public static void copyRecursively(Path source, Path destination) throws IOException {
if (Files.isDirectory(source))
{
Files.createDirectories(destination);
final Set<Path> sources = listFiles(source);
for (Path srcFile : sources)
{
Path destFile = destination.resolve(srcFile.getFileName());
copyRecursively(srcFile, destFile);
}
}
else
{
Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
}
} | [
"public",
"static",
"void",
"copyRecursively",
"(",
"Path",
"source",
",",
"Path",
"destination",
")",
"throws",
"IOException",
"{",
"if",
"(",
"Files",
".",
"isDirectory",
"(",
"source",
")",
")",
"{",
"Files",
".",
"createDirectories",
"(",
"destination",
... | Copy a directory recursively, preserving attributes, in particular permissions. | [
"Copy",
"a",
"directory",
"recursively",
"preserving",
"attributes",
"in",
"particular",
"permissions",
"."
] | train | https://github.com/alexcojocaru/elasticsearch-maven-plugin/blob/c283053cf99dc6b6d411b58629364b6aae62b7f8/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/util/FilesystemUtil.java#L53-L69 |
jmxtrans/embedded-jmxtrans | src/main/java/org/jmxtrans/embedded/util/pool/SocketWriterPoolFactory.java | SocketWriterPoolFactory.validateObject | @Override
public boolean validateObject(HostAndPort hostAndPort, PooledObject<SocketWriter> socketWriterRef) {
Socket socket = socketWriterRef.getObject().getSocket();
return socket.isConnected()
&& socket.isBound()
&& !socket.isClosed()
&& !socket.isInputShutdown()
&& !socket.isOutputShutdown();
} | java | @Override
public boolean validateObject(HostAndPort hostAndPort, PooledObject<SocketWriter> socketWriterRef) {
Socket socket = socketWriterRef.getObject().getSocket();
return socket.isConnected()
&& socket.isBound()
&& !socket.isClosed()
&& !socket.isInputShutdown()
&& !socket.isOutputShutdown();
} | [
"@",
"Override",
"public",
"boolean",
"validateObject",
"(",
"HostAndPort",
"hostAndPort",
",",
"PooledObject",
"<",
"SocketWriter",
">",
"socketWriterRef",
")",
"{",
"Socket",
"socket",
"=",
"socketWriterRef",
".",
"getObject",
"(",
")",
".",
"getSocket",
"(",
... | Defensive approach: we test all the "<code>Socket.isXXX()</code>" flags. | [
"Defensive",
"approach",
":",
"we",
"test",
"all",
"the",
"<code",
">",
"Socket",
".",
"isXXX",
"()",
"<",
"/",
"code",
">",
"flags",
"."
] | train | https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/util/pool/SocketWriterPoolFactory.java#L98-L106 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderService.java | SpiderService.addBatch | public BatchResult addBatch(ApplicationDefinition appDef, String tableName, DBObjectBatch batch) {
checkServiceState();
TableDefinition tableDef = appDef.getTableDef(tableName);
Utils.require(tableDef != null || appDef.allowsAutoTables(),
"Unknown table for application '%s': %s", appDef.getAppName(), tableName);
if (tableDef == null && appDef.allowsAutoTables()) {
tableDef = addAutoTable(appDef, tableName);
assert tableDef != null;
}
BatchObjectUpdater batchUpdater = new BatchObjectUpdater(tableDef);
return batchUpdater.addBatch(batch);
} | java | public BatchResult addBatch(ApplicationDefinition appDef, String tableName, DBObjectBatch batch) {
checkServiceState();
TableDefinition tableDef = appDef.getTableDef(tableName);
Utils.require(tableDef != null || appDef.allowsAutoTables(),
"Unknown table for application '%s': %s", appDef.getAppName(), tableName);
if (tableDef == null && appDef.allowsAutoTables()) {
tableDef = addAutoTable(appDef, tableName);
assert tableDef != null;
}
BatchObjectUpdater batchUpdater = new BatchObjectUpdater(tableDef);
return batchUpdater.addBatch(batch);
} | [
"public",
"BatchResult",
"addBatch",
"(",
"ApplicationDefinition",
"appDef",
",",
"String",
"tableName",
",",
"DBObjectBatch",
"batch",
")",
"{",
"checkServiceState",
"(",
")",
";",
"TableDefinition",
"tableDef",
"=",
"appDef",
".",
"getTableDef",
"(",
"tableName",
... | Add or update a batch of updates for the given application and table. If the
application's autotables option is true and the given table doesn't exist, it is
created automatically. When an object in the batch is assigned an ID that is
already used, the corresponding object is updated. This preserves idempotent
semantics: performing the same add twice is safe as long as IDs are explicitly
assigned. Objects that aren't given explicit IDs are assigned default IDs.
@param appDef {@link ApplicationDefinition} of application to update.
@param tableName Name of table to add objects to.
@param batch {@link DBObjectBatch} containing new or updated objects.
@return {@link BatchResult} indicating results of update. | [
"Add",
"or",
"update",
"a",
"batch",
"of",
"updates",
"for",
"the",
"given",
"application",
"and",
"table",
".",
"If",
"the",
"application",
"s",
"autotables",
"option",
"is",
"true",
"and",
"the",
"given",
"table",
"doesn",
"t",
"exist",
"it",
"is",
"cr... | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderService.java#L230-L243 |
opencb/cellbase | cellbase-app/src/main/java/org/opencb/cellbase/app/transform/DisgenetParser.java | DisgenetParser.fillDisgenetMap | private long fillDisgenetMap(Map<String, Disgenet> disGeNetMap, BufferedReader reader) throws IOException {
long linesProcessed = 0;
String line;
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\t");
String geneId = fields[0];
String geneSymbol = fields[1];
String geneName = fields[2];
String diseaseId = fields[3];
String diseaseName = fields[4];
Float score = Float.parseFloat(fields[5]);
Integer numberOfPubmeds = Integer.parseInt(fields[6]);
String associationType = fields[7];
Set<String> sources = new HashSet<>(Arrays.asList(fields[8].split(", ")));
if (geneId != null && !geneId.equals("")) {
if (disGeNetMap.get(geneId) != null) {
updateElementDisgenetMap(disGeNetMap, geneId, diseaseId, diseaseName, score, numberOfPubmeds, associationType, sources);
} else {
insertNewElementToDisgenetMap(disGeNetMap, geneId, geneSymbol, geneName, diseaseId, diseaseName,
score, numberOfPubmeds, associationType, sources);
}
}
linesProcessed++;
if ((linesProcessed % 10000) == 0) {
logger.info("{} lines processed", linesProcessed);
}
}
return linesProcessed;
} | java | private long fillDisgenetMap(Map<String, Disgenet> disGeNetMap, BufferedReader reader) throws IOException {
long linesProcessed = 0;
String line;
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\t");
String geneId = fields[0];
String geneSymbol = fields[1];
String geneName = fields[2];
String diseaseId = fields[3];
String diseaseName = fields[4];
Float score = Float.parseFloat(fields[5]);
Integer numberOfPubmeds = Integer.parseInt(fields[6]);
String associationType = fields[7];
Set<String> sources = new HashSet<>(Arrays.asList(fields[8].split(", ")));
if (geneId != null && !geneId.equals("")) {
if (disGeNetMap.get(geneId) != null) {
updateElementDisgenetMap(disGeNetMap, geneId, diseaseId, diseaseName, score, numberOfPubmeds, associationType, sources);
} else {
insertNewElementToDisgenetMap(disGeNetMap, geneId, geneSymbol, geneName, diseaseId, diseaseName,
score, numberOfPubmeds, associationType, sources);
}
}
linesProcessed++;
if ((linesProcessed % 10000) == 0) {
logger.info("{} lines processed", linesProcessed);
}
}
return linesProcessed;
} | [
"private",
"long",
"fillDisgenetMap",
"(",
"Map",
"<",
"String",
",",
"Disgenet",
">",
"disGeNetMap",
",",
"BufferedReader",
"reader",
")",
"throws",
"IOException",
"{",
"long",
"linesProcessed",
"=",
"0",
";",
"String",
"line",
";",
"while",
"(",
"(",
"line... | Loads a map {geneId -> Disgenet info} from the Disgenet file.
@param disGeNetMap: Map where keys are Disgenet gene ids and values are Disgenet objects. Will be filled within
this method.
@param reader: BufferedReader pointing to the first line containing actual Disgenet info (header assumed to be
skipped).
@throws IOException in case any problem occurs reading the file. | [
"Loads",
"a",
"map",
"{",
"geneId",
"-",
">",
"Disgenet",
"info",
"}",
"from",
"the",
"Disgenet",
"file",
"."
] | train | https://github.com/opencb/cellbase/blob/70cc3d6ecff747725ade9d051438fc6bf98cae44/cellbase-app/src/main/java/org/opencb/cellbase/app/transform/DisgenetParser.java#L93-L126 |
blinkfox/zealot | src/main/java/com/blinkfox/zealot/core/Zealot.java | Zealot.getSqlInfo | public static SqlInfo getSqlInfo(String nameSpace, String zealotId, Object paramObj) {
if (StringHelper.isBlank(nameSpace) || StringHelper.isBlank(zealotId)) {
throw new ValidFailException("请输入有效的nameSpace或者zealotId的值!");
}
// 获取nameSpace文档中的指定sql的zealotId的节点对应的Node节点,如果是debug模式,则实时获取;否则从缓存中获取.
Node zealotNode = NormalConfig.getInstance().isDebug() ? XmlNodeHelper.getNodeBySpaceAndId(nameSpace, zealotId)
: AbstractZealotConfig.getZealots().get(StringHelper.concat(nameSpace, ZealotConst.SP_AT, zealotId));
if (zealotNode == null) {
throw new NodeNotFoundException("未找到nameSpace为:" + nameSpace + ",zealotId为:" + zealotId + "的节点!");
}
// 生成新的SqlInfo信息并打印出来.
SqlInfo sqlInfo = buildNewSqlInfo(nameSpace, zealotNode, paramObj);
SqlInfoPrinter.newInstance().printZealotSqlInfo(sqlInfo, true, nameSpace, zealotId);
return sqlInfo;
} | java | public static SqlInfo getSqlInfo(String nameSpace, String zealotId, Object paramObj) {
if (StringHelper.isBlank(nameSpace) || StringHelper.isBlank(zealotId)) {
throw new ValidFailException("请输入有效的nameSpace或者zealotId的值!");
}
// 获取nameSpace文档中的指定sql的zealotId的节点对应的Node节点,如果是debug模式,则实时获取;否则从缓存中获取.
Node zealotNode = NormalConfig.getInstance().isDebug() ? XmlNodeHelper.getNodeBySpaceAndId(nameSpace, zealotId)
: AbstractZealotConfig.getZealots().get(StringHelper.concat(nameSpace, ZealotConst.SP_AT, zealotId));
if (zealotNode == null) {
throw new NodeNotFoundException("未找到nameSpace为:" + nameSpace + ",zealotId为:" + zealotId + "的节点!");
}
// 生成新的SqlInfo信息并打印出来.
SqlInfo sqlInfo = buildNewSqlInfo(nameSpace, zealotNode, paramObj);
SqlInfoPrinter.newInstance().printZealotSqlInfo(sqlInfo, true, nameSpace, zealotId);
return sqlInfo;
} | [
"public",
"static",
"SqlInfo",
"getSqlInfo",
"(",
"String",
"nameSpace",
",",
"String",
"zealotId",
",",
"Object",
"paramObj",
")",
"{",
"if",
"(",
"StringHelper",
".",
"isBlank",
"(",
"nameSpace",
")",
"||",
"StringHelper",
".",
"isBlank",
"(",
"zealotId",
... | 通过传入zealot xml文件对应的命名空间、zealot节点的ID以及参数对象(一般是JavaBean或者Map)来生成和获取sqlInfo信息(有参的SQL).
@param nameSpace xml命名空间
@param zealotId xml中的zealotId
@param paramObj 参数对象(一般是JavaBean对象或者Map)
@return 返回SqlInfo对象 | [
"通过传入zealot",
"xml文件对应的命名空间、zealot节点的ID以及参数对象",
"(",
"一般是JavaBean或者Map",
")",
"来生成和获取sqlInfo信息",
"(",
"有参的SQL",
")",
"."
] | train | https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/Zealot.java#L80-L96 |
xerial/snappy-java | src/main/java/org/xerial/snappy/Snappy.java | Snappy.uncompressedLength | public static int uncompressedLength(ByteBuffer compressed)
throws IOException
{
if (!compressed.isDirect()) {
throw new SnappyError(SnappyErrorCode.NOT_A_DIRECT_BUFFER, "input is not a direct buffer");
}
return impl.uncompressedLength(compressed, compressed.position(), compressed.remaining());
} | java | public static int uncompressedLength(ByteBuffer compressed)
throws IOException
{
if (!compressed.isDirect()) {
throw new SnappyError(SnappyErrorCode.NOT_A_DIRECT_BUFFER, "input is not a direct buffer");
}
return impl.uncompressedLength(compressed, compressed.position(), compressed.remaining());
} | [
"public",
"static",
"int",
"uncompressedLength",
"(",
"ByteBuffer",
"compressed",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"compressed",
".",
"isDirect",
"(",
")",
")",
"{",
"throw",
"new",
"SnappyError",
"(",
"SnappyErrorCode",
".",
"NOT_A_DIRECT_BUFF... | Get the uncompressed byte size of the given compressed input. This
operation takes O(1) time.
@param compressed input data [pos() ... limit())
@return uncompressed byte length of the given input
@throws IOException when failed to uncompress the given input. The error code is
{@link SnappyErrorCode#PARSING_ERROR}
@throws SnappyError when the input is not a direct buffer | [
"Get",
"the",
"uncompressed",
"byte",
"size",
"of",
"the",
"given",
"compressed",
"input",
".",
"This",
"operation",
"takes",
"O",
"(",
"1",
")",
"time",
"."
] | train | https://github.com/xerial/snappy-java/blob/9df6ed7bbce88186c82f2e7cdcb7b974421b3340/src/main/java/org/xerial/snappy/Snappy.java#L647-L655 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/DoubleStream.java | DoubleStream.iterate | @NotNull
public static DoubleStream iterate(
final double seed,
@NotNull final DoublePredicate predicate,
@NotNull final DoubleUnaryOperator op) {
Objects.requireNonNull(predicate);
return iterate(seed, op).takeWhile(predicate);
} | java | @NotNull
public static DoubleStream iterate(
final double seed,
@NotNull final DoublePredicate predicate,
@NotNull final DoubleUnaryOperator op) {
Objects.requireNonNull(predicate);
return iterate(seed, op).takeWhile(predicate);
} | [
"@",
"NotNull",
"public",
"static",
"DoubleStream",
"iterate",
"(",
"final",
"double",
"seed",
",",
"@",
"NotNull",
"final",
"DoublePredicate",
"predicate",
",",
"@",
"NotNull",
"final",
"DoubleUnaryOperator",
"op",
")",
"{",
"Objects",
".",
"requireNonNull",
"(... | Creates an {@code DoubleStream} by iterative application {@code DoubleUnaryOperator} function
to an initial element {@code seed}, conditioned on satisfying the supplied predicate.
<p>Example:
<pre>
seed: 0.0
predicate: (a) -> a < 0.2
f: (a) -> a + 0.05
result: [0.0, 0.05, 0.1, 0.15]
</pre>
@param seed the initial value
@param predicate a predicate to determine when the stream must terminate
@param op operator to produce new element by previous one
@return the new stream
@throws NullPointerException if {@code op} is null
@since 1.1.5 | [
"Creates",
"an",
"{",
"@code",
"DoubleStream",
"}",
"by",
"iterative",
"application",
"{",
"@code",
"DoubleUnaryOperator",
"}",
"function",
"to",
"an",
"initial",
"element",
"{",
"@code",
"seed",
"}",
"conditioned",
"on",
"satisfying",
"the",
"supplied",
"predic... | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/DoubleStream.java#L151-L158 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ResourceBundle.java | ResourceBundle.getBundle | public static ResourceBundle getBundle(String bundleName) throws MissingResourceException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
if (classLoader == null) {
classLoader = getLoader();
}
return getBundle(bundleName, Locale.getDefault(), classLoader);
} | java | public static ResourceBundle getBundle(String bundleName) throws MissingResourceException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
if (classLoader == null) {
classLoader = getLoader();
}
return getBundle(bundleName, Locale.getDefault(), classLoader);
} | [
"public",
"static",
"ResourceBundle",
"getBundle",
"(",
"String",
"bundleName",
")",
"throws",
"MissingResourceException",
"{",
"ClassLoader",
"classLoader",
"=",
"ClassLoader",
".",
"getSystemClassLoader",
"(",
")",
";",
"if",
"(",
"classLoader",
"==",
"null",
")",... | Finds the named resource bundle for the default {@code Locale} and the caller's
{@code ClassLoader}.
@param bundleName
the name of the {@code ResourceBundle}.
@return the requested {@code ResourceBundle}.
@throws MissingResourceException
if the {@code ResourceBundle} cannot be found. | [
"Finds",
"the",
"named",
"resource",
"bundle",
"for",
"the",
"default",
"{",
"@code",
"Locale",
"}",
"and",
"the",
"caller",
"s",
"{",
"@code",
"ClassLoader",
"}",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ResourceBundle.java#L134-L140 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/Period.java | Period.plusDays | public Period plusDays(long daysToAdd) {
if (daysToAdd == 0) {
return this;
}
return create(years, months, Math.toIntExact(Math.addExact(days, daysToAdd)));
} | java | public Period plusDays(long daysToAdd) {
if (daysToAdd == 0) {
return this;
}
return create(years, months, Math.toIntExact(Math.addExact(days, daysToAdd)));
} | [
"public",
"Period",
"plusDays",
"(",
"long",
"daysToAdd",
")",
"{",
"if",
"(",
"daysToAdd",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"return",
"create",
"(",
"years",
",",
"months",
",",
"Math",
".",
"toIntExact",
"(",
"Math",
".",
"addExact",
... | Returns a copy of this period with the specified days added.
<p>
This adds the amount to the days unit in a copy of this period.
The years and months units are unaffected.
For example, "1 year, 6 months and 3 days" plus 2 days returns "1 year, 6 months and 5 days".
<p>
This instance is immutable and unaffected by this method call.
@param daysToAdd the days to add, positive or negative
@return a {@code Period} based on this period with the specified days added, not null
@throws ArithmeticException if numeric overflow occurs | [
"Returns",
"a",
"copy",
"of",
"this",
"period",
"with",
"the",
"specified",
"days",
"added",
".",
"<p",
">",
"This",
"adds",
"the",
"amount",
"to",
"the",
"days",
"unit",
"in",
"a",
"copy",
"of",
"this",
"period",
".",
"The",
"years",
"and",
"months",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/Period.java#L680-L685 |
killbill/killbill | util/src/main/java/org/killbill/billing/util/entity/dao/EntitySqlDaoWrapperFactory.java | EntitySqlDaoWrapperFactory.become | public <NewSqlDao extends EntitySqlDao<NewEntityModelDao, NewEntity>,
NewEntityModelDao extends EntityModelDao<NewEntity>,
NewEntity extends Entity> NewSqlDao become(final Class<NewSqlDao> newSqlDaoClass) {
final NewSqlDao newSqlDao = SqlObjectBuilder.attach(handle, newSqlDaoClass);
return create(newSqlDaoClass, newSqlDao);
} | java | public <NewSqlDao extends EntitySqlDao<NewEntityModelDao, NewEntity>,
NewEntityModelDao extends EntityModelDao<NewEntity>,
NewEntity extends Entity> NewSqlDao become(final Class<NewSqlDao> newSqlDaoClass) {
final NewSqlDao newSqlDao = SqlObjectBuilder.attach(handle, newSqlDaoClass);
return create(newSqlDaoClass, newSqlDao);
} | [
"public",
"<",
"NewSqlDao",
"extends",
"EntitySqlDao",
"<",
"NewEntityModelDao",
",",
"NewEntity",
">",
",",
"NewEntityModelDao",
"extends",
"EntityModelDao",
"<",
"NewEntity",
">",
",",
"NewEntity",
"extends",
"Entity",
">",
"NewSqlDao",
"become",
"(",
"final",
"... | Get an instance of a specified EntitySqlDao class, sharing the same database session as the
initial sql dao class with which this wrapper factory was created.
@param newSqlDaoClass the class to instantiate
@param <NewSqlDao> EntitySqlDao type to create
@return instance of NewSqlDao | [
"Get",
"an",
"instance",
"of",
"a",
"specified",
"EntitySqlDao",
"class",
"sharing",
"the",
"same",
"database",
"session",
"as",
"the",
"initial",
"sql",
"dao",
"class",
"with",
"which",
"this",
"wrapper",
"factory",
"was",
"created",
"."
] | train | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/entity/dao/EntitySqlDaoWrapperFactory.java#L59-L64 |
ops4j/org.ops4j.pax.web | pax-web-runtime/src/main/java/org/ops4j/pax/web/service/internal/WhiteboardDtoService.java | WhiteboardDtoService.mapServletContext | private ServletContextDTO mapServletContext(Map.Entry<ServiceReference<ServletContext>, ServletContext> mapEntry) {
final ServiceReference<ServletContext> ref = mapEntry.getKey();
final ServletContext servletContext = mapEntry.getValue();
ServletContextDTO dto = new ServletContextDTO();
dto.serviceId = (long) ref.getProperty(Constants.SERVICE_ID);
// the actual ServletContext might use "" instead of "/" (depends on the
// container). DTO must use "/" for root
dto.contextPath = servletContext.getContextPath().trim().length() == 0 ? "/" : servletContext.getContextPath();
dto.name = servletContext.getServletContextName();
dto.attributes = Collections.list(servletContext.getAttributeNames()).stream()
.map(name -> new SimpleEntry<>(name, servletContext.getAttribute(name)))
.collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));
dto.initParams = Collections.list(servletContext.getInitParameterNames()).stream()
.map(name -> new SimpleEntry<>(name, servletContext.getInitParameter(name)))
.collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));
return dto;
} | java | private ServletContextDTO mapServletContext(Map.Entry<ServiceReference<ServletContext>, ServletContext> mapEntry) {
final ServiceReference<ServletContext> ref = mapEntry.getKey();
final ServletContext servletContext = mapEntry.getValue();
ServletContextDTO dto = new ServletContextDTO();
dto.serviceId = (long) ref.getProperty(Constants.SERVICE_ID);
// the actual ServletContext might use "" instead of "/" (depends on the
// container). DTO must use "/" for root
dto.contextPath = servletContext.getContextPath().trim().length() == 0 ? "/" : servletContext.getContextPath();
dto.name = servletContext.getServletContextName();
dto.attributes = Collections.list(servletContext.getAttributeNames()).stream()
.map(name -> new SimpleEntry<>(name, servletContext.getAttribute(name)))
.collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));
dto.initParams = Collections.list(servletContext.getInitParameterNames()).stream()
.map(name -> new SimpleEntry<>(name, servletContext.getInitParameter(name)))
.collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));
return dto;
} | [
"private",
"ServletContextDTO",
"mapServletContext",
"(",
"Map",
".",
"Entry",
"<",
"ServiceReference",
"<",
"ServletContext",
">",
",",
"ServletContext",
">",
"mapEntry",
")",
"{",
"final",
"ServiceReference",
"<",
"ServletContext",
">",
"ref",
"=",
"mapEntry",
"... | /*
Maps a default context (whithout whiteboard-service) to a ServletContextDTO | [
"/",
"*",
"Maps",
"a",
"default",
"context",
"(",
"whithout",
"whiteboard",
"-",
"service",
")",
"to",
"a",
"ServletContextDTO"
] | train | https://github.com/ops4j/org.ops4j.pax.web/blob/9ecf3676c1d316be0d43ea7fcfdc8f0defffc2a2/pax-web-runtime/src/main/java/org/ops4j/pax/web/service/internal/WhiteboardDtoService.java#L276-L295 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/sampling/VarOptItemsSketch.java | VarOptItemsSketch.toByteArray | public byte[] toByteArray(final ArrayOfItemsSerDe<? super T> serDe) {
if ((r_ == 0) && (h_ == 0)) {
// null class is ok since empty -- no need to call serDe
return toByteArray(serDe, null);
} else {
final int validIndex = (h_ == 0 ? 1 : 0);
final Class<?> clazz = data_.get(validIndex).getClass();
return toByteArray(serDe, clazz);
}
} | java | public byte[] toByteArray(final ArrayOfItemsSerDe<? super T> serDe) {
if ((r_ == 0) && (h_ == 0)) {
// null class is ok since empty -- no need to call serDe
return toByteArray(serDe, null);
} else {
final int validIndex = (h_ == 0 ? 1 : 0);
final Class<?> clazz = data_.get(validIndex).getClass();
return toByteArray(serDe, clazz);
}
} | [
"public",
"byte",
"[",
"]",
"toByteArray",
"(",
"final",
"ArrayOfItemsSerDe",
"<",
"?",
"super",
"T",
">",
"serDe",
")",
"{",
"if",
"(",
"(",
"r_",
"==",
"0",
")",
"&&",
"(",
"h_",
"==",
"0",
")",
")",
"{",
"// null class is ok since empty -- no need to ... | Returns a byte array representation of this sketch. May fail for polymorphic item types.
@param serDe An instance of ArrayOfItemsSerDe
@return a byte array representation of this sketch | [
"Returns",
"a",
"byte",
"array",
"representation",
"of",
"this",
"sketch",
".",
"May",
"fail",
"for",
"polymorphic",
"item",
"types",
"."
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/VarOptItemsSketch.java#L524-L533 |
pawelprazak/java-extended | guava/src/main/java/com/bluecatcode/common/hash/Hash.java | Hash.newHash | public static HashCode newHash(String input, HashFunction function) {
return function.hashString(input, Charsets.UTF_8);
} | java | public static HashCode newHash(String input, HashFunction function) {
return function.hashString(input, Charsets.UTF_8);
} | [
"public",
"static",
"HashCode",
"newHash",
"(",
"String",
"input",
",",
"HashFunction",
"function",
")",
"{",
"return",
"function",
".",
"hashString",
"(",
"input",
",",
"Charsets",
".",
"UTF_8",
")",
";",
"}"
] | Creates a UTF-8 encoded hash using the hash function
@param input string to encode
@param function hash function to use
@return the hash code | [
"Creates",
"a",
"UTF",
"-",
"8",
"encoded",
"hash",
"using",
"the",
"hash",
"function"
] | train | https://github.com/pawelprazak/java-extended/blob/ce1a556a95cbbf7c950a03662938bc02622de69b/guava/src/main/java/com/bluecatcode/common/hash/Hash.java#L28-L30 |
ModeShape/modeshape | sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/DdlTokenStream.java | DdlTokenStream.getMarkedContent | public String getMarkedContent() {
Position startPosition = new Position(currentMarkedPosition.getIndexInContent(), currentMarkedPosition.getLine(),
currentMarkedPosition.getColumn());
mark();
return getContentBetween(startPosition, currentMarkedPosition);
} | java | public String getMarkedContent() {
Position startPosition = new Position(currentMarkedPosition.getIndexInContent(), currentMarkedPosition.getLine(),
currentMarkedPosition.getColumn());
mark();
return getContentBetween(startPosition, currentMarkedPosition);
} | [
"public",
"String",
"getMarkedContent",
"(",
")",
"{",
"Position",
"startPosition",
"=",
"new",
"Position",
"(",
"currentMarkedPosition",
".",
"getIndexInContent",
"(",
")",
",",
"currentMarkedPosition",
".",
"getLine",
"(",
")",
",",
"currentMarkedPosition",
".",
... | Returns the string content for characters bounded by the previous marked position and the position of the currentToken
(inclusive). Method also marks() the new position the the currentToken.
@return the string content for characters bounded by the previous marked position and the position of the currentToken
(inclusive). | [
"Returns",
"the",
"string",
"content",
"for",
"characters",
"bounded",
"by",
"the",
"previous",
"marked",
"position",
"and",
"the",
"position",
"of",
"the",
"currentToken",
"(",
"inclusive",
")",
".",
"Method",
"also",
"marks",
"()",
"the",
"new",
"position",
... | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/DdlTokenStream.java#L222-L229 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/SeaGlassSynthPainterImpl.java | SeaGlassSynthPainterImpl.paintForeground | private void paintForeground(SynthContext ctx, Graphics g, int x, int y, int w, int h, AffineTransform transform) {
SeaGlassPainter foregroundPainter = style.getForegroundPainter(ctx);
if (foregroundPainter != null) {
paint(foregroundPainter, ctx, g, x, y, w, h, transform);
}
} | java | private void paintForeground(SynthContext ctx, Graphics g, int x, int y, int w, int h, AffineTransform transform) {
SeaGlassPainter foregroundPainter = style.getForegroundPainter(ctx);
if (foregroundPainter != null) {
paint(foregroundPainter, ctx, g, x, y, w, h, transform);
}
} | [
"private",
"void",
"paintForeground",
"(",
"SynthContext",
"ctx",
",",
"Graphics",
"g",
",",
"int",
"x",
",",
"int",
"y",
",",
"int",
"w",
",",
"int",
"h",
",",
"AffineTransform",
"transform",
")",
"{",
"SeaGlassPainter",
"foregroundPainter",
"=",
"style",
... | Paint the object's foreground.
@param ctx the SynthContext.
@param g the Graphics context.
@param x the x location corresponding to the upper-left
coordinate to paint.
@param y the y location corresponding to the upper left
coordinate to paint.
@param w the width to paint.
@param h the height to paint.
@param transform the affine transform to apply, or {@code null} if none
is to be applied. | [
"Paint",
"the",
"object",
"s",
"foreground",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/SeaGlassSynthPainterImpl.java#L164-L170 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PathNormalizer.java | PathNormalizer.joinPaths | public static String joinPaths(String prefix, String path) {
String joinedPath = null;
if (prefix.startsWith(JawrConstant.HTTP_URL_PREFIX) || prefix.startsWith(JawrConstant.HTTPS_URL_PREFIX)
|| prefix.startsWith("//")) {
joinedPath = joinDomainToPath(prefix, path);
} else {
String normalizedPrefix = PathNormalizer.normalizePath(prefix);
StringBuilder sb = new StringBuilder(JawrConstant.URL_SEPARATOR);
if (!"".equals(normalizedPrefix))
sb.append(normalizedPrefix).append(JawrConstant.URL_SEPARATOR);
sb.append(PathNormalizer.normalizePath(path));
joinedPath = sb.toString();
}
return joinedPath;
} | java | public static String joinPaths(String prefix, String path) {
String joinedPath = null;
if (prefix.startsWith(JawrConstant.HTTP_URL_PREFIX) || prefix.startsWith(JawrConstant.HTTPS_URL_PREFIX)
|| prefix.startsWith("//")) {
joinedPath = joinDomainToPath(prefix, path);
} else {
String normalizedPrefix = PathNormalizer.normalizePath(prefix);
StringBuilder sb = new StringBuilder(JawrConstant.URL_SEPARATOR);
if (!"".equals(normalizedPrefix))
sb.append(normalizedPrefix).append(JawrConstant.URL_SEPARATOR);
sb.append(PathNormalizer.normalizePath(path));
joinedPath = sb.toString();
}
return joinedPath;
} | [
"public",
"static",
"String",
"joinPaths",
"(",
"String",
"prefix",
",",
"String",
"path",
")",
"{",
"String",
"joinedPath",
"=",
"null",
";",
"if",
"(",
"prefix",
".",
"startsWith",
"(",
"JawrConstant",
".",
"HTTP_URL_PREFIX",
")",
"||",
"prefix",
".",
"s... | Normalizes two paths and joins them as a single path.
@param prefix
the path prefix
@param path
the path
@return the joined path | [
"Normalizes",
"two",
"paths",
"and",
"joins",
"them",
"as",
"a",
"single",
"path",
"."
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PathNormalizer.java#L314-L332 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.hasProperty | public static MetaProperty hasProperty(Object self, String name) {
return InvokerHelper.getMetaClass(self).hasProperty(self, name);
} | java | public static MetaProperty hasProperty(Object self, String name) {
return InvokerHelper.getMetaClass(self).hasProperty(self, name);
} | [
"public",
"static",
"MetaProperty",
"hasProperty",
"(",
"Object",
"self",
",",
"String",
"name",
")",
"{",
"return",
"InvokerHelper",
".",
"getMetaClass",
"(",
"self",
")",
".",
"hasProperty",
"(",
"self",
",",
"name",
")",
";",
"}"
] | <p>Returns true of the implementing MetaClass has a property of the given name
<p>Note that this method will only return true for realised properties and does not take into
account implementation of getProperty or propertyMissing
@param self The object to inspect
@param name The name of the property of interest
@return The found MetaProperty or null if it doesn't exist
@see groovy.lang.MetaObjectProtocol#hasProperty(java.lang.Object, java.lang.String)
@since 1.6.1 | [
"<p",
">",
"Returns",
"true",
"of",
"the",
"implementing",
"MetaClass",
"has",
"a",
"property",
"of",
"the",
"given",
"name"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L17601-L17603 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/ReferencePrefetcher.java | ReferencePrefetcher.associateBatched | protected void associateBatched(Collection owners, Collection children)
{
ObjectReferenceDescriptor ord = getObjectReferenceDescriptor();
ClassDescriptor cld = getOwnerClassDescriptor();
Object owner;
Object relatedObject;
Object fkValues[];
Identity id;
PersistenceBroker pb = getBroker();
PersistentField field = ord.getPersistentField();
Class topLevelClass = pb.getTopLevelClass(ord.getItemClass());
HashMap childrenMap = new HashMap(children.size());
for (Iterator it = children.iterator(); it.hasNext(); )
{
relatedObject = it.next();
childrenMap.put(pb.serviceIdentity().buildIdentity(relatedObject), relatedObject);
}
for (Iterator it = owners.iterator(); it.hasNext(); )
{
owner = it.next();
fkValues = ord.getForeignKeyValues(owner,cld);
if (isNull(fkValues))
{
field.set(owner, null);
continue;
}
id = pb.serviceIdentity().buildIdentity(null, topLevelClass, fkValues);
relatedObject = childrenMap.get(id);
field.set(owner, relatedObject);
}
} | java | protected void associateBatched(Collection owners, Collection children)
{
ObjectReferenceDescriptor ord = getObjectReferenceDescriptor();
ClassDescriptor cld = getOwnerClassDescriptor();
Object owner;
Object relatedObject;
Object fkValues[];
Identity id;
PersistenceBroker pb = getBroker();
PersistentField field = ord.getPersistentField();
Class topLevelClass = pb.getTopLevelClass(ord.getItemClass());
HashMap childrenMap = new HashMap(children.size());
for (Iterator it = children.iterator(); it.hasNext(); )
{
relatedObject = it.next();
childrenMap.put(pb.serviceIdentity().buildIdentity(relatedObject), relatedObject);
}
for (Iterator it = owners.iterator(); it.hasNext(); )
{
owner = it.next();
fkValues = ord.getForeignKeyValues(owner,cld);
if (isNull(fkValues))
{
field.set(owner, null);
continue;
}
id = pb.serviceIdentity().buildIdentity(null, topLevelClass, fkValues);
relatedObject = childrenMap.get(id);
field.set(owner, relatedObject);
}
} | [
"protected",
"void",
"associateBatched",
"(",
"Collection",
"owners",
",",
"Collection",
"children",
")",
"{",
"ObjectReferenceDescriptor",
"ord",
"=",
"getObjectReferenceDescriptor",
"(",
")",
";",
"ClassDescriptor",
"cld",
"=",
"getOwnerClassDescriptor",
"(",
")",
"... | Associate the batched Children with their owner object.
Loop over owners | [
"Associate",
"the",
"batched",
"Children",
"with",
"their",
"owner",
"object",
".",
"Loop",
"over",
"owners"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/ReferencePrefetcher.java#L56-L89 |
ironjacamar/ironjacamar | rarinfo/src/main/java/org/ironjacamar/rarinfo/Main.java | Main.getUrls | private static URL[] getUrls(File directory) throws MalformedURLException, IOException
{
List<URL> list = new LinkedList<URL>();
if (directory.exists() && directory.isDirectory())
{
// Add directory
list.add(directory.toURI().toURL());
// Add the contents of the directory too
File[] jars = directory.listFiles(new FilenameFilter()
{
/**
* Accept
* @param dir The directory
* @param name The name
* @return True if accepts; otherwise false
*/
public boolean accept(File dir, String name)
{
return name.endsWith(".jar");
}
});
if (jars != null)
{
for (int j = 0; j < jars.length; j++)
{
list.add(jars[j].getCanonicalFile().toURI().toURL());
}
}
}
return list.toArray(new URL[list.size()]);
} | java | private static URL[] getUrls(File directory) throws MalformedURLException, IOException
{
List<URL> list = new LinkedList<URL>();
if (directory.exists() && directory.isDirectory())
{
// Add directory
list.add(directory.toURI().toURL());
// Add the contents of the directory too
File[] jars = directory.listFiles(new FilenameFilter()
{
/**
* Accept
* @param dir The directory
* @param name The name
* @return True if accepts; otherwise false
*/
public boolean accept(File dir, String name)
{
return name.endsWith(".jar");
}
});
if (jars != null)
{
for (int j = 0; j < jars.length; j++)
{
list.add(jars[j].getCanonicalFile().toURI().toURL());
}
}
}
return list.toArray(new URL[list.size()]);
} | [
"private",
"static",
"URL",
"[",
"]",
"getUrls",
"(",
"File",
"directory",
")",
"throws",
"MalformedURLException",
",",
"IOException",
"{",
"List",
"<",
"URL",
">",
"list",
"=",
"new",
"LinkedList",
"<",
"URL",
">",
"(",
")",
";",
"if",
"(",
"directory",... | Get the URLs for the directory and all libraries located in the directory
@param directory The directory
@return The URLs
@exception MalformedURLException MalformedURLException
@exception IOException IOException | [
"Get",
"the",
"URLs",
"for",
"the",
"directory",
"and",
"all",
"libraries",
"located",
"in",
"the",
"directory"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/rarinfo/src/main/java/org/ironjacamar/rarinfo/Main.java#L1426-L1459 |
igniterealtime/Smack | smack-experimental/src/main/java/org/jivesoftware/smackx/reference/element/ReferenceElement.java | ReferenceElement.addMention | public static void addMention(Stanza stanza, int begin, int end, BareJid jid) {
URI uri;
try {
uri = new URI("xmpp:" + jid.toString());
} catch (URISyntaxException e) {
throw new AssertionError("Cannot create URI from bareJid.");
}
ReferenceElement reference = new ReferenceElement(begin, end, ReferenceElement.Type.mention, null, uri);
stanza.addExtension(reference);
} | java | public static void addMention(Stanza stanza, int begin, int end, BareJid jid) {
URI uri;
try {
uri = new URI("xmpp:" + jid.toString());
} catch (URISyntaxException e) {
throw new AssertionError("Cannot create URI from bareJid.");
}
ReferenceElement reference = new ReferenceElement(begin, end, ReferenceElement.Type.mention, null, uri);
stanza.addExtension(reference);
} | [
"public",
"static",
"void",
"addMention",
"(",
"Stanza",
"stanza",
",",
"int",
"begin",
",",
"int",
"end",
",",
"BareJid",
"jid",
")",
"{",
"URI",
"uri",
";",
"try",
"{",
"uri",
"=",
"new",
"URI",
"(",
"\"xmpp:\"",
"+",
"jid",
".",
"toString",
"(",
... | Add a reference to another users bare jid to a stanza.
@param stanza stanza.
@param begin start index of the mention in the messages body.
@param end end index of the mention in the messages body.
@param jid referenced jid. | [
"Add",
"a",
"reference",
"to",
"another",
"users",
"bare",
"jid",
"to",
"a",
"stanza",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/reference/element/ReferenceElement.java#L129-L138 |
hibernate/hibernate-ogm | neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/query/parsing/impl/Neo4jAliasResolver.java | Neo4jAliasResolver.findAlias | public String findAlias(String entityAlias, List<String> propertyPathWithoutAlias) {
RelationshipAliasTree aliasTree = relationshipAliases.get( entityAlias );
if ( aliasTree == null ) {
return null;
}
RelationshipAliasTree associationAlias = aliasTree;
for ( int i = 0; i < propertyPathWithoutAlias.size(); i++ ) {
associationAlias = associationAlias.findChild( propertyPathWithoutAlias.get( i ) );
if ( associationAlias == null ) {
return null;
}
}
return associationAlias.getAlias();
} | java | public String findAlias(String entityAlias, List<String> propertyPathWithoutAlias) {
RelationshipAliasTree aliasTree = relationshipAliases.get( entityAlias );
if ( aliasTree == null ) {
return null;
}
RelationshipAliasTree associationAlias = aliasTree;
for ( int i = 0; i < propertyPathWithoutAlias.size(); i++ ) {
associationAlias = associationAlias.findChild( propertyPathWithoutAlias.get( i ) );
if ( associationAlias == null ) {
return null;
}
}
return associationAlias.getAlias();
} | [
"public",
"String",
"findAlias",
"(",
"String",
"entityAlias",
",",
"List",
"<",
"String",
">",
"propertyPathWithoutAlias",
")",
"{",
"RelationshipAliasTree",
"aliasTree",
"=",
"relationshipAliases",
".",
"get",
"(",
"entityAlias",
")",
";",
"if",
"(",
"aliasTree"... | Given the alias of the entity and the path to the relationship it will return the alias
of the component.
@param entityAlias the alias of the entity
@param propertyPathWithoutAlias the path to the property without the alias
@return the alias the relationship or null | [
"Given",
"the",
"alias",
"of",
"the",
"entity",
"and",
"the",
"path",
"to",
"the",
"relationship",
"it",
"will",
"return",
"the",
"alias",
"of",
"the",
"component",
"."
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/query/parsing/impl/Neo4jAliasResolver.java#L130-L143 |
sebastiangraf/treetank | interfacemodules/jax-rx/src/main/java/org/jaxrx/core/ResourcePath.java | ResourcePath.getResource | public String getResource(final int level) {
if (level < resource.length) {
return resource[level];
}
// offset is out of bounds...
throw new IndexOutOfBoundsException("Index: " + level + ", Size: " + resource.length);
} | java | public String getResource(final int level) {
if (level < resource.length) {
return resource[level];
}
// offset is out of bounds...
throw new IndexOutOfBoundsException("Index: " + level + ", Size: " + resource.length);
} | [
"public",
"String",
"getResource",
"(",
"final",
"int",
"level",
")",
"{",
"if",
"(",
"level",
"<",
"resource",
".",
"length",
")",
"{",
"return",
"resource",
"[",
"level",
"]",
";",
"}",
"// offset is out of bounds...\r",
"throw",
"new",
"IndexOutOfBoundsExce... | Returns the resource at the specified level.
@param level
resource level
@return resource | [
"Returns",
"the",
"resource",
"at",
"the",
"specified",
"level",
"."
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/jax-rx/src/main/java/org/jaxrx/core/ResourcePath.java#L125-L131 |
jiaqi/jcli | src/main/java/org/cyclopsgroup/jcli/impl/SingleValueReference.java | SingleValueReference.setValue | void setValue(T bean, String value) {
ref.writeValue(converter.fromCharacters(value), bean);
} | java | void setValue(T bean, String value) {
ref.writeValue(converter.fromCharacters(value), bean);
} | [
"void",
"setValue",
"(",
"T",
"bean",
",",
"String",
"value",
")",
"{",
"ref",
".",
"writeValue",
"(",
"converter",
".",
"fromCharacters",
"(",
"value",
")",
",",
"bean",
")",
";",
"}"
] | Set a string value to bean based on known conversion rule and value reference
@param bean Bean to set value to
@param value String expression of value to set | [
"Set",
"a",
"string",
"value",
"to",
"bean",
"based",
"on",
"known",
"conversion",
"rule",
"and",
"value",
"reference"
] | train | https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/impl/SingleValueReference.java#L18-L20 |
ManfredTremmel/gwt-commons-lang3 | src/main/resources/org/apache/commons/jre/java/util/BitSet.java | BitSet.maskInWord | private static void maskInWord(int[] array, int index, int from, int to) {
if (from == to) {
return;
}
to = 32 - to;
int word = wordAt(array, index);
word |= ((0xffffffff >>> from) << (from + to)) >>> to;
array[index] = word & WORD_MASK;
} | java | private static void maskInWord(int[] array, int index, int from, int to) {
if (from == to) {
return;
}
to = 32 - to;
int word = wordAt(array, index);
word |= ((0xffffffff >>> from) << (from + to)) >>> to;
array[index] = word & WORD_MASK;
} | [
"private",
"static",
"void",
"maskInWord",
"(",
"int",
"[",
"]",
"array",
",",
"int",
"index",
",",
"int",
"from",
",",
"int",
"to",
")",
"{",
"if",
"(",
"from",
"==",
"to",
")",
"{",
"return",
";",
"}",
"to",
"=",
"32",
"-",
"to",
";",
"int",
... | Sets all bits to true in a word within the given bit range.
@param array The array.
@param index The word index.
@param from The lower bit index.
@param to The upper bit index. | [
"Sets",
"all",
"bits",
"to",
"true",
"in",
"a",
"word",
"within",
"the",
"given",
"bit",
"range",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/resources/org/apache/commons/jre/java/util/BitSet.java#L174-L183 |
UrielCh/ovh-java-sdk | ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java | ApiOvhVps.serviceName_distribution_software_GET | public ArrayList<Long> serviceName_distribution_software_GET(String serviceName) throws IOException {
String qPath = "/vps/{serviceName}/distribution/software";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t4);
} | java | public ArrayList<Long> serviceName_distribution_software_GET(String serviceName) throws IOException {
String qPath = "/vps/{serviceName}/distribution/software";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t4);
} | [
"public",
"ArrayList",
"<",
"Long",
">",
"serviceName_distribution_software_GET",
"(",
"String",
"serviceName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/vps/{serviceName}/distribution/software\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPat... | List available softwares for this template Id
REST: GET /vps/{serviceName}/distribution/software
@param serviceName [required] The internal name of your VPS offer | [
"List",
"available",
"softwares",
"for",
"this",
"template",
"Id"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java#L445-L450 |
pravega/pravega | shared/protocol/src/main/java/io/pravega/shared/segment/StreamSegmentNameUtils.java | StreamSegmentNameUtils.computeSegmentId | public static long computeSegmentId(int segmentNumber, int epoch) {
Preconditions.checkArgument(segmentNumber >= 0);
Preconditions.checkArgument(epoch >= 0);
return (long) epoch << 32 | (segmentNumber & 0xFFFFFFFFL);
} | java | public static long computeSegmentId(int segmentNumber, int epoch) {
Preconditions.checkArgument(segmentNumber >= 0);
Preconditions.checkArgument(epoch >= 0);
return (long) epoch << 32 | (segmentNumber & 0xFFFFFFFFL);
} | [
"public",
"static",
"long",
"computeSegmentId",
"(",
"int",
"segmentNumber",
",",
"int",
"epoch",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"segmentNumber",
">=",
"0",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"epoch",
">=",
"0",
")",
... | Method to compute 64 bit segment id which takes segment number and epoch and composes it as
`msb = epoch` `lsb = segmentNumber`.
Primary id identifies the segment container mapping and primary + secondary uniquely identifies a segment
within a stream.
@param segmentNumber segment number.
@param epoch epoch in which segment was created.
@return segment id which is composed using segment number and epoch. | [
"Method",
"to",
"compute",
"64",
"bit",
"segment",
"id",
"which",
"takes",
"segment",
"number",
"and",
"epoch",
"and",
"composes",
"it",
"as",
"msb",
"=",
"epoch",
"lsb",
"=",
"segmentNumber",
".",
"Primary",
"id",
"identifies",
"the",
"segment",
"container"... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/shared/protocol/src/main/java/io/pravega/shared/segment/StreamSegmentNameUtils.java#L212-L216 |
ical4j/ical4j | src/main/java/net/fortuna/ical4j/model/component/VEvent.java | VEvent.getEndDate | public final DtEnd getEndDate(final boolean deriveFromDuration) {
DtEnd dtEnd = getProperty(Property.DTEND);
// No DTEND? No problem, we'll use the DURATION.
if (dtEnd == null && deriveFromDuration && getStartDate() != null) {
final DtStart dtStart = getStartDate();
final Duration vEventDuration;
if (getDuration() != null) {
vEventDuration = getDuration();
} else if (dtStart.getDate() instanceof DateTime) {
// If "DTSTART" is a DATE-TIME, then the event's duration is zero (see: RFC 5545, 3.6.1 Event Component)
vEventDuration = new Duration(java.time.Duration.ZERO);
} else {
// If "DTSTART" is a DATE, then the event's duration is one day (see: RFC 5545, 3.6.1 Event Component)
vEventDuration = new Duration(java.time.Duration.ofDays(1));
}
dtEnd = new DtEnd(Dates.getInstance(Date.from(dtStart.getDate().toInstant().plus(vEventDuration.getDuration())),
dtStart.getParameter(Parameter.VALUE)));
if (dtStart.isUtc()) {
dtEnd.setUtc(true);
} else {
dtEnd.setTimeZone(dtStart.getTimeZone());
}
}
return dtEnd;
} | java | public final DtEnd getEndDate(final boolean deriveFromDuration) {
DtEnd dtEnd = getProperty(Property.DTEND);
// No DTEND? No problem, we'll use the DURATION.
if (dtEnd == null && deriveFromDuration && getStartDate() != null) {
final DtStart dtStart = getStartDate();
final Duration vEventDuration;
if (getDuration() != null) {
vEventDuration = getDuration();
} else if (dtStart.getDate() instanceof DateTime) {
// If "DTSTART" is a DATE-TIME, then the event's duration is zero (see: RFC 5545, 3.6.1 Event Component)
vEventDuration = new Duration(java.time.Duration.ZERO);
} else {
// If "DTSTART" is a DATE, then the event's duration is one day (see: RFC 5545, 3.6.1 Event Component)
vEventDuration = new Duration(java.time.Duration.ofDays(1));
}
dtEnd = new DtEnd(Dates.getInstance(Date.from(dtStart.getDate().toInstant().plus(vEventDuration.getDuration())),
dtStart.getParameter(Parameter.VALUE)));
if (dtStart.isUtc()) {
dtEnd.setUtc(true);
} else {
dtEnd.setTimeZone(dtStart.getTimeZone());
}
}
return dtEnd;
} | [
"public",
"final",
"DtEnd",
"getEndDate",
"(",
"final",
"boolean",
"deriveFromDuration",
")",
"{",
"DtEnd",
"dtEnd",
"=",
"getProperty",
"(",
"Property",
".",
"DTEND",
")",
";",
"// No DTEND? No problem, we'll use the DURATION.",
"if",
"(",
"dtEnd",
"==",
"null",
... | Convenience method to pull the DTEND out of the property list. If DTEND was not specified, use the DTSTART +
DURATION to calculate it.
@param deriveFromDuration specifies whether to derive an end date from the event duration where an end date is
not found
@return The end for this VEVENT. | [
"Convenience",
"method",
"to",
"pull",
"the",
"DTEND",
"out",
"of",
"the",
"property",
"list",
".",
"If",
"DTEND",
"was",
"not",
"specified",
"use",
"the",
"DTSTART",
"+",
"DURATION",
"to",
"calculate",
"it",
"."
] | train | https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/model/component/VEvent.java#L627-L652 |
Netflix/ribbon | ribbon-core/src/main/java/com/netflix/client/ssl/AbstractSslContextFactory.java | AbstractSslContextFactory.createTrustManagers | private TrustManager[] createTrustManagers() throws ClientSslSocketFactoryException {
final TrustManagerFactory factory;
try {
factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(this.trustStore);
} catch (NoSuchAlgorithmException e) {
throw new ClientSslSocketFactoryException(String.format("Failed to create the trust store because the algorithm %s is not supported. ",
KeyManagerFactory.getDefaultAlgorithm()), e);
} catch (KeyStoreException e) {
throw new ClientSslSocketFactoryException("KeyStore exception initializing trust manager factory; this is probably fatal", e);
}
final TrustManager[] managers = factory.getTrustManagers();
LOGGER.debug("TrustManagers are initialized. Total {} managers: ", managers.length);
return managers;
} | java | private TrustManager[] createTrustManagers() throws ClientSslSocketFactoryException {
final TrustManagerFactory factory;
try {
factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(this.trustStore);
} catch (NoSuchAlgorithmException e) {
throw new ClientSslSocketFactoryException(String.format("Failed to create the trust store because the algorithm %s is not supported. ",
KeyManagerFactory.getDefaultAlgorithm()), e);
} catch (KeyStoreException e) {
throw new ClientSslSocketFactoryException("KeyStore exception initializing trust manager factory; this is probably fatal", e);
}
final TrustManager[] managers = factory.getTrustManagers();
LOGGER.debug("TrustManagers are initialized. Total {} managers: ", managers.length);
return managers;
} | [
"private",
"TrustManager",
"[",
"]",
"createTrustManagers",
"(",
")",
"throws",
"ClientSslSocketFactoryException",
"{",
"final",
"TrustManagerFactory",
"factory",
";",
"try",
"{",
"factory",
"=",
"TrustManagerFactory",
".",
"getInstance",
"(",
"TrustManagerFactory",
"."... | Creates the trust managers to be used by the factory from the specified trust store file and
password.
@return the newly created array of trust managers
@throws ClientSslSocketFactoryException if an error is detected in loading the trust store | [
"Creates",
"the",
"trust",
"managers",
"to",
"be",
"used",
"by",
"the",
"factory",
"from",
"the",
"specified",
"trust",
"store",
"file",
"and",
"password",
"."
] | train | https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-core/src/main/java/com/netflix/client/ssl/AbstractSslContextFactory.java#L155-L175 |
aoindustries/ao-encoding | src/main/java/com/aoindustries/encoding/XhtmlValidator.java | XhtmlValidator.checkCharacter | public static void checkCharacter(char c) throws IOException {
if(
(c < 0x20 || c > 0xD7FF) // common case first
&& c != 0x9
&& c != 0xA
&& c != 0xD
&& (c < 0xE000 || c > 0xFFFD)
// high and low surrogates
//&& (c < 0x10000 || c > 0x10FFFF)
&& (c < Character.MIN_HIGH_SURROGATE || c > Character.MAX_LOW_SURROGATE)
) throw new IOException(ApplicationResources.accessor.getMessage("XhtmlValidator.invalidCharacter", Integer.toHexString(c)));
} | java | public static void checkCharacter(char c) throws IOException {
if(
(c < 0x20 || c > 0xD7FF) // common case first
&& c != 0x9
&& c != 0xA
&& c != 0xD
&& (c < 0xE000 || c > 0xFFFD)
// high and low surrogates
//&& (c < 0x10000 || c > 0x10FFFF)
&& (c < Character.MIN_HIGH_SURROGATE || c > Character.MAX_LOW_SURROGATE)
) throw new IOException(ApplicationResources.accessor.getMessage("XhtmlValidator.invalidCharacter", Integer.toHexString(c)));
} | [
"public",
"static",
"void",
"checkCharacter",
"(",
"char",
"c",
")",
"throws",
"IOException",
"{",
"if",
"(",
"(",
"c",
"<",
"0x20",
"||",
"c",
">",
"0xD7FF",
")",
"// common case first",
"&&",
"c",
"!=",
"0x9",
"&&",
"c",
"!=",
"0xA",
"&&",
"c",
"!=... | Checks one character, throws IOException if invalid.
<a href="http://www.w3.org/TR/REC-xml/#charsets">http://www.w3.org/TR/REC-xml/#charsets</a> | [
"Checks",
"one",
"character",
"throws",
"IOException",
"if",
"invalid",
"."
] | train | https://github.com/aoindustries/ao-encoding/blob/54eeb8ff58ab7b44bb02549bbe2572625b449e4e/src/main/java/com/aoindustries/encoding/XhtmlValidator.java#L46-L58 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WRadioButtonSelectExample.java | WRadioButtonSelectExample.makeSimpleExample | private void makeSimpleExample() {
add(new WHeading(HeadingLevel.H3, "Simple WRadioButtonSelect"));
WPanel examplePanel = new WPanel();
examplePanel.setLayout(new FlowLayout(FlowLayout.VERTICAL, Size.MEDIUM));
add(examplePanel);
/**
* The radio button select.
*/
final WRadioButtonSelect rbSelect = new WRadioButtonSelect("australian_state");
final WTextField text = new WTextField();
text.setReadOnly(true);
text.setText(NO_SELECTION);
WButton update = new WButton("Update");
update.setAction(new Action() {
@Override
public void execute(final ActionEvent event) {
text.setText("The selected item is: "
+ rbSelect.getSelected());
}
});
//setting the default submit button improves usability. It can be set on a WPanel or the WRadioButtonSelect directly
examplePanel.setDefaultSubmitButton(update);
examplePanel.add(new WLabel("Select a state or territory", rbSelect));
examplePanel.add(rbSelect);
examplePanel.add(text);
examplePanel.add(update);
add(new WAjaxControl(update, text));
} | java | private void makeSimpleExample() {
add(new WHeading(HeadingLevel.H3, "Simple WRadioButtonSelect"));
WPanel examplePanel = new WPanel();
examplePanel.setLayout(new FlowLayout(FlowLayout.VERTICAL, Size.MEDIUM));
add(examplePanel);
/**
* The radio button select.
*/
final WRadioButtonSelect rbSelect = new WRadioButtonSelect("australian_state");
final WTextField text = new WTextField();
text.setReadOnly(true);
text.setText(NO_SELECTION);
WButton update = new WButton("Update");
update.setAction(new Action() {
@Override
public void execute(final ActionEvent event) {
text.setText("The selected item is: "
+ rbSelect.getSelected());
}
});
//setting the default submit button improves usability. It can be set on a WPanel or the WRadioButtonSelect directly
examplePanel.setDefaultSubmitButton(update);
examplePanel.add(new WLabel("Select a state or territory", rbSelect));
examplePanel.add(rbSelect);
examplePanel.add(text);
examplePanel.add(update);
add(new WAjaxControl(update, text));
} | [
"private",
"void",
"makeSimpleExample",
"(",
")",
"{",
"add",
"(",
"new",
"WHeading",
"(",
"HeadingLevel",
".",
"H3",
",",
"\"Simple WRadioButtonSelect\"",
")",
")",
";",
"WPanel",
"examplePanel",
"=",
"new",
"WPanel",
"(",
")",
";",
"examplePanel",
".",
"se... | Make a simple editable example. The label for this example is used to get the example for use in the unit tests. | [
"Make",
"a",
"simple",
"editable",
"example",
".",
"The",
"label",
"for",
"this",
"example",
"is",
"used",
"to",
"get",
"the",
"example",
"for",
"use",
"in",
"the",
"unit",
"tests",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WRadioButtonSelectExample.java#L71-L102 |
nmorel/gwt-jackson | gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/AbstractCreator.java | AbstractCreator.methodCallCodeWithJParameterizedMapperParameters | private CodeBlock methodCallCodeWithJParameterizedMapperParameters( CodeBlock.Builder builder, ImmutableList<? extends
JParameterizedMapper> parameters
) {
return methodCallParametersCode( builder, Lists.transform( parameters, new Function<JParameterizedMapper, CodeBlock>() {
@Override
public CodeBlock apply( JParameterizedMapper jMapperType ) {
return jMapperType.getInstance();
}
} ) );
} | java | private CodeBlock methodCallCodeWithJParameterizedMapperParameters( CodeBlock.Builder builder, ImmutableList<? extends
JParameterizedMapper> parameters
) {
return methodCallParametersCode( builder, Lists.transform( parameters, new Function<JParameterizedMapper, CodeBlock>() {
@Override
public CodeBlock apply( JParameterizedMapper jMapperType ) {
return jMapperType.getInstance();
}
} ) );
} | [
"private",
"CodeBlock",
"methodCallCodeWithJParameterizedMapperParameters",
"(",
"CodeBlock",
".",
"Builder",
"builder",
",",
"ImmutableList",
"<",
"?",
"extends",
"JParameterizedMapper",
">",
"parameters",
")",
"{",
"return",
"methodCallParametersCode",
"(",
"builder",
"... | Build the code for the parameters of a method call.
@param builder the code builder
@param parameters the parameters
@return the code | [
"Build",
"the",
"code",
"for",
"the",
"parameters",
"of",
"a",
"method",
"call",
"."
] | train | https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/AbstractCreator.java#L949-L959 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/util/Pair.java | Pair.internedStringPair | public static Pair<String, String> internedStringPair(String first, String second) {
return new MutableInternedPair(first, second);
} | java | public static Pair<String, String> internedStringPair(String first, String second) {
return new MutableInternedPair(first, second);
} | [
"public",
"static",
"Pair",
"<",
"String",
",",
"String",
">",
"internedStringPair",
"(",
"String",
"first",
",",
"String",
"second",
")",
"{",
"return",
"new",
"MutableInternedPair",
"(",
"first",
",",
"second",
")",
";",
"}"
] | Returns an MutableInternedPair where the Strings have been interned.
This is a factory method for creating an
MutableInternedPair. It requires the arguments to be Strings.
If this Pair is serialized
and then deserialized, first and second are interned upon
deserialization.
<p><i>Note:</i> I put this in thinking that its use might be
faster than calling <code>x = new Pair(a, b).stringIntern()</code>
but it's not really clear whether this is true.
@param first The first object
@param second The second object
@return An MutableInternedPair, with given first and second | [
"Returns",
"an",
"MutableInternedPair",
"where",
"the",
"Strings",
"have",
"been",
"interned",
".",
"This",
"is",
"a",
"factory",
"method",
"for",
"creating",
"an",
"MutableInternedPair",
".",
"It",
"requires",
"the",
"arguments",
"to",
"be",
"Strings",
".",
"... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/Pair.java#L196-L198 |
metafacture/metafacture-core | metafacture-biblio/src/main/java/org/metafacture/biblio/iso2709/Iso646ByteBuffer.java | Iso646ByteBuffer.parseIntAt | int parseIntAt(final int fromIndex, final int length) {
assert length >= 0;
assert 0 <= fromIndex && (fromIndex + length) <= byteArray.length;
final int multiplyMax = Integer.MAX_VALUE / RADIX;
int result = 0;
for (int i = 0; i < length; ++i) {
if (result > multiplyMax) {
throwNumberIsToLargeException(fromIndex);
}
result *= RADIX;
final int digit = byteToDigit(fromIndex + i);
if (result > Integer.MAX_VALUE - digit) {
throwNumberIsToLargeException(fromIndex);
}
result += digit;
}
return result;
} | java | int parseIntAt(final int fromIndex, final int length) {
assert length >= 0;
assert 0 <= fromIndex && (fromIndex + length) <= byteArray.length;
final int multiplyMax = Integer.MAX_VALUE / RADIX;
int result = 0;
for (int i = 0; i < length; ++i) {
if (result > multiplyMax) {
throwNumberIsToLargeException(fromIndex);
}
result *= RADIX;
final int digit = byteToDigit(fromIndex + i);
if (result > Integer.MAX_VALUE - digit) {
throwNumberIsToLargeException(fromIndex);
}
result += digit;
}
return result;
} | [
"int",
"parseIntAt",
"(",
"final",
"int",
"fromIndex",
",",
"final",
"int",
"length",
")",
"{",
"assert",
"length",
">=",
"0",
";",
"assert",
"0",
"<=",
"fromIndex",
"&&",
"(",
"fromIndex",
"+",
"length",
")",
"<=",
"byteArray",
".",
"length",
";",
"fi... | Parses characters in the specified part of the byte buffer into an integer
This is a simplified version of {@link Integer#parseInt(String)}. It
operates directly on the byte data and works only for positive numbers and
a radix of 10.
@param fromIndex position fo the byte range to convert into an integer
@param length number of bytes to include in the range
@return the integer value represented by the characters at the given
range in the buffer.
@throws NumberFormatException if a non-digit character was encountered or
an overflow occurred. | [
"Parses",
"characters",
"in",
"the",
"specified",
"part",
"of",
"the",
"byte",
"buffer",
"into",
"an",
"integer",
"This",
"is",
"a",
"simplified",
"version",
"of",
"{",
"@link",
"Integer#parseInt",
"(",
"String",
")",
"}",
".",
"It",
"operates",
"directly",
... | train | https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metafacture-biblio/src/main/java/org/metafacture/biblio/iso2709/Iso646ByteBuffer.java#L201-L218 |
elki-project/elki | elki-itemsets/src/main/java/de/lmu/ifi/dbs/elki/algorithm/itemsetmining/APRIORI.java | APRIORI.nextSearchItemset | private boolean nextSearchItemset(BitVector bv, int[] scratchi, int[] iters) {
final int last = scratchi.length - 1;
for(int j = last; j >= 0; j--) {
int n = bv.iterAdvance(iters[j]);
if(n >= 0 && (j == last || n != iters[j + 1])) {
iters[j] = n;
scratchi[j] = bv.iterDim(n);
return true; // Success
}
}
return false;
} | java | private boolean nextSearchItemset(BitVector bv, int[] scratchi, int[] iters) {
final int last = scratchi.length - 1;
for(int j = last; j >= 0; j--) {
int n = bv.iterAdvance(iters[j]);
if(n >= 0 && (j == last || n != iters[j + 1])) {
iters[j] = n;
scratchi[j] = bv.iterDim(n);
return true; // Success
}
}
return false;
} | [
"private",
"boolean",
"nextSearchItemset",
"(",
"BitVector",
"bv",
",",
"int",
"[",
"]",
"scratchi",
",",
"int",
"[",
"]",
"iters",
")",
"{",
"final",
"int",
"last",
"=",
"scratchi",
".",
"length",
"-",
"1",
";",
"for",
"(",
"int",
"j",
"=",
"last",
... | Advance scratch itemset to the next.
@param bv Bit vector data source
@param scratchi Scratch itemset
@param iters Iterator array
@return {@code true} if the itemset had minimum length | [
"Advance",
"scratch",
"itemset",
"to",
"the",
"next",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-itemsets/src/main/java/de/lmu/ifi/dbs/elki/algorithm/itemsetmining/APRIORI.java#L519-L530 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.getParent | public CmsGroup getParent(CmsDbContext dbc, String groupname) throws CmsException {
CmsGroup group = readGroup(dbc, groupname);
if (group.getParentId().isNullUUID()) {
return null;
}
// try to read from cache
CmsGroup parent = m_monitor.getCachedGroup(group.getParentId().toString());
if (parent == null) {
parent = getUserDriver(dbc).readGroup(dbc, group.getParentId());
m_monitor.cacheGroup(parent);
}
return parent;
} | java | public CmsGroup getParent(CmsDbContext dbc, String groupname) throws CmsException {
CmsGroup group = readGroup(dbc, groupname);
if (group.getParentId().isNullUUID()) {
return null;
}
// try to read from cache
CmsGroup parent = m_monitor.getCachedGroup(group.getParentId().toString());
if (parent == null) {
parent = getUserDriver(dbc).readGroup(dbc, group.getParentId());
m_monitor.cacheGroup(parent);
}
return parent;
} | [
"public",
"CmsGroup",
"getParent",
"(",
"CmsDbContext",
"dbc",
",",
"String",
"groupname",
")",
"throws",
"CmsException",
"{",
"CmsGroup",
"group",
"=",
"readGroup",
"(",
"dbc",
",",
"groupname",
")",
";",
"if",
"(",
"group",
".",
"getParentId",
"(",
")",
... | Returns the parent group of a group.<p>
@param dbc the current database context
@param groupname the name of the group
@return group the parent group or <code>null</code>
@throws CmsException if operation was not successful | [
"Returns",
"the",
"parent",
"group",
"of",
"a",
"group",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L4254-L4268 |
kaazing/gateway | mina.core/core/src/main/java/org/apache/mina/proxy/filter/ProxyFilter.java | ProxyFilter.sessionOpened | @Override
public void sessionOpened(NextFilter nextFilter, IoSession session)
throws Exception {
ProxyIoSession proxyIoSession = (ProxyIoSession) session
.getAttribute(ProxyIoSession.PROXY_SESSION);
proxyIoSession.getEventQueue().enqueueEventIfNecessary(
new IoSessionEvent(nextFilter, session,
IoSessionEventType.OPENED));
} | java | @Override
public void sessionOpened(NextFilter nextFilter, IoSession session)
throws Exception {
ProxyIoSession proxyIoSession = (ProxyIoSession) session
.getAttribute(ProxyIoSession.PROXY_SESSION);
proxyIoSession.getEventQueue().enqueueEventIfNecessary(
new IoSessionEvent(nextFilter, session,
IoSessionEventType.OPENED));
} | [
"@",
"Override",
"public",
"void",
"sessionOpened",
"(",
"NextFilter",
"nextFilter",
",",
"IoSession",
"session",
")",
"throws",
"Exception",
"{",
"ProxyIoSession",
"proxyIoSession",
"=",
"(",
"ProxyIoSession",
")",
"session",
".",
"getAttribute",
"(",
"ProxyIoSessi... | Event is stored in an {@link IoSessionEventQueue} for later delivery to the next filter
in the chain when the handshake would have succeed. This will prevent the rest of
the filter chain from being affected by this filter internals.
@param nextFilter the next filter in filter chain
@param session the session object | [
"Event",
"is",
"stored",
"in",
"an",
"{",
"@link",
"IoSessionEventQueue",
"}",
"for",
"later",
"delivery",
"to",
"the",
"next",
"filter",
"in",
"the",
"chain",
"when",
"the",
"handshake",
"would",
"have",
"succeed",
".",
"This",
"will",
"prevent",
"the",
"... | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/proxy/filter/ProxyFilter.java#L316-L324 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Math.java | Math.nextAfter | public static float nextAfter(float start, double direction) {
/*
* The cases:
*
* nextAfter(+infinity, 0) == MAX_VALUE
* nextAfter(+infinity, +infinity) == +infinity
* nextAfter(-infinity, 0) == -MAX_VALUE
* nextAfter(-infinity, -infinity) == -infinity
*
* are naturally handled without any additional testing
*/
// First check for NaN values
if (Float.isNaN(start) || Double.isNaN(direction)) {
// return a NaN derived from the input NaN(s)
return start + (float)direction;
} else if (start == direction) {
return (float)direction;
} else { // start > direction or start < direction
// Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0)
// then bitwise convert start to integer.
int transducer = Float.floatToRawIntBits(start + 0.0f);
/*
* IEEE 754 floating-point numbers are lexicographically
* ordered if treated as signed- magnitude integers .
* Since Java's integers are two's complement,
* incrementing" the two's complement representation of a
* logically negative floating-point value *decrements*
* the signed-magnitude representation. Therefore, when
* the integer representation of a floating-point values
* is less than zero, the adjustment to the representation
* is in the opposite direction than would be expected at
* first.
*/
if (direction > start) {// Calculate next greater value
transducer = transducer + (transducer >= 0 ? 1:-1);
} else { // Calculate next lesser value
assert direction < start;
if (transducer > 0)
--transducer;
else
if (transducer < 0 )
++transducer;
/*
* transducer==0, the result is -MIN_VALUE
*
* The transition from zero (implicitly
* positive) to the smallest negative
* signed magnitude value must be done
* explicitly.
*/
else
transducer = FloatConsts.SIGN_BIT_MASK | 1;
}
return Float.intBitsToFloat(transducer);
}
} | java | public static float nextAfter(float start, double direction) {
/*
* The cases:
*
* nextAfter(+infinity, 0) == MAX_VALUE
* nextAfter(+infinity, +infinity) == +infinity
* nextAfter(-infinity, 0) == -MAX_VALUE
* nextAfter(-infinity, -infinity) == -infinity
*
* are naturally handled without any additional testing
*/
// First check for NaN values
if (Float.isNaN(start) || Double.isNaN(direction)) {
// return a NaN derived from the input NaN(s)
return start + (float)direction;
} else if (start == direction) {
return (float)direction;
} else { // start > direction or start < direction
// Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0)
// then bitwise convert start to integer.
int transducer = Float.floatToRawIntBits(start + 0.0f);
/*
* IEEE 754 floating-point numbers are lexicographically
* ordered if treated as signed- magnitude integers .
* Since Java's integers are two's complement,
* incrementing" the two's complement representation of a
* logically negative floating-point value *decrements*
* the signed-magnitude representation. Therefore, when
* the integer representation of a floating-point values
* is less than zero, the adjustment to the representation
* is in the opposite direction than would be expected at
* first.
*/
if (direction > start) {// Calculate next greater value
transducer = transducer + (transducer >= 0 ? 1:-1);
} else { // Calculate next lesser value
assert direction < start;
if (transducer > 0)
--transducer;
else
if (transducer < 0 )
++transducer;
/*
* transducer==0, the result is -MIN_VALUE
*
* The transition from zero (implicitly
* positive) to the smallest negative
* signed magnitude value must be done
* explicitly.
*/
else
transducer = FloatConsts.SIGN_BIT_MASK | 1;
}
return Float.intBitsToFloat(transducer);
}
} | [
"public",
"static",
"float",
"nextAfter",
"(",
"float",
"start",
",",
"double",
"direction",
")",
"{",
"/*\n * The cases:\n *\n * nextAfter(+infinity, 0) == MAX_VALUE\n * nextAfter(+infinity, +infinity) == +infinity\n * nextAfter(-infinity, 0) == -M... | Returns the floating-point number adjacent to the first
argument in the direction of the second argument. If both
arguments compare as equal a value equivalent to the second argument
is returned.
<p>
Special cases:
<ul>
<li> If either argument is a NaN, then NaN is returned.
<li> If both arguments are signed zeros, a value equivalent
to {@code direction} is returned.
<li> If {@code start} is
±{@link Float#MIN_VALUE} and {@code direction}
has a value such that the result should have a smaller
magnitude, then a zero with the same sign as {@code start}
is returned.
<li> If {@code start} is infinite and
{@code direction} has a value such that the result should
have a smaller magnitude, {@link Float#MAX_VALUE} with the
same sign as {@code start} is returned.
<li> If {@code start} is equal to ±
{@link Float#MAX_VALUE} and {@code direction} has a
value such that the result should have a larger magnitude, an
infinity with same sign as {@code start} is returned.
</ul>
@param start starting floating-point value
@param direction value indicating which of
{@code start}'s neighbors or {@code start} should
be returned
@return The floating-point number adjacent to {@code start} in the
direction of {@code direction}.
@since 1.6 | [
"Returns",
"the",
"floating",
"-",
"point",
"number",
"adjacent",
"to",
"the",
"first",
"argument",
"in",
"the",
"direction",
"of",
"the",
"second",
"argument",
".",
"If",
"both",
"arguments",
"compare",
"as",
"equal",
"a",
"value",
"equivalent",
"to",
"the"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Math.java#L1988-L2046 |
tencentyun/cos-java-sdk | src/main/java/com/qcloud/cos/common_utils/CommonFileUtils.java | CommonFileUtils.getFileContent | public static String getFileContent(InputStream inputStream, long offset, int length)
throws Exception {
byte[] fileContent = getFileContentByte(inputStream, offset, length);
return new String(fileContent, Charset.forName("ISO-8859-1"));
} | java | public static String getFileContent(InputStream inputStream, long offset, int length)
throws Exception {
byte[] fileContent = getFileContentByte(inputStream, offset, length);
return new String(fileContent, Charset.forName("ISO-8859-1"));
} | [
"public",
"static",
"String",
"getFileContent",
"(",
"InputStream",
"inputStream",
",",
"long",
"offset",
",",
"int",
"length",
")",
"throws",
"Exception",
"{",
"byte",
"[",
"]",
"fileContent",
"=",
"getFileContentByte",
"(",
"inputStream",
",",
"offset",
",",
... | 读取指定流从某处开始的内容,此函数有一定的风险,如果流对应的内容过大,则会造成OOM
@param inputStream
@param offset 读取的开始偏移
@param length 读取的长度
@return 读取的内容
@throws Exception | [
"读取指定流从某处开始的内容,此函数有一定的风险,如果流对应的内容过大,则会造成OOM"
] | train | https://github.com/tencentyun/cos-java-sdk/blob/6709a48f67c1ea7b82a7215f5037d6ccf218b630/src/main/java/com/qcloud/cos/common_utils/CommonFileUtils.java#L115-L119 |
wcm-io/wcm-io-sling | commons/src/main/java/io/wcm/sling/commons/request/RequestParam.java | RequestParam.get | public static @Nullable String get(@NotNull ServletRequest request, @NotNull String param) {
return get(request, param, null);
} | java | public static @Nullable String get(@NotNull ServletRequest request, @NotNull String param) {
return get(request, param, null);
} | [
"public",
"static",
"@",
"Nullable",
"String",
"get",
"(",
"@",
"NotNull",
"ServletRequest",
"request",
",",
"@",
"NotNull",
"String",
"param",
")",
"{",
"return",
"get",
"(",
"request",
",",
"param",
",",
"null",
")",
";",
"}"
] | Returns a request parameter.<br>
In addition the method fixes problems with incorrect UTF-8 characters returned by the servlet engine.
All character data is converted from ISO-8859-1 to UTF-8 if not '_charset_' parameter is provided.
@param request Request.
@param param Parameter name.
@return Parameter value or null if it is not set. | [
"Returns",
"a",
"request",
"parameter",
".",
"<br",
">",
"In",
"addition",
"the",
"method",
"fixes",
"problems",
"with",
"incorrect",
"UTF",
"-",
"8",
"characters",
"returned",
"by",
"the",
"servlet",
"engine",
".",
"All",
"character",
"data",
"is",
"convert... | train | https://github.com/wcm-io/wcm-io-sling/blob/90adbe432469378794b5695c72e9cdfa2b7d36f1/commons/src/main/java/io/wcm/sling/commons/request/RequestParam.java#L63-L65 |
alkacon/opencms-core | src/org/opencms/loader/CmsJspLoader.java | CmsJspLoader.removeFromCache | public void removeFromCache(Set<String> rootPaths, boolean online) {
Map<String, Boolean> cache;
if (online) {
cache = m_onlineJsps;
} else {
cache = m_offlineJsps;
}
Iterator<String> itRemove = rootPaths.iterator();
while (itRemove.hasNext()) {
String rootPath = itRemove.next();
cache.remove(rootPath);
}
} | java | public void removeFromCache(Set<String> rootPaths, boolean online) {
Map<String, Boolean> cache;
if (online) {
cache = m_onlineJsps;
} else {
cache = m_offlineJsps;
}
Iterator<String> itRemove = rootPaths.iterator();
while (itRemove.hasNext()) {
String rootPath = itRemove.next();
cache.remove(rootPath);
}
} | [
"public",
"void",
"removeFromCache",
"(",
"Set",
"<",
"String",
">",
"rootPaths",
",",
"boolean",
"online",
")",
"{",
"Map",
"<",
"String",
",",
"Boolean",
">",
"cache",
";",
"if",
"(",
"online",
")",
"{",
"cache",
"=",
"m_onlineJsps",
";",
"}",
"else"... | Removes the given resources from the cache.<p>
@param rootPaths the set of root paths to remove
@param online if online or offline | [
"Removes",
"the",
"given",
"resources",
"from",
"the",
"cache",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsJspLoader.java#L602-L615 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/raw/KeyDecoder.java | KeyDecoder.decodeFloatDesc | public static float decodeFloatDesc(byte[] src, int srcOffset)
throws CorruptEncodingException
{
int bits = DataDecoder.decodeFloatBits(src, srcOffset);
if (bits >= 0) {
bits ^= 0x7fffffff;
}
return Float.intBitsToFloat(bits);
} | java | public static float decodeFloatDesc(byte[] src, int srcOffset)
throws CorruptEncodingException
{
int bits = DataDecoder.decodeFloatBits(src, srcOffset);
if (bits >= 0) {
bits ^= 0x7fffffff;
}
return Float.intBitsToFloat(bits);
} | [
"public",
"static",
"float",
"decodeFloatDesc",
"(",
"byte",
"[",
"]",
"src",
",",
"int",
"srcOffset",
")",
"throws",
"CorruptEncodingException",
"{",
"int",
"bits",
"=",
"DataDecoder",
".",
"decodeFloatBits",
"(",
"src",
",",
"srcOffset",
")",
";",
"if",
"(... | Decodes a float from exactly 4 bytes, as encoded for descending order.
@param src source of encoded bytes
@param srcOffset offset into source array
@return float value | [
"Decodes",
"a",
"float",
"from",
"exactly",
"4",
"bytes",
"as",
"encoded",
"for",
"descending",
"order",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyDecoder.java#L276-L284 |
geomajas/geomajas-project-client-gwt2 | impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java | JsonService.getBooleanValue | public static Boolean getBooleanValue(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
Boolean result = null;
if (value != null && value.isBoolean() != null) {
return ((JSONBoolean) value).booleanValue();
}
return result;
} | java | public static Boolean getBooleanValue(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
Boolean result = null;
if (value != null && value.isBoolean() != null) {
return ((JSONBoolean) value).booleanValue();
}
return result;
} | [
"public",
"static",
"Boolean",
"getBooleanValue",
"(",
"JSONObject",
"jsonObject",
",",
"String",
"key",
")",
"throws",
"JSONException",
"{",
"checkArguments",
"(",
"jsonObject",
",",
"key",
")",
";",
"JSONValue",
"value",
"=",
"jsonObject",
".",
"get",
"(",
"... | Get a boolean value from a {@link JSONObject}.
@param jsonObject The object to get the key value from.
@param key The name of the key to search the value for.
@return Returns the value for the key in the object .
@throws JSONException Thrown in case the key could not be found in the JSON object. | [
"Get",
"a",
"boolean",
"value",
"from",
"a",
"{",
"@link",
"JSONObject",
"}",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java#L377-L385 |
PrashamTrivedi/SharedPreferenceInspector | sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/Utils/SharedPreferenceUtils.java | SharedPreferenceUtils.putString | public void putString(String key, String value) {
sharedPreferences.edit().putString(key, value).commit();
} | java | public void putString(String key, String value) {
sharedPreferences.edit().putString(key, value).commit();
} | [
"public",
"void",
"putString",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"sharedPreferences",
".",
"edit",
"(",
")",
".",
"putString",
"(",
"key",
",",
"value",
")",
".",
"commit",
"(",
")",
";",
"}"
] | put the string value to shared preference
@param key
the name of the preference to save
@param value
the name of the preference to modify.
@see android.content.SharedPreferences#edit()#putString(String, String) | [
"put",
"the",
"string",
"value",
"to",
"shared",
"preference"
] | train | https://github.com/PrashamTrivedi/SharedPreferenceInspector/blob/c04d567c4d0fc5e0f8cda308ca85df19c6b3b838/sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/Utils/SharedPreferenceUtils.java#L431-L433 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java | DocTreeScanner.visitValue | @Override
public R visitValue(ValueTree node, P p) {
return scan(node.getReference(), p);
} | java | @Override
public R visitValue(ValueTree node, P p) {
return scan(node.getReference(), p);
} | [
"@",
"Override",
"public",
"R",
"visitValue",
"(",
"ValueTree",
"node",
",",
"P",
"p",
")",
"{",
"return",
"scan",
"(",
"node",
".",
"getReference",
"(",
")",
",",
"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/DocTreeScanner.java#L511-L514 |
EMCECS/nfs-client-java | src/main/java/com/emc/ecs/nfsclient/nfs/nfs3/Nfs3.java | Nfs3.makeReaddirplusRequest | public NfsReaddirplusRequest makeReaddirplusRequest(byte[] directoryFileHandle, long cookie, long cookieverf,
int dircount, int maxcount) throws FileNotFoundException {
return new Nfs3ReaddirplusRequest(directoryFileHandle, cookie, cookieverf, dircount, maxcount, _credential);
} | java | public NfsReaddirplusRequest makeReaddirplusRequest(byte[] directoryFileHandle, long cookie, long cookieverf,
int dircount, int maxcount) throws FileNotFoundException {
return new Nfs3ReaddirplusRequest(directoryFileHandle, cookie, cookieverf, dircount, maxcount, _credential);
} | [
"public",
"NfsReaddirplusRequest",
"makeReaddirplusRequest",
"(",
"byte",
"[",
"]",
"directoryFileHandle",
",",
"long",
"cookie",
",",
"long",
"cookieverf",
",",
"int",
"dircount",
",",
"int",
"maxcount",
")",
"throws",
"FileNotFoundException",
"{",
"return",
"new",... | /* (non-Javadoc)
@see com.emc.ecs.nfsclient.nfs.Nfs#makeReaddirplusRequest(byte[], long, long, int, int) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/EMCECS/nfs-client-java/blob/7ba25bad5052b95cd286052745327729288b2843/src/main/java/com/emc/ecs/nfsclient/nfs/nfs3/Nfs3.java#L1130-L1133 |
undertow-io/undertow | core/src/main/java/io/undertow/server/Connectors.java | Connectors.setExchangeRequestPath | @Deprecated
public static void setExchangeRequestPath(final HttpServerExchange exchange, final String encodedPath, final String charset, boolean decode, final boolean allowEncodedSlash, StringBuilder decodeBuffer) {
try {
setExchangeRequestPath(exchange, encodedPath, charset, decode, allowEncodedSlash, decodeBuffer, exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_PARAMETERS, UndertowOptions.DEFAULT_MAX_PARAMETERS));
} catch (ParameterLimitException e) {
throw new RuntimeException(e);
}
} | java | @Deprecated
public static void setExchangeRequestPath(final HttpServerExchange exchange, final String encodedPath, final String charset, boolean decode, final boolean allowEncodedSlash, StringBuilder decodeBuffer) {
try {
setExchangeRequestPath(exchange, encodedPath, charset, decode, allowEncodedSlash, decodeBuffer, exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_PARAMETERS, UndertowOptions.DEFAULT_MAX_PARAMETERS));
} catch (ParameterLimitException e) {
throw new RuntimeException(e);
}
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"setExchangeRequestPath",
"(",
"final",
"HttpServerExchange",
"exchange",
",",
"final",
"String",
"encodedPath",
",",
"final",
"String",
"charset",
",",
"boolean",
"decode",
",",
"final",
"boolean",
"allowEncodedSlash",
... | Sets the request path and query parameters, decoding to the requested charset.
@param exchange The exchange
@param encodedPath The encoded path
@param charset The charset | [
"Sets",
"the",
"request",
"path",
"and",
"query",
"parameters",
"decoding",
"to",
"the",
"requested",
"charset",
"."
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/Connectors.java#L415-L422 |
apache/groovy | src/main/java/org/codehaus/groovy/transform/stc/AbstractTypeCheckingExtension.java | AbstractTypeCheckingExtension.makeDynamic | public void makeDynamic(PropertyExpression pexp, ClassNode returnType) {
context.getEnclosingMethod().putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE);
pexp.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, returnType);
storeType(pexp, returnType);
setHandled(true);
if (debug) {
LOG.info("Turning '"+pexp.getText()+"' into a dynamic property access of type "+returnType.toString(false));
}
} | java | public void makeDynamic(PropertyExpression pexp, ClassNode returnType) {
context.getEnclosingMethod().putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE);
pexp.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, returnType);
storeType(pexp, returnType);
setHandled(true);
if (debug) {
LOG.info("Turning '"+pexp.getText()+"' into a dynamic property access of type "+returnType.toString(false));
}
} | [
"public",
"void",
"makeDynamic",
"(",
"PropertyExpression",
"pexp",
",",
"ClassNode",
"returnType",
")",
"{",
"context",
".",
"getEnclosingMethod",
"(",
")",
".",
"putNodeMetaData",
"(",
"StaticTypesMarker",
".",
"DYNAMIC_RESOLUTION",
",",
"Boolean",
".",
"TRUE",
... | Instructs the type checker that a property access is dynamic.
Calling this method automatically sets the handled flag to true.
@param pexp the property or attribute expression
@param returnType the type of the property | [
"Instructs",
"the",
"type",
"checker",
"that",
"a",
"property",
"access",
"is",
"dynamic",
".",
"Calling",
"this",
"method",
"automatically",
"sets",
"the",
"handled",
"flag",
"to",
"true",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/AbstractTypeCheckingExtension.java#L306-L314 |
apereo/cas | support/cas-server-support-validation/src/main/java/org/apereo/cas/web/ServiceValidationViewFactory.java | ServiceValidationViewFactory.registerView | public void registerView(final Class ownerClass, final Pair<View, View> view) {
registerView(ownerClass.getSimpleName(), view);
} | java | public void registerView(final Class ownerClass, final Pair<View, View> view) {
registerView(ownerClass.getSimpleName(), view);
} | [
"public",
"void",
"registerView",
"(",
"final",
"Class",
"ownerClass",
",",
"final",
"Pair",
"<",
"View",
",",
"View",
">",
"view",
")",
"{",
"registerView",
"(",
"ownerClass",
".",
"getSimpleName",
"(",
")",
",",
"view",
")",
";",
"}"
] | Register view.
@param ownerClass the owner class
@param view the view | [
"Register",
"view",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-validation/src/main/java/org/apereo/cas/web/ServiceValidationViewFactory.java#L50-L52 |
jenkinsci/jenkins | core/src/main/java/jenkins/util/xml/XMLUtils.java | XMLUtils.safeTransform | public static void safeTransform(@Nonnull Source source, @Nonnull Result out) throws TransformerException,
SAXException {
InputSource src = SAXSource.sourceToInputSource(source);
if (src != null) {
SAXTransformerFactory stFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
stFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
try {
xmlReader.setFeature(FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_GENERAL_ENTITIES, false);
}
catch (SAXException ignored) { /* ignored */ }
try {
xmlReader.setFeature(FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_PARAMETER_ENTITIES, false);
}
catch (SAXException ignored) { /* ignored */ }
// defend against XXE
// the above features should strip out entities - however the feature may not be supported depending
// on the xml implementation used and this is out of our control.
// So add a fallback plan if all else fails.
xmlReader.setEntityResolver(RestrictiveEntityResolver.INSTANCE);
SAXSource saxSource = new SAXSource(xmlReader, src);
_transform(saxSource, out);
}
else {
// for some reason we could not convert source
// this applies to DOMSource and StAXSource - and possibly 3rd party implementations...
// a DOMSource can already be compromised as it is parsed by the time it gets to us.
if (SystemProperties.getBoolean(DISABLED_PROPERTY_NAME)) {
LOGGER.log(Level.WARNING, "XML external entity (XXE) prevention has been disabled by the system " +
"property {0}=true Your system may be vulnerable to XXE attacks.", DISABLED_PROPERTY_NAME);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Caller stack trace: ", new Exception("XXE Prevention caller history"));
}
_transform(source, out);
}
else {
throw new TransformerException("Could not convert source of type " + source.getClass() + " and " +
"XXEPrevention is enabled.");
}
}
} | java | public static void safeTransform(@Nonnull Source source, @Nonnull Result out) throws TransformerException,
SAXException {
InputSource src = SAXSource.sourceToInputSource(source);
if (src != null) {
SAXTransformerFactory stFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
stFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
try {
xmlReader.setFeature(FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_GENERAL_ENTITIES, false);
}
catch (SAXException ignored) { /* ignored */ }
try {
xmlReader.setFeature(FEATURE_HTTP_XML_ORG_SAX_FEATURES_EXTERNAL_PARAMETER_ENTITIES, false);
}
catch (SAXException ignored) { /* ignored */ }
// defend against XXE
// the above features should strip out entities - however the feature may not be supported depending
// on the xml implementation used and this is out of our control.
// So add a fallback plan if all else fails.
xmlReader.setEntityResolver(RestrictiveEntityResolver.INSTANCE);
SAXSource saxSource = new SAXSource(xmlReader, src);
_transform(saxSource, out);
}
else {
// for some reason we could not convert source
// this applies to DOMSource and StAXSource - and possibly 3rd party implementations...
// a DOMSource can already be compromised as it is parsed by the time it gets to us.
if (SystemProperties.getBoolean(DISABLED_PROPERTY_NAME)) {
LOGGER.log(Level.WARNING, "XML external entity (XXE) prevention has been disabled by the system " +
"property {0}=true Your system may be vulnerable to XXE attacks.", DISABLED_PROPERTY_NAME);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Caller stack trace: ", new Exception("XXE Prevention caller history"));
}
_transform(source, out);
}
else {
throw new TransformerException("Could not convert source of type " + source.getClass() + " and " +
"XXEPrevention is enabled.");
}
}
} | [
"public",
"static",
"void",
"safeTransform",
"(",
"@",
"Nonnull",
"Source",
"source",
",",
"@",
"Nonnull",
"Result",
"out",
")",
"throws",
"TransformerException",
",",
"SAXException",
"{",
"InputSource",
"src",
"=",
"SAXSource",
".",
"sourceToInputSource",
"(",
... | Transform the source to the output in a manner that is protected against XXE attacks.
If the transform can not be completed safely then an IOException is thrown.
Note - to turn off safety set the system property <code>disableXXEPrevention</code> to <code>true</code>.
@param source The XML input to transform. - This should be a <code>StreamSource</code> or a
<code>SAXSource</code> in order to be able to prevent XXE attacks.
@param out The Result of transforming the <code>source</code>. | [
"Transform",
"the",
"source",
"to",
"the",
"output",
"in",
"a",
"manner",
"that",
"is",
"protected",
"against",
"XXE",
"attacks",
".",
"If",
"the",
"transform",
"can",
"not",
"be",
"completed",
"safely",
"then",
"an",
"IOException",
"is",
"thrown",
".",
"N... | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/util/xml/XMLUtils.java#L59-L101 |
phax/ph-oton | ph-oton-html/src/main/java/com/helger/html/js/JSEventMap.java | JSEventMap.addHandler | public void addHandler (@Nonnull final EJSEvent eJSEvent, @Nonnull final IHasJSCode aNewHandler)
{
ValueEnforcer.notNull (eJSEvent, "JSEvent");
ValueEnforcer.notNull (aNewHandler, "NewHandler");
CollectingJSCodeProvider aCode = m_aEvents.get (eJSEvent);
if (aCode == null)
{
aCode = new CollectingJSCodeProvider ();
m_aEvents.put (eJSEvent, aCode);
}
aCode.appendFlattened (aNewHandler);
} | java | public void addHandler (@Nonnull final EJSEvent eJSEvent, @Nonnull final IHasJSCode aNewHandler)
{
ValueEnforcer.notNull (eJSEvent, "JSEvent");
ValueEnforcer.notNull (aNewHandler, "NewHandler");
CollectingJSCodeProvider aCode = m_aEvents.get (eJSEvent);
if (aCode == null)
{
aCode = new CollectingJSCodeProvider ();
m_aEvents.put (eJSEvent, aCode);
}
aCode.appendFlattened (aNewHandler);
} | [
"public",
"void",
"addHandler",
"(",
"@",
"Nonnull",
"final",
"EJSEvent",
"eJSEvent",
",",
"@",
"Nonnull",
"final",
"IHasJSCode",
"aNewHandler",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"eJSEvent",
",",
"\"JSEvent\"",
")",
";",
"ValueEnforcer",
".",
"no... | Add an additional handler for the given JS event. If an existing handler is
present, the new handler is appended at the end.
@param eJSEvent
The JS event. May not be <code>null</code>.
@param aNewHandler
The new handler to be added. May not be <code>null</code>. | [
"Add",
"an",
"additional",
"handler",
"for",
"the",
"given",
"JS",
"event",
".",
"If",
"an",
"existing",
"handler",
"is",
"present",
"the",
"new",
"handler",
"is",
"appended",
"at",
"the",
"end",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-html/src/main/java/com/helger/html/js/JSEventMap.java#L53-L65 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/FileTransferHandlerVaadinUpload.java | FileTransferHandlerVaadinUpload.uploadStarted | @Override
public void uploadStarted(final StartedEvent event) {
// reset internal state here because instance is reused for next upload!
resetState();
final SoftwareModule softwareModule = getSelectedSoftwareModule();
this.fileUploadId = new FileUploadId(event.getFilename(), softwareModule);
if (getUploadState().isFileInUploadState(this.fileUploadId)) {
// actual interrupt will happen a bit late so setting the below
// flag
interruptUploadDueToDuplicateFile();
event.getUpload().interruptUpload();
} else {
LOG.info("Uploading file {}", fileUploadId);
publishUploadStarted(fileUploadId);
if (RegexCharacterCollection.stringContainsCharacter(event.getFilename(), ILLEGAL_FILENAME_CHARACTERS)) {
LOG.info("Filename contains illegal characters {} for upload {}", fileUploadId.getFilename(),
fileUploadId);
interruptUploadDueToIllegalFilename();
event.getUpload().interruptUpload();
} else if (isFileAlreadyContainedInSoftwareModule(fileUploadId, softwareModule)) {
LOG.info("File {} already contained in Software Module {}", fileUploadId.getFilename(), softwareModule);
interruptUploadDueToDuplicateFile();
event.getUpload().interruptUpload();
}
}
} | java | @Override
public void uploadStarted(final StartedEvent event) {
// reset internal state here because instance is reused for next upload!
resetState();
final SoftwareModule softwareModule = getSelectedSoftwareModule();
this.fileUploadId = new FileUploadId(event.getFilename(), softwareModule);
if (getUploadState().isFileInUploadState(this.fileUploadId)) {
// actual interrupt will happen a bit late so setting the below
// flag
interruptUploadDueToDuplicateFile();
event.getUpload().interruptUpload();
} else {
LOG.info("Uploading file {}", fileUploadId);
publishUploadStarted(fileUploadId);
if (RegexCharacterCollection.stringContainsCharacter(event.getFilename(), ILLEGAL_FILENAME_CHARACTERS)) {
LOG.info("Filename contains illegal characters {} for upload {}", fileUploadId.getFilename(),
fileUploadId);
interruptUploadDueToIllegalFilename();
event.getUpload().interruptUpload();
} else if (isFileAlreadyContainedInSoftwareModule(fileUploadId, softwareModule)) {
LOG.info("File {} already contained in Software Module {}", fileUploadId.getFilename(), softwareModule);
interruptUploadDueToDuplicateFile();
event.getUpload().interruptUpload();
}
}
} | [
"@",
"Override",
"public",
"void",
"uploadStarted",
"(",
"final",
"StartedEvent",
"event",
")",
"{",
"// reset internal state here because instance is reused for next upload!",
"resetState",
"(",
")",
";",
"final",
"SoftwareModule",
"softwareModule",
"=",
"getSelectedSoftware... | Upload started for {@link Upload} variant.
@see com.vaadin.ui.Upload.StartedListener#uploadStarted(com.vaadin.ui.Upload.StartedEvent) | [
"Upload",
"started",
"for",
"{",
"@link",
"Upload",
"}",
"variant",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/FileTransferHandlerVaadinUpload.java#L69-L98 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListAccountRelPersistenceImpl.java | CommercePriceListAccountRelPersistenceImpl.findAll | @Override
public List<CommercePriceListAccountRel> findAll(int start, int end) {
return findAll(start, end, null);
} | java | @Override
public List<CommercePriceListAccountRel> findAll(int start, int end) {
return findAll(start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommercePriceListAccountRel",
">",
"findAll",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findAll",
"(",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the commerce price list account rels.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommercePriceListAccountRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of commerce price list account rels
@param end the upper bound of the range of commerce price list account rels (not inclusive)
@return the range of commerce price list account rels | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"price",
"list",
"account",
"rels",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListAccountRelPersistenceImpl.java#L2974-L2977 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/GrahamScanConvexHull2D.java | GrahamScanConvexHull2D.isConvex | private boolean isConvex(double[] a, double[] b, double[] c) {
// We're using factor to improve numerical contrast for small polygons.
double area = (b[0] - a[0]) * factor * (c[1] - a[1]) - (c[0] - a[0]) * factor * (b[1] - a[1]);
return (-1e-13 < area && area < 1e-13) ? (mdist(b, c) > mdist(a, b) + mdist(a, c)) : (area < 0);
} | java | private boolean isConvex(double[] a, double[] b, double[] c) {
// We're using factor to improve numerical contrast for small polygons.
double area = (b[0] - a[0]) * factor * (c[1] - a[1]) - (c[0] - a[0]) * factor * (b[1] - a[1]);
return (-1e-13 < area && area < 1e-13) ? (mdist(b, c) > mdist(a, b) + mdist(a, c)) : (area < 0);
} | [
"private",
"boolean",
"isConvex",
"(",
"double",
"[",
"]",
"a",
",",
"double",
"[",
"]",
"b",
",",
"double",
"[",
"]",
"c",
")",
"{",
"// We're using factor to improve numerical contrast for small polygons.",
"double",
"area",
"=",
"(",
"b",
"[",
"0",
"]",
"... | Simple convexity test.
@param a double[] A
@param b double[] B
@param c double[] C
@return convexity | [
"Simple",
"convexity",
"test",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/GrahamScanConvexHull2D.java#L223-L227 |
mojohaus/jaxb2-maven-plugin | src/main/java/org/codehaus/mojo/jaxb2/shared/filters/Filters.java | Filters.noFilterMatches | public static <T> boolean noFilterMatches(final T object, final List<Filter<T>> filters) {
// Check sanity
Validate.notNull(filters, "filters");
boolean matchedAtLeastOnce = false;
for (Filter<T> current : filters) {
if (current.accept(object)) {
matchedAtLeastOnce = true;
}
}
// All done.
return !matchedAtLeastOnce;
} | java | public static <T> boolean noFilterMatches(final T object, final List<Filter<T>> filters) {
// Check sanity
Validate.notNull(filters, "filters");
boolean matchedAtLeastOnce = false;
for (Filter<T> current : filters) {
if (current.accept(object)) {
matchedAtLeastOnce = true;
}
}
// All done.
return !matchedAtLeastOnce;
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"noFilterMatches",
"(",
"final",
"T",
"object",
",",
"final",
"List",
"<",
"Filter",
"<",
"T",
">",
">",
"filters",
")",
"{",
"// Check sanity",
"Validate",
".",
"notNull",
"(",
"filters",
",",
"\"filters\"",
... | Algorithms for rejecting the supplied object if at least one of the supplied Filters rejects it.
@param object The object to accept (or not).
@param filters The non-null list of Filters to examine the supplied object.
@param <T> The Filter type.
@return {@code true} if at least one of the filters return false from its accept method.
@see Filter#accept(Object) | [
"Algorithms",
"for",
"rejecting",
"the",
"supplied",
"object",
"if",
"at",
"least",
"one",
"of",
"the",
"supplied",
"Filters",
"rejects",
"it",
"."
] | train | https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/Filters.java#L103-L117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.