repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
mojohaus/jaxb2-maven-plugin | src/main/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilities.java | FileSystemUtilities.getFileFor | public static File getFileFor(final URL anURL, final String encoding) {
// Check sanity
Validate.notNull(anURL, "anURL");
Validate.notNull(encoding, "encoding");
final String protocol = anURL.getProtocol();
File toReturn = null;
if ("file".equalsIgnoreCase(protocol)) {
try {
final String decodedPath = URLDecoder.decode(anURL.getPath(), encoding);
toReturn = new File(decodedPath);
} catch (Exception e) {
throw new IllegalArgumentException("Could not get the File for [" + anURL + "]", e);
}
} else if ("jar".equalsIgnoreCase(protocol)) {
try {
// Decode the JAR
final String tmp = URLDecoder.decode(anURL.getFile(), encoding);
// JAR URLs generally contain layered protocols, such as:
// jar:file:/some/path/to/nazgul-tools-validation-aspect-4.0.2.jar!/the/package/ValidationAspect.class
final URL innerURL = new URL(tmp);
// We can handle File protocol URLs here.
if ("file".equalsIgnoreCase(innerURL.getProtocol())) {
// Peel off the inner protocol
final String innerUrlPath = innerURL.getPath();
final String filePath = innerUrlPath.contains("!")
? innerUrlPath.substring(0, innerUrlPath.indexOf("!"))
: innerUrlPath;
toReturn = new File(URLDecoder.decode(filePath, encoding));
}
} catch (Exception e) {
throw new IllegalArgumentException("Could not get the File for [" + anURL + "]", e);
}
}
// All done.
return toReturn;
} | java | public static File getFileFor(final URL anURL, final String encoding) {
// Check sanity
Validate.notNull(anURL, "anURL");
Validate.notNull(encoding, "encoding");
final String protocol = anURL.getProtocol();
File toReturn = null;
if ("file".equalsIgnoreCase(protocol)) {
try {
final String decodedPath = URLDecoder.decode(anURL.getPath(), encoding);
toReturn = new File(decodedPath);
} catch (Exception e) {
throw new IllegalArgumentException("Could not get the File for [" + anURL + "]", e);
}
} else if ("jar".equalsIgnoreCase(protocol)) {
try {
// Decode the JAR
final String tmp = URLDecoder.decode(anURL.getFile(), encoding);
// JAR URLs generally contain layered protocols, such as:
// jar:file:/some/path/to/nazgul-tools-validation-aspect-4.0.2.jar!/the/package/ValidationAspect.class
final URL innerURL = new URL(tmp);
// We can handle File protocol URLs here.
if ("file".equalsIgnoreCase(innerURL.getProtocol())) {
// Peel off the inner protocol
final String innerUrlPath = innerURL.getPath();
final String filePath = innerUrlPath.contains("!")
? innerUrlPath.substring(0, innerUrlPath.indexOf("!"))
: innerUrlPath;
toReturn = new File(URLDecoder.decode(filePath, encoding));
}
} catch (Exception e) {
throw new IllegalArgumentException("Could not get the File for [" + anURL + "]", e);
}
}
// All done.
return toReturn;
} | [
"public",
"static",
"File",
"getFileFor",
"(",
"final",
"URL",
"anURL",
",",
"final",
"String",
"encoding",
")",
"{",
"// Check sanity",
"Validate",
".",
"notNull",
"(",
"anURL",
",",
"\"anURL\"",
")",
";",
"Validate",
".",
"notNull",
"(",
"encoding",
",",
... | Acquires the file for a supplied URL, provided that its protocol is is either a file or a jar.
@param anURL a non-null URL.
@param encoding The encoding to be used by the URLDecoder to decode the path found.
@return The File pointing to the supplied URL, for file or jar protocol URLs and null otherwise. | [
"Acquires",
"the",
"file",
"for",
"a",
"supplied",
"URL",
"provided",
"that",
"its",
"protocol",
"is",
"is",
"either",
"a",
"file",
"or",
"a",
"jar",
"."
] | train | https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilities.java#L193-L236 |
threerings/narya | tools/src/main/java/com/threerings/presents/tools/GeneratedSourceMerger.java | GeneratedSourceMerger.merge | public String merge (String newlyGenerated, String previouslyGenerated)
throws Exception
{
// Extract the generated section names from the output and make sure they're all matched
Map<String, Section> sections = Maps.newLinkedHashMap();
Matcher m = _sectionDelimiter.matcher(newlyGenerated);
while (m.find()) {
Section section = extractGeneratedSection(m, newlyGenerated);
Preconditions.checkArgument(!sections.containsKey(section.name),
"Section '%s' used more than once", section.name);
sections.put(section.name, section);
}
// Merge with the previously generated source
StringBuilder merged = new StringBuilder();
m = _sectionDelimiter.matcher(previouslyGenerated);
int currentStart = 0;
while (m.find()) {
merged.append(previouslyGenerated.substring(currentStart, m.start()));
Section existingSection = extractGeneratedSection(m, previouslyGenerated);
Section newSection = sections.remove(existingSection.name);
if (newSection == null) {
// Allow generated sections to be dropped in the template, but warn in case
// something odd's happening
System.err.println("Dropping previously generated section '" + m.group(1)
+ "' that's no longer generated by the template");
} else if (existingSection.disabled) {
// If the existing code disables this generation, add that disabled comment
merged.append(existingSection.contents);
} else {
// Otherwise pop in the newly generated code in the place of what was there before
merged.append(newSection.contents);
}
currentStart = m.end();
}
// Add generated sections that weren't present in the old output before the last
// non-generated code. It's a 50-50 shot, so warn when this happens
for (Section newSection : sections.values()) {
System.err.println("Adding previously missing generated section '"
+ newSection.name + "' before the last non-generated text");
merged.append(newSection.contents);
}
// Add any text past the last previously generated section
merged.append(previouslyGenerated.substring(currentStart));
return merged.toString();
} | java | public String merge (String newlyGenerated, String previouslyGenerated)
throws Exception
{
// Extract the generated section names from the output and make sure they're all matched
Map<String, Section> sections = Maps.newLinkedHashMap();
Matcher m = _sectionDelimiter.matcher(newlyGenerated);
while (m.find()) {
Section section = extractGeneratedSection(m, newlyGenerated);
Preconditions.checkArgument(!sections.containsKey(section.name),
"Section '%s' used more than once", section.name);
sections.put(section.name, section);
}
// Merge with the previously generated source
StringBuilder merged = new StringBuilder();
m = _sectionDelimiter.matcher(previouslyGenerated);
int currentStart = 0;
while (m.find()) {
merged.append(previouslyGenerated.substring(currentStart, m.start()));
Section existingSection = extractGeneratedSection(m, previouslyGenerated);
Section newSection = sections.remove(existingSection.name);
if (newSection == null) {
// Allow generated sections to be dropped in the template, but warn in case
// something odd's happening
System.err.println("Dropping previously generated section '" + m.group(1)
+ "' that's no longer generated by the template");
} else if (existingSection.disabled) {
// If the existing code disables this generation, add that disabled comment
merged.append(existingSection.contents);
} else {
// Otherwise pop in the newly generated code in the place of what was there before
merged.append(newSection.contents);
}
currentStart = m.end();
}
// Add generated sections that weren't present in the old output before the last
// non-generated code. It's a 50-50 shot, so warn when this happens
for (Section newSection : sections.values()) {
System.err.println("Adding previously missing generated section '"
+ newSection.name + "' before the last non-generated text");
merged.append(newSection.contents);
}
// Add any text past the last previously generated section
merged.append(previouslyGenerated.substring(currentStart));
return merged.toString();
} | [
"public",
"String",
"merge",
"(",
"String",
"newlyGenerated",
",",
"String",
"previouslyGenerated",
")",
"throws",
"Exception",
"{",
"// Extract the generated section names from the output and make sure they're all matched",
"Map",
"<",
"String",
",",
"Section",
">",
"section... | Returns <code>previouslyGenerated</code> with marked sections updated from the same marked
sections in <code>newlyGenerated</code>. Everything outside these sections in
<code>previouslyGenerated</code> is returned as is. A marked section starts with <code>//
GENERATED {name} START</code> and ends with <code>// GENERATED {name} END</code><p>
If <code>previouslyGenerated</code> has a generated section replaced with <code>//
GENERATED {name} DISABLED</code>, that section will no longer be updated. | [
"Returns",
"<code",
">",
"previouslyGenerated<",
"/",
"code",
">",
"with",
"marked",
"sections",
"updated",
"from",
"the",
"same",
"marked",
"sections",
"in",
"<code",
">",
"newlyGenerated<",
"/",
"code",
">",
".",
"Everything",
"outside",
"these",
"sections",
... | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/GeneratedSourceMerger.java#L46-L92 |
powermock/powermock | powermock-core/src/main/java/org/powermock/core/MockRepository.java | MockRepository.putMethodToStub | public static synchronized Object putMethodToStub(Method method, Object value) {
return substituteReturnValues.put(method, value);
} | java | public static synchronized Object putMethodToStub(Method method, Object value) {
return substituteReturnValues.put(method, value);
} | [
"public",
"static",
"synchronized",
"Object",
"putMethodToStub",
"(",
"Method",
"method",
",",
"Object",
"value",
")",
"{",
"return",
"substituteReturnValues",
".",
"put",
"(",
"method",
",",
"value",
")",
";",
"}"
] | Set a substitute return value for a method. Whenever this method will be
called the {@code value} will be returned instead.
@return The previous substitute value if any. | [
"Set",
"a",
"substitute",
"return",
"value",
"for",
"a",
"method",
".",
"Whenever",
"this",
"method",
"will",
"be",
"called",
"the",
"{",
"@code",
"value",
"}",
"will",
"be",
"returned",
"instead",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-core/src/main/java/org/powermock/core/MockRepository.java#L364-L366 |
glyptodon/guacamole-client | extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/tunnel/RestrictedGuacamoleTunnelService.java | RestrictedGuacamoleTunnelService.tryIncrement | private boolean tryIncrement(AtomicInteger counter, int max) {
// Repeatedly attempt to increment the given AtomicInteger until we
// explicitly succeed or explicitly fail
while (true) {
// Get current value
int count = counter.get();
// Bail out if the maximum has already been reached
if (count >= max && max != 0)
return false;
// Attempt to increment
if (counter.compareAndSet(count, count+1))
return true;
// Try again if unsuccessful
}
} | java | private boolean tryIncrement(AtomicInteger counter, int max) {
// Repeatedly attempt to increment the given AtomicInteger until we
// explicitly succeed or explicitly fail
while (true) {
// Get current value
int count = counter.get();
// Bail out if the maximum has already been reached
if (count >= max && max != 0)
return false;
// Attempt to increment
if (counter.compareAndSet(count, count+1))
return true;
// Try again if unsuccessful
}
} | [
"private",
"boolean",
"tryIncrement",
"(",
"AtomicInteger",
"counter",
",",
"int",
"max",
")",
"{",
"// Repeatedly attempt to increment the given AtomicInteger until we",
"// explicitly succeed or explicitly fail",
"while",
"(",
"true",
")",
"{",
"// Get current value",
"int",
... | Attempts to increment the given AtomicInteger without exceeding the
specified maximum value. If the AtomicInteger cannot be incremented
without exceeding the maximum, false is returned.
@param counter
The AtomicInteger to attempt to increment.
@param max
The maximum value that the given AtomicInteger should contain, or
zero if no limit applies.
@return
true if the AtomicInteger was successfully incremented without
exceeding the specified maximum, false if the AtomicInteger could
not be incremented. | [
"Attempts",
"to",
"increment",
"the",
"given",
"AtomicInteger",
"without",
"exceeding",
"the",
"specified",
"maximum",
"value",
".",
"If",
"the",
"AtomicInteger",
"cannot",
"be",
"incremented",
"without",
"exceeding",
"the",
"maximum",
"false",
"is",
"returned",
"... | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/tunnel/RestrictedGuacamoleTunnelService.java#L149-L170 |
alipay/sofa-rpc | core/api/src/main/java/com/alipay/sofa/rpc/transport/ChannelContext.java | ChannelContext.invalidateHeadCache | public void invalidateHeadCache(Byte key, String value) {
if (headerCache != null && headerCache.containsKey(key)) {
String old = headerCache.get(key);
if (!old.equals(value)) {
throw new SofaRpcRuntimeException("Value of old is not match current");
}
headerCache.remove(key);
}
} | java | public void invalidateHeadCache(Byte key, String value) {
if (headerCache != null && headerCache.containsKey(key)) {
String old = headerCache.get(key);
if (!old.equals(value)) {
throw new SofaRpcRuntimeException("Value of old is not match current");
}
headerCache.remove(key);
}
} | [
"public",
"void",
"invalidateHeadCache",
"(",
"Byte",
"key",
",",
"String",
"value",
")",
"{",
"if",
"(",
"headerCache",
"!=",
"null",
"&&",
"headerCache",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"String",
"old",
"=",
"headerCache",
".",
"get",
"(... | Invalidate head cache.
@param key the key
@param value the value | [
"Invalidate",
"head",
"cache",
"."
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/transport/ChannelContext.java#L83-L91 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/ItemDataMoveVisitor.java | ItemDataMoveVisitor.createStates | private void createStates(PropertyData prevProperty, PropertyData newProperty)
{
ReadOnlyChangedSizeHandler delChangedSizeHandler = null;
ReadOnlyChangedSizeHandler addChangedSizeHandler = null;
if (prevProperty instanceof PersistedPropertyData)
{
PersistedPropertyData persistedPrevProp = (PersistedPropertyData)prevProperty;
delChangedSizeHandler = new ReadOnlyChangedSizeHandler(0, persistedPrevProp.getPersistedSize());
addChangedSizeHandler = new ReadOnlyChangedSizeHandler(persistedPrevProp.getPersistedSize(), 0);
}
addStates.add(new ItemState(newProperty, ItemState.RENAMED, false, ancestorToSave, false, false, null,
addChangedSizeHandler));
deleteStates.add(new ItemState(prevProperty, ItemState.DELETED, false, ancestorToSave, false, false, null,
delChangedSizeHandler));
} | java | private void createStates(PropertyData prevProperty, PropertyData newProperty)
{
ReadOnlyChangedSizeHandler delChangedSizeHandler = null;
ReadOnlyChangedSizeHandler addChangedSizeHandler = null;
if (prevProperty instanceof PersistedPropertyData)
{
PersistedPropertyData persistedPrevProp = (PersistedPropertyData)prevProperty;
delChangedSizeHandler = new ReadOnlyChangedSizeHandler(0, persistedPrevProp.getPersistedSize());
addChangedSizeHandler = new ReadOnlyChangedSizeHandler(persistedPrevProp.getPersistedSize(), 0);
}
addStates.add(new ItemState(newProperty, ItemState.RENAMED, false, ancestorToSave, false, false, null,
addChangedSizeHandler));
deleteStates.add(new ItemState(prevProperty, ItemState.DELETED, false, ancestorToSave, false, false, null,
delChangedSizeHandler));
} | [
"private",
"void",
"createStates",
"(",
"PropertyData",
"prevProperty",
",",
"PropertyData",
"newProperty",
")",
"{",
"ReadOnlyChangedSizeHandler",
"delChangedSizeHandler",
"=",
"null",
";",
"ReadOnlyChangedSizeHandler",
"addChangedSizeHandler",
"=",
"null",
";",
"if",
"(... | Creates item states and adds them to changes log. If possible tries
to inject {@link ChangedSizeHandler} to manage data size changes.
@param prevProperty
{@link PropertyData} currently exists into storage.
@param newProperty
{@link PropertyData} will be saved to the storage | [
"Creates",
"item",
"states",
"and",
"adds",
"them",
"to",
"changes",
"log",
".",
"If",
"possible",
"tries",
"to",
"inject",
"{",
"@link",
"ChangedSizeHandler",
"}",
"to",
"manage",
"data",
"size",
"changes",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/ItemDataMoveVisitor.java#L355-L372 |
doanduyhai/Achilles | achilles-core/src/main/java/info/archinnov/achilles/bootstrap/AbstractManagerFactoryBuilder.java | AbstractManagerFactoryBuilder.withRuntimeCodec | public <FROM, TO> T withRuntimeCodec(CodecSignature<FROM, TO> codecSignature, Codec<FROM, TO> codec) {
if (!configMap.containsKey(RUNTIME_CODECS)) {
configMap.put(RUNTIME_CODECS, new HashMap<CodecSignature<?, ?>, Codec<?, ?>>());
}
configMap.<Map<CodecSignature<?, ?>, Codec<?, ?>>>getTyped(RUNTIME_CODECS).put(codecSignature, codec);
return getThis();
} | java | public <FROM, TO> T withRuntimeCodec(CodecSignature<FROM, TO> codecSignature, Codec<FROM, TO> codec) {
if (!configMap.containsKey(RUNTIME_CODECS)) {
configMap.put(RUNTIME_CODECS, new HashMap<CodecSignature<?, ?>, Codec<?, ?>>());
}
configMap.<Map<CodecSignature<?, ?>, Codec<?, ?>>>getTyped(RUNTIME_CODECS).put(codecSignature, codec);
return getThis();
} | [
"public",
"<",
"FROM",
",",
"TO",
">",
"T",
"withRuntimeCodec",
"(",
"CodecSignature",
"<",
"FROM",
",",
"TO",
">",
"codecSignature",
",",
"Codec",
"<",
"FROM",
",",
"TO",
">",
"codec",
")",
"{",
"if",
"(",
"!",
"configMap",
".",
"containsKey",
"(",
... | Specify a runtime codec to register with Achilles
<br/>
<pre class="code"><code class="java">
<strong>final Codec<MyBean, String> beanCodec = new .... // Create your codec with initialization logic here</strong>
<strong>final Codec<MyEnum, String> enumCodec = new .... // Create your codec with initialization logic here</strong>
final CodecSignature<MyBean, String> codecSignature1 = new CodecSignature(MyBean.class, String.class);
final CodecSignature<MyBean, String> codecSignature2 = new CodecSignature(MyEnum.class, String.class);
final Map<CodecSignature<?, ?>, Codec<?, ?>> runtimeCodecs = new HashMap<>();
runtimeCodecs.put(codecSignature1, beanCodec);
runtimeCodecs.put(codecSignature2, enumCodec);
ManagerFactory factory = ManagerFactoryBuilder
.builder(cluster)
...
<strong>.withRuntimeCodec(codecSignature1, beanCodec)</strong>
<strong>.withRuntimeCodec(codecSignature2, enumCodec)</strong>
.build();
</code></pre>
<br/>
<br/>
<em>Remark: you can call this method as many time as there are runtime codecs to be registered</em>
@param codecSignature codec signature, defined by sourceType,targetType and optionally codecName
@param codec runtime codec
@return ManagerFactoryBuilder | [
"Specify",
"a",
"runtime",
"codec",
"to",
"register",
"with",
"Achilles",
"<br",
"/",
">",
"<pre",
"class",
"=",
"code",
">",
"<code",
"class",
"=",
"java",
">"
] | train | https://github.com/doanduyhai/Achilles/blob/8281c33100e72c993e570592ae1a5306afac6813/achilles-core/src/main/java/info/archinnov/achilles/bootstrap/AbstractManagerFactoryBuilder.java#L506-L512 |
graphql-java/graphql-java | src/main/java/graphql/schema/idl/TypeRuntimeWiring.java | TypeRuntimeWiring.newTypeWiring | public static TypeRuntimeWiring newTypeWiring(String typeName, UnaryOperator<Builder> builderFunction) {
return builderFunction.apply(newTypeWiring(typeName)).build();
} | java | public static TypeRuntimeWiring newTypeWiring(String typeName, UnaryOperator<Builder> builderFunction) {
return builderFunction.apply(newTypeWiring(typeName)).build();
} | [
"public",
"static",
"TypeRuntimeWiring",
"newTypeWiring",
"(",
"String",
"typeName",
",",
"UnaryOperator",
"<",
"Builder",
">",
"builderFunction",
")",
"{",
"return",
"builderFunction",
".",
"apply",
"(",
"newTypeWiring",
"(",
"typeName",
")",
")",
".",
"build",
... | This form allows a lambda to be used as the builder
@param typeName the name of the type to wire
@param builderFunction a function that will be given the builder to use
@return the same builder back please | [
"This",
"form",
"allows",
"a",
"lambda",
"to",
"be",
"used",
"as",
"the",
"builder"
] | train | https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/schema/idl/TypeRuntimeWiring.java#L53-L55 |
waldheinz/fat32-lib | src/main/java/de/waldheinz/fs/fat/DosUtils.java | DosUtils.decodeDateTime | public static long decodeDateTime(int dosDate, int dosTime) {
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, (dosTime & 0x1f) * 2);
cal.set(Calendar.MINUTE, (dosTime >> 5) & 0x3f);
cal.set(Calendar.HOUR_OF_DAY, dosTime >> 11);
cal.set(Calendar.DATE, dosDate & 0x1f);
cal.set(Calendar.MONTH, ((dosDate >> 5) & 0x0f) - 1);
cal.set(Calendar.YEAR, 1980 + (dosDate >> 9));
return cal.getTimeInMillis();
} | java | public static long decodeDateTime(int dosDate, int dosTime) {
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, (dosTime & 0x1f) * 2);
cal.set(Calendar.MINUTE, (dosTime >> 5) & 0x3f);
cal.set(Calendar.HOUR_OF_DAY, dosTime >> 11);
cal.set(Calendar.DATE, dosDate & 0x1f);
cal.set(Calendar.MONTH, ((dosDate >> 5) & 0x0f) - 1);
cal.set(Calendar.YEAR, 1980 + (dosDate >> 9));
return cal.getTimeInMillis();
} | [
"public",
"static",
"long",
"decodeDateTime",
"(",
"int",
"dosDate",
",",
"int",
"dosTime",
")",
"{",
"final",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"cal",
".",
"set",
"(",
"Calendar",
".",
"MILLISECOND",
",",
"0",
")",
... | Decode a 16-bit encoded DOS date/time into a java date/time.
@param dosDate
@param dosTime
@return long | [
"Decode",
"a",
"16",
"-",
"bit",
"encoded",
"DOS",
"date",
"/",
"time",
"into",
"a",
"java",
"date",
"/",
"time",
"."
] | train | https://github.com/waldheinz/fat32-lib/blob/3d8f1a986339573576e02eb0b6ea49bfdc9cce26/src/main/java/de/waldheinz/fs/fat/DosUtils.java#L41-L54 |
LearnLib/learnlib | algorithms/active/lstar/src/main/java/de/learnlib/algorithms/lstar/AbstractLStar.java | AbstractLStar.completeConsistentTable | protected boolean completeConsistentTable(List<List<Row<I>>> unclosed, boolean checkConsistency) {
boolean refined = false;
List<List<Row<I>>> unclosedIter = unclosed;
do {
while (!unclosedIter.isEmpty()) {
List<Row<I>> closingRows = selectClosingRows(unclosedIter);
unclosedIter = table.toShortPrefixes(closingRows, oracle);
refined = true;
}
if (checkConsistency) {
Inconsistency<I> incons;
do {
incons = table.findInconsistency();
if (incons != null) {
Word<I> newSuffix = analyzeInconsistency(incons);
unclosedIter = table.addSuffix(newSuffix, oracle);
}
} while (unclosedIter.isEmpty() && (incons != null));
}
} while (!unclosedIter.isEmpty());
return refined;
} | java | protected boolean completeConsistentTable(List<List<Row<I>>> unclosed, boolean checkConsistency) {
boolean refined = false;
List<List<Row<I>>> unclosedIter = unclosed;
do {
while (!unclosedIter.isEmpty()) {
List<Row<I>> closingRows = selectClosingRows(unclosedIter);
unclosedIter = table.toShortPrefixes(closingRows, oracle);
refined = true;
}
if (checkConsistency) {
Inconsistency<I> incons;
do {
incons = table.findInconsistency();
if (incons != null) {
Word<I> newSuffix = analyzeInconsistency(incons);
unclosedIter = table.addSuffix(newSuffix, oracle);
}
} while (unclosedIter.isEmpty() && (incons != null));
}
} while (!unclosedIter.isEmpty());
return refined;
} | [
"protected",
"boolean",
"completeConsistentTable",
"(",
"List",
"<",
"List",
"<",
"Row",
"<",
"I",
">",
">",
">",
"unclosed",
",",
"boolean",
"checkConsistency",
")",
"{",
"boolean",
"refined",
"=",
"false",
";",
"List",
"<",
"List",
"<",
"Row",
"<",
"I"... | Iteratedly checks for unclosedness and inconsistencies in the table, and fixes any occurrences thereof. This
process is repeated until the observation table is both closed and consistent.
@param unclosed
the unclosed rows (equivalence classes) to start with. | [
"Iteratedly",
"checks",
"for",
"unclosedness",
"and",
"inconsistencies",
"in",
"the",
"table",
"and",
"fixes",
"any",
"occurrences",
"thereof",
".",
"This",
"process",
"is",
"repeated",
"until",
"the",
"observation",
"table",
"is",
"both",
"closed",
"and",
"cons... | train | https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/algorithms/active/lstar/src/main/java/de/learnlib/algorithms/lstar/AbstractLStar.java#L136-L160 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCircuitPeeringsInner.java | ExpressRouteCircuitPeeringsInner.beginCreateOrUpdateAsync | public Observable<ExpressRouteCircuitPeeringInner> beginCreateOrUpdateAsync(String resourceGroupName, String circuitName, String peeringName, ExpressRouteCircuitPeeringInner peeringParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, peeringParameters).map(new Func1<ServiceResponse<ExpressRouteCircuitPeeringInner>, ExpressRouteCircuitPeeringInner>() {
@Override
public ExpressRouteCircuitPeeringInner call(ServiceResponse<ExpressRouteCircuitPeeringInner> response) {
return response.body();
}
});
} | java | public Observable<ExpressRouteCircuitPeeringInner> beginCreateOrUpdateAsync(String resourceGroupName, String circuitName, String peeringName, ExpressRouteCircuitPeeringInner peeringParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, peeringParameters).map(new Func1<ServiceResponse<ExpressRouteCircuitPeeringInner>, ExpressRouteCircuitPeeringInner>() {
@Override
public ExpressRouteCircuitPeeringInner call(ServiceResponse<ExpressRouteCircuitPeeringInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ExpressRouteCircuitPeeringInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"circuitName",
",",
"String",
"peeringName",
",",
"ExpressRouteCircuitPeeringInner",
"peeringParameters",
")",
"{",
"return",
... | Creates or updates a peering in the specified express route circuits.
@param resourceGroupName The name of the resource group.
@param circuitName The name of the express route circuit.
@param peeringName The name of the peering.
@param peeringParameters Parameters supplied to the create or update express route circuit peering operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ExpressRouteCircuitPeeringInner object | [
"Creates",
"or",
"updates",
"a",
"peering",
"in",
"the",
"specified",
"express",
"route",
"circuits",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCircuitPeeringsInner.java#L473-L480 |
axibase/atsd-api-java | src/main/java/com/axibase/tsd/client/MetaDataService.java | MetaDataService.retrieveMetricSeries | public List<Series> retrieveMetricSeries(String metricName, String entityName) {
return retrieveMetricSeries(metricName, Collections.singletonMap("entity", entityName));
} | java | public List<Series> retrieveMetricSeries(String metricName, String entityName) {
return retrieveMetricSeries(metricName, Collections.singletonMap("entity", entityName));
} | [
"public",
"List",
"<",
"Series",
">",
"retrieveMetricSeries",
"(",
"String",
"metricName",
",",
"String",
"entityName",
")",
"{",
"return",
"retrieveMetricSeries",
"(",
"metricName",
",",
"Collections",
".",
"singletonMap",
"(",
"\"entity\"",
",",
"entityName",
")... | Retrieve series list of the specified metric
@param metricName metric name
@param entityName entity name's filter
@return list of series | [
"Retrieve",
"series",
"list",
"of",
"the",
"specified",
"metric"
] | train | https://github.com/axibase/atsd-api-java/blob/63a0767d08b202dad2ebef4372ff947d6fba0246/src/main/java/com/axibase/tsd/client/MetaDataService.java#L596-L598 |
xmlet/XsdAsmFaster | src/main/java/org/xmlet/xsdasmfaster/classes/infrastructure/RestrictionValidator.java | RestrictionValidator.validateFractionDigits | public static void validateFractionDigits(int fractionDigits, double value){
if (value != ((int) value)){
String doubleValue = String.valueOf(value);
int numberOfFractionDigits = doubleValue.substring(doubleValue.indexOf(',')).length();
if (numberOfFractionDigits > fractionDigits){
throw new RestrictionViolationException("Violation of fractionDigits restriction, value should have a maximum of " + fractionDigits + " decimal places.");
}
}
} | java | public static void validateFractionDigits(int fractionDigits, double value){
if (value != ((int) value)){
String doubleValue = String.valueOf(value);
int numberOfFractionDigits = doubleValue.substring(doubleValue.indexOf(',')).length();
if (numberOfFractionDigits > fractionDigits){
throw new RestrictionViolationException("Violation of fractionDigits restriction, value should have a maximum of " + fractionDigits + " decimal places.");
}
}
} | [
"public",
"static",
"void",
"validateFractionDigits",
"(",
"int",
"fractionDigits",
",",
"double",
"value",
")",
"{",
"if",
"(",
"value",
"!=",
"(",
"(",
"int",
")",
"value",
")",
")",
"{",
"String",
"doubleValue",
"=",
"String",
".",
"valueOf",
"(",
"va... | Validates the number of fraction digits present in the {@code value} received.
@param fractionDigits The allowed number of fraction digits.
@param value The {@link Double} to be validated. | [
"Validates",
"the",
"number",
"of",
"fraction",
"digits",
"present",
"in",
"the",
"{"
] | train | https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/infrastructure/RestrictionValidator.java#L18-L28 |
nextreports/nextreports-server | src/ro/nextreports/server/report/jasper/JasperReportsUtil.java | JasperReportsUtil.getValueClassName | public static String getValueClassName(StorageService storageService, DataSource ds, String sql) throws Exception {
try {
if ((sql != null) && !sql.trim().equals("")) {
Connection con = null;
try {
con = ConnectionUtil.createConnection(storageService, ds);
int index = sql.toLowerCase().indexOf("where");
int index2 = sql.indexOf("${");
String newSql = sql;
if ((index > 0) && (index2 > 0)) {
newSql = sql.substring(0, index) + " where 1 = 0";
}
QueryUtil qu = new QueryUtil(con, DialectUtil.getDialect(con));
List<NameType> list = qu.executeQueryForColumnNames(newSql);
//System.out.println("*** newType=" + list.get(0).getType());
return list.get(0).getType();
} finally {
ConnectionUtil.closeConnection(con);
}
}
} catch (Exception ex) {
ex.printStackTrace();
LOG.error(ex.getMessage(), ex);
throw ex;
}
return null;
} | java | public static String getValueClassName(StorageService storageService, DataSource ds, String sql) throws Exception {
try {
if ((sql != null) && !sql.trim().equals("")) {
Connection con = null;
try {
con = ConnectionUtil.createConnection(storageService, ds);
int index = sql.toLowerCase().indexOf("where");
int index2 = sql.indexOf("${");
String newSql = sql;
if ((index > 0) && (index2 > 0)) {
newSql = sql.substring(0, index) + " where 1 = 0";
}
QueryUtil qu = new QueryUtil(con, DialectUtil.getDialect(con));
List<NameType> list = qu.executeQueryForColumnNames(newSql);
//System.out.println("*** newType=" + list.get(0).getType());
return list.get(0).getType();
} finally {
ConnectionUtil.closeConnection(con);
}
}
} catch (Exception ex) {
ex.printStackTrace();
LOG.error(ex.getMessage(), ex);
throw ex;
}
return null;
} | [
"public",
"static",
"String",
"getValueClassName",
"(",
"StorageService",
"storageService",
",",
"DataSource",
"ds",
",",
"String",
"sql",
")",
"throws",
"Exception",
"{",
"try",
"{",
"if",
"(",
"(",
"sql",
"!=",
"null",
")",
"&&",
"!",
"sql",
".",
"trim",... | get value class name for the first column on a select sql query | [
"get",
"value",
"class",
"name",
"for",
"the",
"first",
"column",
"on",
"a",
"select",
"sql",
"query"
] | train | https://github.com/nextreports/nextreports-server/blob/cfce12f5c6d52cb6a739388d50142c6e2e07c55e/src/ro/nextreports/server/report/jasper/JasperReportsUtil.java#L522-L549 |
zaproxy/zaproxy | src/org/parosproxy/paros/network/SSLConnector.java | SSLConnector.createTunnelServerSocket | public Socket createTunnelServerSocket(String targethost, Socket socket) throws IOException {
InetAddress listeningAddress = socket.getLocalAddress();
// ZAP: added host name parameter
SSLSocket s = (SSLSocket) getTunnelSSLSocketFactory(targethost, listeningAddress).createSocket(socket, socket
.getInetAddress().getHostAddress(), socket.getPort(), true);
s.setUseClientMode(false);
s.startHandshake();
return s;
} | java | public Socket createTunnelServerSocket(String targethost, Socket socket) throws IOException {
InetAddress listeningAddress = socket.getLocalAddress();
// ZAP: added host name parameter
SSLSocket s = (SSLSocket) getTunnelSSLSocketFactory(targethost, listeningAddress).createSocket(socket, socket
.getInetAddress().getHostAddress(), socket.getPort(), true);
s.setUseClientMode(false);
s.startHandshake();
return s;
} | [
"public",
"Socket",
"createTunnelServerSocket",
"(",
"String",
"targethost",
",",
"Socket",
"socket",
")",
"throws",
"IOException",
"{",
"InetAddress",
"listeningAddress",
"=",
"socket",
".",
"getLocalAddress",
"(",
")",
";",
"// ZAP: added host name parameter\r",
"SSLS... | Create a SSLsocket using an existing connected socket. It can be used
such as a tunneled SSL proxy socket (eg when a CONNECT request is
received). This SSLSocket will start server side handshake immediately.
@param targethost the host where you want to connect to
@param socket
@return
@throws IOException | [
"Create",
"a",
"SSLsocket",
"using",
"an",
"existing",
"connected",
"socket",
".",
"It",
"can",
"be",
"used",
"such",
"as",
"a",
"tunneled",
"SSL",
"proxy",
"socket",
"(",
"eg",
"when",
"a",
"CONNECT",
"request",
"is",
"received",
")",
".",
"This",
"SSLS... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/network/SSLConnector.java#L553-L562 |
algolia/instantsearch-android | core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java | Searcher.forwardBackendSearchResult | @NonNull
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public Searcher forwardBackendSearchResult(@NonNull JSONObject response) {
if (!hasHits(response)) {
endReached = true;
} else {
checkIfLastPage(response);
}
updateListeners(response, false);
updateFacetStats(response);
EventBus.getDefault().post(new ResultEvent(this, response, query, REQUEST_UNKNOWN));
return this;
} | java | @NonNull
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public Searcher forwardBackendSearchResult(@NonNull JSONObject response) {
if (!hasHits(response)) {
endReached = true;
} else {
checkIfLastPage(response);
}
updateListeners(response, false);
updateFacetStats(response);
EventBus.getDefault().post(new ResultEvent(this, response, query, REQUEST_UNKNOWN));
return this;
} | [
"@",
"NonNull",
"@",
"SuppressWarnings",
"(",
"{",
"\"WeakerAccess\"",
",",
"\"unused\"",
"}",
")",
"// For library users",
"public",
"Searcher",
"forwardBackendSearchResult",
"(",
"@",
"NonNull",
"JSONObject",
"response",
")",
"{",
"if",
"(",
"!",
"hasHits",
"(",... | Forwards the given algolia response to the {@link Searcher#resultListeners results listeners}.
<p>
<i>This method is useful if you rely on a backend implementation,
but still want to use InstantSearch Android in your frontend application.</i>
@param response the response sent by the algolia server.
@return this {@link Searcher} for chaining.
@throws IllegalStateException if the given response is malformated. | [
"Forwards",
"the",
"given",
"algolia",
"response",
"to",
"the",
"{",
"@link",
"Searcher#resultListeners",
"results",
"listeners",
"}",
".",
"<p",
">",
"<i",
">",
"This",
"method",
"is",
"useful",
"if",
"you",
"rely",
"on",
"a",
"backend",
"implementation",
"... | train | https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java#L382-L395 |
lucmoreau/ProvToolbox | prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java | ProvFactory.newValue | public Value newValue(Object value, QualifiedName type) {
if (value==null) return null;
Value res = of.createValue();
res.setType(type);
res.setValueFromObject(value);
return res;
} | java | public Value newValue(Object value, QualifiedName type) {
if (value==null) return null;
Value res = of.createValue();
res.setType(type);
res.setValueFromObject(value);
return res;
} | [
"public",
"Value",
"newValue",
"(",
"Object",
"value",
",",
"QualifiedName",
"type",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"return",
"null",
";",
"Value",
"res",
"=",
"of",
".",
"createValue",
"(",
")",
";",
"res",
".",
"setType",
"(",
"ty... | Factory method to create an instance of the PROV-DM prov:value attribute (see {@link Value}).
Use class {@link Name} for predefined {@link QualifiedName}s for the common types.
@param value an {@link Object}
@param type a {@link QualifiedName} to denote the type of value
@return a new {@link Value} | [
"Factory",
"method",
"to",
"create",
"an",
"instance",
"of",
"the",
"PROV",
"-",
"DM",
"prov",
":",
"value",
"attribute",
"(",
"see",
"{"
] | train | https://github.com/lucmoreau/ProvToolbox/blob/f865952868ffb69432937b08728c86bebbe4678a/prov-model/src/main/java/org/openprovenance/prov/model/ProvFactory.java#L1053-L1059 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSEditLogLoader.java | FSEditLogLoader.getAndUpdateLastInodeId | private static long getAndUpdateLastInodeId(FSDirectory fsDir,
long inodeIdFromOp, int logVersion) throws IOException {
long inodeId = inodeIdFromOp;
if (inodeId == INodeId.GRANDFATHER_INODE_ID) {
// This id is read from old edit log
if (LayoutVersion.supports(Feature.ADD_INODE_ID, logVersion)) {
throw new IOException("The layout version " + logVersion
+ " supports inodeId but gave bogus inodeId");
}
inodeId = fsDir.allocateNewInodeId();
} else {
// need to reset lastInodeId. fsdir gets lastInodeId firstly from
// fsimage but editlog captures more recent inodeId allocations
if (inodeId > fsDir.getLastInodeId()) {
fsDir.resetLastInodeId(inodeId);
}
}
return inodeId;
} | java | private static long getAndUpdateLastInodeId(FSDirectory fsDir,
long inodeIdFromOp, int logVersion) throws IOException {
long inodeId = inodeIdFromOp;
if (inodeId == INodeId.GRANDFATHER_INODE_ID) {
// This id is read from old edit log
if (LayoutVersion.supports(Feature.ADD_INODE_ID, logVersion)) {
throw new IOException("The layout version " + logVersion
+ " supports inodeId but gave bogus inodeId");
}
inodeId = fsDir.allocateNewInodeId();
} else {
// need to reset lastInodeId. fsdir gets lastInodeId firstly from
// fsimage but editlog captures more recent inodeId allocations
if (inodeId > fsDir.getLastInodeId()) {
fsDir.resetLastInodeId(inodeId);
}
}
return inodeId;
} | [
"private",
"static",
"long",
"getAndUpdateLastInodeId",
"(",
"FSDirectory",
"fsDir",
",",
"long",
"inodeIdFromOp",
",",
"int",
"logVersion",
")",
"throws",
"IOException",
"{",
"long",
"inodeId",
"=",
"inodeIdFromOp",
";",
"if",
"(",
"inodeId",
"==",
"INodeId",
"... | Allocate inode id for legacy edit log, or generate inode id for new edit log,
and update lastInodeId in {@link FSDirectory}
Also doing some sanity check
@param fsDir {@link FSDirectory}
@param inodeIdFromOp inode id read from edit log
@param logVersion current layout version
@param lastInodeId the latest inode id in the system
@return inode id
@throws IOException When invalid inode id in layout that supports inode id. | [
"Allocate",
"inode",
"id",
"for",
"legacy",
"edit",
"log",
"or",
"generate",
"inode",
"id",
"for",
"new",
"edit",
"log",
"and",
"update",
"lastInodeId",
"in",
"{",
"@link",
"FSDirectory",
"}",
"Also",
"doing",
"some",
"sanity",
"check"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSEditLogLoader.java#L82-L100 |
languagetool-org/languagetool | languagetool-core/src/main/java/org/languagetool/rules/patterns/Match.java | Match.createState | public MatchState createState(Synthesizer synthesizer, AnalyzedTokenReadings token) {
MatchState state = new MatchState(this, synthesizer);
state.setToken(token);
return state;
} | java | public MatchState createState(Synthesizer synthesizer, AnalyzedTokenReadings token) {
MatchState state = new MatchState(this, synthesizer);
state.setToken(token);
return state;
} | [
"public",
"MatchState",
"createState",
"(",
"Synthesizer",
"synthesizer",
",",
"AnalyzedTokenReadings",
"token",
")",
"{",
"MatchState",
"state",
"=",
"new",
"MatchState",
"(",
"this",
",",
"synthesizer",
")",
";",
"state",
".",
"setToken",
"(",
"token",
")",
... | Creates a state used for actually matching a token.
@since 2.3 | [
"Creates",
"a",
"state",
"used",
"for",
"actually",
"matching",
"a",
"token",
"."
] | train | https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/patterns/Match.java#L92-L96 |
apache/groovy | src/main/groovy/groovy/time/TimeCategory.java | TimeCategory.minus | public static TimeDuration minus(final Date lhs, final Date rhs) {
long milliseconds = lhs.getTime() - rhs.getTime();
long days = milliseconds / (24 * 60 * 60 * 1000);
milliseconds -= days * 24 * 60 * 60 * 1000;
int hours = (int) (milliseconds / (60 * 60 * 1000));
milliseconds -= hours * 60 * 60 * 1000;
int minutes = (int) (milliseconds / (60 * 1000));
milliseconds -= minutes * 60 * 1000;
int seconds = (int) (milliseconds / 1000);
milliseconds -= seconds * 1000;
return new TimeDuration((int) days, hours, minutes, seconds, (int) milliseconds);
} | java | public static TimeDuration minus(final Date lhs, final Date rhs) {
long milliseconds = lhs.getTime() - rhs.getTime();
long days = milliseconds / (24 * 60 * 60 * 1000);
milliseconds -= days * 24 * 60 * 60 * 1000;
int hours = (int) (milliseconds / (60 * 60 * 1000));
milliseconds -= hours * 60 * 60 * 1000;
int minutes = (int) (milliseconds / (60 * 1000));
milliseconds -= minutes * 60 * 1000;
int seconds = (int) (milliseconds / 1000);
milliseconds -= seconds * 1000;
return new TimeDuration((int) days, hours, minutes, seconds, (int) milliseconds);
} | [
"public",
"static",
"TimeDuration",
"minus",
"(",
"final",
"Date",
"lhs",
",",
"final",
"Date",
"rhs",
")",
"{",
"long",
"milliseconds",
"=",
"lhs",
".",
"getTime",
"(",
")",
"-",
"rhs",
".",
"getTime",
"(",
")",
";",
"long",
"days",
"=",
"milliseconds... | Subtract one date from the other.
@param lhs a Date
@param rhs another Date
@return a Duration | [
"Subtract",
"one",
"date",
"from",
"the",
"other",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/time/TimeCategory.java#L118-L130 |
kuali/ojb-1.0.4 | src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java | OjbTagsHandler.forAllReferenceDefinitions | public void forAllReferenceDefinitions(String template, Properties attributes) throws XDocletException
{
for (Iterator it = _curClassDef.getReferences(); it.hasNext(); )
{
_curReferenceDef = (ReferenceDescriptorDef)it.next();
// first we check whether it is an inherited anonymous reference
if (_curReferenceDef.isAnonymous() && (_curReferenceDef.getOwner() != _curClassDef))
{
continue;
}
if (!isFeatureIgnored(LEVEL_REFERENCE) &&
!_curReferenceDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
generate(template);
}
}
_curReferenceDef = null;
} | java | public void forAllReferenceDefinitions(String template, Properties attributes) throws XDocletException
{
for (Iterator it = _curClassDef.getReferences(); it.hasNext(); )
{
_curReferenceDef = (ReferenceDescriptorDef)it.next();
// first we check whether it is an inherited anonymous reference
if (_curReferenceDef.isAnonymous() && (_curReferenceDef.getOwner() != _curClassDef))
{
continue;
}
if (!isFeatureIgnored(LEVEL_REFERENCE) &&
!_curReferenceDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
generate(template);
}
}
_curReferenceDef = null;
} | [
"public",
"void",
"forAllReferenceDefinitions",
"(",
"String",
"template",
",",
"Properties",
"attributes",
")",
"throws",
"XDocletException",
"{",
"for",
"(",
"Iterator",
"it",
"=",
"_curClassDef",
".",
"getReferences",
"(",
")",
";",
"it",
".",
"hasNext",
"(",... | Processes the template for all reference definitions of the current class definition.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"Processes",
"the",
"template",
"for",
"all",
"reference",
"definitions",
"of",
"the",
"current",
"class",
"definition",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java#L954-L971 |
Netflix/ribbon | ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/reactive/ExecutionContextListenerInvoker.java | ExecutionContextListenerInvoker.onStartWithServer | public void onStartWithServer(ExecutionContext<I> context, ExecutionInfo info) {
for (ExecutionListener<I, O> listener: listeners) {
try {
if (!isListenerDisabled(listener)) {
listener.onStartWithServer(context.getChildContext(listener), info);
}
} catch (Throwable e) {
if (e instanceof AbortExecutionException) {
throw (AbortExecutionException) e;
}
logger.error("Error invoking listener " + listener, e);
}
}
} | java | public void onStartWithServer(ExecutionContext<I> context, ExecutionInfo info) {
for (ExecutionListener<I, O> listener: listeners) {
try {
if (!isListenerDisabled(listener)) {
listener.onStartWithServer(context.getChildContext(listener), info);
}
} catch (Throwable e) {
if (e instanceof AbortExecutionException) {
throw (AbortExecutionException) e;
}
logger.error("Error invoking listener " + listener, e);
}
}
} | [
"public",
"void",
"onStartWithServer",
"(",
"ExecutionContext",
"<",
"I",
">",
"context",
",",
"ExecutionInfo",
"info",
")",
"{",
"for",
"(",
"ExecutionListener",
"<",
"I",
",",
"O",
">",
"listener",
":",
"listeners",
")",
"{",
"try",
"{",
"if",
"(",
"!"... | Called when a server is chosen and the request is going to be executed on the server. | [
"Called",
"when",
"a",
"server",
"is",
"chosen",
"and",
"the",
"request",
"is",
"going",
"to",
"be",
"executed",
"on",
"the",
"server",
"."
] | train | https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/reactive/ExecutionContextListenerInvoker.java#L94-L107 |
umeding/fuzzer | src/main/java/com/uwemeding/fuzzer/java/JavaOutputType.java | JavaOutputType.addCalculateCrispValue | private void addCalculateCrispValue(Program program, Java.CLASS clazz) {
Java.METHOD calc = clazz.addMETHOD("private", "Number", "calculateCrispValue");
calc.setComment("Calculate the crisp value");
calc.setReturnComment("the crisp value");
calc.addArg("Number", "from", "Start interval");
calc.addArg("Number", "to", "End interval");
calc.addArg("Number", "step", "Interval step");
calc.addArg("double[]", "fuzzy", "Fuzzy value");
calc.addS("double area = 0.0");
calc.addS("double moment = 0.0");
Java.FOR fout = calc.addFOR("int i = 0", "i < fuzzy.length", "i++");
fout.addS("double normalized = from.doubleValue() + (step.doubleValue() * i)");
fout.addS("area += fuzzy[i]");
fout.addS("moment += fuzzy[i] * normalized");
calc.addS("double crisp = Math.abs(area) < " + program.getEpsilon() + " ? "
+ "to.doubleValue() + step.doubleValue() : moment / area");
calc.addRETURN("Math.abs(crisp) > " + program.getEpsilon() + " ? crisp : 0.0");
} | java | private void addCalculateCrispValue(Program program, Java.CLASS clazz) {
Java.METHOD calc = clazz.addMETHOD("private", "Number", "calculateCrispValue");
calc.setComment("Calculate the crisp value");
calc.setReturnComment("the crisp value");
calc.addArg("Number", "from", "Start interval");
calc.addArg("Number", "to", "End interval");
calc.addArg("Number", "step", "Interval step");
calc.addArg("double[]", "fuzzy", "Fuzzy value");
calc.addS("double area = 0.0");
calc.addS("double moment = 0.0");
Java.FOR fout = calc.addFOR("int i = 0", "i < fuzzy.length", "i++");
fout.addS("double normalized = from.doubleValue() + (step.doubleValue() * i)");
fout.addS("area += fuzzy[i]");
fout.addS("moment += fuzzy[i] * normalized");
calc.addS("double crisp = Math.abs(area) < " + program.getEpsilon() + " ? "
+ "to.doubleValue() + step.doubleValue() : moment / area");
calc.addRETURN("Math.abs(crisp) > " + program.getEpsilon() + " ? crisp : 0.0");
} | [
"private",
"void",
"addCalculateCrispValue",
"(",
"Program",
"program",
",",
"Java",
".",
"CLASS",
"clazz",
")",
"{",
"Java",
".",
"METHOD",
"calc",
"=",
"clazz",
".",
"addMETHOD",
"(",
"\"private\"",
",",
"\"Number\"",
",",
"\"calculateCrispValue\"",
")",
";"... | Calculate the crisp output value.
<p>
@param method the calling method
@param variable the output variable | [
"Calculate",
"the",
"crisp",
"output",
"value",
".",
"<p",
">"
] | train | https://github.com/umeding/fuzzer/blob/e8aa46313bb1d1328865f26f99455124aede828c/src/main/java/com/uwemeding/fuzzer/java/JavaOutputType.java#L235-L256 |
jmrozanec/cron-utils | src/main/java/com/cronutils/model/definition/CronDefinitionBuilder.java | CronDefinitionBuilder.instanceDefinitionFor | public static CronDefinition instanceDefinitionFor(final CronType cronType) {
switch (cronType) {
case CRON4J:
return cron4j();
case QUARTZ:
return quartz();
case UNIX:
return unixCrontab();
case SPRING:
return spring();
default:
throw new IllegalArgumentException(String.format("No cron definition found for %s", cronType));
}
} | java | public static CronDefinition instanceDefinitionFor(final CronType cronType) {
switch (cronType) {
case CRON4J:
return cron4j();
case QUARTZ:
return quartz();
case UNIX:
return unixCrontab();
case SPRING:
return spring();
default:
throw new IllegalArgumentException(String.format("No cron definition found for %s", cronType));
}
} | [
"public",
"static",
"CronDefinition",
"instanceDefinitionFor",
"(",
"final",
"CronType",
"cronType",
")",
"{",
"switch",
"(",
"cronType",
")",
"{",
"case",
"CRON4J",
":",
"return",
"cron4j",
"(",
")",
";",
"case",
"QUARTZ",
":",
"return",
"quartz",
"(",
")",... | Creates CronDefinition instance matching cronType specification.
@param cronType - some cron type. If null, a RuntimeException will be raised.
@return CronDefinition instance if definition is found; a RuntimeException otherwise. | [
"Creates",
"CronDefinition",
"instance",
"matching",
"cronType",
"specification",
"."
] | train | https://github.com/jmrozanec/cron-utils/blob/adac5ec8fd9160b082f9762a6eedea0715731170/src/main/java/com/cronutils/model/definition/CronDefinitionBuilder.java#L376-L389 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/Type1Font.java | Type1Font.setKerning | public boolean setKerning(int char1, int char2, int kern) {
String first = GlyphList.unicodeToName(char1);
if (first == null)
return false;
String second = GlyphList.unicodeToName(char2);
if (second == null)
return false;
Object obj[] = (Object[])KernPairs.get(first);
if (obj == null) {
obj = new Object[]{second, Integer.valueOf(kern)};
KernPairs.put(first, obj);
return true;
}
for (int k = 0; k < obj.length; k += 2) {
if (second.equals(obj[k])) {
obj[k + 1] = Integer.valueOf(kern);
return true;
}
}
int size = obj.length;
Object obj2[] = new Object[size + 2];
System.arraycopy(obj, 0, obj2, 0, size);
obj2[size] = second;
obj2[size + 1] = Integer.valueOf(kern);
KernPairs.put(first, obj2);
return true;
} | java | public boolean setKerning(int char1, int char2, int kern) {
String first = GlyphList.unicodeToName(char1);
if (first == null)
return false;
String second = GlyphList.unicodeToName(char2);
if (second == null)
return false;
Object obj[] = (Object[])KernPairs.get(first);
if (obj == null) {
obj = new Object[]{second, Integer.valueOf(kern)};
KernPairs.put(first, obj);
return true;
}
for (int k = 0; k < obj.length; k += 2) {
if (second.equals(obj[k])) {
obj[k + 1] = Integer.valueOf(kern);
return true;
}
}
int size = obj.length;
Object obj2[] = new Object[size + 2];
System.arraycopy(obj, 0, obj2, 0, size);
obj2[size] = second;
obj2[size + 1] = Integer.valueOf(kern);
KernPairs.put(first, obj2);
return true;
} | [
"public",
"boolean",
"setKerning",
"(",
"int",
"char1",
",",
"int",
"char2",
",",
"int",
"kern",
")",
"{",
"String",
"first",
"=",
"GlyphList",
".",
"unicodeToName",
"(",
"char1",
")",
";",
"if",
"(",
"first",
"==",
"null",
")",
"return",
"false",
";",... | Sets the kerning between two Unicode chars.
@param char1 the first char
@param char2 the second char
@param kern the kerning to apply in normalized 1000 units
@return <code>true</code> if the kerning was applied, <code>false</code> otherwise | [
"Sets",
"the",
"kerning",
"between",
"two",
"Unicode",
"chars",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/Type1Font.java#L787-L813 |
janus-project/guava.janusproject.io | guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/FluentIterable.java | FluentIterable.append | @Beta
@CheckReturnValue
public final FluentIterable<E> append(Iterable<? extends E> other) {
return from(Iterables.concat(iterable, other));
} | java | @Beta
@CheckReturnValue
public final FluentIterable<E> append(Iterable<? extends E> other) {
return from(Iterables.concat(iterable, other));
} | [
"@",
"Beta",
"@",
"CheckReturnValue",
"public",
"final",
"FluentIterable",
"<",
"E",
">",
"append",
"(",
"Iterable",
"<",
"?",
"extends",
"E",
">",
"other",
")",
"{",
"return",
"from",
"(",
"Iterables",
".",
"concat",
"(",
"iterable",
",",
"other",
")",
... | Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable,
followed by those of {@code other}. The iterators are not polled until necessary.
<p>The returned iterable's {@code Iterator} supports {@code remove()} when the corresponding
{@code Iterator} supports it.
@since 18.0 | [
"Returns",
"a",
"fluent",
"iterable",
"whose",
"iterators",
"traverse",
"first",
"the",
"elements",
"of",
"this",
"fluent",
"iterable",
"followed",
"by",
"those",
"of",
"{",
"@code",
"other",
"}",
".",
"The",
"iterators",
"are",
"not",
"polled",
"until",
"ne... | train | https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/FluentIterable.java#L174-L178 |
NLPchina/ansj_seg | src/main/java/org/ansj/library/DicLibrary.java | DicLibrary.insertOrCreate | public static void insertOrCreate(String key, String keyword, String nature, int freq) {
Forest dic = get(key);
if(dic==null){
dic = new Forest() ;
put(key,key,dic);
}
String[] paramers = new String[2];
paramers[0] = nature;
paramers[1] = String.valueOf(freq);
Value value = new Value(keyword, paramers);
Library.insertWord(dic, value);
} | java | public static void insertOrCreate(String key, String keyword, String nature, int freq) {
Forest dic = get(key);
if(dic==null){
dic = new Forest() ;
put(key,key,dic);
}
String[] paramers = new String[2];
paramers[0] = nature;
paramers[1] = String.valueOf(freq);
Value value = new Value(keyword, paramers);
Library.insertWord(dic, value);
} | [
"public",
"static",
"void",
"insertOrCreate",
"(",
"String",
"key",
",",
"String",
"keyword",
",",
"String",
"nature",
",",
"int",
"freq",
")",
"{",
"Forest",
"dic",
"=",
"get",
"(",
"key",
")",
";",
"if",
"(",
"dic",
"==",
"null",
")",
"{",
"dic",
... | 关键词增加
@param keyword 所要增加的关键词
@param nature 关键词的词性
@param freq 关键词的词频 | [
"关键词增加"
] | train | https://github.com/NLPchina/ansj_seg/blob/1addfa08c9dc86872fcdb06c7f0955dd5d197585/src/main/java/org/ansj/library/DicLibrary.java#L74-L85 |
contentful/contentful-management.java | src/main/java/com/contentful/java/cma/ModuleSpaceMemberships.java | ModuleSpaceMemberships.fetchOne | public CMASpaceMembership fetchOne(String spaceId, String membershipId) {
assertNotNull(spaceId, "spaceId");
assertNotNull(membershipId, "membershipId");
return service.fetchOne(spaceId, membershipId).blockingFirst();
} | java | public CMASpaceMembership fetchOne(String spaceId, String membershipId) {
assertNotNull(spaceId, "spaceId");
assertNotNull(membershipId, "membershipId");
return service.fetchOne(spaceId, membershipId).blockingFirst();
} | [
"public",
"CMASpaceMembership",
"fetchOne",
"(",
"String",
"spaceId",
",",
"String",
"membershipId",
")",
"{",
"assertNotNull",
"(",
"spaceId",
",",
"\"spaceId\"",
")",
";",
"assertNotNull",
"(",
"membershipId",
",",
"\"membershipId\"",
")",
";",
"return",
"servic... | Fetches one space membership by its id from Contentful.
@param spaceId the space this membership is hosted by.
@param membershipId the id of the membership to be found.
@return null if no membership was found, otherwise the found membership.
@throws IllegalArgumentException if space id is null.
@throws IllegalArgumentException if membership id is null. | [
"Fetches",
"one",
"space",
"membership",
"by",
"its",
"id",
"from",
"Contentful",
"."
] | train | https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/ModuleSpaceMemberships.java#L152-L157 |
nmdp-bioinformatics/genotype-list | gl-service/src/main/java/org/nmdp/gl/service/nomenclature/AbstractNomenclature.java | AbstractNomenclature.loadAllele | protected final Allele loadAllele(final String glstring, final String accession) throws IOException {
final String id = glstringResolver.resolveAllele(glstring);
Allele allele = idResolver.findAllele(id);
if (allele == null) {
Matcher m = ALLELE_PATTERN.matcher(glstring);
if (m.matches()) {
String locusPart = m.group(1);
Locus locus = loadLocus(locusPart);
allele = new Allele(id, accession, glstring, locus);
glRegistry.registerAllele(allele);
}
else {
throw new IOException("allele \"" + glstring + "\" not a valid formatted glstring");
}
}
return allele;
} | java | protected final Allele loadAllele(final String glstring, final String accession) throws IOException {
final String id = glstringResolver.resolveAllele(glstring);
Allele allele = idResolver.findAllele(id);
if (allele == null) {
Matcher m = ALLELE_PATTERN.matcher(glstring);
if (m.matches()) {
String locusPart = m.group(1);
Locus locus = loadLocus(locusPart);
allele = new Allele(id, accession, glstring, locus);
glRegistry.registerAllele(allele);
}
else {
throw new IOException("allele \"" + glstring + "\" not a valid formatted glstring");
}
}
return allele;
} | [
"protected",
"final",
"Allele",
"loadAllele",
"(",
"final",
"String",
"glstring",
",",
"final",
"String",
"accession",
")",
"throws",
"IOException",
"{",
"final",
"String",
"id",
"=",
"glstringResolver",
".",
"resolveAllele",
"(",
"glstring",
")",
";",
"Allele",... | Load and register the specified allele in GL String format.
@param glstring allele in GL String format, must not be null or empty
@param accession allele accession, must not be null
@return the registered allele
@throws IOException if an I/O error occurs | [
"Load",
"and",
"register",
"the",
"specified",
"allele",
"in",
"GL",
"String",
"format",
"."
] | train | https://github.com/nmdp-bioinformatics/genotype-list/blob/03b2579552cb9f680a62ffaaecdca9c2a5d12ee4/gl-service/src/main/java/org/nmdp/gl/service/nomenclature/AbstractNomenclature.java#L96-L112 |
finmath/finmath-lib | src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java | HullWhiteModel.getV | private RandomVariable getV(double time, double maturity) {
if(time == maturity) {
return new Scalar(0.0);
}
int timeIndexStart = volatilityModel.getTimeDiscretization().getTimeIndex(time);
if(timeIndexStart < 0) {
timeIndexStart = -timeIndexStart-2; // Get timeIndex corresponding to previous point
}
int timeIndexEnd =volatilityModel.getTimeDiscretization().getTimeIndex(maturity);
if(timeIndexEnd < 0) {
timeIndexEnd = -timeIndexEnd-2; // Get timeIndex corresponding to previous point
}
RandomVariable integral = new Scalar(0.0);
double timePrev = time;
double timeNext;
RandomVariable expMRTimePrev = getMRTime(timePrev,maturity).mult(-1).exp();
for(int timeIndex=timeIndexStart+1; timeIndex<=timeIndexEnd; timeIndex++) {
timeNext = volatilityModel.getTimeDiscretization().getTime(timeIndex);
RandomVariable meanReversion = volatilityModel.getMeanReversion(timeIndex-1);
RandomVariable volatility = volatilityModel.getVolatility(timeIndex-1);
RandomVariable volatilityPerMeanReversionSquared = volatility.squared().div(meanReversion.squared());
RandomVariable expMRTimeNext = getMRTime(timeNext,maturity).mult(-1).exp();
integral = integral.add(volatilityPerMeanReversionSquared.mult(
expMRTimeNext.sub(expMRTimePrev).mult(-2).div(meanReversion)
.add( expMRTimeNext.squared().sub(expMRTimePrev.squared()).div(meanReversion).div(2.0))
.add(timeNext-timePrev)
));
timePrev = timeNext;
expMRTimePrev = expMRTimeNext;
}
timeNext = maturity;
RandomVariable meanReversion = volatilityModel.getMeanReversion(timeIndexEnd);
RandomVariable volatility = volatilityModel.getVolatility(timeIndexEnd);
RandomVariable volatilityPerMeanReversionSquared = volatility.squared().div(meanReversion.squared());
RandomVariable expMRTimeNext = getMRTime(timeNext,maturity).mult(-1).exp();
integral = integral.add(volatilityPerMeanReversionSquared.mult(
expMRTimeNext.sub(expMRTimePrev).mult(-2).div(meanReversion)
.add( expMRTimeNext.squared().sub(expMRTimePrev.squared()).div(meanReversion).div(2.0))
.add(timeNext-timePrev)
));
return integral;
} | java | private RandomVariable getV(double time, double maturity) {
if(time == maturity) {
return new Scalar(0.0);
}
int timeIndexStart = volatilityModel.getTimeDiscretization().getTimeIndex(time);
if(timeIndexStart < 0) {
timeIndexStart = -timeIndexStart-2; // Get timeIndex corresponding to previous point
}
int timeIndexEnd =volatilityModel.getTimeDiscretization().getTimeIndex(maturity);
if(timeIndexEnd < 0) {
timeIndexEnd = -timeIndexEnd-2; // Get timeIndex corresponding to previous point
}
RandomVariable integral = new Scalar(0.0);
double timePrev = time;
double timeNext;
RandomVariable expMRTimePrev = getMRTime(timePrev,maturity).mult(-1).exp();
for(int timeIndex=timeIndexStart+1; timeIndex<=timeIndexEnd; timeIndex++) {
timeNext = volatilityModel.getTimeDiscretization().getTime(timeIndex);
RandomVariable meanReversion = volatilityModel.getMeanReversion(timeIndex-1);
RandomVariable volatility = volatilityModel.getVolatility(timeIndex-1);
RandomVariable volatilityPerMeanReversionSquared = volatility.squared().div(meanReversion.squared());
RandomVariable expMRTimeNext = getMRTime(timeNext,maturity).mult(-1).exp();
integral = integral.add(volatilityPerMeanReversionSquared.mult(
expMRTimeNext.sub(expMRTimePrev).mult(-2).div(meanReversion)
.add( expMRTimeNext.squared().sub(expMRTimePrev.squared()).div(meanReversion).div(2.0))
.add(timeNext-timePrev)
));
timePrev = timeNext;
expMRTimePrev = expMRTimeNext;
}
timeNext = maturity;
RandomVariable meanReversion = volatilityModel.getMeanReversion(timeIndexEnd);
RandomVariable volatility = volatilityModel.getVolatility(timeIndexEnd);
RandomVariable volatilityPerMeanReversionSquared = volatility.squared().div(meanReversion.squared());
RandomVariable expMRTimeNext = getMRTime(timeNext,maturity).mult(-1).exp();
integral = integral.add(volatilityPerMeanReversionSquared.mult(
expMRTimeNext.sub(expMRTimePrev).mult(-2).div(meanReversion)
.add( expMRTimeNext.squared().sub(expMRTimePrev.squared()).div(meanReversion).div(2.0))
.add(timeNext-timePrev)
));
return integral;
} | [
"private",
"RandomVariable",
"getV",
"(",
"double",
"time",
",",
"double",
"maturity",
")",
"{",
"if",
"(",
"time",
"==",
"maturity",
")",
"{",
"return",
"new",
"Scalar",
"(",
"0.0",
")",
";",
"}",
"int",
"timeIndexStart",
"=",
"volatilityModel",
".",
"g... | Calculates the drift adjustment for the log numeraire, that is
\(
\int_{t}^{T} \sigma^{2}(s) B(s,T)^{2} \mathrm{d}s
\) where \( B(t,T) = \int_{t}^{T} \exp(-\int_{s}^{T} a(\tau) \mathrm{d}\tau) \mathrm{d}s \).
@param time The parameter t in \( \int_{t}^{T} \sigma^{2}(s) B(s,T)^{2} \mathrm{d}s \)
@param maturity The parameter T in \( \int_{t}^{T} \sigma^{2}(s) B(s,T)^{2} \mathrm{d}s \)
@return The integral \( \int_{t}^{T} \sigma^{2}(s) B(s,T)^{2} \mathrm{d}s \). | [
"Calculates",
"the",
"drift",
"adjustment",
"for",
"the",
"log",
"numeraire",
"that",
"is",
"\\",
"(",
"\\",
"int_",
"{",
"t",
"}",
"^",
"{",
"T",
"}",
"\\",
"sigma^",
"{",
"2",
"}",
"(",
"s",
")",
"B",
"(",
"s",
"T",
")",
"^",
"{",
"2",
"}",... | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java#L656-L700 |
Bandwidth/java-bandwidth | src/main/java/com/bandwidth/sdk/model/Call.java | Call.create | public static Call create(final String to, final String from) throws Exception {
return create(to, from, "none", null);
} | java | public static Call create(final String to, final String from) throws Exception {
return create(to, from, "none", null);
} | [
"public",
"static",
"Call",
"create",
"(",
"final",
"String",
"to",
",",
"final",
"String",
"from",
")",
"throws",
"Exception",
"{",
"return",
"create",
"(",
"to",
",",
"from",
",",
"\"none\"",
",",
"null",
")",
";",
"}"
] | Convenience factory method to make an outbound call
@param to the to number
@param from the from number
@return the call
@throws Exception error. | [
"Convenience",
"factory",
"method",
"to",
"make",
"an",
"outbound",
"call"
] | train | https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/model/Call.java#L105-L107 |
greenmail-mail-test/greenmail | greenmail-core/src/main/java/com/icegreen/greenmail/imap/ImapRequestLineReader.java | ImapRequestLineReader.nextChar | public char nextChar() throws ProtocolException {
if (!nextSeen) {
try {
final int read = input.read();
final char c = (char) read;
buf.append(c);
if(read == -1) {
dumpLine();
throw new ProtocolException("End of stream");
}
nextChar = c;
nextSeen = true;
} catch (IOException e) {
throw new ProtocolException("Error reading from stream.", e);
}
}
return nextChar;
} | java | public char nextChar() throws ProtocolException {
if (!nextSeen) {
try {
final int read = input.read();
final char c = (char) read;
buf.append(c);
if(read == -1) {
dumpLine();
throw new ProtocolException("End of stream");
}
nextChar = c;
nextSeen = true;
} catch (IOException e) {
throw new ProtocolException("Error reading from stream.", e);
}
}
return nextChar;
} | [
"public",
"char",
"nextChar",
"(",
")",
"throws",
"ProtocolException",
"{",
"if",
"(",
"!",
"nextSeen",
")",
"{",
"try",
"{",
"final",
"int",
"read",
"=",
"input",
".",
"read",
"(",
")",
";",
"final",
"char",
"c",
"=",
"(",
"char",
")",
"read",
";"... | Reads the next character in the current line. This method will continue to return
the same character until the {@link #consume()} method is called.
@return The next character.
@throws ProtocolException If the end-of-stream is reached. | [
"Reads",
"the",
"next",
"character",
"in",
"the",
"current",
"line",
".",
"This",
"method",
"will",
"continue",
"to",
"return",
"the",
"same",
"character",
"until",
"the",
"{",
"@link",
"#consume",
"()",
"}",
"method",
"is",
"called",
"."
] | train | https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/imap/ImapRequestLineReader.java#L70-L87 |
phax/ph-schedule | ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java | DateBuilder.tomorrowAt | public static Date tomorrowAt (final int hour, final int minute, final int second)
{
validateSecond (second);
validateMinute (minute);
validateHour (hour);
final Date date = new Date ();
final Calendar c = PDTFactory.createCalendar ();
c.setTime (date);
c.setLenient (true);
// advance one day
c.add (Calendar.DAY_OF_YEAR, 1);
c.set (Calendar.HOUR_OF_DAY, hour);
c.set (Calendar.MINUTE, minute);
c.set (Calendar.SECOND, second);
c.set (Calendar.MILLISECOND, 0);
return c.getTime ();
} | java | public static Date tomorrowAt (final int hour, final int minute, final int second)
{
validateSecond (second);
validateMinute (minute);
validateHour (hour);
final Date date = new Date ();
final Calendar c = PDTFactory.createCalendar ();
c.setTime (date);
c.setLenient (true);
// advance one day
c.add (Calendar.DAY_OF_YEAR, 1);
c.set (Calendar.HOUR_OF_DAY, hour);
c.set (Calendar.MINUTE, minute);
c.set (Calendar.SECOND, second);
c.set (Calendar.MILLISECOND, 0);
return c.getTime ();
} | [
"public",
"static",
"Date",
"tomorrowAt",
"(",
"final",
"int",
"hour",
",",
"final",
"int",
"minute",
",",
"final",
"int",
"second",
")",
"{",
"validateSecond",
"(",
"second",
")",
";",
"validateMinute",
"(",
"minute",
")",
";",
"validateHour",
"(",
"hour"... | <p>
Get a <code>Date</code> object that represents the given time, on
tomorrow's date.
</p>
@param second
The value (0-59) to give the seconds field of the date
@param minute
The value (0-59) to give the minutes field of the date
@param hour
The value (0-23) to give the hours field of the date
@return the new date | [
"<p",
">",
"Get",
"a",
"<code",
">",
"Date<",
"/",
"code",
">",
"object",
"that",
"represents",
"the",
"given",
"time",
"on",
"tomorrow",
"s",
"date",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java#L345-L366 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionValuePersistenceImpl.java | CPOptionValuePersistenceImpl.findByC_K | @Override
public CPOptionValue findByC_K(long CPOptionId, String key)
throws NoSuchCPOptionValueException {
CPOptionValue cpOptionValue = fetchByC_K(CPOptionId, key);
if (cpOptionValue == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("CPOptionId=");
msg.append(CPOptionId);
msg.append(", key=");
msg.append(key);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchCPOptionValueException(msg.toString());
}
return cpOptionValue;
} | java | @Override
public CPOptionValue findByC_K(long CPOptionId, String key)
throws NoSuchCPOptionValueException {
CPOptionValue cpOptionValue = fetchByC_K(CPOptionId, key);
if (cpOptionValue == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("CPOptionId=");
msg.append(CPOptionId);
msg.append(", key=");
msg.append(key);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchCPOptionValueException(msg.toString());
}
return cpOptionValue;
} | [
"@",
"Override",
"public",
"CPOptionValue",
"findByC_K",
"(",
"long",
"CPOptionId",
",",
"String",
"key",
")",
"throws",
"NoSuchCPOptionValueException",
"{",
"CPOptionValue",
"cpOptionValue",
"=",
"fetchByC_K",
"(",
"CPOptionId",
",",
"key",
")",
";",
"if",
"(",
... | Returns the cp option value where CPOptionId = ? and key = ? or throws a {@link NoSuchCPOptionValueException} if it could not be found.
@param CPOptionId the cp option ID
@param key the key
@return the matching cp option value
@throws NoSuchCPOptionValueException if a matching cp option value could not be found | [
"Returns",
"the",
"cp",
"option",
"value",
"where",
"CPOptionId",
"=",
"?",
";",
"and",
"key",
"=",
"?",
";",
"or",
"throws",
"a",
"{",
"@link",
"NoSuchCPOptionValueException",
"}",
"if",
"it",
"could",
"not",
"be",
"found",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionValuePersistenceImpl.java#L3025-L3051 |
protostuff/protostuff | protostuff-core/src/main/java/io/protostuff/CodedInput.java | CodedInput.mergeObjectEncodedAsGroup | private <T> T mergeObjectEncodedAsGroup(T value, final Schema<T> schema) throws IOException
{
// if (recursionDepth >= recursionLimit) {
// throw ProtobufException.recursionLimitExceeded();
// }
// ++recursionDepth;
if (value == null)
{
value = schema.newMessage();
}
schema.mergeFrom(this, value);
if (!schema.isInitialized(value))
{
throw new UninitializedMessageException(value, schema);
}
// handling is in #readFieldNumber
checkLastTagWas(0);
// --recursionDepth;
return value;
} | java | private <T> T mergeObjectEncodedAsGroup(T value, final Schema<T> schema) throws IOException
{
// if (recursionDepth >= recursionLimit) {
// throw ProtobufException.recursionLimitExceeded();
// }
// ++recursionDepth;
if (value == null)
{
value = schema.newMessage();
}
schema.mergeFrom(this, value);
if (!schema.isInitialized(value))
{
throw new UninitializedMessageException(value, schema);
}
// handling is in #readFieldNumber
checkLastTagWas(0);
// --recursionDepth;
return value;
} | [
"private",
"<",
"T",
">",
"T",
"mergeObjectEncodedAsGroup",
"(",
"T",
"value",
",",
"final",
"Schema",
"<",
"T",
">",
"schema",
")",
"throws",
"IOException",
"{",
"// if (recursionDepth >= recursionLimit) {",
"// throw ProtobufException.recursionLimitExceeded();",
"// }",... | Reads a message field value from the stream (using the {@code group} encoding). | [
"Reads",
"a",
"message",
"field",
"value",
"from",
"the",
"stream",
"(",
"using",
"the",
"{"
] | train | https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-core/src/main/java/io/protostuff/CodedInput.java#L348-L368 |
sannies/mp4parser | streaming/src/main/java/org/mp4parser/streaming/output/mp4/FragmentedMp4Writer.java | FragmentedMp4Writer.isFragmentReady | protected boolean isFragmentReady(StreamingTrack streamingTrack, StreamingSample next) {
long ts = nextSampleStartTime.get(streamingTrack);
long cfst = nextFragmentCreateStartTime.get(streamingTrack);
if ((ts > cfst + 3 * streamingTrack.getTimescale())) {
// mininum fragment length == 3 seconds
SampleFlagsSampleExtension sfExt = next.getSampleExtension(SampleFlagsSampleExtension.class);
if (sfExt == null || sfExt.isSyncSample()) {
//System.err.println(streamingTrack + " ready at " + ts);
// the next sample needs to be a sync sample
// when there is no SampleFlagsSampleExtension we assume syncSample == true
return true;
}
}
return false;
} | java | protected boolean isFragmentReady(StreamingTrack streamingTrack, StreamingSample next) {
long ts = nextSampleStartTime.get(streamingTrack);
long cfst = nextFragmentCreateStartTime.get(streamingTrack);
if ((ts > cfst + 3 * streamingTrack.getTimescale())) {
// mininum fragment length == 3 seconds
SampleFlagsSampleExtension sfExt = next.getSampleExtension(SampleFlagsSampleExtension.class);
if (sfExt == null || sfExt.isSyncSample()) {
//System.err.println(streamingTrack + " ready at " + ts);
// the next sample needs to be a sync sample
// when there is no SampleFlagsSampleExtension we assume syncSample == true
return true;
}
}
return false;
} | [
"protected",
"boolean",
"isFragmentReady",
"(",
"StreamingTrack",
"streamingTrack",
",",
"StreamingSample",
"next",
")",
"{",
"long",
"ts",
"=",
"nextSampleStartTime",
".",
"get",
"(",
"streamingTrack",
")",
";",
"long",
"cfst",
"=",
"nextFragmentCreateStartTime",
"... | Tests if the currently received samples for a given track
form a valid fragment taking the latest received sample into
account. The next sample is not part of the segment and
will be added to the fragment buffer later.
@param streamingTrack track to test
@param next the lastest samples
@return true if a fragment has been created. | [
"Tests",
"if",
"the",
"currently",
"received",
"samples",
"for",
"a",
"given",
"track",
"form",
"a",
"valid",
"fragment",
"taking",
"the",
"latest",
"received",
"sample",
"into",
"account",
".",
"The",
"next",
"sample",
"is",
"not",
"part",
"of",
"the",
"s... | train | https://github.com/sannies/mp4parser/blob/3382ff5d489363900f352a8da0f794a20ad3b063/streaming/src/main/java/org/mp4parser/streaming/output/mp4/FragmentedMp4Writer.java#L299-L314 |
cdk/cdk | base/standard/src/main/java/org/openscience/cdk/graph/rebond/RebondTool.java | RebondTool.isBonded | private boolean isBonded(double covalentRadiusA, double covalentRadiusB, double distance2) {
double maxAcceptable = covalentRadiusA + covalentRadiusB + bondTolerance;
double maxAcceptable2 = maxAcceptable * maxAcceptable;
double minBondDistance2 = this.minBondDistance * this.minBondDistance;
if (distance2 < minBondDistance2) return false;
return distance2 <= maxAcceptable2;
} | java | private boolean isBonded(double covalentRadiusA, double covalentRadiusB, double distance2) {
double maxAcceptable = covalentRadiusA + covalentRadiusB + bondTolerance;
double maxAcceptable2 = maxAcceptable * maxAcceptable;
double minBondDistance2 = this.minBondDistance * this.minBondDistance;
if (distance2 < minBondDistance2) return false;
return distance2 <= maxAcceptable2;
} | [
"private",
"boolean",
"isBonded",
"(",
"double",
"covalentRadiusA",
",",
"double",
"covalentRadiusB",
",",
"double",
"distance2",
")",
"{",
"double",
"maxAcceptable",
"=",
"covalentRadiusA",
"+",
"covalentRadiusB",
"+",
"bondTolerance",
";",
"double",
"maxAcceptable2"... | Returns the bond order for the bond. At this moment, it only returns
0 or 1, but not 2 or 3, or aromatic bond order. | [
"Returns",
"the",
"bond",
"order",
"for",
"the",
"bond",
".",
"At",
"this",
"moment",
"it",
"only",
"returns",
"0",
"or",
"1",
"but",
"not",
"2",
"or",
"3",
"or",
"aromatic",
"bond",
"order",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/graph/rebond/RebondTool.java#L117-L123 |
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/android/ContentValues.java | ContentValues.put | public ContentValues put(String key, String value) {
mValues.put(key, value);
return this;
} | java | public ContentValues put(String key, String value) {
mValues.put(key, value);
return this;
} | [
"public",
"ContentValues",
"put",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"mValues",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds a value to the set.
@param key the name of the value to forceInsert
@param value the data for the value to forceInsert | [
"Adds",
"a",
"value",
"to",
"the",
"set",
"."
] | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/android/ContentValues.java#L96-L99 |
lets-blade/blade | src/main/java/com/blade/server/netty/StaticFileHandler.java | StaticFileHandler.setDateAndCacheHeaders | private void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
response.headers().set(HttpConst.DATE, DateKit.gmtDate());
// Add cache headers
if (httpCacheSeconds > 0) {
response.headers().set(HttpConst.EXPIRES, DateKit.gmtDate(LocalDateTime.now().plusSeconds(httpCacheSeconds)));
response.headers().set(HttpConst.CACHE_CONTROL, "private, max-age=" + httpCacheSeconds);
if (null != fileToCache) {
response.headers().set(HttpConst.LAST_MODIFIED, DateKit.gmtDate(new Date(fileToCache.lastModified())));
} else {
response.headers().set(HttpConst.LAST_MODIFIED, DateKit.gmtDate(LocalDateTime.now().plusDays(-1)));
}
}
} | java | private void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
response.headers().set(HttpConst.DATE, DateKit.gmtDate());
// Add cache headers
if (httpCacheSeconds > 0) {
response.headers().set(HttpConst.EXPIRES, DateKit.gmtDate(LocalDateTime.now().plusSeconds(httpCacheSeconds)));
response.headers().set(HttpConst.CACHE_CONTROL, "private, max-age=" + httpCacheSeconds);
if (null != fileToCache) {
response.headers().set(HttpConst.LAST_MODIFIED, DateKit.gmtDate(new Date(fileToCache.lastModified())));
} else {
response.headers().set(HttpConst.LAST_MODIFIED, DateKit.gmtDate(LocalDateTime.now().plusDays(-1)));
}
}
} | [
"private",
"void",
"setDateAndCacheHeaders",
"(",
"HttpResponse",
"response",
",",
"File",
"fileToCache",
")",
"{",
"response",
".",
"headers",
"(",
")",
".",
"set",
"(",
"HttpConst",
".",
"DATE",
",",
"DateKit",
".",
"gmtDate",
"(",
")",
")",
";",
"// Add... | Sets the Date and Cache headers for the HTTP Response
@param response HTTP response
@param fileToCache file to extract content type | [
"Sets",
"the",
"Date",
"and",
"Cache",
"headers",
"for",
"the",
"HTTP",
"Response"
] | train | https://github.com/lets-blade/blade/blob/60624ee528be12122c49a9ad1713e336b959e59a/src/main/java/com/blade/server/netty/StaticFileHandler.java#L345-L357 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/SecurityRulesInner.java | SecurityRulesInner.beginDelete | public void beginDelete(String resourceGroupName, String networkSecurityGroupName, String securityRuleName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, securityRuleName).toBlocking().single().body();
} | java | public void beginDelete(String resourceGroupName, String networkSecurityGroupName, String securityRuleName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, securityRuleName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"resourceGroupName",
",",
"String",
"networkSecurityGroupName",
",",
"String",
"securityRuleName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"networkSecurityGroupName",
",",
"securityRuleNam... | Deletes the specified network security rule.
@param resourceGroupName The name of the resource group.
@param networkSecurityGroupName The name of the network security group.
@param securityRuleName The name of the security rule.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Deletes",
"the",
"specified",
"network",
"security",
"rule",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/SecurityRulesInner.java#L177-L179 |
OpenLiberty/open-liberty | dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/util/BatchWorkUnit.java | BatchWorkUnit.threadBegin | protected void threadBegin() {
//
// Note the 'beforeCallbacks' list is not going to have a well-defined order, so it is of limited use.
// We probably want to revisit this with some kind of priority/order based on ranking to make
// it more useful.
//
// At the moment we treat the setting of the tran timeout separately, rather than as a IJobExecutionStartCallbackService,
// to reflect the fact that this is provided by a required dependency. If we were to want this to function in SE mode,
// say, we might want to factor this too as an "extension" that is provided by another layer, and so incorporate this into a
// more generic, extensible "before" processing.
try {
tranMgr.setTransactionTimeout(0);
if (beforeCallbacks != null) {
for (IJobExecutionStartCallbackService callback : beforeCallbacks) {
if (logger.isLoggable(Level.FINER)) {
logger.logp(Level.FINER, CLASSNAME, "threadBegin", "Calling before callback", callback);
}
callback.jobStarted(runtimeWorkUnitExecution);
}
}
} catch (Throwable t) {
// Fail the execution if any of our before-work-unit callbacks failed. E.g. the joblog context setup
// was unsuccessful. We may want to make it an option whether or not to fail here in the future.
runtimeWorkUnitExecution.logExecutionFailedMessage();
throw new BatchContainerRuntimeException("An error occurred during thread initialization.", t);
}
} | java | protected void threadBegin() {
//
// Note the 'beforeCallbacks' list is not going to have a well-defined order, so it is of limited use.
// We probably want to revisit this with some kind of priority/order based on ranking to make
// it more useful.
//
// At the moment we treat the setting of the tran timeout separately, rather than as a IJobExecutionStartCallbackService,
// to reflect the fact that this is provided by a required dependency. If we were to want this to function in SE mode,
// say, we might want to factor this too as an "extension" that is provided by another layer, and so incorporate this into a
// more generic, extensible "before" processing.
try {
tranMgr.setTransactionTimeout(0);
if (beforeCallbacks != null) {
for (IJobExecutionStartCallbackService callback : beforeCallbacks) {
if (logger.isLoggable(Level.FINER)) {
logger.logp(Level.FINER, CLASSNAME, "threadBegin", "Calling before callback", callback);
}
callback.jobStarted(runtimeWorkUnitExecution);
}
}
} catch (Throwable t) {
// Fail the execution if any of our before-work-unit callbacks failed. E.g. the joblog context setup
// was unsuccessful. We may want to make it an option whether or not to fail here in the future.
runtimeWorkUnitExecution.logExecutionFailedMessage();
throw new BatchContainerRuntimeException("An error occurred during thread initialization.", t);
}
} | [
"protected",
"void",
"threadBegin",
"(",
")",
"{",
"//",
"// Note the 'beforeCallbacks' list is not going to have a well-defined order, so it is of limited use.",
"// We probably want to revisit this with some kind of priority/order based on ranking to make",
"// it more useful.",
"//",
"// At... | All the beginning of thread processing.
Note we are going to fail fast out of here and fail the execution upon experiencing any exception. | [
"All",
"the",
"beginning",
"of",
"thread",
"processing",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/util/BatchWorkUnit.java#L171-L197 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/parser/PdfContentReaderTool.java | PdfContentReaderTool.listContentStream | static public void listContentStream(File pdfFile, PrintWriter out) throws IOException {
PdfReader reader = new PdfReader(pdfFile.getCanonicalPath());
int maxPageNum = reader.getNumberOfPages();
for (int pageNum = 1; pageNum <= maxPageNum; pageNum++){
listContentStreamForPage(reader, pageNum, out);
}
} | java | static public void listContentStream(File pdfFile, PrintWriter out) throws IOException {
PdfReader reader = new PdfReader(pdfFile.getCanonicalPath());
int maxPageNum = reader.getNumberOfPages();
for (int pageNum = 1; pageNum <= maxPageNum; pageNum++){
listContentStreamForPage(reader, pageNum, out);
}
} | [
"static",
"public",
"void",
"listContentStream",
"(",
"File",
"pdfFile",
",",
"PrintWriter",
"out",
")",
"throws",
"IOException",
"{",
"PdfReader",
"reader",
"=",
"new",
"PdfReader",
"(",
"pdfFile",
".",
"getCanonicalPath",
"(",
")",
")",
";",
"int",
"maxPageN... | Writes information about each page in a PDF file to the specified output stream.
@since 2.1.5
@param pdfFile a File instance referring to a PDF file
@param out the output stream to send the content to
@throws IOException | [
"Writes",
"information",
"about",
"each",
"page",
"in",
"a",
"PDF",
"file",
"to",
"the",
"specified",
"output",
"stream",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/parser/PdfContentReaderTool.java#L163-L172 |
aws/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Item.java | Item.withNumber | public Item withNumber(String attrName, Number val) {
checkInvalidAttribute(attrName, val);
attributes.put(attrName, toBigDecimal(val));
return this;
} | java | public Item withNumber(String attrName, Number val) {
checkInvalidAttribute(attrName, val);
attributes.put(attrName, toBigDecimal(val));
return this;
} | [
"public",
"Item",
"withNumber",
"(",
"String",
"attrName",
",",
"Number",
"val",
")",
"{",
"checkInvalidAttribute",
"(",
"attrName",
",",
"val",
")",
";",
"attributes",
".",
"put",
"(",
"attrName",
",",
"toBigDecimal",
"(",
"val",
")",
")",
";",
"return",
... | Sets the value of the specified attribute in the current item to the
given value. | [
"Sets",
"the",
"value",
"of",
"the",
"specified",
"attribute",
"in",
"the",
"current",
"item",
"to",
"the",
"given",
"value",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Item.java#L277-L281 |
google/closure-compiler | src/com/google/javascript/jscomp/VariableMap.java | VariableMap.fromBytes | @GwtIncompatible("com.google.common.base.Splitter.onPattern()")
public static VariableMap fromBytes(byte[] bytes) throws ParseException {
String string = new String(bytes, UTF_8);
ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
int startOfLine = 0;
while (startOfLine < string.length()) {
int newLine = string.indexOf('\n', startOfLine);
if (newLine == -1) {
newLine = string.length();
}
int endOfLine = newLine;
if (string.charAt(newLine - 1) == '\r') {
newLine--;
}
String line = string.substring(startOfLine, newLine);
startOfLine = endOfLine + 1; // update index for next iteration
if (line.isEmpty()) {
continue;
}
int pos = findIndexOfUnescapedChar(line, SEPARATOR);
if (pos <= 0) {
throw new ParseException("Bad line: " + line, 0);
}
map.put(
unescape(line.substring(0, pos)),
pos == line.length() - 1 ? "" : unescape(line.substring(pos + 1)));
}
return new VariableMap(map.build());
} | java | @GwtIncompatible("com.google.common.base.Splitter.onPattern()")
public static VariableMap fromBytes(byte[] bytes) throws ParseException {
String string = new String(bytes, UTF_8);
ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
int startOfLine = 0;
while (startOfLine < string.length()) {
int newLine = string.indexOf('\n', startOfLine);
if (newLine == -1) {
newLine = string.length();
}
int endOfLine = newLine;
if (string.charAt(newLine - 1) == '\r') {
newLine--;
}
String line = string.substring(startOfLine, newLine);
startOfLine = endOfLine + 1; // update index for next iteration
if (line.isEmpty()) {
continue;
}
int pos = findIndexOfUnescapedChar(line, SEPARATOR);
if (pos <= 0) {
throw new ParseException("Bad line: " + line, 0);
}
map.put(
unescape(line.substring(0, pos)),
pos == line.length() - 1 ? "" : unescape(line.substring(pos + 1)));
}
return new VariableMap(map.build());
} | [
"@",
"GwtIncompatible",
"(",
"\"com.google.common.base.Splitter.onPattern()\"",
")",
"public",
"static",
"VariableMap",
"fromBytes",
"(",
"byte",
"[",
"]",
"bytes",
")",
"throws",
"ParseException",
"{",
"String",
"string",
"=",
"new",
"String",
"(",
"bytes",
",",
... | Deserializes the variable map from a byte array returned by
{@link #toBytes()}. | [
"Deserializes",
"the",
"variable",
"map",
"from",
"a",
"byte",
"array",
"returned",
"by",
"{"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/VariableMap.java#L128-L156 |
innoq/LiQID | ldap-connector/src/main/java/com/innoq/ldap/connector/LdapHelper.java | LdapHelper.getUserTemplate | public LdapUser getUserTemplate(String uid) {
LdapUser user = new LdapUser(uid, this);
user.set("dn", getDNForNode(user));
for (String oc : userObjectClasses) {
user.addObjectClass(oc.trim());
}
user = (LdapUser) updateObjectClasses(user);
// TODO this needs to be cleaner :-/.
// for inetOrgPerson
if (user.getObjectClasses().contains("inetOrgPerson")
|| user.getObjectClasses().contains("person")) {
user.set("sn", uid);
}
// for JabberAccount
if (user.getObjectClasses().contains("JabberAccount")) {
user.set("jabberID", uid + "@" + defaultValues.get("jabberServer"));
user.set("jabberAccess", "TRUE");
}
// for posixAccount
if (user.getObjectClasses().contains("posixAccount")) {
user.set("uidNumber", "99999");
user.set("gidNumber", "99999");
user.set("cn", uid);
user.set("homeDirectory", "/dev/null");
}
// for ldapPublicKey
if (user.getObjectClasses().contains("ldapPublicKey")) {
user.set("sshPublicKey", defaultValues.get("sshKey"));
}
return user;
} | java | public LdapUser getUserTemplate(String uid) {
LdapUser user = new LdapUser(uid, this);
user.set("dn", getDNForNode(user));
for (String oc : userObjectClasses) {
user.addObjectClass(oc.trim());
}
user = (LdapUser) updateObjectClasses(user);
// TODO this needs to be cleaner :-/.
// for inetOrgPerson
if (user.getObjectClasses().contains("inetOrgPerson")
|| user.getObjectClasses().contains("person")) {
user.set("sn", uid);
}
// for JabberAccount
if (user.getObjectClasses().contains("JabberAccount")) {
user.set("jabberID", uid + "@" + defaultValues.get("jabberServer"));
user.set("jabberAccess", "TRUE");
}
// for posixAccount
if (user.getObjectClasses().contains("posixAccount")) {
user.set("uidNumber", "99999");
user.set("gidNumber", "99999");
user.set("cn", uid);
user.set("homeDirectory", "/dev/null");
}
// for ldapPublicKey
if (user.getObjectClasses().contains("ldapPublicKey")) {
user.set("sshPublicKey", defaultValues.get("sshKey"));
}
return user;
} | [
"public",
"LdapUser",
"getUserTemplate",
"(",
"String",
"uid",
")",
"{",
"LdapUser",
"user",
"=",
"new",
"LdapUser",
"(",
"uid",
",",
"this",
")",
";",
"user",
".",
"set",
"(",
"\"dn\"",
",",
"getDNForNode",
"(",
"user",
")",
")",
";",
"for",
"(",
"S... | Returns a basic LDAP-User-Template for a new LDAP-User.
@param uid of the new LDAP-User.
@return the (prefiled) User-Template. | [
"Returns",
"a",
"basic",
"LDAP",
"-",
"User",
"-",
"Template",
"for",
"a",
"new",
"LDAP",
"-",
"User",
"."
] | train | https://github.com/innoq/LiQID/blob/ae3de2c1fd78c40219780d510eba57c931901279/ldap-connector/src/main/java/com/innoq/ldap/connector/LdapHelper.java#L619-L654 |
threerings/nenya | tools/src/main/java/com/threerings/cast/bundle/tools/ComponentBundlerUtil.java | ComponentBundlerUtil.addTileSetRuleSet | protected static void addTileSetRuleSet (Digester digester, TileSetRuleSet ruleSet)
{
ruleSet.setPrefix("actions" + ActionRuleSet.ACTION_PATH);
digester.addRuleSet(ruleSet);
digester.addSetNext(ruleSet.getPath(), "addTileSet", TileSet.class.getName());
} | java | protected static void addTileSetRuleSet (Digester digester, TileSetRuleSet ruleSet)
{
ruleSet.setPrefix("actions" + ActionRuleSet.ACTION_PATH);
digester.addRuleSet(ruleSet);
digester.addSetNext(ruleSet.getPath(), "addTileSet", TileSet.class.getName());
} | [
"protected",
"static",
"void",
"addTileSetRuleSet",
"(",
"Digester",
"digester",
",",
"TileSetRuleSet",
"ruleSet",
")",
"{",
"ruleSet",
".",
"setPrefix",
"(",
"\"actions\"",
"+",
"ActionRuleSet",
".",
"ACTION_PATH",
")",
";",
"digester",
".",
"addRuleSet",
"(",
... | Configures <code>ruleSet</code> and hooks it into <code>digester</code>. | [
"Configures",
"<code",
">",
"ruleSet<",
"/",
"code",
">",
"and",
"hooks",
"it",
"into",
"<code",
">",
"digester<",
"/",
"code",
">",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/tools/src/main/java/com/threerings/cast/bundle/tools/ComponentBundlerUtil.java#L76-L81 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/security/remoting/BasicAuthHttpInvokerRequestExecutor.java | BasicAuthHttpInvokerRequestExecutor.prepareConnection | protected void prepareConnection(HttpURLConnection con, int contentLength)
throws IOException {
super.prepareConnection(con, contentLength);
Authentication auth = getAuthenticationToken();
if ((auth != null) && (auth.getName() != null)
&& (auth.getCredentials() != null)) {
String base64 = auth.getName() + ":"
+ auth.getCredentials().toString();
con.setRequestProperty("Authorization", "Basic "
+ new String(Base64.encodeBase64(base64.getBytes())));
if (logger.isDebugEnabled()) {
logger.debug("HttpInvocation now presenting via BASIC authentication with token:: "
+ auth);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Unable to set BASIC authentication header as Authentication token is invalid: "
+ auth);
}
}
doPrepareConnection(con, contentLength);
} | java | protected void prepareConnection(HttpURLConnection con, int contentLength)
throws IOException {
super.prepareConnection(con, contentLength);
Authentication auth = getAuthenticationToken();
if ((auth != null) && (auth.getName() != null)
&& (auth.getCredentials() != null)) {
String base64 = auth.getName() + ":"
+ auth.getCredentials().toString();
con.setRequestProperty("Authorization", "Basic "
+ new String(Base64.encodeBase64(base64.getBytes())));
if (logger.isDebugEnabled()) {
logger.debug("HttpInvocation now presenting via BASIC authentication with token:: "
+ auth);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Unable to set BASIC authentication header as Authentication token is invalid: "
+ auth);
}
}
doPrepareConnection(con, contentLength);
} | [
"protected",
"void",
"prepareConnection",
"(",
"HttpURLConnection",
"con",
",",
"int",
"contentLength",
")",
"throws",
"IOException",
"{",
"super",
".",
"prepareConnection",
"(",
"con",
",",
"contentLength",
")",
";",
"Authentication",
"auth",
"=",
"getAuthenticatio... | Called every time a HTTP invocation is made.
<p>
Simply allows the parent to setup the connection, and then adds an
<code>Authorization</code> HTTP header property that will be used for
BASIC authentication. Following that a call to
{@link #doPrepareConnection} is made to allow subclasses to apply any
additional configuration desired to the connection prior to invoking the
request.
<p>
The previously saved authentication token is used to obtain the principal
and credentials. If the saved token is null, then the "Authorization"
header will not be added to the request.
@param con
the HTTP connection to prepare
@param contentLength
the length of the content to send
@throws IOException
if thrown by HttpURLConnection methods | [
"Called",
"every",
"time",
"a",
"HTTP",
"invocation",
"is",
"made",
".",
"<p",
">",
"Simply",
"allows",
"the",
"parent",
"to",
"setup",
"the",
"connection",
"and",
"then",
"adds",
"an",
"<code",
">",
"Authorization<",
"/",
"code",
">",
"HTTP",
"header",
... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/security/remoting/BasicAuthHttpInvokerRequestExecutor.java#L131-L157 |
sawano/java-commons | src/main/java/se/sawano/java/commons/lang/validate/Validate.java | Validate.isInstanceOf | public static <T> T isInstanceOf(final Class<?> type, final T obj, final String message, final Object... values) {
return INSTANCE.isInstanceOf(type, obj, message, values);
} | java | public static <T> T isInstanceOf(final Class<?> type, final T obj, final String message, final Object... values) {
return INSTANCE.isInstanceOf(type, obj, message, values);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"isInstanceOf",
"(",
"final",
"Class",
"<",
"?",
">",
"type",
",",
"final",
"T",
"obj",
",",
"final",
"String",
"message",
",",
"final",
"Object",
"...",
"values",
")",
"{",
"return",
"INSTANCE",
".",
"isInstance... | <p>Validate that the argument is an instance of the specified class; otherwise throwing an exception with the specified message. This method is useful when validating according to an arbitrary
class</p>
<pre>Validate.isInstanceOf(OkClass.classs, object, "Wrong class, object is of class %s",
object.getClass().getName());</pre>
@param <T>
the type of the object to check
@param type
the class the object must be validated against, not null
@param obj
the object to check, null throws an exception
@param message
the {@link String#format(String, Object...)} exception message if invalid, not null
@param values
the optional values for the formatted exception message, null array not recommended
@return the object
@throws IllegalArgumentValidationException
if argument is not of specified class
@see #isInstanceOf(Class, Object) | [
"<p",
">",
"Validate",
"that",
"the",
"argument",
"is",
"an",
"instance",
"of",
"the",
"specified",
"class",
";",
"otherwise",
"throwing",
"an",
"exception",
"with",
"the",
"specified",
"message",
".",
"This",
"method",
"is",
"useful",
"when",
"validating",
... | train | https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/Validate.java#L1737-L1739 |
alipay/sofa-rpc | core/api/src/main/java/com/alipay/sofa/rpc/client/ProviderInfo.java | ProviderInfo.setDynamicAttrs | public ProviderInfo setDynamicAttrs(Map<String, Object> dynamicAttrs) {
this.dynamicAttrs.clear();
this.dynamicAttrs.putAll(dynamicAttrs);
return this;
} | java | public ProviderInfo setDynamicAttrs(Map<String, Object> dynamicAttrs) {
this.dynamicAttrs.clear();
this.dynamicAttrs.putAll(dynamicAttrs);
return this;
} | [
"public",
"ProviderInfo",
"setDynamicAttrs",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"dynamicAttrs",
")",
"{",
"this",
".",
"dynamicAttrs",
".",
"clear",
"(",
")",
";",
"this",
".",
"dynamicAttrs",
".",
"putAll",
"(",
"dynamicAttrs",
")",
";",
"retu... | Sets dynamic attribute.
@param dynamicAttrs the dynamic attribute
@return this | [
"Sets",
"dynamic",
"attribute",
"."
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/client/ProviderInfo.java#L433-L437 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/script/ScriptVars.java | ScriptVars.setScriptVar | public static void setScriptVar(ScriptContext context, String key, String value) {
setScriptVarImpl(getScriptName(context), key, value);
} | java | public static void setScriptVar(ScriptContext context, String key, String value) {
setScriptVarImpl(getScriptName(context), key, value);
} | [
"public",
"static",
"void",
"setScriptVar",
"(",
"ScriptContext",
"context",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"setScriptVarImpl",
"(",
"getScriptName",
"(",
"context",
")",
",",
"key",
",",
"value",
")",
";",
"}"
] | Sets or removes a script variable.
<p>
The variable is removed when the {@code value} is {@code null}.
@param context the context of the script.
@param key the key of the variable.
@param value the value of the variable.
@throws IllegalArgumentException if one of the following conditions is met:
<ul>
<li>The {@code context} is {@code null} or it does not contain the name of the script;</li>
<li>The {@code key} is {@code null} or its length is higher than the maximum allowed
({@value #MAX_KEY_SIZE});</li>
<li>The {@code value}'s length is higher than the maximum allowed ({@value #MAX_VALUE_SIZE});</li>
<li>The number of script variables is higher than the maximum allowed ({@value #MAX_SCRIPT_VARS});</li>
</ul> | [
"Sets",
"or",
"removes",
"a",
"script",
"variable",
".",
"<p",
">",
"The",
"variable",
"is",
"removed",
"when",
"the",
"{",
"@code",
"value",
"}",
"is",
"{",
"@code",
"null",
"}",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/script/ScriptVars.java#L157-L159 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/db/ResultSetUtility.java | ResultSetUtility.convertToMap | public Map<String, Object> convertToMap(ResultSet rs) throws SQLException{
return convertToMap(rs, null);
} | java | public Map<String, Object> convertToMap(ResultSet rs) throws SQLException{
return convertToMap(rs, null);
} | [
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"convertToMap",
"(",
"ResultSet",
"rs",
")",
"throws",
"SQLException",
"{",
"return",
"convertToMap",
"(",
"rs",
",",
"null",
")",
";",
"}"
] | Convert current row of the ResultSet to a Map. The keys of the Map are property names transformed from column names.
@param rs the result set
@return a Map representation of current row
@throws SQLException | [
"Convert",
"current",
"row",
"of",
"the",
"ResultSet",
"to",
"a",
"Map",
".",
"The",
"keys",
"of",
"the",
"Map",
"are",
"property",
"names",
"transformed",
"from",
"column",
"names",
"."
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ResultSetUtility.java#L60-L62 |
voldemort/voldemort | src/java/voldemort/utils/pool/ResourcePoolConfig.java | ResourcePoolConfig.setTimeout | public ResourcePoolConfig setTimeout(long timeout, TimeUnit unit) {
if(timeout < 0)
throw new IllegalArgumentException("The timeout must be a non-negative number.");
this.timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, unit);
return this;
} | java | public ResourcePoolConfig setTimeout(long timeout, TimeUnit unit) {
if(timeout < 0)
throw new IllegalArgumentException("The timeout must be a non-negative number.");
this.timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, unit);
return this;
} | [
"public",
"ResourcePoolConfig",
"setTimeout",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"{",
"if",
"(",
"timeout",
"<",
"0",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The timeout must be a non-negative number.\"",
")",
";",
"this",
".",
... | The timeout which we block for when a resource is not available
@param timeout The timeout
@param unit The units of the timeout | [
"The",
"timeout",
"which",
"we",
"block",
"for",
"when",
"a",
"resource",
"is",
"not",
"available"
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/ResourcePoolConfig.java#L59-L64 |
recommenders/rival | rival-examples/src/main/java/net/recommenders/rival/examples/movietweetings/RandomMahoutIBRecommenderEvaluator.java | RandomMahoutIBRecommenderEvaluator.prepareSplits | public static void prepareSplits(final String url, final float percentage, final String inFile, final String folder, final String outPath) {
DataDownloader dd = new DataDownloader(url, folder);
dd.download();
boolean perUser = true;
long seed = SEED;
UIPParser parser = new UIPParser();
parser.setDelimiter(':');
parser.setUserTok(USER_TOK);
parser.setItemTok(ITEM_TOK);
parser.setPrefTok(PREF_TOK);
parser.setTimeTok(TIME_TOK);
DataModelIF<Long, Long> data = null;
try {
data = parser.parseData(new File(inFile));
} catch (IOException e) {
e.printStackTrace();
}
DataModelIF<Long, Long>[] splits = new RandomSplitter<Long, Long>(percentage, perUser, seed, false).split(data);
File dir = new File(outPath);
if (!dir.exists()) {
if (!dir.mkdir()) {
System.err.println("Directory " + dir + " could not be created");
return;
}
}
for (int i = 0; i < splits.length / 2; i++) {
DataModelIF<Long, Long> training = splits[2 * i];
DataModelIF<Long, Long> test = splits[2 * i + 1];
String trainingFile = outPath + "train_" + i + ".csv";
String testFile = outPath + "test_" + i + ".csv";
System.out.println("train: " + trainingFile);
System.out.println("test: " + testFile);
boolean overwrite = true;
try {
DataModelUtils.saveDataModel(training, trainingFile, overwrite, "\t");
DataModelUtils.saveDataModel(test, testFile, overwrite, "\t");
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
} | java | public static void prepareSplits(final String url, final float percentage, final String inFile, final String folder, final String outPath) {
DataDownloader dd = new DataDownloader(url, folder);
dd.download();
boolean perUser = true;
long seed = SEED;
UIPParser parser = new UIPParser();
parser.setDelimiter(':');
parser.setUserTok(USER_TOK);
parser.setItemTok(ITEM_TOK);
parser.setPrefTok(PREF_TOK);
parser.setTimeTok(TIME_TOK);
DataModelIF<Long, Long> data = null;
try {
data = parser.parseData(new File(inFile));
} catch (IOException e) {
e.printStackTrace();
}
DataModelIF<Long, Long>[] splits = new RandomSplitter<Long, Long>(percentage, perUser, seed, false).split(data);
File dir = new File(outPath);
if (!dir.exists()) {
if (!dir.mkdir()) {
System.err.println("Directory " + dir + " could not be created");
return;
}
}
for (int i = 0; i < splits.length / 2; i++) {
DataModelIF<Long, Long> training = splits[2 * i];
DataModelIF<Long, Long> test = splits[2 * i + 1];
String trainingFile = outPath + "train_" + i + ".csv";
String testFile = outPath + "test_" + i + ".csv";
System.out.println("train: " + trainingFile);
System.out.println("test: " + testFile);
boolean overwrite = true;
try {
DataModelUtils.saveDataModel(training, trainingFile, overwrite, "\t");
DataModelUtils.saveDataModel(test, testFile, overwrite, "\t");
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
} | [
"public",
"static",
"void",
"prepareSplits",
"(",
"final",
"String",
"url",
",",
"final",
"float",
"percentage",
",",
"final",
"String",
"inFile",
",",
"final",
"String",
"folder",
",",
"final",
"String",
"outPath",
")",
"{",
"DataDownloader",
"dd",
"=",
"ne... | Downloads a dataset and stores the splits generated from it.
@param url url where dataset can be downloaded from
@param percentage percentage to be used in the random split
@param inFile file to be used once the dataset has been downloaded
@param folder folder where dataset will be stored
@param outPath path where the splits will be stored | [
"Downloads",
"a",
"dataset",
"and",
"stores",
"the",
"splits",
"generated",
"from",
"it",
"."
] | train | https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/movietweetings/RandomMahoutIBRecommenderEvaluator.java#L121-L165 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java | MutateInBuilder.arrayAppend | @Deprecated
public <T> MutateInBuilder arrayAppend(String path, T value, boolean createPath) {
asyncBuilder.arrayAppend(path, value, new SubdocOptionsBuilder().createPath(createPath));
return this;
} | java | @Deprecated
public <T> MutateInBuilder arrayAppend(String path, T value, boolean createPath) {
asyncBuilder.arrayAppend(path, value, new SubdocOptionsBuilder().createPath(createPath));
return this;
} | [
"@",
"Deprecated",
"public",
"<",
"T",
">",
"MutateInBuilder",
"arrayAppend",
"(",
"String",
"path",
",",
"T",
"value",
",",
"boolean",
"createPath",
")",
"{",
"asyncBuilder",
".",
"arrayAppend",
"(",
"path",
",",
"value",
",",
"new",
"SubdocOptionsBuilder",
... | Append to an existing array, pushing the value to the back/last position in
the array.
@param path the path of the array.
@param value the value to insert at the back of the array.
@param createPath true to create missing intermediary nodes. | [
"Append",
"to",
"an",
"existing",
"array",
"pushing",
"the",
"value",
"to",
"the",
"back",
"/",
"last",
"position",
"in",
"the",
"array",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java#L808-L812 |
SonarSource/sonarqube | server/sonar-db-dao/src/main/java/org/sonar/db/component/ComponentDao.java | ComponentDao.selectByQuery | public List<ComponentDto> selectByQuery(DbSession session, ComponentQuery query, int offset, int limit) {
return selectByQueryImpl(session, null, query, offset, limit);
} | java | public List<ComponentDto> selectByQuery(DbSession session, ComponentQuery query, int offset, int limit) {
return selectByQueryImpl(session, null, query, offset, limit);
} | [
"public",
"List",
"<",
"ComponentDto",
">",
"selectByQuery",
"(",
"DbSession",
"session",
",",
"ComponentQuery",
"query",
",",
"int",
"offset",
",",
"int",
"limit",
")",
"{",
"return",
"selectByQueryImpl",
"(",
"session",
",",
"null",
",",
"query",
",",
"off... | Same as {@link #selectByQuery(DbSession, String, ComponentQuery, int, int)} except
that the filter on organization is disabled. | [
"Same",
"as",
"{"
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/component/ComponentDao.java#L108-L110 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/RepositoryApi.java | RepositoryApi.getRepositoryArchive | public File getRepositoryArchive(Object projectIdOrPath, String sha, File directory, String format) throws GitLabApiException {
ArchiveFormat archiveFormat = ArchiveFormat.forValue(format);
return (getRepositoryArchive(projectIdOrPath, sha, directory, archiveFormat));
} | java | public File getRepositoryArchive(Object projectIdOrPath, String sha, File directory, String format) throws GitLabApiException {
ArchiveFormat archiveFormat = ArchiveFormat.forValue(format);
return (getRepositoryArchive(projectIdOrPath, sha, directory, archiveFormat));
} | [
"public",
"File",
"getRepositoryArchive",
"(",
"Object",
"projectIdOrPath",
",",
"String",
"sha",
",",
"File",
"directory",
",",
"String",
"format",
")",
"throws",
"GitLabApiException",
"{",
"ArchiveFormat",
"archiveFormat",
"=",
"ArchiveFormat",
".",
"forValue",
"(... | Get an archive of the complete repository by SHA (optional) and saves to the specified directory.
If the archive already exists in the directory it will be overwritten.
<pre><code>GitLab Endpoint: GET /projects/:id/repository/archive</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param sha the SHA of the archive to get
@param directory the File instance of the directory to save the archive to, if null will use "java.io.tmpdir"
@param format The archive format, defaults to "tar.gz" if null
@return a File instance pointing to the downloaded instance
@throws GitLabApiException if format is not a valid archive format or any exception occurs | [
"Get",
"an",
"archive",
"of",
"the",
"complete",
"repository",
"by",
"SHA",
"(",
"optional",
")",
"and",
"saves",
"to",
"the",
"specified",
"directory",
".",
"If",
"the",
"archive",
"already",
"exists",
"in",
"the",
"directory",
"it",
"will",
"be",
"overwr... | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryApi.java#L620-L623 |
amaembo/streamex | src/main/java/one/util/streamex/EntryStream.java | EntryStream.toMapAndThen | public <R> R toMapAndThen(Function<? super Map<K, V>, R> finisher) {
if (context.fjp != null)
return context.terminate(() -> finisher.apply(toMap()));
return finisher.apply(toMap());
} | java | public <R> R toMapAndThen(Function<? super Map<K, V>, R> finisher) {
if (context.fjp != null)
return context.terminate(() -> finisher.apply(toMap()));
return finisher.apply(toMap());
} | [
"public",
"<",
"R",
">",
"R",
"toMapAndThen",
"(",
"Function",
"<",
"?",
"super",
"Map",
"<",
"K",
",",
"V",
">",
",",
"R",
">",
"finisher",
")",
"{",
"if",
"(",
"context",
".",
"fjp",
"!=",
"null",
")",
"return",
"context",
".",
"terminate",
"("... | Creates a {@link Map} containing the elements of this stream, then
performs finishing transformation and returns its result. There are no
guarantees on the type or serializability of the {@code Map} created.
<p>
This is a <a href="package-summary.html#StreamOps">terminal</a>
operation.
<p>
Created {@code Map} is guaranteed to be modifiable.
<p>
For parallel stream the concurrent {@code Map} is created.
@param <R> the type of the result
@param finisher a function to be applied to the intermediate map
@return result of applying the finisher transformation to the {@code Map}
of the stream elements.
@throws IllegalStateException if this stream contains duplicate keys
(according to {@link Object#equals(Object)})
@see #toMap()
@since 0.5.5 | [
"Creates",
"a",
"{",
"@link",
"Map",
"}",
"containing",
"the",
"elements",
"of",
"this",
"stream",
"then",
"performs",
"finishing",
"transformation",
"and",
"returns",
"its",
"result",
".",
"There",
"are",
"no",
"guarantees",
"on",
"the",
"type",
"or",
"seri... | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/EntryStream.java#L1181-L1185 |
tvesalainen/util | util/src/main/java/org/vesalainen/nio/file/attribute/UserAttrs.java | UserAttrs.getShortAttribute | public static final short getShortAttribute(Path path, String attribute, LinkOption... options) throws IOException
{
return getShortAttribute(path, attribute, (short)-1, options);
} | java | public static final short getShortAttribute(Path path, String attribute, LinkOption... options) throws IOException
{
return getShortAttribute(path, attribute, (short)-1, options);
} | [
"public",
"static",
"final",
"short",
"getShortAttribute",
"(",
"Path",
"path",
",",
"String",
"attribute",
",",
"LinkOption",
"...",
"options",
")",
"throws",
"IOException",
"{",
"return",
"getShortAttribute",
"(",
"path",
",",
"attribute",
",",
"(",
"short",
... | Returns user-defined-attribute -1 if not found.
@param path
@param attribute
@param options
@return
@throws IOException | [
"Returns",
"user",
"-",
"defined",
"-",
"attribute",
"-",
"1",
"if",
"not",
"found",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/file/attribute/UserAttrs.java#L125-L128 |
jhg023/SimpleNet | src/main/java/simplenet/Server.java | Server.writeHelper | private void writeHelper(Consumer<Client> consumer, Collection<? extends Client> clients) {
var toExclude = Collections.newSetFromMap(new IdentityHashMap<>(clients.size()));
toExclude.addAll(clients);
connectedClients.stream().filter(Predicate.not(toExclude::contains)).forEach(consumer);
} | java | private void writeHelper(Consumer<Client> consumer, Collection<? extends Client> clients) {
var toExclude = Collections.newSetFromMap(new IdentityHashMap<>(clients.size()));
toExclude.addAll(clients);
connectedClients.stream().filter(Predicate.not(toExclude::contains)).forEach(consumer);
} | [
"private",
"void",
"writeHelper",
"(",
"Consumer",
"<",
"Client",
">",
"consumer",
",",
"Collection",
"<",
"?",
"extends",
"Client",
">",
"clients",
")",
"{",
"var",
"toExclude",
"=",
"Collections",
".",
"newSetFromMap",
"(",
"new",
"IdentityHashMap",
"<>",
... | A helper method that eliminates code duplication in the {@link #writeToAllExcept(Packet, Collection)} and
{@link #writeAndFlushToAllExcept(Packet, Collection)} methods.
@param consumer The action to perform for each {@link Client}.
@param clients A {@link Collection} of {@link Client}s to exclude from receiving the {@link Packet}. | [
"A",
"helper",
"method",
"that",
"eliminates",
"code",
"duplication",
"in",
"the",
"{",
"@link",
"#writeToAllExcept",
"(",
"Packet",
"Collection",
")",
"}",
"and",
"{",
"@link",
"#writeAndFlushToAllExcept",
"(",
"Packet",
"Collection",
")",
"}",
"methods",
"."
] | train | https://github.com/jhg023/SimpleNet/blob/a5b55cbfe1768c6a28874f12adac3c748f2b509a/src/main/java/simplenet/Server.java#L224-L228 |
cybazeitalia/emaze-dysfunctional | src/main/java/net/emaze/dysfunctional/dispatching/delegates/Flipper.java | Flipper.apply | @Override
public R apply(T former, U latter) {
return function.apply(latter, former);
} | java | @Override
public R apply(T former, U latter) {
return function.apply(latter, former);
} | [
"@",
"Override",
"public",
"R",
"apply",
"(",
"T",
"former",
",",
"U",
"latter",
")",
"{",
"return",
"function",
".",
"apply",
"(",
"latter",
",",
"former",
")",
";",
"}"
] | Performs on the nested function swapping former and latter formal
parameters.
@param former the former formal parameter used as latter in the nested
function
@param latter the latter formal parameter used as former in the nested
function
@return the result of the function | [
"Performs",
"on",
"the",
"nested",
"function",
"swapping",
"former",
"and",
"latter",
"formal",
"parameters",
"."
] | train | https://github.com/cybazeitalia/emaze-dysfunctional/blob/98115a436e35335c5e8831f9fdc12f6d93d524be/src/main/java/net/emaze/dysfunctional/dispatching/delegates/Flipper.java#L36-L39 |
sai-pullabhotla/catatumbo | src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java | DefaultEntityManager.executeEntityListeners | public void executeEntityListeners(CallbackType callbackType, Object entity) {
// We may get null entities here. For example loading a nonexistent ID
// or IDs.
if (entity == null) {
return;
}
EntityListenersMetadata entityListenersMetadata = EntityIntrospector
.getEntityListenersMetadata(entity);
List<CallbackMetadata> callbacks = entityListenersMetadata.getCallbacks(callbackType);
if (!entityListenersMetadata.isExcludeDefaultListeners()) {
executeGlobalListeners(callbackType, entity);
}
if (callbacks == null) {
return;
}
for (CallbackMetadata callback : callbacks) {
switch (callback.getListenerType()) {
case EXTERNAL:
Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass());
invokeCallbackMethod(callback.getCallbackMethod(), listener, entity);
break;
case INTERNAL:
invokeCallbackMethod(callback.getCallbackMethod(), entity);
break;
default:
String message = String.format("Unknown or unimplemented callback listener type: %s",
callback.getListenerType());
throw new EntityManagerException(message);
}
}
} | java | public void executeEntityListeners(CallbackType callbackType, Object entity) {
// We may get null entities here. For example loading a nonexistent ID
// or IDs.
if (entity == null) {
return;
}
EntityListenersMetadata entityListenersMetadata = EntityIntrospector
.getEntityListenersMetadata(entity);
List<CallbackMetadata> callbacks = entityListenersMetadata.getCallbacks(callbackType);
if (!entityListenersMetadata.isExcludeDefaultListeners()) {
executeGlobalListeners(callbackType, entity);
}
if (callbacks == null) {
return;
}
for (CallbackMetadata callback : callbacks) {
switch (callback.getListenerType()) {
case EXTERNAL:
Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass());
invokeCallbackMethod(callback.getCallbackMethod(), listener, entity);
break;
case INTERNAL:
invokeCallbackMethod(callback.getCallbackMethod(), entity);
break;
default:
String message = String.format("Unknown or unimplemented callback listener type: %s",
callback.getListenerType());
throw new EntityManagerException(message);
}
}
} | [
"public",
"void",
"executeEntityListeners",
"(",
"CallbackType",
"callbackType",
",",
"Object",
"entity",
")",
"{",
"// We may get null entities here. For example loading a nonexistent ID",
"// or IDs.",
"if",
"(",
"entity",
"==",
"null",
")",
"{",
"return",
";",
"}",
"... | Executes the entity listeners associated with the given entity.
@param callbackType
the event type
@param entity
the entity that produced the event | [
"Executes",
"the",
"entity",
"listeners",
"associated",
"with",
"the",
"given",
"entity",
"."
] | train | https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java#L440-L470 |
wcm-io-caravan/caravan-hal | resource/src/main/java/io/wcm/caravan/hal/resource/HalResource.java | HalResource.addLinks | public HalResource addLinks(String relation, Link... links) {
return addResources(HalResourceType.LINKS, relation, true, links);
} | java | public HalResource addLinks(String relation, Link... links) {
return addResources(HalResourceType.LINKS, relation, true, links);
} | [
"public",
"HalResource",
"addLinks",
"(",
"String",
"relation",
",",
"Link",
"...",
"links",
")",
"{",
"return",
"addResources",
"(",
"HalResourceType",
".",
"LINKS",
",",
"relation",
",",
"true",
",",
"links",
")",
";",
"}"
] | Adds links for the given relation
@param relation Link relation
@param links Links to add
@return HAL resource | [
"Adds",
"links",
"for",
"the",
"given",
"relation"
] | train | https://github.com/wcm-io-caravan/caravan-hal/blob/25d58756b58c70c8c48a17fe781e673dd93d5085/resource/src/main/java/io/wcm/caravan/hal/resource/HalResource.java#L317-L319 |
git-commit-id/maven-git-commit-id-plugin | src/main/java/pl/project13/jgit/DescribeCommand.java | DescribeCommand.createDescribeResult | private DescribeResult createDescribeResult(ObjectReader objectReader, ObjectId headCommitId, boolean dirty, @Nullable Pair<Integer, String> howFarFromWhichTag) {
if (howFarFromWhichTag == null) {
return new DescribeResult(objectReader, headCommitId, dirty, dirtyOption)
.withCommitIdAbbrev(abbrev);
} else if (howFarFromWhichTag.first > 0 || forceLongFormat) {
return new DescribeResult(objectReader, howFarFromWhichTag.second, howFarFromWhichTag.first, headCommitId, dirty, dirtyOption, forceLongFormat)
.withCommitIdAbbrev(abbrev); // we're a bit away from a tag
} else if (howFarFromWhichTag.first == 0) {
return new DescribeResult(howFarFromWhichTag.second)
.withCommitIdAbbrev(abbrev); // we're ON a tag
} else if (alwaysFlag) {
return new DescribeResult(objectReader, headCommitId)
.withCommitIdAbbrev(abbrev); // we have no tags! display the commit
} else {
return DescribeResult.EMPTY;
}
} | java | private DescribeResult createDescribeResult(ObjectReader objectReader, ObjectId headCommitId, boolean dirty, @Nullable Pair<Integer, String> howFarFromWhichTag) {
if (howFarFromWhichTag == null) {
return new DescribeResult(objectReader, headCommitId, dirty, dirtyOption)
.withCommitIdAbbrev(abbrev);
} else if (howFarFromWhichTag.first > 0 || forceLongFormat) {
return new DescribeResult(objectReader, howFarFromWhichTag.second, howFarFromWhichTag.first, headCommitId, dirty, dirtyOption, forceLongFormat)
.withCommitIdAbbrev(abbrev); // we're a bit away from a tag
} else if (howFarFromWhichTag.first == 0) {
return new DescribeResult(howFarFromWhichTag.second)
.withCommitIdAbbrev(abbrev); // we're ON a tag
} else if (alwaysFlag) {
return new DescribeResult(objectReader, headCommitId)
.withCommitIdAbbrev(abbrev); // we have no tags! display the commit
} else {
return DescribeResult.EMPTY;
}
} | [
"private",
"DescribeResult",
"createDescribeResult",
"(",
"ObjectReader",
"objectReader",
",",
"ObjectId",
"headCommitId",
",",
"boolean",
"dirty",
",",
"@",
"Nullable",
"Pair",
"<",
"Integer",
",",
"String",
">",
"howFarFromWhichTag",
")",
"{",
"if",
"(",
"howFar... | Prepares the final result of this command.
It tries to put as much information as possible into the result,
and will fallback to a plain commit hash if nothing better is returnable.
The exact logic is following what <pre>git-describe</pre> would do. | [
"Prepares",
"the",
"final",
"result",
"of",
"this",
"command",
".",
"It",
"tries",
"to",
"put",
"as",
"much",
"information",
"as",
"possible",
"into",
"the",
"result",
"and",
"will",
"fallback",
"to",
"a",
"plain",
"commit",
"hash",
"if",
"nothing",
"bette... | train | https://github.com/git-commit-id/maven-git-commit-id-plugin/blob/a276551fb043d1b7fc4c890603f6ea0c79dc729a/src/main/java/pl/project13/jgit/DescribeCommand.java#L309-L329 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/actions/ReceiveMessageAction.java | ReceiveMessageAction.doExecute | @Override
public void doExecute(TestContext context) {
try {
Message receivedMessage;
String selector = MessageSelectorBuilder.build(messageSelector, messageSelectorMap, context);
//receive message either selected or plain with message receiver
if (StringUtils.hasText(selector)) {
receivedMessage = receiveSelected(context, selector);
} else {
receivedMessage = receive(context);
}
if (receivedMessage == null) {
throw new CitrusRuntimeException("Failed to receive message - message is not available");
}
//validate the message
validateMessage(receivedMessage, context);
} catch (IOException e) {
throw new CitrusRuntimeException(e);
}
} | java | @Override
public void doExecute(TestContext context) {
try {
Message receivedMessage;
String selector = MessageSelectorBuilder.build(messageSelector, messageSelectorMap, context);
//receive message either selected or plain with message receiver
if (StringUtils.hasText(selector)) {
receivedMessage = receiveSelected(context, selector);
} else {
receivedMessage = receive(context);
}
if (receivedMessage == null) {
throw new CitrusRuntimeException("Failed to receive message - message is not available");
}
//validate the message
validateMessage(receivedMessage, context);
} catch (IOException e) {
throw new CitrusRuntimeException(e);
}
} | [
"@",
"Override",
"public",
"void",
"doExecute",
"(",
"TestContext",
"context",
")",
"{",
"try",
"{",
"Message",
"receivedMessage",
";",
"String",
"selector",
"=",
"MessageSelectorBuilder",
".",
"build",
"(",
"messageSelector",
",",
"messageSelectorMap",
",",
"cont... | Method receives a message via {@link com.consol.citrus.endpoint.Endpoint} instance
constructs a validation context and starts the message validation
via {@link MessageValidator}.
@throws CitrusRuntimeException | [
"Method",
"receives",
"a",
"message",
"via",
"{",
"@link",
"com",
".",
"consol",
".",
"citrus",
".",
"endpoint",
".",
"Endpoint",
"}",
"instance",
"constructs",
"a",
"validation",
"context",
"and",
"starts",
"the",
"message",
"validation",
"via",
"{",
"@link... | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/actions/ReceiveMessageAction.java#L110-L132 |
unbescape/unbescape | src/main/java/org/unbescape/csv/CsvEscape.java | CsvEscape.unescapeCsv | public static void unescapeCsv(final String text, final Writer writer)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
CsvEscapeUtil.unescape(new InternalStringReader(text), writer);
} | java | public static void unescapeCsv(final String text, final Writer writer)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
CsvEscapeUtil.unescape(new InternalStringReader(text), writer);
} | [
"public",
"static",
"void",
"unescapeCsv",
"(",
"final",
"String",
"text",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Argument 'writer' can... | <p>
Perform a CSV <strong>unescape</strong> operation on a <tt>String</tt> input, writing results
to a <tt>Writer</tt>.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"a",
"CSV",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
">",
"Writer<",
"/",
"tt",
">",
".",
"<",
"/",
"p",
... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/csv/CsvEscape.java#L275-L284 |
alkacon/opencms-core | src/org/opencms/mail/CmsMailSettings.java | CmsMailSettings.addMailHost | public void addMailHost(String hostname, String order, String protocol, String username, String password) {
addMailHost(hostname, "25", order, protocol, null, username, password);
} | java | public void addMailHost(String hostname, String order, String protocol, String username, String password) {
addMailHost(hostname, "25", order, protocol, null, username, password);
} | [
"public",
"void",
"addMailHost",
"(",
"String",
"hostname",
",",
"String",
"order",
",",
"String",
"protocol",
",",
"String",
"username",
",",
"String",
"password",
")",
"{",
"addMailHost",
"(",
"hostname",
",",
"\"25\"",
",",
"order",
",",
"protocol",
",",
... | Adds a new mail host to the internal list of mail hosts with default port 25.<p>
@param hostname the name of the mail host
@param order the order in which the host is tried
@param protocol the protocol to use (default "smtp")
@param username the user name to use for authentication
@param password the password to use for authentication | [
"Adds",
"a",
"new",
"mail",
"host",
"to",
"the",
"internal",
"list",
"of",
"mail",
"hosts",
"with",
"default",
"port",
"25",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/mail/CmsMailSettings.java#L84-L87 |
dasein-cloud/dasein-cloud-aws | src/main/java/org/dasein/cloud/aws/compute/EC2Instance.java | EC2Instance.getPassword | @Override
public @Nullable String getPassword( @Nonnull String instanceId ) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getPassword");
try {
return new GetPassCallable(instanceId, getProvider()).call();
} catch( CloudException ce ) {
throw ce;
} catch( Exception e ) {
throw new InternalException(e);
} finally {
APITrace.end();
}
} | java | @Override
public @Nullable String getPassword( @Nonnull String instanceId ) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getPassword");
try {
return new GetPassCallable(instanceId, getProvider()).call();
} catch( CloudException ce ) {
throw ce;
} catch( Exception e ) {
throw new InternalException(e);
} finally {
APITrace.end();
}
} | [
"@",
"Override",
"public",
"@",
"Nullable",
"String",
"getPassword",
"(",
"@",
"Nonnull",
"String",
"instanceId",
")",
"throws",
"InternalException",
",",
"CloudException",
"{",
"APITrace",
".",
"begin",
"(",
"getProvider",
"(",
")",
",",
"\"getPassword\"",
")",... | Get encrypted initial Windows password. This method only definitely works with standard Amazon AMIs:
http://aws.amazon.com/windows/amis/
Other AMIs in the public library may have had their password changed, and it will not be retrievable on instances
launched from those.
@param instanceId
@return
@throws InternalException
@throws CloudException | [
"Get",
"encrypted",
"initial",
"Windows",
"password",
".",
"This",
"method",
"only",
"definitely",
"works",
"with",
"standard",
"Amazon",
"AMIs",
":",
"http",
":",
"//",
"aws",
".",
"amazon",
".",
"com",
"/",
"windows",
"/",
"amis",
"/",
"Other",
"AMIs",
... | train | https://github.com/dasein-cloud/dasein-cloud-aws/blob/05098574197a1f573f77447cadc39a76bf00b99d/src/main/java/org/dasein/cloud/aws/compute/EC2Instance.java#L432-L444 |
wildfly/wildfly-core | launcher/src/main/java/org/wildfly/core/launcher/CliCommandBuilder.java | CliCommandBuilder.setConnection | public CliCommandBuilder setConnection(final String hostname, final int port) {
addCliArgument(CliArgument.CONNECT);
setController(hostname, port);
return this;
} | java | public CliCommandBuilder setConnection(final String hostname, final int port) {
addCliArgument(CliArgument.CONNECT);
setController(hostname, port);
return this;
} | [
"public",
"CliCommandBuilder",
"setConnection",
"(",
"final",
"String",
"hostname",
",",
"final",
"int",
"port",
")",
"{",
"addCliArgument",
"(",
"CliArgument",
".",
"CONNECT",
")",
";",
"setController",
"(",
"hostname",
",",
"port",
")",
";",
"return",
"this"... | Sets the hostname and port to connect to.
<p>
This sets both the {@code --connect} and {@code --controller} arguments.
</p>
@param hostname the host name
@param port the port
@return the builder | [
"Sets",
"the",
"hostname",
"and",
"port",
"to",
"connect",
"to",
".",
"<p",
">",
"This",
"sets",
"both",
"the",
"{",
"@code",
"--",
"connect",
"}",
"and",
"{",
"@code",
"--",
"controller",
"}",
"arguments",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/launcher/src/main/java/org/wildfly/core/launcher/CliCommandBuilder.java#L155-L159 |
Azure/azure-sdk-for-java | servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/primitives/CoreMessageReceiver.java | CoreMessageReceiver.create | @Deprecated
public static CompletableFuture<CoreMessageReceiver> create(
final MessagingFactory factory,
final String name,
final String recvPath,
final int prefetchCount,
final SettleModePair settleModePair)
{
return create(factory, name, recvPath, prefetchCount, settleModePair, null);
} | java | @Deprecated
public static CompletableFuture<CoreMessageReceiver> create(
final MessagingFactory factory,
final String name,
final String recvPath,
final int prefetchCount,
final SettleModePair settleModePair)
{
return create(factory, name, recvPath, prefetchCount, settleModePair, null);
} | [
"@",
"Deprecated",
"public",
"static",
"CompletableFuture",
"<",
"CoreMessageReceiver",
">",
"create",
"(",
"final",
"MessagingFactory",
"factory",
",",
"final",
"String",
"name",
",",
"final",
"String",
"recvPath",
",",
"final",
"int",
"prefetchCount",
",",
"fina... | Connection has to be associated with Reactor before Creating a receiver on it. | [
"Connection",
"has",
"to",
"be",
"associated",
"with",
"Reactor",
"before",
"Creating",
"a",
"receiver",
"on",
"it",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/primitives/CoreMessageReceiver.java#L221-L230 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/pkcs/PKCS9Attributes.java | PKCS9Attributes.encode | public void encode(byte tag, OutputStream out) throws IOException {
out.write(tag);
out.write(derEncoding, 1, derEncoding.length -1);
} | java | public void encode(byte tag, OutputStream out) throws IOException {
out.write(tag);
out.write(derEncoding, 1, derEncoding.length -1);
} | [
"public",
"void",
"encode",
"(",
"byte",
"tag",
",",
"OutputStream",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"tag",
")",
";",
"out",
".",
"write",
"(",
"derEncoding",
",",
"1",
",",
"derEncoding",
".",
"length",
"-",
"1",
... | Put the DER encoding of this PKCS9 attribute set on an
DerOutputStream, tagged with the given implicit tag.
@param tag the implicit tag to use in the DER encoding.
@param out the output stream on which to put the DER encoding.
@exception IOException on output error. | [
"Put",
"the",
"DER",
"encoding",
"of",
"this",
"PKCS9",
"attribute",
"set",
"on",
"an",
"DerOutputStream",
"tagged",
"with",
"the",
"given",
"implicit",
"tag",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/pkcs/PKCS9Attributes.java#L238-L241 |
sagiegurari/fax4j | src/main/java/org/fax4j/spi/http/ApacheHTTPClient.java | ApacheHTTPClient.createMultiPartRequestContent | protected RequestEntity createMultiPartRequestContent(HTTPRequest httpRequest,HttpMethodBase httpMethodClient)
{
RequestEntity requestEntity=null;
ContentPart<?>[] contentParts=httpRequest.getContentAsParts();
if(contentParts!=null)
{
int partsAmount=contentParts.length;
if(partsAmount>0)
{
//init array
Part[] parts=new Part[partsAmount];
ContentPart<?> contentPart=null;
String name=null;
Object content=null;
ContentPartType contentPartType=null;
for(int index=0;index<partsAmount;index++)
{
//get next part
contentPart=contentParts[index];
if(contentPart!=null)
{
//get part values
name=contentPart.getName();
content=contentPart.getContent();
contentPartType=contentPart.getType();
//create new part
switch(contentPartType)
{
case FILE:
File file=(File)content;
try
{
parts[index]=new FilePart(name,file);
}
catch(FileNotFoundException exception)
{
throw new FaxException("Fax file: "+file.getAbsolutePath()+" not found.",exception);
}
break;
case STRING:
parts[index]=new StringPart(name,(String)content);
break;
default:
throw new FaxException("Unsupported content type provided: "+contentPartType);
}
}
}
requestEntity=new MultipartRequestEntity(parts,httpMethodClient.getParams());
}
}
return requestEntity;
} | java | protected RequestEntity createMultiPartRequestContent(HTTPRequest httpRequest,HttpMethodBase httpMethodClient)
{
RequestEntity requestEntity=null;
ContentPart<?>[] contentParts=httpRequest.getContentAsParts();
if(contentParts!=null)
{
int partsAmount=contentParts.length;
if(partsAmount>0)
{
//init array
Part[] parts=new Part[partsAmount];
ContentPart<?> contentPart=null;
String name=null;
Object content=null;
ContentPartType contentPartType=null;
for(int index=0;index<partsAmount;index++)
{
//get next part
contentPart=contentParts[index];
if(contentPart!=null)
{
//get part values
name=contentPart.getName();
content=contentPart.getContent();
contentPartType=contentPart.getType();
//create new part
switch(contentPartType)
{
case FILE:
File file=(File)content;
try
{
parts[index]=new FilePart(name,file);
}
catch(FileNotFoundException exception)
{
throw new FaxException("Fax file: "+file.getAbsolutePath()+" not found.",exception);
}
break;
case STRING:
parts[index]=new StringPart(name,(String)content);
break;
default:
throw new FaxException("Unsupported content type provided: "+contentPartType);
}
}
}
requestEntity=new MultipartRequestEntity(parts,httpMethodClient.getParams());
}
}
return requestEntity;
} | [
"protected",
"RequestEntity",
"createMultiPartRequestContent",
"(",
"HTTPRequest",
"httpRequest",
",",
"HttpMethodBase",
"httpMethodClient",
")",
"{",
"RequestEntity",
"requestEntity",
"=",
"null",
";",
"ContentPart",
"<",
"?",
">",
"[",
"]",
"contentParts",
"=",
"htt... | This function creates a multi part type request entity and populates it
with the data from the provided HTTP request.
@param httpRequest
The HTTP request
@param httpMethodClient
The apache HTTP method
@return The request entity | [
"This",
"function",
"creates",
"a",
"multi",
"part",
"type",
"request",
"entity",
"and",
"populates",
"it",
"with",
"the",
"data",
"from",
"the",
"provided",
"HTTP",
"request",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/http/ApacheHTTPClient.java#L331-L387 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/util/impl/DOMImpl.java | DOMImpl.createIFrameElement | public com.google.gwt.dom.client.Element createIFrameElement(Document doc, String name) {
IFrameElement element = doc.createIFrameElement();
element.setName(name);
return element;
} | java | public com.google.gwt.dom.client.Element createIFrameElement(Document doc, String name) {
IFrameElement element = doc.createIFrameElement();
element.setName(name);
return element;
} | [
"public",
"com",
".",
"google",
".",
"gwt",
".",
"dom",
".",
"client",
".",
"Element",
"createIFrameElement",
"(",
"Document",
"doc",
",",
"String",
"name",
")",
"{",
"IFrameElement",
"element",
"=",
"doc",
".",
"createIFrameElement",
"(",
")",
";",
"eleme... | Creates an iFrame element with the given name attribute.<p>
@param doc the document
@param name the name attribute value
@return the iFrame element | [
"Creates",
"an",
"iFrame",
"element",
"with",
"the",
"given",
"name",
"attribute",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/impl/DOMImpl.java#L50-L55 |
JadiraOrg/jadira | bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java | BasicBinder.registerUnmarshaller | public final <S, T> void registerUnmarshaller(Class<S> source, Class<T> target, FromUnmarshaller<S, T> converter, Class<? extends Annotation> qualifier) {
registerUnmarshaller(new ConverterKey<S,T>(source, target, qualifier == null ? DefaultBinding.class : qualifier), converter);
} | java | public final <S, T> void registerUnmarshaller(Class<S> source, Class<T> target, FromUnmarshaller<S, T> converter, Class<? extends Annotation> qualifier) {
registerUnmarshaller(new ConverterKey<S,T>(source, target, qualifier == null ? DefaultBinding.class : qualifier), converter);
} | [
"public",
"final",
"<",
"S",
",",
"T",
">",
"void",
"registerUnmarshaller",
"(",
"Class",
"<",
"S",
">",
"source",
",",
"Class",
"<",
"T",
">",
"target",
",",
"FromUnmarshaller",
"<",
"S",
",",
"T",
">",
"converter",
",",
"Class",
"<",
"?",
"extends"... | Register an UnMarshaller with the given source and target class.
The unmarshaller is used as follows: Instances of the source can be marshalled into the target class.
@param source The source (input) class
@param target The target (output) class
@param converter The FromUnmarshaller to be registered
@param qualifier The qualifier for which the unmarshaller must be registered | [
"Register",
"an",
"UnMarshaller",
"with",
"the",
"given",
"source",
"and",
"target",
"class",
".",
"The",
"unmarshaller",
"is",
"used",
"as",
"follows",
":",
"Instances",
"of",
"the",
"source",
"can",
"be",
"marshalled",
"into",
"the",
"target",
"class",
"."... | train | https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java#L623-L625 |
openengsb/openengsb | components/services/src/main/java/org/openengsb/core/services/internal/security/ldap/EntryFactory.java | EntryFactory.namedObject | public static Entry namedObject(String name, Dn baseDn) {
Dn dn = LdapUtils.concatDn(SchemaConstants.CN_ATTRIBUTE, name, baseDn);
Entry entry = new DefaultEntry(dn);
try {
entry.add(SchemaConstants.OBJECT_CLASS_ATTRIBUTE, SchemaConstants.NAMED_OBJECT_OC);
entry.add(SchemaConstants.CN_ATTRIBUTE, name);
} catch (LdapException e) {
throw new LdapRuntimeException(e);
}
return entry;
} | java | public static Entry namedObject(String name, Dn baseDn) {
Dn dn = LdapUtils.concatDn(SchemaConstants.CN_ATTRIBUTE, name, baseDn);
Entry entry = new DefaultEntry(dn);
try {
entry.add(SchemaConstants.OBJECT_CLASS_ATTRIBUTE, SchemaConstants.NAMED_OBJECT_OC);
entry.add(SchemaConstants.CN_ATTRIBUTE, name);
} catch (LdapException e) {
throw new LdapRuntimeException(e);
}
return entry;
} | [
"public",
"static",
"Entry",
"namedObject",
"(",
"String",
"name",
",",
"Dn",
"baseDn",
")",
"{",
"Dn",
"dn",
"=",
"LdapUtils",
".",
"concatDn",
"(",
"SchemaConstants",
".",
"CN_ATTRIBUTE",
",",
"name",
",",
"baseDn",
")",
";",
"Entry",
"entry",
"=",
"ne... | Returns an {@link Entry} whose {@link Dn} is baseDn followed by name as Rdn. The attribute type of the Rdn is
'common name'. | [
"Returns",
"an",
"{"
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/services/src/main/java/org/openengsb/core/services/internal/security/ldap/EntryFactory.java#L61-L71 |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/types/CompareHelper.java | CompareHelper.lt | public static <T> boolean lt(Comparable<T> a, T b)
{
return lt(a.compareTo(b));
} | java | public static <T> boolean lt(Comparable<T> a, T b)
{
return lt(a.compareTo(b));
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"lt",
"(",
"Comparable",
"<",
"T",
">",
"a",
",",
"T",
"b",
")",
"{",
"return",
"lt",
"(",
"a",
".",
"compareTo",
"(",
"b",
")",
")",
";",
"}"
] | <code>a < b</code>
@param <T>
@param a
@param b
@return true if a < b | [
"<code",
">",
"a",
"<",
"b<",
"/",
"code",
">"
] | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/CompareHelper.java#L82-L85 |
kaazing/gateway | resource.address/spi/src/main/java/org/kaazing/gateway/resource/address/ResourceAddressFactory.java | ResourceAddressFactory.newResourceAddress | public ResourceAddress newResourceAddress(String location, ResourceOptions options) {
return newResourceAddress(location, options, null /* qualifier */);
} | java | public ResourceAddress newResourceAddress(String location, ResourceOptions options) {
return newResourceAddress(location, options, null /* qualifier */);
} | [
"public",
"ResourceAddress",
"newResourceAddress",
"(",
"String",
"location",
",",
"ResourceOptions",
"options",
")",
"{",
"return",
"newResourceAddress",
"(",
"location",
",",
"options",
",",
"null",
"/* qualifier */",
")",
";",
"}"
] | Creates a new resource address for the given location and options
@param options cannot be null, otherwise NullPointerException is thrown
@return resource address | [
"Creates",
"a",
"new",
"resource",
"address",
"for",
"the",
"given",
"location",
"and",
"options"
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/resource.address/spi/src/main/java/org/kaazing/gateway/resource/address/ResourceAddressFactory.java#L134-L136 |
pravega/pravega | controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java | StreamMetrics.truncateStreamFailed | public void truncateStreamFailed(String scope, String streamName) {
DYNAMIC_LOGGER.incCounterValue(globalMetricName(TRUNCATE_STREAM_FAILED), 1);
DYNAMIC_LOGGER.incCounterValue(TRUNCATE_STREAM_FAILED, 1, streamTags(scope, streamName));
} | java | public void truncateStreamFailed(String scope, String streamName) {
DYNAMIC_LOGGER.incCounterValue(globalMetricName(TRUNCATE_STREAM_FAILED), 1);
DYNAMIC_LOGGER.incCounterValue(TRUNCATE_STREAM_FAILED, 1, streamTags(scope, streamName));
} | [
"public",
"void",
"truncateStreamFailed",
"(",
"String",
"scope",
",",
"String",
"streamName",
")",
"{",
"DYNAMIC_LOGGER",
".",
"incCounterValue",
"(",
"globalMetricName",
"(",
"TRUNCATE_STREAM_FAILED",
")",
",",
"1",
")",
";",
"DYNAMIC_LOGGER",
".",
"incCounterValu... | This method increments the counter of failed Stream truncate operations in the system as well as the failed
truncate attempts for this specific Stream.
@param scope Scope.
@param streamName Name of the Stream. | [
"This",
"method",
"increments",
"the",
"counter",
"of",
"failed",
"Stream",
"truncate",
"operations",
"in",
"the",
"system",
"as",
"well",
"as",
"the",
"failed",
"truncate",
"attempts",
"for",
"this",
"specific",
"Stream",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java#L178-L181 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/Kickflip.java | Kickflip.addLocationToStream | public static void addLocationToStream(final Context context, final Stream stream, final EventBus eventBus) {
DeviceLocation.getLastKnownLocation(context, false, new DeviceLocation.LocationResult() {
@Override
public void gotLocation(Location location) {
stream.setLatitude(location.getLatitude());
stream.setLongitude(location.getLongitude());
try {
Geocoder geocoder = new Geocoder(context);
Address address = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1).get(0);
stream.setCity(address.getLocality());
stream.setCountry(address.getCountryName());
stream.setState(address.getAdminArea());
if (eventBus != null) {
eventBus.post(new StreamLocationAddedEvent());
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
} | java | public static void addLocationToStream(final Context context, final Stream stream, final EventBus eventBus) {
DeviceLocation.getLastKnownLocation(context, false, new DeviceLocation.LocationResult() {
@Override
public void gotLocation(Location location) {
stream.setLatitude(location.getLatitude());
stream.setLongitude(location.getLongitude());
try {
Geocoder geocoder = new Geocoder(context);
Address address = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1).get(0);
stream.setCity(address.getLocality());
stream.setCountry(address.getCountryName());
stream.setState(address.getAdminArea());
if (eventBus != null) {
eventBus.post(new StreamLocationAddedEvent());
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
} | [
"public",
"static",
"void",
"addLocationToStream",
"(",
"final",
"Context",
"context",
",",
"final",
"Stream",
"stream",
",",
"final",
"EventBus",
"eventBus",
")",
"{",
"DeviceLocation",
".",
"getLastKnownLocation",
"(",
"context",
",",
"false",
",",
"new",
"Dev... | Convenience method for attaching the current reverse geocoded device location to a given
{@link io.kickflip.sdk.api.json.Stream}
@param context the host application {@link android.content.Context}
@param stream the {@link io.kickflip.sdk.api.json.Stream} to attach location to
@param eventBus an {@link com.google.common.eventbus.EventBus} to be notified of the complete action | [
"Convenience",
"method",
"for",
"attaching",
"the",
"current",
"reverse",
"geocoded",
"device",
"location",
"to",
"a",
"given",
"{",
"@link",
"io",
".",
"kickflip",
".",
"sdk",
".",
"api",
".",
"json",
".",
"Stream",
"}"
] | train | https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/Kickflip.java#L191-L214 |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/util/DateUtilities.java | DateUtilities.addDays | public static Date addDays(long dt, int days)
{
Calendar c = getCalendar();
if(dt > 0L)
c.setTimeInMillis(dt);
c.add(Calendar.DATE, days);
return c.getTime();
} | java | public static Date addDays(long dt, int days)
{
Calendar c = getCalendar();
if(dt > 0L)
c.setTimeInMillis(dt);
c.add(Calendar.DATE, days);
return c.getTime();
} | [
"public",
"static",
"Date",
"addDays",
"(",
"long",
"dt",
",",
"int",
"days",
")",
"{",
"Calendar",
"c",
"=",
"getCalendar",
"(",
")",
";",
"if",
"(",
"dt",
">",
"0L",
")",
"c",
".",
"setTimeInMillis",
"(",
"dt",
")",
";",
"c",
".",
"add",
"(",
... | Returns the given date adding the given number of days.
@param dt The date to add the days to
@param days The number of days to add. To subtract days, use a negative value.
@return The date with the given days added | [
"Returns",
"the",
"given",
"date",
"adding",
"the",
"given",
"number",
"of",
"days",
"."
] | train | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/util/DateUtilities.java#L354-L361 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractInput.java | AbstractInput.doHandleChanged | protected void doHandleChanged() {
// If there is an associated action, execute it
if (getActionOnChange() != null) {
final ActionEvent event = new ActionEvent(this, getActionCommand(), getActionObject());
final boolean isCAT = isCurrentAjaxTrigger();
Runnable later = new Runnable() {
@Override
public void run() {
getActionOnChange().execute(event);
if (isCAT && UIContextHolder.getCurrent().getFocussed() == null) {
setFocussed();
}
}
};
invokeLater(later);
} else if (AjaxHelper.isCurrentAjaxTrigger(this) && UIContextHolder.getCurrent().getFocussed() == null) {
setFocussed();
}
} | java | protected void doHandleChanged() {
// If there is an associated action, execute it
if (getActionOnChange() != null) {
final ActionEvent event = new ActionEvent(this, getActionCommand(), getActionObject());
final boolean isCAT = isCurrentAjaxTrigger();
Runnable later = new Runnable() {
@Override
public void run() {
getActionOnChange().execute(event);
if (isCAT && UIContextHolder.getCurrent().getFocussed() == null) {
setFocussed();
}
}
};
invokeLater(later);
} else if (AjaxHelper.isCurrentAjaxTrigger(this) && UIContextHolder.getCurrent().getFocussed() == null) {
setFocussed();
}
} | [
"protected",
"void",
"doHandleChanged",
"(",
")",
"{",
"// If there is an associated action, execute it",
"if",
"(",
"getActionOnChange",
"(",
")",
"!=",
"null",
")",
"{",
"final",
"ActionEvent",
"event",
"=",
"new",
"ActionEvent",
"(",
"this",
",",
"getActionComman... | Perform change logic for this component.
<p>Reset focus ONLY if the current Request is an Ajax request. See https://github.com/BorderTech/wcomponents/issues/501.</p> | [
"Perform",
"change",
"logic",
"for",
"this",
"component",
".",
"<p",
">",
"Reset",
"focus",
"ONLY",
"if",
"the",
"current",
"Request",
"is",
"an",
"Ajax",
"request",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"BorderTech",
"/",
"wcomponen... | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractInput.java#L301-L320 |
jbundle/jbundle | base/remote/src/main/java/org/jbundle/base/remote/db/TableSession.java | TableSession.set | public void set(Object data, int iOpenMode) throws DBException, RemoteException
{
Record record = this.getMainRecord();
int iOldOpenMode = record.getOpenMode();
try {
Utility.getLogger().info("EJB Set");
synchronized (this.getTask())
{
record.setOpenMode((iOldOpenMode & ~DBConstants.LOCK_TYPE_MASK) | (iOpenMode & DBConstants.LOCK_TYPE_MASK)); // Use client's lock data
if (record.getEditMode() == Constants.EDIT_CURRENT)
record.edit();
Record recordBase = record.getTable().getCurrentTable().getRecord();
int iFieldTypes = this.getFieldTypes(recordBase);
int iErrorCode = this.moveBufferToFields(data, iFieldTypes, recordBase);
if (iErrorCode != DBConstants.NORMAL_RETURN)
; //?
if (DBConstants.TRUE.equals(record.getTable().getProperty(DBParams.SUPRESSREMOTEDBMESSAGES)))
record.setSupressRemoteMessages(true);
record.getTable().set(recordBase);
}
} catch (DBException ex) {
throw ex;
} catch (Exception ex) {
ex.printStackTrace();
throw new DBException(ex.getMessage());
} finally {
record.setSupressRemoteMessages(false);
this.getMainRecord().setOpenMode(iOldOpenMode);
}
} | java | public void set(Object data, int iOpenMode) throws DBException, RemoteException
{
Record record = this.getMainRecord();
int iOldOpenMode = record.getOpenMode();
try {
Utility.getLogger().info("EJB Set");
synchronized (this.getTask())
{
record.setOpenMode((iOldOpenMode & ~DBConstants.LOCK_TYPE_MASK) | (iOpenMode & DBConstants.LOCK_TYPE_MASK)); // Use client's lock data
if (record.getEditMode() == Constants.EDIT_CURRENT)
record.edit();
Record recordBase = record.getTable().getCurrentTable().getRecord();
int iFieldTypes = this.getFieldTypes(recordBase);
int iErrorCode = this.moveBufferToFields(data, iFieldTypes, recordBase);
if (iErrorCode != DBConstants.NORMAL_RETURN)
; //?
if (DBConstants.TRUE.equals(record.getTable().getProperty(DBParams.SUPRESSREMOTEDBMESSAGES)))
record.setSupressRemoteMessages(true);
record.getTable().set(recordBase);
}
} catch (DBException ex) {
throw ex;
} catch (Exception ex) {
ex.printStackTrace();
throw new DBException(ex.getMessage());
} finally {
record.setSupressRemoteMessages(false);
this.getMainRecord().setOpenMode(iOldOpenMode);
}
} | [
"public",
"void",
"set",
"(",
"Object",
"data",
",",
"int",
"iOpenMode",
")",
"throws",
"DBException",
",",
"RemoteException",
"{",
"Record",
"record",
"=",
"this",
".",
"getMainRecord",
"(",
")",
";",
"int",
"iOldOpenMode",
"=",
"record",
".",
"getOpenMode"... | Update the current record.
This method has some wierd code to emulate the way behaviors are called on a write.
@param The data to update.
@exception DBException File exception. | [
"Update",
"the",
"current",
"record",
".",
"This",
"method",
"has",
"some",
"wierd",
"code",
"to",
"emulate",
"the",
"way",
"behaviors",
"are",
"called",
"on",
"a",
"write",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/remote/src/main/java/org/jbundle/base/remote/db/TableSession.java#L354-L383 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.containsIgnoreCase | public static boolean containsIgnoreCase (@Nullable final String sText,
@Nullable final String sSearch,
@Nonnull final Locale aSortLocale)
{
return getIndexOfIgnoreCase (sText, sSearch, aSortLocale) != STRING_NOT_FOUND;
} | java | public static boolean containsIgnoreCase (@Nullable final String sText,
@Nullable final String sSearch,
@Nonnull final Locale aSortLocale)
{
return getIndexOfIgnoreCase (sText, sSearch, aSortLocale) != STRING_NOT_FOUND;
} | [
"public",
"static",
"boolean",
"containsIgnoreCase",
"(",
"@",
"Nullable",
"final",
"String",
"sText",
",",
"@",
"Nullable",
"final",
"String",
"sSearch",
",",
"@",
"Nonnull",
"final",
"Locale",
"aSortLocale",
")",
"{",
"return",
"getIndexOfIgnoreCase",
"(",
"sT... | Check if sSearch is contained within sText ignoring case.
@param sText
The text to search in. May be <code>null</code>.
@param sSearch
The text to search for. May be <code>null</code>.
@param aSortLocale
The locale to be used for case unifying.
@return <code>true</code> if sSearch is contained in sText,
<code>false</code> otherwise.
@see String#contains(CharSequence) | [
"Check",
"if",
"sSearch",
"is",
"contained",
"within",
"sText",
"ignoring",
"case",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L3062-L3067 |
Azure/azure-sdk-for-java | streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/InputsInner.java | InputsInner.getAsync | public Observable<InputInner> getAsync(String resourceGroupName, String jobName, String inputName) {
return getWithServiceResponseAsync(resourceGroupName, jobName, inputName).map(new Func1<ServiceResponseWithHeaders<InputInner, InputsGetHeaders>, InputInner>() {
@Override
public InputInner call(ServiceResponseWithHeaders<InputInner, InputsGetHeaders> response) {
return response.body();
}
});
} | java | public Observable<InputInner> getAsync(String resourceGroupName, String jobName, String inputName) {
return getWithServiceResponseAsync(resourceGroupName, jobName, inputName).map(new Func1<ServiceResponseWithHeaders<InputInner, InputsGetHeaders>, InputInner>() {
@Override
public InputInner call(ServiceResponseWithHeaders<InputInner, InputsGetHeaders> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"InputInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"jobName",
",",
"String",
"inputName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"jobName",
",",
"inputName",
")",
... | Gets details about the specified input.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param jobName The name of the streaming job.
@param inputName The name of the input.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the InputInner object | [
"Gets",
"details",
"about",
"the",
"specified",
"input",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/InputsInner.java#L641-L648 |
hibernate/hibernate-ogm | neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/EmbeddedNeo4jDialect.java | EmbeddedNeo4jDialect.createRelationship | private Relationship createRelationship(AssociationKey associationKey, Tuple associationRow, AssociatedEntityKeyMetadata associatedEntityKeyMetadata, AssociationContext associationContext) {
switch ( associationKey.getMetadata().getAssociationKind() ) {
case EMBEDDED_COLLECTION:
return createRelationshipWithEmbeddedNode( associationKey, associationRow, associatedEntityKeyMetadata );
case ASSOCIATION:
return findOrCreateRelationshipWithEntityNode( associationKey, associationRow, associatedEntityKeyMetadata, associationContext.getTupleTypeContext() );
default:
throw new AssertionFailure( "Unrecognized associationKind: " + associationKey.getMetadata().getAssociationKind() );
}
} | java | private Relationship createRelationship(AssociationKey associationKey, Tuple associationRow, AssociatedEntityKeyMetadata associatedEntityKeyMetadata, AssociationContext associationContext) {
switch ( associationKey.getMetadata().getAssociationKind() ) {
case EMBEDDED_COLLECTION:
return createRelationshipWithEmbeddedNode( associationKey, associationRow, associatedEntityKeyMetadata );
case ASSOCIATION:
return findOrCreateRelationshipWithEntityNode( associationKey, associationRow, associatedEntityKeyMetadata, associationContext.getTupleTypeContext() );
default:
throw new AssertionFailure( "Unrecognized associationKind: " + associationKey.getMetadata().getAssociationKind() );
}
} | [
"private",
"Relationship",
"createRelationship",
"(",
"AssociationKey",
"associationKey",
",",
"Tuple",
"associationRow",
",",
"AssociatedEntityKeyMetadata",
"associatedEntityKeyMetadata",
",",
"AssociationContext",
"associationContext",
")",
"{",
"switch",
"(",
"associationKey... | When dealing with some scenarios like, for example, a bidirectional association, OGM calls this method twice:
<p>
the first time with the information related to the owner of the association and the {@link RowKey},
the second time using the same {@link RowKey} but with the {@link AssociationKey} referring to the other side of the association.
@param associatedEntityKeyMetadata
@param associationContext | [
"When",
"dealing",
"with",
"some",
"scenarios",
"like",
"for",
"example",
"a",
"bidirectional",
"association",
"OGM",
"calls",
"this",
"method",
"twice",
":",
"<p",
">",
"the",
"first",
"time",
"with",
"the",
"information",
"related",
"to",
"the",
"owner",
"... | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/EmbeddedNeo4jDialect.java#L241-L250 |
cycorp/api-suite | core-api/src/main/java/com/cyc/session/exception/SessionServiceException.java | SessionServiceException.fromThrowable | public static SessionServiceException fromThrowable(Class interfaceClass, Throwable cause) {
return (cause instanceof SessionServiceException
&& Objects.equals(interfaceClass, ((SessionServiceException) cause).getInterfaceClass()))
? (SessionServiceException) cause
: new SessionServiceException(interfaceClass, cause);
} | java | public static SessionServiceException fromThrowable(Class interfaceClass, Throwable cause) {
return (cause instanceof SessionServiceException
&& Objects.equals(interfaceClass, ((SessionServiceException) cause).getInterfaceClass()))
? (SessionServiceException) cause
: new SessionServiceException(interfaceClass, cause);
} | [
"public",
"static",
"SessionServiceException",
"fromThrowable",
"(",
"Class",
"interfaceClass",
",",
"Throwable",
"cause",
")",
"{",
"return",
"(",
"cause",
"instanceof",
"SessionServiceException",
"&&",
"Objects",
".",
"equals",
"(",
"interfaceClass",
",",
"(",
"("... | Converts a Throwable to a SessionServiceException. If the Throwable is a
SessionServiceException, it will be passed through unmodified; otherwise, it will be wrapped
in a new SessionServiceException.
@param cause the Throwable to convert
@param interfaceClass
@return a SessionServiceException | [
"Converts",
"a",
"Throwable",
"to",
"a",
"SessionServiceException",
".",
"If",
"the",
"Throwable",
"is",
"a",
"SessionServiceException",
"it",
"will",
"be",
"passed",
"through",
"unmodified",
";",
"otherwise",
"it",
"will",
"be",
"wrapped",
"in",
"a",
"new",
"... | train | https://github.com/cycorp/api-suite/blob/1d52affabc4635e3715a059e38741712cbdbf2d5/core-api/src/main/java/com/cyc/session/exception/SessionServiceException.java#L45-L50 |
plaid/plaid-java | src/main/java/com/plaid/client/PlaidClient.java | PlaidClient.parseError | public ErrorResponse parseError(Response response) {
if (response.isSuccessful()) {
throw new IllegalArgumentException("Response must be unsuccessful.");
}
Converter<ResponseBody, ErrorResponse> responseBodyObjectConverter =
retrofit.responseBodyConverter(ErrorResponse.class, new Annotation[0]);
try {
return responseBodyObjectConverter.convert(response.errorBody());
} catch (IOException ex) {
throw new RuntimeException("Could not parse error response", ex);
}
} | java | public ErrorResponse parseError(Response response) {
if (response.isSuccessful()) {
throw new IllegalArgumentException("Response must be unsuccessful.");
}
Converter<ResponseBody, ErrorResponse> responseBodyObjectConverter =
retrofit.responseBodyConverter(ErrorResponse.class, new Annotation[0]);
try {
return responseBodyObjectConverter.convert(response.errorBody());
} catch (IOException ex) {
throw new RuntimeException("Could not parse error response", ex);
}
} | [
"public",
"ErrorResponse",
"parseError",
"(",
"Response",
"response",
")",
"{",
"if",
"(",
"response",
".",
"isSuccessful",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Response must be unsuccessful.\"",
")",
";",
"}",
"Converter",
"<",
... | A helper to assist with decoding unsuccessful responses.
This is not done automatically, because an unsuccessful result may have many causes
such as network issues, intervening HTTP proxies, load balancers, partial responses, etc,
which means that a response can easily be incomplete, or not even the expected well-formed
JSON error.
Therefore, even when using this helper, be prepared for it to throw an exception instead of
successfully decoding every error response!
@param response the unsuccessful response object to deserialize.
@return the resulting {@link ErrorResponse}, assuming deserialization succeeded.
@throws RuntimeException if the response cannot be deserialized | [
"A",
"helper",
"to",
"assist",
"with",
"decoding",
"unsuccessful",
"responses",
"."
] | train | https://github.com/plaid/plaid-java/blob/360f1f8a5178fa0c3c2c2e07a58f8ccec5f33117/src/main/java/com/plaid/client/PlaidClient.java#L80-L93 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/NonCollectionMethodUse.java | NonCollectionMethodUse.sawOpcode | @Override
public void sawOpcode(int seen) {
if (seen == Const.INVOKEVIRTUAL) {
String className = getClassConstantOperand();
String methodName = getNameConstantOperand();
String methodSig = getSigConstantOperand();
FQMethod methodInfo = new FQMethod(className, methodName, methodSig);
if (oldMethods.contains(methodInfo)) {
bugReporter.reportBug(new BugInstance(this, BugType.NCMU_NON_COLLECTION_METHOD_USE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(this));
}
}
} | java | @Override
public void sawOpcode(int seen) {
if (seen == Const.INVOKEVIRTUAL) {
String className = getClassConstantOperand();
String methodName = getNameConstantOperand();
String methodSig = getSigConstantOperand();
FQMethod methodInfo = new FQMethod(className, methodName, methodSig);
if (oldMethods.contains(methodInfo)) {
bugReporter.reportBug(new BugInstance(this, BugType.NCMU_NON_COLLECTION_METHOD_USE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(this));
}
}
} | [
"@",
"Override",
"public",
"void",
"sawOpcode",
"(",
"int",
"seen",
")",
"{",
"if",
"(",
"seen",
"==",
"Const",
".",
"INVOKEVIRTUAL",
")",
"{",
"String",
"className",
"=",
"getClassConstantOperand",
"(",
")",
";",
"String",
"methodName",
"=",
"getNameConstan... | implements the visitor to look for method calls that are one of the old pre-collections1.2 set of methods
@param seen
the currently parsed opcode | [
"implements",
"the",
"visitor",
"to",
"look",
"for",
"method",
"calls",
"that",
"are",
"one",
"of",
"the",
"old",
"pre",
"-",
"collections1",
".",
"2",
"set",
"of",
"methods"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/NonCollectionMethodUse.java#L70-L83 |
find-sec-bugs/find-sec-bugs | findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/injection/BasicInjectionDetector.java | BasicInjectionDetector.loadSink | protected void loadSink(String line, String bugType) {
SINKS_LOADER.loadSink(line, bugType, new SinksLoader.InjectionPointReceiver() {
@Override
public void receiveInjectionPoint(String fullMethodName, InjectionPoint injectionPoint) {
addParsedInjectionPoint(fullMethodName, injectionPoint);
}
});
} | java | protected void loadSink(String line, String bugType) {
SINKS_LOADER.loadSink(line, bugType, new SinksLoader.InjectionPointReceiver() {
@Override
public void receiveInjectionPoint(String fullMethodName, InjectionPoint injectionPoint) {
addParsedInjectionPoint(fullMethodName, injectionPoint);
}
});
} | [
"protected",
"void",
"loadSink",
"(",
"String",
"line",
",",
"String",
"bugType",
")",
"{",
"SINKS_LOADER",
".",
"loadSink",
"(",
"line",
",",
"bugType",
",",
"new",
"SinksLoader",
".",
"InjectionPointReceiver",
"(",
")",
"{",
"@",
"Override",
"public",
"voi... | Loads a single taint sink (like a line of configuration)
@param line specification of the sink
@param bugType type of an injection bug | [
"Loads",
"a",
"single",
"taint",
"sink",
"(",
"like",
"a",
"line",
"of",
"configuration",
")"
] | train | https://github.com/find-sec-bugs/find-sec-bugs/blob/362da013cef4925e6a1506dd3511fe5bdcc5fba3/findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/injection/BasicInjectionDetector.java#L176-L183 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/cache/ObjectCacheTwoLevelImpl.java | ObjectCacheTwoLevelImpl.beforeClose | public void beforeClose(PBStateEvent event)
{
/*
arminw:
this is a workaround for use in managed environments. When a PB instance is used
within a container a PB.close call is done when leave the container method. This close
the PB handle (but the real instance is still in use) and the PB listener are notified.
But the JTA tx was not committed at
this point in time and the session cache should not be cleared, because the updated/new
objects will be pushed to the real cache on commit call (if we clear, nothing to push).
So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle
is closed), if true we don't reset the session cache.
*/
if(!broker.isInTransaction())
{
if(log.isDebugEnabled()) log.debug("Clearing the session cache");
resetSessionCache();
}
} | java | public void beforeClose(PBStateEvent event)
{
/*
arminw:
this is a workaround for use in managed environments. When a PB instance is used
within a container a PB.close call is done when leave the container method. This close
the PB handle (but the real instance is still in use) and the PB listener are notified.
But the JTA tx was not committed at
this point in time and the session cache should not be cleared, because the updated/new
objects will be pushed to the real cache on commit call (if we clear, nothing to push).
So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle
is closed), if true we don't reset the session cache.
*/
if(!broker.isInTransaction())
{
if(log.isDebugEnabled()) log.debug("Clearing the session cache");
resetSessionCache();
}
} | [
"public",
"void",
"beforeClose",
"(",
"PBStateEvent",
"event",
")",
"{",
"/*\r\n arminw:\r\n this is a workaround for use in managed environments. When a PB instance is used\r\n within a container a PB.close call is done when leave the container method. This close\r\n the... | Before closing the PersistenceBroker ensure that the session
cache is cleared | [
"Before",
"closing",
"the",
"PersistenceBroker",
"ensure",
"that",
"the",
"session",
"cache",
"is",
"cleared"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/cache/ObjectCacheTwoLevelImpl.java#L518-L536 |
WhereIsMyTransport/TransportApiSdk.Java | transportapisdk/src/main/java/transportapisdk/TransportApiClient.java | TransportApiClient.getStopsNearby | public TransportApiResult<List<Stop>> getStopsNearby(StopQueryOptions options, double latitude, double longitude, int radiusInMeters)
{
if (options == null)
{
options = StopQueryOptions.defaultQueryOptions();
}
if (radiusInMeters < 0)
{
throw new IllegalArgumentException("Invalid limit. Valid values are positive numbers only.");
}
return TransportApiClientCalls.getStops(tokenComponent, settings, options, new Point(longitude, latitude), radiusInMeters, null);
} | java | public TransportApiResult<List<Stop>> getStopsNearby(StopQueryOptions options, double latitude, double longitude, int radiusInMeters)
{
if (options == null)
{
options = StopQueryOptions.defaultQueryOptions();
}
if (radiusInMeters < 0)
{
throw new IllegalArgumentException("Invalid limit. Valid values are positive numbers only.");
}
return TransportApiClientCalls.getStops(tokenComponent, settings, options, new Point(longitude, latitude), radiusInMeters, null);
} | [
"public",
"TransportApiResult",
"<",
"List",
"<",
"Stop",
">",
">",
"getStopsNearby",
"(",
"StopQueryOptions",
"options",
",",
"double",
"latitude",
",",
"double",
"longitude",
",",
"int",
"radiusInMeters",
")",
"{",
"if",
"(",
"options",
"==",
"null",
")",
... | Gets a list of stops nearby ordered by distance from the point specified.
@param options Options to limit the results by. Default: StopQueryOptions.defaultQueryOptions()
@param latitude Latitude in decimal degrees.
@param longitude Longitude in decimal degrees.
@param radiusInMeters Radius in meters to filter results by.
@return A list of stops nearby the specified point. | [
"Gets",
"a",
"list",
"of",
"stops",
"nearby",
"ordered",
"by",
"distance",
"from",
"the",
"point",
"specified",
"."
] | train | https://github.com/WhereIsMyTransport/TransportApiSdk.Java/blob/f4ade7046c8dadfcb2976ee354f85f67a6e930a2/transportapisdk/src/main/java/transportapisdk/TransportApiClient.java#L300-L313 |
vvakame/JsonPullParser | jsonpullparser-apt/src/main/java/net/vvakame/util/jsonpullparser/factory/JsonModelGenerator.java | JsonModelGenerator.from | public static JsonModelGenerator from(Element element, String classNamePostfix) {
JsonModelGenerator generator = new JsonModelGenerator(element, classNamePostfix);
generator.processJsonModel();
generator.processJsonKeys();
generator.processStoreJson();
if (generator.jsonModel.existsBase) {
JsonModelGenerator baseGenerator =
from(generator.jsonModel.targetBaseElement, classNamePostfix);
generator.jsonModel.getInheritKeys().addAll(baseGenerator.jsonModel.getKeys());
}
return generator;
} | java | public static JsonModelGenerator from(Element element, String classNamePostfix) {
JsonModelGenerator generator = new JsonModelGenerator(element, classNamePostfix);
generator.processJsonModel();
generator.processJsonKeys();
generator.processStoreJson();
if (generator.jsonModel.existsBase) {
JsonModelGenerator baseGenerator =
from(generator.jsonModel.targetBaseElement, classNamePostfix);
generator.jsonModel.getInheritKeys().addAll(baseGenerator.jsonModel.getKeys());
}
return generator;
} | [
"public",
"static",
"JsonModelGenerator",
"from",
"(",
"Element",
"element",
",",
"String",
"classNamePostfix",
")",
"{",
"JsonModelGenerator",
"generator",
"=",
"new",
"JsonModelGenerator",
"(",
"element",
",",
"classNamePostfix",
")",
";",
"generator",
".",
"proce... | Process {@link Element} to generate.
@param element
@param classNamePostfix
@return {@link JsonModelGenerator}
@author vvakame | [
"Process",
"{"
] | train | https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-apt/src/main/java/net/vvakame/util/jsonpullparser/factory/JsonModelGenerator.java#L92-L106 |
johncarl81/transfuse | transfuse-support/src/main/java/org/androidtransfuse/util/Contract.java | Contract.atLength | public static void atLength(final Object[] array, final int length, final String arrayName) {
notNull(array, arrayName);
notNegative(length, "length");
if (array.length != length) {
throw new IllegalArgumentException("expecting " + maskNullArgument(arrayName) + " to be of length " + length + ".");
}
} | java | public static void atLength(final Object[] array, final int length, final String arrayName) {
notNull(array, arrayName);
notNegative(length, "length");
if (array.length != length) {
throw new IllegalArgumentException("expecting " + maskNullArgument(arrayName) + " to be of length " + length + ".");
}
} | [
"public",
"static",
"void",
"atLength",
"(",
"final",
"Object",
"[",
"]",
"array",
",",
"final",
"int",
"length",
",",
"final",
"String",
"arrayName",
")",
"{",
"notNull",
"(",
"array",
",",
"arrayName",
")",
";",
"notNegative",
"(",
"length",
",",
"\"le... | Checks that an array is of a given length
@param array the array
@param length the desired length of the array
@param arrayName the name of the array
@throws IllegalArgumentException if the array is null or if the array's length is not as expected | [
"Checks",
"that",
"an",
"array",
"is",
"of",
"a",
"given",
"length"
] | train | https://github.com/johncarl81/transfuse/blob/a5f837504797a6c4f8628f7e1dde09b8e6368c8b/transfuse-support/src/main/java/org/androidtransfuse/util/Contract.java#L128-L135 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jmx.connector.client.rest/src/com/ibm/ws/jmx/connector/converter/JSONConverter.java | JSONConverter.writeServerNotificationRegistration | public void writeServerNotificationRegistration(OutputStream out, ServerNotificationRegistration value) throws IOException {
writeStartObject(out);
boolean hasOperation = value.operation != null;
if (hasOperation) {
writeSimpleStringField(out, OM_OPERATION, value.operation.name());
}
writeObjectNameField(out, OM_OBJECTNAME, value.objectName);
writeObjectNameField(out, OM_LISTENER, value.listener);
writeNotificationFilterField(out, OM_FILTER, value.filter);
writePOJOField(out, OM_HANDBACK, value.handback);
if (hasOperation) {
writeIntField(out, OM_FILTERID, value.filterID);
writeIntField(out, OM_HANDBACKID, value.handbackID);
}
writeEndObject(out);
} | java | public void writeServerNotificationRegistration(OutputStream out, ServerNotificationRegistration value) throws IOException {
writeStartObject(out);
boolean hasOperation = value.operation != null;
if (hasOperation) {
writeSimpleStringField(out, OM_OPERATION, value.operation.name());
}
writeObjectNameField(out, OM_OBJECTNAME, value.objectName);
writeObjectNameField(out, OM_LISTENER, value.listener);
writeNotificationFilterField(out, OM_FILTER, value.filter);
writePOJOField(out, OM_HANDBACK, value.handback);
if (hasOperation) {
writeIntField(out, OM_FILTERID, value.filterID);
writeIntField(out, OM_HANDBACKID, value.handbackID);
}
writeEndObject(out);
} | [
"public",
"void",
"writeServerNotificationRegistration",
"(",
"OutputStream",
"out",
",",
"ServerNotificationRegistration",
"value",
")",
"throws",
"IOException",
"{",
"writeStartObject",
"(",
"out",
")",
";",
"boolean",
"hasOperation",
"=",
"value",
".",
"operation",
... | Encode a ServerNotificationRegistration instance as JSON:
{
"operation" : ("Add" | "RemoveAll" | "RemoveSpecific")
"objectName" : ObjectName,
"listener" : ObjectName,
"filter" : NotificationFilter,
"handback" : POJO,
"filterID" : Integer,
"handbackID" : Integer
}
@param out The stream to write JSON to
@param value The ServerNotificationRegistration instance to encode.
Can't be null.
@throws IOException If an I/O error occurs
@see #readServerNotificationRegistration(InputStream) | [
"Encode",
"a",
"ServerNotificationRegistration",
"instance",
"as",
"JSON",
":",
"{",
"operation",
":",
"(",
"Add",
"|",
"RemoveAll",
"|",
"RemoveSpecific",
")",
"objectName",
":",
"ObjectName",
"listener",
":",
"ObjectName",
"filter",
":",
"NotificationFilter",
"h... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.client.rest/src/com/ibm/ws/jmx/connector/converter/JSONConverter.java#L1526-L1541 |
Azure/azure-sdk-for-java | servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/management/ManagementClientAsync.java | ManagementClientAsync.getRulesAsync | public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) {
return getRulesAsync(topicName, subscriptionName, 100, 0);
} | java | public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) {
return getRulesAsync(topicName, subscriptionName, 100, 0);
} | [
"public",
"CompletableFuture",
"<",
"List",
"<",
"RuleDescription",
">",
">",
"getRulesAsync",
"(",
"String",
"topicName",
",",
"String",
"subscriptionName",
")",
"{",
"return",
"getRulesAsync",
"(",
"topicName",
",",
"subscriptionName",
",",
"100",
",",
"0",
")... | Retrieves the list of rules for a given topic-subscription in the namespace.
@param topicName - The name of the topic.
@param subscriptionName - The name of the subscription.
@return the first 100 rules. | [
"Retrieves",
"the",
"list",
"of",
"rules",
"for",
"a",
"given",
"topic",
"-",
"subscription",
"in",
"the",
"namespace",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/management/ManagementClientAsync.java#L431-L433 |
belaban/JGroups | src/org/jgroups/util/Headers.java | Headers.putHeader | public static Header[] putHeader(final Header[] headers, short id, Header hdr, boolean replace_if_present) {
int i=0;
Header[] hdrs=headers;
boolean resized=false;
while(i < hdrs.length) {
if(hdrs[i] == null) {
hdrs[i]=hdr;
return resized? hdrs: null;
}
short hdr_id=hdrs[i].getProtId();
if(hdr_id == id) {
if(replace_if_present || hdrs[i] == null)
hdrs[i]=hdr;
return resized? hdrs : null;
}
i++;
if(i >= hdrs.length) {
hdrs=resize(hdrs);
resized=true;
}
}
throw new IllegalStateException("unable to add element " + id + ", index=" + i); // we should never come here
} | java | public static Header[] putHeader(final Header[] headers, short id, Header hdr, boolean replace_if_present) {
int i=0;
Header[] hdrs=headers;
boolean resized=false;
while(i < hdrs.length) {
if(hdrs[i] == null) {
hdrs[i]=hdr;
return resized? hdrs: null;
}
short hdr_id=hdrs[i].getProtId();
if(hdr_id == id) {
if(replace_if_present || hdrs[i] == null)
hdrs[i]=hdr;
return resized? hdrs : null;
}
i++;
if(i >= hdrs.length) {
hdrs=resize(hdrs);
resized=true;
}
}
throw new IllegalStateException("unable to add element " + id + ", index=" + i); // we should never come here
} | [
"public",
"static",
"Header",
"[",
"]",
"putHeader",
"(",
"final",
"Header",
"[",
"]",
"headers",
",",
"short",
"id",
",",
"Header",
"hdr",
",",
"boolean",
"replace_if_present",
")",
"{",
"int",
"i",
"=",
"0",
";",
"Header",
"[",
"]",
"hdrs",
"=",
"h... | Adds hdr at the next available slot. If none is available, the headers array passed in will be copied and the copy
returned
@param headers The headers array
@param id The protocol ID of the header
@param hdr The header
@param replace_if_present Whether or not to overwrite an existing header
@return A new copy of headers if the array needed to be expanded, or null otherwise | [
"Adds",
"hdr",
"at",
"the",
"next",
"available",
"slot",
".",
"If",
"none",
"is",
"available",
"the",
"headers",
"array",
"passed",
"in",
"will",
"be",
"copied",
"and",
"the",
"copy",
"returned"
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/Headers.java#L114-L136 |
shrinkwrap/resolver | maven/api-maven-embedded/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/embedded/EmbeddedMaven.java | EmbeddedMaven.withMavenInvokerSet | public static MavenInvokerEquippedEmbeddedMaven withMavenInvokerSet(InvocationRequest request, Invoker invoker) {
MavenInvokerUnequippedEmbeddedMaven embeddedMaven = Resolvers.use(MavenInvokerUnequippedEmbeddedMaven.class);
return embeddedMaven.setMavenInvoker(request, invoker);
} | java | public static MavenInvokerEquippedEmbeddedMaven withMavenInvokerSet(InvocationRequest request, Invoker invoker) {
MavenInvokerUnequippedEmbeddedMaven embeddedMaven = Resolvers.use(MavenInvokerUnequippedEmbeddedMaven.class);
return embeddedMaven.setMavenInvoker(request, invoker);
} | [
"public",
"static",
"MavenInvokerEquippedEmbeddedMaven",
"withMavenInvokerSet",
"(",
"InvocationRequest",
"request",
",",
"Invoker",
"invoker",
")",
"{",
"MavenInvokerUnequippedEmbeddedMaven",
"embeddedMaven",
"=",
"Resolvers",
".",
"use",
"(",
"MavenInvokerUnequippedEmbeddedMa... | Specifies an {@link InvocationRequest} and an {@link Invoker} the EmbeddedMaven should be used with.
<p>
When you use this approach, it is expected that both instances are properly set by you and no additional
parameters (such as -DskipTests) is added by Resolver. You can also observe some limited functionality
provided by Resolver API.
</p>
<p>
If you prefer more comfortable and less boilerplate approach, then use the method {@link #forProject(String)}
</p>
@param request An {@link InvocationRequest} the EmbeddedMaven should be used with
@param invoker An {@link Invoker} the EmbeddedMaven should be used with
@return Set EmbeddedMaven instance | [
"Specifies",
"an",
"{",
"@link",
"InvocationRequest",
"}",
"and",
"an",
"{",
"@link",
"Invoker",
"}",
"the",
"EmbeddedMaven",
"should",
"be",
"used",
"with",
".",
"<p",
">",
"When",
"you",
"use",
"this",
"approach",
"it",
"is",
"expected",
"that",
"both",
... | train | https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/maven/api-maven-embedded/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/embedded/EmbeddedMaven.java#L87-L91 |
lightblueseas/swing-components | src/main/java/de/alpharogroup/swing/img/ImageExtensions.java | ImageExtensions.concatenateImages | public static BufferedImage concatenateImages(final List<BufferedImage> imgCollection,
final int width, final int height, final int imageType,
final Direction concatenationDirection)
{
final BufferedImage img = new BufferedImage(width, height, imageType);
int x = 0;
int y = 0;
for (final BufferedImage bi : imgCollection)
{
final boolean imageDrawn = img.createGraphics().drawImage(bi, x, y, null);
if (!imageDrawn)
{
throw new RuntimeException("BufferedImage could not be drawn:" + bi.toString());
}
if (concatenationDirection.equals(Direction.vertical))
{
y += bi.getHeight();
}
else
{
x += bi.getWidth();
}
}
return img;
} | java | public static BufferedImage concatenateImages(final List<BufferedImage> imgCollection,
final int width, final int height, final int imageType,
final Direction concatenationDirection)
{
final BufferedImage img = new BufferedImage(width, height, imageType);
int x = 0;
int y = 0;
for (final BufferedImage bi : imgCollection)
{
final boolean imageDrawn = img.createGraphics().drawImage(bi, x, y, null);
if (!imageDrawn)
{
throw new RuntimeException("BufferedImage could not be drawn:" + bi.toString());
}
if (concatenationDirection.equals(Direction.vertical))
{
y += bi.getHeight();
}
else
{
x += bi.getWidth();
}
}
return img;
} | [
"public",
"static",
"BufferedImage",
"concatenateImages",
"(",
"final",
"List",
"<",
"BufferedImage",
">",
"imgCollection",
",",
"final",
"int",
"width",
",",
"final",
"int",
"height",
",",
"final",
"int",
"imageType",
",",
"final",
"Direction",
"concatenationDire... | Concatenate the given list of BufferedImage objects to one image and returns the concatenated
BufferedImage object.
@param imgCollection
the BufferedImage collection
@param width
the width of the image that will be returned.
@param height
the height of the image that will be returned.
@param imageType
type of the created image
@param concatenationDirection
the direction of the concatenation.
@return the buffered image | [
"Concatenate",
"the",
"given",
"list",
"of",
"BufferedImage",
"objects",
"to",
"one",
"image",
"and",
"returns",
"the",
"concatenated",
"BufferedImage",
"object",
"."
] | train | https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/swing/img/ImageExtensions.java#L90-L114 |
Javacord/Javacord | javacord-api/src/main/java/org/javacord/api/entity/message/embed/EmbedBuilder.java | EmbedBuilder.setThumbnail | public EmbedBuilder setThumbnail(BufferedImage thumbnail, String fileType) {
delegate.setThumbnail(thumbnail, fileType);
return this;
} | java | public EmbedBuilder setThumbnail(BufferedImage thumbnail, String fileType) {
delegate.setThumbnail(thumbnail, fileType);
return this;
} | [
"public",
"EmbedBuilder",
"setThumbnail",
"(",
"BufferedImage",
"thumbnail",
",",
"String",
"fileType",
")",
"{",
"delegate",
".",
"setThumbnail",
"(",
"thumbnail",
",",
"fileType",
")",
";",
"return",
"this",
";",
"}"
] | Sets the thumbnail of the embed.
@param thumbnail The thumbnail.
@param fileType The type of the file, e.g. "png" or "gif".
@return The current instance in order to chain call methods. | [
"Sets",
"the",
"thumbnail",
"of",
"the",
"embed",
"."
] | train | https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/message/embed/EmbedBuilder.java#L587-L590 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.javaeesec/src/com/ibm/ws/security/javaeesec/identitystore/LdapIdentityStore.java | LdapIdentityStore.getCallerSearchControls | private SearchControls getCallerSearchControls() {
String[] attrIds = { idStoreDefinition.getCallerNameAttribute() };
long limit = Long.valueOf(idStoreDefinition.getMaxResults());
int timeOut = idStoreDefinition.getReadTimeout();
int scope = getSearchScope(idStoreDefinition.getCallerSearchScope());
return new SearchControls(scope, limit, timeOut, attrIds, false, false);
} | java | private SearchControls getCallerSearchControls() {
String[] attrIds = { idStoreDefinition.getCallerNameAttribute() };
long limit = Long.valueOf(idStoreDefinition.getMaxResults());
int timeOut = idStoreDefinition.getReadTimeout();
int scope = getSearchScope(idStoreDefinition.getCallerSearchScope());
return new SearchControls(scope, limit, timeOut, attrIds, false, false);
} | [
"private",
"SearchControls",
"getCallerSearchControls",
"(",
")",
"{",
"String",
"[",
"]",
"attrIds",
"=",
"{",
"idStoreDefinition",
".",
"getCallerNameAttribute",
"(",
")",
"}",
";",
"long",
"limit",
"=",
"Long",
".",
"valueOf",
"(",
"idStoreDefinition",
".",
... | Get the {@link SearchControls} object for the caller search.
@return The {@link SearchControls} object to use when search LDAP for the user. | [
"Get",
"the",
"{",
"@link",
"SearchControls",
"}",
"object",
"for",
"the",
"caller",
"search",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.javaeesec/src/com/ibm/ws/security/javaeesec/identitystore/LdapIdentityStore.java#L511-L517 |
vvakame/JsonPullParser | jsonpullparser-apt/src/main/java/net/vvakame/util/jsonpullparser/factory/template/Template.java | Template.writeGen | public static void writeGen(JavaFileObject fileObject, JsonModelModel model)
throws IOException {
MvelTemplate.writeGen(fileObject, model);
} | java | public static void writeGen(JavaFileObject fileObject, JsonModelModel model)
throws IOException {
MvelTemplate.writeGen(fileObject, model);
} | [
"public",
"static",
"void",
"writeGen",
"(",
"JavaFileObject",
"fileObject",
",",
"JsonModelModel",
"model",
")",
"throws",
"IOException",
"{",
"MvelTemplate",
".",
"writeGen",
"(",
"fileObject",
",",
"model",
")",
";",
"}"
] | Generates source code into the given file object from the given data model, utilizing the templating engine.
@param fileObject Target file object
@param model Data model for source code generation
@throws IOException
@author vvakame | [
"Generates",
"source",
"code",
"into",
"the",
"given",
"file",
"object",
"from",
"the",
"given",
"data",
"model",
"utilizing",
"the",
"templating",
"engine",
"."
] | train | https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-apt/src/main/java/net/vvakame/util/jsonpullparser/factory/template/Template.java#L41-L44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.