repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 194 | func_name stringlengths 6 111 | whole_func_string stringlengths 80 3.8k | language stringclasses 1
value | func_code_string stringlengths 80 3.8k | func_code_tokens listlengths 20 697 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 434 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
soi-toolkit/soi-toolkit-mule | commons/components/commons-mule/src/main/java/org/soitoolkit/commons/mule/sftp/SftpUtil.java | SftpUtil.initEndpointDirectories | public static void initEndpointDirectories(MuleContext muleContext, String[] serviceNames, String[] endpointNames) throws Exception {
// Stop all named services (either Flows or services
List<Lifecycle> services = new ArrayList<Lifecycle>();
for (String serviceName : serviceNames) {
try {
Lifecycle service = muleContext.getRegistry().lookupObject(serviceName);
// logServiceStatus(service);
// service.stop();
// logServiceStatus(service);
services.add(service);
} catch (Exception e) {
logger.error("Error '" + e.getMessage()
+ "' occured while stopping the service " + serviceName
+ ". Perhaps the service did not exist in the config?");
throw e;
}
}
// Now init the directory for each named endpoint, one by one
for (String endpointName : endpointNames) {
initEndpointDirectory(muleContext, endpointName);
}
// We are done, startup the services again so that the test can begin...
for (@SuppressWarnings("unused") Lifecycle service : services) {
// logServiceStatus(service);
// service.start();
// logServiceStatus(service);
}
} | java | public static void initEndpointDirectories(MuleContext muleContext, String[] serviceNames, String[] endpointNames) throws Exception {
// Stop all named services (either Flows or services
List<Lifecycle> services = new ArrayList<Lifecycle>();
for (String serviceName : serviceNames) {
try {
Lifecycle service = muleContext.getRegistry().lookupObject(serviceName);
// logServiceStatus(service);
// service.stop();
// logServiceStatus(service);
services.add(service);
} catch (Exception e) {
logger.error("Error '" + e.getMessage()
+ "' occured while stopping the service " + serviceName
+ ". Perhaps the service did not exist in the config?");
throw e;
}
}
// Now init the directory for each named endpoint, one by one
for (String endpointName : endpointNames) {
initEndpointDirectory(muleContext, endpointName);
}
// We are done, startup the services again so that the test can begin...
for (@SuppressWarnings("unused") Lifecycle service : services) {
// logServiceStatus(service);
// service.start();
// logServiceStatus(service);
}
} | [
"public",
"static",
"void",
"initEndpointDirectories",
"(",
"MuleContext",
"muleContext",
",",
"String",
"[",
"]",
"serviceNames",
",",
"String",
"[",
"]",
"endpointNames",
")",
"throws",
"Exception",
"{",
"// Stop all named services (either Flows or services",
"List",
... | Initiates a list of sftp-endpoint-directories. Ensures that affected
services are stopped during the initiation.
@param serviceNames
@param endpointNames
@param muleContext
@throws Exception | [
"Initiates",
"a",
"list",
"of",
"sftp",
"-",
"endpoint",
"-",
"directories",
".",
"Ensures",
"that",
"affected",
"services",
"are",
"stopped",
"during",
"the",
"initiation",
"."
] | train | https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/commons/components/commons-mule/src/main/java/org/soitoolkit/commons/mule/sftp/SftpUtil.java#L69-L99 |
qiujuer/Genius-Android | caprice/ui/src/main/java/net/qiujuer/genius/ui/compat/UiCompat.java | UiCompat.setOutlineProvider | public static void setOutlineProvider(View view, final BalloonMarkerDrawable balloonMarkerDrawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UiCompatNotCrash.setOutlineProvider(view, balloonMarkerDrawable);
}
} | java | public static void setOutlineProvider(View view, final BalloonMarkerDrawable balloonMarkerDrawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UiCompatNotCrash.setOutlineProvider(view, balloonMarkerDrawable);
}
} | [
"public",
"static",
"void",
"setOutlineProvider",
"(",
"View",
"view",
",",
"final",
"BalloonMarkerDrawable",
"balloonMarkerDrawable",
")",
"{",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"LOLLIPOP",
")",
"{",
... | Sets the custom Outline provider on API>=21.
Does nothing on API<21
@param view View
@param balloonMarkerDrawable OutlineProvider Drawable | [
"Sets",
"the",
"custom",
"Outline",
"provider",
"on",
"API",
">",
"=",
"21",
".",
"Does",
"nothing",
"on",
"API<21"
] | train | https://github.com/qiujuer/Genius-Android/blob/babefaf1321f5883a21cada582b6fa5104adc648/caprice/ui/src/main/java/net/qiujuer/genius/ui/compat/UiCompat.java#L44-L48 |
mattprecious/telescope | telescope/src/main/java/com/mattprecious/telescope/FileProvider.java | FileProvider.getPathStrategy | private static PathStrategy getPathStrategy(Context context, String authority) {
PathStrategy strat;
synchronized (sCache) {
strat = sCache.get(authority);
if (strat == null) {
try {
strat = parsePathStrategy(context, authority);
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
} catch (XmlPullParserException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
}
sCache.put(authority, strat);
}
}
return strat;
} | java | private static PathStrategy getPathStrategy(Context context, String authority) {
PathStrategy strat;
synchronized (sCache) {
strat = sCache.get(authority);
if (strat == null) {
try {
strat = parsePathStrategy(context, authority);
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
} catch (XmlPullParserException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
}
sCache.put(authority, strat);
}
}
return strat;
} | [
"private",
"static",
"PathStrategy",
"getPathStrategy",
"(",
"Context",
"context",
",",
"String",
"authority",
")",
"{",
"PathStrategy",
"strat",
";",
"synchronized",
"(",
"sCache",
")",
"{",
"strat",
"=",
"sCache",
".",
"get",
"(",
"authority",
")",
";",
"i... | Return {@link PathStrategy} for given authority, either by parsing or
returning from cache. | [
"Return",
"{"
] | train | https://github.com/mattprecious/telescope/blob/ce5e2710fb16ee214026fc25b091eb946fdbbb3c/telescope/src/main/java/com/mattprecious/telescope/FileProvider.java#L529-L547 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseIntObj | @Nullable
public static Integer parseIntObj (@Nullable final String sStr, @Nullable final Integer aDefault)
{
return parseIntObj (sStr, DEFAULT_RADIX, aDefault);
} | java | @Nullable
public static Integer parseIntObj (@Nullable final String sStr, @Nullable final Integer aDefault)
{
return parseIntObj (sStr, DEFAULT_RADIX, aDefault);
} | [
"@",
"Nullable",
"public",
"static",
"Integer",
"parseIntObj",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"@",
"Nullable",
"final",
"Integer",
"aDefault",
")",
"{",
"return",
"parseIntObj",
"(",
"sStr",
",",
"DEFAULT_RADIX",
",",
"aDefault",
")",
... | Parse the given {@link String} as {@link Integer} with radix
{@link #DEFAULT_RADIX}.
@param sStr
The string to parse. May be <code>null</code>.
@param aDefault
The default value to be returned if the passed string could not be
converted to a valid value. May be <code>null</code>.
@return <code>aDefault</code> if the string does not represent a valid
value. | [
"Parse",
"the",
"given",
"{",
"@link",
"String",
"}",
"as",
"{",
"@link",
"Integer",
"}",
"with",
"radix",
"{",
"@link",
"#DEFAULT_RADIX",
"}",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L864-L868 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/lss/LssClient.java | LssClient.updateStreamPresets | public void updateStreamPresets(String domain, String app, String stream, Map<String, String> presets) {
UpdateStreamPresetsRequest request = new UpdateStreamPresetsRequest()
.withDomain(domain)
.withApp(app)
.withStream(stream)
.withPresets(presets);
updateStreamPresets(request);
} | java | public void updateStreamPresets(String domain, String app, String stream, Map<String, String> presets) {
UpdateStreamPresetsRequest request = new UpdateStreamPresetsRequest()
.withDomain(domain)
.withApp(app)
.withStream(stream)
.withPresets(presets);
updateStreamPresets(request);
} | [
"public",
"void",
"updateStreamPresets",
"(",
"String",
"domain",
",",
"String",
"app",
",",
"String",
"stream",
",",
"Map",
"<",
"String",
",",
"String",
">",
"presets",
")",
"{",
"UpdateStreamPresetsRequest",
"request",
"=",
"new",
"UpdateStreamPresetsRequest",
... | Update stream's presets
@param domain The requested domain which the specific stream belongs to
@param app The requested app which the specific stream belongs to
@param stream The requested stream which need to update the presets
@param presets The new presets is setting to the specific stream;
it's a map, and key is line number, and value is preset name | [
"Update",
"stream",
"s",
"presets"
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L1624-L1631 |
thinkaurelius/titan | titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/BackendTransaction.java | BackendTransaction.acquireIndexLock | public void acquireIndexLock(StaticBuffer key, StaticBuffer column) throws BackendException {
acquiredLock = true;
indexStore.acquireLock(key, column, null, storeTx);
} | java | public void acquireIndexLock(StaticBuffer key, StaticBuffer column) throws BackendException {
acquiredLock = true;
indexStore.acquireLock(key, column, null, storeTx);
} | [
"public",
"void",
"acquireIndexLock",
"(",
"StaticBuffer",
"key",
",",
"StaticBuffer",
"column",
")",
"throws",
"BackendException",
"{",
"acquiredLock",
"=",
"true",
";",
"indexStore",
".",
"acquireLock",
"(",
"key",
",",
"column",
",",
"null",
",",
"storeTx",
... | Acquires a lock for the key-column pair on the property index which ensures that nobody else can take a lock on that
respective entry for the duration of this lock (but somebody could potentially still overwrite
the key-value entry without taking a lock).
The expectedValue defines the value expected to match the value at the time the lock is acquired (or null if it is expected
that the key-column pair does not exist).
<p/>
If this method is called multiple times with the same key-column pair in the same transaction, all but the first invocation are ignored.
<p/>
The lock has to be released when the transaction closes (commits or aborts).
@param key Key on which to lock
@param column Column the column on which to lock | [
"Acquires",
"a",
"lock",
"for",
"the",
"key",
"-",
"column",
"pair",
"on",
"the",
"property",
"index",
"which",
"ensures",
"that",
"nobody",
"else",
"can",
"take",
"a",
"lock",
"on",
"that",
"respective",
"entry",
"for",
"the",
"duration",
"of",
"this",
... | train | https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/BackendTransaction.java#L238-L241 |
elki-project/elki | elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/data/model/ModelUtil.java | ModelUtil.getPrototypeOrCentroid | public static <V extends NumberVector> V getPrototypeOrCentroid(Model model, Relation<? extends V> relation, DBIDs ids, NumberVector.Factory<V> factory) {
assert (ids.size() > 0);
V v = getPrototype(model, relation, factory);
return v != null ? v : factory.newNumberVector(Centroid.make(relation, ids));
} | java | public static <V extends NumberVector> V getPrototypeOrCentroid(Model model, Relation<? extends V> relation, DBIDs ids, NumberVector.Factory<V> factory) {
assert (ids.size() > 0);
V v = getPrototype(model, relation, factory);
return v != null ? v : factory.newNumberVector(Centroid.make(relation, ids));
} | [
"public",
"static",
"<",
"V",
"extends",
"NumberVector",
">",
"V",
"getPrototypeOrCentroid",
"(",
"Model",
"model",
",",
"Relation",
"<",
"?",
"extends",
"V",
">",
"relation",
",",
"DBIDs",
"ids",
",",
"NumberVector",
".",
"Factory",
"<",
"V",
">",
"factor... | Get the representative vector for a cluster model, or compute the centroid.
@param model Model
@param relation Data relation (for representatives specified per DBID)
@param ids Cluster ids (must not be empty.
@return Vector of type V, {@code null} if not supported.
@param <V> desired vector type | [
"Get",
"the",
"representative",
"vector",
"for",
"a",
"cluster",
"model",
"or",
"compute",
"the",
"centroid",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/data/model/ModelUtil.java#L127-L131 |
icode/ameba | src/main/java/ameba/container/internal/ConfigHelper.java | ConfigHelper.getContainerLifecycleListener | public static LifecycleListener getContainerLifecycleListener(final ApplicationHandler applicationHandler) {
final Iterable<ContainerLifecycleListener> listeners = Iterables.concat(
Providers.getAllProviders(applicationHandler.getInjectionManager(), ContainerLifecycleListener.class),
new LinkedList<ContainerLifecycleListener>() {{
add(new ServiceLocatorShutdownListener());
}});
return new LifecycleListener() {
@Override
public void onReloadShutdown(Container container, Runnable tryScope) {
for (final ContainerLifecycleListener listener : listeners) {
if (listener instanceof ServiceLocatorShutdownListener) {
container = new ContainerDelegate(container);
tryScope.run();
}
listener.onShutdown(container);
}
}
@Override
public void onStartup(final Container container) {
for (final ContainerLifecycleListener listener : listeners) {
listener.onStartup(container);
}
}
@Override
public void onReload(final Container container) {
for (final ContainerLifecycleListener listener : listeners) {
listener.onReload(container);
}
}
@Override
public void onShutdown(final Container container) {
for (final ContainerLifecycleListener listener : listeners) {
listener.onShutdown(container);
}
}
};
} | java | public static LifecycleListener getContainerLifecycleListener(final ApplicationHandler applicationHandler) {
final Iterable<ContainerLifecycleListener> listeners = Iterables.concat(
Providers.getAllProviders(applicationHandler.getInjectionManager(), ContainerLifecycleListener.class),
new LinkedList<ContainerLifecycleListener>() {{
add(new ServiceLocatorShutdownListener());
}});
return new LifecycleListener() {
@Override
public void onReloadShutdown(Container container, Runnable tryScope) {
for (final ContainerLifecycleListener listener : listeners) {
if (listener instanceof ServiceLocatorShutdownListener) {
container = new ContainerDelegate(container);
tryScope.run();
}
listener.onShutdown(container);
}
}
@Override
public void onStartup(final Container container) {
for (final ContainerLifecycleListener listener : listeners) {
listener.onStartup(container);
}
}
@Override
public void onReload(final Container container) {
for (final ContainerLifecycleListener listener : listeners) {
listener.onReload(container);
}
}
@Override
public void onShutdown(final Container container) {
for (final ContainerLifecycleListener listener : listeners) {
listener.onShutdown(container);
}
}
};
} | [
"public",
"static",
"LifecycleListener",
"getContainerLifecycleListener",
"(",
"final",
"ApplicationHandler",
"applicationHandler",
")",
"{",
"final",
"Iterable",
"<",
"ContainerLifecycleListener",
">",
"listeners",
"=",
"Iterables",
".",
"concat",
"(",
"Providers",
".",
... | Provides a single ContainerLifecycleListener instance based on the {@link ApplicationHandler application} configuration.
This method looks for providers implementing {@link org.glassfish.jersey.server.spi.ContainerLifecycleListener} interface and aggregates them into
a single umbrella listener instance that is returned.
@param applicationHandler actual application from where to get the listener.
@return a single instance of a ContainerLifecycleListener, can not be null. | [
"Provides",
"a",
"single",
"ContainerLifecycleListener",
"instance",
"based",
"on",
"the",
"{",
"@link",
"ApplicationHandler",
"application",
"}",
"configuration",
".",
"This",
"method",
"looks",
"for",
"providers",
"implementing",
"{",
"@link",
"org",
".",
"glassfi... | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/container/internal/ConfigHelper.java#L37-L79 |
biojava/biojava | biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java | FeatureList.selectOverlapping | public FeatureList selectOverlapping(String seqname, Location location, boolean useBothStrands)
throws Exception {
FeatureList list = new FeatureList();
for (FeatureI feature : this) {
boolean overlaps = false;
if (feature.seqname().equals(seqname)) {
if (location.isSameStrand(feature.location())) {
overlaps = feature.location().overlaps(location);
} else if (useBothStrands) {
overlaps = feature.location().overlaps(location.opposite());
}
}
if (overlaps) {
list.add(feature);
}
}
return list;
} | java | public FeatureList selectOverlapping(String seqname, Location location, boolean useBothStrands)
throws Exception {
FeatureList list = new FeatureList();
for (FeatureI feature : this) {
boolean overlaps = false;
if (feature.seqname().equals(seqname)) {
if (location.isSameStrand(feature.location())) {
overlaps = feature.location().overlaps(location);
} else if (useBothStrands) {
overlaps = feature.location().overlaps(location.opposite());
}
}
if (overlaps) {
list.add(feature);
}
}
return list;
} | [
"public",
"FeatureList",
"selectOverlapping",
"(",
"String",
"seqname",
",",
"Location",
"location",
",",
"boolean",
"useBothStrands",
")",
"throws",
"Exception",
"{",
"FeatureList",
"list",
"=",
"new",
"FeatureList",
"(",
")",
";",
"for",
"(",
"FeatureI",
"feat... | Create a list of all features that overlap the specified location on the specified
sequence.
@param seqname The sequence name. Only features with this sequence name will be checked for overlap.
@param location The location to check.
@param useBothStrands If true, locations are mapped to their positive strand image
before being checked for overlap. If false, only features whose locations are
on the same strand as the specified location will be considered for inclusion.
@return The new list of features that overlap the location. | [
"Create",
"a",
"list",
"of",
"all",
"features",
"that",
"overlap",
"the",
"specified",
"location",
"on",
"the",
"specified",
"sequence",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java#L356-L374 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WCheckBoxSelectExample.java | WCheckBoxSelectExample.addFlatSelectExample | private void addFlatSelectExample() {
add(new WHeading(HeadingLevel.H3, "WCheckBoxSelect with flat layout"));
add(new ExplanatoryText("Setting the layout to FLAT will make thecheck boxes be rendered in a horizontal line. They will wrap when they reach"
+ " the edge of the parent container."));
final WCheckBoxSelect select = new WCheckBoxSelect("australian_state");
select.setToolTip("Make a selection");
select.setButtonLayout(WCheckBoxSelect.LAYOUT_FLAT);
add(select);
} | java | private void addFlatSelectExample() {
add(new WHeading(HeadingLevel.H3, "WCheckBoxSelect with flat layout"));
add(new ExplanatoryText("Setting the layout to FLAT will make thecheck boxes be rendered in a horizontal line. They will wrap when they reach"
+ " the edge of the parent container."));
final WCheckBoxSelect select = new WCheckBoxSelect("australian_state");
select.setToolTip("Make a selection");
select.setButtonLayout(WCheckBoxSelect.LAYOUT_FLAT);
add(select);
} | [
"private",
"void",
"addFlatSelectExample",
"(",
")",
"{",
"add",
"(",
"new",
"WHeading",
"(",
"HeadingLevel",
".",
"H3",
",",
"\"WCheckBoxSelect with flat layout\"",
")",
")",
";",
"add",
"(",
"new",
"ExplanatoryText",
"(",
"\"Setting the layout to FLAT will make thec... | WCheckBoxSelect layout options These examples show the various ways to lay out the options in a WCheckBoxSelect
NOTE: the default (if no buttonLayout is set) is LAYOUT_STACKED. adds a WCheckBoxSelect with LAYOUT_FLAT | [
"WCheckBoxSelect",
"layout",
"options",
"These",
"examples",
"show",
"the",
"various",
"ways",
"to",
"lay",
"out",
"the",
"options",
"in",
"a",
"WCheckBoxSelect",
"NOTE",
":",
"the",
"default",
"(",
"if",
"no",
"buttonLayout",
"is",
"set",
")",
"is",
"LAYOUT... | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WCheckBoxSelectExample.java#L210-L218 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/util/PropertiesUtils.java | PropertiesUtils.hasProperty | public static boolean hasProperty(Properties props, String key) {
String value = props.getProperty(key);
if (value == null) {
return false;
}
value = value.toLowerCase();
return ! (value.equals("false") || value.equals("no") || value.equals("off"));
} | java | public static boolean hasProperty(Properties props, String key) {
String value = props.getProperty(key);
if (value == null) {
return false;
}
value = value.toLowerCase();
return ! (value.equals("false") || value.equals("no") || value.equals("off"));
} | [
"public",
"static",
"boolean",
"hasProperty",
"(",
"Properties",
"props",
",",
"String",
"key",
")",
"{",
"String",
"value",
"=",
"props",
".",
"getProperty",
"(",
"key",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}"... | Returns true iff the given Properties contains a property with the given
key (name), and its value is not "false" or "no" or "off".
@param props Properties object
@param key The key to test
@return true iff the given Properties contains a property with the given
key (name), and its value is not "false" or "no" or "off". | [
"Returns",
"true",
"iff",
"the",
"given",
"Properties",
"contains",
"a",
"property",
"with",
"the",
"given",
"key",
"(",
"name",
")",
"and",
"its",
"value",
"is",
"not",
"false",
"or",
"no",
"or",
"off",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/PropertiesUtils.java#L26-L33 |
trajano/caliper | caliper/src/main/java/com/google/caliper/options/CommandLineParser.java | CommandLineParser.parseAndInject | public void parseAndInject(String[] args, T injectee) throws InvalidCommandException {
this.injectee = injectee;
pendingInjections.clear();
Iterator<String> argsIter = Iterators.forArray(args);
ImmutableList.Builder<String> builder = ImmutableList.builder();
while (argsIter.hasNext()) {
String arg = argsIter.next();
if (arg.equals("--")) {
break; // "--" marks the end of options and the beginning of positional arguments.
} else if (arg.startsWith("--")) {
parseLongOption(arg, argsIter);
} else if (arg.startsWith("-")) {
parseShortOptions(arg, argsIter);
} else {
builder.add(arg);
// allow positional arguments to mix with options since many linux commands do
}
}
for (PendingInjection pi : pendingInjections) {
pi.injectableOption.inject(pi.value, injectee);
}
ImmutableList<String> leftovers = builder.addAll(argsIter).build();
invokeMethod(injectee, injectionMap.leftoversMethod, leftovers);
} | java | public void parseAndInject(String[] args, T injectee) throws InvalidCommandException {
this.injectee = injectee;
pendingInjections.clear();
Iterator<String> argsIter = Iterators.forArray(args);
ImmutableList.Builder<String> builder = ImmutableList.builder();
while (argsIter.hasNext()) {
String arg = argsIter.next();
if (arg.equals("--")) {
break; // "--" marks the end of options and the beginning of positional arguments.
} else if (arg.startsWith("--")) {
parseLongOption(arg, argsIter);
} else if (arg.startsWith("-")) {
parseShortOptions(arg, argsIter);
} else {
builder.add(arg);
// allow positional arguments to mix with options since many linux commands do
}
}
for (PendingInjection pi : pendingInjections) {
pi.injectableOption.inject(pi.value, injectee);
}
ImmutableList<String> leftovers = builder.addAll(argsIter).build();
invokeMethod(injectee, injectionMap.leftoversMethod, leftovers);
} | [
"public",
"void",
"parseAndInject",
"(",
"String",
"[",
"]",
"args",
",",
"T",
"injectee",
")",
"throws",
"InvalidCommandException",
"{",
"this",
".",
"injectee",
"=",
"injectee",
";",
"pendingInjections",
".",
"clear",
"(",
")",
";",
"Iterator",
"<",
"Strin... | Parses the command-line arguments 'args', setting the @Option fields of the 'optionSource'
provided to the constructor. Returns a list of the positional arguments left over after
processing all options. | [
"Parses",
"the",
"command",
"-",
"line",
"arguments",
"args",
"setting",
"the"
] | train | https://github.com/trajano/caliper/blob/a8bcfd84fa9d7b893b3edfadc3b13240ae5cd658/caliper/src/main/java/com/google/caliper/options/CommandLineParser.java#L153-L179 |
zerodhatech/javakiteconnect | kiteconnect/src/com/zerodhatech/ticker/KiteTicker.java | KiteTicker.getIndeciesData | private Tick getIndeciesData(byte[] bin, int x){
int dec = 100;
Tick tick = new Tick();
tick.setMode(modeFull);
tick.setTradable(false);
tick.setInstrumentToken(x);
tick.setLastTradedPrice(convertToDouble(getBytes(bin, 4, 8)) / dec);
tick.setHighPrice(convertToDouble(getBytes(bin, 8, 12)) / dec);
tick.setLowPrice(convertToDouble(getBytes(bin, 12, 16)) / dec);
tick.setOpenPrice(convertToDouble(getBytes(bin, 16, 20)) / dec);
tick.setClosePrice(convertToDouble(getBytes(bin, 20, 24)) / dec);
tick.setNetPriceChangeFromClosingPrice(convertToDouble(getBytes(bin, 24, 28)) / dec);
if(bin.length > 28) {
long tickTimeStamp = convertToLong(getBytes(bin, 28, 32)) * 1000;
if(isValidDate(tickTimeStamp)) {
tick.setTickTimestamp(new Date(tickTimeStamp));
} else {
tick.setTickTimestamp(null);
}
}
return tick;
} | java | private Tick getIndeciesData(byte[] bin, int x){
int dec = 100;
Tick tick = new Tick();
tick.setMode(modeFull);
tick.setTradable(false);
tick.setInstrumentToken(x);
tick.setLastTradedPrice(convertToDouble(getBytes(bin, 4, 8)) / dec);
tick.setHighPrice(convertToDouble(getBytes(bin, 8, 12)) / dec);
tick.setLowPrice(convertToDouble(getBytes(bin, 12, 16)) / dec);
tick.setOpenPrice(convertToDouble(getBytes(bin, 16, 20)) / dec);
tick.setClosePrice(convertToDouble(getBytes(bin, 20, 24)) / dec);
tick.setNetPriceChangeFromClosingPrice(convertToDouble(getBytes(bin, 24, 28)) / dec);
if(bin.length > 28) {
long tickTimeStamp = convertToLong(getBytes(bin, 28, 32)) * 1000;
if(isValidDate(tickTimeStamp)) {
tick.setTickTimestamp(new Date(tickTimeStamp));
} else {
tick.setTickTimestamp(null);
}
}
return tick;
} | [
"private",
"Tick",
"getIndeciesData",
"(",
"byte",
"[",
"]",
"bin",
",",
"int",
"x",
")",
"{",
"int",
"dec",
"=",
"100",
";",
"Tick",
"tick",
"=",
"new",
"Tick",
"(",
")",
";",
"tick",
".",
"setMode",
"(",
"modeFull",
")",
";",
"tick",
".",
"setT... | Parses NSE indices data.
@return Tick is the parsed index data. | [
"Parses",
"NSE",
"indices",
"data",
"."
] | train | https://github.com/zerodhatech/javakiteconnect/blob/4a3f15ff2c8a1b3b6ec61799f8bb047e4dfeb92d/kiteconnect/src/com/zerodhatech/ticker/KiteTicker.java#L479-L500 |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java | VmService.createVM | public Map<String, String> createVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
VmUtils utils = new VmUtils();
ManagedObjectReference vmFolderMor = utils.getMorFolder(vmInputs.getFolderName(), connectionResources);
ManagedObjectReference resourcePoolMor = utils.getMorResourcePool(vmInputs.getResourcePool(), connectionResources);
ManagedObjectReference hostMor = utils.getMorHost(vmInputs.getHostname(), connectionResources, null);
VirtualMachineConfigSpec vmConfigSpec = new VmConfigSpecs().getVmConfigSpec(vmInputs, connectionResources);
ManagedObjectReference task = connectionResources.getVimPortType()
.createVMTask(vmFolderMor, vmConfigSpec, resourcePoolMor, hostMor);
return new ResponseHelper(connectionResources, task).getResultsMap("Success: Created [" +
vmInputs.getVirtualMachineName() + "] VM. The taskId is: " + task.getValue(),
"Failure: Could not create [" + vmInputs.getVirtualMachineName() + "] VM");
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> createVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
VmUtils utils = new VmUtils();
ManagedObjectReference vmFolderMor = utils.getMorFolder(vmInputs.getFolderName(), connectionResources);
ManagedObjectReference resourcePoolMor = utils.getMorResourcePool(vmInputs.getResourcePool(), connectionResources);
ManagedObjectReference hostMor = utils.getMorHost(vmInputs.getHostname(), connectionResources, null);
VirtualMachineConfigSpec vmConfigSpec = new VmConfigSpecs().getVmConfigSpec(vmInputs, connectionResources);
ManagedObjectReference task = connectionResources.getVimPortType()
.createVMTask(vmFolderMor, vmConfigSpec, resourcePoolMor, hostMor);
return new ResponseHelper(connectionResources, task).getResultsMap("Success: Created [" +
vmInputs.getVirtualMachineName() + "] VM. The taskId is: " + task.getValue(),
"Failure: Could not create [" + vmInputs.getVirtualMachineName() + "] VM");
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"createVM",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"ConnectionResources",
"(",
"httpInputs",
",",
... | Method used to connect to specified data center and create a virtual machine using the inputs provided.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to create a new virtual machine
@return Map with String as key and value that contains returnCode of the operation, success message with task id
of the execution or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"specified",
"data",
"center",
"and",
"create",
"a",
"virtual",
"machine",
"using",
"the",
"inputs",
"provided",
"."
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java#L83-L107 |
hamcrest/hamcrest-junit | src/main/java/org/hamcrest/junit/ErrorCollector.java | ErrorCollector.checkThat | public <T> void checkThat(final T value, final Matcher<T> matcher) {
checkThat("", value, matcher);
} | java | public <T> void checkThat(final T value, final Matcher<T> matcher) {
checkThat("", value, matcher);
} | [
"public",
"<",
"T",
">",
"void",
"checkThat",
"(",
"final",
"T",
"value",
",",
"final",
"Matcher",
"<",
"T",
">",
"matcher",
")",
"{",
"checkThat",
"(",
"\"\"",
",",
"value",
",",
"matcher",
")",
";",
"}"
] | Adds a failure to the table if {@code matcher} does not match {@code value}.
Execution continues, but the test will fail at the end if the match fails. | [
"Adds",
"a",
"failure",
"to",
"the",
"table",
"if",
"{"
] | train | https://github.com/hamcrest/hamcrest-junit/blob/5e02d55230b560f255433bcc490afaeda9e1a043/src/main/java/org/hamcrest/junit/ErrorCollector.java#L54-L56 |
shrinkwrap/shrinkwrap | impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/io/tar/TarHeader.java | TarHeader.parseOctal | public static long parseOctal(byte[] header, int offset, int length) throws InvalidHeaderException {
long result = 0;
boolean stillPadding = true;
int end = offset + length;
for (int i = offset; i < end; ++i) {
if (header[i] == 0) {
break;
}
if (header[i] == (byte) ' ' || header[i] == '0') {
if (stillPadding) {
continue;
}
if (header[i] == (byte) ' ') {
break;
}
}
stillPadding = false;
result = (result << 3) + (header[i] - '0');
}
return result;
} | java | public static long parseOctal(byte[] header, int offset, int length) throws InvalidHeaderException {
long result = 0;
boolean stillPadding = true;
int end = offset + length;
for (int i = offset; i < end; ++i) {
if (header[i] == 0) {
break;
}
if (header[i] == (byte) ' ' || header[i] == '0') {
if (stillPadding) {
continue;
}
if (header[i] == (byte) ' ') {
break;
}
}
stillPadding = false;
result = (result << 3) + (header[i] - '0');
}
return result;
} | [
"public",
"static",
"long",
"parseOctal",
"(",
"byte",
"[",
"]",
"header",
",",
"int",
"offset",
",",
"int",
"length",
")",
"throws",
"InvalidHeaderException",
"{",
"long",
"result",
"=",
"0",
";",
"boolean",
"stillPadding",
"=",
"true",
";",
"int",
"end",... | Parse an octal string from a header buffer. This is used for the file permission mode value.
@param header
The header buffer from which to parse.
@param offset
The offset into the buffer from which to parse.
@param length
The number of header bytes to parse.
@return The long value of the octal string. | [
"Parse",
"an",
"octal",
"string",
"from",
"a",
"header",
"buffer",
".",
"This",
"is",
"used",
"for",
"the",
"file",
"permission",
"mode",
"value",
"."
] | train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/io/tar/TarHeader.java#L256-L282 |
google/j2objc | translator/src/main/java/com/google/devtools/j2objc/translate/Functionizer.java | Functionizer.setFunctionCaller | private void setFunctionCaller(MethodDeclaration method, ExecutableElement methodElement) {
TypeMirror returnType = methodElement.getReturnType();
TypeElement declaringClass = ElementUtil.getDeclaringClass(methodElement);
Block body = new Block();
method.setBody(body);
method.removeModifiers(Modifier.NATIVE);
List<Statement> stmts = body.getStatements();
FunctionInvocation invocation =
new FunctionInvocation(newFunctionElement(methodElement), returnType);
List<Expression> args = invocation.getArguments();
if (!ElementUtil.isStatic(methodElement)) {
args.add(new ThisExpression(declaringClass.asType()));
}
for (SingleVariableDeclaration param : method.getParameters()) {
args.add(new SimpleName(param.getVariableElement()));
}
if (TypeUtil.isVoid(returnType)) {
stmts.add(new ExpressionStatement(invocation));
if (ElementUtil.isConstructor(methodElement)) {
stmts.add(new ReturnStatement(new ThisExpression(declaringClass.asType())));
}
} else {
stmts.add(new ReturnStatement(invocation));
}
} | java | private void setFunctionCaller(MethodDeclaration method, ExecutableElement methodElement) {
TypeMirror returnType = methodElement.getReturnType();
TypeElement declaringClass = ElementUtil.getDeclaringClass(methodElement);
Block body = new Block();
method.setBody(body);
method.removeModifiers(Modifier.NATIVE);
List<Statement> stmts = body.getStatements();
FunctionInvocation invocation =
new FunctionInvocation(newFunctionElement(methodElement), returnType);
List<Expression> args = invocation.getArguments();
if (!ElementUtil.isStatic(methodElement)) {
args.add(new ThisExpression(declaringClass.asType()));
}
for (SingleVariableDeclaration param : method.getParameters()) {
args.add(new SimpleName(param.getVariableElement()));
}
if (TypeUtil.isVoid(returnType)) {
stmts.add(new ExpressionStatement(invocation));
if (ElementUtil.isConstructor(methodElement)) {
stmts.add(new ReturnStatement(new ThisExpression(declaringClass.asType())));
}
} else {
stmts.add(new ReturnStatement(invocation));
}
} | [
"private",
"void",
"setFunctionCaller",
"(",
"MethodDeclaration",
"method",
",",
"ExecutableElement",
"methodElement",
")",
"{",
"TypeMirror",
"returnType",
"=",
"methodElement",
".",
"getReturnType",
"(",
")",
";",
"TypeElement",
"declaringClass",
"=",
"ElementUtil",
... | Replace method block statements with single statement that invokes function. | [
"Replace",
"method",
"block",
"statements",
"with",
"single",
"statement",
"that",
"invokes",
"function",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/translator/src/main/java/com/google/devtools/j2objc/translate/Functionizer.java#L487-L511 |
ModeShape/modeshape | web/modeshape-web-explorer/src/main/java/org/modeshape/web/client/contents/Contents.java | Contents.importXML | public void importXML(String name, int option) {
console.jcrService().importXML(repository, workspace(), path(), name,
option, new AsyncCallback<Object>() {
@Override
public void onFailure(Throwable caught) {
SC.say(caught.getMessage());
}
@Override
public void onSuccess(Object result) {
SC.say("Complete");
}
});
} | java | public void importXML(String name, int option) {
console.jcrService().importXML(repository, workspace(), path(), name,
option, new AsyncCallback<Object>() {
@Override
public void onFailure(Throwable caught) {
SC.say(caught.getMessage());
}
@Override
public void onSuccess(Object result) {
SC.say("Complete");
}
});
} | [
"public",
"void",
"importXML",
"(",
"String",
"name",
",",
"int",
"option",
")",
"{",
"console",
".",
"jcrService",
"(",
")",
".",
"importXML",
"(",
"repository",
",",
"workspace",
"(",
")",
",",
"path",
"(",
")",
",",
"name",
",",
"option",
",",
"ne... | Imports contents from the given file.
@param name
@param option | [
"Imports",
"contents",
"from",
"the",
"given",
"file",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/web/modeshape-web-explorer/src/main/java/org/modeshape/web/client/contents/Contents.java#L369-L382 |
hypercube1024/firefly | firefly-common/src/main/java/com/firefly/utils/retry/WaitStrategies.java | WaitStrategies.exponentialWait | public static <V> Action1<TaskContext<V>> exponentialWait(long initTime, long maxTime, TimeUnit timeUnit) {
return exponentialWait(initTime, maxTime, timeUnit, 2);
} | java | public static <V> Action1<TaskContext<V>> exponentialWait(long initTime, long maxTime, TimeUnit timeUnit) {
return exponentialWait(initTime, maxTime, timeUnit, 2);
} | [
"public",
"static",
"<",
"V",
">",
"Action1",
"<",
"TaskContext",
"<",
"V",
">",
">",
"exponentialWait",
"(",
"long",
"initTime",
",",
"long",
"maxTime",
",",
"TimeUnit",
"timeUnit",
")",
"{",
"return",
"exponentialWait",
"(",
"initTime",
",",
"maxTime",
"... | The exponential increase sleep time.
@param initTime The first sleep time.
@param maxTime The max sleep time.
@param timeUnit The time unit.
@param <V> The return value type.
@return The wait strategy action. | [
"The",
"exponential",
"increase",
"sleep",
"time",
"."
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/retry/WaitStrategies.java#L55-L57 |
gallandarakhneorg/afc | advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java | BusItinerary.getDistanceBetweenBusHalts | @Pure
public double getDistanceBetweenBusHalts(int firsthaltIndex, int lasthaltIndex) {
if (firsthaltIndex < 0 || firsthaltIndex >= this.validHalts.size() - 1) {
throw new ArrayIndexOutOfBoundsException(firsthaltIndex);
}
if (lasthaltIndex <= firsthaltIndex || lasthaltIndex >= this.validHalts.size()) {
throw new ArrayIndexOutOfBoundsException(lasthaltIndex);
}
double length = 0;
final BusItineraryHalt b1 = this.validHalts.get(firsthaltIndex);
final BusItineraryHalt b2 = this.validHalts.get(lasthaltIndex);
final int firstSegment = b1.getRoadSegmentIndex();
final int lastSegment = b2.getRoadSegmentIndex();
for (int i = firstSegment + 1; i < lastSegment; ++i) {
final RoadSegment segment = this.roadSegments.getRoadSegmentAt(i);
length += segment.getLength();
}
Direction1D direction = getRoadSegmentDirection(firstSegment);
if (direction.isRevertedSegmentDirection()) {
length += b1.getPositionOnSegment();
} else {
length += this.roadSegments.getRoadSegmentAt(firstSegment).getLength() - b1.getPositionOnSegment();
}
direction = getRoadSegmentDirection(lastSegment);
if (direction.isSegmentDirection()) {
length += b2.getPositionOnSegment();
} else {
length += this.roadSegments.getRoadSegmentAt(firstSegment).getLength() - b2.getPositionOnSegment();
}
return length;
} | java | @Pure
public double getDistanceBetweenBusHalts(int firsthaltIndex, int lasthaltIndex) {
if (firsthaltIndex < 0 || firsthaltIndex >= this.validHalts.size() - 1) {
throw new ArrayIndexOutOfBoundsException(firsthaltIndex);
}
if (lasthaltIndex <= firsthaltIndex || lasthaltIndex >= this.validHalts.size()) {
throw new ArrayIndexOutOfBoundsException(lasthaltIndex);
}
double length = 0;
final BusItineraryHalt b1 = this.validHalts.get(firsthaltIndex);
final BusItineraryHalt b2 = this.validHalts.get(lasthaltIndex);
final int firstSegment = b1.getRoadSegmentIndex();
final int lastSegment = b2.getRoadSegmentIndex();
for (int i = firstSegment + 1; i < lastSegment; ++i) {
final RoadSegment segment = this.roadSegments.getRoadSegmentAt(i);
length += segment.getLength();
}
Direction1D direction = getRoadSegmentDirection(firstSegment);
if (direction.isRevertedSegmentDirection()) {
length += b1.getPositionOnSegment();
} else {
length += this.roadSegments.getRoadSegmentAt(firstSegment).getLength() - b1.getPositionOnSegment();
}
direction = getRoadSegmentDirection(lastSegment);
if (direction.isSegmentDirection()) {
length += b2.getPositionOnSegment();
} else {
length += this.roadSegments.getRoadSegmentAt(firstSegment).getLength() - b2.getPositionOnSegment();
}
return length;
} | [
"@",
"Pure",
"public",
"double",
"getDistanceBetweenBusHalts",
"(",
"int",
"firsthaltIndex",
",",
"int",
"lasthaltIndex",
")",
"{",
"if",
"(",
"firsthaltIndex",
"<",
"0",
"||",
"firsthaltIndex",
">=",
"this",
".",
"validHalts",
".",
"size",
"(",
")",
"-",
"1... | Replies the distance between two bus halt.
@param firsthaltIndex is the index of the first bus halt.
@param lasthaltIndex is the index of the last bus halt.
@return the distance in meters between the given bus halts. | [
"Replies",
"the",
"distance",
"between",
"two",
"bus",
"halt",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java#L934-L970 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java | ULocale.acceptLanguage | public static ULocale acceptLanguage(String acceptLanguageList, boolean[] fallback) {
return acceptLanguage(acceptLanguageList, ULocale.getAvailableLocales(),
fallback);
} | java | public static ULocale acceptLanguage(String acceptLanguageList, boolean[] fallback) {
return acceptLanguage(acceptLanguageList, ULocale.getAvailableLocales(),
fallback);
} | [
"public",
"static",
"ULocale",
"acceptLanguage",
"(",
"String",
"acceptLanguageList",
",",
"boolean",
"[",
"]",
"fallback",
")",
"{",
"return",
"acceptLanguage",
"(",
"acceptLanguageList",
",",
"ULocale",
".",
"getAvailableLocales",
"(",
")",
",",
"fallback",
")",... | <strong>[icu]</strong> Based on a HTTP formatted list of acceptable locales, determine an available
locale for the user. NullPointerException is thrown if acceptLanguageList or
availableLocales is null. If fallback is non-null, it will contain true if a
fallback locale (one not in the acceptLanguageList) was returned. The value on
entry is ignored. ULocale will be one of the locales in availableLocales, or the
ROOT ULocale if if a ROOT locale was used as a fallback (because nothing else in
availableLocales matched). No ULocale array element should be null; behavior is
undefined if this is the case. This function will choose a locale from the
ULocale.getAvailableLocales() list as available.
@param acceptLanguageList list in HTTP "Accept-Language:" format of acceptable locales
@param fallback if non-null, a 1-element array containing a boolean to be set with
the fallback status
@return one of the locales from the ULocale.getAvailableLocales() list, or null if
none match | [
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Based",
"on",
"a",
"HTTP",
"formatted",
"list",
"of",
"acceptable",
"locales",
"determine",
"an",
"available",
"locale",
"for",
"the",
"user",
".",
"NullPointerException",
"is",
"thrown",
"if",
"ac... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java#L2017-L2020 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSHome.java | EJSHome.WASInternal_copyPrimaryKey | protected final Object WASInternal_copyPrimaryKey(Object obj) {
// Make a "deep copy" of the primarykey object if the noPriaryKeyMutation
// property is false.
if (!noPrimaryKeyMutation && !statefulSessionHome) {
//PK34120: start
Object copy = null;
//Get the CCL from the bmd and use SetContextClassLoaderPrivileged to change the CCL if necessary.
Object oldCL = EJBThreadData.svThreadContextAccessor.pushContextClassLoaderForUnprivileged(beanMetaData.classLoader); //PK83186
try {
copy = container.ivObjectCopier.copy((Serializable) obj); // RTC102299
} catch (Throwable t) {
FFDCFilter.processException(t, CLASS_NAME + ".WASInternal_copyPrimaryKey",
"4016", this);
ContainerEJBException ex = new ContainerEJBException
("WASInternal_copyPrimaryKey failed attempting to process PrimaryKey", t);
Tr.error(tc,
"CAUGHT_EXCEPTION_THROWING_NEW_EXCEPTION_CNTR0035E",
new Object[] { t, ex.toString() });
throw ex;
} finally {
EJBThreadData.svThreadContextAccessor.popContextClassLoaderForUnprivileged(oldCL);
}
return copy;
//PK34120: end
}
return obj;
} | java | protected final Object WASInternal_copyPrimaryKey(Object obj) {
// Make a "deep copy" of the primarykey object if the noPriaryKeyMutation
// property is false.
if (!noPrimaryKeyMutation && !statefulSessionHome) {
//PK34120: start
Object copy = null;
//Get the CCL from the bmd and use SetContextClassLoaderPrivileged to change the CCL if necessary.
Object oldCL = EJBThreadData.svThreadContextAccessor.pushContextClassLoaderForUnprivileged(beanMetaData.classLoader); //PK83186
try {
copy = container.ivObjectCopier.copy((Serializable) obj); // RTC102299
} catch (Throwable t) {
FFDCFilter.processException(t, CLASS_NAME + ".WASInternal_copyPrimaryKey",
"4016", this);
ContainerEJBException ex = new ContainerEJBException
("WASInternal_copyPrimaryKey failed attempting to process PrimaryKey", t);
Tr.error(tc,
"CAUGHT_EXCEPTION_THROWING_NEW_EXCEPTION_CNTR0035E",
new Object[] { t, ex.toString() });
throw ex;
} finally {
EJBThreadData.svThreadContextAccessor.popContextClassLoaderForUnprivileged(oldCL);
}
return copy;
//PK34120: end
}
return obj;
} | [
"protected",
"final",
"Object",
"WASInternal_copyPrimaryKey",
"(",
"Object",
"obj",
")",
"{",
"// Make a \"deep copy\" of the primarykey object if the noPriaryKeyMutation",
"// property is false.",
"if",
"(",
"!",
"noPrimaryKeyMutation",
"&&",
"!",
"statefulSessionHome",
")",
"... | This method is used to make a copy of the Primary Key object.
For the APAR PK26539, the user is doing a EJBLocalObject.getPrimaryKey().
They are then modifying the resultant primary key (PK) and using the PK for further
operations. When the user updates the PK, they are essentially editing the "live" PK
that we used as part of our caching, thus messing up our internal cache. However, what the
user is doing is perfectly fine and acceptable. To account for this, we need to do a "deep"
copy to copy the PK object and return the copy of the PK object, not the "live" object. This
issue was only hit in the local case as we had already accounted for this in the remote case.
PK34120: The above info is true, but with one twist. When EJBLocalObject.getPrimaryKey is called,
there is the potential that the ContextClassLoader (CCL) used during the copy is not the same
CCL used later when operations are performed on the key. As such, we must make sure that the
same CCL is used every time the key is copied. To do this, we must get the CCL from the bean meta
data and make sure that CCL is used for the duration of the copy. This copy is a special
case. For most methods on EJBLocalObject pre/postInvoke is called which will set the
correct CCL. However, the EJBLocalObject.getPrimaryKey method is a special case were pre/postInvoke
processing isn't called, thus resulting in the potential for an incorrect CCL being used during the copy.
@param obj the object to be copied | [
"This",
"method",
"is",
"used",
"to",
"make",
"a",
"copy",
"of",
"the",
"Primary",
"Key",
"object",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSHome.java#L3575-L3603 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/bos/BosClient.java | BosClient.appendObject | public AppendObjectResponse appendObject(String bucketName, String key, String value, ObjectMetadata metadata) {
try {
return this.appendObject(bucketName, key, value.getBytes(DEFAULT_ENCODING), metadata);
} catch (UnsupportedEncodingException e) {
throw new BceClientException("Fail to get bytes.", e);
}
} | java | public AppendObjectResponse appendObject(String bucketName, String key, String value, ObjectMetadata metadata) {
try {
return this.appendObject(bucketName, key, value.getBytes(DEFAULT_ENCODING), metadata);
} catch (UnsupportedEncodingException e) {
throw new BceClientException("Fail to get bytes.", e);
}
} | [
"public",
"AppendObjectResponse",
"appendObject",
"(",
"String",
"bucketName",
",",
"String",
"key",
",",
"String",
"value",
",",
"ObjectMetadata",
"metadata",
")",
"{",
"try",
"{",
"return",
"this",
".",
"appendObject",
"(",
"bucketName",
",",
"key",
",",
"va... | Uploads the specified string and object metadata to Bos under the specified bucket and key name.
@param bucketName The name of an existing bucket, to which you have Write permission.
@param key The key under which to store the specified file.
@param value The string containing the value to be uploaded to Bos.
@param metadata Additional metadata instructing Bos how to handle the uploaded data
(e.g. custom user metadata, hooks for specifying content type, etc.).
@return An AppendObjectResponse object containing the information returned by Bos for the newly created object. | [
"Uploads",
"the",
"specified",
"string",
"and",
"object",
"metadata",
"to",
"Bos",
"under",
"the",
"specified",
"bucket",
"and",
"key",
"name",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bos/BosClient.java#L1717-L1723 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Integer.java | Integer.getInteger | public static Integer getInteger(String nm, Integer val) {
String v = null;
try {
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
return Integer.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
} | java | public static Integer getInteger(String nm, Integer val) {
String v = null;
try {
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
return Integer.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
} | [
"public",
"static",
"Integer",
"getInteger",
"(",
"String",
"nm",
",",
"Integer",
"val",
")",
"{",
"String",
"v",
"=",
"null",
";",
"try",
"{",
"v",
"=",
"System",
".",
"getProperty",
"(",
"nm",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
... | Returns the integer value of the system property with the
specified name. The first argument is treated as the name of a
system property. System properties are accessible through the
{@link java.lang.System#getProperty(java.lang.String)} method.
The string value of this property is then interpreted as an
integer value, as per the {@link Integer#decode decode} method,
and an {@code Integer} object representing this value is
returned; in summary:
<ul><li>If the property value begins with the two ASCII characters
{@code 0x} or the ASCII character {@code #}, not
followed by a minus sign, then the rest of it is parsed as a
hexadecimal integer exactly as by the method
{@link #valueOf(java.lang.String, int)} with radix 16.
<li>If the property value begins with the ASCII character
{@code 0} followed by another character, it is parsed as an
octal integer exactly as by the method
{@link #valueOf(java.lang.String, int)} with radix 8.
<li>Otherwise, the property value is parsed as a decimal integer
exactly as by the method {@link #valueOf(java.lang.String, int)}
with radix 10.
</ul>
<p>The second argument is the default value. The default value is
returned if there is no property of the specified name, if the
property does not have the correct numeric format, or if the
specified name is empty or {@code null}.
@param nm property name.
@param val default value.
@return the {@code Integer} value of the property.
@throws SecurityException for the same reasons as
{@link System#getProperty(String) System.getProperty}
@see System#getProperty(java.lang.String)
@see System#getProperty(java.lang.String, java.lang.String) | [
"Returns",
"the",
"integer",
"value",
"of",
"the",
"system",
"property",
"with",
"the",
"specified",
"name",
".",
"The",
"first",
"argument",
"is",
"treated",
"as",
"the",
"name",
"of",
"a",
"system",
"property",
".",
"System",
"properties",
"are",
"accessib... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Integer.java#L898-L911 |
flow/caustic | api/src/main/java/com/flowpowered/caustic/api/util/MeshGenerator.java | MeshGenerator.generatePlane | public static VertexData generatePlane(Vector2f size) {
final VertexData destination = new VertexData();
final VertexAttribute positionsAttribute = new VertexAttribute("positions", DataType.FLOAT, 3);
destination.addAttribute(0, positionsAttribute);
final TFloatList positions = new TFloatArrayList();
final VertexAttribute normalsAttribute = new VertexAttribute("normals", DataType.FLOAT, 3);
destination.addAttribute(1, normalsAttribute);
final TFloatList normals = new TFloatArrayList();
final VertexAttribute textureCoordsAttribute = new VertexAttribute("textureCoords", DataType.FLOAT, 2);
destination.addAttribute(2, textureCoordsAttribute);
final TFloatList textureCoords = new TFloatArrayList();
final TIntList indices = destination.getIndices();
// Generate the mesh
generatePlane(positions, normals, textureCoords, indices, size);
// Put the mesh in the vertex data
positionsAttribute.setData(positions);
normalsAttribute.setData(normals);
textureCoordsAttribute.setData(textureCoords);
return destination;
} | java | public static VertexData generatePlane(Vector2f size) {
final VertexData destination = new VertexData();
final VertexAttribute positionsAttribute = new VertexAttribute("positions", DataType.FLOAT, 3);
destination.addAttribute(0, positionsAttribute);
final TFloatList positions = new TFloatArrayList();
final VertexAttribute normalsAttribute = new VertexAttribute("normals", DataType.FLOAT, 3);
destination.addAttribute(1, normalsAttribute);
final TFloatList normals = new TFloatArrayList();
final VertexAttribute textureCoordsAttribute = new VertexAttribute("textureCoords", DataType.FLOAT, 2);
destination.addAttribute(2, textureCoordsAttribute);
final TFloatList textureCoords = new TFloatArrayList();
final TIntList indices = destination.getIndices();
// Generate the mesh
generatePlane(positions, normals, textureCoords, indices, size);
// Put the mesh in the vertex data
positionsAttribute.setData(positions);
normalsAttribute.setData(normals);
textureCoordsAttribute.setData(textureCoords);
return destination;
} | [
"public",
"static",
"VertexData",
"generatePlane",
"(",
"Vector2f",
"size",
")",
"{",
"final",
"VertexData",
"destination",
"=",
"new",
"VertexData",
"(",
")",
";",
"final",
"VertexAttribute",
"positionsAttribute",
"=",
"new",
"VertexAttribute",
"(",
"\"positions\""... | Generates a plane on xy. The center is at the middle of the plane.
@param size The size of the plane to generate, on x and y
@return The vertex data | [
"Generates",
"a",
"plane",
"on",
"xy",
".",
"The",
"center",
"is",
"at",
"the",
"middle",
"of",
"the",
"plane",
"."
] | train | https://github.com/flow/caustic/blob/88652fcf0621ce158a0e92ce4c570ed6b1f6fca9/api/src/main/java/com/flowpowered/caustic/api/util/MeshGenerator.java#L593-L612 |
sarl/sarl | main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/BundleUtil.java | BundleUtil.getSourceBundlePath | public static IPath getSourceBundlePath(Bundle bundle, IPath bundleLocation) {
IPath sourcesPath = null;
// Not an essential functionality, make it robust
try {
final IPath srcFolderPath = getSourceRootProjectFolderPath(bundle);
if (srcFolderPath == null) {
//common case, jar file.
final IPath bundlesParentFolder = bundleLocation.removeLastSegments(1);
final String binaryJarName = bundleLocation.lastSegment();
final String symbolicName = bundle.getSymbolicName();
final String sourceJarName = binaryJarName.replace(symbolicName,
symbolicName.concat(SOURCE_SUFIX));
final IPath potentialSourceJar = bundlesParentFolder.append(sourceJarName);
if (potentialSourceJar.toFile().exists()) {
sourcesPath = potentialSourceJar;
}
} else {
sourcesPath = srcFolderPath;
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
return sourcesPath;
} | java | public static IPath getSourceBundlePath(Bundle bundle, IPath bundleLocation) {
IPath sourcesPath = null;
// Not an essential functionality, make it robust
try {
final IPath srcFolderPath = getSourceRootProjectFolderPath(bundle);
if (srcFolderPath == null) {
//common case, jar file.
final IPath bundlesParentFolder = bundleLocation.removeLastSegments(1);
final String binaryJarName = bundleLocation.lastSegment();
final String symbolicName = bundle.getSymbolicName();
final String sourceJarName = binaryJarName.replace(symbolicName,
symbolicName.concat(SOURCE_SUFIX));
final IPath potentialSourceJar = bundlesParentFolder.append(sourceJarName);
if (potentialSourceJar.toFile().exists()) {
sourcesPath = potentialSourceJar;
}
} else {
sourcesPath = srcFolderPath;
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
return sourcesPath;
} | [
"public",
"static",
"IPath",
"getSourceBundlePath",
"(",
"Bundle",
"bundle",
",",
"IPath",
"bundleLocation",
")",
"{",
"IPath",
"sourcesPath",
"=",
"null",
";",
"// Not an essential functionality, make it robust",
"try",
"{",
"final",
"IPath",
"srcFolderPath",
"=",
"g... | Replies the source location for the given bundle.
<p>The source location is usually the root folder where the source code of the bundle is located.
<p>We can't use P2Utils and we can't use SimpleConfiguratorManipulator because of
API breakage between 3.5 and 4.2.
So we do a bit EDV (Computer data processing) ;-)
@param bundle the bundle for which the source location must be computed.
@param bundleLocation the location of the bundle, as replied by {@link #getBundlePath(Bundle)}.
@return the path to the source folder of the bundle, or {@code null} if undefined.
@see #getBundlePath(Bundle) | [
"Replies",
"the",
"source",
"location",
"for",
"the",
"given",
"bundle",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/BundleUtil.java#L120-L144 |
vdmeer/skb-java-base | src/main/java/de/vandermeer/skb/base/shell/SkbShellFactory.java | SkbShellFactory.newCommand | public static SkbShellCommand newCommand(String command, SkbShellArgument[] arguments, SkbShellCommandCategory category, String description, String addedHelp){
return new AbstractShellCommand(command, arguments, category, description, addedHelp);
} | java | public static SkbShellCommand newCommand(String command, SkbShellArgument[] arguments, SkbShellCommandCategory category, String description, String addedHelp){
return new AbstractShellCommand(command, arguments, category, description, addedHelp);
} | [
"public",
"static",
"SkbShellCommand",
"newCommand",
"(",
"String",
"command",
",",
"SkbShellArgument",
"[",
"]",
"arguments",
",",
"SkbShellCommandCategory",
"category",
",",
"String",
"description",
",",
"String",
"addedHelp",
")",
"{",
"return",
"new",
"AbstractS... | Returns a new shell command, use the factory to create one.
@param command the actual command
@param arguments the command's arguments, can be null
@param category the command's category, can be null
@param description the command's description
@param addedHelp additional help, can be null
@return new shell command
@throws IllegalArgumentException if command or description was null | [
"Returns",
"a",
"new",
"shell",
"command",
"use",
"the",
"factory",
"to",
"create",
"one",
"."
] | train | https://github.com/vdmeer/skb-java-base/blob/6d845bcc482aa9344d016e80c0c3455aeae13a13/src/main/java/de/vandermeer/skb/base/shell/SkbShellFactory.java#L110-L112 |
jOOQ/jOOL | jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java | Unchecked.intConsumer | public static IntConsumer intConsumer(CheckedIntConsumer consumer, Consumer<Throwable> handler) {
return i -> {
try {
consumer.accept(i);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
}
};
} | java | public static IntConsumer intConsumer(CheckedIntConsumer consumer, Consumer<Throwable> handler) {
return i -> {
try {
consumer.accept(i);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
}
};
} | [
"public",
"static",
"IntConsumer",
"intConsumer",
"(",
"CheckedIntConsumer",
"consumer",
",",
"Consumer",
"<",
"Throwable",
">",
"handler",
")",
"{",
"return",
"i",
"->",
"{",
"try",
"{",
"consumer",
".",
"accept",
"(",
"i",
")",
";",
"}",
"catch",
"(",
... | Wrap a {@link CheckedIntConsumer} in a {@link IntConsumer} with a custom handler for checked exceptions.
<p>
Example:
<code><pre>
Arrays.stream(new int[] { 1, 2 }).forEach(Unchecked.intConsumer(
i -> {
if (i < 0)
throw new Exception("Only positive numbers allowed");
},
e -> {
throw new IllegalStateException(e);
}
));
</pre></code> | [
"Wrap",
"a",
"{"
] | train | https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L735-L746 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ExpressRouteCircuitAuthorizationsInner.java | ExpressRouteCircuitAuthorizationsInner.createOrUpdateAsync | public Observable<ExpressRouteCircuitAuthorizationInner> createOrUpdateAsync(String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).map(new Func1<ServiceResponse<ExpressRouteCircuitAuthorizationInner>, ExpressRouteCircuitAuthorizationInner>() {
@Override
public ExpressRouteCircuitAuthorizationInner call(ServiceResponse<ExpressRouteCircuitAuthorizationInner> response) {
return response.body();
}
});
} | java | public Observable<ExpressRouteCircuitAuthorizationInner> createOrUpdateAsync(String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).map(new Func1<ServiceResponse<ExpressRouteCircuitAuthorizationInner>, ExpressRouteCircuitAuthorizationInner>() {
@Override
public ExpressRouteCircuitAuthorizationInner call(ServiceResponse<ExpressRouteCircuitAuthorizationInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ExpressRouteCircuitAuthorizationInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"circuitName",
",",
"String",
"authorizationName",
",",
"ExpressRouteCircuitAuthorizationInner",
"authorizationParameters",
")",
... | Creates or updates an authorization in the specified express route circuit.
@param resourceGroupName The name of the resource group.
@param circuitName The name of the express route circuit.
@param authorizationName The name of the authorization.
@param authorizationParameters Parameters supplied to the create or update express route circuit authorization operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"an",
"authorization",
"in",
"the",
"specified",
"express",
"route",
"circuit",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ExpressRouteCircuitAuthorizationsInner.java#L391-L398 |
comapi/comapi-chat-sdk-android | COMAPI/chat/src/main/java/com/comapi/chat/PersistenceController.java | PersistenceController.upsertMessageStatuses | public Observable<Boolean> upsertMessageStatuses(String conversationId, String profileId, List<MessageStatusUpdate> msgStatusList) {
return asObservable(new Executor<Boolean>() {
@Override
void execute(ChatStore store, Emitter<Boolean> emitter) {
store.beginTransaction();
boolean isSuccess = false;
for (MessageStatusUpdate statusUpdate : msgStatusList) {
for (String messageId : statusUpdate.getMessageIds()) {
LocalMessageStatus status = null;
if (MessageStatus.delivered.name().equals(statusUpdate.getStatus())) {
status = LocalMessageStatus.delivered;
} else if (MessageStatus.read.name().equals(statusUpdate.getStatus())) {
status = LocalMessageStatus.read;
}
if (status != null) {
isSuccess = store.update(ChatMessageStatus.builder().populate(conversationId, messageId, profileId, status, DateHelper.getUTCMilliseconds(statusUpdate.getTimestamp()), null).build());
}
}
}
store.endTransaction();
emitter.onNext(isSuccess);
emitter.onCompleted();
}
});
} | java | public Observable<Boolean> upsertMessageStatuses(String conversationId, String profileId, List<MessageStatusUpdate> msgStatusList) {
return asObservable(new Executor<Boolean>() {
@Override
void execute(ChatStore store, Emitter<Boolean> emitter) {
store.beginTransaction();
boolean isSuccess = false;
for (MessageStatusUpdate statusUpdate : msgStatusList) {
for (String messageId : statusUpdate.getMessageIds()) {
LocalMessageStatus status = null;
if (MessageStatus.delivered.name().equals(statusUpdate.getStatus())) {
status = LocalMessageStatus.delivered;
} else if (MessageStatus.read.name().equals(statusUpdate.getStatus())) {
status = LocalMessageStatus.read;
}
if (status != null) {
isSuccess = store.update(ChatMessageStatus.builder().populate(conversationId, messageId, profileId, status, DateHelper.getUTCMilliseconds(statusUpdate.getTimestamp()), null).build());
}
}
}
store.endTransaction();
emitter.onNext(isSuccess);
emitter.onCompleted();
}
});
} | [
"public",
"Observable",
"<",
"Boolean",
">",
"upsertMessageStatuses",
"(",
"String",
"conversationId",
",",
"String",
"profileId",
",",
"List",
"<",
"MessageStatusUpdate",
">",
"msgStatusList",
")",
"{",
"return",
"asObservable",
"(",
"new",
"Executor",
"<",
"Bool... | Insert new message statuses obtained from message query.
@param conversationId Unique conversation id.
@param profileId Profile id from current session details.
@param msgStatusList New message statuses.
@return Observable emitting result. | [
"Insert",
"new",
"message",
"statuses",
"obtained",
"from",
"message",
"query",
"."
] | train | https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/PersistenceController.java#L387-L417 |
datacleaner/DataCleaner | engine/core/src/main/java/org/datacleaner/job/runner/ConsumeRowHandler.java | ConsumeRowHandler.consumeRow | public ConsumeRowResult consumeRow(final InputRow row) {
final FilterOutcomes outcomes = new FilterOutcomesImpl(_alwaysSatisfiedOutcomes);
final ConsumeRowHandlerDelegate delegate = new ConsumeRowHandlerDelegate(_consumers, row, 0, outcomes);
return delegate.consume();
} | java | public ConsumeRowResult consumeRow(final InputRow row) {
final FilterOutcomes outcomes = new FilterOutcomesImpl(_alwaysSatisfiedOutcomes);
final ConsumeRowHandlerDelegate delegate = new ConsumeRowHandlerDelegate(_consumers, row, 0, outcomes);
return delegate.consume();
} | [
"public",
"ConsumeRowResult",
"consumeRow",
"(",
"final",
"InputRow",
"row",
")",
"{",
"final",
"FilterOutcomes",
"outcomes",
"=",
"new",
"FilterOutcomesImpl",
"(",
"_alwaysSatisfiedOutcomes",
")",
";",
"final",
"ConsumeRowHandlerDelegate",
"delegate",
"=",
"new",
"Co... | Consumes a {@link InputRow} by applying all transformations etc. to it,
returning a result of transformed rows and their {@link FilterOutcomes}s.
@param row
@return | [
"Consumes",
"a",
"{",
"@link",
"InputRow",
"}",
"by",
"applying",
"all",
"transformations",
"etc",
".",
"to",
"it",
"returning",
"a",
"result",
"of",
"transformed",
"rows",
"and",
"their",
"{",
"@link",
"FilterOutcomes",
"}",
"s",
"."
] | train | https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/job/runner/ConsumeRowHandler.java#L142-L146 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF5.java | CommonOps_DDF5.addEquals | public static void addEquals( DMatrix5 a , DMatrix5 b ) {
a.a1 += b.a1;
a.a2 += b.a2;
a.a3 += b.a3;
a.a4 += b.a4;
a.a5 += b.a5;
} | java | public static void addEquals( DMatrix5 a , DMatrix5 b ) {
a.a1 += b.a1;
a.a2 += b.a2;
a.a3 += b.a3;
a.a4 += b.a4;
a.a5 += b.a5;
} | [
"public",
"static",
"void",
"addEquals",
"(",
"DMatrix5",
"a",
",",
"DMatrix5",
"b",
")",
"{",
"a",
".",
"a1",
"+=",
"b",
".",
"a1",
";",
"a",
".",
"a2",
"+=",
"b",
".",
"a2",
";",
"a",
".",
"a3",
"+=",
"b",
".",
"a3",
";",
"a",
".",
"a4",
... | <p>Performs the following operation:<br>
<br>
a = a + b <br>
a<sub>i</sub> = a<sub>i</sub> + b<sub>i</sub> <br>
</p>
@param a A Vector. Modified.
@param b A Vector. Not modified. | [
"<p",
">",
"Performs",
"the",
"following",
"operation",
":",
"<br",
">",
"<br",
">",
"a",
"=",
"a",
"+",
"b",
"<br",
">",
"a<sub",
">",
"i<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"i<",
"/",
"sub",
">",
"+",
"b<sub",
">",
"i<",
"/",
"sub",
">",... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF5.java#L146-L152 |
apache/incubator-gobblin | gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/Instrumented.java | Instrumented.updateTimer | public static void updateTimer(Optional<Timer> timer, final long duration, final TimeUnit unit) {
timer.transform(new Function<Timer, Timer>() {
@Override
public Timer apply(@Nonnull Timer input) {
input.update(duration, unit);
return input;
}
});
} | java | public static void updateTimer(Optional<Timer> timer, final long duration, final TimeUnit unit) {
timer.transform(new Function<Timer, Timer>() {
@Override
public Timer apply(@Nonnull Timer input) {
input.update(duration, unit);
return input;
}
});
} | [
"public",
"static",
"void",
"updateTimer",
"(",
"Optional",
"<",
"Timer",
">",
"timer",
",",
"final",
"long",
"duration",
",",
"final",
"TimeUnit",
"unit",
")",
"{",
"timer",
".",
"transform",
"(",
"new",
"Function",
"<",
"Timer",
",",
"Timer",
">",
"(",... | Updates a timer only if it is defined.
@param timer an Optional<{@link com.codahale.metrics.Timer}>
@param duration
@param unit | [
"Updates",
"a",
"timer",
"only",
"if",
"it",
"is",
"defined",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/Instrumented.java#L240-L248 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncAgentsInner.java | SyncAgentsInner.beginCreateOrUpdateAsync | public Observable<SyncAgentInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, String syncAgentName, String syncDatabaseId) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, syncAgentName, syncDatabaseId).map(new Func1<ServiceResponse<SyncAgentInner>, SyncAgentInner>() {
@Override
public SyncAgentInner call(ServiceResponse<SyncAgentInner> response) {
return response.body();
}
});
} | java | public Observable<SyncAgentInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, String syncAgentName, String syncDatabaseId) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, syncAgentName, syncDatabaseId).map(new Func1<ServiceResponse<SyncAgentInner>, SyncAgentInner>() {
@Override
public SyncAgentInner call(ServiceResponse<SyncAgentInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"SyncAgentInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"syncAgentName",
",",
"String",
"syncDatabaseId",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync... | Creates or updates a sync agent.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server on which the sync agent is hosted.
@param syncAgentName The name of the sync agent.
@param syncDatabaseId ARM resource id of the sync database in the sync agent.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SyncAgentInner object | [
"Creates",
"or",
"updates",
"a",
"sync",
"agent",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncAgentsInner.java#L489-L496 |
mikepenz/MaterialDrawer | library/src/main/java/com/mikepenz/materialdrawer/util/DrawerUIUtils.java | DrawerUIUtils.getIconStateList | public static StateListDrawable getIconStateList(Drawable icon, Drawable selectedIcon) {
StateListDrawable iconStateListDrawable = new StateListDrawable();
iconStateListDrawable.addState(new int[]{android.R.attr.state_selected}, selectedIcon);
iconStateListDrawable.addState(new int[]{}, icon);
return iconStateListDrawable;
} | java | public static StateListDrawable getIconStateList(Drawable icon, Drawable selectedIcon) {
StateListDrawable iconStateListDrawable = new StateListDrawable();
iconStateListDrawable.addState(new int[]{android.R.attr.state_selected}, selectedIcon);
iconStateListDrawable.addState(new int[]{}, icon);
return iconStateListDrawable;
} | [
"public",
"static",
"StateListDrawable",
"getIconStateList",
"(",
"Drawable",
"icon",
",",
"Drawable",
"selectedIcon",
")",
"{",
"StateListDrawable",
"iconStateListDrawable",
"=",
"new",
"StateListDrawable",
"(",
")",
";",
"iconStateListDrawable",
".",
"addState",
"(",
... | helper to create a stateListDrawable for the icon
@param icon
@param selectedIcon
@return | [
"helper",
"to",
"create",
"a",
"stateListDrawable",
"for",
"the",
"icon"
] | train | https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/util/DrawerUIUtils.java#L155-L160 |
threerings/nenya | core/src/main/java/com/threerings/media/image/ImageManager.java | ImageManager.getImageKey | public ImageKey getImageKey (String rset, String path)
{
return getImageKey(getDataProvider(rset), path);
} | java | public ImageKey getImageKey (String rset, String path)
{
return getImageKey(getDataProvider(rset), path);
} | [
"public",
"ImageKey",
"getImageKey",
"(",
"String",
"rset",
",",
"String",
"path",
")",
"{",
"return",
"getImageKey",
"(",
"getDataProvider",
"(",
"rset",
")",
",",
"path",
")",
";",
"}"
] | Returns an image key that can be used to fetch the image identified by the specified
resource set and image path. | [
"Returns",
"an",
"image",
"key",
"that",
"can",
"be",
"used",
"to",
"fetch",
"the",
"image",
"identified",
"by",
"the",
"specified",
"resource",
"set",
"and",
"image",
"path",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/image/ImageManager.java#L262-L265 |
ravendb/ravendb-jvm-client | src/main/java/net/ravendb/client/documents/subscriptions/DocumentSubscriptions.java | DocumentSubscriptions.getSubscriptionWorker | public SubscriptionWorker<ObjectNode> getSubscriptionWorker(SubscriptionWorkerOptions options, String database) {
return getSubscriptionWorker(ObjectNode.class, options, database);
} | java | public SubscriptionWorker<ObjectNode> getSubscriptionWorker(SubscriptionWorkerOptions options, String database) {
return getSubscriptionWorker(ObjectNode.class, options, database);
} | [
"public",
"SubscriptionWorker",
"<",
"ObjectNode",
">",
"getSubscriptionWorker",
"(",
"SubscriptionWorkerOptions",
"options",
",",
"String",
"database",
")",
"{",
"return",
"getSubscriptionWorker",
"(",
"ObjectNode",
".",
"class",
",",
"options",
",",
"database",
")",... | It opens a subscription and starts pulling documents since a last processed document for that subscription.
The connection options determine client and server cooperation rules like document batch sizes or a timeout in a matter of which a client
needs to acknowledge that batch has been processed. The acknowledgment is sent after all documents are processed by subscription's handlers.
There can be only a single client that is connected to a subscription.
@param options Subscription options
@param database Target database
@return Subscription object that allows to add/remove subscription handlers. | [
"It",
"opens",
"a",
"subscription",
"and",
"starts",
"pulling",
"documents",
"since",
"a",
"last",
"processed",
"document",
"for",
"that",
"subscription",
".",
"The",
"connection",
"options",
"determine",
"client",
"and",
"server",
"cooperation",
"rules",
"like",
... | train | https://github.com/ravendb/ravendb-jvm-client/blob/5a45727de507b541d1571e79ddd97c7d88bee787/src/main/java/net/ravendb/client/documents/subscriptions/DocumentSubscriptions.java#L167-L169 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java | PaymentProtocol.createPayToAddressOutput | public static Protos.Output createPayToAddressOutput(@Nullable Coin amount, Address address) {
Protos.Output.Builder output = Protos.Output.newBuilder();
if (amount != null) {
final NetworkParameters params = address.getParameters();
if (params.hasMaxMoney() && amount.compareTo(params.getMaxMoney()) > 0)
throw new IllegalArgumentException("Amount too big: " + amount);
output.setAmount(amount.value);
} else {
output.setAmount(0);
}
output.setScript(ByteString.copyFrom(ScriptBuilder.createOutputScript(address).getProgram()));
return output.build();
} | java | public static Protos.Output createPayToAddressOutput(@Nullable Coin amount, Address address) {
Protos.Output.Builder output = Protos.Output.newBuilder();
if (amount != null) {
final NetworkParameters params = address.getParameters();
if (params.hasMaxMoney() && amount.compareTo(params.getMaxMoney()) > 0)
throw new IllegalArgumentException("Amount too big: " + amount);
output.setAmount(amount.value);
} else {
output.setAmount(0);
}
output.setScript(ByteString.copyFrom(ScriptBuilder.createOutputScript(address).getProgram()));
return output.build();
} | [
"public",
"static",
"Protos",
".",
"Output",
"createPayToAddressOutput",
"(",
"@",
"Nullable",
"Coin",
"amount",
",",
"Address",
"address",
")",
"{",
"Protos",
".",
"Output",
".",
"Builder",
"output",
"=",
"Protos",
".",
"Output",
".",
"newBuilder",
"(",
")"... | Create a standard pay to address output for usage in {@link #createPaymentRequest} and
{@link #createPaymentMessage}.
@param amount amount to pay, or null
@param address address to pay to
@return output | [
"Create",
"a",
"standard",
"pay",
"to",
"address",
"output",
"for",
"usage",
"in",
"{",
"@link",
"#createPaymentRequest",
"}",
"and",
"{",
"@link",
"#createPaymentMessage",
"}",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java#L400-L412 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/YearMonth.java | YearMonth.plusYears | public YearMonth plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
int newYear = YEAR.checkValidIntValue(year + yearsToAdd); // safe overflow
return with(newYear, month);
} | java | public YearMonth plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
int newYear = YEAR.checkValidIntValue(year + yearsToAdd); // safe overflow
return with(newYear, month);
} | [
"public",
"YearMonth",
"plusYears",
"(",
"long",
"yearsToAdd",
")",
"{",
"if",
"(",
"yearsToAdd",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"int",
"newYear",
"=",
"YEAR",
".",
"checkValidIntValue",
"(",
"year",
"+",
"yearsToAdd",
")",
";",
"// saf... | Returns a copy of this {@code YearMonth} with the specified number of years added.
<p>
This instance is immutable and unaffected by this method call.
@param yearsToAdd the years to add, may be negative
@return a {@code YearMonth} based on this year-month with the years added, not null
@throws DateTimeException if the result exceeds the supported range | [
"Returns",
"a",
"copy",
"of",
"this",
"{",
"@code",
"YearMonth",
"}",
"with",
"the",
"specified",
"number",
"of",
"years",
"added",
".",
"<p",
">",
"This",
"instance",
"is",
"immutable",
"and",
"unaffected",
"by",
"this",
"method",
"call",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/YearMonth.java#L823-L829 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/jdbc/SnowflakeFileTransferAgent.java | SnowflakeFileTransferAgent.extractLocationAndPath | static public remoteLocation extractLocationAndPath(String stageLocationPath)
{
String location = stageLocationPath;
String path = "";
// split stage location as location name and path
if (stageLocationPath.contains("/"))
{
location = stageLocationPath.substring(0, stageLocationPath.indexOf("/"));
path = stageLocationPath.substring(stageLocationPath.indexOf("/") + 1);
}
return new remoteLocation(location, path);
} | java | static public remoteLocation extractLocationAndPath(String stageLocationPath)
{
String location = stageLocationPath;
String path = "";
// split stage location as location name and path
if (stageLocationPath.contains("/"))
{
location = stageLocationPath.substring(0, stageLocationPath.indexOf("/"));
path = stageLocationPath.substring(stageLocationPath.indexOf("/") + 1);
}
return new remoteLocation(location, path);
} | [
"static",
"public",
"remoteLocation",
"extractLocationAndPath",
"(",
"String",
"stageLocationPath",
")",
"{",
"String",
"location",
"=",
"stageLocationPath",
";",
"String",
"path",
"=",
"\"\"",
";",
"// split stage location as location name and path",
"if",
"(",
"stageLoc... | A small helper for extracting location name and path from full location path
@param stageLocationPath stage location
@return remoteLocation object | [
"A",
"small",
"helper",
"for",
"extracting",
"location",
"name",
"and",
"path",
"from",
"full",
"location",
"path"
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeFileTransferAgent.java#L2775-L2788 |
IBM/ibm-cos-sdk-java | ibm-cos-java-sdk-core/src/main/java/com/ibm/cloud/objectstorage/util/AWSRequestMetricsFullSupport.java | AWSRequestMetricsFullSupport.startEvent | @Override
public void startEvent(String eventName) {
/* This will overwrite past events */
eventsBeingProfiled.put // ignoring the wall clock time
(eventName, TimingInfo.startTimingFullSupport(System.nanoTime()));
} | java | @Override
public void startEvent(String eventName) {
/* This will overwrite past events */
eventsBeingProfiled.put // ignoring the wall clock time
(eventName, TimingInfo.startTimingFullSupport(System.nanoTime()));
} | [
"@",
"Override",
"public",
"void",
"startEvent",
"(",
"String",
"eventName",
")",
"{",
"/* This will overwrite past events */",
"eventsBeingProfiled",
".",
"put",
"// ignoring the wall clock time",
"(",
"eventName",
",",
"TimingInfo",
".",
"startTimingFullSupport",
"(",
"... | Start an event which will be timed. The startTime and endTime are added
to timingInfo only after endEvent is called. For every startEvent there
should be a corresponding endEvent. If you start the same event without
ending it, this will overwrite the old event. i.e. There is no support
for recursive events yet. Having said that, if you start and end an event
in that sequence multiple times, all events are logged in timingInfo in
that order.
This feature is enabled if the system property
"com.ibm.cloud.objectstorage.sdk.enableRuntimeProfiling" is set, or if a
{@link RequestMetricCollector} is in use either at the request, web service
client, or AWS SDK level.
@param eventName
- The name of the event to start
@see AwsSdkMetrics | [
"Start",
"an",
"event",
"which",
"will",
"be",
"timed",
".",
"The",
"startTime",
"and",
"endTime",
"are",
"added",
"to",
"timingInfo",
"only",
"after",
"endEvent",
"is",
"called",
".",
"For",
"every",
"startEvent",
"there",
"should",
"be",
"a",
"correspondin... | train | https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-core/src/main/java/com/ibm/cloud/objectstorage/util/AWSRequestMetricsFullSupport.java#L82-L87 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_upgrade.java | xen_upgrade.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_upgrade_responses result = (xen_upgrade_responses) service.get_payload_formatter().string_to_resource(xen_upgrade_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_upgrade_response_array);
}
xen_upgrade[] result_xen_upgrade = new xen_upgrade[result.xen_upgrade_response_array.length];
for(int i = 0; i < result.xen_upgrade_response_array.length; i++)
{
result_xen_upgrade[i] = result.xen_upgrade_response_array[i].xen_upgrade[0];
}
return result_xen_upgrade;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_upgrade_responses result = (xen_upgrade_responses) service.get_payload_formatter().string_to_resource(xen_upgrade_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_upgrade_response_array);
}
xen_upgrade[] result_xen_upgrade = new xen_upgrade[result.xen_upgrade_response_array.length];
for(int i = 0; i < result.xen_upgrade_response_array.length; i++)
{
result_xen_upgrade[i] = result.xen_upgrade_response_array[i].xen_upgrade[0];
}
return result_xen_upgrade;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"xen_upgrade_responses",
"result",
"=",
"(",
"xen_upgrade_responses",
")",
"service",
".",
"get_payload_format... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_upgrade.java#L241-L258 |
authlete/authlete-java-common | src/main/java/com/authlete/common/dto/BackchannelAuthenticationCompleteRequest.java | BackchannelAuthenticationCompleteRequest.setClaims | public BackchannelAuthenticationCompleteRequest setClaims(Map<String, Object> claims)
{
if (claims == null || claims.size() == 0)
{
this.claims = null;
}
else
{
setClaims(Utils.toJson(claims));
}
return this;
} | java | public BackchannelAuthenticationCompleteRequest setClaims(Map<String, Object> claims)
{
if (claims == null || claims.size() == 0)
{
this.claims = null;
}
else
{
setClaims(Utils.toJson(claims));
}
return this;
} | [
"public",
"BackchannelAuthenticationCompleteRequest",
"setClaims",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"claims",
")",
"{",
"if",
"(",
"claims",
"==",
"null",
"||",
"claims",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"this",
".",
"claims",
"=... | Set additional claims which will be embedded in the ID token.
<p>
The argument is converted into a JSON string and passed to
{@link #setClaims(String)} method.
</p>
@param claims
Additional claims. Keys are claim names.
@return
{@code this} object. | [
"Set",
"additional",
"claims",
"which",
"will",
"be",
"embedded",
"in",
"the",
"ID",
"token",
"."
] | train | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/dto/BackchannelAuthenticationCompleteRequest.java#L573-L585 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.cart_cartId_dedicatedReseller_GET | public ArrayList<OvhGenericProductDefinition> cart_cartId_dedicatedReseller_GET(String cartId, String family, String planCode) throws IOException {
String qPath = "/order/cart/{cartId}/dedicatedReseller";
StringBuilder sb = path(qPath, cartId);
query(sb, "family", family);
query(sb, "planCode", planCode);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t3);
} | java | public ArrayList<OvhGenericProductDefinition> cart_cartId_dedicatedReseller_GET(String cartId, String family, String planCode) throws IOException {
String qPath = "/order/cart/{cartId}/dedicatedReseller";
StringBuilder sb = path(qPath, cartId);
query(sb, "family", family);
query(sb, "planCode", planCode);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t3);
} | [
"public",
"ArrayList",
"<",
"OvhGenericProductDefinition",
">",
"cart_cartId_dedicatedReseller_GET",
"(",
"String",
"cartId",
",",
"String",
"family",
",",
"String",
"planCode",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/cart/{cartId}/dedicatedRe... | Get informations about a dedicated server for US Reseller
REST: GET /order/cart/{cartId}/dedicatedReseller
@param cartId [required] Cart identifier
@param planCode [required] Filter the value of planCode property (=)
@param family [required] Filter the value of family property (=) | [
"Get",
"informations",
"about",
"a",
"dedicated",
"server",
"for",
"US",
"Reseller"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L7639-L7646 |
alkacon/opencms-core | src/org/opencms/ade/contenteditor/CmsContentService.java | CmsContentService.writeContent | private CmsXmlContent writeContent(CmsObject cms, CmsFile file, CmsXmlContent content, String encoding)
throws CmsException {
String decodedContent = content.toString();
try {
file.setContents(decodedContent.getBytes(encoding));
} catch (UnsupportedEncodingException e) {
throw new CmsException(
org.opencms.workplace.editors.Messages.get().container(
org.opencms.workplace.editors.Messages.ERR_INVALID_CONTENT_ENC_1,
file.getRootPath()),
e);
}
// the file content might have been modified during the write operation
cms.getRequestContext().setAttribute(ATTR_EDITOR_SAVING, "true");
try {
file = cms.writeFile(file);
} finally {
cms.getRequestContext().removeAttribute(ATTR_EDITOR_SAVING);
}
return CmsXmlContentFactory.unmarshal(cms, file);
} | java | private CmsXmlContent writeContent(CmsObject cms, CmsFile file, CmsXmlContent content, String encoding)
throws CmsException {
String decodedContent = content.toString();
try {
file.setContents(decodedContent.getBytes(encoding));
} catch (UnsupportedEncodingException e) {
throw new CmsException(
org.opencms.workplace.editors.Messages.get().container(
org.opencms.workplace.editors.Messages.ERR_INVALID_CONTENT_ENC_1,
file.getRootPath()),
e);
}
// the file content might have been modified during the write operation
cms.getRequestContext().setAttribute(ATTR_EDITOR_SAVING, "true");
try {
file = cms.writeFile(file);
} finally {
cms.getRequestContext().removeAttribute(ATTR_EDITOR_SAVING);
}
return CmsXmlContentFactory.unmarshal(cms, file);
} | [
"private",
"CmsXmlContent",
"writeContent",
"(",
"CmsObject",
"cms",
",",
"CmsFile",
"file",
",",
"CmsXmlContent",
"content",
",",
"String",
"encoding",
")",
"throws",
"CmsException",
"{",
"String",
"decodedContent",
"=",
"content",
".",
"toString",
"(",
")",
";... | Writes the xml content to the vfs and re-initializes the member variables.<p>
@param cms the cms context
@param file the file to write to
@param content the content
@param encoding the file encoding
@return the content
@throws CmsException if writing the file fails | [
"Writes",
"the",
"xml",
"content",
"to",
"the",
"vfs",
"and",
"re",
"-",
"initializes",
"the",
"member",
"variables",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/contenteditor/CmsContentService.java#L2703-L2724 |
mcxiaoke/Android-Next | core/src/main/java/com/mcxiaoke/next/utils/IOUtils.java | IOUtils.readStringFromAssets | public static String readStringFromAssets(Context context, String fileName) throws IOException {
if (context == null || StringUtils.isEmpty(fileName)) {
return null;
}
StringBuilder s = new StringBuilder("");
InputStreamReader in = new InputStreamReader(context.getResources().getAssets().open(fileName));
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
s.append(line);
}
return s.toString();
} | java | public static String readStringFromAssets(Context context, String fileName) throws IOException {
if (context == null || StringUtils.isEmpty(fileName)) {
return null;
}
StringBuilder s = new StringBuilder("");
InputStreamReader in = new InputStreamReader(context.getResources().getAssets().open(fileName));
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
s.append(line);
}
return s.toString();
} | [
"public",
"static",
"String",
"readStringFromAssets",
"(",
"Context",
"context",
",",
"String",
"fileName",
")",
"throws",
"IOException",
"{",
"if",
"(",
"context",
"==",
"null",
"||",
"StringUtils",
".",
"isEmpty",
"(",
"fileName",
")",
")",
"{",
"return",
... | get an asset using ACCESS_STREAMING mode. This provides access to files that have been bundled with an
application as assets -- that is, files placed in to the "assets" directory.
@param context
@param fileName The name of the asset to open. This name can be hierarchical.
@return | [
"get",
"an",
"asset",
"using",
"ACCESS_STREAMING",
"mode",
".",
"This",
"provides",
"access",
"to",
"files",
"that",
"have",
"been",
"bundled",
"with",
"an",
"application",
"as",
"assets",
"--",
"that",
"is",
"files",
"placed",
"in",
"to",
"the",
"assets",
... | train | https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/core/src/main/java/com/mcxiaoke/next/utils/IOUtils.java#L1062-L1075 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlSerialMethodWriter.java | HtmlSerialMethodWriter.getSerializableMethods | public Content getSerializableMethods(String heading, Content serializableMethodContent) {
Content headingContent = new StringContent(heading);
Content serialHeading = HtmlTree.HEADING(HtmlConstants.SERIALIZED_MEMBER_HEADING,
headingContent);
Content li = HtmlTree.LI(HtmlStyle.blockList, serialHeading);
li.addContent(serializableMethodContent);
return li;
} | java | public Content getSerializableMethods(String heading, Content serializableMethodContent) {
Content headingContent = new StringContent(heading);
Content serialHeading = HtmlTree.HEADING(HtmlConstants.SERIALIZED_MEMBER_HEADING,
headingContent);
Content li = HtmlTree.LI(HtmlStyle.blockList, serialHeading);
li.addContent(serializableMethodContent);
return li;
} | [
"public",
"Content",
"getSerializableMethods",
"(",
"String",
"heading",
",",
"Content",
"serializableMethodContent",
")",
"{",
"Content",
"headingContent",
"=",
"new",
"StringContent",
"(",
"heading",
")",
";",
"Content",
"serialHeading",
"=",
"HtmlTree",
".",
"HEA... | Add serializable methods.
@param heading the heading for the section
@param serializableMethodContent the tree to be added to the serializable methods
content tree
@return a content tree for the serializable methods content | [
"Add",
"serializable",
"methods",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlSerialMethodWriter.java#L96-L103 |
fcrepo3/fcrepo | fcrepo-installer/src/main/java/org/fcrepo/utilities/install/container/Tomcat.java | Tomcat.installFedoraContext | protected void installFedoraContext() throws InstallationFailedException {
File contextDir =
new File(getConf().getPath() + File.separator + "Catalina"
+ File.separator + "localhost");
contextDir.mkdirs();
try {
String content =
IOUtils.toString(this.getClass()
.getResourceAsStream("/webapp-context/context.xml"))
.replace("${fedora.home}",
getOptions().getValue(InstallOptions.FEDORA_HOME));
String name =
getOptions()
.getValue(InstallOptions.FEDORA_APP_SERVER_CONTEXT)
+ ".xml";
FileOutputStream out =
new FileOutputStream(new File(contextDir, name));
out.write(content.getBytes());
out.close();
} catch (Exception e) {
throw new InstallationFailedException(e.getMessage(), e);
}
} | java | protected void installFedoraContext() throws InstallationFailedException {
File contextDir =
new File(getConf().getPath() + File.separator + "Catalina"
+ File.separator + "localhost");
contextDir.mkdirs();
try {
String content =
IOUtils.toString(this.getClass()
.getResourceAsStream("/webapp-context/context.xml"))
.replace("${fedora.home}",
getOptions().getValue(InstallOptions.FEDORA_HOME));
String name =
getOptions()
.getValue(InstallOptions.FEDORA_APP_SERVER_CONTEXT)
+ ".xml";
FileOutputStream out =
new FileOutputStream(new File(contextDir, name));
out.write(content.getBytes());
out.close();
} catch (Exception e) {
throw new InstallationFailedException(e.getMessage(), e);
}
} | [
"protected",
"void",
"installFedoraContext",
"(",
")",
"throws",
"InstallationFailedException",
"{",
"File",
"contextDir",
"=",
"new",
"File",
"(",
"getConf",
"(",
")",
".",
"getPath",
"(",
")",
"+",
"File",
".",
"separator",
"+",
"\"Catalina\"",
"+",
"File",
... | Creates a Tomcat context for Fedora in
$CATALINA_HOME/conf/Catalina/localhost which sets the fedora.home system
property to the installer-provided value. | [
"Creates",
"a",
"Tomcat",
"context",
"for",
"Fedora",
"in",
"$CATALINA_HOME",
"/",
"conf",
"/",
"Catalina",
"/",
"localhost",
"which",
"sets",
"the",
"fedora",
".",
"home",
"system",
"property",
"to",
"the",
"installer",
"-",
"provided",
"value",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-installer/src/main/java/org/fcrepo/utilities/install/container/Tomcat.java#L69-L96 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/DocPath.java | DocPath.forName | public static DocPath forName(Utils utils, TypeElement typeElement) {
return (typeElement == null) ? empty : new DocPath(utils.getSimpleName(typeElement) + ".html");
} | java | public static DocPath forName(Utils utils, TypeElement typeElement) {
return (typeElement == null) ? empty : new DocPath(utils.getSimpleName(typeElement) + ".html");
} | [
"public",
"static",
"DocPath",
"forName",
"(",
"Utils",
"utils",
",",
"TypeElement",
"typeElement",
")",
"{",
"return",
"(",
"typeElement",
"==",
"null",
")",
"?",
"empty",
":",
"new",
"DocPath",
"(",
"utils",
".",
"getSimpleName",
"(",
"typeElement",
")",
... | Return the path for the simple name of the class.
For example, if the class is java.lang.Object,
the path is Object.html. | [
"Return",
"the",
"path",
"for",
"the",
"simple",
"name",
"of",
"the",
"class",
".",
"For",
"example",
"if",
"the",
"class",
"is",
"java",
".",
"lang",
".",
"Object",
"the",
"path",
"is",
"Object",
".",
"html",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/DocPath.java#L72-L74 |
prestodb/presto | presto-main/src/main/java/com/facebook/presto/sql/planner/ExpressionDomainTranslator.java | ExpressionDomainTranslator.fromPredicate | public static ExtractionResult fromPredicate(
Metadata metadata,
Session session,
Expression predicate,
TypeProvider types)
{
return new Visitor(metadata, session, types).process(predicate, false);
} | java | public static ExtractionResult fromPredicate(
Metadata metadata,
Session session,
Expression predicate,
TypeProvider types)
{
return new Visitor(metadata, session, types).process(predicate, false);
} | [
"public",
"static",
"ExtractionResult",
"fromPredicate",
"(",
"Metadata",
"metadata",
",",
"Session",
"session",
",",
"Expression",
"predicate",
",",
"TypeProvider",
"types",
")",
"{",
"return",
"new",
"Visitor",
"(",
"metadata",
",",
"session",
",",
"types",
")... | Convert an Expression predicate into an ExtractionResult consisting of:
1) A successfully extracted TupleDomain
2) An Expression fragment which represents the part of the original Expression that will need to be re-evaluated
after filtering with the TupleDomain. | [
"Convert",
"an",
"Expression",
"predicate",
"into",
"an",
"ExtractionResult",
"consisting",
"of",
":",
"1",
")",
"A",
"successfully",
"extracted",
"TupleDomain",
"2",
")",
"An",
"Expression",
"fragment",
"which",
"represents",
"the",
"part",
"of",
"the",
"origin... | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/sql/planner/ExpressionDomainTranslator.java#L277-L284 |
atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/impl/RaftServiceManager.java | RaftServiceManager.snapshotService | private void snapshotService(SnapshotWriter writer, RaftServiceContext service) {
writer.writeLong(service.serviceId().id());
writer.writeString(service.serviceType().name());
writer.writeString(service.serviceName());
byte[] config = Serializer.using(service.serviceType().namespace()).encode(service.serviceConfig());
writer.writeInt(config.length).writeBytes(config);
try {
service.takeSnapshot(writer);
} catch (Exception e) {
logger.error("Failed to take snapshot of service {}", service.serviceId(), e);
}
} | java | private void snapshotService(SnapshotWriter writer, RaftServiceContext service) {
writer.writeLong(service.serviceId().id());
writer.writeString(service.serviceType().name());
writer.writeString(service.serviceName());
byte[] config = Serializer.using(service.serviceType().namespace()).encode(service.serviceConfig());
writer.writeInt(config.length).writeBytes(config);
try {
service.takeSnapshot(writer);
} catch (Exception e) {
logger.error("Failed to take snapshot of service {}", service.serviceId(), e);
}
} | [
"private",
"void",
"snapshotService",
"(",
"SnapshotWriter",
"writer",
",",
"RaftServiceContext",
"service",
")",
"{",
"writer",
".",
"writeLong",
"(",
"service",
".",
"serviceId",
"(",
")",
".",
"id",
"(",
")",
")",
";",
"writer",
".",
"writeString",
"(",
... | Takes a snapshot of the given service.
@param writer the snapshot writer
@param service the service to snapshot | [
"Takes",
"a",
"snapshot",
"of",
"the",
"given",
"service",
"."
] | train | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/impl/RaftServiceManager.java#L476-L487 |
overturetool/overture | ide/debug/src/main/java/org/overture/ide/debug/core/launching/VdmLaunchConfigurationDelegate.java | VdmLaunchConfigurationDelegate.abort | private static void abort(String message, Throwable e) throws CoreException
{
throw new CoreException((IStatus) new Status(IStatus.ERROR, IDebugConstants.PLUGIN_ID, 0, message, e));
} | java | private static void abort(String message, Throwable e) throws CoreException
{
throw new CoreException((IStatus) new Status(IStatus.ERROR, IDebugConstants.PLUGIN_ID, 0, message, e));
} | [
"private",
"static",
"void",
"abort",
"(",
"String",
"message",
",",
"Throwable",
"e",
")",
"throws",
"CoreException",
"{",
"throw",
"new",
"CoreException",
"(",
"(",
"IStatus",
")",
"new",
"Status",
"(",
"IStatus",
".",
"ERROR",
",",
"IDebugConstants",
".",... | Throws an exception with a new status containing the given message and optional exception.
@param message
error message
@param e
underlying exception
@throws CoreException | [
"Throws",
"an",
"exception",
"with",
"a",
"new",
"status",
"containing",
"the",
"given",
"message",
"and",
"optional",
"exception",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/core/launching/VdmLaunchConfigurationDelegate.java#L621-L624 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/context/RequestViewContext.java | RequestViewContext.refreshRequestViewContext | public void refreshRequestViewContext(FacesContext facesContext, UIViewRoot root)
{
for (Map.Entry<String, UIComponent> entry : root.getFacets().entrySet())
{
UIComponent facet = entry.getValue();
if (facet.getId() != null && facet.getId().startsWith("javax_faces_location_"))
{
try
{
facesContext.getAttributes().put(SKIP_ITERATION_HINT, Boolean.TRUE);
VisitContext visitContext = VisitContext.createVisitContext(facesContext, null, VISIT_HINTS);
facet.visitTree(visitContext, new RefreshViewContext());
}
finally
{
// We must remove hint in finally, because an exception can break this phase,
// but lifecycle can continue, if custom exception handler swallows the exception
facesContext.getAttributes().remove(SKIP_ITERATION_HINT);
}
}
}
} | java | public void refreshRequestViewContext(FacesContext facesContext, UIViewRoot root)
{
for (Map.Entry<String, UIComponent> entry : root.getFacets().entrySet())
{
UIComponent facet = entry.getValue();
if (facet.getId() != null && facet.getId().startsWith("javax_faces_location_"))
{
try
{
facesContext.getAttributes().put(SKIP_ITERATION_HINT, Boolean.TRUE);
VisitContext visitContext = VisitContext.createVisitContext(facesContext, null, VISIT_HINTS);
facet.visitTree(visitContext, new RefreshViewContext());
}
finally
{
// We must remove hint in finally, because an exception can break this phase,
// but lifecycle can continue, if custom exception handler swallows the exception
facesContext.getAttributes().remove(SKIP_ITERATION_HINT);
}
}
}
} | [
"public",
"void",
"refreshRequestViewContext",
"(",
"FacesContext",
"facesContext",
",",
"UIViewRoot",
"root",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"UIComponent",
">",
"entry",
":",
"root",
".",
"getFacets",
"(",
")",
".",
"entrySet... | Scans UIViewRoot facets with added component resources by the effect of
@ResourceDependency annotation, and register the associated inspected classes
so new component resources will not be added to the component tree again and again.
@param facesContext
@param root | [
"Scans",
"UIViewRoot",
"facets",
"with",
"added",
"component",
"resources",
"by",
"the",
"effect",
"of",
"@ResourceDependency",
"annotation",
"and",
"register",
"the",
"associated",
"inspected",
"classes",
"so",
"new",
"component",
"resources",
"will",
"not",
"be",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/context/RequestViewContext.java#L189-L211 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java | Resolve.resolveImplicitThis | Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
return resolveImplicitThis(pos, env, t, false);
} | java | Type resolveImplicitThis(DiagnosticPosition pos, Env<AttrContext> env, Type t) {
return resolveImplicitThis(pos, env, t, false);
} | [
"Type",
"resolveImplicitThis",
"(",
"DiagnosticPosition",
"pos",
",",
"Env",
"<",
"AttrContext",
">",
"env",
",",
"Type",
"t",
")",
"{",
"return",
"resolveImplicitThis",
"(",
"pos",
",",
"env",
",",
"t",
",",
"false",
")",
";",
"}"
] | Resolve an appropriate implicit this instance for t's container.
JLS 8.8.5.1 and 15.9.2 | [
"Resolve",
"an",
"appropriate",
"implicit",
"this",
"instance",
"for",
"t",
"s",
"container",
".",
"JLS",
"8",
".",
"8",
".",
"5",
".",
"1",
"and",
"15",
".",
"9",
".",
"2"
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java#L3626-L3628 |
gitblit/fathom | fathom-x509/src/main/java/fathom/x509/X509Utils.java | X509Utils.newCertificateAuthority | public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile, X509Log x509log) {
try {
KeyPair caPair = newKeyPair();
ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPair.getPrivate());
// clone metadata
X509Metadata caMetadata = metadata.clone(CA_CN, metadata.password);
X500Name issuerDN = buildDistinguishedName(caMetadata);
// Generate self-signed certificate
X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(
issuerDN,
BigInteger.valueOf(System.currentTimeMillis()),
caMetadata.notBefore,
caMetadata.notAfter,
issuerDN,
caPair.getPublic());
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
caBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(caPair.getPublic()));
caBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caPair.getPublic()));
caBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));
caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC);
X509Certificate cert = converter.getCertificate(caBuilder.build(caSigner));
// confirm the validity of the CA certificate
cert.checkValidity(new Date());
cert.verify(cert.getPublicKey());
// Delete existing keystore
if (storeFile.exists()) {
storeFile.delete();
}
// Save private key and certificate to new keystore
KeyStore store = openKeyStore(storeFile, caMetadata.password);
store.setKeyEntry(CA_ALIAS, caPair.getPrivate(), caMetadata.password.toCharArray(),
new Certificate[]{cert});
saveKeyStore(storeFile, store, caMetadata.password);
x509log.log(MessageFormat.format("New CA certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getIssuerDN().getName()));
// update serial number in metadata object
caMetadata.serialNumber = cert.getSerialNumber().toString();
return cert;
} catch (Throwable t) {
throw new RuntimeException("Failed to generate Fathom CA certificate!", t);
}
} | java | public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile, X509Log x509log) {
try {
KeyPair caPair = newKeyPair();
ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPair.getPrivate());
// clone metadata
X509Metadata caMetadata = metadata.clone(CA_CN, metadata.password);
X500Name issuerDN = buildDistinguishedName(caMetadata);
// Generate self-signed certificate
X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(
issuerDN,
BigInteger.valueOf(System.currentTimeMillis()),
caMetadata.notBefore,
caMetadata.notAfter,
issuerDN,
caPair.getPublic());
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
caBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(caPair.getPublic()));
caBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caPair.getPublic()));
caBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));
caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC);
X509Certificate cert = converter.getCertificate(caBuilder.build(caSigner));
// confirm the validity of the CA certificate
cert.checkValidity(new Date());
cert.verify(cert.getPublicKey());
// Delete existing keystore
if (storeFile.exists()) {
storeFile.delete();
}
// Save private key and certificate to new keystore
KeyStore store = openKeyStore(storeFile, caMetadata.password);
store.setKeyEntry(CA_ALIAS, caPair.getPrivate(), caMetadata.password.toCharArray(),
new Certificate[]{cert});
saveKeyStore(storeFile, store, caMetadata.password);
x509log.log(MessageFormat.format("New CA certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getIssuerDN().getName()));
// update serial number in metadata object
caMetadata.serialNumber = cert.getSerialNumber().toString();
return cert;
} catch (Throwable t) {
throw new RuntimeException("Failed to generate Fathom CA certificate!", t);
}
} | [
"public",
"static",
"X509Certificate",
"newCertificateAuthority",
"(",
"X509Metadata",
"metadata",
",",
"File",
"storeFile",
",",
"X509Log",
"x509log",
")",
"{",
"try",
"{",
"KeyPair",
"caPair",
"=",
"newKeyPair",
"(",
")",
";",
"ContentSigner",
"caSigner",
"=",
... | Creates a new certificate authority PKCS#12 store. This function will
destroy any existing CA store.
@param metadata
@param storeFile
@param x509log
@return | [
"Creates",
"a",
"new",
"certificate",
"authority",
"PKCS#12",
"store",
".",
"This",
"function",
"will",
"destroy",
"any",
"existing",
"CA",
"store",
"."
] | train | https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-x509/src/main/java/fathom/x509/X509Utils.java#L606-L658 |
VoltDB/voltdb | src/frontend/org/voltdb/jdbc/JDBC4ExecutionFuture.java | JDBC4ExecutionFuture.get | @Override
public ClientResponse get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
if (!this.latch.await(timeout, unit)) {
this.status.compareAndSet(STATUS_RUNNING, STATUS_TIMEOUT);
throw new TimeoutException();
}
if (isCancelled()) {
throw new CancellationException();
} else if (this.response.getStatus() != ClientResponse.SUCCESS) {
this.status.compareAndSet(STATUS_RUNNING, STATUS_FAILURE);
throw new ExecutionException(new Exception(response.getStatusString()));
} else {
this.status.compareAndSet(STATUS_RUNNING, STATUS_SUCCESS);
return this.response;
}
} | java | @Override
public ClientResponse get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
if (!this.latch.await(timeout, unit)) {
this.status.compareAndSet(STATUS_RUNNING, STATUS_TIMEOUT);
throw new TimeoutException();
}
if (isCancelled()) {
throw new CancellationException();
} else if (this.response.getStatus() != ClientResponse.SUCCESS) {
this.status.compareAndSet(STATUS_RUNNING, STATUS_FAILURE);
throw new ExecutionException(new Exception(response.getStatusString()));
} else {
this.status.compareAndSet(STATUS_RUNNING, STATUS_SUCCESS);
return this.response;
}
} | [
"@",
"Override",
"public",
"ClientResponse",
"get",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"throws",
"InterruptedException",
",",
"ExecutionException",
",",
"TimeoutException",
"{",
"if",
"(",
"!",
"this",
".",
"latch",
".",
"await",
"(",
"timeo... | Waits if necessary for at most the given time for the computation to complete, and then
retrieves its result, if available.
@param timeout
the maximum time to wait.
@param unit
the time unit of the timeout argument .
@return the computed result.
@throws CancellationException
if the computation was cancelled.
@throws ExecutionException
if the computation threw an exception.
@throws InterruptedException
if the current thread was interrupted while waiting.
@throws TimeoutException
if the wait timed out | [
"Waits",
"if",
"necessary",
"for",
"at",
"most",
"the",
"given",
"time",
"for",
"the",
"computation",
"to",
"complete",
"and",
"then",
"retrieves",
"its",
"result",
"if",
"available",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4ExecutionFuture.java#L124-L140 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/ocr/OcrClient.java | OcrClient.idcardRecognition | public IdcardRecognitionResponse idcardRecognition(String image, String side, Boolean direction) {
IdcardRecognitionRequest request = new IdcardRecognitionRequest().withImage(image)
.withSide(side).withDirection(direction);
return idcardRecognition(request);
} | java | public IdcardRecognitionResponse idcardRecognition(String image, String side, Boolean direction) {
IdcardRecognitionRequest request = new IdcardRecognitionRequest().withImage(image)
.withSide(side).withDirection(direction);
return idcardRecognition(request);
} | [
"public",
"IdcardRecognitionResponse",
"idcardRecognition",
"(",
"String",
"image",
",",
"String",
"side",
",",
"Boolean",
"direction",
")",
"{",
"IdcardRecognitionRequest",
"request",
"=",
"new",
"IdcardRecognitionRequest",
"(",
")",
".",
"withImage",
"(",
"image",
... | Gets the idcard recognition properties of specific image resource.
<p>
The caller <i>must</i> authenticate with a valid BCE Access Key / Private Key pair.
@param image The image data which needs to be base64
@param side The side of idcard image. (front/back)
@param direction Decide if the image has been rotated (true/false)
@return The idcard recognition properties of the image resource | [
"Gets",
"the",
"idcard",
"recognition",
"properties",
"of",
"specific",
"image",
"resource",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/ocr/OcrClient.java#L139-L143 |
jcuda/jcuda | JCudaJava/src/main/java/jcuda/runtime/JCuda.java | JCuda.cudaMallocPitch | public static int cudaMallocPitch(Pointer devPtr, long pitch[], long width, long height)
{
return checkResult(cudaMallocPitchNative(devPtr, pitch, width, height));
} | java | public static int cudaMallocPitch(Pointer devPtr, long pitch[], long width, long height)
{
return checkResult(cudaMallocPitchNative(devPtr, pitch, width, height));
} | [
"public",
"static",
"int",
"cudaMallocPitch",
"(",
"Pointer",
"devPtr",
",",
"long",
"pitch",
"[",
"]",
",",
"long",
"width",
",",
"long",
"height",
")",
"{",
"return",
"checkResult",
"(",
"cudaMallocPitchNative",
"(",
"devPtr",
",",
"pitch",
",",
"width",
... | Allocates pitched memory on the device.
<pre>
cudaError_t cudaMallocPitch (
void** devPtr,
size_t* pitch,
size_t width,
size_t height )
</pre>
<div>
<p>Allocates pitched memory on the device.
Allocates at least <tt>width</tt> (in bytes) * <tt>height</tt> bytes
of linear memory on the device and returns in <tt>*devPtr</tt> a
pointer to the allocated memory. The function may pad the allocation
to ensure that corresponding pointers in any given
row will continue to meet the alignment
requirements for coalescing as the address is updated from row to row.
The pitch returned
in <tt>*pitch</tt> by cudaMallocPitch()
is the width in bytes of the allocation. The intended usage of <tt>pitch</tt> is as a separate parameter of the allocation, used to
compute addresses within the 2D array. Given the row and column of
an array element of type <tt>T</tt>,
the address is computed as:
<pre> T* pElement = (T*)((char*)BaseAddress
+ Row * pitch) + Column;</pre>
</p>
<p>For allocations of 2D arrays, it is
recommended that programmers consider performing pitch allocations
using cudaMallocPitch(). Due to pitch alignment restrictions in the
hardware, this is especially true if the application will be performing
2D memory
copies between different regions of
device memory (whether linear memory or CUDA arrays).
</p>
<div>
<span>Note:</span>
<p>Note that this
function may also return error codes from previous, asynchronous
launches.
</p>
</div>
</p>
</div>
@param devPtr Pointer to allocated pitched device memory
@param pitch Pitch for allocation
@param width Requested pitched allocation width (in bytes)
@param height Requested pitched allocation height
@return cudaSuccess, cudaErrorMemoryAllocation
@see JCuda#cudaMalloc
@see JCuda#cudaFree
@see JCuda#cudaMallocArray
@see JCuda#cudaFreeArray
@see JCuda#cudaMallocHost
@see JCuda#cudaFreeHost
@see JCuda#cudaMalloc3D
@see JCuda#cudaMalloc3DArray
@see JCuda#cudaHostAlloc | [
"Allocates",
"pitched",
"memory",
"on",
"the",
"device",
"."
] | train | https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/runtime/JCuda.java#L4187-L4190 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2017_03_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_03_01/implementation/RegistriesInner.java | RegistriesInner.listCredentialsAsync | public Observable<RegistryListCredentialsResultInner> listCredentialsAsync(String resourceGroupName, String registryName) {
return listCredentialsWithServiceResponseAsync(resourceGroupName, registryName).map(new Func1<ServiceResponse<RegistryListCredentialsResultInner>, RegistryListCredentialsResultInner>() {
@Override
public RegistryListCredentialsResultInner call(ServiceResponse<RegistryListCredentialsResultInner> response) {
return response.body();
}
});
} | java | public Observable<RegistryListCredentialsResultInner> listCredentialsAsync(String resourceGroupName, String registryName) {
return listCredentialsWithServiceResponseAsync(resourceGroupName, registryName).map(new Func1<ServiceResponse<RegistryListCredentialsResultInner>, RegistryListCredentialsResultInner>() {
@Override
public RegistryListCredentialsResultInner call(ServiceResponse<RegistryListCredentialsResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RegistryListCredentialsResultInner",
">",
"listCredentialsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
")",
"{",
"return",
"listCredentialsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"registryName",
")"... | Lists the login credentials for the specified container registry.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RegistryListCredentialsResultInner object | [
"Lists",
"the",
"login",
"credentials",
"for",
"the",
"specified",
"container",
"registry",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2017_03_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_03_01/implementation/RegistriesInner.java#L900-L907 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShaderData.java | GVRShaderData.setFloatArray | public void setFloatArray(String key, float val[])
{
checkKeyIsUniform(key);
NativeShaderData.setFloatVec(getNative(), key, val, val.length);
} | java | public void setFloatArray(String key, float val[])
{
checkKeyIsUniform(key);
NativeShaderData.setFloatVec(getNative(), key, val, val.length);
} | [
"public",
"void",
"setFloatArray",
"(",
"String",
"key",
",",
"float",
"val",
"[",
"]",
")",
"{",
"checkKeyIsUniform",
"(",
"key",
")",
";",
"NativeShaderData",
".",
"setFloatVec",
"(",
"getNative",
"(",
")",
",",
"key",
",",
"val",
",",
"val",
".",
"l... | Set the value for a floating point vector uniform.
<p>
@param key name of uniform to set.
@param val floating point array with new data. The size of the array must be
at least as large as the uniform being updated.
@throws IllegalArgumentException if key is not in uniform descriptor or array is wrong length.
@see #getFloatVec(String) | [
"Set",
"the",
"value",
"for",
"a",
"floating",
"point",
"vector",
"uniform",
".",
"<p",
">"
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShaderData.java#L418-L422 |
dadoonet/elasticsearch-beyonder | src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java | TemplateElasticsearchUpdater.isTemplateExist | public static boolean isTemplateExist(RestClient client, String template) throws IOException {
Response response = client.performRequest(new Request("HEAD", "/_template/" + template));
return response.getStatusLine().getStatusCode() == 200;
} | java | public static boolean isTemplateExist(RestClient client, String template) throws IOException {
Response response = client.performRequest(new Request("HEAD", "/_template/" + template));
return response.getStatusLine().getStatusCode() == 200;
} | [
"public",
"static",
"boolean",
"isTemplateExist",
"(",
"RestClient",
"client",
",",
"String",
"template",
")",
"throws",
"IOException",
"{",
"Response",
"response",
"=",
"client",
".",
"performRequest",
"(",
"new",
"Request",
"(",
"\"HEAD\"",
",",
"\"/_template/\"... | Check if a template exists
@param client Elasticsearch client
@param template template name
@return true if the template exists
@throws IOException if something goes wrong | [
"Check",
"if",
"a",
"template",
"exists"
] | train | https://github.com/dadoonet/elasticsearch-beyonder/blob/275bf63432b97169a90a266e983143cca9ad7629/src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java#L230-L233 |
uniform-java/uniform | src/main/java/net/uniform/api/html/SimpleHTMLTag.java | SimpleHTMLTag.setProperty | public SimpleHTMLTag setProperty(String key, String value) {
key = UniformUtils.checkPropertyNameAndLowerCase(key);
if (properties == null) {
properties = new HashMap<>();
}
properties.put(key, value);
return this;
} | java | public SimpleHTMLTag setProperty(String key, String value) {
key = UniformUtils.checkPropertyNameAndLowerCase(key);
if (properties == null) {
properties = new HashMap<>();
}
properties.put(key, value);
return this;
} | [
"public",
"SimpleHTMLTag",
"setProperty",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"key",
"=",
"UniformUtils",
".",
"checkPropertyNameAndLowerCase",
"(",
"key",
")",
";",
"if",
"(",
"properties",
"==",
"null",
")",
"{",
"properties",
"=",
"new... | Sets a property of the tag by key.
@param key Property key
@param value Property value
@return This tag | [
"Sets",
"a",
"property",
"of",
"the",
"tag",
"by",
"key",
"."
] | train | https://github.com/uniform-java/uniform/blob/0b84f0db562253165bc06c69f631e464dca0cb48/src/main/java/net/uniform/api/html/SimpleHTMLTag.java#L192-L202 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java | ChallengeCache.addCachedChallenge | public void addCachedChallenge(HttpUrl url, Map<String, String> challenge) {
if (url == null || challenge == null) {
return;
}
String authority = getAuthority(url);
authority = authority.toLowerCase(Locale.ENGLISH);
cachedChallenges.put(authority, challenge);
} | java | public void addCachedChallenge(HttpUrl url, Map<String, String> challenge) {
if (url == null || challenge == null) {
return;
}
String authority = getAuthority(url);
authority = authority.toLowerCase(Locale.ENGLISH);
cachedChallenges.put(authority, challenge);
} | [
"public",
"void",
"addCachedChallenge",
"(",
"HttpUrl",
"url",
",",
"Map",
"<",
"String",
",",
"String",
">",
"challenge",
")",
"{",
"if",
"(",
"url",
"==",
"null",
"||",
"challenge",
"==",
"null",
")",
"{",
"return",
";",
"}",
"String",
"authority",
"... | Uses authority to cache challenge.
@param url
the url that is used as a cache key.
@param challenge
the challenge to cache. | [
"Uses",
"authority",
"to",
"cache",
"challenge",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java#L43-L50 |
Mthwate/DatLib | src/main/java/com/mthwate/datlib/HashUtils.java | HashUtils.md5Hex | public static String md5Hex(String data, Charset charset) throws NoSuchAlgorithmException {
return md5Hex(data.getBytes(charset));
} | java | public static String md5Hex(String data, Charset charset) throws NoSuchAlgorithmException {
return md5Hex(data.getBytes(charset));
} | [
"public",
"static",
"String",
"md5Hex",
"(",
"String",
"data",
",",
"Charset",
"charset",
")",
"throws",
"NoSuchAlgorithmException",
"{",
"return",
"md5Hex",
"(",
"data",
".",
"getBytes",
"(",
"charset",
")",
")",
";",
"}"
] | Hashes a string using the MD5 algorithm. Returns a hexadecimal result.
@since 1.1
@param data the string to hash
@param charset the charset of the string
@return the hexadecimal MD5 hash of the string
@throws NoSuchAlgorithmException the algorithm is not supported by existing providers | [
"Hashes",
"a",
"string",
"using",
"the",
"MD5",
"algorithm",
".",
"Returns",
"a",
"hexadecimal",
"result",
"."
] | train | https://github.com/Mthwate/DatLib/blob/f0b3a9f9cf6fdc773d4f86234ebd95986c9b6077/src/main/java/com/mthwate/datlib/HashUtils.java#L212-L214 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/BooleanIndexing.java | BooleanIndexing.lastIndex | public static INDArray lastIndex(INDArray array, Condition condition) {
if (!(condition instanceof BaseCondition))
throw new UnsupportedOperationException("Only static Conditions are supported");
LastIndex idx = new LastIndex(array, condition);
Nd4j.getExecutioner().exec(idx);
return Nd4j.scalar(DataType.LONG, idx.getFinalResult().longValue());
} | java | public static INDArray lastIndex(INDArray array, Condition condition) {
if (!(condition instanceof BaseCondition))
throw new UnsupportedOperationException("Only static Conditions are supported");
LastIndex idx = new LastIndex(array, condition);
Nd4j.getExecutioner().exec(idx);
return Nd4j.scalar(DataType.LONG, idx.getFinalResult().longValue());
} | [
"public",
"static",
"INDArray",
"lastIndex",
"(",
"INDArray",
"array",
",",
"Condition",
"condition",
")",
"{",
"if",
"(",
"!",
"(",
"condition",
"instanceof",
"BaseCondition",
")",
")",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Only static Conditions... | This method returns last index matching given condition
PLEASE NOTE: This method will return -1 value if condition wasn't met
@param array
@param condition
@return | [
"This",
"method",
"returns",
"last",
"index",
"matching",
"given",
"condition"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/BooleanIndexing.java#L315-L322 |
samtingleff/jchronic | src/main/java/com/mdimension/jchronic/handlers/Handler.java | Handler.findWithin | public static Span findWithin(List<Repeater<?>> tags, Span span, Pointer.PointerType pointer, Options options) {
if (options.isDebug()) {
System.out.println("Chronic.findWithin: " + tags + " in " + span);
}
if (tags.isEmpty()) {
return span;
}
Repeater<?> head = tags.get(0);
List<Repeater<?>> rest = (tags.size() > 1) ? tags.subList(1, tags.size()) : new LinkedList<Repeater<?>>();
head.setStart((pointer == Pointer.PointerType.FUTURE) ? span.getBeginCalendar() : span.getEndCalendar());
Span h = head.thisSpan(PointerType.NONE);
if (span.contains(h.getBegin()) || span.contains(h.getEnd())) {
return findWithin(rest, h, pointer, options);
}
return null;
} | java | public static Span findWithin(List<Repeater<?>> tags, Span span, Pointer.PointerType pointer, Options options) {
if (options.isDebug()) {
System.out.println("Chronic.findWithin: " + tags + " in " + span);
}
if (tags.isEmpty()) {
return span;
}
Repeater<?> head = tags.get(0);
List<Repeater<?>> rest = (tags.size() > 1) ? tags.subList(1, tags.size()) : new LinkedList<Repeater<?>>();
head.setStart((pointer == Pointer.PointerType.FUTURE) ? span.getBeginCalendar() : span.getEndCalendar());
Span h = head.thisSpan(PointerType.NONE);
if (span.contains(h.getBegin()) || span.contains(h.getEnd())) {
return findWithin(rest, h, pointer, options);
}
return null;
} | [
"public",
"static",
"Span",
"findWithin",
"(",
"List",
"<",
"Repeater",
"<",
"?",
">",
">",
"tags",
",",
"Span",
"span",
",",
"Pointer",
".",
"PointerType",
"pointer",
",",
"Options",
"options",
")",
"{",
"if",
"(",
"options",
".",
"isDebug",
"(",
")",... | Recursively finds repeaters within other repeaters.
Returns a Span representing the innermost time span
or nil if no repeater union could be found | [
"Recursively",
"finds",
"repeaters",
"within",
"other",
"repeaters",
".",
"Returns",
"a",
"Span",
"representing",
"the",
"innermost",
"time",
"span",
"or",
"nil",
"if",
"no",
"repeater",
"union",
"could",
"be",
"found"
] | train | https://github.com/samtingleff/jchronic/blob/b66bd2815eda3e79adefa2642f8ccf6b4b7586ce/src/main/java/com/mdimension/jchronic/handlers/Handler.java#L346-L362 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/NameNode.java | NameNode.initializeGenericKeys | public static void initializeGenericKeys(Configuration conf, String serviceKey) {
if ((serviceKey == null) || serviceKey.isEmpty()) {
return;
}
// adjust meta directory names by service key
adjustMetaDirectoryNames(conf, serviceKey);
DFSUtil.setGenericConf(conf, serviceKey, NAMESERVICE_SPECIFIC_KEYS);
} | java | public static void initializeGenericKeys(Configuration conf, String serviceKey) {
if ((serviceKey == null) || serviceKey.isEmpty()) {
return;
}
// adjust meta directory names by service key
adjustMetaDirectoryNames(conf, serviceKey);
DFSUtil.setGenericConf(conf, serviceKey, NAMESERVICE_SPECIFIC_KEYS);
} | [
"public",
"static",
"void",
"initializeGenericKeys",
"(",
"Configuration",
"conf",
",",
"String",
"serviceKey",
")",
"{",
"if",
"(",
"(",
"serviceKey",
"==",
"null",
")",
"||",
"serviceKey",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"// adjus... | In federation configuration is set for a set of
namenode and secondary namenode/backup/checkpointer, which are
grouped under a logical nameservice ID. The configuration keys specific
to them have suffix set to configured nameserviceId.
This method copies the value from specific key of format key.nameserviceId
to key, to set up the generic configuration. Once this is done, only
generic version of the configuration is read in rest of the code, for
backward compatibility and simpler code changes.
@param conf
Configuration object to lookup specific key and to set the value
to the key passed. Note the conf object is modified
@see DFSUtil#setGenericConf(Configuration, String, String...) | [
"In",
"federation",
"configuration",
"is",
"set",
"for",
"a",
"set",
"of",
"namenode",
"and",
"secondary",
"namenode",
"/",
"backup",
"/",
"checkpointer",
"which",
"are",
"grouped",
"under",
"a",
"logical",
"nameservice",
"ID",
".",
"The",
"configuration",
"ke... | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/NameNode.java#L554-L563 |
alkacon/opencms-core | src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java | CmsDefaultXmlContentHandler.addSearchField | @Deprecated
protected void addSearchField(CmsXmlContentDefinition contentDefinition, CmsSearchField field) {
addSearchField(contentDefinition, field, I_CmsXmlContentHandler.MappingType.ELEMENT);
} | java | @Deprecated
protected void addSearchField(CmsXmlContentDefinition contentDefinition, CmsSearchField field) {
addSearchField(contentDefinition, field, I_CmsXmlContentHandler.MappingType.ELEMENT);
} | [
"@",
"Deprecated",
"protected",
"void",
"addSearchField",
"(",
"CmsXmlContentDefinition",
"contentDefinition",
",",
"CmsSearchField",
"field",
")",
"{",
"addSearchField",
"(",
"contentDefinition",
",",
"field",
",",
"I_CmsXmlContentHandler",
".",
"MappingType",
".",
"EL... | Adds a Solr field for an element.<p>
@param contentDefinition the XML content definition this XML content handler belongs to
@param field the Solr field | [
"Adds",
"a",
"Solr",
"field",
"for",
"an",
"element",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L2058-L2062 |
jbundle/jbundle | main/screen/src/main/java/org/jbundle/main/user/screen/UserLoginScreen.java | UserLoginScreen.doServletCommand | public ScreenModel doServletCommand(ScreenModel screenParent)
{
ScreenModel screen = super.doServletCommand(screenParent); // Process params from previous screen
String strCommand = this.getProperty(DBParams.COMMAND);
BaseApplication application = (BaseApplication)this.getTask().getApplication();
String strDesc = application.getResources(ResourceConstants.MAIN_RESOURCE, true).getString(MenuConstants.LOGIN);
if (strDesc.equals(strCommand))
{
if (this.getTask().getStatusText(DBConstants.WARNING_MESSAGE) == null)
{ // Normal return = logged in, go to main menu.
this.free();
return null; // This will cause the main menu to display
}
}
strDesc = application.getResources(ResourceConstants.MAIN_RESOURCE, true).getString(UserEntryScreen.CREATE_NEW_USER);
if (strDesc.equals(strCommand))
{
screen.free();
screen = new UserEntryScreen(null, null, (BasePanel)screenParent, null, 0, null);
screen.setProperty(DBParams.SCREEN, UserEntryScreen.class.getName());
}
return screen;
} | java | public ScreenModel doServletCommand(ScreenModel screenParent)
{
ScreenModel screen = super.doServletCommand(screenParent); // Process params from previous screen
String strCommand = this.getProperty(DBParams.COMMAND);
BaseApplication application = (BaseApplication)this.getTask().getApplication();
String strDesc = application.getResources(ResourceConstants.MAIN_RESOURCE, true).getString(MenuConstants.LOGIN);
if (strDesc.equals(strCommand))
{
if (this.getTask().getStatusText(DBConstants.WARNING_MESSAGE) == null)
{ // Normal return = logged in, go to main menu.
this.free();
return null; // This will cause the main menu to display
}
}
strDesc = application.getResources(ResourceConstants.MAIN_RESOURCE, true).getString(UserEntryScreen.CREATE_NEW_USER);
if (strDesc.equals(strCommand))
{
screen.free();
screen = new UserEntryScreen(null, null, (BasePanel)screenParent, null, 0, null);
screen.setProperty(DBParams.SCREEN, UserEntryScreen.class.getName());
}
return screen;
} | [
"public",
"ScreenModel",
"doServletCommand",
"(",
"ScreenModel",
"screenParent",
")",
"{",
"ScreenModel",
"screen",
"=",
"super",
".",
"doServletCommand",
"(",
"screenParent",
")",
";",
"// Process params from previous screen",
"String",
"strCommand",
"=",
"this",
".",
... | Do the special HTML command.
This gives the screen a chance to change screens for special HTML commands.
You have a chance to change two things:
1. The information display line (this will display on the next screen... ie., submit was successful)
2. The error display line (if there was an error)
@return this or the new screen to display. | [
"Do",
"the",
"special",
"HTML",
"command",
".",
"This",
"gives",
"the",
"screen",
"a",
"chance",
"to",
"change",
"screens",
"for",
"special",
"HTML",
"commands",
".",
"You",
"have",
"a",
"chance",
"to",
"change",
"two",
"things",
":",
"1",
".",
"The",
... | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/main/screen/src/main/java/org/jbundle/main/user/screen/UserLoginScreen.java#L208-L231 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/RouteTablesInner.java | RouteTablesInner.beginUpdateTags | public RouteTableInner beginUpdateTags(String resourceGroupName, String routeTableName, Map<String, String> tags) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, routeTableName, tags).toBlocking().single().body();
} | java | public RouteTableInner beginUpdateTags(String resourceGroupName, String routeTableName, Map<String, String> tags) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, routeTableName, tags).toBlocking().single().body();
} | [
"public",
"RouteTableInner",
"beginUpdateTags",
"(",
"String",
"resourceGroupName",
",",
"String",
"routeTableName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"return",
"beginUpdateTagsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"r... | Updates a route table tags.
@param resourceGroupName The name of the resource group.
@param routeTableName The name of the route table.
@param tags Resource tags.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the RouteTableInner object if successful. | [
"Updates",
"a",
"route",
"table",
"tags",
"."
] | 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/RouteTablesInner.java#L835-L837 |
trellis-ldp/trellis | components/webdav/src/main/java/org/trellisldp/webdav/TrellisWebDAV.java | TrellisWebDAV.copyResource | @COPY
@Timed
public void copyResource(@Suspended final AsyncResponse response, @Context final Request request,
@Context final UriInfo uriInfo, @Context final HttpHeaders headers,
@Context final SecurityContext security) {
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security);
final Session session = getSession(req.getPrincipalName());
final IRI destination = getDestination(headers, getBaseUrl(req));
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
// Default is recursive copy as per RFC-4918
final Depth.DEPTH depth = getDepth(headers.getHeaderString("Depth"));
getParent(destination).thenCombine(services.getResourceService().get(destination), this::checkResources)
.thenCompose(parent -> services.getResourceService().touch(parent.getIdentifier()))
.thenCompose(future -> services.getResourceService().get(identifier))
.thenApply(this::checkResource)
.thenCompose(res -> copyTo(res, session, depth, destination, getBaseUrl(req)))
.thenApply(future -> status(NO_CONTENT).build())
.exceptionally(this::handleException).thenApply(response::resume);
} | java | @COPY
@Timed
public void copyResource(@Suspended final AsyncResponse response, @Context final Request request,
@Context final UriInfo uriInfo, @Context final HttpHeaders headers,
@Context final SecurityContext security) {
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security);
final Session session = getSession(req.getPrincipalName());
final IRI destination = getDestination(headers, getBaseUrl(req));
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
// Default is recursive copy as per RFC-4918
final Depth.DEPTH depth = getDepth(headers.getHeaderString("Depth"));
getParent(destination).thenCombine(services.getResourceService().get(destination), this::checkResources)
.thenCompose(parent -> services.getResourceService().touch(parent.getIdentifier()))
.thenCompose(future -> services.getResourceService().get(identifier))
.thenApply(this::checkResource)
.thenCompose(res -> copyTo(res, session, depth, destination, getBaseUrl(req)))
.thenApply(future -> status(NO_CONTENT).build())
.exceptionally(this::handleException).thenApply(response::resume);
} | [
"@",
"COPY",
"@",
"Timed",
"public",
"void",
"copyResource",
"(",
"@",
"Suspended",
"final",
"AsyncResponse",
"response",
",",
"@",
"Context",
"final",
"Request",
"request",
",",
"@",
"Context",
"final",
"UriInfo",
"uriInfo",
",",
"@",
"Context",
"final",
"H... | Copy a resource.
@param response the async response
@param request the request
@param uriInfo the URI info
@param headers the headers
@param security the security context | [
"Copy",
"a",
"resource",
"."
] | train | https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/webdav/src/main/java/org/trellisldp/webdav/TrellisWebDAV.java#L167-L185 |
buschmais/jqa-rdbms-plugin | src/main/java/com/buschmais/jqassistant/plugin/rdbms/impl/scanner/AbstractSchemaScannerPlugin.java | AbstractSchemaScannerPlugin.getColumnTypeDescriptor | private ColumnTypeDescriptor getColumnTypeDescriptor(ColumnDataType columnDataType, Map<String, ColumnTypeDescriptor> columnTypes, Store store) {
String databaseSpecificTypeName = columnDataType.getDatabaseSpecificTypeName();
ColumnTypeDescriptor columnTypeDescriptor = columnTypes.get(databaseSpecificTypeName);
if (columnTypeDescriptor == null) {
columnTypeDescriptor = store.find(ColumnTypeDescriptor.class, databaseSpecificTypeName);
if (columnTypeDescriptor == null) {
columnTypeDescriptor = store.create(ColumnTypeDescriptor.class);
columnTypeDescriptor.setDatabaseType(databaseSpecificTypeName);
columnTypeDescriptor.setAutoIncrementable(columnDataType.isAutoIncrementable());
columnTypeDescriptor.setCaseSensitive(columnDataType.isCaseSensitive());
columnTypeDescriptor.setPrecision(columnDataType.getPrecision());
columnTypeDescriptor.setMinimumScale(columnDataType.getMinimumScale());
columnTypeDescriptor.setMaximumScale(columnDataType.getMaximumScale());
columnTypeDescriptor.setFixedPrecisionScale(columnDataType.isFixedPrecisionScale());
columnTypeDescriptor.setNumericPrecisionRadix(columnDataType.getNumPrecisionRadix());
columnTypeDescriptor.setUnsigned(columnDataType.isUnsigned());
columnTypeDescriptor.setUserDefined(columnDataType.isUserDefined());
columnTypeDescriptor.setNullable(columnDataType.isNullable());
}
columnTypes.put(databaseSpecificTypeName, columnTypeDescriptor);
}
return columnTypeDescriptor;
} | java | private ColumnTypeDescriptor getColumnTypeDescriptor(ColumnDataType columnDataType, Map<String, ColumnTypeDescriptor> columnTypes, Store store) {
String databaseSpecificTypeName = columnDataType.getDatabaseSpecificTypeName();
ColumnTypeDescriptor columnTypeDescriptor = columnTypes.get(databaseSpecificTypeName);
if (columnTypeDescriptor == null) {
columnTypeDescriptor = store.find(ColumnTypeDescriptor.class, databaseSpecificTypeName);
if (columnTypeDescriptor == null) {
columnTypeDescriptor = store.create(ColumnTypeDescriptor.class);
columnTypeDescriptor.setDatabaseType(databaseSpecificTypeName);
columnTypeDescriptor.setAutoIncrementable(columnDataType.isAutoIncrementable());
columnTypeDescriptor.setCaseSensitive(columnDataType.isCaseSensitive());
columnTypeDescriptor.setPrecision(columnDataType.getPrecision());
columnTypeDescriptor.setMinimumScale(columnDataType.getMinimumScale());
columnTypeDescriptor.setMaximumScale(columnDataType.getMaximumScale());
columnTypeDescriptor.setFixedPrecisionScale(columnDataType.isFixedPrecisionScale());
columnTypeDescriptor.setNumericPrecisionRadix(columnDataType.getNumPrecisionRadix());
columnTypeDescriptor.setUnsigned(columnDataType.isUnsigned());
columnTypeDescriptor.setUserDefined(columnDataType.isUserDefined());
columnTypeDescriptor.setNullable(columnDataType.isNullable());
}
columnTypes.put(databaseSpecificTypeName, columnTypeDescriptor);
}
return columnTypeDescriptor;
} | [
"private",
"ColumnTypeDescriptor",
"getColumnTypeDescriptor",
"(",
"ColumnDataType",
"columnDataType",
",",
"Map",
"<",
"String",
",",
"ColumnTypeDescriptor",
">",
"columnTypes",
",",
"Store",
"store",
")",
"{",
"String",
"databaseSpecificTypeName",
"=",
"columnDataType",... | Return the column type descriptor for the given data type.
@param columnDataType The data type.
@param columnTypes The cached data types.
@param store The store.
@return The column type descriptor. | [
"Return",
"the",
"column",
"type",
"descriptor",
"for",
"the",
"given",
"data",
"type",
"."
] | train | https://github.com/buschmais/jqa-rdbms-plugin/blob/96c3919907deee00175cf5ab005867d76e01ba62/src/main/java/com/buschmais/jqassistant/plugin/rdbms/impl/scanner/AbstractSchemaScannerPlugin.java#L392-L414 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/GeometryCoordinateDimension.java | GeometryCoordinateDimension.convert | public static LinearRing convert(LineString lineString,int dimension) {
return gf.createLinearRing(convertSequence(lineString.getCoordinates(),dimension));
} | java | public static LinearRing convert(LineString lineString,int dimension) {
return gf.createLinearRing(convertSequence(lineString.getCoordinates(),dimension));
} | [
"public",
"static",
"LinearRing",
"convert",
"(",
"LineString",
"lineString",
",",
"int",
"dimension",
")",
"{",
"return",
"gf",
".",
"createLinearRing",
"(",
"convertSequence",
"(",
"lineString",
".",
"getCoordinates",
"(",
")",
",",
"dimension",
")",
")",
";... | Force the dimension of the LineString and update correctly the coordinate
dimension
@param lineString
@param dimension
@return | [
"Force",
"the",
"dimension",
"of",
"the",
"LineString",
"and",
"update",
"correctly",
"the",
"coordinate",
"dimension"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/GeometryCoordinateDimension.java#L143-L145 |
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/CmsContentEditorHandler.java | CmsContentEditorHandler.openDialog | public void openDialog(final CmsContainerPageElementPanel element, final boolean inline, boolean wasNew) {
if (!inline && element.hasEditHandler()) {
m_handler.m_controller.getEditOptions(
element.getId(),
false,
new I_CmsSimpleCallback<CmsDialogOptionsAndInfo>() {
public void execute(CmsDialogOptionsAndInfo editOptions) {
final I_CmsSimpleCallback<CmsUUID> editCallBack = new I_CmsSimpleCallback<CmsUUID>() {
public void execute(CmsUUID arg) {
String contentId = element.getId();
if (!element.getId().startsWith(arg.toString())) {
// the content structure ID has changed, the current element needs to be replaced after editing
m_replaceElement = element;
contentId = arg.toString();
}
internalOpenDialog(element, contentId, inline, wasNew);
}
};
if (editOptions == null) {
internalOpenDialog(element, element.getId(), inline, wasNew);
} else if (editOptions.getOptions().getOptions().size() == 1) {
m_handler.m_controller.prepareForEdit(
element.getId(),
editOptions.getOptions().getOptions().get(0).getValue(),
editCallBack);
} else {
CmsOptionDialog dialog = new CmsOptionDialog(
Messages.get().key(Messages.GUI_EDIT_HANDLER_SELECT_EDIT_OPTION_0),
editOptions.getOptions(),
editOptions.getInfo(),
new I_CmsSimpleCallback<String>() {
public void execute(String arg) {
m_handler.m_controller.prepareForEdit(element.getId(), arg, editCallBack);
}
});
dialog.addDialogClose(new Command() {
public void execute() {
cancelEdit();
}
});
dialog.center();
}
}
});
} else {
internalOpenDialog(element, element.getId(), inline, wasNew);
}
} | java | public void openDialog(final CmsContainerPageElementPanel element, final boolean inline, boolean wasNew) {
if (!inline && element.hasEditHandler()) {
m_handler.m_controller.getEditOptions(
element.getId(),
false,
new I_CmsSimpleCallback<CmsDialogOptionsAndInfo>() {
public void execute(CmsDialogOptionsAndInfo editOptions) {
final I_CmsSimpleCallback<CmsUUID> editCallBack = new I_CmsSimpleCallback<CmsUUID>() {
public void execute(CmsUUID arg) {
String contentId = element.getId();
if (!element.getId().startsWith(arg.toString())) {
// the content structure ID has changed, the current element needs to be replaced after editing
m_replaceElement = element;
contentId = arg.toString();
}
internalOpenDialog(element, contentId, inline, wasNew);
}
};
if (editOptions == null) {
internalOpenDialog(element, element.getId(), inline, wasNew);
} else if (editOptions.getOptions().getOptions().size() == 1) {
m_handler.m_controller.prepareForEdit(
element.getId(),
editOptions.getOptions().getOptions().get(0).getValue(),
editCallBack);
} else {
CmsOptionDialog dialog = new CmsOptionDialog(
Messages.get().key(Messages.GUI_EDIT_HANDLER_SELECT_EDIT_OPTION_0),
editOptions.getOptions(),
editOptions.getInfo(),
new I_CmsSimpleCallback<String>() {
public void execute(String arg) {
m_handler.m_controller.prepareForEdit(element.getId(), arg, editCallBack);
}
});
dialog.addDialogClose(new Command() {
public void execute() {
cancelEdit();
}
});
dialog.center();
}
}
});
} else {
internalOpenDialog(element, element.getId(), inline, wasNew);
}
} | [
"public",
"void",
"openDialog",
"(",
"final",
"CmsContainerPageElementPanel",
"element",
",",
"final",
"boolean",
"inline",
",",
"boolean",
"wasNew",
")",
"{",
"if",
"(",
"!",
"inline",
"&&",
"element",
".",
"hasEditHandler",
"(",
")",
")",
"{",
"m_handler",
... | Opens the XML content editor.<p>
@param element the container element widget
@param inline <code>true</code> to open the in-line editor for the given element if available
@param wasNew <code>true</code> in case this is a newly created element not previously edited | [
"Opens",
"the",
"XML",
"content",
"editor",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContentEditorHandler.java#L166-L222 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/UCharacter.java | UCharacter.getCodePoint | public static int getCodePoint(char lead, char trail)
{
if (Character.isSurrogatePair(lead, trail)) {
return Character.toCodePoint(lead, trail);
}
throw new IllegalArgumentException("Illegal surrogate characters");
} | java | public static int getCodePoint(char lead, char trail)
{
if (Character.isSurrogatePair(lead, trail)) {
return Character.toCodePoint(lead, trail);
}
throw new IllegalArgumentException("Illegal surrogate characters");
} | [
"public",
"static",
"int",
"getCodePoint",
"(",
"char",
"lead",
",",
"char",
"trail",
")",
"{",
"if",
"(",
"Character",
".",
"isSurrogatePair",
"(",
"lead",
",",
"trail",
")",
")",
"{",
"return",
"Character",
".",
"toCodePoint",
"(",
"lead",
",",
"trail"... | <strong>[icu]</strong> Returns a code point corresponding to the two surrogate code units.
@param lead the lead char
@param trail the trail char
@return code point if surrogate characters are valid.
@exception IllegalArgumentException thrown when the code units do
not form a valid code point | [
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Returns",
"a",
"code",
"point",
"corresponding",
"to",
"the",
"two",
"surrogate",
"code",
"units",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/UCharacter.java#L4247-L4253 |
ow2-chameleon/fuchsia | bases/knx/calimero/src/main/java/tuwien/auto/calimero/link/medium/RawFrameFactory.java | RawFrameFactory.createPL132 | public static RawFrame createPL132(byte[] data, int offset) throws KNXFormatException
{
if (data.length - offset == 2)
return new PL132Ack(data, offset);
return new PL132LData(data, offset);
} | java | public static RawFrame createPL132(byte[] data, int offset) throws KNXFormatException
{
if (data.length - offset == 2)
return new PL132Ack(data, offset);
return new PL132LData(data, offset);
} | [
"public",
"static",
"RawFrame",
"createPL132",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
")",
"throws",
"KNXFormatException",
"{",
"if",
"(",
"data",
".",
"length",
"-",
"offset",
"==",
"2",
")",
"return",
"new",
"PL132Ack",
"(",
"data",
",",
... | Creates a raw frame out of a byte array for the PL132 communication medium.
<p>
@param data byte array containing the PL132 raw frame structure
@param offset start offset of frame structure in <code>data</code>, 0 <=
offset < <code>data.length</code>
@return the created PL132 raw frame
@throws KNXFormatException on no valid frame structure | [
"Creates",
"a",
"raw",
"frame",
"out",
"of",
"a",
"byte",
"array",
"for",
"the",
"PL132",
"communication",
"medium",
".",
"<p",
">"
] | train | https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/bases/knx/calimero/src/main/java/tuwien/auto/calimero/link/medium/RawFrameFactory.java#L157-L162 |
alexa/alexa-skills-kit-sdk-for-java | ask-sdk-servlet-support/src/com/amazon/ask/servlet/verifiers/SkillRequestTimestampVerifier.java | SkillRequestTimestampVerifier.verify | public void verify(HttpServletRequest servletRequest, byte[] serializedRequestEnvelope, RequestEnvelope deserializedRequestEnvelope) {
if (deserializedRequestEnvelope == null) {
throw new SecurityException("Incoming request did not contain a request envelope");
}
Request request = deserializedRequestEnvelope.getRequest();
if (request == null || request.getTimestamp() == null) {
throw new SecurityException("Incoming request was null or did not contain a timestamp to evaluate");
}
long requestTimestamp = request.getTimestamp().toInstant().toEpochMilli();
long delta = Math.abs(System.currentTimeMillis() - requestTimestamp);
boolean withinTolerance = delta <= toleranceInMilliseconds;
if (!withinTolerance) {
throw new SecurityException(String.format("Request with id %s and timestamp %s failed timestamp validation" +
" with a delta of %s", request.getRequestId(), requestTimestamp, delta));
}
} | java | public void verify(HttpServletRequest servletRequest, byte[] serializedRequestEnvelope, RequestEnvelope deserializedRequestEnvelope) {
if (deserializedRequestEnvelope == null) {
throw new SecurityException("Incoming request did not contain a request envelope");
}
Request request = deserializedRequestEnvelope.getRequest();
if (request == null || request.getTimestamp() == null) {
throw new SecurityException("Incoming request was null or did not contain a timestamp to evaluate");
}
long requestTimestamp = request.getTimestamp().toInstant().toEpochMilli();
long delta = Math.abs(System.currentTimeMillis() - requestTimestamp);
boolean withinTolerance = delta <= toleranceInMilliseconds;
if (!withinTolerance) {
throw new SecurityException(String.format("Request with id %s and timestamp %s failed timestamp validation" +
" with a delta of %s", request.getRequestId(), requestTimestamp, delta));
}
} | [
"public",
"void",
"verify",
"(",
"HttpServletRequest",
"servletRequest",
",",
"byte",
"[",
"]",
"serializedRequestEnvelope",
",",
"RequestEnvelope",
"deserializedRequestEnvelope",
")",
"{",
"if",
"(",
"deserializedRequestEnvelope",
"==",
"null",
")",
"{",
"throw",
"ne... | Validates if the provided date is inclusively within the verifier tolerance, either in the
past or future, of the current system time. This method will throw a {@link SecurityException} if the
tolerance is not in the expected range, or if the request is null or does not contain a timestamp value.
{@inheritDoc} | [
"Validates",
"if",
"the",
"provided",
"date",
"is",
"inclusively",
"within",
"the",
"verifier",
"tolerance",
"either",
"in",
"the",
"past",
"or",
"future",
"of",
"the",
"current",
"system",
"time",
".",
"This",
"method",
"will",
"throw",
"a",
"{",
"@link",
... | train | https://github.com/alexa/alexa-skills-kit-sdk-for-java/blob/c49194da0693898c70f3f2c4a372f5a12da04e3e/ask-sdk-servlet-support/src/com/amazon/ask/servlet/verifiers/SkillRequestTimestampVerifier.java#L81-L98 |
intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/HTTPURLConnectionInterceptor.java | HTTPURLConnectionInterceptor.setResponseElements | private void setResponseElements(IntuitMessage intuitMessage, HttpURLConnection httpUrlConnection) throws FMSException {
LOG.debug("Response headers:"+httpUrlConnection.getHeaderFields());
ResponseElements responseElements = intuitMessage.getResponseElements();
responseElements.setEncodingHeader(httpUrlConnection.getContentEncoding());
responseElements.setContentTypeHeader(httpUrlConnection.getContentType());
try {
responseElements.setStatusCode(httpUrlConnection.getResponseCode());
InputStream responseStream;
try {
responseStream = httpUrlConnection.getInputStream();
}
catch (IOException ioe) {
// Any error response from the server. Read the error stream instead of the responseStream. It contains the response from the server for the error code.
responseStream = httpUrlConnection.getErrorStream();
}
responseElements.setResponseContent(getCopyOfResponseContent(responseStream));
} catch (IllegalStateException e) {
LOG.error("IllegalStateException while get the content from HttpRespose.", e);
throw new FMSException(e);
} catch (Exception e) {
LOG.error("IOException in HTTPURLConnectionInterceptor while reading the entity from HttpResponse.", e);
throw new FMSException(e);
}
} | java | private void setResponseElements(IntuitMessage intuitMessage, HttpURLConnection httpUrlConnection) throws FMSException {
LOG.debug("Response headers:"+httpUrlConnection.getHeaderFields());
ResponseElements responseElements = intuitMessage.getResponseElements();
responseElements.setEncodingHeader(httpUrlConnection.getContentEncoding());
responseElements.setContentTypeHeader(httpUrlConnection.getContentType());
try {
responseElements.setStatusCode(httpUrlConnection.getResponseCode());
InputStream responseStream;
try {
responseStream = httpUrlConnection.getInputStream();
}
catch (IOException ioe) {
// Any error response from the server. Read the error stream instead of the responseStream. It contains the response from the server for the error code.
responseStream = httpUrlConnection.getErrorStream();
}
responseElements.setResponseContent(getCopyOfResponseContent(responseStream));
} catch (IllegalStateException e) {
LOG.error("IllegalStateException while get the content from HttpRespose.", e);
throw new FMSException(e);
} catch (Exception e) {
LOG.error("IOException in HTTPURLConnectionInterceptor while reading the entity from HttpResponse.", e);
throw new FMSException(e);
}
} | [
"private",
"void",
"setResponseElements",
"(",
"IntuitMessage",
"intuitMessage",
",",
"HttpURLConnection",
"httpUrlConnection",
")",
"throws",
"FMSException",
"{",
"LOG",
".",
"debug",
"(",
"\"Response headers:\"",
"+",
"httpUrlConnection",
".",
"getHeaderFields",
"(",
... | Method to set the response elements by reading the values from the response | [
"Method",
"to",
"set",
"the",
"response",
"elements",
"by",
"reading",
"the",
"values",
"from",
"the",
"response"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/HTTPURLConnectionInterceptor.java#L184-L209 |
js-lib-com/template.xhtml | src/main/java/js/template/xhtml/ListOperator.java | ListOperator.doExec | @Override
protected Object doExec(Element element, Object scope, String propertyPath, Object... arguments) throws IOException, TemplateException {
if (!propertyPath.equals(".") && ConverterRegistry.hasType(scope.getClass())) {
throw new TemplateException("Operand is property path but scope is not an object.");
}
Element itemTemplate = element.getFirstChild();
if (itemTemplate == null) {
throw new TemplateException("Invalid list element |%s|. Missing item template.", element);
}
for (Object item : content.getIterable(scope, propertyPath)) {
serializer.writeItem(itemTemplate, item);
}
return null;
} | java | @Override
protected Object doExec(Element element, Object scope, String propertyPath, Object... arguments) throws IOException, TemplateException {
if (!propertyPath.equals(".") && ConverterRegistry.hasType(scope.getClass())) {
throw new TemplateException("Operand is property path but scope is not an object.");
}
Element itemTemplate = element.getFirstChild();
if (itemTemplate == null) {
throw new TemplateException("Invalid list element |%s|. Missing item template.", element);
}
for (Object item : content.getIterable(scope, propertyPath)) {
serializer.writeItem(itemTemplate, item);
}
return null;
} | [
"@",
"Override",
"protected",
"Object",
"doExec",
"(",
"Element",
"element",
",",
"Object",
"scope",
",",
"String",
"propertyPath",
",",
"Object",
"...",
"arguments",
")",
"throws",
"IOException",
",",
"TemplateException",
"{",
"if",
"(",
"!",
"propertyPath",
... | Execute LIST operator. Extract content list then repeat context element first child for every list item.
@param element context element,
@param scope scope object,
@param propertyPath property path,
@param arguments optional arguments, not used.
@return always returns null to signal full processing.
@throws IOException if underlying writer fails to write.
@throws TemplateException if element has no children or content list is undefined. | [
"Execute",
"LIST",
"operator",
".",
"Extract",
"content",
"list",
"then",
"repeat",
"context",
"element",
"first",
"child",
"for",
"every",
"list",
"item",
"."
] | train | https://github.com/js-lib-com/template.xhtml/blob/d50cec08aca9ab9680baebe2a26a341c096564fb/src/main/java/js/template/xhtml/ListOperator.java#L74-L87 |
apache/flink | flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/util/AWSUtil.java | AWSUtil.createKinesisClient | public static AmazonKinesis createKinesisClient(Properties configProps, ClientConfiguration awsClientConfig) {
// set a Flink-specific user agent
awsClientConfig.setUserAgentPrefix(String.format(USER_AGENT_FORMAT,
EnvironmentInformation.getVersion(),
EnvironmentInformation.getRevisionInformation().commitId));
// utilize automatic refreshment of credentials by directly passing the AWSCredentialsProvider
AmazonKinesisClientBuilder builder = AmazonKinesisClientBuilder.standard()
.withCredentials(AWSUtil.getCredentialsProvider(configProps))
.withClientConfiguration(awsClientConfig);
if (configProps.containsKey(AWSConfigConstants.AWS_ENDPOINT)) {
// Set signingRegion as null, to facilitate mocking Kinesis for local tests
builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
configProps.getProperty(AWSConfigConstants.AWS_ENDPOINT),
null));
} else {
builder.withRegion(Regions.fromName(configProps.getProperty(AWSConfigConstants.AWS_REGION)));
}
return builder.build();
} | java | public static AmazonKinesis createKinesisClient(Properties configProps, ClientConfiguration awsClientConfig) {
// set a Flink-specific user agent
awsClientConfig.setUserAgentPrefix(String.format(USER_AGENT_FORMAT,
EnvironmentInformation.getVersion(),
EnvironmentInformation.getRevisionInformation().commitId));
// utilize automatic refreshment of credentials by directly passing the AWSCredentialsProvider
AmazonKinesisClientBuilder builder = AmazonKinesisClientBuilder.standard()
.withCredentials(AWSUtil.getCredentialsProvider(configProps))
.withClientConfiguration(awsClientConfig);
if (configProps.containsKey(AWSConfigConstants.AWS_ENDPOINT)) {
// Set signingRegion as null, to facilitate mocking Kinesis for local tests
builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
configProps.getProperty(AWSConfigConstants.AWS_ENDPOINT),
null));
} else {
builder.withRegion(Regions.fromName(configProps.getProperty(AWSConfigConstants.AWS_REGION)));
}
return builder.build();
} | [
"public",
"static",
"AmazonKinesis",
"createKinesisClient",
"(",
"Properties",
"configProps",
",",
"ClientConfiguration",
"awsClientConfig",
")",
"{",
"// set a Flink-specific user agent",
"awsClientConfig",
".",
"setUserAgentPrefix",
"(",
"String",
".",
"format",
"(",
"USE... | Creates an Amazon Kinesis Client.
@param configProps configuration properties containing the access key, secret key, and region
@param awsClientConfig preconfigured AWS SDK client configuration
@return a new Amazon Kinesis Client | [
"Creates",
"an",
"Amazon",
"Kinesis",
"Client",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/util/AWSUtil.java#L76-L96 |
wildfly-swarm-archive/ARCHIVE-wildfly-swarm | batch-jberet/api/src/main/java/org/wildfly/swarm/batch/jberet/BatchFraction.java | BatchFraction.threadPool | public BatchFraction threadPool(final String name, final int maxThreads, final int keepAliveTime, final TimeUnit keepAliveUnits) {
final ThreadPool<?> threadPool = new ThreadPool<>(name);
threadPool.maxThreads(maxThreads)
.keepaliveTime("time", Integer.toBinaryString(keepAliveTime))
.keepaliveTime("unit", keepAliveUnits.name().toLowerCase(Locale.ROOT));
return threadPool(threadPool);
} | java | public BatchFraction threadPool(final String name, final int maxThreads, final int keepAliveTime, final TimeUnit keepAliveUnits) {
final ThreadPool<?> threadPool = new ThreadPool<>(name);
threadPool.maxThreads(maxThreads)
.keepaliveTime("time", Integer.toBinaryString(keepAliveTime))
.keepaliveTime("unit", keepAliveUnits.name().toLowerCase(Locale.ROOT));
return threadPool(threadPool);
} | [
"public",
"BatchFraction",
"threadPool",
"(",
"final",
"String",
"name",
",",
"final",
"int",
"maxThreads",
",",
"final",
"int",
"keepAliveTime",
",",
"final",
"TimeUnit",
"keepAliveUnits",
")",
"{",
"final",
"ThreadPool",
"<",
"?",
">",
"threadPool",
"=",
"ne... | Creates a new thread-pool that can be used for batch jobs.
@param name the maximum number of threads to set the pool to
@param keepAliveTime the time to keep threads alive
@param keepAliveUnits the time unit for the keep alive time
@return this fraction | [
"Creates",
"a",
"new",
"thread",
"-",
"pool",
"that",
"can",
"be",
"used",
"for",
"batch",
"jobs",
"."
] | train | https://github.com/wildfly-swarm-archive/ARCHIVE-wildfly-swarm/blob/28ef71bcfa743a7267666e0ed2919c37b356c09b/batch-jberet/api/src/main/java/org/wildfly/swarm/batch/jberet/BatchFraction.java#L179-L185 |
jMetal/jMetal | jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/espea/util/ScalarizationUtils.java | ScalarizationUtils.weightedSum | public static <S extends Solution<?>> void weightedSum(List<S> solutionsList, double[] weights) {
for (S solution : solutionsList) {
double sum = weights[0] * solution.getObjective(0);
for (int i = 1; i < solution.getNumberOfObjectives(); i++) {
sum += weights[i] * solution.getObjective(i);
}
setScalarizationValue(solution, sum);
}
} | java | public static <S extends Solution<?>> void weightedSum(List<S> solutionsList, double[] weights) {
for (S solution : solutionsList) {
double sum = weights[0] * solution.getObjective(0);
for (int i = 1; i < solution.getNumberOfObjectives(); i++) {
sum += weights[i] * solution.getObjective(i);
}
setScalarizationValue(solution, sum);
}
} | [
"public",
"static",
"<",
"S",
"extends",
"Solution",
"<",
"?",
">",
">",
"void",
"weightedSum",
"(",
"List",
"<",
"S",
">",
"solutionsList",
",",
"double",
"[",
"]",
"weights",
")",
"{",
"for",
"(",
"S",
"solution",
":",
"solutionsList",
")",
"{",
"d... | Objective values are multiplied by weights and summed. Weights should
always be positive.
@param solutionsList A list of solutions.
@param weights Positive constants by which objectives are summed. | [
"Objective",
"values",
"are",
"multiplied",
"by",
"weights",
"and",
"summed",
".",
"Weights",
"should",
"always",
"be",
"positive",
"."
] | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/espea/util/ScalarizationUtils.java#L128-L137 |
OpenLiberty/open-liberty | dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/ExceptionUtils.java | ExceptionUtils.validateProductMatches | @SuppressWarnings("rawtypes")
static String validateProductMatches(String feature, List productMatchers, File installDir, boolean installingAsset) {
return validateProductMatches(feature, null, productMatchers, installDir, installingAsset);
} | java | @SuppressWarnings("rawtypes")
static String validateProductMatches(String feature, List productMatchers, File installDir, boolean installingAsset) {
return validateProductMatches(feature, null, productMatchers, installDir, installingAsset);
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"static",
"String",
"validateProductMatches",
"(",
"String",
"feature",
",",
"List",
"productMatchers",
",",
"File",
"installDir",
",",
"boolean",
"installingAsset",
")",
"{",
"return",
"validateProductMatches",
"(",
... | Calls validate product matches with null dependency
@param feature
@param productMatchers
@param installDir
@param installingAsset
@return | [
"Calls",
"validate",
"product",
"matches",
"with",
"null",
"dependency"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/ExceptionUtils.java#L473-L476 |
apptik/JustJson | json-core/src/main/java/io/apptik/json/JsonObject.java | JsonObject.getDouble | public Double getDouble(String name, boolean strict) throws JsonException {
JsonElement el = get(name);
Double res = null;
if (strict && !el.isNumber()) {
throw Util.typeMismatch(name, el, "double", true);
}
if (el.isNumber()) {
res = el.asDouble();
}
if (el.isString()) {
res = Util.toDouble(el.asString());
}
if (res == null)
throw Util.typeMismatch(name, el, "double", strict);
return res;
} | java | public Double getDouble(String name, boolean strict) throws JsonException {
JsonElement el = get(name);
Double res = null;
if (strict && !el.isNumber()) {
throw Util.typeMismatch(name, el, "double", true);
}
if (el.isNumber()) {
res = el.asDouble();
}
if (el.isString()) {
res = Util.toDouble(el.asString());
}
if (res == null)
throw Util.typeMismatch(name, el, "double", strict);
return res;
} | [
"public",
"Double",
"getDouble",
"(",
"String",
"name",
",",
"boolean",
"strict",
")",
"throws",
"JsonException",
"{",
"JsonElement",
"el",
"=",
"get",
"(",
"name",
")",
";",
"Double",
"res",
"=",
"null",
";",
"if",
"(",
"strict",
"&&",
"!",
"el",
".",... | Returns the value mapped by {@code name} if it exists and is a double or
can be coerced to a double, or throws otherwise.
@throws JsonException if the mapping doesn't exist or cannot be coerced
to a double. | [
"Returns",
"the",
"value",
"mapped",
"by",
"{",
"@code",
"name",
"}",
"if",
"it",
"exists",
"and",
"is",
"a",
"double",
"or",
"can",
"be",
"coerced",
"to",
"a",
"double",
"or",
"throws",
"otherwise",
"."
] | train | https://github.com/apptik/JustJson/blob/c90f0dd7f84df26da4749be8cd9b026fff499a79/json-core/src/main/java/io/apptik/json/JsonObject.java#L414-L429 |
eyp/serfj | src/main/java/net/sf/serfj/ResponseHelper.java | ResponseHelper.renderPage | public void renderPage(String resource, String page) throws IOException {
// If page comes with an extension
String path = "/" + this.viewsPath + "/";
if (resource != null) {
path += resource + "/";
}
if (page.indexOf('.') > 1) {
this.requestedPage = path + page;
} else {
// Search a page with .jsp, .html or .htm extension
this.requestedPage = this.searchPage(path + page);
}
} | java | public void renderPage(String resource, String page) throws IOException {
// If page comes with an extension
String path = "/" + this.viewsPath + "/";
if (resource != null) {
path += resource + "/";
}
if (page.indexOf('.') > 1) {
this.requestedPage = path + page;
} else {
// Search a page with .jsp, .html or .htm extension
this.requestedPage = this.searchPage(path + page);
}
} | [
"public",
"void",
"renderPage",
"(",
"String",
"resource",
",",
"String",
"page",
")",
"throws",
"IOException",
"{",
"// If page comes with an extension",
"String",
"path",
"=",
"\"/\"",
"+",
"this",
".",
"viewsPath",
"+",
"\"/\"",
";",
"if",
"(",
"resource",
... | Renders a page from a resource.
@param resource
The name of the resource (bank, account, etc...). It must
exists below /views directory.
@param page
The page can have an extension or not. If it doesn't have an
extension, the framework first looks for page.jsp, then with
.html or .htm extension.
@throws IOException
if the page doesn't exist. | [
"Renders",
"a",
"page",
"from",
"a",
"resource",
"."
] | train | https://github.com/eyp/serfj/blob/e617592af6f24e59ea58443f2785c44aa2312189/src/main/java/net/sf/serfj/ResponseHelper.java#L153-L165 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectHasValueImpl_CustomFieldSerializer.java | OWLObjectHasValueImpl_CustomFieldSerializer.serializeInstance | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLObjectHasValueImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLObjectHasValueImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | [
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"OWLObjectHasValueImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}"
] | Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful | [
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamWriter",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectHasValueImpl_CustomFieldSerializer.java#L72-L75 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/admin/internal/MessagingMBeanFactoryImpl.java | MessagingMBeanFactoryImpl.createQueueMBean | private Controllable createQueueMBean(Controllable c) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "createQueuePointMBean", new Object[] { c });
JsQueue qp = new JsQueue(_me, c);
controllableMap.put(c, qp);
try {
Dictionary<String, Object> properties = new Hashtable<String, Object>();
properties.put("service.vendor", "IBM");
String cName = c.getName();
properties.put("jmx.objectname", "WebSphere:feature=wasJmsServer,type=Queue,name=" + cName);
ServiceRegistration<QueueMBean> qMbean = (ServiceRegistration<QueueMBean>) bcontext.registerService(QueueMBean.class.getName(), qp, properties);
serviceObjects.put(cName, qMbean);
} catch (Exception e) {
SibTr.exception(tc, e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createQueuePointMBean", new Object[] { qp });
return qp;
} | java | private Controllable createQueueMBean(Controllable c) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "createQueuePointMBean", new Object[] { c });
JsQueue qp = new JsQueue(_me, c);
controllableMap.put(c, qp);
try {
Dictionary<String, Object> properties = new Hashtable<String, Object>();
properties.put("service.vendor", "IBM");
String cName = c.getName();
properties.put("jmx.objectname", "WebSphere:feature=wasJmsServer,type=Queue,name=" + cName);
ServiceRegistration<QueueMBean> qMbean = (ServiceRegistration<QueueMBean>) bcontext.registerService(QueueMBean.class.getName(), qp, properties);
serviceObjects.put(cName, qMbean);
} catch (Exception e) {
SibTr.exception(tc, e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createQueuePointMBean", new Object[] { qp });
return qp;
} | [
"private",
"Controllable",
"createQueueMBean",
"(",
"Controllable",
"c",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"\"createQueuePointMB... | Create an instance of the required MBean and register it
@param c
@return | [
"Create",
"an",
"instance",
"of",
"the",
"required",
"MBean",
"and",
"register",
"it"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/admin/internal/MessagingMBeanFactoryImpl.java#L294-L314 |
fcrepo4-labs/fcrepo4-client | fcrepo-client-impl/src/main/java/org/fcrepo/client/utils/HttpHelper.java | HttpHelper.createGetMethod | public HttpGet createGetMethod(final String path, final Map<String, List<String>> params) {
return new HttpGet(repositoryURL + path + queryString(params));
} | java | public HttpGet createGetMethod(final String path, final Map<String, List<String>> params) {
return new HttpGet(repositoryURL + path + queryString(params));
} | [
"public",
"HttpGet",
"createGetMethod",
"(",
"final",
"String",
"path",
",",
"final",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"params",
")",
"{",
"return",
"new",
"HttpGet",
"(",
"repositoryURL",
"+",
"path",
"+",
"queryString",
"(",
... | Create GET method with list of parameters
@param path Resource path, relative to repository baseURL
@param params Query parameters
@return GET method | [
"Create",
"GET",
"method",
"with",
"list",
"of",
"parameters"
] | train | https://github.com/fcrepo4-labs/fcrepo4-client/blob/21eaf27200c5b2542095f6ebb9dd8ec865b95bbd/fcrepo-client-impl/src/main/java/org/fcrepo/client/utils/HttpHelper.java#L224-L226 |
apache/flink | flink-formats/flink-avro-confluent-registry/src/main/java/org/apache/flink/formats/avro/registry/confluent/ConfluentRegistryAvroDeserializationSchema.java | ConfluentRegistryAvroDeserializationSchema.forSpecific | public static <T extends SpecificRecord> ConfluentRegistryAvroDeserializationSchema<T> forSpecific(Class<T> tClass,
String url) {
return forSpecific(tClass, url, DEFAULT_IDENTITY_MAP_CAPACITY);
} | java | public static <T extends SpecificRecord> ConfluentRegistryAvroDeserializationSchema<T> forSpecific(Class<T> tClass,
String url) {
return forSpecific(tClass, url, DEFAULT_IDENTITY_MAP_CAPACITY);
} | [
"public",
"static",
"<",
"T",
"extends",
"SpecificRecord",
">",
"ConfluentRegistryAvroDeserializationSchema",
"<",
"T",
">",
"forSpecific",
"(",
"Class",
"<",
"T",
">",
"tClass",
",",
"String",
"url",
")",
"{",
"return",
"forSpecific",
"(",
"tClass",
",",
"url... | Creates {@link AvroDeserializationSchema} that produces classes that were generated from avro
schema and looks up writer schema in Confluent Schema Registry.
@param tClass class of record to be produced
@param url url of schema registry to connect
@return deserialized record | [
"Creates",
"{",
"@link",
"AvroDeserializationSchema",
"}",
"that",
"produces",
"classes",
"that",
"were",
"generated",
"from",
"avro",
"schema",
"and",
"looks",
"up",
"writer",
"schema",
"in",
"Confluent",
"Schema",
"Registry",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-formats/flink-avro-confluent-registry/src/main/java/org/apache/flink/formats/avro/registry/confluent/ConfluentRegistryAvroDeserializationSchema.java#L95-L98 |
alkacon/opencms-core | src/org/opencms/file/wrapper/CmsResourceWrapperModules.java | CmsResourceWrapperModules.matchParentPath | private boolean matchParentPath(String expectedParent, String path) {
String parent = CmsResource.getParentFolder(path);
if (parent == null) {
return false;
}
return matchPath(expectedParent, parent);
} | java | private boolean matchParentPath(String expectedParent, String path) {
String parent = CmsResource.getParentFolder(path);
if (parent == null) {
return false;
}
return matchPath(expectedParent, parent);
} | [
"private",
"boolean",
"matchParentPath",
"(",
"String",
"expectedParent",
",",
"String",
"path",
")",
"{",
"String",
"parent",
"=",
"CmsResource",
".",
"getParentFolder",
"(",
"path",
")",
";",
"if",
"(",
"parent",
"==",
"null",
")",
"{",
"return",
"false",
... | Checks if a given path is a direct descendant of another path.<p>
@param expectedParent the expected parent folder
@param path a path
@return true if the path is a direct child of expectedParent | [
"Checks",
"if",
"a",
"given",
"path",
"is",
"a",
"direct",
"descendant",
"of",
"another",
"path",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/wrapper/CmsResourceWrapperModules.java#L553-L560 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/allocator/impl/AtomicAllocator.java | AtomicAllocator.purgeZeroObject | protected void purgeZeroObject(Long bucketId, Long objectId, AllocationPoint point, boolean copyback) {
allocationsMap.remove(objectId);
memoryHandler.purgeZeroObject(bucketId, objectId, point, copyback);
getFlowController().getEventsProvider().storeEvent(point.getLastWriteEvent());
getFlowController().getEventsProvider().storeEvent(point.getLastReadEvent());
} | java | protected void purgeZeroObject(Long bucketId, Long objectId, AllocationPoint point, boolean copyback) {
allocationsMap.remove(objectId);
memoryHandler.purgeZeroObject(bucketId, objectId, point, copyback);
getFlowController().getEventsProvider().storeEvent(point.getLastWriteEvent());
getFlowController().getEventsProvider().storeEvent(point.getLastReadEvent());
} | [
"protected",
"void",
"purgeZeroObject",
"(",
"Long",
"bucketId",
",",
"Long",
"objectId",
",",
"AllocationPoint",
"point",
",",
"boolean",
"copyback",
")",
"{",
"allocationsMap",
".",
"remove",
"(",
"objectId",
")",
";",
"memoryHandler",
".",
"purgeZeroObject",
... | This method frees native system memory referenced by specified tracking id/AllocationPoint
@param bucketId
@param objectId
@param point
@param copyback | [
"This",
"method",
"frees",
"native",
"system",
"memory",
"referenced",
"by",
"specified",
"tracking",
"id",
"/",
"AllocationPoint"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/allocator/impl/AtomicAllocator.java#L530-L537 |
ModeShape/modeshape | sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/StandardDdlParser.java | StandardDdlParser.parseCreateCollationStatement | protected AstNode parseCreateCollationStatement( DdlTokenStream tokens,
AstNode parentNode ) throws ParsingException {
assert tokens != null;
assert parentNode != null;
markStartOfStatement(tokens);
tokens.consume(STMT_CREATE_COLLATION);
String name = parseName(tokens);
AstNode node = nodeFactory().node(name, parentNode, TYPE_CREATE_COLLATION_STATEMENT);
// character set attribute
tokens.consume("FOR");
String charSetName = parseName(tokens);
node.setProperty(COLLATION_CHARACTER_SET_NAME, charSetName);
// collation source
// TODO author=Horia Chiorean date=1/4/12 description=Only parsing a string atm (should probably be some nested nodes -
// see StandardDdl.cnd
tokens.consume("FROM");
String collationSource = null;
if (tokens.canConsume("EXTERNAL") || tokens.canConsume("DESC")) {
collationSource = consumeParenBoundedTokens(tokens, false);
} else if (tokens.canConsume("TRANSLATION")) {
StringBuilder translationCollation = new StringBuilder("TRANSLATION ").append(tokens.consume());
if (tokens.canConsume("THEN", "COLLATION")) {
translationCollation.append(" THEN COLLATION ");
translationCollation.append(parseName(tokens));
}
collationSource = translationCollation.toString();
} else {
collationSource = parseName(tokens);
}
node.setProperty(COLLATION_SOURCE, collationSource);
// pad attribute
if (tokens.canConsume("PAD", "SPACE")) {
node.setProperty(PAD_ATTRIBUTE, PAD_ATTRIBUTE_PAD);
} else if (tokens.canConsume("NO", "PAD")) {
node.setProperty(PAD_ATTRIBUTE, PAD_ATTRIBUTE_NO_PAD);
}
parseUntilTerminator(tokens);
markEndOfStatement(tokens, node);
return node;
} | java | protected AstNode parseCreateCollationStatement( DdlTokenStream tokens,
AstNode parentNode ) throws ParsingException {
assert tokens != null;
assert parentNode != null;
markStartOfStatement(tokens);
tokens.consume(STMT_CREATE_COLLATION);
String name = parseName(tokens);
AstNode node = nodeFactory().node(name, parentNode, TYPE_CREATE_COLLATION_STATEMENT);
// character set attribute
tokens.consume("FOR");
String charSetName = parseName(tokens);
node.setProperty(COLLATION_CHARACTER_SET_NAME, charSetName);
// collation source
// TODO author=Horia Chiorean date=1/4/12 description=Only parsing a string atm (should probably be some nested nodes -
// see StandardDdl.cnd
tokens.consume("FROM");
String collationSource = null;
if (tokens.canConsume("EXTERNAL") || tokens.canConsume("DESC")) {
collationSource = consumeParenBoundedTokens(tokens, false);
} else if (tokens.canConsume("TRANSLATION")) {
StringBuilder translationCollation = new StringBuilder("TRANSLATION ").append(tokens.consume());
if (tokens.canConsume("THEN", "COLLATION")) {
translationCollation.append(" THEN COLLATION ");
translationCollation.append(parseName(tokens));
}
collationSource = translationCollation.toString();
} else {
collationSource = parseName(tokens);
}
node.setProperty(COLLATION_SOURCE, collationSource);
// pad attribute
if (tokens.canConsume("PAD", "SPACE")) {
node.setProperty(PAD_ATTRIBUTE, PAD_ATTRIBUTE_PAD);
} else if (tokens.canConsume("NO", "PAD")) {
node.setProperty(PAD_ATTRIBUTE, PAD_ATTRIBUTE_NO_PAD);
}
parseUntilTerminator(tokens);
markEndOfStatement(tokens, node);
return node;
} | [
"protected",
"AstNode",
"parseCreateCollationStatement",
"(",
"DdlTokenStream",
"tokens",
",",
"AstNode",
"parentNode",
")",
"throws",
"ParsingException",
"{",
"assert",
"tokens",
"!=",
"null",
";",
"assert",
"parentNode",
"!=",
"null",
";",
"markStartOfStatement",
"(... | Parses DDL CREATE COLLATION {@link AstNode} based on SQL 92 specifications.
@param tokens the {@link DdlTokenStream} representing the tokenized DDL content; may not be null
@param parentNode the parent {@link AstNode} node; may not be null
@return the parsed statement node {@link AstNode}
@throws ParsingException | [
"Parses",
"DDL",
"CREATE",
"COLLATION",
"{",
"@link",
"AstNode",
"}",
"based",
"on",
"SQL",
"92",
"specifications",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/StandardDdlParser.java#L1107-L1154 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/random/RandomString.java | RandomString.nextString | public static String nextString(int min, int max) {
StringBuilder result = new StringBuilder();
int length = RandomInteger.nextInteger(min, max);
for (int i = 0; i < length; i++) {
int index = RandomInteger.nextInteger(_chars.length());
result.append(_chars.charAt(index));
}
return result.toString();
} | java | public static String nextString(int min, int max) {
StringBuilder result = new StringBuilder();
int length = RandomInteger.nextInteger(min, max);
for (int i = 0; i < length; i++) {
int index = RandomInteger.nextInteger(_chars.length());
result.append(_chars.charAt(index));
}
return result.toString();
} | [
"public",
"static",
"String",
"nextString",
"(",
"int",
"min",
",",
"int",
"max",
")",
"{",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"int",
"length",
"=",
"RandomInteger",
".",
"nextInteger",
"(",
"min",
",",
"max",
")",
";"... | Generates a random string, consisting of upper and lower case letters (of the
English alphabet), digits (0-9), and symbols.
@param min (optional) minimum string length.
@param max maximum string length.
@return a random string. | [
"Generates",
"a",
"random",
"string",
"consisting",
"of",
"upper",
"and",
"lower",
"case",
"letters",
"(",
"of",
"the",
"English",
"alphabet",
")",
"digits",
"(",
"0",
"-",
"9",
")",
"and",
"symbols",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/random/RandomString.java#L86-L96 |
Whiley/WhileyCompiler | src/main/java/wyil/check/DefiniteAssignmentCheck.java | DefiniteAssignmentCheck.visitProperty | @Override
public ControlFlow visitProperty(Decl.Property declaration, DefinitelyAssignedSet dummy) {
DefinitelyAssignedSet environment = new DefinitelyAssignedSet();
// Definitely assigned variables includes all parameters.
environment = environment.addAll(declaration.getParameters());
// Iterate through each statement in the body of the function or method,
// updating the set of definitely assigned variables as appropriate.
visitExpressions(declaration.getInvariant(),environment);
//
return null;
} | java | @Override
public ControlFlow visitProperty(Decl.Property declaration, DefinitelyAssignedSet dummy) {
DefinitelyAssignedSet environment = new DefinitelyAssignedSet();
// Definitely assigned variables includes all parameters.
environment = environment.addAll(declaration.getParameters());
// Iterate through each statement in the body of the function or method,
// updating the set of definitely assigned variables as appropriate.
visitExpressions(declaration.getInvariant(),environment);
//
return null;
} | [
"@",
"Override",
"public",
"ControlFlow",
"visitProperty",
"(",
"Decl",
".",
"Property",
"declaration",
",",
"DefinitelyAssignedSet",
"dummy",
")",
"{",
"DefinitelyAssignedSet",
"environment",
"=",
"new",
"DefinitelyAssignedSet",
"(",
")",
";",
"// Definitely assigned v... | Check a function or method declaration for definite assignment.
@param declaration
@return | [
"Check",
"a",
"function",
"or",
"method",
"declaration",
"for",
"definite",
"assignment",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/DefiniteAssignmentCheck.java#L94-L104 |
apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.getPropAsLong | public long getPropAsLong(String key, long def) {
return Long.parseLong(getProp(key, String.valueOf(def)));
} | java | public long getPropAsLong(String key, long def) {
return Long.parseLong(getProp(key, String.valueOf(def)));
} | [
"public",
"long",
"getPropAsLong",
"(",
"String",
"key",
",",
"long",
"def",
")",
"{",
"return",
"Long",
".",
"parseLong",
"(",
"getProp",
"(",
"key",
",",
"String",
".",
"valueOf",
"(",
"def",
")",
")",
")",
";",
"}"
] | Get the value of a property as a long integer, using the given default value if the property is not set.
@param key property key
@param def default value
@return long integer value associated with the key or the default value if the property is not set | [
"Get",
"the",
"value",
"of",
"a",
"property",
"as",
"a",
"long",
"integer",
"using",
"the",
"given",
"default",
"value",
"if",
"the",
"property",
"is",
"not",
"set",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L363-L365 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AtomCache.java | AtomCache.getStructureForDomain | public Structure getStructureForDomain(ScopDomain domain) throws IOException, StructureException {
return getStructureForDomain(domain, ScopFactory.getSCOP());
} | java | public Structure getStructureForDomain(ScopDomain domain) throws IOException, StructureException {
return getStructureForDomain(domain, ScopFactory.getSCOP());
} | [
"public",
"Structure",
"getStructureForDomain",
"(",
"ScopDomain",
"domain",
")",
"throws",
"IOException",
",",
"StructureException",
"{",
"return",
"getStructureForDomain",
"(",
"domain",
",",
"ScopFactory",
".",
"getSCOP",
"(",
")",
")",
";",
"}"
] | Returns the representation of a {@link ScopDomain} as a BioJava {@link Structure} object.
@param domain
a SCOP domain
@return a Structure object
@throws IOException
@throws StructureException | [
"Returns",
"the",
"representation",
"of",
"a",
"{",
"@link",
"ScopDomain",
"}",
"as",
"a",
"BioJava",
"{",
"@link",
"Structure",
"}",
"object",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AtomCache.java#L528-L530 |
ben-manes/caffeine | simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/segment/RandomWindowTinyLfuPolicy.java | RandomWindowTinyLfuPolicy.policies | public static Set<Policy> policies(Config config) {
RandomWindowTinyLfuSettings settings = new RandomWindowTinyLfuSettings(config);
return settings.percentMain().stream()
.map(percentMain -> new RandomWindowTinyLfuPolicy(percentMain, settings))
.collect(toSet());
} | java | public static Set<Policy> policies(Config config) {
RandomWindowTinyLfuSettings settings = new RandomWindowTinyLfuSettings(config);
return settings.percentMain().stream()
.map(percentMain -> new RandomWindowTinyLfuPolicy(percentMain, settings))
.collect(toSet());
} | [
"public",
"static",
"Set",
"<",
"Policy",
">",
"policies",
"(",
"Config",
"config",
")",
"{",
"RandomWindowTinyLfuSettings",
"settings",
"=",
"new",
"RandomWindowTinyLfuSettings",
"(",
"config",
")",
";",
"return",
"settings",
".",
"percentMain",
"(",
")",
".",
... | Returns all variations of this policy based on the configuration parameters. | [
"Returns",
"all",
"variations",
"of",
"this",
"policy",
"based",
"on",
"the",
"configuration",
"parameters",
"."
] | train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/segment/RandomWindowTinyLfuPolicy.java#L67-L72 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java | EscapedFunctions2.sqllog | public static void sqllog(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "ln(", "log", parsedArgs);
} | java | public static void sqllog(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "ln(", "log", parsedArgs);
} | [
"public",
"static",
"void",
"sqllog",
"(",
"StringBuilder",
"buf",
",",
"List",
"<",
"?",
"extends",
"CharSequence",
">",
"parsedArgs",
")",
"throws",
"SQLException",
"{",
"singleArgumentFunctionCall",
"(",
"buf",
",",
"\"ln(\"",
",",
"\"log\"",
",",
"parsedArgs... | log to ln translation
@param buf The buffer to append into
@param parsedArgs arguments
@throws SQLException if something wrong happens | [
"log",
"to",
"ln",
"translation"
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L98-L100 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/JdbcAccessImpl.java | JdbcAccessImpl.executeDelete | public void executeDelete(Query query, ClassDescriptor cld) throws PersistenceBrokerException
{
if (logger.isDebugEnabled())
{
logger.debug("executeDelete (by Query): " + query);
}
final StatementManagerIF sm = broker.serviceStatementManager();
PreparedStatement stmt = null;
final String sql = this.broker.serviceSqlGenerator().getPreparedDeleteStatement(query, cld).getStatement();
try
{
stmt = sm.getPreparedStatement(cld, sql,
false, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, cld.getDeleteProcedure()!=null);
sm.bindStatement(stmt, query, cld, 1);
if (logger.isDebugEnabled())
logger.debug("executeDelete (by Query): " + stmt);
stmt.executeUpdate();
}
catch (SQLException e)
{
throw ExceptionHelper.generateException(e, sql, cld, null, logger);
}
finally
{
sm.closeResources(stmt, null);
}
} | java | public void executeDelete(Query query, ClassDescriptor cld) throws PersistenceBrokerException
{
if (logger.isDebugEnabled())
{
logger.debug("executeDelete (by Query): " + query);
}
final StatementManagerIF sm = broker.serviceStatementManager();
PreparedStatement stmt = null;
final String sql = this.broker.serviceSqlGenerator().getPreparedDeleteStatement(query, cld).getStatement();
try
{
stmt = sm.getPreparedStatement(cld, sql,
false, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, cld.getDeleteProcedure()!=null);
sm.bindStatement(stmt, query, cld, 1);
if (logger.isDebugEnabled())
logger.debug("executeDelete (by Query): " + stmt);
stmt.executeUpdate();
}
catch (SQLException e)
{
throw ExceptionHelper.generateException(e, sql, cld, null, logger);
}
finally
{
sm.closeResources(stmt, null);
}
} | [
"public",
"void",
"executeDelete",
"(",
"Query",
"query",
",",
"ClassDescriptor",
"cld",
")",
"throws",
"PersistenceBrokerException",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"executeDelete (by Query): \""... | Performs a DELETE operation based on the given {@link Query} against RDBMS.
@param query the query string.
@param cld ClassDescriptor providing JDBC information. | [
"Performs",
"a",
"DELETE",
"operation",
"based",
"on",
"the",
"given",
"{"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/JdbcAccessImpl.java#L165-L193 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/trees/BobChrisTreeNormalizer.java | BobChrisTreeNormalizer.normalizeWholeTree | @Override
public Tree normalizeWholeTree(Tree tree, TreeFactory tf) {
return tree.prune(emptyFilter, tf).spliceOut(aOverAFilter, tf);
} | java | @Override
public Tree normalizeWholeTree(Tree tree, TreeFactory tf) {
return tree.prune(emptyFilter, tf).spliceOut(aOverAFilter, tf);
} | [
"@",
"Override",
"public",
"Tree",
"normalizeWholeTree",
"(",
"Tree",
"tree",
",",
"TreeFactory",
"tf",
")",
"{",
"return",
"tree",
".",
"prune",
"(",
"emptyFilter",
",",
"tf",
")",
".",
"spliceOut",
"(",
"aOverAFilter",
",",
"tf",
")",
";",
"}"
] | Normalize a whole tree -- one can assume that this is the
root. This implementation deletes empty elements (ones with
nonterminal tag label '-NONE-') from the tree, and splices out
unary A over A nodes. It does work for a null tree. | [
"Normalize",
"a",
"whole",
"tree",
"--",
"one",
"can",
"assume",
"that",
"this",
"is",
"the",
"root",
".",
"This",
"implementation",
"deletes",
"empty",
"elements",
"(",
"ones",
"with",
"nonterminal",
"tag",
"label",
"-",
"NONE",
"-",
")",
"from",
"the",
... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/trees/BobChrisTreeNormalizer.java#L101-L104 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.