repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 218 | func_name stringlengths 5 140 | whole_func_string stringlengths 79 3.99k | language stringclasses 1
value | func_code_string stringlengths 79 3.99k | func_code_tokens listlengths 20 624 | func_documentation_string stringlengths 61 1.96k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 107 339 |
|---|---|---|---|---|---|---|---|---|---|---|
boncey/Flickr4Java | src/examples/java/UploadPhoto.java | UploadPhoto.constructAuth | private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {
Auth auth = new Auth();
auth.setToken(authToken);
auth.setTokenSecret(tokenSecret);
// Prompt to ask what permission is needed: read, update or delete.
auth.setPermission(Permission.fromString("delete"));
User user = new User();
// Later change the following 3. Either ask user to pass on command line or read
// from saved file.
user.setId(nsid);
user.setUsername((username));
user.setRealName("");
auth.setUser(user);
this.authStore.store(auth);
return auth;
} | java | private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {
Auth auth = new Auth();
auth.setToken(authToken);
auth.setTokenSecret(tokenSecret);
// Prompt to ask what permission is needed: read, update or delete.
auth.setPermission(Permission.fromString("delete"));
User user = new User();
// Later change the following 3. Either ask user to pass on command line or read
// from saved file.
user.setId(nsid);
user.setUsername((username));
user.setRealName("");
auth.setUser(user);
this.authStore.store(auth);
return auth;
} | [
"private",
"Auth",
"constructAuth",
"(",
"String",
"authToken",
",",
"String",
"tokenSecret",
",",
"String",
"username",
")",
"throws",
"IOException",
"{",
"Auth",
"auth",
"=",
"new",
"Auth",
"(",
")",
";",
"auth",
".",
"setToken",
"(",
"authToken",
")",
"... | If the Authtoken was already created in a separate program but not saved to file.
@param authToken
@param tokenSecret
@param username
@return
@throws IOException | [
"If",
"the",
"Authtoken",
"was",
"already",
"created",
"in",
"a",
"separate",
"program",
"but",
"not",
"saved",
"to",
"file",
"."
] | train | https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/examples/java/UploadPhoto.java#L199-L217 |
cdk/cdk | tool/pcore/src/main/java/org/openscience/cdk/pharmacophore/PharmacophoreMatcher.java | PharmacophoreMatcher.getTargetQueryBondMappings | public List<HashMap<IBond, IBond>> getTargetQueryBondMappings() {
if (mappings == null) return null;
List<HashMap<IBond,IBond>> bondMap = new ArrayList<>();
// query -> target so need to inverse the mapping
// XXX: re-subsearching the query
for (Map<IBond,IBond> map : mappings.toBondMap()) {
bondMap.add(new HashMap<>(HashBiMap.create(map).inverse()));
}
return bondMap;
} | java | public List<HashMap<IBond, IBond>> getTargetQueryBondMappings() {
if (mappings == null) return null;
List<HashMap<IBond,IBond>> bondMap = new ArrayList<>();
// query -> target so need to inverse the mapping
// XXX: re-subsearching the query
for (Map<IBond,IBond> map : mappings.toBondMap()) {
bondMap.add(new HashMap<>(HashBiMap.create(map).inverse()));
}
return bondMap;
} | [
"public",
"List",
"<",
"HashMap",
"<",
"IBond",
",",
"IBond",
">",
">",
"getTargetQueryBondMappings",
"(",
")",
"{",
"if",
"(",
"mappings",
"==",
"null",
")",
"return",
"null",
";",
"List",
"<",
"HashMap",
"<",
"IBond",
",",
"IBond",
">",
">",
"bondMap... | Return a list of HashMap's that allows one to get the query constraint for a given pharmacophore bond.
If the matching is successful, the return value is a List of HashMaps, each
HashMap corresponding to a separate match. Each HashMap is keyed on the {@link org.openscience.cdk.pharmacophore.PharmacophoreBond}
in the target molecule that matched a constraint ({@link org.openscience.cdk.pharmacophore.PharmacophoreQueryBond} or
{@link org.openscience.cdk.pharmacophore.PharmacophoreQueryAngleBond}. The value is the corresponding query bond.
@return A List of HashMaps, identifying the query constraint corresponding to a matched constraint in the target
molecule. | [
"Return",
"a",
"list",
"of",
"HashMap",
"s",
"that",
"allows",
"one",
"to",
"get",
"the",
"query",
"constraint",
"for",
"a",
"given",
"pharmacophore",
"bond",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/pcore/src/main/java/org/openscience/cdk/pharmacophore/PharmacophoreMatcher.java#L275-L287 |
JDBDT/jdbdt | src/main/java/org/jdbdt/DataSetBuilder.java | DataSetBuilder.nextRandomLong | private long nextRandomLong(long a, long b) {
return a + (rng.nextLong() & Long.MAX_VALUE) % (b - a + 1);
} | java | private long nextRandomLong(long a, long b) {
return a + (rng.nextLong() & Long.MAX_VALUE) % (b - a + 1);
} | [
"private",
"long",
"nextRandomLong",
"(",
"long",
"a",
",",
"long",
"b",
")",
"{",
"return",
"a",
"+",
"(",
"rng",
".",
"nextLong",
"(",
")",
"&",
"Long",
".",
"MAX_VALUE",
")",
"%",
"(",
"b",
"-",
"a",
"+",
"1",
")",
";",
"}"
] | Auxiliary method that generates a pseudo-random long
within a given internal
@param a Lower bound
@param b Upper bound
@return A long value in the interval <code>[a, b]</code> | [
"Auxiliary",
"method",
"that",
"generates",
"a",
"pseudo",
"-",
"random",
"long",
"within",
"a",
"given",
"internal"
] | train | https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/DataSetBuilder.java#L878-L880 |
alkacon/opencms-core | src-modules/org/opencms/workplace/CmsWidgetDialog.java | CmsWidgetDialog.getParamValue | public String getParamValue(String name, int index) {
List<CmsWidgetDialogParameter> params = m_widgetParamValues.get(name);
if (params != null) {
if ((index >= 0) && (index < params.size())) {
CmsWidgetDialogParameter param = params.get(index);
if (param.getId().equals(CmsWidgetDialogParameter.createId(name, index))) {
return param.getStringValue(getCms());
}
}
}
return null;
} | java | public String getParamValue(String name, int index) {
List<CmsWidgetDialogParameter> params = m_widgetParamValues.get(name);
if (params != null) {
if ((index >= 0) && (index < params.size())) {
CmsWidgetDialogParameter param = params.get(index);
if (param.getId().equals(CmsWidgetDialogParameter.createId(name, index))) {
return param.getStringValue(getCms());
}
}
}
return null;
} | [
"public",
"String",
"getParamValue",
"(",
"String",
"name",
",",
"int",
"index",
")",
"{",
"List",
"<",
"CmsWidgetDialogParameter",
">",
"params",
"=",
"m_widgetParamValues",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"params",
"!=",
"null",
")",
"{",
... | Returns the value of the widget parameter with the given name and index, or <code>null</code>
if no such widget parameter is available.<p>
@param name the widget parameter name to get the value for
@param index the widget parameter index
@return the value of the widget parameter with the given name and index | [
"Returns",
"the",
"value",
"of",
"the",
"widget",
"parameter",
"with",
"the",
"given",
"name",
"and",
"index",
"or",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"no",
"such",
"widget",
"parameter",
"is",
"available",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/CmsWidgetDialog.java#L505-L518 |
casmi/casmi | src/main/java/casmi/graphics/material/Material.java | Material.setDiffuse | public void setDiffuse(float red, float green, float blue){
diffuse[0] = red;
diffuse[1] = green;
diffuse[2] = blue;
Di = true;
} | java | public void setDiffuse(float red, float green, float blue){
diffuse[0] = red;
diffuse[1] = green;
diffuse[2] = blue;
Di = true;
} | [
"public",
"void",
"setDiffuse",
"(",
"float",
"red",
",",
"float",
"green",
",",
"float",
"blue",
")",
"{",
"diffuse",
"[",
"0",
"]",
"=",
"red",
";",
"diffuse",
"[",
"1",
"]",
"=",
"green",
";",
"diffuse",
"[",
"2",
"]",
"=",
"blue",
";",
"Di",
... | Sets the diffuse color of the materials used for shapes drawn to the screen.
@param red
The red color of the diffuse.
@param green
The green color of the diffuse.
@param blue
The blue color of the diffuse. | [
"Sets",
"the",
"diffuse",
"color",
"of",
"the",
"materials",
"used",
"for",
"shapes",
"drawn",
"to",
"the",
"screen",
"."
] | train | https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/material/Material.java#L126-L131 |
ben-manes/caffeine | jcache/src/main/java/com/github/benmanes/caffeine/jcache/CacheProxy.java | CacheProxy.putNoCopyOrAwait | protected V putNoCopyOrAwait(K key, V value, boolean publishToWriter, int[] puts) {
requireNonNull(key);
requireNonNull(value);
@SuppressWarnings("unchecked")
V[] replaced = (V[]) new Object[1];
cache.asMap().compute(copyOf(key), (k, expirable) -> {
V newValue = copyOf(value);
if (publishToWriter && configuration.isWriteThrough()) {
publishToCacheWriter(writer::write, () -> new EntryProxy<>(key, value));
}
if ((expirable != null) && !expirable.isEternal()
&& expirable.hasExpired(currentTimeMillis())) {
dispatcher.publishExpired(this, key, expirable.get());
statistics.recordEvictions(1L);
expirable = null;
}
long expireTimeMS = getWriteExpireTimeMS((expirable == null));
if ((expirable != null) && (expireTimeMS == Long.MIN_VALUE)) {
expireTimeMS = expirable.getExpireTimeMS();
}
if (expireTimeMS == 0) {
replaced[0] = (expirable == null) ? null : expirable.get();
return null;
} else if (expirable == null) {
dispatcher.publishCreated(this, key, newValue);
} else {
replaced[0] = expirable.get();
dispatcher.publishUpdated(this, key, expirable.get(), newValue);
}
puts[0]++;
return new Expirable<>(newValue, expireTimeMS);
});
return replaced[0];
} | java | protected V putNoCopyOrAwait(K key, V value, boolean publishToWriter, int[] puts) {
requireNonNull(key);
requireNonNull(value);
@SuppressWarnings("unchecked")
V[] replaced = (V[]) new Object[1];
cache.asMap().compute(copyOf(key), (k, expirable) -> {
V newValue = copyOf(value);
if (publishToWriter && configuration.isWriteThrough()) {
publishToCacheWriter(writer::write, () -> new EntryProxy<>(key, value));
}
if ((expirable != null) && !expirable.isEternal()
&& expirable.hasExpired(currentTimeMillis())) {
dispatcher.publishExpired(this, key, expirable.get());
statistics.recordEvictions(1L);
expirable = null;
}
long expireTimeMS = getWriteExpireTimeMS((expirable == null));
if ((expirable != null) && (expireTimeMS == Long.MIN_VALUE)) {
expireTimeMS = expirable.getExpireTimeMS();
}
if (expireTimeMS == 0) {
replaced[0] = (expirable == null) ? null : expirable.get();
return null;
} else if (expirable == null) {
dispatcher.publishCreated(this, key, newValue);
} else {
replaced[0] = expirable.get();
dispatcher.publishUpdated(this, key, expirable.get(), newValue);
}
puts[0]++;
return new Expirable<>(newValue, expireTimeMS);
});
return replaced[0];
} | [
"protected",
"V",
"putNoCopyOrAwait",
"(",
"K",
"key",
",",
"V",
"value",
",",
"boolean",
"publishToWriter",
",",
"int",
"[",
"]",
"puts",
")",
"{",
"requireNonNull",
"(",
"key",
")",
";",
"requireNonNull",
"(",
"value",
")",
";",
"@",
"SuppressWarnings",
... | Associates the specified value with the specified key in the cache.
@param key key with which the specified value is to be associated
@param value value to be associated with the specified key
@param publishToWriter if the writer should be notified
@param puts the accumulator for additions and updates
@return the old value | [
"Associates",
"the",
"specified",
"value",
"with",
"the",
"specified",
"key",
"in",
"the",
"cache",
"."
] | train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/jcache/src/main/java/com/github/benmanes/caffeine/jcache/CacheProxy.java#L342-L376 |
BlueBrain/bluima | modules/bluima_typesystem/src/main/java/de/julielab/jules/types/Header.java | Header.setAuthors | public void setAuthors(int i, AuthorInfo v) {
if (Header_Type.featOkTst && ((Header_Type)jcasType).casFeat_authors == null)
jcasType.jcas.throwFeatMissing("authors", "de.julielab.jules.types.Header");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Header_Type)jcasType).casFeatCode_authors), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Header_Type)jcasType).casFeatCode_authors), i, jcasType.ll_cas.ll_getFSRef(v));} | java | public void setAuthors(int i, AuthorInfo v) {
if (Header_Type.featOkTst && ((Header_Type)jcasType).casFeat_authors == null)
jcasType.jcas.throwFeatMissing("authors", "de.julielab.jules.types.Header");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Header_Type)jcasType).casFeatCode_authors), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Header_Type)jcasType).casFeatCode_authors), i, jcasType.ll_cas.ll_getFSRef(v));} | [
"public",
"void",
"setAuthors",
"(",
"int",
"i",
",",
"AuthorInfo",
"v",
")",
"{",
"if",
"(",
"Header_Type",
".",
"featOkTst",
"&&",
"(",
"(",
"Header_Type",
")",
"jcasType",
")",
".",
"casFeat_authors",
"==",
"null",
")",
"jcasType",
".",
"jcas",
".",
... | indexed setter for authors - sets an indexed value - The authors of the document, O
@generated
@param i index in the array to set
@param v value to set into the array | [
"indexed",
"setter",
"for",
"authors",
"-",
"sets",
"an",
"indexed",
"value",
"-",
"The",
"authors",
"of",
"the",
"document",
"O"
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/Header.java#L226-L230 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_networkInterfaceController_mac_mrtg_GET | public ArrayList<OvhMrtgTimestampValue> serviceName_networkInterfaceController_mac_mrtg_GET(String serviceName, String mac, OvhMrtgPeriodEnum period, OvhMrtgTypeEnum type) throws IOException {
String qPath = "/dedicated/server/{serviceName}/networkInterfaceController/{mac}/mrtg";
StringBuilder sb = path(qPath, serviceName, mac);
query(sb, "period", period);
query(sb, "type", type);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t4);
} | java | public ArrayList<OvhMrtgTimestampValue> serviceName_networkInterfaceController_mac_mrtg_GET(String serviceName, String mac, OvhMrtgPeriodEnum period, OvhMrtgTypeEnum type) throws IOException {
String qPath = "/dedicated/server/{serviceName}/networkInterfaceController/{mac}/mrtg";
StringBuilder sb = path(qPath, serviceName, mac);
query(sb, "period", period);
query(sb, "type", type);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t4);
} | [
"public",
"ArrayList",
"<",
"OvhMrtgTimestampValue",
">",
"serviceName_networkInterfaceController_mac_mrtg_GET",
"(",
"String",
"serviceName",
",",
"String",
"mac",
",",
"OvhMrtgPeriodEnum",
"period",
",",
"OvhMrtgTypeEnum",
"type",
")",
"throws",
"IOException",
"{",
"Str... | Retrieve traffic graph values
REST: GET /dedicated/server/{serviceName}/networkInterfaceController/{mac}/mrtg
@param type [required] mrtg type
@param period [required] mrtg period
@param serviceName [required] The internal name of your dedicated server
@param mac [required] NetworkInterfaceController mac
API beta | [
"Retrieve",
"traffic",
"graph",
"values"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L484-L491 |
jbundle/osgi | core/src/main/java/org/jbundle/util/osgi/finder/BaseClassFinderService.java | BaseClassFinderService.findBundleClassLoader | public ClassLoader findBundleClassLoader(String packageName, String versionRange)
{
ClassLoader classLoader = this.getClassLoaderFromBundle(null, packageName, versionRange);
if (classLoader == null) {
Object resource = this.deployThisResource(packageName, versionRange, false);
if (resource != null)
classLoader = this.getClassLoaderFromBundle(resource, packageName, versionRange);
}
return classLoader;
} | java | public ClassLoader findBundleClassLoader(String packageName, String versionRange)
{
ClassLoader classLoader = this.getClassLoaderFromBundle(null, packageName, versionRange);
if (classLoader == null) {
Object resource = this.deployThisResource(packageName, versionRange, false);
if (resource != null)
classLoader = this.getClassLoaderFromBundle(resource, packageName, versionRange);
}
return classLoader;
} | [
"public",
"ClassLoader",
"findBundleClassLoader",
"(",
"String",
"packageName",
",",
"String",
"versionRange",
")",
"{",
"ClassLoader",
"classLoader",
"=",
"this",
".",
"getClassLoaderFromBundle",
"(",
"null",
",",
"packageName",
",",
"versionRange",
")",
";",
"if",... | Get the bundle classloader for this package.
@param string The class name to find the bundle for.
@return The class loader.
@throws ClassNotFoundException | [
"Get",
"the",
"bundle",
"classloader",
"for",
"this",
"package",
"."
] | train | https://github.com/jbundle/osgi/blob/beb02aef78736a4f799aaac001c8f0327bf0536c/core/src/main/java/org/jbundle/util/osgi/finder/BaseClassFinderService.java#L247-L258 |
andi12/msbuild-maven-plugin | msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/MSBuildMojo.java | MSBuildMojo.getOutputName | private String getOutputName() throws MojoExecutionException
{
if ( MSBuildPackaging.isSolution( mavenProject.getPackaging() ) )
{
throw new MojoExecutionException( "Internal error: Cannot determine single output name for a solutions" );
}
String projectFileName = projectFile.getName();
if ( ! projectFileName.contains( "." ) )
{
throw new MojoExecutionException( "Project file name has no extension, please check your configuration" );
}
projectFileName = projectFileName.substring( 0, projectFileName.lastIndexOf( '.' ) );
return projectFileName;
} | java | private String getOutputName() throws MojoExecutionException
{
if ( MSBuildPackaging.isSolution( mavenProject.getPackaging() ) )
{
throw new MojoExecutionException( "Internal error: Cannot determine single output name for a solutions" );
}
String projectFileName = projectFile.getName();
if ( ! projectFileName.contains( "." ) )
{
throw new MojoExecutionException( "Project file name has no extension, please check your configuration" );
}
projectFileName = projectFileName.substring( 0, projectFileName.lastIndexOf( '.' ) );
return projectFileName;
} | [
"private",
"String",
"getOutputName",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"if",
"(",
"MSBuildPackaging",
".",
"isSolution",
"(",
"mavenProject",
".",
"getPackaging",
"(",
")",
")",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"Internal... | Works out the output filename (without the extension) from the project.
@return the name part of output files
@throws MojoExecutionException if called on a solution file or if the project filename has no extension | [
"Works",
"out",
"the",
"output",
"filename",
"(",
"without",
"the",
"extension",
")",
"from",
"the",
"project",
"."
] | train | https://github.com/andi12/msbuild-maven-plugin/blob/224159c15efba20d482f8c630f7947339b1a1b86/msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/MSBuildMojo.java#L63-L76 |
apache/incubator-gobblin | gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/HiveProxyQueryExecutor.java | HiveProxyQueryExecutor.executeQueries | public void executeQueries(List<String> queries, Optional<String> proxy)
throws SQLException {
Preconditions.checkArgument(!this.statementMap.isEmpty(), "No hive connection. Unable to execute queries");
if (!proxy.isPresent()) {
Preconditions.checkArgument(this.statementMap.size() == 1, "Multiple Hive connections. Please specify a user");
proxy = Optional.fromNullable(this.statementMap.keySet().iterator().next());
}
Statement statement = this.statementMap.get(proxy.get());
for (String query : queries) {
statement.execute(query);
}
} | java | public void executeQueries(List<String> queries, Optional<String> proxy)
throws SQLException {
Preconditions.checkArgument(!this.statementMap.isEmpty(), "No hive connection. Unable to execute queries");
if (!proxy.isPresent()) {
Preconditions.checkArgument(this.statementMap.size() == 1, "Multiple Hive connections. Please specify a user");
proxy = Optional.fromNullable(this.statementMap.keySet().iterator().next());
}
Statement statement = this.statementMap.get(proxy.get());
for (String query : queries) {
statement.execute(query);
}
} | [
"public",
"void",
"executeQueries",
"(",
"List",
"<",
"String",
">",
"queries",
",",
"Optional",
"<",
"String",
">",
"proxy",
")",
"throws",
"SQLException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"!",
"this",
".",
"statementMap",
".",
"isEmpty",
"(... | Execute queries.
@param queries the queries
@param proxy the proxy
@throws SQLException the sql exception | [
"Execute",
"queries",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/HiveProxyQueryExecutor.java#L180-L191 |
duracloud/duracloud | security/src/main/java/org/duracloud/security/vote/UserIpLimitsAccessVoter.java | UserIpLimitsAccessVoter.ipInRange | protected boolean ipInRange(String ipAddress, String range) {
IpAddressMatcher addressMatcher = new IpAddressMatcher(range);
return addressMatcher.matches(ipAddress);
} | java | protected boolean ipInRange(String ipAddress, String range) {
IpAddressMatcher addressMatcher = new IpAddressMatcher(range);
return addressMatcher.matches(ipAddress);
} | [
"protected",
"boolean",
"ipInRange",
"(",
"String",
"ipAddress",
",",
"String",
"range",
")",
"{",
"IpAddressMatcher",
"addressMatcher",
"=",
"new",
"IpAddressMatcher",
"(",
"range",
")",
";",
"return",
"addressMatcher",
".",
"matches",
"(",
"ipAddress",
")",
";... | Determines if a given IP address is in the given IP range.
@param ipAddress single IP address
@param range IP address range using CIDR notation
@return true if the address is in the range, false otherwise | [
"Determines",
"if",
"a",
"given",
"IP",
"address",
"is",
"in",
"the",
"given",
"IP",
"range",
"."
] | train | https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/security/src/main/java/org/duracloud/security/vote/UserIpLimitsAccessVoter.java#L138-L141 |
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/DocumentRevisionTree.java | DocumentRevisionTree.lookup | public InternalDocumentRevision lookup(String id, String rev) {
for(DocumentRevisionNode n : sequenceMap.values()) {
if(n.getData().getId().equals(id) && n.getData().getRevision().equals(rev)) {
return n.getData();
}
}
return null;
} | java | public InternalDocumentRevision lookup(String id, String rev) {
for(DocumentRevisionNode n : sequenceMap.values()) {
if(n.getData().getId().equals(id) && n.getData().getRevision().equals(rev)) {
return n.getData();
}
}
return null;
} | [
"public",
"InternalDocumentRevision",
"lookup",
"(",
"String",
"id",
",",
"String",
"rev",
")",
"{",
"for",
"(",
"DocumentRevisionNode",
"n",
":",
"sequenceMap",
".",
"values",
"(",
")",
")",
"{",
"if",
"(",
"n",
".",
"getData",
"(",
")",
".",
"getId",
... | <p>Returns the {@link InternalDocumentRevision} for a document ID and revision ID.</p>
@param id document ID
@param rev revision ID
@return the {@code DocumentRevision} for the document and revision ID | [
"<p",
">",
"Returns",
"the",
"{"
] | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/DocumentRevisionTree.java#L248-L255 |
wisdom-framework/wisdom | extensions/wisdom-monitor/src/main/java/org/wisdom/monitor/extensions/wisdom/RouteModel.java | RouteModel.from | public static ObjectNode from(Route route, Json json) {
return json.newObject().put("url", route.getUrl())
.put("controller", route.getControllerClass().getName())
.put("method", route.getControllerMethod().getName())
.put("http_method", route.getHttpMethod().toString());
} | java | public static ObjectNode from(Route route, Json json) {
return json.newObject().put("url", route.getUrl())
.put("controller", route.getControllerClass().getName())
.put("method", route.getControllerMethod().getName())
.put("http_method", route.getHttpMethod().toString());
} | [
"public",
"static",
"ObjectNode",
"from",
"(",
"Route",
"route",
",",
"Json",
"json",
")",
"{",
"return",
"json",
".",
"newObject",
"(",
")",
".",
"put",
"(",
"\"url\"",
",",
"route",
".",
"getUrl",
"(",
")",
")",
".",
"put",
"(",
"\"controller\"",
"... | Creates the JSON representation of the given route.
@param route the route
@param json the JSON service
@return the json representation | [
"Creates",
"the",
"JSON",
"representation",
"of",
"the",
"given",
"route",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/extensions/wisdom-monitor/src/main/java/org/wisdom/monitor/extensions/wisdom/RouteModel.java#L37-L42 |
looly/hutool | hutool-captcha/src/main/java/cn/hutool/captcha/LineCaptcha.java | LineCaptcha.drawString | private void drawString(Graphics2D g, String code) {
// 抗锯齿
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 创建字体
g.setFont(this.font);
// 文字
int minY = GraphicsUtil.getMinY(g);
if(minY < 0) {
minY = this.height -1;
}
final int len = this.generator.getLength();
int charWidth = width / len;
for (int i = 0; i < len; i++) {
// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
g.setColor(ImgUtil.randomColor());
g.drawString(String.valueOf(code.charAt(i)), i * charWidth, RandomUtil.randomInt(minY, this.height));
}
} | java | private void drawString(Graphics2D g, String code) {
// 抗锯齿
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 创建字体
g.setFont(this.font);
// 文字
int minY = GraphicsUtil.getMinY(g);
if(minY < 0) {
minY = this.height -1;
}
final int len = this.generator.getLength();
int charWidth = width / len;
for (int i = 0; i < len; i++) {
// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
g.setColor(ImgUtil.randomColor());
g.drawString(String.valueOf(code.charAt(i)), i * charWidth, RandomUtil.randomInt(minY, this.height));
}
} | [
"private",
"void",
"drawString",
"(",
"Graphics2D",
"g",
",",
"String",
"code",
")",
"{",
"// 抗锯齿\r",
"g",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_ANTIALIASING",
",",
"RenderingHints",
".",
"VALUE_ANTIALIAS_ON",
")",
";",
"// 创建字体\r",
"g",
".",... | 绘制字符串
@param g {@link Graphics2D}画笔
@param random 随机对象
@param code 验证码 | [
"绘制字符串"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-captcha/src/main/java/cn/hutool/captcha/LineCaptcha.java#L71-L90 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java | ByteUtils.intsToBytes | public static final void intsToBytes( byte[] dst, int dst_offset, int[] src, int src_offset, int length ) {
if ((src == null) || (dst == null) || ((dst_offset + length) > dst.length) || ((src_offset + length) > (src.length * 4))
|| ((src_offset % 4) != 0) || ((length % 4) != 0)) {
croak("intsToBytes parameters are invalid:" + " src=" + Arrays.toString(src) + " dst=" + Arrays.toString(dst)
+ " (dst_offset=" + dst_offset + " + length=" + length + ")=" + (dst_offset + length) + " > dst.length="
+ ((dst == null) ? 0 : dst.length) + " (src_offset=" + src_offset + " + length=" + length + ")="
+ (src_offset + length) + " > (src.length=" + ((src == null) ? 0 : src.length) + "*4)="
+ ((src == null) ? 0 : (src.length * 4)) + " (src_offset=" + src_offset + " % 4)=" + (src_offset % 4)
+ " != 0" + " (length=" + length + " % 4)=" + (length % 4) + " != 0");
}
// Convert parameters to normal format
int[] offset = new int[1];
offset[0] = dst_offset;
int int_src_offset = src_offset / 4;
for( int i = 0; i < (length / 4); ++i ) {
intToBytes(src[int_src_offset++], dst, offset);
}
} | java | public static final void intsToBytes( byte[] dst, int dst_offset, int[] src, int src_offset, int length ) {
if ((src == null) || (dst == null) || ((dst_offset + length) > dst.length) || ((src_offset + length) > (src.length * 4))
|| ((src_offset % 4) != 0) || ((length % 4) != 0)) {
croak("intsToBytes parameters are invalid:" + " src=" + Arrays.toString(src) + " dst=" + Arrays.toString(dst)
+ " (dst_offset=" + dst_offset + " + length=" + length + ")=" + (dst_offset + length) + " > dst.length="
+ ((dst == null) ? 0 : dst.length) + " (src_offset=" + src_offset + " + length=" + length + ")="
+ (src_offset + length) + " > (src.length=" + ((src == null) ? 0 : src.length) + "*4)="
+ ((src == null) ? 0 : (src.length * 4)) + " (src_offset=" + src_offset + " % 4)=" + (src_offset % 4)
+ " != 0" + " (length=" + length + " % 4)=" + (length % 4) + " != 0");
}
// Convert parameters to normal format
int[] offset = new int[1];
offset[0] = dst_offset;
int int_src_offset = src_offset / 4;
for( int i = 0; i < (length / 4); ++i ) {
intToBytes(src[int_src_offset++], dst, offset);
}
} | [
"public",
"static",
"final",
"void",
"intsToBytes",
"(",
"byte",
"[",
"]",
"dst",
",",
"int",
"dst_offset",
",",
"int",
"[",
"]",
"src",
",",
"int",
"src_offset",
",",
"int",
"length",
")",
"{",
"if",
"(",
"(",
"src",
"==",
"null",
")",
"||",
"(",
... | Convert an array of <code>int</code>s into an array of
<code>bytes</code>.
@param dst the array to write
@param dst_offset the start offset in <code>dst</code>
@param src the array to read
@param src_offset the start offset in <code>src</code>, times 4. This
measures the offset as if <code>src</code> were an array of
<code>byte</code>s (rather than <code>int</code>s).
@param length the number of <code>byte</code>s to copy. | [
"Convert",
"an",
"array",
"of",
"<code",
">",
"int<",
"/",
"code",
">",
"s",
"into",
"an",
"array",
"of",
"<code",
">",
"bytes<",
"/",
"code",
">",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java#L435-L455 |
EasyinnovaSL/Tiff-Library-4J | src/main/java/com/easyinnova/tiff/model/IfdTags.java | IfdTags.addTag | public void addTag(String tagName, String tagValue) {
int id = TiffTags.getTagId(tagName);
TagValue tag = new TagValue(id, 2);
for (int i = 0; i < tagValue.length(); i++) {
int val = tagValue.charAt(i);
if (val > 127) val = 0;
Ascii cha = new Ascii(val);
tag.add(cha);
}
Ascii chaf = new Ascii(0);
tag.add(chaf);
addTag(tag);
} | java | public void addTag(String tagName, String tagValue) {
int id = TiffTags.getTagId(tagName);
TagValue tag = new TagValue(id, 2);
for (int i = 0; i < tagValue.length(); i++) {
int val = tagValue.charAt(i);
if (val > 127) val = 0;
Ascii cha = new Ascii(val);
tag.add(cha);
}
Ascii chaf = new Ascii(0);
tag.add(chaf);
addTag(tag);
} | [
"public",
"void",
"addTag",
"(",
"String",
"tagName",
",",
"String",
"tagValue",
")",
"{",
"int",
"id",
"=",
"TiffTags",
".",
"getTagId",
"(",
"tagName",
")",
";",
"TagValue",
"tag",
"=",
"new",
"TagValue",
"(",
"id",
",",
"2",
")",
";",
"for",
"(",
... | Adds the tag.
@param tagName the tag name
@param tagValue the tag value | [
"Adds",
"the",
"tag",
"."
] | train | https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/model/IfdTags.java#L108-L120 |
elki-project/elki | elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java | DBIDUtil.randomSampleExcept | public static ModifiableDBIDs randomSampleExcept(DBIDs source, DBIDRef except, int k, RandomFactory rnd) {
return randomSampleExcept(source, except, k, rnd.getSingleThreadedRandom());
} | java | public static ModifiableDBIDs randomSampleExcept(DBIDs source, DBIDRef except, int k, RandomFactory rnd) {
return randomSampleExcept(source, except, k, rnd.getSingleThreadedRandom());
} | [
"public",
"static",
"ModifiableDBIDs",
"randomSampleExcept",
"(",
"DBIDs",
"source",
",",
"DBIDRef",
"except",
",",
"int",
"k",
",",
"RandomFactory",
"rnd",
")",
"{",
"return",
"randomSampleExcept",
"(",
"source",
",",
"except",
",",
"k",
",",
"rnd",
".",
"g... | Produce a random sample of the given DBIDs.
@param source Original DBIDs, no duplicates allowed
@param except Excluded object
@param k k Parameter
@param rnd Random generator
@return new DBIDs | [
"Produce",
"a",
"random",
"sample",
"of",
"the",
"given",
"DBIDs",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java#L586-L588 |
martinpaljak/apdu4j | src/main/java/apdu4j/remote/RemoteTerminal.java | RemoteTerminal.decrypt | public Button decrypt(String message, byte[] apdu) throws IOException, UserCancelExcption{
Map<String, Object> m = JSONProtocol.cmd("decrypt");
m.put("text", message);
m.put("bytes", HexUtils.bin2hex(apdu));
pipe.send(m);
Map<String, Object> r = pipe.recv();
if (JSONProtocol.check(m, r)) {
return Button.valueOf(((String)r.get("button")).toUpperCase());
} else {
throw new IOException("Unknown button pressed");
}
} | java | public Button decrypt(String message, byte[] apdu) throws IOException, UserCancelExcption{
Map<String, Object> m = JSONProtocol.cmd("decrypt");
m.put("text", message);
m.put("bytes", HexUtils.bin2hex(apdu));
pipe.send(m);
Map<String, Object> r = pipe.recv();
if (JSONProtocol.check(m, r)) {
return Button.valueOf(((String)r.get("button")).toUpperCase());
} else {
throw new IOException("Unknown button pressed");
}
} | [
"public",
"Button",
"decrypt",
"(",
"String",
"message",
",",
"byte",
"[",
"]",
"apdu",
")",
"throws",
"IOException",
",",
"UserCancelExcption",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"m",
"=",
"JSONProtocol",
".",
"cmd",
"(",
"\"decrypt\"",
")",
... | Shows the response of the APDU to the user.
Normally this requires the verification of a PIN code beforehand.
@param message text to display to the user
@param apdu APDU to send to the terminal
@return {@link Button} that was pressed by the user
@throws IOException when communication fails | [
"Shows",
"the",
"response",
"of",
"the",
"APDU",
"to",
"the",
"user",
"."
] | train | https://github.com/martinpaljak/apdu4j/blob/dca977bfa9e4fa236a9a7b87a2a09e5472ea9969/src/main/java/apdu4j/remote/RemoteTerminal.java#L154-L165 |
GenesysPureEngage/authentication-client-java | src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java | AuthenticationApi.signInAsync | public com.squareup.okhttp.Call signInAsync(String username, String password, Boolean saml, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = signInValidateBeforeCall(username, password, saml, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
} | java | public com.squareup.okhttp.Call signInAsync(String username, String password, Boolean saml, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = signInValidateBeforeCall(username, password, saml, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"signInAsync",
"(",
"String",
"username",
",",
"String",
"password",
",",
"Boolean",
"saml",
",",
"final",
"ApiCallback",
"<",
"Void",
">",
"callback",
")",
"throws",
"ApiException",
"{",
"Progres... | Perform form-based authentication. (asynchronously)
Perform form-based authentication by submitting an agent's username and password.
@param username The agent's username, formatted as 'tenant\\username'. (required)
@param password The agent's password. (required)
@param saml Specifies whether to login using [Security Assertion Markup Language](https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language) (SAML). (optional)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object | [
"Perform",
"form",
"-",
"based",
"authentication",
".",
"(",
"asynchronously",
")",
"Perform",
"form",
"-",
"based",
"authentication",
"by",
"submitting",
"an",
"agent'",
";",
"s",
"username",
"and",
"password",
"."
] | train | https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java#L1227-L1251 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ResourceBundle.java | ResourceBundle.getBundle | public static ResourceBundle getBundle(String baseName, ResourceBundle.Control control) {
return getBundle(baseName, Locale.getDefault(), getLoader(), control);
} | java | public static ResourceBundle getBundle(String baseName, ResourceBundle.Control control) {
return getBundle(baseName, Locale.getDefault(), getLoader(), control);
} | [
"public",
"static",
"ResourceBundle",
"getBundle",
"(",
"String",
"baseName",
",",
"ResourceBundle",
".",
"Control",
"control",
")",
"{",
"return",
"getBundle",
"(",
"baseName",
",",
"Locale",
".",
"getDefault",
"(",
")",
",",
"getLoader",
"(",
")",
",",
"co... | Finds the named resource bundle for the specified base name and control.
@param baseName
the base name of a resource bundle
@param control
the control that control the access sequence
@return the named resource bundle
@since 1.6 | [
"Finds",
"the",
"named",
"resource",
"bundle",
"for",
"the",
"specified",
"base",
"name",
"and",
"control",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ResourceBundle.java#L252-L254 |
square/phrase | src/main/java/com/squareup/phrase/Phrase.java | Phrase.from | public static Phrase from(Context c, @StringRes int patternResourceId) {
return from(c.getResources(), patternResourceId);
} | java | public static Phrase from(Context c, @StringRes int patternResourceId) {
return from(c.getResources(), patternResourceId);
} | [
"public",
"static",
"Phrase",
"from",
"(",
"Context",
"c",
",",
"@",
"StringRes",
"int",
"patternResourceId",
")",
"{",
"return",
"from",
"(",
"c",
".",
"getResources",
"(",
")",
",",
"patternResourceId",
")",
";",
"}"
] | Entry point into this API.
@throws IllegalArgumentException if pattern contains any syntax errors. | [
"Entry",
"point",
"into",
"this",
"API",
"."
] | train | https://github.com/square/phrase/blob/d91f18e80790832db11b811c462f8e5cd492d97e/src/main/java/com/squareup/phrase/Phrase.java#L96-L98 |
eyp/serfj | src/main/java/net/sf/serfj/RestController.java | RestController.renderPage | public void renderPage(String resource, String page) throws IOException {
this.response.renderPage(resource, page);
} | java | public void renderPage(String resource, String page) throws IOException {
this.response.renderPage(resource, page);
} | [
"public",
"void",
"renderPage",
"(",
"String",
"resource",
",",
"String",
"page",
")",
"throws",
"IOException",
"{",
"this",
".",
"response",
".",
"renderPage",
"(",
"resource",
",",
"page",
")",
";",
"}"
] | 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/RestController.java#L176-L178 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/nio/ClassLoaderUtil.java | ClassLoaderUtil.getOrCreate | public static <T> T getOrCreate(T instance, ClassLoader classLoader, String className) {
if (instance != null) {
return instance;
} else if (className != null) {
try {
return ClassLoaderUtil.newInstance(classLoader, className);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
} else {
return null;
}
} | java | public static <T> T getOrCreate(T instance, ClassLoader classLoader, String className) {
if (instance != null) {
return instance;
} else if (className != null) {
try {
return ClassLoaderUtil.newInstance(classLoader, className);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
} else {
return null;
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getOrCreate",
"(",
"T",
"instance",
",",
"ClassLoader",
"classLoader",
",",
"String",
"className",
")",
"{",
"if",
"(",
"instance",
"!=",
"null",
")",
"{",
"return",
"instance",
";",
"}",
"else",
"if",
"(",
"cla... | Returns the {@code instance}, if not null, or constructs a new instance of the class using
{@link #newInstance(ClassLoader, String)}.
@param instance the instance of the class, can be null
@param classLoader the classloader used for class instantiation
@param className the name of the class being constructed. If null, null is returned.
@return the provided {@code instance} or a newly constructed instance of {@code className}
or null, if {@code className} was null | [
"Returns",
"the",
"{",
"@code",
"instance",
"}",
"if",
"not",
"null",
"or",
"constructs",
"a",
"new",
"instance",
"of",
"the",
"class",
"using",
"{",
"@link",
"#newInstance",
"(",
"ClassLoader",
"String",
")",
"}",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/nio/ClassLoaderUtil.java#L89-L101 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/app/ActivityUtils.java | ActivityUtils.findViewById | @SuppressWarnings("unchecked") // we know that return value type is a child of view, and V is bound to a child of view.
public static <V extends View> V findViewById(Activity activity, int id) {
return (V) activity.findViewById(id);
} | java | @SuppressWarnings("unchecked") // we know that return value type is a child of view, and V is bound to a child of view.
public static <V extends View> V findViewById(Activity activity, int id) {
return (V) activity.findViewById(id);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"// we know that return value type is a child of view, and V is bound to a child of view.",
"public",
"static",
"<",
"V",
"extends",
"View",
">",
"V",
"findViewById",
"(",
"Activity",
"activity",
",",
"int",
"id",
")",
"... | Find the specific view from the activity.
Returning value type is bound to your variable type.
@param activity the activity.
@param id the view id.
@param <V> the view class type parameter.
@return the view, null if not found. | [
"Find",
"the",
"specific",
"view",
"from",
"the",
"activity",
".",
"Returning",
"value",
"type",
"is",
"bound",
"to",
"your",
"variable",
"type",
"."
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/app/ActivityUtils.java#L23-L26 |
dodie/scott | scott/src/main/java/hu/advancedweb/scott/instrumentation/transformation/ScopeExtractorMethodVisitor.java | ScopeExtractorMethodVisitor.getTryFixedEndLabel | private Label getTryFixedEndLabel(LocalVariableScopeData scope, TryCatchBlockLabels enclosingTry) {
if (enclosingTry == null) {
return scope.labels.end;
} else {
if (getIndex(enclosingTry.handler) < getIndex(scope.labels.end)) {
return enclosingTry.handler;
} else {
return scope.labels.end;
}
}
} | java | private Label getTryFixedEndLabel(LocalVariableScopeData scope, TryCatchBlockLabels enclosingTry) {
if (enclosingTry == null) {
return scope.labels.end;
} else {
if (getIndex(enclosingTry.handler) < getIndex(scope.labels.end)) {
return enclosingTry.handler;
} else {
return scope.labels.end;
}
}
} | [
"private",
"Label",
"getTryFixedEndLabel",
"(",
"LocalVariableScopeData",
"scope",
",",
"TryCatchBlockLabels",
"enclosingTry",
")",
"{",
"if",
"(",
"enclosingTry",
"==",
"null",
")",
"{",
"return",
"scope",
".",
"labels",
".",
"end",
";",
"}",
"else",
"{",
"if... | The initially recorded variable scopes in try blocks has wrong end line numbers.
They are pointing to the end of the catch blocks, even if they were declared in
the try block. This method calculates the correct end Label for a variable scope.
Fix for issue #14. | [
"The",
"initially",
"recorded",
"variable",
"scopes",
"in",
"try",
"blocks",
"has",
"wrong",
"end",
"line",
"numbers",
".",
"They",
"are",
"pointing",
"to",
"the",
"end",
"of",
"the",
"catch",
"blocks",
"even",
"if",
"they",
"were",
"declared",
"in",
"the"... | train | https://github.com/dodie/scott/blob/fd6b492584d3ae7e072871ff2b094cce6041fc99/scott/src/main/java/hu/advancedweb/scott/instrumentation/transformation/ScopeExtractorMethodVisitor.java#L208-L218 |
box/box-java-sdk | src/main/java/com/box/sdk/MetadataTemplate.java | MetadataTemplate.getMetadataTemplate | public static MetadataTemplate getMetadataTemplate(BoxAPIConnection api, String templateName) {
String scope = scopeBasedOnType(templateName);
return getMetadataTemplate(api, templateName, scope);
} | java | public static MetadataTemplate getMetadataTemplate(BoxAPIConnection api, String templateName) {
String scope = scopeBasedOnType(templateName);
return getMetadataTemplate(api, templateName, scope);
} | [
"public",
"static",
"MetadataTemplate",
"getMetadataTemplate",
"(",
"BoxAPIConnection",
"api",
",",
"String",
"templateName",
")",
"{",
"String",
"scope",
"=",
"scopeBasedOnType",
"(",
"templateName",
")",
";",
"return",
"getMetadataTemplate",
"(",
"api",
",",
"temp... | Gets the metadata template of specified template type.
@param api the API connection to be used.
@param templateName the metadata template type name.
@return the metadata template returned from the server. | [
"Gets",
"the",
"metadata",
"template",
"of",
"specified",
"template",
"type",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/MetadataTemplate.java#L428-L431 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/code/Scope.java | Scope.dup | public Scope dup(Symbol newOwner) {
Scope result = new Scope(this, newOwner, this.table, this.nelems);
shared++;
// System.out.println("====> duping scope " + this.hashCode() + " owned by " + newOwner + " to " + result.hashCode());
// new Error().printStackTrace(System.out);
return result;
} | java | public Scope dup(Symbol newOwner) {
Scope result = new Scope(this, newOwner, this.table, this.nelems);
shared++;
// System.out.println("====> duping scope " + this.hashCode() + " owned by " + newOwner + " to " + result.hashCode());
// new Error().printStackTrace(System.out);
return result;
} | [
"public",
"Scope",
"dup",
"(",
"Symbol",
"newOwner",
")",
"{",
"Scope",
"result",
"=",
"new",
"Scope",
"(",
"this",
",",
"newOwner",
",",
"this",
".",
"table",
",",
"this",
".",
"nelems",
")",
";",
"shared",
"++",
";",
"// System.out.println(\"====> duping... | Construct a fresh scope within this scope, with new owner,
which shares its table with the outer scope. Used in connection with
method leave if scope access is stack-like in order to avoid allocation
of fresh tables. | [
"Construct",
"a",
"fresh",
"scope",
"within",
"this",
"scope",
"with",
"new",
"owner",
"which",
"shares",
"its",
"table",
"with",
"the",
"outer",
"scope",
".",
"Used",
"in",
"connection",
"with",
"method",
"leave",
"if",
"scope",
"access",
"is",
"stack",
"... | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/code/Scope.java#L131-L137 |
TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/HandshakeReader.java | HandshakeReader.validateUpgrade | private void validateUpgrade(StatusLine statusLine, Map<String, List<String>> headers) throws WebSocketException
{
// Get the values of Upgrade.
List<String> values = headers.get("Upgrade");
if (values == null || values.size() == 0)
{
// The opening handshake response does not contain 'Upgrade' header.
throw new OpeningHandshakeException(
WebSocketError.NO_UPGRADE_HEADER,
"The opening handshake response does not contain 'Upgrade' header.",
statusLine, headers);
}
for (String value : values)
{
// Split the value of Upgrade header into elements.
String[] elements = value.split("\\s*,\\s*");
for (String element : elements)
{
if ("websocket".equalsIgnoreCase(element))
{
// Found 'websocket' in Upgrade header.
return;
}
}
}
// 'websocket' was not found in 'Upgrade' header.
throw new OpeningHandshakeException(
WebSocketError.NO_WEBSOCKET_IN_UPGRADE_HEADER,
"'websocket' was not found in 'Upgrade' header.",
statusLine, headers);
} | java | private void validateUpgrade(StatusLine statusLine, Map<String, List<String>> headers) throws WebSocketException
{
// Get the values of Upgrade.
List<String> values = headers.get("Upgrade");
if (values == null || values.size() == 0)
{
// The opening handshake response does not contain 'Upgrade' header.
throw new OpeningHandshakeException(
WebSocketError.NO_UPGRADE_HEADER,
"The opening handshake response does not contain 'Upgrade' header.",
statusLine, headers);
}
for (String value : values)
{
// Split the value of Upgrade header into elements.
String[] elements = value.split("\\s*,\\s*");
for (String element : elements)
{
if ("websocket".equalsIgnoreCase(element))
{
// Found 'websocket' in Upgrade header.
return;
}
}
}
// 'websocket' was not found in 'Upgrade' header.
throw new OpeningHandshakeException(
WebSocketError.NO_WEBSOCKET_IN_UPGRADE_HEADER,
"'websocket' was not found in 'Upgrade' header.",
statusLine, headers);
} | [
"private",
"void",
"validateUpgrade",
"(",
"StatusLine",
"statusLine",
",",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"headers",
")",
"throws",
"WebSocketException",
"{",
"// Get the values of Upgrade.",
"List",
"<",
"String",
">",
"values",
"=... | Validate the value of {@code Upgrade} header.
<blockquote>
<p>From RFC 6455, p19.</p>
<p><i>
If the response lacks an {@code Upgrade} header field or the {@code Upgrade}
header field contains a value that is not an ASCII case-insensitive match for
the value "websocket", the client MUST Fail the WebSocket Connection.
</i></p>
</blockquote> | [
"Validate",
"the",
"value",
"of",
"{",
"@code",
"Upgrade",
"}",
"header",
"."
] | train | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/HandshakeReader.java#L300-L334 |
elki-project/elki | elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/AbstractMTreeNode.java | AbstractMTreeNode.coveringRadiusFromEntries | public double coveringRadiusFromEntries(DBID routingObjectID, AbstractMTree<O, N, E, ?> mTree) {
double coveringRadius = 0.;
for(int i = 0; i < getNumEntries(); i++) {
E entry = getEntry(i);
final double cover = entry.getParentDistance() + entry.getCoveringRadius();
coveringRadius = coveringRadius < cover ? cover : coveringRadius;
}
return coveringRadius;
} | java | public double coveringRadiusFromEntries(DBID routingObjectID, AbstractMTree<O, N, E, ?> mTree) {
double coveringRadius = 0.;
for(int i = 0; i < getNumEntries(); i++) {
E entry = getEntry(i);
final double cover = entry.getParentDistance() + entry.getCoveringRadius();
coveringRadius = coveringRadius < cover ? cover : coveringRadius;
}
return coveringRadius;
} | [
"public",
"double",
"coveringRadiusFromEntries",
"(",
"DBID",
"routingObjectID",
",",
"AbstractMTree",
"<",
"O",
",",
"N",
",",
"E",
",",
"?",
">",
"mTree",
")",
"{",
"double",
"coveringRadius",
"=",
"0.",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i... | Determines and returns the covering radius of this node.
@param routingObjectID the object id of the routing object of this node
@param mTree the M-Tree
@return the covering radius of this node | [
"Determines",
"and",
"returns",
"the",
"covering",
"radius",
"of",
"this",
"node",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/AbstractMTreeNode.java#L86-L94 |
unbescape/unbescape | src/main/java/org/unbescape/uri/UriEscape.java | UriEscape.unescapeUriQueryParam | public static void unescapeUriQueryParam(final Reader reader, final Writer writer, final String encoding)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
UriEscapeUtil.unescape(reader, writer, UriEscapeUtil.UriEscapeType.QUERY_PARAM, encoding);
} | java | public static void unescapeUriQueryParam(final Reader reader, final Writer writer, final String encoding)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
UriEscapeUtil.unescape(reader, writer, UriEscapeUtil.UriEscapeType.QUERY_PARAM, encoding);
} | [
"public",
"static",
"void",
"unescapeUriQueryParam",
"(",
"final",
"Reader",
"reader",
",",
"final",
"Writer",
"writer",
",",
"final",
"String",
"encoding",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"Ille... | <p>
Perform am URI query parameter (name or value) <strong>unescape</strong> operation
on a <tt>Reader</tt> input, writing results to a <tt>Writer</tt>.
</p>
<p>
This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input,
even for those characters that do not need to be percent-encoded in this context (unreserved characters
can be percent-encoded even if/when this is not required, though it is not generally considered a
good practice).
</p>
<p>
This method will use specified <tt>encoding</tt> in order to determine the characters specified in the
percent-encoded byte sequences.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param reader the <tt>Reader</tt> reading the text to be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@param encoding the encoding to be used for unescaping.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"am",
"URI",
"query",
"parameter",
"(",
"name",
"or",
"value",
")",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"Reader<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L2295-L2308 |
prestodb/presto | presto-main/src/main/java/com/facebook/presto/operator/scalar/ColorFunctions.java | ColorFunctions.toAnsi | private static int toAnsi(int red, int green, int blue)
{
// rescale to 0-5 range
red = red * 6 / 256;
green = green * 6 / 256;
blue = blue * 6 / 256;
return 16 + red * 36 + green * 6 + blue;
} | java | private static int toAnsi(int red, int green, int blue)
{
// rescale to 0-5 range
red = red * 6 / 256;
green = green * 6 / 256;
blue = blue * 6 / 256;
return 16 + red * 36 + green * 6 + blue;
} | [
"private",
"static",
"int",
"toAnsi",
"(",
"int",
"red",
",",
"int",
"green",
",",
"int",
"blue",
")",
"{",
"// rescale to 0-5 range",
"red",
"=",
"red",
"*",
"6",
"/",
"256",
";",
"green",
"=",
"green",
"*",
"6",
"/",
"256",
";",
"blue",
"=",
"blu... | Convert the given color (rgb or system) to an ansi-compatible index (for use with ESC[38;5;<value>m) | [
"Convert",
"the",
"given",
"color",
"(",
"rgb",
"or",
"system",
")",
"to",
"an",
"ansi",
"-",
"compatible",
"index",
"(",
"for",
"use",
"with",
"ESC",
"[",
"38",
";",
"5",
";",
"<value",
">",
"m",
")"
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/operator/scalar/ColorFunctions.java#L249-L257 |
gallandarakhneorg/afc | core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d1/Transform1D.java | Transform1D.setPath | public void setPath(List<? extends S> path, Direction1D direction) {
this.path = path == null || path.isEmpty() ? null : new ArrayList<>(path);
this.firstSegmentDirection = detectFirstSegmentDirection(direction);
} | java | public void setPath(List<? extends S> path, Direction1D direction) {
this.path = path == null || path.isEmpty() ? null : new ArrayList<>(path);
this.firstSegmentDirection = detectFirstSegmentDirection(direction);
} | [
"public",
"void",
"setPath",
"(",
"List",
"<",
"?",
"extends",
"S",
">",
"path",
",",
"Direction1D",
"direction",
")",
"{",
"this",
".",
"path",
"=",
"path",
"==",
"null",
"||",
"path",
".",
"isEmpty",
"(",
")",
"?",
"null",
":",
"new",
"ArrayList",
... | Set the path used by this transformation.
@param path is the new path
@param direction is the direction to follow on the path if the path contains only one segment. | [
"Set",
"the",
"path",
"used",
"by",
"this",
"transformation",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d1/Transform1D.java#L254-L257 |
ist-dresden/composum | sling/core/commons/src/main/java/com/composum/sling/core/event/AbstractChangeObserver.java | AbstractChangeObserver.getContentNode | protected Node getContentNode(Session session, String path)
throws RepositoryException {
Node node = null;
try {
Item item = session.getItem(path);
if (item.isNode()) {
node = (Node) item;
} else {
node = item.getParent();
}
while (node != null
&& !isTargetNode(node)
&& (path = getTargetPath(node)) != null) {
node = node.getParent();
}
} catch (PathNotFoundException ignore) {
// probably removed... ignore
}
return path != null ? node : null;
} | java | protected Node getContentNode(Session session, String path)
throws RepositoryException {
Node node = null;
try {
Item item = session.getItem(path);
if (item.isNode()) {
node = (Node) item;
} else {
node = item.getParent();
}
while (node != null
&& !isTargetNode(node)
&& (path = getTargetPath(node)) != null) {
node = node.getParent();
}
} catch (PathNotFoundException ignore) {
// probably removed... ignore
}
return path != null ? node : null;
} | [
"protected",
"Node",
"getContentNode",
"(",
"Session",
"session",
",",
"String",
"path",
")",
"throws",
"RepositoryException",
"{",
"Node",
"node",
"=",
"null",
";",
"try",
"{",
"Item",
"item",
"=",
"session",
".",
"getItem",
"(",
"path",
")",
";",
"if",
... | determines the target node (the node to perform the change) of one event item | [
"determines",
"the",
"target",
"node",
"(",
"the",
"node",
"to",
"perform",
"the",
"change",
")",
"of",
"one",
"event",
"item"
] | train | https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/event/AbstractChangeObserver.java#L255-L274 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java | ArrayFunctions.arrayPrepend | public static Expression arrayPrepend(String expression, Expression value) {
return arrayPrepend(x(expression), value);
} | java | public static Expression arrayPrepend(String expression, Expression value) {
return arrayPrepend(x(expression), value);
} | [
"public",
"static",
"Expression",
"arrayPrepend",
"(",
"String",
"expression",
",",
"Expression",
"value",
")",
"{",
"return",
"arrayPrepend",
"(",
"x",
"(",
"expression",
")",
",",
"value",
")",
";",
"}"
] | Returned expression results in the new array with value pre-pended. | [
"Returned",
"expression",
"results",
"in",
"the",
"new",
"array",
"with",
"value",
"pre",
"-",
"pended",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L289-L291 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java | FileUtil.readLines | public static <T extends Collection<String>> T readLines(File file, String charset, T collection) throws IORuntimeException {
return FileReader.create(file, CharsetUtil.charset(charset)).readLines(collection);
} | java | public static <T extends Collection<String>> T readLines(File file, String charset, T collection) throws IORuntimeException {
return FileReader.create(file, CharsetUtil.charset(charset)).readLines(collection);
} | [
"public",
"static",
"<",
"T",
"extends",
"Collection",
"<",
"String",
">",
">",
"T",
"readLines",
"(",
"File",
"file",
",",
"String",
"charset",
",",
"T",
"collection",
")",
"throws",
"IORuntimeException",
"{",
"return",
"FileReader",
".",
"create",
"(",
"... | 从文件中读取每一行数据
@param <T> 集合类型
@param file 文件路径
@param charset 字符集
@param collection 集合
@return 文件中的每行内容的集合
@throws IORuntimeException IO异常 | [
"从文件中读取每一行数据"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L2220-L2222 |
codelibs/fess | src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java | FessMessages.addConstraintsEanMessage | public FessMessages addConstraintsEanMessage(String property, String type) {
assertPropertyNotNull(property);
add(property, new UserMessage(CONSTRAINTS_EAN_MESSAGE, type));
return this;
} | java | public FessMessages addConstraintsEanMessage(String property, String type) {
assertPropertyNotNull(property);
add(property, new UserMessage(CONSTRAINTS_EAN_MESSAGE, type));
return this;
} | [
"public",
"FessMessages",
"addConstraintsEanMessage",
"(",
"String",
"property",
",",
"String",
"type",
")",
"{",
"assertPropertyNotNull",
"(",
"property",
")",
";",
"add",
"(",
"property",
",",
"new",
"UserMessage",
"(",
"CONSTRAINTS_EAN_MESSAGE",
",",
"type",
")... | Add the created action message for the key 'constraints.EAN.message' with parameters.
<pre>
message: {item} is invalid {type} barcode.
</pre>
@param property The property name for the message. (NotNull)
@param type The parameter type for message. (NotNull)
@return this. (NotNull) | [
"Add",
"the",
"created",
"action",
"message",
"for",
"the",
"key",
"constraints",
".",
"EAN",
".",
"message",
"with",
"parameters",
".",
"<pre",
">",
"message",
":",
"{",
"item",
"}",
"is",
"invalid",
"{",
"type",
"}",
"barcode",
".",
"<",
"/",
"pre",
... | train | https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L814-L818 |
apache/flink | flink-connectors/flink-connector-kafka-0.8/src/main/java/org/apache/flink/streaming/connectors/kafka/internals/SimpleConsumerThread.java | SimpleConsumerThread.requestAndSetSpecificTimeOffsetsFromKafka | private static void requestAndSetSpecificTimeOffsetsFromKafka(
SimpleConsumer consumer,
List<KafkaTopicPartitionState<TopicAndPartition>> partitions,
long whichTime) throws IOException {
Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<>();
for (KafkaTopicPartitionState<TopicAndPartition> part : partitions) {
requestInfo.put(part.getKafkaPartitionHandle(), new PartitionOffsetRequestInfo(whichTime, 1));
}
requestAndSetOffsetsFromKafka(consumer, partitions, requestInfo);
} | java | private static void requestAndSetSpecificTimeOffsetsFromKafka(
SimpleConsumer consumer,
List<KafkaTopicPartitionState<TopicAndPartition>> partitions,
long whichTime) throws IOException {
Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<>();
for (KafkaTopicPartitionState<TopicAndPartition> part : partitions) {
requestInfo.put(part.getKafkaPartitionHandle(), new PartitionOffsetRequestInfo(whichTime, 1));
}
requestAndSetOffsetsFromKafka(consumer, partitions, requestInfo);
} | [
"private",
"static",
"void",
"requestAndSetSpecificTimeOffsetsFromKafka",
"(",
"SimpleConsumer",
"consumer",
",",
"List",
"<",
"KafkaTopicPartitionState",
"<",
"TopicAndPartition",
">",
">",
"partitions",
",",
"long",
"whichTime",
")",
"throws",
"IOException",
"{",
"Map... | Request offsets before a specific time for a set of partitions, via a Kafka consumer.
@param consumer The consumer connected to lead broker
@param partitions The list of partitions we need offsets for
@param whichTime The type of time we are requesting. -1 and -2 are special constants (See OffsetRequest) | [
"Request",
"offsets",
"before",
"a",
"specific",
"time",
"for",
"a",
"set",
"of",
"partitions",
"via",
"a",
"Kafka",
"consumer",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kafka-0.8/src/main/java/org/apache/flink/streaming/connectors/kafka/internals/SimpleConsumerThread.java#L442-L452 |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/xml/XmlPath.java | XmlPath.evaluate | public static String evaluate(XmlObject xmlbean, String path) {
XmlCursor cursor = xmlbean.newCursor();
String value;
// 1.2.3. use XQuery or selectPath
//
// cursor.toFirstChild();
// String defaultNamespace = cursor.namespaceForPrefix("");
// String namespaceDecl = "declare default element namespace '" + defaultNamespace + "';";
// Map<String,String> namespaces = new HashMap<String,String>();
// cursor.getAllNamespaces(namespaces);
// for (String prefix : namespaces.keySet())
// {
// namespaceDecl += "declare namespace " + prefix + "='" + namespaces.get(prefix) + "';";
// }
// 1. use XQuery
// XmlCursor results = cursor.execQuery(namespaceDecl + path);
// value = (results==null)?null:results.getTextValue();
// 2. use selectPath on XmlObject
// XmlObject[] result = xmlbean.selectPath(namespaceDecl + path);
// 3. use selectPath on XmlCursor
// cursor.toParent();
// XmlOptions options = new XmlOptions();
// options.put(Path.PATH_DELEGATE_INTERFACE,"org.apache.xmlbeans.impl.xpath.saxon.XBeansXPath");
// cursor.selectPath(namespaceDecl + path, options);
// if (cursor.getSelectionCount()>0) {
// cursor.toNextSelection();
// value = cursor.getTextValue();
// } else value = null;
// 4. use our own implementation
try {
XmlPath matcher = new XmlPath(path);
value = matcher.evaluate_segment(cursor, matcher.path_seg);
} catch (XmlException e) {
value = null; // xpath syntax error - treated as no match
}
cursor.dispose();
return value;
} | java | public static String evaluate(XmlObject xmlbean, String path) {
XmlCursor cursor = xmlbean.newCursor();
String value;
// 1.2.3. use XQuery or selectPath
//
// cursor.toFirstChild();
// String defaultNamespace = cursor.namespaceForPrefix("");
// String namespaceDecl = "declare default element namespace '" + defaultNamespace + "';";
// Map<String,String> namespaces = new HashMap<String,String>();
// cursor.getAllNamespaces(namespaces);
// for (String prefix : namespaces.keySet())
// {
// namespaceDecl += "declare namespace " + prefix + "='" + namespaces.get(prefix) + "';";
// }
// 1. use XQuery
// XmlCursor results = cursor.execQuery(namespaceDecl + path);
// value = (results==null)?null:results.getTextValue();
// 2. use selectPath on XmlObject
// XmlObject[] result = xmlbean.selectPath(namespaceDecl + path);
// 3. use selectPath on XmlCursor
// cursor.toParent();
// XmlOptions options = new XmlOptions();
// options.put(Path.PATH_DELEGATE_INTERFACE,"org.apache.xmlbeans.impl.xpath.saxon.XBeansXPath");
// cursor.selectPath(namespaceDecl + path, options);
// if (cursor.getSelectionCount()>0) {
// cursor.toNextSelection();
// value = cursor.getTextValue();
// } else value = null;
// 4. use our own implementation
try {
XmlPath matcher = new XmlPath(path);
value = matcher.evaluate_segment(cursor, matcher.path_seg);
} catch (XmlException e) {
value = null; // xpath syntax error - treated as no match
}
cursor.dispose();
return value;
} | [
"public",
"static",
"String",
"evaluate",
"(",
"XmlObject",
"xmlbean",
",",
"String",
"path",
")",
"{",
"XmlCursor",
"cursor",
"=",
"xmlbean",
".",
"newCursor",
"(",
")",
";",
"String",
"value",
";",
"// 1.2.3. use XQuery or selectPath",
"//",
"// cursor.to... | Using XPath or XQuery.
NOTE!!!! To use this code, need to include
xbean_xpath.jar, saxon9.jar, saxon9-dom.jar in CLASSPATH
in startWebLogic.cmd
@param xmlbean
@param path
@return | [
"Using",
"XPath",
"or",
"XQuery",
".",
"NOTE!!!!",
"To",
"use",
"this",
"code",
"need",
"to",
"include",
"xbean_xpath",
".",
"jar",
"saxon9",
".",
"jar",
"saxon9",
"-",
"dom",
".",
"jar",
"in",
"CLASSPATH",
"in",
"startWebLogic",
".",
"cmd"
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/xml/XmlPath.java#L62-L104 |
hibernate/hibernate-ogm | core/src/main/java/org/hibernate/ogm/datastore/document/impl/EmbeddableStateFinder.java | EmbeddableStateFinder.maybeCacheOnNonNullEmbeddable | private void maybeCacheOnNonNullEmbeddable(String[] path, int index, Set<String> columnsOfEmbeddable) {
if ( index == path.length - 2 ) {
//right level (i.e. the most specific embeddable for the column at bay
for ( String columnInvolved : columnsOfEmbeddable ) {
if ( columnInvolved.split( "\\." ).length == path.length ) {
// Only cache for columns from the same embeddable
columnToOuterMostNullEmbeddableCache.put( columnInvolved, null );
}
}
}
} | java | private void maybeCacheOnNonNullEmbeddable(String[] path, int index, Set<String> columnsOfEmbeddable) {
if ( index == path.length - 2 ) {
//right level (i.e. the most specific embeddable for the column at bay
for ( String columnInvolved : columnsOfEmbeddable ) {
if ( columnInvolved.split( "\\." ).length == path.length ) {
// Only cache for columns from the same embeddable
columnToOuterMostNullEmbeddableCache.put( columnInvolved, null );
}
}
}
} | [
"private",
"void",
"maybeCacheOnNonNullEmbeddable",
"(",
"String",
"[",
"]",
"path",
",",
"int",
"index",
",",
"Set",
"<",
"String",
">",
"columnsOfEmbeddable",
")",
"{",
"if",
"(",
"index",
"==",
"path",
".",
"length",
"-",
"2",
")",
"{",
"//right level (... | The embeddable is not null.
Only cache the values if we are in the most specific embeddable containing {@code column}
otherwise a more specific embeddable might be null and we would miss it
Only set the values for the columns sharing this specific embeddable
columns from deeper embeddables might be null | [
"The",
"embeddable",
"is",
"not",
"null",
".",
"Only",
"cache",
"the",
"values",
"if",
"we",
"are",
"in",
"the",
"most",
"specific",
"embeddable",
"containing",
"{",
"@code",
"column",
"}",
"otherwise",
"a",
"more",
"specific",
"embeddable",
"might",
"be",
... | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/datastore/document/impl/EmbeddableStateFinder.java#L97-L107 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractIndexWriter.java | AbstractIndexWriter.addClassInfo | protected void addClassInfo(TypeElement te, Content contentTree) {
contentTree.addContent(contents.getContent("doclet.in",
utils.getTypeElementName(te, false),
getPackageLink(utils.containingPackage(te),
utils.getPackageName(utils.containingPackage(te)))
));
} | java | protected void addClassInfo(TypeElement te, Content contentTree) {
contentTree.addContent(contents.getContent("doclet.in",
utils.getTypeElementName(te, false),
getPackageLink(utils.containingPackage(te),
utils.getPackageName(utils.containingPackage(te)))
));
} | [
"protected",
"void",
"addClassInfo",
"(",
"TypeElement",
"te",
",",
"Content",
"contentTree",
")",
"{",
"contentTree",
".",
"addContent",
"(",
"contents",
".",
"getContent",
"(",
"\"doclet.in\"",
",",
"utils",
".",
"getTypeElementName",
"(",
"te",
",",
"false",
... | Add the classkind (class, interface, exception), error of the class
passed.
@param te the class being documented
@param contentTree the content tree to which the class info will be added | [
"Add",
"the",
"classkind",
"(",
"class",
"interface",
"exception",
")",
"error",
"of",
"the",
"class",
"passed",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractIndexWriter.java#L294-L300 |
eobermuhlner/big-math | ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigComplexMath.java | BigComplexMath.sqrt | public static BigComplex sqrt(BigComplex x, MathContext mathContext) {
// https://math.stackexchange.com/questions/44406/how-do-i-get-the-square-root-of-a-complex-number
MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
BigDecimal magnitude = x.abs(mc);
BigComplex a = x.add(magnitude, mc);
return a.divide(a.abs(mc), mc).multiply(BigDecimalMath.sqrt(magnitude, mc), mc).round(mathContext);
} | java | public static BigComplex sqrt(BigComplex x, MathContext mathContext) {
// https://math.stackexchange.com/questions/44406/how-do-i-get-the-square-root-of-a-complex-number
MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());
BigDecimal magnitude = x.abs(mc);
BigComplex a = x.add(magnitude, mc);
return a.divide(a.abs(mc), mc).multiply(BigDecimalMath.sqrt(magnitude, mc), mc).round(mathContext);
} | [
"public",
"static",
"BigComplex",
"sqrt",
"(",
"BigComplex",
"x",
",",
"MathContext",
"mathContext",
")",
"{",
"// https://math.stackexchange.com/questions/44406/how-do-i-get-the-square-root-of-a-complex-number",
"MathContext",
"mc",
"=",
"new",
"MathContext",
"(",
"mathContext... | Calculates the square root of {@link BigComplex} x in the complex domain (√x).
<p>See <a href="https://en.wikipedia.org/wiki/Square_root#Square_root_of_an_imaginary_number">Wikipedia: Square root (Square root of an imaginary number)</a></p>
@param x the {@link BigComplex} to calculate the square root for
@param mathContext the {@link MathContext} used for the result
@return the calculated square root {@link BigComplex} with the precision specified in the <code>mathContext</code> | [
"Calculates",
"the",
"square",
"root",
"of",
"{",
"@link",
"BigComplex",
"}",
"x",
"in",
"the",
"complex",
"domain",
"(",
"√x",
")",
"."
] | train | https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigComplexMath.java#L284-L292 |
jcuda/jcuda | JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java | JCudaDriver.cuLaunchGrid | @Deprecated
public static int cuLaunchGrid(CUfunction f, int grid_width, int grid_height)
{
return checkResult(cuLaunchGridNative(f, grid_width, grid_height));
} | java | @Deprecated
public static int cuLaunchGrid(CUfunction f, int grid_width, int grid_height)
{
return checkResult(cuLaunchGridNative(f, grid_width, grid_height));
} | [
"@",
"Deprecated",
"public",
"static",
"int",
"cuLaunchGrid",
"(",
"CUfunction",
"f",
",",
"int",
"grid_width",
",",
"int",
"grid_height",
")",
"{",
"return",
"checkResult",
"(",
"cuLaunchGridNative",
"(",
"f",
",",
"grid_width",
",",
"grid_height",
")",
")",
... | Launches a CUDA function.
<pre>
CUresult cuLaunchGrid (
CUfunction f,
int grid_width,
int grid_height )
</pre>
<div>
<p>Launches a CUDA function.
Deprecated Invokes the kernel <tt>f</tt>
on a <tt>grid_width</tt> x <tt>grid_height</tt> grid of blocks. Each
block contains the number of threads specified by a previous call to
cuFuncSetBlockShape().
</p>
<div>
<span>Note:</span>
<p>Note that this
function may also return error codes from previous, asynchronous
launches.
</p>
</div>
</p>
</div>
@param f Kernel to launch
@param grid_width Width of grid in blocks
@param grid_height Height of grid in blocks
@return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED,
CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE,
CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES,
CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING,
CUDA_ERROR_SHARED_OBJECT_INIT_FAILED
@see JCudaDriver#cuFuncSetBlockShape
@see JCudaDriver#cuFuncSetSharedSize
@see JCudaDriver#cuFuncGetAttribute
@see JCudaDriver#cuParamSetSize
@see JCudaDriver#cuParamSetf
@see JCudaDriver#cuParamSeti
@see JCudaDriver#cuParamSetv
@see JCudaDriver#cuLaunch
@see JCudaDriver#cuLaunchGridAsync
@see JCudaDriver#cuLaunchKernel
@deprecated Deprecated in CUDA | [
"Launches",
"a",
"CUDA",
"function",
"."
] | train | https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L13246-L13250 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/WorkbinsApi.java | WorkbinsApi.subscribeToWorkbinNotifications | public ApiSuccessResponse subscribeToWorkbinNotifications(String workbinId, SubscribeToWorkbinNotificationsData subscribeToWorkbinNotificationsData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = subscribeToWorkbinNotificationsWithHttpInfo(workbinId, subscribeToWorkbinNotificationsData);
return resp.getData();
} | java | public ApiSuccessResponse subscribeToWorkbinNotifications(String workbinId, SubscribeToWorkbinNotificationsData subscribeToWorkbinNotificationsData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = subscribeToWorkbinNotificationsWithHttpInfo(workbinId, subscribeToWorkbinNotificationsData);
return resp.getData();
} | [
"public",
"ApiSuccessResponse",
"subscribeToWorkbinNotifications",
"(",
"String",
"workbinId",
",",
"SubscribeToWorkbinNotificationsData",
"subscribeToWorkbinNotificationsData",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"ApiSuccessResponse",
">",
"resp",
"=",
"sub... | Subscribe to be notified of changes of the content of a Workbin.
@param workbinId Id of the Workbin (required)
@param subscribeToWorkbinNotificationsData (required)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Subscribe",
"to",
"be",
"notified",
"of",
"changes",
"of",
"the",
"content",
"of",
"a",
"Workbin",
"."
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/WorkbinsApi.java#L775-L778 |
ManfredTremmel/gwt-bean-validators | gwt-bean-validators-restygwt-jaxrs/src/main/super/de/knightsoftnet/validators/supersource/de/knightsoftnet/validators/shared/impl/PhoneNumberValueRestValidator.java | PhoneNumberValueRestValidator.isValid | @Override
public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) {
final String valueAsString = Objects.toString(pvalue, null);
if (StringUtils.isEmpty(valueAsString)) {
// empty field is ok
return true;
}
try {
String countryCode = BeanUtils.getProperty(pvalue, fieldCountryCode);
final String phoneNumber = BeanUtils.getProperty(pvalue, fieldPhoneNumber);
if (StringUtils.isEmpty(phoneNumber)) {
return true;
}
if (allowLowerCaseCountryCode) {
countryCode = StringUtils.upperCase(countryCode);
}
final PathDefinitionInterface pathDefinition = GWT.create(PathDefinitionInterface.class);
final String url =
pathDefinition.getRestBasePath() + "/" + PhoneNumber.ROOT + "/" + PhoneNumber.VALIDATE //
+ "?" + Parameters.COUNTRY + "=" + countryCode //
+ "&" + Parameters.PHONE_NUMBER + "=" + urlEncode(phoneNumber) //
+ "&" + Parameters.DIN_5008 + "=" + PhoneNumberValueRestValidator.this.allowDin5008 //
+ "&" + Parameters.E123 + "=" + PhoneNumberValueRestValidator.this.allowE123 //
+ "&" + Parameters.URI + "=" + PhoneNumberValueRestValidator.this.allowUri //
+ "&" + Parameters.MS + "=" + PhoneNumberValueRestValidator.this.allowMs //
+ "&" + Parameters.COMMON + "=" + PhoneNumberValueRestValidator.this.allowCommon;
final String restResult = CachedSyncHttpGetCall.syncRestCall(url);
if (StringUtils.equalsIgnoreCase("TRUE", restResult)) {
return true;
}
switchContext(pcontext);
return false;
} catch (final Exception ignore) {
switchContext(pcontext);
return false;
}
} | java | @Override
public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) {
final String valueAsString = Objects.toString(pvalue, null);
if (StringUtils.isEmpty(valueAsString)) {
// empty field is ok
return true;
}
try {
String countryCode = BeanUtils.getProperty(pvalue, fieldCountryCode);
final String phoneNumber = BeanUtils.getProperty(pvalue, fieldPhoneNumber);
if (StringUtils.isEmpty(phoneNumber)) {
return true;
}
if (allowLowerCaseCountryCode) {
countryCode = StringUtils.upperCase(countryCode);
}
final PathDefinitionInterface pathDefinition = GWT.create(PathDefinitionInterface.class);
final String url =
pathDefinition.getRestBasePath() + "/" + PhoneNumber.ROOT + "/" + PhoneNumber.VALIDATE //
+ "?" + Parameters.COUNTRY + "=" + countryCode //
+ "&" + Parameters.PHONE_NUMBER + "=" + urlEncode(phoneNumber) //
+ "&" + Parameters.DIN_5008 + "=" + PhoneNumberValueRestValidator.this.allowDin5008 //
+ "&" + Parameters.E123 + "=" + PhoneNumberValueRestValidator.this.allowE123 //
+ "&" + Parameters.URI + "=" + PhoneNumberValueRestValidator.this.allowUri //
+ "&" + Parameters.MS + "=" + PhoneNumberValueRestValidator.this.allowMs //
+ "&" + Parameters.COMMON + "=" + PhoneNumberValueRestValidator.this.allowCommon;
final String restResult = CachedSyncHttpGetCall.syncRestCall(url);
if (StringUtils.equalsIgnoreCase("TRUE", restResult)) {
return true;
}
switchContext(pcontext);
return false;
} catch (final Exception ignore) {
switchContext(pcontext);
return false;
}
} | [
"@",
"Override",
"public",
"final",
"boolean",
"isValid",
"(",
"final",
"Object",
"pvalue",
",",
"final",
"ConstraintValidatorContext",
"pcontext",
")",
"{",
"final",
"String",
"valueAsString",
"=",
"Objects",
".",
"toString",
"(",
"pvalue",
",",
"null",
")",
... | {@inheritDoc} check if given string is a valid gln.
@see javax.validation.ConstraintValidator#isValid(java.lang.Object,
javax.validation.ConstraintValidatorContext) | [
"{",
"@inheritDoc",
"}",
"check",
"if",
"given",
"string",
"is",
"a",
"valid",
"gln",
"."
] | train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/gwt-bean-validators-restygwt-jaxrs/src/main/super/de/knightsoftnet/validators/supersource/de/knightsoftnet/validators/shared/impl/PhoneNumberValueRestValidator.java#L112-L150 |
aws/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/UpdateItemRequest.java | UpdateItemRequest.withKey | public UpdateItemRequest withKey(java.util.Map.Entry<String, AttributeValue> hashKey, java.util.Map.Entry<String, AttributeValue> rangeKey)
throws IllegalArgumentException {
setKey(hashKey, rangeKey);
return this;
} | java | public UpdateItemRequest withKey(java.util.Map.Entry<String, AttributeValue> hashKey, java.util.Map.Entry<String, AttributeValue> rangeKey)
throws IllegalArgumentException {
setKey(hashKey, rangeKey);
return this;
} | [
"public",
"UpdateItemRequest",
"withKey",
"(",
"java",
".",
"util",
".",
"Map",
".",
"Entry",
"<",
"String",
",",
"AttributeValue",
">",
"hashKey",
",",
"java",
".",
"util",
".",
"Map",
".",
"Entry",
"<",
"String",
",",
"AttributeValue",
">",
"rangeKey",
... | Set the hash and range key attributes of the item.
<p>
For a hash-only table, you only need to provide the hash attribute. For a hash-and-range table, you must provide
both.
<p>
Returns a reference to this object so that method calls can be chained together.
@param hashKey
a map entry including the name and value of the primary hash key.
@param rangeKey
a map entry including the name and value of the primary range key, or null if it is a hash-only table. | [
"Set",
"the",
"hash",
"and",
"range",
"key",
"attributes",
"of",
"the",
"item",
".",
"<p",
">",
"For",
"a",
"hash",
"-",
"only",
"table",
"you",
"only",
"need",
"to",
"provide",
"the",
"hash",
"attribute",
".",
"For",
"a",
"hash",
"-",
"and",
"-",
... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/UpdateItemRequest.java#L3106-L3110 |
belaban/JGroups | src/org/jgroups/protocols/pbcast/ClientGmsImpl.java | ClientGmsImpl.firstOfAllClients | protected boolean firstOfAllClients(final Address joiner, final Responses rsps) {
log.trace("%s: could not determine coordinator from rsps %s", gms.local_addr, rsps);
// so the member to become singleton member (and thus coord) is the first of all clients
SortedSet<Address> clients=new TreeSet<>();
clients.add(joiner); // add myself again (was removed by findInitialMembers())
for(PingData response: rsps)
clients.add(response.getAddress());
log.trace("%s: nodes to choose new coord from are: %s", gms.local_addr, clients);
Address new_coord=clients.first();
if(new_coord.equals(joiner)) {
log.trace("%s: I (%s) am the first of the nodes, will become coordinator", gms.local_addr, joiner);
becomeSingletonMember(joiner);
return true;
}
log.trace("%s: I (%s) am not the first of the nodes, waiting for another client to become coordinator",
gms.local_addr, joiner);
// Util.sleep(500);
return false;
} | java | protected boolean firstOfAllClients(final Address joiner, final Responses rsps) {
log.trace("%s: could not determine coordinator from rsps %s", gms.local_addr, rsps);
// so the member to become singleton member (and thus coord) is the first of all clients
SortedSet<Address> clients=new TreeSet<>();
clients.add(joiner); // add myself again (was removed by findInitialMembers())
for(PingData response: rsps)
clients.add(response.getAddress());
log.trace("%s: nodes to choose new coord from are: %s", gms.local_addr, clients);
Address new_coord=clients.first();
if(new_coord.equals(joiner)) {
log.trace("%s: I (%s) am the first of the nodes, will become coordinator", gms.local_addr, joiner);
becomeSingletonMember(joiner);
return true;
}
log.trace("%s: I (%s) am not the first of the nodes, waiting for another client to become coordinator",
gms.local_addr, joiner);
// Util.sleep(500);
return false;
} | [
"protected",
"boolean",
"firstOfAllClients",
"(",
"final",
"Address",
"joiner",
",",
"final",
"Responses",
"rsps",
")",
"{",
"log",
".",
"trace",
"(",
"\"%s: could not determine coordinator from rsps %s\"",
",",
"gms",
".",
"local_addr",
",",
"rsps",
")",
";",
"//... | Handles the case where no coord responses were received. Returns true if we became the coord
(caller needs to terminate the join() call), or false when the caller needs to continue | [
"Handles",
"the",
"case",
"where",
"no",
"coord",
"responses",
"were",
"received",
".",
"Returns",
"true",
"if",
"we",
"became",
"the",
"coord",
"(",
"caller",
"needs",
"to",
"terminate",
"the",
"join",
"()",
"call",
")",
"or",
"false",
"when",
"the",
"c... | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/protocols/pbcast/ClientGmsImpl.java#L157-L177 |
actorapp/actor-platform | actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/crypto/Curve25519.java | Curve25519.keyGen | public static Curve25519KeyPair keyGen(byte[] randomBytes) {
byte[] privateKey = keyGenPrivate(randomBytes);
byte[] publicKey = keyGenPublic(privateKey);
return new Curve25519KeyPair(publicKey, privateKey);
} | java | public static Curve25519KeyPair keyGen(byte[] randomBytes) {
byte[] privateKey = keyGenPrivate(randomBytes);
byte[] publicKey = keyGenPublic(privateKey);
return new Curve25519KeyPair(publicKey, privateKey);
} | [
"public",
"static",
"Curve25519KeyPair",
"keyGen",
"(",
"byte",
"[",
"]",
"randomBytes",
")",
"{",
"byte",
"[",
"]",
"privateKey",
"=",
"keyGenPrivate",
"(",
"randomBytes",
")",
";",
"byte",
"[",
"]",
"publicKey",
"=",
"keyGenPublic",
"(",
"privateKey",
")",... | Generating KeyPair
@param randomBytes 32 random bytes
@return generated key pair | [
"Generating",
"KeyPair"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/crypto/Curve25519.java#L23-L27 |
google/closure-compiler | src/com/google/javascript/jscomp/modules/Binding.java | Binding.from | static Binding from(Module namespaceBoundModule, Node sourceNode) {
return new AutoValue_Binding(
namespaceBoundModule.metadata(),
sourceNode,
/* originatingExport= */ null,
/* isModuleNamespace= */ true,
namespaceBoundModule.closureNamespace(),
CreatedBy.IMPORT);
} | java | static Binding from(Module namespaceBoundModule, Node sourceNode) {
return new AutoValue_Binding(
namespaceBoundModule.metadata(),
sourceNode,
/* originatingExport= */ null,
/* isModuleNamespace= */ true,
namespaceBoundModule.closureNamespace(),
CreatedBy.IMPORT);
} | [
"static",
"Binding",
"from",
"(",
"Module",
"namespaceBoundModule",
",",
"Node",
"sourceNode",
")",
"{",
"return",
"new",
"AutoValue_Binding",
"(",
"namespaceBoundModule",
".",
"metadata",
"(",
")",
",",
"sourceNode",
",",
"/* originatingExport= */",
"null",
",",
... | Binding for an entire module namespace created by an <code>import *</code>. | [
"Binding",
"for",
"an",
"entire",
"module",
"namespace",
"created",
"by",
"an",
"<code",
">",
"import",
"*",
"<",
"/",
"code",
">",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/modules/Binding.java#L120-L128 |
dlemmermann/CalendarFX | CalendarFXView/src/main/java/com/calendarfx/model/Entry.java | Entry.changeEndTime | public final void changeEndTime(LocalTime time, boolean keepDuration) {
requireNonNull(time);
Interval interval = getInterval();
LocalDateTime newEndDateTime = getEndAsLocalDateTime().with(time);
LocalDateTime startDateTime = getStartAsLocalDateTime();
if (keepDuration) {
startDateTime = newEndDateTime.minus(getDuration());
setInterval(startDateTime, newEndDateTime, getZoneId());
} else {
/*
* We might have a problem if the new end time is BEFORE the current start time.
*/
if (newEndDateTime.isBefore(startDateTime.plus(getMinimumDuration()))) {
interval = interval.withStartDateTime(newEndDateTime.minus(getMinimumDuration()));
}
setInterval(interval.withEndTime(time));
}
} | java | public final void changeEndTime(LocalTime time, boolean keepDuration) {
requireNonNull(time);
Interval interval = getInterval();
LocalDateTime newEndDateTime = getEndAsLocalDateTime().with(time);
LocalDateTime startDateTime = getStartAsLocalDateTime();
if (keepDuration) {
startDateTime = newEndDateTime.minus(getDuration());
setInterval(startDateTime, newEndDateTime, getZoneId());
} else {
/*
* We might have a problem if the new end time is BEFORE the current start time.
*/
if (newEndDateTime.isBefore(startDateTime.plus(getMinimumDuration()))) {
interval = interval.withStartDateTime(newEndDateTime.minus(getMinimumDuration()));
}
setInterval(interval.withEndTime(time));
}
} | [
"public",
"final",
"void",
"changeEndTime",
"(",
"LocalTime",
"time",
",",
"boolean",
"keepDuration",
")",
"{",
"requireNonNull",
"(",
"time",
")",
";",
"Interval",
"interval",
"=",
"getInterval",
"(",
")",
";",
"LocalDateTime",
"newEndDateTime",
"=",
"getEndAsL... | Changes the end time of the entry interval.
@param time the new end time
@param keepDuration if true then this method will also change the start time in such a way that the total duration
of the entry will not change. If false then this method will ensure that the entry's interval
stays valid, which means that the start time will be before the end time and that the
duration of the entry will be at least the duration defined by the {@link #minimumDurationProperty()}. | [
"Changes",
"the",
"end",
"time",
"of",
"the",
"entry",
"interval",
"."
] | train | https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/model/Entry.java#L527-L548 |
aggregateknowledge/java-hll | src/main/java/net/agkn/hll/serialization/BigEndianAscendingWordSerializer.java | BigEndianAscendingWordSerializer.writeWord | @Override
public void writeWord(final long word) {
if(wordsWritten == wordCount) {
throw new RuntimeException("Cannot write more words, backing array full!");
}
int bitsLeftInWord = wordLength;
while(bitsLeftInWord > 0) {
// Move to the next byte if the current one is fully packed.
if(bitsLeftInByte == 0) {
byteIndex++;
bitsLeftInByte = BITS_PER_BYTE;
}
final long consumedMask;
if(bitsLeftInWord == 64) {
consumedMask = ~0L;
} else {
consumedMask = ((1L << bitsLeftInWord) - 1L);
}
// Fix how many bits will be written in this cycle. Choose the
// smaller of the remaining bits in the word or byte.
final int numberOfBitsToWrite = Math.min(bitsLeftInByte, bitsLeftInWord);
final int bitsInByteRemainingAfterWrite = (bitsLeftInByte - numberOfBitsToWrite);
// In general, we write the highest bits of the word first, so we
// strip the highest bits that were consumed in previous cycles.
final long remainingBitsOfWordToWrite = (word & consumedMask);
final long bitsThatTheByteCanAccept;
// If there is more left in the word than can be written to this
// byte, shift off the bits that can't be written off the bottom.
if(bitsLeftInWord > numberOfBitsToWrite) {
bitsThatTheByteCanAccept = (remainingBitsOfWordToWrite >>> (bitsLeftInWord - bitsLeftInByte));
} else {
// If the byte can accept all remaining bits, there is no need
// to shift off the bits that won't be written in this cycle.
bitsThatTheByteCanAccept = remainingBitsOfWordToWrite;
}
// Align the word bits to write up against the byte bits that have
// already been written. This shift may do nothing if the remainder
// of the byte is being consumed in this cycle.
final long alignedBits = (bitsThatTheByteCanAccept << bitsInByteRemainingAfterWrite);
// Update the byte with the alignedBits.
bytes[byteIndex] |= (byte)alignedBits;
// Update state with bit count written.
bitsLeftInWord -= numberOfBitsToWrite;
bitsLeftInByte = bitsInByteRemainingAfterWrite;
}
wordsWritten ++;
} | java | @Override
public void writeWord(final long word) {
if(wordsWritten == wordCount) {
throw new RuntimeException("Cannot write more words, backing array full!");
}
int bitsLeftInWord = wordLength;
while(bitsLeftInWord > 0) {
// Move to the next byte if the current one is fully packed.
if(bitsLeftInByte == 0) {
byteIndex++;
bitsLeftInByte = BITS_PER_BYTE;
}
final long consumedMask;
if(bitsLeftInWord == 64) {
consumedMask = ~0L;
} else {
consumedMask = ((1L << bitsLeftInWord) - 1L);
}
// Fix how many bits will be written in this cycle. Choose the
// smaller of the remaining bits in the word or byte.
final int numberOfBitsToWrite = Math.min(bitsLeftInByte, bitsLeftInWord);
final int bitsInByteRemainingAfterWrite = (bitsLeftInByte - numberOfBitsToWrite);
// In general, we write the highest bits of the word first, so we
// strip the highest bits that were consumed in previous cycles.
final long remainingBitsOfWordToWrite = (word & consumedMask);
final long bitsThatTheByteCanAccept;
// If there is more left in the word than can be written to this
// byte, shift off the bits that can't be written off the bottom.
if(bitsLeftInWord > numberOfBitsToWrite) {
bitsThatTheByteCanAccept = (remainingBitsOfWordToWrite >>> (bitsLeftInWord - bitsLeftInByte));
} else {
// If the byte can accept all remaining bits, there is no need
// to shift off the bits that won't be written in this cycle.
bitsThatTheByteCanAccept = remainingBitsOfWordToWrite;
}
// Align the word bits to write up against the byte bits that have
// already been written. This shift may do nothing if the remainder
// of the byte is being consumed in this cycle.
final long alignedBits = (bitsThatTheByteCanAccept << bitsInByteRemainingAfterWrite);
// Update the byte with the alignedBits.
bytes[byteIndex] |= (byte)alignedBits;
// Update state with bit count written.
bitsLeftInWord -= numberOfBitsToWrite;
bitsLeftInByte = bitsInByteRemainingAfterWrite;
}
wordsWritten ++;
} | [
"@",
"Override",
"public",
"void",
"writeWord",
"(",
"final",
"long",
"word",
")",
"{",
"if",
"(",
"wordsWritten",
"==",
"wordCount",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Cannot write more words, backing array full!\"",
")",
";",
"}",
"int",
"bi... | /* (non-Javadoc)
@see net.agkn.hll.serialization.IWordSerializer#writeWord(long)
@throws RuntimeException if the number of words written is greater than the
<code>wordCount</code> parameter in the constructor. | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/aggregateknowledge/java-hll/blob/1f4126e79a85b79581460c75bf1c1634b8a7402d/src/main/java/net/agkn/hll/serialization/BigEndianAscendingWordSerializer.java#L104-L160 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheProviderWrapper.java | CacheProviderWrapper.setValue | @Override
public void setValue(com.ibm.ws.cache.EntryInfo entryInfo, Object value, boolean coordinate, boolean directive) {
final String methodName = "setValue()";
Object id = null;
if (entryInfo != null) {
id = entryInfo.getIdObject();
}
if (directive == DynaCacheConstants.VBC_CACHE_NEW_CONTENT) {
this.coreCache.put(entryInfo, value);
} else {
this.coreCache.touch(entryInfo.id, entryInfo.validatorExpirationTime, entryInfo.expirationTime);
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " cacheName=" + cacheName + " id=" + id + " directive=" + directive);
}
} | java | @Override
public void setValue(com.ibm.ws.cache.EntryInfo entryInfo, Object value, boolean coordinate, boolean directive) {
final String methodName = "setValue()";
Object id = null;
if (entryInfo != null) {
id = entryInfo.getIdObject();
}
if (directive == DynaCacheConstants.VBC_CACHE_NEW_CONTENT) {
this.coreCache.put(entryInfo, value);
} else {
this.coreCache.touch(entryInfo.id, entryInfo.validatorExpirationTime, entryInfo.expirationTime);
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " cacheName=" + cacheName + " id=" + id + " directive=" + directive);
}
} | [
"@",
"Override",
"public",
"void",
"setValue",
"(",
"com",
".",
"ibm",
".",
"ws",
".",
"cache",
".",
"EntryInfo",
"entryInfo",
",",
"Object",
"value",
",",
"boolean",
"coordinate",
",",
"boolean",
"directive",
")",
"{",
"final",
"String",
"methodName",
"="... | Puts an entry into the cache. If the entry already exists in the
cache, this method will ALSO update the same.
Called by DistributedNioMap (old ProxyCache)
Called by Cache.setEntry(cacheEntry, source)
@param entryInfo The EntryInfo object
@param value The value of the object
@param coordinate Indicates that the value should be set in other caches caching this value. (No effect on CoreCache)
@param directive boolean to indicate CACHE_NEW_CONTENT or USE_CACHED_VALUE | [
"Puts",
"an",
"entry",
"into",
"the",
"cache",
".",
"If",
"the",
"entry",
"already",
"exists",
"in",
"the",
"cache",
"this",
"method",
"will",
"ALSO",
"update",
"the",
"same",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheProviderWrapper.java#L649-L664 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/constraint/ConBox.java | ConBox.hasDifferentCompartments | public static Constraint hasDifferentCompartments()
{
String acStr = "PhysicalEntity/cellularLocation/term";
return new Field(acStr, acStr, Field.Operation.NOT_EMPTY_AND_NOT_INTERSECT);
} | java | public static Constraint hasDifferentCompartments()
{
String acStr = "PhysicalEntity/cellularLocation/term";
return new Field(acStr, acStr, Field.Operation.NOT_EMPTY_AND_NOT_INTERSECT);
} | [
"public",
"static",
"Constraint",
"hasDifferentCompartments",
"(",
")",
"{",
"String",
"acStr",
"=",
"\"PhysicalEntity/cellularLocation/term\"",
";",
"return",
"new",
"Field",
"(",
"acStr",
",",
"acStr",
",",
"Field",
".",
"Operation",
".",
"NOT_EMPTY_AND_NOT_INTERSEC... | Checks if two physical entities have non-empty and different compartments.
@return the constraint | [
"Checks",
"if",
"two",
"physical",
"entities",
"have",
"non",
"-",
"empty",
"and",
"different",
"compartments",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/constraint/ConBox.java#L645-L649 |
EXIficient/exificient-core | src/main/java/com/siemens/ct/exi/core/util/MethodsBag.java | MethodsBag.itosReverse | public final static void itosReverse(long i, int index, char[] buf) {
assert (i >= 0);
long q;
int r;
// Get 2 digits/iteration using longs until quotient fits into an int
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int) (i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
buf[index++] = DigitOnes[r];
buf[index++] = DigitTens[r];
}
// Get 2 digits/iteration using ints
int q2;
int i2 = (int) i;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 100);
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
buf[index++] = DigitOnes[r];
buf[index++] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i2 <= 65536, i2);
for (;;) {
q2 = (i2 * 52429) >>> (16 + 3);
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
buf[index++] = digits[r];
i2 = q2;
if (i2 == 0)
break;
}
} | java | public final static void itosReverse(long i, int index, char[] buf) {
assert (i >= 0);
long q;
int r;
// Get 2 digits/iteration using longs until quotient fits into an int
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int) (i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
buf[index++] = DigitOnes[r];
buf[index++] = DigitTens[r];
}
// Get 2 digits/iteration using ints
int q2;
int i2 = (int) i;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 100);
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
buf[index++] = DigitOnes[r];
buf[index++] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i2 <= 65536, i2);
for (;;) {
q2 = (i2 * 52429) >>> (16 + 3);
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
buf[index++] = digits[r];
i2 = q2;
if (i2 == 0)
break;
}
} | [
"public",
"final",
"static",
"void",
"itosReverse",
"(",
"long",
"i",
",",
"int",
"index",
",",
"char",
"[",
"]",
"buf",
")",
"{",
"assert",
"(",
"i",
">=",
"0",
")",
";",
"long",
"q",
";",
"int",
"r",
";",
"// Get 2 digits/iteration using longs until qu... | Places characters representing the integer i into the character array buf
in reverse order.
Will fail if i < 0 (zero)
@param i
integer
@param index
index
@param buf
character buffer | [
"Places",
"characters",
"representing",
"the",
"integer",
"i",
"into",
"the",
"character",
"array",
"buf",
"in",
"reverse",
"order",
"."
] | train | https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/util/MethodsBag.java#L496-L533 |
akberc/ceylon-maven-plugin | src/main/java/com/dgwave/car/common/CeylonUtil.java | CeylonUtil.extractFile | public static void extractFile(final ZipInputStream in, final File outdir, final String name) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir, name)));
int count = -1;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
out.close();
} | java | public static void extractFile(final ZipInputStream in, final File outdir, final String name) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir, name)));
int count = -1;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
out.close();
} | [
"public",
"static",
"void",
"extractFile",
"(",
"final",
"ZipInputStream",
"in",
",",
"final",
"File",
"outdir",
",",
"final",
"String",
"name",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"BUFFER_SIZE",
"]",
";"... | Extracts a single file from a zip archive.
@param in Input zip stream
@param outdir Output directory
@param name File name
@throws IOException In case of IO error | [
"Extracts",
"a",
"single",
"file",
"from",
"a",
"zip",
"archive",
"."
] | train | https://github.com/akberc/ceylon-maven-plugin/blob/b7f6c4a2b24f2fa237350c9e715f4193e83415ef/src/main/java/com/dgwave/car/common/CeylonUtil.java#L223-L231 |
Azure/azure-sdk-for-java | servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java | ClientFactory.acceptSessionFromEntityPath | public static IMessageSession acceptSessionFromEntityPath(MessagingFactory messagingFactory, String entityPath, String sessionId, ReceiveMode receiveMode) throws InterruptedException, ServiceBusException {
return Utils.completeFuture(acceptSessionFromEntityPathAsync(messagingFactory, entityPath, sessionId, receiveMode));
} | java | public static IMessageSession acceptSessionFromEntityPath(MessagingFactory messagingFactory, String entityPath, String sessionId, ReceiveMode receiveMode) throws InterruptedException, ServiceBusException {
return Utils.completeFuture(acceptSessionFromEntityPathAsync(messagingFactory, entityPath, sessionId, receiveMode));
} | [
"public",
"static",
"IMessageSession",
"acceptSessionFromEntityPath",
"(",
"MessagingFactory",
"messagingFactory",
",",
"String",
"entityPath",
",",
"String",
"sessionId",
",",
"ReceiveMode",
"receiveMode",
")",
"throws",
"InterruptedException",
",",
"ServiceBusException",
... | Accept a {@link IMessageSession} from service bus using the client settings with specified session id. Session Id can be null, if null, service will return the first available session.
@param messagingFactory messaging factory (which represents a connection) on which the session receiver needs to be created.
@param entityPath path of entity
@param sessionId session id, if null, service will return the first available session, otherwise, service will return specified session
@param receiveMode PeekLock or ReceiveAndDelete
@return IMessageSession instance
@throws InterruptedException if the current thread was interrupted while waiting
@throws ServiceBusException if the session cannot be accepted | [
"Accept",
"a",
"{"
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L611-L613 |
upwork/java-upwork | src/com/Upwork/api/OAuthClient.java | OAuthClient.sendPostRequest | private JSONObject sendPostRequest(String url, Integer type, HashMap<String, String> params) throws JSONException {
String fullUrl = getFullUrl(url);
HttpPost request = new HttpPost(fullUrl);
switch(type) {
case METHOD_PUT:
case METHOD_DELETE:
// assign overload value
String oValue;
if (type == METHOD_PUT) {
oValue = "put";
} else {
oValue = "delete";
}
params.put(OVERLOAD_PARAM, oValue);
case METHOD_POST:
break;
default:
throw new RuntimeException("Wrong http method requested");
}
// doing post request using json to avoid issue with urlencoded symbols
JSONObject json = new JSONObject();
for (Map.Entry<String, String> entry : params.entrySet()) {
json.put(entry.getKey(), entry.getValue());
}
request.setHeader("Content-Type", "application/json");
try {
request.setEntity(new StringEntity(json.toString()));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// sign request
try {
mOAuthConsumer.sign(request);
}
catch (OAuthException e) {
e.printStackTrace();
}
return UpworkRestClient.getJSONObject(request, type, params);
} | java | private JSONObject sendPostRequest(String url, Integer type, HashMap<String, String> params) throws JSONException {
String fullUrl = getFullUrl(url);
HttpPost request = new HttpPost(fullUrl);
switch(type) {
case METHOD_PUT:
case METHOD_DELETE:
// assign overload value
String oValue;
if (type == METHOD_PUT) {
oValue = "put";
} else {
oValue = "delete";
}
params.put(OVERLOAD_PARAM, oValue);
case METHOD_POST:
break;
default:
throw new RuntimeException("Wrong http method requested");
}
// doing post request using json to avoid issue with urlencoded symbols
JSONObject json = new JSONObject();
for (Map.Entry<String, String> entry : params.entrySet()) {
json.put(entry.getKey(), entry.getValue());
}
request.setHeader("Content-Type", "application/json");
try {
request.setEntity(new StringEntity(json.toString()));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// sign request
try {
mOAuthConsumer.sign(request);
}
catch (OAuthException e) {
e.printStackTrace();
}
return UpworkRestClient.getJSONObject(request, type, params);
} | [
"private",
"JSONObject",
"sendPostRequest",
"(",
"String",
"url",
",",
"Integer",
"type",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"params",
")",
"throws",
"JSONException",
"{",
"String",
"fullUrl",
"=",
"getFullUrl",
"(",
"url",
")",
";",
"HttpPos... | Send signed POST OAuth request
@param url Relative URL
@param type Type of HTTP request (HTTP method)
@param params Hash of parameters
@throws JSONException If JSON object is invalid or request was abnormal
@return {@link JSONObject} JSON Object that contains data from response | [
"Send",
"signed",
"POST",
"OAuth",
"request"
] | train | https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/OAuthClient.java#L323-L368 |
powermock/powermock | powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java | BsdVirtualMachine.writeString | private void writeString(int fd, String s) throws IOException {
if (s.length() > 0) {
byte b[];
try {
b = s.getBytes("UTF-8");
} catch (java.io.UnsupportedEncodingException x) {
throw new InternalError();
}
BsdVirtualMachine.write(fd, b, 0, b.length);
}
byte b[] = new byte[1];
b[0] = 0;
write(fd, b, 0, 1);
} | java | private void writeString(int fd, String s) throws IOException {
if (s.length() > 0) {
byte b[];
try {
b = s.getBytes("UTF-8");
} catch (java.io.UnsupportedEncodingException x) {
throw new InternalError();
}
BsdVirtualMachine.write(fd, b, 0, b.length);
}
byte b[] = new byte[1];
b[0] = 0;
write(fd, b, 0, 1);
} | [
"private",
"void",
"writeString",
"(",
"int",
"fd",
",",
"String",
"s",
")",
"throws",
"IOException",
"{",
"if",
"(",
"s",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"byte",
"b",
"[",
"]",
";",
"try",
"{",
"b",
"=",
"s",
".",
"getBytes",
"(",... | /*
Write/sends the given to the target VM. String is transmitted in
UTF-8 encoding. | [
"/",
"*",
"Write",
"/",
"sends",
"the",
"given",
"to",
"the",
"target",
"VM",
".",
"String",
"is",
"transmitted",
"in",
"UTF",
"-",
"8",
"encoding",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java#L267-L280 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.delegatedAccount_email_filter_name_GET | public OvhFilter delegatedAccount_email_filter_name_GET(String email, String name) throws IOException {
String qPath = "/email/domain/delegatedAccount/{email}/filter/{name}";
StringBuilder sb = path(qPath, email, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhFilter.class);
} | java | public OvhFilter delegatedAccount_email_filter_name_GET(String email, String name) throws IOException {
String qPath = "/email/domain/delegatedAccount/{email}/filter/{name}";
StringBuilder sb = path(qPath, email, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhFilter.class);
} | [
"public",
"OvhFilter",
"delegatedAccount_email_filter_name_GET",
"(",
"String",
"email",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/domain/delegatedAccount/{email}/filter/{name}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
... | Get this object properties
REST: GET /email/domain/delegatedAccount/{email}/filter/{name}
@param email [required] Email
@param name [required] Filter name | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L244-L249 |
apache/incubator-druid | processing/src/main/java/org/apache/druid/query/TimewarpOperator.java | TimewarpOperator.computeOffset | protected long computeOffset(final long t, final DateTimeZone tz)
{
// start is the beginning of the last period ending within dataInterval
long start = dataInterval.getEndMillis() - periodMillis;
long startOffset = start % periodMillis - originMillis % periodMillis;
if (startOffset < 0) {
startOffset += periodMillis;
}
start -= startOffset;
// tOffset is the offset time t within the last period
long tOffset = t % periodMillis - originMillis % periodMillis;
if (tOffset < 0) {
tOffset += periodMillis;
}
tOffset += start;
return tOffset - t - (tz.getOffset(tOffset) - tz.getOffset(t));
} | java | protected long computeOffset(final long t, final DateTimeZone tz)
{
// start is the beginning of the last period ending within dataInterval
long start = dataInterval.getEndMillis() - periodMillis;
long startOffset = start % periodMillis - originMillis % periodMillis;
if (startOffset < 0) {
startOffset += periodMillis;
}
start -= startOffset;
// tOffset is the offset time t within the last period
long tOffset = t % periodMillis - originMillis % periodMillis;
if (tOffset < 0) {
tOffset += periodMillis;
}
tOffset += start;
return tOffset - t - (tz.getOffset(tOffset) - tz.getOffset(t));
} | [
"protected",
"long",
"computeOffset",
"(",
"final",
"long",
"t",
",",
"final",
"DateTimeZone",
"tz",
")",
"{",
"// start is the beginning of the last period ending within dataInterval",
"long",
"start",
"=",
"dataInterval",
".",
"getEndMillis",
"(",
")",
"-",
"periodMil... | Map time t into the last `period` ending within `dataInterval`
@param t the current time to be mapped into `dataInterval`
@return the offset between the mapped time and time t | [
"Map",
"time",
"t",
"into",
"the",
"last",
"period",
"ending",
"within",
"dataInterval"
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/query/TimewarpOperator.java#L148-L166 |
alkacon/opencms-core | src/org/opencms/jsp/util/CmsJspContentLoadBean.java | CmsJspContentLoadBean.convertResourceList | public static List<CmsJspContentAccessBean> convertResourceList(
CmsObject cms,
Locale locale,
List<CmsResource> resources) {
List<CmsJspContentAccessBean> result = new ArrayList<CmsJspContentAccessBean>(resources.size());
for (int i = 0, size = resources.size(); i < size; i++) {
CmsResource res = resources.get(i);
result.add(new CmsJspContentAccessBean(cms, locale, res));
}
return result;
} | java | public static List<CmsJspContentAccessBean> convertResourceList(
CmsObject cms,
Locale locale,
List<CmsResource> resources) {
List<CmsJspContentAccessBean> result = new ArrayList<CmsJspContentAccessBean>(resources.size());
for (int i = 0, size = resources.size(); i < size; i++) {
CmsResource res = resources.get(i);
result.add(new CmsJspContentAccessBean(cms, locale, res));
}
return result;
} | [
"public",
"static",
"List",
"<",
"CmsJspContentAccessBean",
">",
"convertResourceList",
"(",
"CmsObject",
"cms",
",",
"Locale",
"locale",
",",
"List",
"<",
"CmsResource",
">",
"resources",
")",
"{",
"List",
"<",
"CmsJspContentAccessBean",
">",
"result",
"=",
"ne... | Converts a list of {@link CmsResource} objects to a list of {@link CmsJspContentAccessBean} objects,
using the given locale.<p>
@param cms the current OpenCms user context
@param locale the default locale to use when accessing the content
@param resources a list of of {@link CmsResource} objects that should be converted
@return a list of {@link CmsJspContentAccessBean} objects created from the given {@link CmsResource} objects | [
"Converts",
"a",
"list",
"of",
"{",
"@link",
"CmsResource",
"}",
"objects",
"to",
"a",
"list",
"of",
"{",
"@link",
"CmsJspContentAccessBean",
"}",
"objects",
"using",
"the",
"given",
"locale",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspContentLoadBean.java#L118-L129 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java | TypeUtility.isCollectionOfType | public static boolean isCollectionOfType(TypeName typeName, TypeName elementTypeName) {
return isAssignable(typeName, Collection.class)
&& isEquals(((ParameterizedTypeName) typeName).typeArguments.get(0), elementTypeName);
} | java | public static boolean isCollectionOfType(TypeName typeName, TypeName elementTypeName) {
return isAssignable(typeName, Collection.class)
&& isEquals(((ParameterizedTypeName) typeName).typeArguments.get(0), elementTypeName);
} | [
"public",
"static",
"boolean",
"isCollectionOfType",
"(",
"TypeName",
"typeName",
",",
"TypeName",
"elementTypeName",
")",
"{",
"return",
"isAssignable",
"(",
"typeName",
",",
"Collection",
".",
"class",
")",
"&&",
"isEquals",
"(",
"(",
"(",
"ParameterizedTypeName... | Checks if is collection and if element type is the one passed as parameter.
@param typeName
the type name
@param elementTypeName
the element type name
@return true, if is collection | [
"Checks",
"if",
"is",
"collection",
"and",
"if",
"element",
"type",
"is",
"the",
"one",
"passed",
"as",
"parameter",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java#L697-L700 |
alkacon/opencms-core | src/org/opencms/importexport/CmsExport.java | CmsExport.exportGroup | protected void exportGroup(Element parent, CmsGroup group) throws CmsImportExportException, SAXException {
try {
String parentgroup;
if ((group.getParentId() == null) || group.getParentId().isNullUUID()) {
parentgroup = "";
} else {
parentgroup = getCms().getParent(group.getName()).getName();
}
Element e = parent.addElement(CmsImportVersion10.N_GROUP);
e.addElement(CmsImportVersion10.N_NAME).addText(group.getSimpleName());
e.addElement(CmsImportVersion10.N_DESCRIPTION).addCDATA(group.getDescription());
e.addElement(CmsImportVersion10.N_FLAGS).addText(Integer.toString(group.getFlags()));
e.addElement(CmsImportVersion10.N_PARENTGROUP).addText(parentgroup);
// write the XML
digestElement(parent, e);
} catch (CmsException e) {
CmsMessageContainer message = org.opencms.db.Messages.get().container(
org.opencms.db.Messages.ERR_GET_PARENT_GROUP_1,
group.getName());
if (LOG.isDebugEnabled()) {
LOG.debug(message.key(), e);
}
throw new CmsImportExportException(message, e);
}
} | java | protected void exportGroup(Element parent, CmsGroup group) throws CmsImportExportException, SAXException {
try {
String parentgroup;
if ((group.getParentId() == null) || group.getParentId().isNullUUID()) {
parentgroup = "";
} else {
parentgroup = getCms().getParent(group.getName()).getName();
}
Element e = parent.addElement(CmsImportVersion10.N_GROUP);
e.addElement(CmsImportVersion10.N_NAME).addText(group.getSimpleName());
e.addElement(CmsImportVersion10.N_DESCRIPTION).addCDATA(group.getDescription());
e.addElement(CmsImportVersion10.N_FLAGS).addText(Integer.toString(group.getFlags()));
e.addElement(CmsImportVersion10.N_PARENTGROUP).addText(parentgroup);
// write the XML
digestElement(parent, e);
} catch (CmsException e) {
CmsMessageContainer message = org.opencms.db.Messages.get().container(
org.opencms.db.Messages.ERR_GET_PARENT_GROUP_1,
group.getName());
if (LOG.isDebugEnabled()) {
LOG.debug(message.key(), e);
}
throw new CmsImportExportException(message, e);
}
} | [
"protected",
"void",
"exportGroup",
"(",
"Element",
"parent",
",",
"CmsGroup",
"group",
")",
"throws",
"CmsImportExportException",
",",
"SAXException",
"{",
"try",
"{",
"String",
"parentgroup",
";",
"if",
"(",
"(",
"group",
".",
"getParentId",
"(",
")",
"==",
... | Exports one single group with all it's data.<p>
@param parent the parent node to add the groups to
@param group the group to be exported
@throws CmsImportExportException if something goes wrong
@throws SAXException if something goes wrong processing the manifest.xml | [
"Exports",
"one",
"single",
"group",
"with",
"all",
"it",
"s",
"data",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsExport.java#L938-L966 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/dictionary/CustomDictionary.java | CustomDictionary.add | public static boolean add(String word)
{
if (HanLP.Config.Normalization) word = CharTable.convert(word);
if (contains(word)) return false;
return insert(word, null);
} | java | public static boolean add(String word)
{
if (HanLP.Config.Normalization) word = CharTable.convert(word);
if (contains(word)) return false;
return insert(word, null);
} | [
"public",
"static",
"boolean",
"add",
"(",
"String",
"word",
")",
"{",
"if",
"(",
"HanLP",
".",
"Config",
".",
"Normalization",
")",
"word",
"=",
"CharTable",
".",
"convert",
"(",
"word",
")",
";",
"if",
"(",
"contains",
"(",
"word",
")",
")",
"retur... | 往自定义词典中插入一个新词(非覆盖模式)<br>
动态增删不会持久化到词典文件
@param word 新词 如“裸婚”
@return 是否插入成功(失败的原因可能是不覆盖等,可以通过调试模式了解原因) | [
"往自定义词典中插入一个新词(非覆盖模式)<br",
">",
"动态增删不会持久化到词典文件"
] | train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/dictionary/CustomDictionary.java#L278-L283 |
wellner/jcarafe | jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java | ObjectArrayList.mergeSortFromTo | public void mergeSortFromTo(int from, int to) {
if (size==0) return;
checkRangeFromTo(from, to, size);
java.util.Arrays.sort(elements, from, to+1);
} | java | public void mergeSortFromTo(int from, int to) {
if (size==0) return;
checkRangeFromTo(from, to, size);
java.util.Arrays.sort(elements, from, to+1);
} | [
"public",
"void",
"mergeSortFromTo",
"(",
"int",
"from",
",",
"int",
"to",
")",
"{",
"if",
"(",
"size",
"==",
"0",
")",
"return",
";",
"checkRangeFromTo",
"(",
"from",
",",
"to",
",",
"size",
")",
";",
"java",
".",
"util",
".",
"Arrays",
".",
"sort... | Sorts the specified range of the receiver into
ascending order, according to the <i>natural ordering</i> of its
elements. All elements in this range must implement the
<tt>Comparable</tt> interface. Furthermore, all elements in this range
must be <i>mutually comparable</i> (that is, <tt>e1.compareTo(e2)</tt>
must not throw a <tt>ClassCastException</tt> for any elements
<tt>e1</tt> and <tt>e2</tt> in the array).<p>
This sort is guaranteed to be <i>stable</i>: equal elements will
not be reordered as a result of the sort.<p>
The sorting algorithm is a modified mergesort (in which the merge is
omitted if the highest element in the low sublist is less than the
lowest element in the high sublist). This algorithm offers guaranteed
n*log(n) performance, and can approach linear performance on nearly
sorted lists.
<p><b>You should never call this method unless you are sure that this particular sorting algorithm is the right one for your data set.</b>
It is generally better to call <tt>sort()</tt> or <tt>sortFromTo(...)</tt> instead, because those methods automatically choose the best sorting algorithm.
@param from the index of the first element (inclusive) to be sorted.
@param to the index of the last element (inclusive) to be sorted.
@exception IndexOutOfBoundsException index is out of range (<tt>size()>0 && (from<0 || from>to || to>=size())</tt>). | [
"Sorts",
"the",
"specified",
"range",
"of",
"the",
"receiver",
"into",
"ascending",
"order",
"according",
"to",
"the",
"<i",
">",
"natural",
"ordering<",
"/",
"i",
">",
"of",
"its",
"elements",
".",
"All",
"elements",
"in",
"this",
"range",
"must",
"implem... | train | https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java#L550-L554 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.domain_account_accountName_migrate_destinationServiceName_destinationEmailAddress_destinationEmailAddress_checkMigrate_GET | public OvhMigrationCheckStruct domain_account_accountName_migrate_destinationServiceName_destinationEmailAddress_destinationEmailAddress_checkMigrate_GET(String domain, String accountName, String destinationServiceName, String destinationEmailAddress) throws IOException {
String qPath = "/email/domain/{domain}/account/{accountName}/migrate/{destinationServiceName}/destinationEmailAddress/{destinationEmailAddress}/checkMigrate";
StringBuilder sb = path(qPath, domain, accountName, destinationServiceName, destinationEmailAddress);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhMigrationCheckStruct.class);
} | java | public OvhMigrationCheckStruct domain_account_accountName_migrate_destinationServiceName_destinationEmailAddress_destinationEmailAddress_checkMigrate_GET(String domain, String accountName, String destinationServiceName, String destinationEmailAddress) throws IOException {
String qPath = "/email/domain/{domain}/account/{accountName}/migrate/{destinationServiceName}/destinationEmailAddress/{destinationEmailAddress}/checkMigrate";
StringBuilder sb = path(qPath, domain, accountName, destinationServiceName, destinationEmailAddress);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhMigrationCheckStruct.class);
} | [
"public",
"OvhMigrationCheckStruct",
"domain_account_accountName_migrate_destinationServiceName_destinationEmailAddress_destinationEmailAddress_checkMigrate_GET",
"(",
"String",
"domain",
",",
"String",
"accountName",
",",
"String",
"destinationServiceName",
",",
"String",
"destinationEm... | Check if it's possible to migrate
REST: GET /email/domain/{domain}/account/{accountName}/migrate/{destinationServiceName}/destinationEmailAddress/{destinationEmailAddress}/checkMigrate
@param domain [required] Name of your domain name
@param accountName [required] Name of account
@param destinationServiceName [required] Service name allowed as migration destination
@param destinationEmailAddress [required] Destination account name
API beta | [
"Check",
"if",
"it",
"s",
"possible",
"to",
"migrate"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L507-L512 |
apptentive/apptentive-android | apptentive/src/main/java/com/apptentive/android/sdk/module/engagement/interaction/model/MessageCenterInteraction.java | MessageCenterInteraction.getRegularStatus | public MessageCenterStatus getRegularStatus() {
InteractionConfiguration configuration = getConfiguration();
if (configuration == null) {
return null;
}
JSONObject status = configuration.optJSONObject(KEY_STATUS);
if (status == null) {
return null;
}
String statusBody = status.optString(KEY_STATUS_BODY);
if (statusBody == null || statusBody.isEmpty()) {
return null;
}
return new MessageCenterStatus(statusBody, null);
} | java | public MessageCenterStatus getRegularStatus() {
InteractionConfiguration configuration = getConfiguration();
if (configuration == null) {
return null;
}
JSONObject status = configuration.optJSONObject(KEY_STATUS);
if (status == null) {
return null;
}
String statusBody = status.optString(KEY_STATUS_BODY);
if (statusBody == null || statusBody.isEmpty()) {
return null;
}
return new MessageCenterStatus(statusBody, null);
} | [
"public",
"MessageCenterStatus",
"getRegularStatus",
"(",
")",
"{",
"InteractionConfiguration",
"configuration",
"=",
"getConfiguration",
"(",
")",
";",
"if",
"(",
"configuration",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"JSONObject",
"status",
"=",
... | Regular status shows customer's hours, expected time until response | [
"Regular",
"status",
"shows",
"customer",
"s",
"hours",
"expected",
"time",
"until",
"response"
] | train | https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/module/engagement/interaction/model/MessageCenterInteraction.java#L217-L231 |
Red5/red5-server-common | src/main/java/org/red5/server/stream/StreamService.java | StreamService.closeStream | public void closeStream(IConnection conn, Number streamId) {
log.info("closeStream stream id: {} connection: {}", streamId, conn.getSessionId());
if (conn instanceof IStreamCapableConnection) {
IStreamCapableConnection scConn = (IStreamCapableConnection) conn;
IClientStream stream = scConn.getStreamById(streamId);
if (stream != null) {
if (stream instanceof IClientBroadcastStream) {
// this is a broadcasting stream (from Flash Player to Red5)
IClientBroadcastStream bs = (IClientBroadcastStream) stream;
IBroadcastScope bsScope = getBroadcastScope(conn.getScope(), bs.getPublishedName());
if (bsScope != null && conn instanceof BaseConnection) {
((BaseConnection) conn).unregisterBasicScope(bsScope);
}
}
stream.close();
scConn.deleteStreamById(streamId);
// in case of broadcasting stream, status is sent automatically by Red5
if (!(stream instanceof IClientBroadcastStream)) {
StreamService.sendNetStreamStatus(conn, StatusCodes.NS_PLAY_STOP, "Stream closed by server", stream.getName(), Status.STATUS, streamId);
}
} else {
log.info("Stream not found - streamId: {} connection: {}", streamId, conn.getSessionId());
}
} else {
log.warn("Connection is not instance of IStreamCapableConnection: {}", conn);
}
} | java | public void closeStream(IConnection conn, Number streamId) {
log.info("closeStream stream id: {} connection: {}", streamId, conn.getSessionId());
if (conn instanceof IStreamCapableConnection) {
IStreamCapableConnection scConn = (IStreamCapableConnection) conn;
IClientStream stream = scConn.getStreamById(streamId);
if (stream != null) {
if (stream instanceof IClientBroadcastStream) {
// this is a broadcasting stream (from Flash Player to Red5)
IClientBroadcastStream bs = (IClientBroadcastStream) stream;
IBroadcastScope bsScope = getBroadcastScope(conn.getScope(), bs.getPublishedName());
if (bsScope != null && conn instanceof BaseConnection) {
((BaseConnection) conn).unregisterBasicScope(bsScope);
}
}
stream.close();
scConn.deleteStreamById(streamId);
// in case of broadcasting stream, status is sent automatically by Red5
if (!(stream instanceof IClientBroadcastStream)) {
StreamService.sendNetStreamStatus(conn, StatusCodes.NS_PLAY_STOP, "Stream closed by server", stream.getName(), Status.STATUS, streamId);
}
} else {
log.info("Stream not found - streamId: {} connection: {}", streamId, conn.getSessionId());
}
} else {
log.warn("Connection is not instance of IStreamCapableConnection: {}", conn);
}
} | [
"public",
"void",
"closeStream",
"(",
"IConnection",
"conn",
",",
"Number",
"streamId",
")",
"{",
"log",
".",
"info",
"(",
"\"closeStream stream id: {} connection: {}\"",
",",
"streamId",
",",
"conn",
".",
"getSessionId",
"(",
")",
")",
";",
"if",
"(",
"conn"... | Close stream. This method can close both IClientBroadcastStream (coming from Flash Player to Red5) and ISubscriberStream (from Red5
to Flash Player). Corresponding application handlers (streamSubscriberClose, etc.) are called as if close was initiated by Flash
Player.
It is recommended to remember stream id in application handlers, ex.:
<pre>
public void streamBroadcastStart(IBroadcastStream stream) {
super.streamBroadcastStart(stream);
if (stream instanceof IClientBroadcastStream) {
int publishedStreamId = ((ClientBroadcastStream) stream).getStreamId();
Red5.getConnectionLocal().setAttribute(PUBLISHED_STREAM_ID_ATTRIBUTE, publishedStreamId);
}
}
</pre>
<pre>
public void streamPlaylistItemPlay(IPlaylistSubscriberStream stream, IPlayItem item, boolean isLive) {
super.streamPlaylistItemPlay(stream, item, isLive);
Red5.getConnectionLocal().setAttribute(WATCHED_STREAM_ID_ATTRIBUTE, stream.getStreamId());
}
</pre>
When stream is closed, corresponding NetStream status will be sent to stream provider / consumers. Implementation is based on Red5's
StreamService.close()
@param conn
client connection
@param streamId
stream ID (number: 1,2,...) | [
"Close",
"stream",
".",
"This",
"method",
"can",
"close",
"both",
"IClientBroadcastStream",
"(",
"coming",
"from",
"Flash",
"Player",
"to",
"Red5",
")",
"and",
"ISubscriberStream",
"(",
"from",
"Red5",
"to",
"Flash",
"Player",
")",
".",
"Corresponding",
"appli... | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/stream/StreamService.java#L183-L209 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/CacheableWorkspaceDataManager.java | CacheableWorkspaceDataManager.getReferencedPropertiesData | protected List<PropertyData> getReferencedPropertiesData(final String identifier) throws RepositoryException
{
List<PropertyData> refProps = null;
if (cache.isEnabled())
{
refProps = cache.getReferencedProperties(identifier);
if (refProps != null)
{
return refProps;
}
}
final DataRequest request = new DataRequest(identifier, DataRequest.GET_REFERENCES);
try
{
request.start();
if (cache.isEnabled())
{
// Try first to get the value from the cache since a
// request could have been launched just before
refProps = cache.getReferencedProperties(identifier);
if (refProps != null)
{
return refProps;
}
}
return executeAction(new PrivilegedExceptionAction<List<PropertyData>>()
{
public List<PropertyData> run() throws RepositoryException
{
List<PropertyData> refProps = CacheableWorkspaceDataManager.super.getReferencesData(identifier, false);
if (cache.isEnabled())
{
cache.addReferencedProperties(identifier, refProps);
}
return refProps;
}
});
}
finally
{
request.done();
}
} | java | protected List<PropertyData> getReferencedPropertiesData(final String identifier) throws RepositoryException
{
List<PropertyData> refProps = null;
if (cache.isEnabled())
{
refProps = cache.getReferencedProperties(identifier);
if (refProps != null)
{
return refProps;
}
}
final DataRequest request = new DataRequest(identifier, DataRequest.GET_REFERENCES);
try
{
request.start();
if (cache.isEnabled())
{
// Try first to get the value from the cache since a
// request could have been launched just before
refProps = cache.getReferencedProperties(identifier);
if (refProps != null)
{
return refProps;
}
}
return executeAction(new PrivilegedExceptionAction<List<PropertyData>>()
{
public List<PropertyData> run() throws RepositoryException
{
List<PropertyData> refProps = CacheableWorkspaceDataManager.super.getReferencesData(identifier, false);
if (cache.isEnabled())
{
cache.addReferencedProperties(identifier, refProps);
}
return refProps;
}
});
}
finally
{
request.done();
}
} | [
"protected",
"List",
"<",
"PropertyData",
">",
"getReferencedPropertiesData",
"(",
"final",
"String",
"identifier",
")",
"throws",
"RepositoryException",
"{",
"List",
"<",
"PropertyData",
">",
"refProps",
"=",
"null",
";",
"if",
"(",
"cache",
".",
"isEnabled",
"... | Get referenced properties data.
@param identifier
referenceable identifier
@return List of PropertyData
@throws RepositoryException
Repository error | [
"Get",
"referenced",
"properties",
"data",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/CacheableWorkspaceDataManager.java#L1626-L1669 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/P2sVpnGatewaysInner.java | P2sVpnGatewaysInner.beginGenerateVpnProfile | public VpnProfileResponseInner beginGenerateVpnProfile(String resourceGroupName, String gatewayName, AuthenticationMethod authenticationMethod) {
return beginGenerateVpnProfileWithServiceResponseAsync(resourceGroupName, gatewayName, authenticationMethod).toBlocking().single().body();
} | java | public VpnProfileResponseInner beginGenerateVpnProfile(String resourceGroupName, String gatewayName, AuthenticationMethod authenticationMethod) {
return beginGenerateVpnProfileWithServiceResponseAsync(resourceGroupName, gatewayName, authenticationMethod).toBlocking().single().body();
} | [
"public",
"VpnProfileResponseInner",
"beginGenerateVpnProfile",
"(",
"String",
"resourceGroupName",
",",
"String",
"gatewayName",
",",
"AuthenticationMethod",
"authenticationMethod",
")",
"{",
"return",
"beginGenerateVpnProfileWithServiceResponseAsync",
"(",
"resourceGroupName",
... | Generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group.
@param resourceGroupName The name of the resource group.
@param gatewayName The name of the P2SVpnGateway.
@param authenticationMethod VPN client Authentication Method. Possible values are: 'EAPTLS' and 'EAPMSCHAPv2'. Possible values include: 'EAPTLS', 'EAPMSCHAPv2'
@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 VpnProfileResponseInner object if successful. | [
"Generates",
"VPN",
"profile",
"for",
"P2S",
"client",
"of",
"the",
"P2SVpnGateway",
"in",
"the",
"specified",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/P2sVpnGatewaysInner.java#L1297-L1299 |
box/box-java-sdk | src/main/java/com/box/sdk/URLTemplate.java | URLTemplate.buildWithQuery | public URL buildWithQuery(String base, String queryString, Object... values) {
String urlString = String.format(base + this.template, values) + queryString;
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
assert false : "An invalid URL template indicates a bug in the SDK.";
}
return url;
} | java | public URL buildWithQuery(String base, String queryString, Object... values) {
String urlString = String.format(base + this.template, values) + queryString;
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
assert false : "An invalid URL template indicates a bug in the SDK.";
}
return url;
} | [
"public",
"URL",
"buildWithQuery",
"(",
"String",
"base",
",",
"String",
"queryString",
",",
"Object",
"...",
"values",
")",
"{",
"String",
"urlString",
"=",
"String",
".",
"format",
"(",
"base",
"+",
"this",
".",
"template",
",",
"values",
")",
"+",
"qu... | Build a URL with Query String and URL Parameters.
@param base base URL
@param queryString query string
@param values URL Parameters
@return URL | [
"Build",
"a",
"URL",
"with",
"Query",
"String",
"and",
"URL",
"Parameters",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/URLTemplate.java#L46-L56 |
cdk/cdk | storage/smiles/src/main/java/org/openscience/cdk/smiles/BeamToCDK.java | BeamToCDK.newTetrahedral | private IStereoElement newTetrahedral(int u, int[] vs, IAtom[] atoms, Configuration c) {
// no way to handle tetrahedral configurations with implicit
// hydrogen or lone pair at the moment
if (vs.length != 4) {
// sanity check
if (vs.length != 3) return null;
// there is an implicit hydrogen (or lone-pair) we insert the
// central atom in sorted position
vs = insert(u, vs);
}
// @TH1/@TH2 = anti-clockwise and clockwise respectively
Stereo stereo = c == Configuration.TH1 ? Stereo.ANTI_CLOCKWISE : Stereo.CLOCKWISE;
return new TetrahedralChirality(atoms[u], new IAtom[]{atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]]},
stereo);
} | java | private IStereoElement newTetrahedral(int u, int[] vs, IAtom[] atoms, Configuration c) {
// no way to handle tetrahedral configurations with implicit
// hydrogen or lone pair at the moment
if (vs.length != 4) {
// sanity check
if (vs.length != 3) return null;
// there is an implicit hydrogen (or lone-pair) we insert the
// central atom in sorted position
vs = insert(u, vs);
}
// @TH1/@TH2 = anti-clockwise and clockwise respectively
Stereo stereo = c == Configuration.TH1 ? Stereo.ANTI_CLOCKWISE : Stereo.CLOCKWISE;
return new TetrahedralChirality(atoms[u], new IAtom[]{atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]]},
stereo);
} | [
"private",
"IStereoElement",
"newTetrahedral",
"(",
"int",
"u",
",",
"int",
"[",
"]",
"vs",
",",
"IAtom",
"[",
"]",
"atoms",
",",
"Configuration",
"c",
")",
"{",
"// no way to handle tetrahedral configurations with implicit",
"// hydrogen or lone pair at the moment",
"i... | Creates a tetrahedral element for the given configuration. Currently only
tetrahedral centres with 4 explicit atoms are handled.
@param u central atom
@param vs neighboring atom indices (in order)
@param atoms array of the CDK atoms (pre-converted)
@param c the configuration of the neighbors (vs) for the order they
are given
@return tetrahedral stereo element for addition to an atom container | [
"Creates",
"a",
"tetrahedral",
"element",
"for",
"the",
"given",
"configuration",
".",
"Currently",
"only",
"tetrahedral",
"centres",
"with",
"4",
"explicit",
"atoms",
"are",
"handled",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/storage/smiles/src/main/java/org/openscience/cdk/smiles/BeamToCDK.java#L447-L466 |
UrielCh/ovh-java-sdk | ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java | ApiOvhSms.serviceName_users_login_DELETE | public void serviceName_users_login_DELETE(String serviceName, String login) throws IOException {
String qPath = "/sms/{serviceName}/users/{login}";
StringBuilder sb = path(qPath, serviceName, login);
exec(qPath, "DELETE", sb.toString(), null);
} | java | public void serviceName_users_login_DELETE(String serviceName, String login) throws IOException {
String qPath = "/sms/{serviceName}/users/{login}";
StringBuilder sb = path(qPath, serviceName, login);
exec(qPath, "DELETE", sb.toString(), null);
} | [
"public",
"void",
"serviceName_users_login_DELETE",
"(",
"String",
"serviceName",
",",
"String",
"login",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/sms/{serviceName}/users/{login}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"... | Delete the sms user given
REST: DELETE /sms/{serviceName}/users/{login}
@param serviceName [required] The internal name of your SMS offer
@param login [required] The sms user login | [
"Delete",
"the",
"sms",
"user",
"given"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java#L703-L707 |
mijecu25/dsa | src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java | LinearSearch.searchLast | public static <E> int searchLast(E[] array, E value) {
return LinearSearch.searchLast(array, value, 1);
} | java | public static <E> int searchLast(E[] array, E value) {
return LinearSearch.searchLast(array, value, 1);
} | [
"public",
"static",
"<",
"E",
">",
"int",
"searchLast",
"(",
"E",
"[",
"]",
"array",
",",
"E",
"value",
")",
"{",
"return",
"LinearSearch",
".",
"searchLast",
"(",
"array",
",",
"value",
",",
"1",
")",
";",
"}"
] | Search for the value in the array and return the index of the first occurrence from the
end of the array
@param <E> the type of elements in this array.
@param array array that we are searching in.
@param value value that is being searched in the array.
@return the index where the value is found in the array, else -1. | [
"Search",
"for",
"the",
"value",
"in",
"the",
"array",
"and",
"return",
"the",
"index",
"of",
"the",
"first",
"occurrence",
"from",
"the",
"end",
"of",
"the",
"array"
] | train | https://github.com/mijecu25/dsa/blob/a22971b746833e78a3939ae4de65e8f6bf2e3fd4/src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java#L160-L162 |
Azure/azure-sdk-for-java | hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ClustersInner.java | ClustersInner.rotateDiskEncryptionKey | public void rotateDiskEncryptionKey(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) {
rotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body();
} | java | public void rotateDiskEncryptionKey(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) {
rotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body();
} | [
"public",
"void",
"rotateDiskEncryptionKey",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
",",
"ClusterDiskEncryptionParameters",
"parameters",
")",
"{",
"rotateDiskEncryptionKeyWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterName",
",",
... | Rotate disk encryption key of the specified HDInsight cluster.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@param parameters The parameters for the disk encryption operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Rotate",
"disk",
"encryption",
"key",
"of",
"the",
"specified",
"HDInsight",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ClustersInner.java#L1293-L1295 |
EdwardRaff/JSAT | JSAT/src/jsat/utils/concurrent/AtomicDoubleArray.java | AtomicDoubleArray.getAndSet | public double getAndSet(int i, double newValue)
{
long oldL = larray.getAndSet(i, Double.doubleToRawLongBits(newValue));
return Double.longBitsToDouble(oldL);
} | java | public double getAndSet(int i, double newValue)
{
long oldL = larray.getAndSet(i, Double.doubleToRawLongBits(newValue));
return Double.longBitsToDouble(oldL);
} | [
"public",
"double",
"getAndSet",
"(",
"int",
"i",
",",
"double",
"newValue",
")",
"{",
"long",
"oldL",
"=",
"larray",
".",
"getAndSet",
"(",
"i",
",",
"Double",
".",
"doubleToRawLongBits",
"(",
"newValue",
")",
")",
";",
"return",
"Double",
".",
"longBit... | Atomically sets the element at position {@code i} to the given value
and returns the old value.
@param i the index
@param newValue the new value
@return the previous value | [
"Atomically",
"sets",
"the",
"element",
"at",
"position",
"{",
"@code",
"i",
"}",
"to",
"the",
"given",
"value",
"and",
"returns",
"the",
"old",
"value",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/utils/concurrent/AtomicDoubleArray.java#L113-L117 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/ComputeNodesImpl.java | ComputeNodesImpl.addUser | public void addUser(String poolId, String nodeId, ComputeNodeUser user) {
addUserWithServiceResponseAsync(poolId, nodeId, user).toBlocking().single().body();
} | java | public void addUser(String poolId, String nodeId, ComputeNodeUser user) {
addUserWithServiceResponseAsync(poolId, nodeId, user).toBlocking().single().body();
} | [
"public",
"void",
"addUser",
"(",
"String",
"poolId",
",",
"String",
"nodeId",
",",
"ComputeNodeUser",
"user",
")",
"{",
"addUserWithServiceResponseAsync",
"(",
"poolId",
",",
"nodeId",
",",
"user",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
... | Adds a user account to the specified compute node.
You can add a user account to a node only when it is in the idle or running state.
@param poolId The ID of the pool that contains the compute node.
@param nodeId The ID of the machine on which you want to create a user account.
@param user The user account to be created.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws BatchErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Adds",
"a",
"user",
"account",
"to",
"the",
"specified",
"compute",
"node",
".",
"You",
"can",
"add",
"a",
"user",
"account",
"to",
"a",
"node",
"only",
"when",
"it",
"is",
"in",
"the",
"idle",
"or",
"running",
"state",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/ComputeNodesImpl.java#L178-L180 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/util/SecretDetector.java | SecretDetector.maskText | private static String maskText(String text, int begPos, int endPos)
{
// Convert the SQL statement to a char array to obe able to modify it.
char[] chars = text.toCharArray();
// Mask the value in the SQL statement using *.
for (int curPos = begPos; curPos < endPos; curPos++)
{
chars[curPos] = '☺';
}
// Convert it back to a string
return String.valueOf(chars);
} | java | private static String maskText(String text, int begPos, int endPos)
{
// Convert the SQL statement to a char array to obe able to modify it.
char[] chars = text.toCharArray();
// Mask the value in the SQL statement using *.
for (int curPos = begPos; curPos < endPos; curPos++)
{
chars[curPos] = '☺';
}
// Convert it back to a string
return String.valueOf(chars);
} | [
"private",
"static",
"String",
"maskText",
"(",
"String",
"text",
",",
"int",
"begPos",
",",
"int",
"endPos",
")",
"{",
"// Convert the SQL statement to a char array to obe able to modify it.",
"char",
"[",
"]",
"chars",
"=",
"text",
".",
"toCharArray",
"(",
")",
... | Masks given text between begin position and end position.
@param text text to mask
@param begPos begin position (inclusive)
@param endPos end position (exclusive)
@return masked text | [
"Masks",
"given",
"text",
"between",
"begin",
"position",
"and",
"end",
"position",
"."
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/util/SecretDetector.java#L155-L168 |
apache/groovy | subprojects/groovy-sql/src/main/java/groovy/sql/GroovyResultSetExtension.java | GroovyResultSetExtension.setProperty | public void setProperty(String columnName, Object newValue) {
try {
getResultSet().updateObject(columnName, newValue);
updated = true;
}
catch (SQLException e) {
throw new MissingPropertyException(columnName, GroovyResultSetProxy.class, e);
}
} | java | public void setProperty(String columnName, Object newValue) {
try {
getResultSet().updateObject(columnName, newValue);
updated = true;
}
catch (SQLException e) {
throw new MissingPropertyException(columnName, GroovyResultSetProxy.class, e);
}
} | [
"public",
"void",
"setProperty",
"(",
"String",
"columnName",
",",
"Object",
"newValue",
")",
"{",
"try",
"{",
"getResultSet",
"(",
")",
".",
"updateObject",
"(",
"columnName",
",",
"newValue",
")",
";",
"updated",
"=",
"true",
";",
"}",
"catch",
"(",
"S... | Updates the designated column with an <code>Object</code> value.
@param columnName the SQL name of the column
@param newValue the updated value
@throws MissingPropertyException if an SQLException happens while setting the new value
@see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object)
@see ResultSet#updateObject(java.lang.String, java.lang.Object) | [
"Updates",
"the",
"designated",
"column",
"with",
"an",
"<code",
">",
"Object<",
"/",
"code",
">",
"value",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/GroovyResultSetExtension.java#L133-L141 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java | CommerceOrderPersistenceImpl.findByBillingAddressId | @Override
public List<CommerceOrder> findByBillingAddressId(long billingAddressId,
int start, int end) {
return findByBillingAddressId(billingAddressId, start, end, null);
} | java | @Override
public List<CommerceOrder> findByBillingAddressId(long billingAddressId,
int start, int end) {
return findByBillingAddressId(billingAddressId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceOrder",
">",
"findByBillingAddressId",
"(",
"long",
"billingAddressId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByBillingAddressId",
"(",
"billingAddressId",
",",
"start",
",",
"end",
",",... | Returns a range of all the commerce orders where billingAddressId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param billingAddressId the billing address ID
@param start the lower bound of the range of commerce orders
@param end the upper bound of the range of commerce orders (not inclusive)
@return the range of matching commerce orders | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"orders",
"where",
"billingAddressId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java#L2538-L2542 |
threerings/nenya | core/src/main/java/com/threerings/cast/builder/SpritePanel.java | SpritePanel.generateSprite | protected void generateSprite ()
{
int components[] = _model.getSelectedComponents();
CharacterDescriptor desc = new CharacterDescriptor(components, null);
CharacterSprite sprite = _charmgr.getCharacter(desc);
setSprite(sprite);
} | java | protected void generateSprite ()
{
int components[] = _model.getSelectedComponents();
CharacterDescriptor desc = new CharacterDescriptor(components, null);
CharacterSprite sprite = _charmgr.getCharacter(desc);
setSprite(sprite);
} | [
"protected",
"void",
"generateSprite",
"(",
")",
"{",
"int",
"components",
"[",
"]",
"=",
"_model",
".",
"getSelectedComponents",
"(",
")",
";",
"CharacterDescriptor",
"desc",
"=",
"new",
"CharacterDescriptor",
"(",
"components",
",",
"null",
")",
";",
"Charac... | Generates a new character sprite for display to reflect the
currently selected character components. | [
"Generates",
"a",
"new",
"character",
"sprite",
"for",
"display",
"to",
"reflect",
"the",
"currently",
"selected",
"character",
"components",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/cast/builder/SpritePanel.java#L88-L94 |
networknt/light-4j | client/src/main/java/com/networknt/client/Http2Client.java | Http2Client.propagateHeaders | public Result propagateHeaders(ClientRequest request, final HttpServerExchange exchange) {
String tid = exchange.getRequestHeaders().getFirst(HttpStringConstants.TRACEABILITY_ID);
String token = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
String cid = exchange.getRequestHeaders().getFirst(HttpStringConstants.CORRELATION_ID);
return populateHeader(request, token, cid, tid);
} | java | public Result propagateHeaders(ClientRequest request, final HttpServerExchange exchange) {
String tid = exchange.getRequestHeaders().getFirst(HttpStringConstants.TRACEABILITY_ID);
String token = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
String cid = exchange.getRequestHeaders().getFirst(HttpStringConstants.CORRELATION_ID);
return populateHeader(request, token, cid, tid);
} | [
"public",
"Result",
"propagateHeaders",
"(",
"ClientRequest",
"request",
",",
"final",
"HttpServerExchange",
"exchange",
")",
"{",
"String",
"tid",
"=",
"exchange",
".",
"getRequestHeaders",
"(",
")",
".",
"getFirst",
"(",
"HttpStringConstants",
".",
"TRACEABILITY_I... | Support API to API calls with scope token. The token is the original token from consumer and
the client credentials token of caller API is added from cache.
This method is used in API to API call
@param request the http request
@param exchange the http server exchange | [
"Support",
"API",
"to",
"API",
"calls",
"with",
"scope",
"token",
".",
"The",
"token",
"is",
"the",
"original",
"token",
"from",
"consumer",
"and",
"the",
"client",
"credentials",
"token",
"of",
"caller",
"API",
"is",
"added",
"from",
"cache",
"."
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/client/src/main/java/com/networknt/client/Http2Client.java#L350-L355 |
hdbeukel/james-core | src/main/java/org/jamesframework/core/subset/neigh/adv/DisjointMultiAdditionNeighbourhood.java | DisjointMultiAdditionNeighbourhood.getAllMoves | @Override
public List<SubsetMove> getAllMoves(SubsetSolution solution) {
// create empty list to store generated moves
List<SubsetMove> moves = new ArrayList<>();
// get set of candidate IDs for addition (fixed IDs are discarded)
Set<Integer> addCandidates = getAddCandidates(solution);
// compute number of additions
int curNumAdd = numAdditions(addCandidates, solution);
if(curNumAdd == 0){
// impossible: return empty set
return moves;
}
// create all moves that add curNumAdd items
Set<Integer> add;
SubsetIterator<Integer> itAdd = new SubsetIterator<>(addCandidates, curNumAdd);
while(itAdd.hasNext()){
add = itAdd.next();
// create and add move
moves.add(new GeneralSubsetMove(add, Collections.emptySet()));
}
// return all moves
return moves;
} | java | @Override
public List<SubsetMove> getAllMoves(SubsetSolution solution) {
// create empty list to store generated moves
List<SubsetMove> moves = new ArrayList<>();
// get set of candidate IDs for addition (fixed IDs are discarded)
Set<Integer> addCandidates = getAddCandidates(solution);
// compute number of additions
int curNumAdd = numAdditions(addCandidates, solution);
if(curNumAdd == 0){
// impossible: return empty set
return moves;
}
// create all moves that add curNumAdd items
Set<Integer> add;
SubsetIterator<Integer> itAdd = new SubsetIterator<>(addCandidates, curNumAdd);
while(itAdd.hasNext()){
add = itAdd.next();
// create and add move
moves.add(new GeneralSubsetMove(add, Collections.emptySet()));
}
// return all moves
return moves;
} | [
"@",
"Override",
"public",
"List",
"<",
"SubsetMove",
">",
"getAllMoves",
"(",
"SubsetSolution",
"solution",
")",
"{",
"// create empty list to store generated moves",
"List",
"<",
"SubsetMove",
">",
"moves",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"// get s... | <p>
Generates the list of all possible moves that perform \(k\) additions, where \(k\) is the fixed number
specified at construction. Note: taking into account the current number of unselected items, the imposed
maximum subset size (if set) and the fixed IDs (if any) may result in fewer additions (as many as possible).
</p>
<p>
May return an empty list if no moves can be generated.
</p>
@param solution solution for which all possible multi addition moves are generated
@return list of all multi addition moves, may be empty | [
"<p",
">",
"Generates",
"the",
"list",
"of",
"all",
"possible",
"moves",
"that",
"perform",
"\\",
"(",
"k",
"\\",
")",
"additions",
"where",
"\\",
"(",
"k",
"\\",
")",
"is",
"the",
"fixed",
"number",
"specified",
"at",
"construction",
".",
"Note",
":",... | train | https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/subset/neigh/adv/DisjointMultiAdditionNeighbourhood.java#L176-L198 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/backend/BackendManager.java | BackendManager.convertExceptionToJson | public Object convertExceptionToJson(Throwable pExp, JmxRequest pJmxReq) {
JsonConvertOptions opts = getJsonConvertOptions(pJmxReq);
try {
JSONObject expObj =
(JSONObject) converters.getToJsonConverter().convertToJson(pExp,null,opts);
return expObj;
} catch (AttributeNotFoundException e) {
// Cannot happen, since we dont use a path
return null;
}
} | java | public Object convertExceptionToJson(Throwable pExp, JmxRequest pJmxReq) {
JsonConvertOptions opts = getJsonConvertOptions(pJmxReq);
try {
JSONObject expObj =
(JSONObject) converters.getToJsonConverter().convertToJson(pExp,null,opts);
return expObj;
} catch (AttributeNotFoundException e) {
// Cannot happen, since we dont use a path
return null;
}
} | [
"public",
"Object",
"convertExceptionToJson",
"(",
"Throwable",
"pExp",
",",
"JmxRequest",
"pJmxReq",
")",
"{",
"JsonConvertOptions",
"opts",
"=",
"getJsonConvertOptions",
"(",
"pJmxReq",
")",
";",
"try",
"{",
"JSONObject",
"expObj",
"=",
"(",
"JSONObject",
")",
... | Convert a Throwable to a JSON object so that it can be included in an error response
@param pExp throwable to convert
@param pJmxReq the request from where to take the serialization options
@return the exception. | [
"Convert",
"a",
"Throwable",
"to",
"a",
"JSON",
"object",
"so",
"that",
"it",
"can",
"be",
"included",
"in",
"an",
"error",
"response"
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/backend/BackendManager.java#L187-L198 |
spotify/docker-maven-plugin | src/main/java/com/spotify/docker/CompositeImageName.java | CompositeImageName.create | static CompositeImageName create(final String imageName, final List<String> imageTags)
throws MojoExecutionException {
final boolean containsTag = containsTag(imageName);
final String name = containsTag ? StringUtils.substringBeforeLast(imageName, ":") : imageName;
if (StringUtils.isBlank(name)) {
throw new MojoExecutionException("imageName not set!");
}
final List<String> tags = new ArrayList<>();
final String tag = containsTag ? StringUtils.substringAfterLast(imageName, ":") : "";
if (StringUtils.isNotBlank(tag)) {
tags.add(tag);
}
if (imageTags != null) {
tags.addAll(imageTags);
}
if (tags.size() == 0) {
throw new MojoExecutionException("No tag included in imageName and no imageTags set!");
}
return new CompositeImageName(name, tags);
} | java | static CompositeImageName create(final String imageName, final List<String> imageTags)
throws MojoExecutionException {
final boolean containsTag = containsTag(imageName);
final String name = containsTag ? StringUtils.substringBeforeLast(imageName, ":") : imageName;
if (StringUtils.isBlank(name)) {
throw new MojoExecutionException("imageName not set!");
}
final List<String> tags = new ArrayList<>();
final String tag = containsTag ? StringUtils.substringAfterLast(imageName, ":") : "";
if (StringUtils.isNotBlank(tag)) {
tags.add(tag);
}
if (imageTags != null) {
tags.addAll(imageTags);
}
if (tags.size() == 0) {
throw new MojoExecutionException("No tag included in imageName and no imageTags set!");
}
return new CompositeImageName(name, tags);
} | [
"static",
"CompositeImageName",
"create",
"(",
"final",
"String",
"imageName",
",",
"final",
"List",
"<",
"String",
">",
"imageTags",
")",
"throws",
"MojoExecutionException",
"{",
"final",
"boolean",
"containsTag",
"=",
"containsTag",
"(",
"imageName",
")",
";",
... | An image name can be a plain image name or in the composite format <name>:<tag> and
this factory method makes sure that we get the plain image name as well as all the desired tags
for an image, including any composite tag.
@param imageName Image name.
@param imageTags List of image tags.
@return {@link CompositeImageName}
@throws MojoExecutionException | [
"An",
"image",
"name",
"can",
"be",
"a",
"plain",
"image",
"name",
"or",
"in",
"the",
"composite",
"format",
"<",
";",
"name>",
";",
":",
"<",
";",
"tag>",
";",
"and",
"this",
"factory",
"method",
"makes",
"sure",
"that",
"we",
"get",
"the",
... | train | https://github.com/spotify/docker-maven-plugin/blob/c5bbc1c4993f5dc37c96457fa5de5af8308f7829/src/main/java/com/spotify/docker/CompositeImageName.java#L53-L75 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata2/model/curves/DiscountCurveInterpolation.java | DiscountCurveInterpolation.createDiscountCurveFromAnnualizedZeroRates | public static DiscountCurveInterpolation createDiscountCurveFromAnnualizedZeroRates(
String name, LocalDate referenceDate,
double[] times, RandomVariable[] givenAnnualizedZeroRates, boolean[] isParameter,
InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) {
RandomVariable[] givenDiscountFactors = new RandomVariable[givenAnnualizedZeroRates.length];
for(int timeIndex=0; timeIndex<times.length;timeIndex++) {
givenDiscountFactors[timeIndex] = givenAnnualizedZeroRates[timeIndex].add(1.0).pow(-times[timeIndex]);
}
return createDiscountCurveFromDiscountFactors(name, referenceDate, times, givenDiscountFactors, isParameter, interpolationMethod, extrapolationMethod, interpolationEntity);
} | java | public static DiscountCurveInterpolation createDiscountCurveFromAnnualizedZeroRates(
String name, LocalDate referenceDate,
double[] times, RandomVariable[] givenAnnualizedZeroRates, boolean[] isParameter,
InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) {
RandomVariable[] givenDiscountFactors = new RandomVariable[givenAnnualizedZeroRates.length];
for(int timeIndex=0; timeIndex<times.length;timeIndex++) {
givenDiscountFactors[timeIndex] = givenAnnualizedZeroRates[timeIndex].add(1.0).pow(-times[timeIndex]);
}
return createDiscountCurveFromDiscountFactors(name, referenceDate, times, givenDiscountFactors, isParameter, interpolationMethod, extrapolationMethod, interpolationEntity);
} | [
"public",
"static",
"DiscountCurveInterpolation",
"createDiscountCurveFromAnnualizedZeroRates",
"(",
"String",
"name",
",",
"LocalDate",
"referenceDate",
",",
"double",
"[",
"]",
"times",
",",
"RandomVariable",
"[",
"]",
"givenAnnualizedZeroRates",
",",
"boolean",
"[",
... | Create a discount curve from given times and given annualized zero rates using given interpolation and extrapolation methods.
The discount factor is determined by
<code>
givenDiscountFactors[timeIndex] = Math.pow(1.0 + givenAnnualizedZeroRates[timeIndex], -times[timeIndex]);
</code>
@param name The name of this discount curve.
@param referenceDate The reference date for this curve, i.e., the date which defined t=0.
@param times Array of times as doubles.
@param givenAnnualizedZeroRates Array of corresponding zero rates.
@param isParameter Array of booleans specifying whether this point is served "as as parameter", e.g., whether it is calibrates (e.g. using CalibratedCurves).
@param interpolationMethod The interpolation method used for the curve.
@param extrapolationMethod The extrapolation method used for the curve.
@param interpolationEntity The entity interpolated/extrapolated.
@return A new discount factor object. | [
"Create",
"a",
"discount",
"curve",
"from",
"given",
"times",
"and",
"given",
"annualized",
"zero",
"rates",
"using",
"given",
"interpolation",
"and",
"extrapolation",
"methods",
".",
"The",
"discount",
"factor",
"is",
"determined",
"by",
"<code",
">",
"givenDis... | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/DiscountCurveInterpolation.java#L325-L337 |
alipay/sofa-rpc | core/api/src/main/java/com/alipay/sofa/rpc/transport/ChannelContext.java | ChannelContext.putHeadCache | public void putHeadCache(Short key, String value) {
if (headerCache == null) {
synchronized (this) {
if (headerCache == null) {
headerCache = new TwoWayMap<Short, String>();
}
}
}
if (headerCache != null && !headerCache.containsKey(key)) {
headerCache.put(key, value);
}
} | java | public void putHeadCache(Short key, String value) {
if (headerCache == null) {
synchronized (this) {
if (headerCache == null) {
headerCache = new TwoWayMap<Short, String>();
}
}
}
if (headerCache != null && !headerCache.containsKey(key)) {
headerCache.put(key, value);
}
} | [
"public",
"void",
"putHeadCache",
"(",
"Short",
"key",
",",
"String",
"value",
")",
"{",
"if",
"(",
"headerCache",
"==",
"null",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"headerCache",
"==",
"null",
")",
"{",
"headerCache",
"=",
"new... | Put header cache
@param key the key
@param value the value | [
"Put",
"header",
"cache"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/transport/ChannelContext.java#L64-L75 |
moparisthebest/beehive | beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/databinding/datagrid/AbstractHtmlTableCell.java | AbstractHtmlTableCell.setBehavior | public void setBehavior(String name, Object value, String facet)
throws JspException {
String s = Bundle.getString("Tags_BehaviorFacetNotSupported", new Object[]{facet});
throw new JspException(s);
} | java | public void setBehavior(String name, Object value, String facet)
throws JspException {
String s = Bundle.getString("Tags_BehaviorFacetNotSupported", new Object[]{facet});
throw new JspException(s);
} | [
"public",
"void",
"setBehavior",
"(",
"String",
"name",
",",
"Object",
"value",
",",
"String",
"facet",
")",
"throws",
"JspException",
"{",
"String",
"s",
"=",
"Bundle",
".",
"getString",
"(",
"\"Tags_BehaviorFacetNotSupported\"",
",",
"new",
"Object",
"[",
"]... | <p>
Base support for setting behavior values via the {@link IBehaviorConsumer} interface. The
AbstractHtmlTableCell does not support any attributes by default. Attributes set via this
interface are used to configure internal functionality of the tags which is not exposed
via JSP tag attributes.
</p>
@param name the name of the behavior
@param value the value of the behavior
@param facet the name of a facet of the tag to which the behavior will be applied. This is optional.
@throws JspException | [
"<p",
">",
"Base",
"support",
"for",
"setting",
"behavior",
"values",
"via",
"the",
"{"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/databinding/datagrid/AbstractHtmlTableCell.java#L461-L465 |
facebookarchive/hadoop-20 | src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/FairScheduler.java | FairScheduler.getAvailableSlots | private int getAvailableSlots(TaskTrackerStatus tts, TaskType type) {
return getMaxSlots(tts, type) - occupiedSlotsAfterHeartbeat(tts, type);
} | java | private int getAvailableSlots(TaskTrackerStatus tts, TaskType type) {
return getMaxSlots(tts, type) - occupiedSlotsAfterHeartbeat(tts, type);
} | [
"private",
"int",
"getAvailableSlots",
"(",
"TaskTrackerStatus",
"tts",
",",
"TaskType",
"type",
")",
"{",
"return",
"getMaxSlots",
"(",
"tts",
",",
"type",
")",
"-",
"occupiedSlotsAfterHeartbeat",
"(",
"tts",
",",
"type",
")",
";",
"}"
] | Obtain the how many more slots can be scheduled on this tasktracker
@param tts The status of the tasktracker
@param type The type of the task to be scheduled
@return the number of tasks can be scheduled | [
"Obtain",
"the",
"how",
"many",
"more",
"slots",
"can",
"be",
"scheduled",
"on",
"this",
"tasktracker"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/FairScheduler.java#L805-L807 |
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/jboss/logging/Logger.java | Logger.logf | public void logf(Level level, String format, Object param1) {
if (isEnabled(level)) {
doLogf(level, FQCN, format, new Object[] { param1 }, null);
}
} | java | public void logf(Level level, String format, Object param1) {
if (isEnabled(level)) {
doLogf(level, FQCN, format, new Object[] { param1 }, null);
}
} | [
"public",
"void",
"logf",
"(",
"Level",
"level",
",",
"String",
"format",
",",
"Object",
"param1",
")",
"{",
"if",
"(",
"isEnabled",
"(",
"level",
")",
")",
"{",
"doLogf",
"(",
"level",
",",
"FQCN",
",",
"format",
",",
"new",
"Object",
"[",
"]",
"{... | Issue a formatted log message at the given log level.
@param level the level
@param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor
@param param1 the sole parameter | [
"Issue",
"a",
"formatted",
"log",
"message",
"at",
"the",
"given",
"log",
"level",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L2295-L2299 |
Whiley/WhileyCompiler | src/main/java/wyil/check/FlowTypeCheck.java | FlowTypeCheck.extractElementType | public SemanticType extractElementType(SemanticType.Reference type, SyntacticItem item) {
if (type == null) {
return null;
} else {
return type.getElement();
}
} | java | public SemanticType extractElementType(SemanticType.Reference type, SyntacticItem item) {
if (type == null) {
return null;
} else {
return type.getElement();
}
} | [
"public",
"SemanticType",
"extractElementType",
"(",
"SemanticType",
".",
"Reference",
"type",
",",
"SyntacticItem",
"item",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"return",
"type",
".",
"getElement",
... | Extract the element type from a reference. The array type can be null if some
earlier part of type checking generated an error message and we are just
continuing after that.
@param type
@param item
@return | [
"Extract",
"the",
"element",
"type",
"from",
"a",
"reference",
".",
"The",
"array",
"type",
"can",
"be",
"null",
"if",
"some",
"earlier",
"part",
"of",
"type",
"checking",
"generated",
"an",
"error",
"message",
"and",
"we",
"are",
"just",
"continuing",
"af... | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L1978-L1984 |
vdmeer/asciitable | src/main/java/de/vandermeer/asciitable/AT_Row.java | AT_Row.setPaddingTopBottom | public AT_Row setPaddingTopBottom(int paddingTop, int paddingBottom){
if(this.hasCells()){
for(AT_Cell cell : this.getCells()){
cell.getContext().setPaddingTopBottom(paddingTop, paddingBottom);
}
}
return this;
} | java | public AT_Row setPaddingTopBottom(int paddingTop, int paddingBottom){
if(this.hasCells()){
for(AT_Cell cell : this.getCells()){
cell.getContext().setPaddingTopBottom(paddingTop, paddingBottom);
}
}
return this;
} | [
"public",
"AT_Row",
"setPaddingTopBottom",
"(",
"int",
"paddingTop",
",",
"int",
"paddingBottom",
")",
"{",
"if",
"(",
"this",
".",
"hasCells",
"(",
")",
")",
"{",
"for",
"(",
"AT_Cell",
"cell",
":",
"this",
".",
"getCells",
"(",
")",
")",
"{",
"cell",... | Sets top and bottom padding for all cells in the row (only if both values are not smaller than 0).
@param paddingTop new top padding, ignored if smaller than 0
@param paddingBottom new bottom padding, ignored if smaller than 0
@return this to allow chaining | [
"Sets",
"top",
"and",
"bottom",
"padding",
"for",
"all",
"cells",
"in",
"the",
"row",
"(",
"only",
"if",
"both",
"values",
"are",
"not",
"smaller",
"than",
"0",
")",
"."
] | train | https://github.com/vdmeer/asciitable/blob/b6a73710271c89f9c749603be856ba84a969ed5f/src/main/java/de/vandermeer/asciitable/AT_Row.java#L285-L292 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/GridTable.java | GridTable.init | public void init(BaseDatabase database, Record record)
{
super.init(database, record);
m_gridList = new DataRecordList();
m_iEndOfFileIndex = UNKNOWN_POSITION; // Actual end of file (-1 means don't know)
m_gridBuffer = new DataRecordBuffer();
m_gridNew = new DataRecordBuffer();
m_iPhysicalFilePosition = UNKNOWN_POSITION;
m_iLogicalFilePosition = UNKNOWN_POSITION;
if (((record.getOpenMode() & DBConstants.OPEN_READ_ONLY) != DBConstants.OPEN_READ_ONLY)
&& (record.getCounterField() != null))
record.setOpenMode(record.getOpenMode() | DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY); // Must have for GridTable to re-read.
} | java | public void init(BaseDatabase database, Record record)
{
super.init(database, record);
m_gridList = new DataRecordList();
m_iEndOfFileIndex = UNKNOWN_POSITION; // Actual end of file (-1 means don't know)
m_gridBuffer = new DataRecordBuffer();
m_gridNew = new DataRecordBuffer();
m_iPhysicalFilePosition = UNKNOWN_POSITION;
m_iLogicalFilePosition = UNKNOWN_POSITION;
if (((record.getOpenMode() & DBConstants.OPEN_READ_ONLY) != DBConstants.OPEN_READ_ONLY)
&& (record.getCounterField() != null))
record.setOpenMode(record.getOpenMode() | DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY); // Must have for GridTable to re-read.
} | [
"public",
"void",
"init",
"(",
"BaseDatabase",
"database",
",",
"Record",
"record",
")",
"{",
"super",
".",
"init",
"(",
"database",
",",
"record",
")",
";",
"m_gridList",
"=",
"new",
"DataRecordList",
"(",
")",
";",
"m_iEndOfFileIndex",
"=",
"UNKNOWN_POSITI... | Constructor.
@param database Should be null, as the last table on the chain contains the database.
@param record The record's current table will be changed to grid table and moved down my list. | [
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/GridTable.java#L132-L147 |
operasoftware/operaprestodriver | src/com/opera/core/systems/common/lang/OperaStrings.java | OperaStrings.escapeJsString | public static String escapeJsString(String string, String quote) {
// This should be expanded to match all invalid characters (e.g. newlines) but for the moment
// we'll trust we'll only get quotes.
Pattern escapePattern = Pattern.compile("([^\\\\])" + quote);
// Prepend a space so that the regex can match quotes at the beginning of the string
Matcher m = escapePattern.matcher(" " + string);
StringBuffer sb = new StringBuffer();
while (m.find()) {
// $1 -> inserts the character before the quote \\\\\" -> \\", apparently just \" isn't
// treated literally.
m.appendReplacement(sb, "$1\\\\" + quote);
}
m.appendTail(sb);
// Remove the prepended space.
return sb.substring(1);
} | java | public static String escapeJsString(String string, String quote) {
// This should be expanded to match all invalid characters (e.g. newlines) but for the moment
// we'll trust we'll only get quotes.
Pattern escapePattern = Pattern.compile("([^\\\\])" + quote);
// Prepend a space so that the regex can match quotes at the beginning of the string
Matcher m = escapePattern.matcher(" " + string);
StringBuffer sb = new StringBuffer();
while (m.find()) {
// $1 -> inserts the character before the quote \\\\\" -> \\", apparently just \" isn't
// treated literally.
m.appendReplacement(sb, "$1\\\\" + quote);
}
m.appendTail(sb);
// Remove the prepended space.
return sb.substring(1);
} | [
"public",
"static",
"String",
"escapeJsString",
"(",
"String",
"string",
",",
"String",
"quote",
")",
"{",
"// This should be expanded to match all invalid characters (e.g. newlines) but for the moment",
"// we'll trust we'll only get quotes.",
"Pattern",
"escapePattern",
"=",
"Pat... | Escape characters for safe insertion in a JavaScript string.
@param string the string to escape
@param quote the type of quote to escape. Either " or '
@return the escaped string | [
"Escape",
"characters",
"for",
"safe",
"insertion",
"in",
"a",
"JavaScript",
"string",
"."
] | train | https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/common/lang/OperaStrings.java#L96-L115 |
beangle/beangle3 | commons/web/src/main/java/org/beangle/commons/web/util/CookieUtils.java | CookieUtils.getCookie | public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
Cookie returnCookie = null;
if (cookies == null) { return returnCookie; }
for (int i = 0; i < cookies.length; i++) {
Cookie thisCookie = cookies[i];
if (thisCookie.getName().equals(name) && !thisCookie.getValue().equals("")) {
returnCookie = thisCookie;
break;
}
}
return returnCookie;
} | java | public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
Cookie returnCookie = null;
if (cookies == null) { return returnCookie; }
for (int i = 0; i < cookies.length; i++) {
Cookie thisCookie = cookies[i];
if (thisCookie.getName().equals(name) && !thisCookie.getValue().equals("")) {
returnCookie = thisCookie;
break;
}
}
return returnCookie;
} | [
"public",
"static",
"Cookie",
"getCookie",
"(",
"HttpServletRequest",
"request",
",",
"String",
"name",
")",
"{",
"Cookie",
"[",
"]",
"cookies",
"=",
"request",
".",
"getCookies",
"(",
")",
";",
"Cookie",
"returnCookie",
"=",
"null",
";",
"if",
"(",
"cooki... | Convenience method to get a cookie by name
@param request
the current request
@param name
the name of the cookie to find
@return the cookie (if found), null if not found | [
"Convenience",
"method",
"to",
"get",
"a",
"cookie",
"by",
"name"
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/web/src/main/java/org/beangle/commons/web/util/CookieUtils.java#L83-L96 |
milaboratory/milib | src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java | QualityTrimmer.extendRange | public static Range extendRange(SequenceQuality quality, QualityTrimmerParameters parameters, Range initialRange) {
int lower = pabs(trim(quality, 0, initialRange.getLower(), -1, false, parameters));
int upper = pabs(trim(quality, initialRange.getUpper(), quality.size(), +1, false, parameters)) + 1;
return new Range(lower, upper, initialRange.isReverse());
} | java | public static Range extendRange(SequenceQuality quality, QualityTrimmerParameters parameters, Range initialRange) {
int lower = pabs(trim(quality, 0, initialRange.getLower(), -1, false, parameters));
int upper = pabs(trim(quality, initialRange.getUpper(), quality.size(), +1, false, parameters)) + 1;
return new Range(lower, upper, initialRange.isReverse());
} | [
"public",
"static",
"Range",
"extendRange",
"(",
"SequenceQuality",
"quality",
",",
"QualityTrimmerParameters",
"parameters",
",",
"Range",
"initialRange",
")",
"{",
"int",
"lower",
"=",
"pabs",
"(",
"trim",
"(",
"quality",
",",
"0",
",",
"initialRange",
".",
... | Extend initialRange to the biggest possible range that fulfils the criteria of QualityTrimmer along the whole extended region.
The criteria may not be fulfilled for the initial range.
@param quality quality values
@param parameters trimming parameters
@param initialRange initial range to extend
@return | [
"Extend",
"initialRange",
"to",
"the",
"biggest",
"possible",
"range",
"that",
"fulfils",
"the",
"criteria",
"of",
"QualityTrimmer",
"along",
"the",
"whole",
"extended",
"region",
"."
] | train | https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java#L158-L162 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/alert/ExtensionAlert.java | ExtensionAlert.showAlertAddDialog | public void showAlertAddDialog(HttpMessage httpMessage, int historyType) {
if (dialogAlertAdd == null || !dialogAlertAdd.isVisible()) {
dialogAlertAdd = new AlertAddDialog(getView().getMainFrame(), false);
dialogAlertAdd.setHttpMessage(httpMessage, historyType);
dialogAlertAdd.setVisible(true);
}
} | java | public void showAlertAddDialog(HttpMessage httpMessage, int historyType) {
if (dialogAlertAdd == null || !dialogAlertAdd.isVisible()) {
dialogAlertAdd = new AlertAddDialog(getView().getMainFrame(), false);
dialogAlertAdd.setHttpMessage(httpMessage, historyType);
dialogAlertAdd.setVisible(true);
}
} | [
"public",
"void",
"showAlertAddDialog",
"(",
"HttpMessage",
"httpMessage",
",",
"int",
"historyType",
")",
"{",
"if",
"(",
"dialogAlertAdd",
"==",
"null",
"||",
"!",
"dialogAlertAdd",
".",
"isVisible",
"(",
")",
")",
"{",
"dialogAlertAdd",
"=",
"new",
"AlertAd... | Shows the Add Alert dialogue, using the given {@code HttpMessage} and history type for the {@code HistoryReference} that
will be created if the user creates the alert. The current session will be used to create the {@code HistoryReference}.
The alert created will be added to the newly created {@code HistoryReference}.
<p>
Should be used when the alert is added to a temporary {@code HistoryReference} as the temporary {@code HistoryReference}s
are deleted when the session is closed.
@param httpMessage the {@code HttpMessage} that will be used to create the {@code HistoryReference}, must not be
{@code null}.
@param historyType the type of the history reference that will be used to create the {@code HistoryReference}.
@since 2.7.0
@see Model#getSession()
@see HistoryReference#HistoryReference(org.parosproxy.paros.model.Session, int, HttpMessage) | [
"Shows",
"the",
"Add",
"Alert",
"dialogue",
"using",
"the",
"given",
"{",
"@code",
"HttpMessage",
"}",
"and",
"history",
"type",
"for",
"the",
"{",
"@code",
"HistoryReference",
"}",
"that",
"will",
"be",
"created",
"if",
"the",
"user",
"creates",
"the",
"a... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/alert/ExtensionAlert.java#L981-L987 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/ui/SeaGlassTextFieldUI.java | SeaGlassTextFieldUI.getContext | private SeaGlassContext getContext(JComponent c, Region region, int state) {
SynthStyle style = findStyle;
if (region == SeaGlassRegion.SEARCH_FIELD_CANCEL_BUTTON) {
style = cancelStyle;
}
return SeaGlassContext.getContext(SeaGlassContext.class, c, region, style, state);
} | java | private SeaGlassContext getContext(JComponent c, Region region, int state) {
SynthStyle style = findStyle;
if (region == SeaGlassRegion.SEARCH_FIELD_CANCEL_BUTTON) {
style = cancelStyle;
}
return SeaGlassContext.getContext(SeaGlassContext.class, c, region, style, state);
} | [
"private",
"SeaGlassContext",
"getContext",
"(",
"JComponent",
"c",
",",
"Region",
"region",
",",
"int",
"state",
")",
"{",
"SynthStyle",
"style",
"=",
"findStyle",
";",
"if",
"(",
"region",
"==",
"SeaGlassRegion",
".",
"SEARCH_FIELD_CANCEL_BUTTON",
")",
"{",
... | DOCUMENT ME!
@param c DOCUMENT ME!
@param region DOCUMENT ME!
@param state DOCUMENT ME!
@return DOCUMENT ME! | [
"DOCUMENT",
"ME!"
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/ui/SeaGlassTextFieldUI.java#L378-L386 |
stanfy/goro | goro/src/main/java/com/stanfy/enroscar/goro/Goro.java | Goro.bindAndAutoReconnectWith | public static BoundGoro bindAndAutoReconnectWith(final Context context) {
if (context == null) {
throw new IllegalArgumentException("Context cannot be null");
}
return new BoundGoroImpl(context, null);
} | java | public static BoundGoro bindAndAutoReconnectWith(final Context context) {
if (context == null) {
throw new IllegalArgumentException("Context cannot be null");
}
return new BoundGoroImpl(context, null);
} | [
"public",
"static",
"BoundGoro",
"bindAndAutoReconnectWith",
"(",
"final",
"Context",
"context",
")",
"{",
"if",
"(",
"context",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Context cannot be null\"",
")",
";",
"}",
"return",
"new",
... | Creates a Goro implementation that binds to {@link com.stanfy.enroscar.goro.GoroService}
in order to run scheduled tasks in service context.
<p>
This method is functionally identical to
</p>
<pre>
BoundGoro goro = Goro.bindWith(context, new BoundGoro.OnUnexpectedDisconnection() {
public void onServiceDisconnected(BoundGoro goro) {
goro.bind();
}
});
</pre>
@param context context that will bind to the service
@return Goro implementation that binds to {@link GoroService}.
@see #bindWith(Context, BoundGoro.OnUnexpectedDisconnection) | [
"Creates",
"a",
"Goro",
"implementation",
"that",
"binds",
"to",
"{"
] | train | https://github.com/stanfy/goro/blob/6618e63a926833d61f492ec611ee77668d756820/goro/src/main/java/com/stanfy/enroscar/goro/Goro.java#L69-L74 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/stat/ns/nstrafficdomain_stats.java | nstrafficdomain_stats.get | public static nstrafficdomain_stats get(nitro_service service, Long td) throws Exception{
nstrafficdomain_stats obj = new nstrafficdomain_stats();
obj.set_td(td);
nstrafficdomain_stats response = (nstrafficdomain_stats) obj.stat_resource(service);
return response;
} | java | public static nstrafficdomain_stats get(nitro_service service, Long td) throws Exception{
nstrafficdomain_stats obj = new nstrafficdomain_stats();
obj.set_td(td);
nstrafficdomain_stats response = (nstrafficdomain_stats) obj.stat_resource(service);
return response;
} | [
"public",
"static",
"nstrafficdomain_stats",
"get",
"(",
"nitro_service",
"service",
",",
"Long",
"td",
")",
"throws",
"Exception",
"{",
"nstrafficdomain_stats",
"obj",
"=",
"new",
"nstrafficdomain_stats",
"(",
")",
";",
"obj",
".",
"set_td",
"(",
"td",
")",
"... | Use this API to fetch statistics of nstrafficdomain_stats resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"statistics",
"of",
"nstrafficdomain_stats",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/ns/nstrafficdomain_stats.java#L201-L206 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.