method stringlengths 13 441k | clean_method stringlengths 7 313k | doc stringlengths 17 17.3k | comment stringlengths 3 1.42k | method_name stringlengths 1 273 | extra dict | imports list | imports_info stringlengths 19 34.8k | cluster_imports_info stringlengths 15 3.66k | libraries list | libraries_info stringlengths 6 661 | id int64 0 2.92M |
|---|---|---|---|---|---|---|---|---|---|---|---|
return Response.status(Response.Status.BAD_REQUEST)
.type(MediaType.APPLICATION_JSON)
.entity(toJson(ex))
.build();
} | return Response.status(Response.Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON) .entity(toJson(ex)) .build(); } | /**
* Map any ConstraintViolationException to a json response responding with
* {@link javax.ws.rs.core.Response.Status#INTERNAL_SERVER_ERROR}.
*
* @param ex the ConstraintViolationException to map to a response.
* @return a response mapped from the supplied ConstraintViolationException.
*/ | Map any ConstraintViolationException to a json response responding with <code>javax.ws.rs.core.Response.Status#INTERNAL_SERVER_ERROR</code> | toResponse | {
"repo_name": "dan-zx/zekke-webapp",
"path": "src/main/java/com/zekke/webapp/ws/rest/provider/ConstraintViolationExceptionHandler.java",
"license": "apache-2.0",
"size": 3247
} | [
"javax.ws.rs.core.MediaType",
"javax.ws.rs.core.Response"
] | import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; | import javax.ws.rs.core.*; | [
"javax.ws"
] | javax.ws; | 2,421,807 |
ControllerServiceReferencingComponentsEntity updateControllerServiceReferencingComponents(
Map<String, Revision> referenceRevisions, String controllerServiceId, ScheduledState scheduledState, ControllerServiceState controllerServiceState); | ControllerServiceReferencingComponentsEntity updateControllerServiceReferencingComponents( Map<String, Revision> referenceRevisions, String controllerServiceId, ScheduledState scheduledState, ControllerServiceState controllerServiceState); | /**
* Updates the referencing components for the specified controller service.
*
* @param referenceRevisions revisions
* @param controllerServiceId id
* @param scheduledState state
* @param controllerServiceState the value of state
* @return The referencing component dtos
*/ | Updates the referencing components for the specified controller service | updateControllerServiceReferencingComponents | {
"repo_name": "zhengsg/nifi",
"path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java",
"license": "apache-2.0",
"size": 73433
} | [
"java.util.Map",
"org.apache.nifi.controller.ScheduledState",
"org.apache.nifi.controller.service.ControllerServiceState",
"org.apache.nifi.web.api.entity.ControllerServiceReferencingComponentsEntity"
] | import java.util.Map; import org.apache.nifi.controller.ScheduledState; import org.apache.nifi.controller.service.ControllerServiceState; import org.apache.nifi.web.api.entity.ControllerServiceReferencingComponentsEntity; | import java.util.*; import org.apache.nifi.controller.*; import org.apache.nifi.controller.service.*; import org.apache.nifi.web.api.entity.*; | [
"java.util",
"org.apache.nifi"
] | java.util; org.apache.nifi; | 1,845,588 |
public static void main(String[] argv) {
boolean removeExistingDatabase = false;
String databaseName = "access.db";
for (int i = 0; i < argv.length; i++) {
if (argv[i].equals("-r")) {
removeExistingDatabase = true;
} else if (argv[i].equals("-?")) {
usage();
} else if (argv[i].startsWith("-")) {
usage();
} else {
if ((argv.length - i) != 1)
usage();
databaseName = argv[i];
break;
}
}
try {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setInitializeCache(true);
envConfig.setInitializeLocking(true);
if (create) {
envConfig.setAllowCreate(true);
}
Environment env = new Environment(new File("."), envConfig);
// Remove the previous database.
if (removeExistingDatabase) {
env.removeDatabase(null, databaseName, null);
}
// create the app and run it
AccessExample app = new AccessExample(env, databaseName);
app.run();
} catch (DatabaseException e) {
e.printStackTrace();
System.exit(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
System.exit(0);
}
private Database db;
private SortedMap map;
private Environment env;
public AccessExample(Environment env, String databaseName)
throws Exception {
this.env = env;
//
// Lets mimic the db.AccessExample 100%
// and use plain old byte arrays to store the key and data strings.
//
ByteArrayBinding keyBinding = new ByteArrayBinding();
ByteArrayBinding dataBinding = new ByteArrayBinding();
//
// Open a data store.
//
DatabaseConfig dbConfig = new DatabaseConfig();
if (create) {
dbConfig.setAllowCreate(true);
dbConfig.setType(DatabaseType.BTREE);
}
this.db = env.openDatabase(null, databaseName, null, dbConfig);
//
// Now create a collection style map view of the data store
// so that it is easy to work with the data in the database.
//
this.map = new StoredSortedMap(db, keyBinding, dataBinding, true);
} | static void function(String[] argv) { boolean removeExistingDatabase = false; String databaseName = STR; for (int i = 0; i < argv.length; i++) { if (argv[i].equals("-r")) { removeExistingDatabase = true; } else if (argv[i].equals("-?")) { usage(); } else if (argv[i].startsWith("-")) { usage(); } else { if ((argv.length - i) != 1) usage(); databaseName = argv[i]; break; } } try { EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(true); envConfig.setInitializeCache(true); envConfig.setInitializeLocking(true); if (create) { envConfig.setAllowCreate(true); } Environment env = new Environment(new File("."), envConfig); if (removeExistingDatabase) { env.removeDatabase(null, databaseName, null); } AccessExample app = new AccessExample(env, databaseName); app.run(); } catch (DatabaseException e) { e.printStackTrace(); System.exit(1); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.exit(0); } private Database db; private SortedMap map; private Environment env; public AccessExample(Environment env, String databaseName) throws Exception { this.env = env; ByteArrayBinding dataBinding = new ByteArrayBinding(); if (create) { dbConfig.setAllowCreate(true); dbConfig.setType(DatabaseType.BTREE); } this.db = env.openDatabase(null, databaseName, null, dbConfig); } | /**
* The main program for the AccessExample class
*
*@param argv The command line arguments
*/ | The main program for the AccessExample class | main | {
"repo_name": "mollstam/UnrealPy",
"path": "UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/db-4.7.25.0/examples_java/src/collections/access/AccessExample.java",
"license": "mit",
"size": 8239
} | [
"com.sleepycat.bind.ByteArrayBinding",
"com.sleepycat.db.Database",
"com.sleepycat.db.DatabaseException",
"com.sleepycat.db.DatabaseType",
"com.sleepycat.db.Environment",
"com.sleepycat.db.EnvironmentConfig",
"java.io.File",
"java.io.FileNotFoundException",
"java.util.SortedMap"
] | import com.sleepycat.bind.ByteArrayBinding; import com.sleepycat.db.Database; import com.sleepycat.db.DatabaseException; import com.sleepycat.db.DatabaseType; import com.sleepycat.db.Environment; import com.sleepycat.db.EnvironmentConfig; import java.io.File; import java.io.FileNotFoundException; import java.util.SortedMap; | import com.sleepycat.bind.*; import com.sleepycat.db.*; import java.io.*; import java.util.*; | [
"com.sleepycat.bind",
"com.sleepycat.db",
"java.io",
"java.util"
] | com.sleepycat.bind; com.sleepycat.db; java.io; java.util; | 2,328,442 |
public synchronized TestConfigurationResult getTestConfigurationResult(Long resultId) {
return cache.get(resultId);
}
| synchronized TestConfigurationResult function(Long resultId) { return cache.get(resultId); } | /**
* Gets a TestResult from cache identified by the given job id.
*
* @param resultId the result id
* @return the TestResult or null, if no job was found
*/ | Gets a TestResult from cache identified by the given job id | getTestConfigurationResult | {
"repo_name": "NABUCCO/org.nabucco.testautomation.engine",
"path": "org.nabucco.testautomation.engine/src/main/org/nabucco/testautomation/engine/execution/cache/TestConfigurationResultCache.java",
"license": "epl-1.0",
"size": 2079
} | [
"org.nabucco.testautomation.result.facade.datatype.TestConfigurationResult"
] | import org.nabucco.testautomation.result.facade.datatype.TestConfigurationResult; | import org.nabucco.testautomation.result.facade.datatype.*; | [
"org.nabucco.testautomation"
] | org.nabucco.testautomation; | 2,171,283 |
public static KEKIdentifier getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
return getInstance(ASN1Sequence.getInstance(obj, explicit));
} | static KEKIdentifier function( ASN1TaggedObject obj, boolean explicit) { return getInstance(ASN1Sequence.getInstance(obj, explicit)); } | /**
* return a KEKIdentifier object from a tagged object.
*
* @param obj the tagged object holding the object we want.
* @param explicit true if the object is meant to be explicitly
* tagged false otherwise.
* @exception IllegalArgumentException if the object held by the
* tagged object cannot be converted.
*/ | return a KEKIdentifier object from a tagged object | getInstance | {
"repo_name": "sake/bouncycastle-java",
"path": "src/org/bouncycastle/asn1/cms/KEKIdentifier.java",
"license": "mit",
"size": 3754
} | [
"org.bouncycastle.asn1.ASN1Sequence",
"org.bouncycastle.asn1.ASN1TaggedObject"
] | import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; | import org.bouncycastle.asn1.*; | [
"org.bouncycastle.asn1"
] | org.bouncycastle.asn1; | 259,203 |
void generateTrunk()
{
int var1 = this.basePos[0];
int var2 = this.basePos[1];
int var3 = this.basePos[1] + this.height;
int var4 = this.basePos[2];
int[] var5 = new int[] {var1, var2, var4};
int[] var6 = new int[] {var1, var3, var4};
this.placeBlockLine(var5, var6, TFCBlocks.LogNatural);
if (this.trunkSize == 2)
{
++var5[0];
++var6[0];
this.placeBlockLine(var5, var6, TFCBlocks.LogNatural);
++var5[2];
++var6[2];
this.placeBlockLine(var5, var6, TFCBlocks.LogNatural);
var5[0] += -1;
var6[0] += -1;
this.placeBlockLine(var5, var6, TFCBlocks.LogNatural);
}
}
| void generateTrunk() { int var1 = this.basePos[0]; int var2 = this.basePos[1]; int var3 = this.basePos[1] + this.height; int var4 = this.basePos[2]; int[] var5 = new int[] {var1, var2, var4}; int[] var6 = new int[] {var1, var3, var4}; this.placeBlockLine(var5, var6, TFCBlocks.LogNatural); if (this.trunkSize == 2) { ++var5[0]; ++var6[0]; this.placeBlockLine(var5, var6, TFCBlocks.LogNatural); ++var5[2]; ++var6[2]; this.placeBlockLine(var5, var6, TFCBlocks.LogNatural); var5[0] += -1; var6[0] += -1; this.placeBlockLine(var5, var6, TFCBlocks.LogNatural); } } | /**
* Places the trunk for the big tree that is being generated. Able to generate double-sized trunks by changing a
* field that is always 1 to 2.
*/ | Places the trunk for the big tree that is being generated. Able to generate double-sized trunks by changing a field that is always 1 to 2 | generateTrunk | {
"repo_name": "raymondbh/TFCraft",
"path": "src/Common/com/bioxx/tfc/WorldGen/Generators/Trees/WorldGenCustomBigTree.java",
"license": "gpl-3.0",
"size": 12660
} | [
"com.bioxx.tfc.api.TFCBlocks"
] | import com.bioxx.tfc.api.TFCBlocks; | import com.bioxx.tfc.api.*; | [
"com.bioxx.tfc"
] | com.bioxx.tfc; | 1,422,228 |
private UnicodeSet applyPropertyPattern(String pattern, ParsePosition ppos, SymbolTable symbols) {
int pos = ppos.getIndex();
// On entry, ppos should point to one of the following locations:
// Minimum length is 5 characters, e.g. \p{L}
if ((pos+5) > pattern.length()) {
return null;
}
boolean posix = false; // true for [:pat:], false for \p{pat} \P{pat} \N{pat}
boolean isName = false; // true for \N{pat}, o/w false
boolean invert = false;
// Look for an opening [:, [:^, \p, or \P
if (pattern.regionMatches(pos, "[:", 0, 2)) {
posix = true;
pos = Utility.skipWhitespace(pattern, pos+2);
if (pos < pattern.length() && pattern.charAt(pos) == '^') {
++pos;
invert = true;
}
} else if (pattern.regionMatches(true, pos, "\\p", 0, 2) ||
pattern.regionMatches(pos, "\\N", 0, 2)) {
char c = pattern.charAt(pos+1);
invert = (c == 'P');
isName = (c == 'N');
pos = Utility.skipWhitespace(pattern, pos+2);
if (pos == pattern.length() || pattern.charAt(pos++) != '{') {
// Syntax error; "\p" or "\P" not followed by "{"
return null;
}
} else {
// Open delimiter not seen
return null;
}
// Look for the matching close delimiter, either :] or }
int close = pattern.indexOf(posix ? ":]" : "}", pos);
if (close < 0) {
// Syntax error; close delimiter missing
return null;
}
// Look for an '=' sign. If this is present, we will parse a
// medium \p{gc=Cf} or long \p{GeneralCategory=Format}
// pattern.
int equals = pattern.indexOf('=', pos);
String propName, valueName;
if (equals >= 0 && equals < close && !isName) {
// Equals seen; parse medium/long pattern
propName = pattern.substring(pos, equals);
valueName = pattern.substring(equals+1, close);
}
else {
// Handle case where no '=' is seen, and \N{}
propName = pattern.substring(pos, close);
valueName = "";
// Handle \N{name}
if (isName) {
// This is a little inefficient since it means we have to
// parse "na" back to UProperty.NAME even though we already
// know it's UProperty.NAME. If we refactor the API to
// support args of (int, String) then we can remove
// "na" and make this a little more efficient.
valueName = propName;
propName = "na";
}
}
applyPropertyAlias(propName, valueName, symbols);
if (invert) {
complement();
}
// Move to the limit position after the close delimiter
ppos.setIndex(close + (posix ? 2 : 1));
return this;
} | UnicodeSet function(String pattern, ParsePosition ppos, SymbolTable symbols) { int pos = ppos.getIndex(); if ((pos+5) > pattern.length()) { return null; } boolean posix = false; boolean isName = false; boolean invert = false; if (pattern.regionMatches(pos, "[:", 0, 2)) { posix = true; pos = Utility.skipWhitespace(pattern, pos+2); if (pos < pattern.length() && pattern.charAt(pos) == '^') { ++pos; invert = true; } } else if (pattern.regionMatches(true, pos, "\\p", 0, 2) pattern.regionMatches(pos, "\\N", 0, 2)) { char c = pattern.charAt(pos+1); invert = (c == 'P'); isName = (c == 'N'); pos = Utility.skipWhitespace(pattern, pos+2); if (pos == pattern.length() pattern.charAt(pos++) != '{') { return null; } } else { return null; } int close = pattern.indexOf(posix ? ":]" : "}", pos); if (close < 0) { return null; } int equals = pattern.indexOf('=', pos); String propName, valueName; if (equals >= 0 && equals < close && !isName) { propName = pattern.substring(pos, equals); valueName = pattern.substring(equals+1, close); } else { propName = pattern.substring(pos, close); valueName = STRna"; } } applyPropertyAlias(propName, valueName, symbols); if (invert) { complement(); } ppos.setIndex(close + (posix ? 2 : 1)); return this; } | /**
* Parse the given property pattern at the given parse position.
* @param symbols TODO
*/ | Parse the given property pattern at the given parse position | applyPropertyPattern | {
"repo_name": "TheTypoMaster/Scaper",
"path": "openjdk/jdk/src/share/classes/sun/text/normalizer/UnicodeSet.java",
"license": "gpl-2.0",
"size": 70393
} | [
"java.text.ParsePosition"
] | import java.text.ParsePosition; | import java.text.*; | [
"java.text"
] | java.text; | 500,224 |
public void accept(RevisionVisitor visitor)
{
visitor.visit(this);
Iterator<Delta> iter = deltas_.iterator();
while (iter.hasNext())
{
(iter.next()).accept(visitor);
}
} | void function(RevisionVisitor visitor) { visitor.visit(this); Iterator<Delta> iter = deltas_.iterator(); while (iter.hasNext()) { (iter.next()).accept(visitor); } } | /**
* Accepts a visitor.
*
* @param visitor
* the {@link RevisionVisitor} visiting this instance
*/ | Accepts a visitor | accept | {
"repo_name": "Servoy/wicket",
"path": "wicket/src/main/java/org/apache/wicket/util/diff/Revision.java",
"license": "apache-2.0",
"size": 7418
} | [
"java.util.Iterator"
] | import java.util.Iterator; | import java.util.*; | [
"java.util"
] | java.util; | 850,409 |
@Deprecated
public TermVectorsRequest doc(BytesReference doc, boolean generateRandomId) {
return this.doc(doc, generateRandomId, XContentFactory.xContentType(doc));
} | TermVectorsRequest function(BytesReference doc, boolean generateRandomId) { return this.doc(doc, generateRandomId, XContentFactory.xContentType(doc)); } | /**
* Sets an artificial document from which term vectors are requested for.
* @deprecated use {@link #doc(BytesReference, boolean, XContentType)} to avoid content auto detection
*/ | Sets an artificial document from which term vectors are requested for | doc | {
"repo_name": "markwalkom/elasticsearch",
"path": "core/src/main/java/org/elasticsearch/action/termvectors/TermVectorsRequest.java",
"license": "apache-2.0",
"size": 25308
} | [
"org.elasticsearch.common.bytes.BytesReference",
"org.elasticsearch.common.xcontent.XContentFactory"
] | import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.XContentFactory; | import org.elasticsearch.common.bytes.*; import org.elasticsearch.common.xcontent.*; | [
"org.elasticsearch.common"
] | org.elasticsearch.common; | 1,095,062 |
EReference getAllPatternEntry_Exclusuion();
| EReference getAllPatternEntry_Exclusuion(); | /**
* Returns the meta object for the containment reference list '{@link hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.AllPatternEntry#getExclusuion <em>Exclusuion</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Exclusuion</em>'.
* @see hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.AllPatternEntry#getExclusuion()
* @see #getAllPatternEntry()
* @generated
*/ | Returns the meta object for the containment reference list '<code>hu.bme.mit.inf.dslreasoner.application.applicationConfiguration.AllPatternEntry#getExclusuion Exclusuion</code>'. | getAllPatternEntry_Exclusuion | {
"repo_name": "viatra/VIATRA-Generator",
"path": "Application/hu.bme.mit.inf.dslreasoner.application/src-gen/hu/bme/mit/inf/dslreasoner/application/applicationConfiguration/ApplicationConfigurationPackage.java",
"license": "epl-1.0",
"size": 236178
} | [
"org.eclipse.emf.ecore.EReference"
] | import org.eclipse.emf.ecore.EReference; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 1,261,693 |
private List<DeploymentUnit> getRedundantUnits(final DeploymentUnit loadedUnit) {
int loadedVersion = loadedUnit.getVersion();
Set<String> tasksNames = loadedUnit.getTaskMethods().keySet();
List<DeploymentUnit> olderUnits = deploymentUnitManager.getAllDeploymentUnits().stream()
.filter(d -> d.getName().equals(loadedUnit.getName()) && d.getVersion() < loadedVersion).collect(Collectors.toList());
return olderUnits.stream().filter(o -> tasksNames.containsAll(o.getTaskMethods().keySet())).collect(Collectors.toList());
}
/**
* Wrapper on {@link #buildResponse(Response.Status, String, Throwable)} which builds a response object from the status code, msg.
*
* @param status Http response code.
* @param msg Accompanying message as a response.
* @return {@link Response} | List<DeploymentUnit> function(final DeploymentUnit loadedUnit) { int loadedVersion = loadedUnit.getVersion(); Set<String> tasksNames = loadedUnit.getTaskMethods().keySet(); List<DeploymentUnit> olderUnits = deploymentUnitManager.getAllDeploymentUnits().stream() .filter(d -> d.getName().equals(loadedUnit.getName()) && d.getVersion() < loadedVersion).collect(Collectors.toList()); return olderUnits.stream().filter(o -> tasksNames.containsAll(o.getTaskMethods().keySet())).collect(Collectors.toList()); } /** * Wrapper on {@link #buildResponse(Response.Status, String, Throwable)} which builds a response object from the status code, msg. * * @param status Http response code. * @param msg Accompanying message as a response. * @return {@link Response} | /**
* Returns a list of previously loaded deploymentUnits which can be safely removed.
*
* @param loadedUnit
* @return
*/ | Returns a list of previously loaded deploymentUnits which can be safely removed | getRedundantUnits | {
"repo_name": "flipkart-incubator/flux",
"path": "runtime/src/main/java/com/flipkart/flux/resource/DeploymentUnitResource.java",
"license": "apache-2.0",
"size": 8292
} | [
"com.flipkart.flux.deploymentunit.DeploymentUnit",
"java.util.List",
"java.util.Set",
"java.util.stream.Collectors",
"javax.ws.rs.core.Response"
] | import com.flipkart.flux.deploymentunit.DeploymentUnit; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.ws.rs.core.Response; | import com.flipkart.flux.deploymentunit.*; import java.util.*; import java.util.stream.*; import javax.ws.rs.core.*; | [
"com.flipkart.flux",
"java.util",
"javax.ws"
] | com.flipkart.flux; java.util; javax.ws; | 2,345,612 |
Future<?> schedule(Runnable task, CronExpression expression); | Future<?> schedule(Runnable task, CronExpression expression); | /**
* Schedules the specified task to execute according to the specified cron expression.
*
* @param task the Runnable task to schedule
* @param expression a cron expression
* @return a future
*/ | Schedules the specified task to execute according to the specified cron expression | schedule | {
"repo_name": "jprante/elasticsearch-jdbc",
"path": "src/main/java/org/xbib/elasticsearch/common/cron/CronExecutorService.java",
"license": "apache-2.0",
"size": 1182
} | [
"java.util.concurrent.Future"
] | import java.util.concurrent.Future; | import java.util.concurrent.*; | [
"java.util"
] | java.util; | 880,464 |
boolean registerMutation(ItemStack result, ItemStack parent1, ItemStack parent2, double chance); | boolean registerMutation(ItemStack result, ItemStack parent1, ItemStack parent2, double chance); | /**
* Registers a new mutation
* @param result
* @param parent1
* @param parent2
* @return True if successful
*/ | Registers a new mutation | registerMutation | {
"repo_name": "HenryLoenwind/AgriCraft",
"path": "src/main/java/com/InfinityRaider/AgriCraft/api/v1/APIv1.java",
"license": "mit",
"size": 17453
} | [
"net.minecraft.item.ItemStack"
] | import net.minecraft.item.ItemStack; | import net.minecraft.item.*; | [
"net.minecraft.item"
] | net.minecraft.item; | 2,110,143 |
public static <T> T unmarshall(Reader input, Class<T> clazz, Adapter<?, ?>... adapters) throws IOException {
HierarchicProperties<T> p = new HierarchicProperties<T>(clazz, adapters);
p.load(input);
return p.properties;
} | static <T> T function(Reader input, Class<T> clazz, Adapter<?, ?>... adapters) throws IOException { HierarchicProperties<T> p = new HierarchicProperties<T>(clazz, adapters); p.load(input); return p.properties; } | /**
* Unmarshall a property file to a tree of objects.
*
* @param input The property file.
* @param clazz The target result (tree root)
* @param adapters Optionally, allow to map string values to items or list of items for specific classes or keys.
* @param <T> The type of the target object.
* @return The properties as a tree of objects.
* @throws IOException When an I/O error occurs.
*/ | Unmarshall a property file to a tree of objects | unmarshall | {
"repo_name": "alternet/alternet.ml",
"path": "tools/src/main/java/ml/alternet/properties/Binder.java",
"license": "mit",
"size": 31962
} | [
"java.io.IOException",
"java.io.Reader"
] | import java.io.IOException; import java.io.Reader; | import java.io.*; | [
"java.io"
] | java.io; | 1,034,622 |
public KeyStroke getAcceleratorKey() {
return resources.getOptionalKeyStroke( "action.back.accelerator" ); //$NON-NLS-1$
} | KeyStroke function() { return resources.getOptionalKeyStroke( STR ); } | /**
* Returns the accelerator key for the export action.
*
* @return The accelerator key.
*/ | Returns the accelerator key for the export action | getAcceleratorKey | {
"repo_name": "mbatchelor/pentaho-reporting",
"path": "engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/modules/gui/base/actions/GoToPreviousPageActionPlugin.java",
"license": "lgpl-2.1",
"size": 4908
} | [
"javax.swing.KeyStroke"
] | import javax.swing.KeyStroke; | import javax.swing.*; | [
"javax.swing"
] | javax.swing; | 2,847,281 |
private void process() {
if (this.hash == null || this.lastMod == 0L) {
InputStream versionStream = getPropertyStream();
if (versionStream != null) {
try {
Properties props = new Properties();
props.load(versionStream);
String hashText = props.getProperty(UUID_PROPERTY);
if (hashText == null || hashText.isEmpty()) {
throw new RuntimeException("Can't parse precomputed hash from " + this.versionUri);
}
// compiled hash gives us actual string value
this.hash = new CompiledHash(hashText);
this.lastMod = Long.parseLong(props.getProperty(LASTMOD_PROPERTY));
return;
} catch (IOException e) {
throw new RuntimeException("Can't parse precomputed info from " + this.versionUri, e);
}
}
throw new RuntimeException("Can't find " + this.versionUri + " to get precomputed uuid");
}
}
private static class CompiledHash extends Hash {
private String hashText;
private CompiledHash(String hashText) throws IOException {
this.hashText = hashText;
} | void function() { if (this.hash == null this.lastMod == 0L) { InputStream versionStream = getPropertyStream(); if (versionStream != null) { try { Properties props = new Properties(); props.load(versionStream); String hashText = props.getProperty(UUID_PROPERTY); if (hashText == null hashText.isEmpty()) { throw new RuntimeException(STR + this.versionUri); } this.hash = new CompiledHash(hashText); this.lastMod = Long.parseLong(props.getProperty(LASTMOD_PROPERTY)); return; } catch (IOException e) { throw new RuntimeException(STR + this.versionUri, e); } } throw new RuntimeException(STR + this.versionUri + STR); } } private static class CompiledHash extends Hash { private String hashText; private CompiledHash(String hashText) throws IOException { this.hashText = hashText; } | /**
* Checks whether hash or lastMod are set and reads file to get uid and lastmod
*/ | Checks whether hash or lastMod are set and reads file to get uid and lastmod | process | {
"repo_name": "lhong375/aura",
"path": "aura-util/src/main/java/org/auraframework/util/resource/CompiledGroup.java",
"license": "apache-2.0",
"size": 5469
} | [
"java.io.IOException",
"java.io.InputStream",
"java.util.Properties",
"org.auraframework.util.text.Hash"
] | import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.auraframework.util.text.Hash; | import java.io.*; import java.util.*; import org.auraframework.util.text.*; | [
"java.io",
"java.util",
"org.auraframework.util"
] | java.io; java.util; org.auraframework.util; | 871,571 |
return javaType;
}
/**
* Creates and instance of {@link TypeReference} which maintains the generic {@code T} of the passed {@link Class}.
* <p>
* This method will cache the instance of {@link TypeReference} using the passed {@link Class} as the key. This is
* meant to be used with non-generic types such as primitive object types and POJOs, not {@code Map<String, Object>} | return javaType; } /** * Creates and instance of {@link TypeReference} which maintains the generic {@code T} of the passed {@link Class}. * <p> * This method will cache the instance of {@link TypeReference} using the passed {@link Class} as the key. This is * meant to be used with non-generic types such as primitive object types and POJOs, not {@code Map<String, Object>} | /**
* Returns the {@link Type} representing {@code T}.
*
* @return The {@link Type} representing {@code T}.
*/ | Returns the <code>Type</code> representing T | getJavaType | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/core/azure-core/src/main/java/com/azure/core/util/serializer/TypeReference.java",
"license": "mit",
"size": 4354
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 1,325,067 |
public static PlanFragment getPlanFragment(CatalogType catalog_obj, int id) {
Database catalog_db = CatalogUtil.getDatabase(catalog_obj);
for (Procedure catalog_proc : catalog_db.getProcedures()) {
for (Statement catalog_stmt : catalog_proc.getStatements()) {
for (PlanFragment catalog_frag : catalog_stmt.getFragments())
if (catalog_frag.getId() == id)
return (catalog_frag);
for (PlanFragment catalog_frag : catalog_stmt.getMs_fragments())
if (catalog_frag.getId() == id)
return (catalog_frag);
} // FOR (stmt)
} // FOR (proc)
return (null);
}
// ------------------------------------------------------------
// UTILITY METHODS
// ------------------------------------------------------------ | static PlanFragment function(CatalogType catalog_obj, int id) { Database catalog_db = CatalogUtil.getDatabase(catalog_obj); for (Procedure catalog_proc : catalog_db.getProcedures()) { for (Statement catalog_stmt : catalog_proc.getStatements()) { for (PlanFragment catalog_frag : catalog_stmt.getFragments()) if (catalog_frag.getId() == id) return (catalog_frag); for (PlanFragment catalog_frag : catalog_stmt.getMs_fragments()) if (catalog_frag.getId() == id) return (catalog_frag); } } return (null); } | /**
* Return a PlanFragment for a given id. This is slow and should only be
* used for debugging purposes
*
* @param catalog_obj
* @param id
* @return
*/ | Return a PlanFragment for a given id. This is slow and should only be used for debugging purposes | getPlanFragment | {
"repo_name": "gxyang/hstore",
"path": "src/frontend/edu/brown/catalog/CatalogUtil.java",
"license": "gpl-3.0",
"size": 121408
} | [
"org.voltdb.catalog.CatalogType",
"org.voltdb.catalog.Database",
"org.voltdb.catalog.PlanFragment",
"org.voltdb.catalog.Procedure",
"org.voltdb.catalog.Statement"
] | import org.voltdb.catalog.CatalogType; import org.voltdb.catalog.Database; import org.voltdb.catalog.PlanFragment; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Statement; | import org.voltdb.catalog.*; | [
"org.voltdb.catalog"
] | org.voltdb.catalog; | 880,138 |
private void saveToContext(Context context) {
ParameterParser urlParamParser = context.getUrlParamParser();
ParameterParser formParamParser = context.getPostParamParser();
if (urlParamParser instanceof StandardParameterParser) {
StandardParameterParser urlStdParamParser = (StandardParameterParser) urlParamParser;
urlStdParamParser.setKeyValuePairSeparators(this.getUrlKvPairSeparators().getText());
urlStdParamParser.setKeyValueSeparators(this.getUrlKeyValueSeparators().getText());
urlStdParamParser.setStructuralParameters(this.getStructuralParamsModel().getLines());
context.setUrlParamParser(urlStdParamParser);
}
if (formParamParser instanceof StandardParameterParser) {
StandardParameterParser formStdParamParser = (StandardParameterParser) formParamParser;
formStdParamParser.setKeyValuePairSeparators(this.getPostKvPairSeparators().getText());
formStdParamParser.setKeyValueSeparators(this.getPostKeyValueSeparators().getText());
context.setPostParamParser(formStdParamParser);
}
}
| void function(Context context) { ParameterParser urlParamParser = context.getUrlParamParser(); ParameterParser formParamParser = context.getPostParamParser(); if (urlParamParser instanceof StandardParameterParser) { StandardParameterParser urlStdParamParser = (StandardParameterParser) urlParamParser; urlStdParamParser.setKeyValuePairSeparators(this.getUrlKvPairSeparators().getText()); urlStdParamParser.setKeyValueSeparators(this.getUrlKeyValueSeparators().getText()); urlStdParamParser.setStructuralParameters(this.getStructuralParamsModel().getLines()); context.setUrlParamParser(urlStdParamParser); } if (formParamParser instanceof StandardParameterParser) { StandardParameterParser formStdParamParser = (StandardParameterParser) formParamParser; formStdParamParser.setKeyValuePairSeparators(this.getPostKvPairSeparators().getText()); formStdParamParser.setKeyValueSeparators(this.getPostKeyValueSeparators().getText()); context.setPostParamParser(formStdParamParser); } } | /**
* Save the data from this panel to the provided context.
*
* @param context the context
*/ | Save the data from this panel to the provided context | saveToContext | {
"repo_name": "0xkasun/zaproxy",
"path": "src/org/zaproxy/zap/view/ContextStructurePanel.java",
"license": "apache-2.0",
"size": 11089
} | [
"org.zaproxy.zap.model.Context",
"org.zaproxy.zap.model.ParameterParser",
"org.zaproxy.zap.model.StandardParameterParser"
] | import org.zaproxy.zap.model.Context; import org.zaproxy.zap.model.ParameterParser; import org.zaproxy.zap.model.StandardParameterParser; | import org.zaproxy.zap.model.*; | [
"org.zaproxy.zap"
] | org.zaproxy.zap; | 486,751 |
@Path("{clusterName}/kerberos_descriptors")
public ClusterKerberosDescriptorService getCompositeKerberosDescriptor(
@Context javax.ws.rs.core.Request request,
@PathParam("clusterName") String clusterName) {
return new ClusterKerberosDescriptorService(clusterName);
} | @Path(STR) ClusterKerberosDescriptorService function( @Context javax.ws.rs.core.Request request, @PathParam(STR) String clusterName) { return new ClusterKerberosDescriptorService(clusterName); } | /**
* Handles: GET /clusters/{clusterID}/kerberos_descriptor
* Gets the composite Kerberos descriptor associated with the cluster.
*
* @param request the request.
* @param clusterName the cluster name.
* @return composite Kerberos descriptor resource representation
*/ | Handles: GET /clusters/{clusterID}/kerberos_descriptor Gets the composite Kerberos descriptor associated with the cluster | getCompositeKerberosDescriptor | {
"repo_name": "sekikn/ambari",
"path": "ambari-server/src/main/java/org/apache/ambari/server/api/services/ClusterService.java",
"license": "apache-2.0",
"size": 33903
} | [
"javax.ws.rs.Path",
"javax.ws.rs.PathParam",
"javax.ws.rs.core.Context"
] | import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; | import javax.ws.rs.*; import javax.ws.rs.core.*; | [
"javax.ws"
] | javax.ws; | 1,710,019 |
public IRenderInto<T> getBeforeRenderer() {
return m_beforeRenderer;
} | IRenderInto<T> function() { return m_beforeRenderer; } | /**
* Enables inserting of custom content that would be enveloped into additionaly added row that is inserted before rows that are part of builtin content.
*/ | Enables inserting of custom content that would be enveloped into additionaly added row that is inserted before rows that are part of builtin content | getBeforeRenderer | {
"repo_name": "fjalvingh/domui",
"path": "to.etc.domui/src/main/java/to/etc/domui/component/input/SimpleLookupInputRenderer.java",
"license": "lgpl-2.1",
"size": 6845
} | [
"to.etc.domui.util.IRenderInto"
] | import to.etc.domui.util.IRenderInto; | import to.etc.domui.util.*; | [
"to.etc.domui"
] | to.etc.domui; | 2,376,243 |
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
updateConnectButtonState();
if (requestCode == OUR_REQUEST_CODE && responseCode == RESULT_OK) {
// If we have a successful result, we will want to be able to resolve any further
// errors, so turn on resolution with our flag.
mAutoResolveOnFail = true;
// If we have a successful result, let's call connect() again. If there are any more
// errors to resolve we'll get our onConnectionFailed, but if not,
// we'll get onConnected.
initiatePlusClientConnect();
} else if (requestCode == OUR_REQUEST_CODE && responseCode != RESULT_OK) {
// If we've got an error we can't resolve, we're no longer in the midst of signing
// in, so we can stop the progress spinner.
setProgressBarVisible(false);
}
} | void function(int requestCode, int responseCode, Intent intent) { updateConnectButtonState(); if (requestCode == OUR_REQUEST_CODE && responseCode == RESULT_OK) { mAutoResolveOnFail = true; initiatePlusClientConnect(); } else if (requestCode == OUR_REQUEST_CODE && responseCode != RESULT_OK) { setProgressBarVisible(false); } } | /**
* An earlier connection failed, and we're now receiving the result of the resolution attempt
* by PlusClient.
*
* @see #onConnectionFailed(ConnectionResult)
*/ | An earlier connection failed, and we're now receiving the result of the resolution attempt by PlusClient | onActivityResult | {
"repo_name": "LordNash/Weather-APP",
"path": "app/src/main/java/teamtreehouse/com/stormy/PlusBaseActivity.java",
"license": "unlicense",
"size": 9971
} | [
"android.content.Intent"
] | import android.content.Intent; | import android.content.*; | [
"android.content"
] | android.content; | 1,980,929 |
public void setAttributes(HashMap<String, String> attributes) {
this.setAttributeAware(true);
this._attributes = attributes;
} | void function(HashMap<String, String> attributes) { this.setAttributeAware(true); this._attributes = attributes; } | /**
* Sets the map that allows a parser to search a nodes attribute for a
* successful match.
*
* @param attributes
* The map to set
*/ | Sets the map that allows a parser to search a nodes attribute for a successful match | setAttributes | {
"repo_name": "lmu-bioinformatics/xmlpipedb",
"path": "xmlpipedbutils/src/edu/lmu/xmlpipedb/util/engines/Criterion.java",
"license": "lgpl-3.0",
"size": 6469
} | [
"java.util.HashMap"
] | import java.util.HashMap; | import java.util.*; | [
"java.util"
] | java.util; | 403,295 |
public DateRangeAggregationBuilder addUnboundedTo(String key, String to) {
addRange(new Range(key, null, to));
return this;
} | DateRangeAggregationBuilder function(String key, String to) { addRange(new Range(key, null, to)); return this; } | /**
* Add a new range with no lower bound.
*
* @param key
* the key to use for this range in the response
* @param to
* the upper bound on the dates, exclusive
*/ | Add a new range with no lower bound | addUnboundedTo | {
"repo_name": "dpursehouse/elasticsearch",
"path": "core/src/main/java/org/elasticsearch/search/aggregations/bucket/range/date/DateRangeAggregationBuilder.java",
"license": "apache-2.0",
"size": 9035
} | [
"org.elasticsearch.search.aggregations.bucket.range.RangeAggregator"
] | import org.elasticsearch.search.aggregations.bucket.range.RangeAggregator; | import org.elasticsearch.search.aggregations.bucket.range.*; | [
"org.elasticsearch.search"
] | org.elasticsearch.search; | 1,528,123 |
public boolean propagatesViaParameters(IRequestHandler handler); | boolean function(IRequestHandler handler); | /**
* Indicates if the conversation should be propagated via url-parameters for the given request
* handler. This can either be a get parameter in a rendered url, or via page parameters.
*
* @param handler
* The current request handler
* @return true if the conversation should be propagated for the given request handler.
*/ | Indicates if the conversation should be propagated via url-parameters for the given request handler. This can either be a get parameter in a rendered url, or via page parameters | propagatesViaParameters | {
"repo_name": "topicusonderwijs/wicket",
"path": "wicket-cdi/src/main/java/org/apache/wicket/cdi/IConversationPropagation.java",
"license": "apache-2.0",
"size": 2043
} | [
"org.apache.wicket.request.IRequestHandler"
] | import org.apache.wicket.request.IRequestHandler; | import org.apache.wicket.request.*; | [
"org.apache.wicket"
] | org.apache.wicket; | 826,219 |
public HandlerManager getEventBus() {
return eventBus;
} | HandlerManager function() { return eventBus; } | /**
* To get Event Bus.
*
* @return the eventBus
*/ | To get Event Bus | getEventBus | {
"repo_name": "kuzavas/ephesoft",
"path": "dcma-gwt/dcma-gwt-admin/src/main/java/com/ephesoft/dcma/gwt/admin/bm/client/presenter/module/ConfigureModulePresenter.java",
"license": "agpl-3.0",
"size": 10846
} | [
"com.google.gwt.event.shared.HandlerManager"
] | import com.google.gwt.event.shared.HandlerManager; | import com.google.gwt.event.shared.*; | [
"com.google.gwt"
] | com.google.gwt; | 2,487,471 |
void startNextScroll(TimeValue lastBatchStartTime, TimeValue now, int lastBatchSize) {
if (task.isCancelled()) {
finishHim(null);
return;
}
TimeValue extraKeepAlive = task.throttleWaitTime(lastBatchStartTime, now, lastBatchSize);
scrollSource.startNextScroll(extraKeepAlive, response -> {
onScrollResponse(lastBatchStartTime, lastBatchSize, response);
});
} | void startNextScroll(TimeValue lastBatchStartTime, TimeValue now, int lastBatchSize) { if (task.isCancelled()) { finishHim(null); return; } TimeValue extraKeepAlive = task.throttleWaitTime(lastBatchStartTime, now, lastBatchSize); scrollSource.startNextScroll(extraKeepAlive, response -> { onScrollResponse(lastBatchStartTime, lastBatchSize, response); }); } | /**
* Start the next scroll request.
*
* @param lastBatchSize the number of requests sent in the last batch. This is used to calculate the throttling values which are applied
* when the scroll returns
*/ | Start the next scroll request | startNextScroll | {
"repo_name": "strapdata/elassandra5-rc",
"path": "modules/reindex/src/main/java/org/elasticsearch/index/reindex/AbstractAsyncBulkByScrollAction.java",
"license": "apache-2.0",
"size": 35699
} | [
"org.elasticsearch.common.unit.TimeValue"
] | import org.elasticsearch.common.unit.TimeValue; | import org.elasticsearch.common.unit.*; | [
"org.elasticsearch.common"
] | org.elasticsearch.common; | 1,037,921 |
public MetricSpecification withDimensions(List<Dimension> dimensions) {
this.dimensions = dimensions;
return this;
} | MetricSpecification function(List<Dimension> dimensions) { this.dimensions = dimensions; return this; } | /**
* Set dimensions of blobs, including blob type and access tier.
*
* @param dimensions the dimensions value to set
* @return the MetricSpecification object itself.
*/ | Set dimensions of blobs, including blob type and access tier | withDimensions | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/netapp/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/netapp/v2020_06_01/MetricSpecification.java",
"license": "mit",
"size": 6496
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,674,626 |
protected String toFile(String uri)
{
String file = uri.startsWith(URI_PREFIX) ?
uri.substring(URI_PREFIX.length()) : uri;
try{
return URLDecoder.decode(file, "utf-8");
}catch(Exception e){
throw new RuntimeException(e);
}
} | String function(String uri) { String file = uri.startsWith(URI_PREFIX) ? uri.substring(URI_PREFIX.length()) : uri; try{ return URLDecoder.decode(file, "utf-8"); }catch(Exception e){ throw new RuntimeException(e); } } | /**
* Converts the supplied uri to a file name if necessary.
*
* @param uri The uri.
* @return The file name.
*/ | Converts the supplied uri to a file name if necessary | toFile | {
"repo_name": "euclio/eclim",
"path": "org.eclim.wst/java/org/eclim/plugin/wst/command/validate/WstValidateCommand.java",
"license": "gpl-3.0",
"size": 1998
} | [
"java.net.URLDecoder"
] | import java.net.URLDecoder; | import java.net.*; | [
"java.net"
] | java.net; | 144,638 |
public List getMessages()
{
List messages = new ArrayList();
//if(displayUnreadOnly)
// messages = selectedTopic.getUnreadMessages();
//else
if(selectedTopic == null)
{
LOG.debug("selectedTopic is null in getMessages");
return messages;
}
messages = selectedTopic.getMessages();
if (messages != null && !messages.isEmpty())
messages = filterModeratedMessages(messages, selectedTopic.getTopic(), selectedForum.getForum());
return messages;
} | List function() { List messages = new ArrayList(); if(selectedTopic == null) { LOG.debug(STR); return messages; } messages = selectedTopic.getMessages(); if (messages != null && !messages.isEmpty()) messages = filterModeratedMessages(messages, selectedTopic.getTopic(), selectedForum.getForum()); return messages; } | /**
* Returns list of DecoratedMessageBean objects, ie, the messages
*/ | Returns list of DecoratedMessageBean objects, ie, the messages | getMessages | {
"repo_name": "introp-software/sakai",
"path": "msgcntr/messageforums-app/src/java/org/sakaiproject/tool/messageforums/DiscussionForumTool.java",
"license": "apache-2.0",
"size": 350698
} | [
"java.util.ArrayList",
"java.util.List"
] | import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,070,536 |
public void initialize() {
cpuThreads = new BooleanLabel(constants.yes(), constants.no());
memoryOverCommit = new PercentLabel<Integer>();
resiliencePolicy = new ResiliencePolicyLabel();
clusterType = new ClusterTypeLabel();
driver.initialize(this); | void function() { cpuThreads = new BooleanLabel(constants.yes(), constants.no()); memoryOverCommit = new PercentLabel<Integer>(); resiliencePolicy = new ResiliencePolicyLabel(); clusterType = new ClusterTypeLabel(); driver.initialize(this); | /**
* Initialize the form. Call this after ID has been set on the form,
* so that form fields can use the ID as their prefix.
*/ | Initialize the form. Call this after ID has been set on the form, so that form fields can use the ID as their prefix | initialize | {
"repo_name": "jtux270/translate",
"path": "ovirt/3.6_source/frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/view/tab/cluster/ClusterGeneralModelForm.java",
"license": "gpl-3.0",
"size": 6370
} | [
"org.ovirt.engine.ui.common.widget.label.BooleanLabel",
"org.ovirt.engine.ui.common.widget.label.ClusterTypeLabel",
"org.ovirt.engine.ui.common.widget.label.ResiliencePolicyLabel",
"org.ovirt.engine.ui.webadmin.widget.label.PercentLabel"
] | import org.ovirt.engine.ui.common.widget.label.BooleanLabel; import org.ovirt.engine.ui.common.widget.label.ClusterTypeLabel; import org.ovirt.engine.ui.common.widget.label.ResiliencePolicyLabel; import org.ovirt.engine.ui.webadmin.widget.label.PercentLabel; | import org.ovirt.engine.ui.common.widget.label.*; import org.ovirt.engine.ui.webadmin.widget.label.*; | [
"org.ovirt.engine"
] | org.ovirt.engine; | 2,254,257 |
public int readInt() throws IOException {
return ((readByte() & 0xFF) << 24) | ((readByte() & 0xFF) << 16)
| ((readByte() & 0xFF) << 8) | (readByte() & 0xFF);
}
/**
* Reads an int stored in variable-length format. Reads between one and
* five bytes. Smaller values take fewer bytes. Negative numbers
* will always use all 5 bytes and are therefore better serialized
* using {@link #readInt} | int function() throws IOException { return ((readByte() & 0xFF) << 24) ((readByte() & 0xFF) << 16) ((readByte() & 0xFF) << 8) (readByte() & 0xFF); } /** * Reads an int stored in variable-length format. Reads between one and * five bytes. Smaller values take fewer bytes. Negative numbers * will always use all 5 bytes and are therefore better serialized * using {@link #readInt} | /**
* Reads four bytes and returns an int.
*/ | Reads four bytes and returns an int | readInt | {
"repo_name": "davidvgalbraith/elasticsearch",
"path": "core/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java",
"license": "apache-2.0",
"size": 24673
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 656,835 |
@Test void testGroupBySortLimit() {
final String sql = "select \"brand_name\", \"gender\", sum(\"unit_sales\") as s\n"
+ "from \"foodmart\"\n"
+ "group by \"brand_name\", \"gender\"\n"
+ "order by s desc limit 3";
final String druidQuery = "{'queryType':'groupBy','dataSource':'foodmart',"
+ "'granularity':'all','dimensions':[{'type':'default',"
+ "'dimension':'brand_name','outputName':'brand_name','outputType':'STRING'},"
+ "{'type':'default','dimension':'gender','outputName':'gender','outputType':'STRING'}],"
+ "'limitSpec':{'type':'default','limit':3,'columns':[{'dimension':'S',"
+ "'direction':'descending','dimensionOrder':'numeric'}]},"
+ "'aggregations':[{'type':'longSum','name':'S','fieldName':'unit_sales'}],"
+ "'intervals':['1900-01-09T00:00:00.000Z/2992-01-10T00:00:00.000Z']}";
final String explain = "PLAN=EnumerableInterpreter\n"
+ " DruidQuery(table=[[foodmart, foodmart]], intervals=[[1900-01-09T00:00:00.000Z/"
+ "2992-01-10T00:00:00.000Z]], projects=[[$2, $39, $89]], groups=[{0, 1}], "
+ "aggs=[[SUM($2)]], sort0=[2], dir0=[DESC], fetch=[3])";
sql(sql)
.runs()
.returnsOrdered("brand_name=Hermanos; gender=M; S=4286",
"brand_name=Hermanos; gender=F; S=4183",
"brand_name=Tell Tale; gender=F; S=4033")
.explainContains(explain)
.queryContains(new DruidChecker(druidQuery));
} | @Test void testGroupBySortLimit() { final String sql = STRbrand_name\STRgender\STRunit_sales\STR + STRfoodmart\"\n" + STRbrand_name\STRgender\"\n" + STR; final String druidQuery = STR + STR + STR + STR + STR + STR + STR + STR; final String explain = STR + STR + STR + STR; sql(sql) .runs() .returnsOrdered(STR, STR, STR) .explainContains(explain) .queryContains(new DruidChecker(druidQuery)); } | /** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1578">[CALCITE-1578]
* Druid adapter: wrong semantics of topN query limit with granularity</a>. */ | Test case for [CALCITE-1578] | testGroupBySortLimit | {
"repo_name": "datametica/calcite",
"path": "druid/src/test/java/org/apache/calcite/test/DruidAdapter2IT.java",
"license": "apache-2.0",
"size": 201561
} | [
"org.junit.jupiter.api.Test"
] | import org.junit.jupiter.api.Test; | import org.junit.jupiter.api.*; | [
"org.junit.jupiter"
] | org.junit.jupiter; | 102,661 |
protected DcmElement put(DcmElement newElem) {
if (log.isDebugEnabled()) {
log.debug("put " + newElem);
}
if ((newElem.tag() & 0xffff) == 0) {
return newElem;
}
if (Tags.isPrivate(newElem.tag())) {
try {
((DcmElementImpl) newElem).tag = adjustPrivateTag(
newElem.tag(), true);
} catch (DcmValueException e) {
log.warn("Could not access creator ID - ignore " + newElem, e);
return newElem;
}
}
return doPut(newElem);
} | DcmElement function(DcmElement newElem) { if (log.isDebugEnabled()) { log.debug(STR + newElem); } if ((newElem.tag() & 0xffff) == 0) { return newElem; } if (Tags.isPrivate(newElem.tag())) { try { ((DcmElementImpl) newElem).tag = adjustPrivateTag( newElem.tag(), true); } catch (DcmValueException e) { log.warn(STR + newElem, e); return newElem; } } return doPut(newElem); } | /**
* Description of the Method
*
* @param newElem
* Description of the Parameter
* @return Description of the Return Value
*/ | Description of the Method | put | {
"repo_name": "medicayun/medicayundicom",
"path": "dcm4che14/tags/DCM4CHE_1_4_31/src/java/org/dcm4cheri/data/DcmObjectImpl.java",
"license": "apache-2.0",
"size": 86527
} | [
"org.dcm4che.data.DcmElement",
"org.dcm4che.data.DcmValueException",
"org.dcm4che.dict.Tags"
] | import org.dcm4che.data.DcmElement; import org.dcm4che.data.DcmValueException; import org.dcm4che.dict.Tags; | import org.dcm4che.data.*; import org.dcm4che.dict.*; | [
"org.dcm4che.data",
"org.dcm4che.dict"
] | org.dcm4che.data; org.dcm4che.dict; | 1,516,368 |
public void disconnect() throws ConnectionException,
AccessException {
Log.info("Disconnected RPC connection to Perforce server "
+ this.serverHost + ":" + this.serverPort);
this.dispatcher.shutdown(this.rpcConnection);
this.rpcConnection.disconnect(this.dispatcher);
this.haveSentProtocolSpecs = false;
this.protocolSpecs = null;
super.disconnect();
}
| void function() throws ConnectionException, AccessException { Log.info(STR + this.serverHost + ":" + this.serverPort); this.dispatcher.shutdown(this.rpcConnection); this.rpcConnection.disconnect(this.dispatcher); this.haveSentProtocolSpecs = false; this.protocolSpecs = null; super.disconnect(); } | /**
* Try to cleanly disconnect from the Perforce server at the other end
* of the current connection (with the emphasis on "cleanly"). This
* should theoretically include sending a release2 message, but we
* don't always get the chance to do that.
*
* @see com.perforce.p4java.impl.mapbased.server.Server#disconnect()
*/ | Try to cleanly disconnect from the Perforce server at the other end of the current connection (with the emphasis on "cleanly"). This should theoretically include sending a release2 message, but we don't always get the chance to do that | disconnect | {
"repo_name": "paulseawa/p4ic4idea",
"path": "p4java/src/com/perforce/p4java/impl/mapbased/rpc/NtsServerImpl.java",
"license": "apache-2.0",
"size": 25674
} | [
"com.perforce.p4java.Log",
"com.perforce.p4java.exception.AccessException",
"com.perforce.p4java.exception.ConnectionException"
] | import com.perforce.p4java.Log; import com.perforce.p4java.exception.AccessException; import com.perforce.p4java.exception.ConnectionException; | import com.perforce.p4java.*; import com.perforce.p4java.exception.*; | [
"com.perforce.p4java"
] | com.perforce.p4java; | 2,693,033 |
private static void addCell(HSSFRow row, HSSFCellStyle cellStyle, int index, String value) {
HSSFCell cell = row.createCell(index);
if (cellStyle != null) {
cell.setCellStyle(cellStyle);
}
cell.setCellValue(new HSSFRichTextString(value));
} | static void function(HSSFRow row, HSSFCellStyle cellStyle, int index, String value) { HSSFCell cell = row.createCell(index); if (cellStyle != null) { cell.setCellStyle(cellStyle); } cell.setCellValue(new HSSFRichTextString(value)); } | /**
* Adds a cell to the row
* @param row the row
* @param cellStyle cell style
* @param index index of the cell
* @param value value to be added
*/ | Adds a cell to the row | addCell | {
"repo_name": "impetus-opensource/jumbune",
"path": "utilities/src/main/java/org/jumbune/utils/ExportUtil.java",
"license": "lgpl-3.0",
"size": 14081
} | [
"org.apache.poi.hssf.usermodel.HSSFCell",
"org.apache.poi.hssf.usermodel.HSSFCellStyle",
"org.apache.poi.hssf.usermodel.HSSFRichTextString",
"org.apache.poi.hssf.usermodel.HSSFRow"
] | import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; | import org.apache.poi.hssf.usermodel.*; | [
"org.apache.poi"
] | org.apache.poi; | 2,783,263 |
boolean pauseScheduler(final String sessionId) throws RestServerException, ServiceException; | boolean pauseScheduler(final String sessionId) throws RestServerException, ServiceException; | /**
* Pauses the Scheduler.
* @param sessionId the session id of the user which is logged in
* @return true if the pause was successfully, false otherwise.
*/ | Pauses the Scheduler | pauseScheduler | {
"repo_name": "ow2-proactive/scheduling-portal",
"path": "scheduler-portal/src/main/java/org/ow2/proactive_grid_cloud_portal/scheduler/client/SchedulerService.java",
"license": "agpl-3.0",
"size": 21328
} | [
"org.ow2.proactive_grid_cloud_portal.common.shared.RestServerException",
"org.ow2.proactive_grid_cloud_portal.common.shared.ServiceException"
] | import org.ow2.proactive_grid_cloud_portal.common.shared.RestServerException; import org.ow2.proactive_grid_cloud_portal.common.shared.ServiceException; | import org.ow2.proactive_grid_cloud_portal.common.shared.*; | [
"org.ow2.proactive_grid_cloud_portal"
] | org.ow2.proactive_grid_cloud_portal; | 1,089,220 |
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
} | void function(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } | /**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/ | Handles the HTTP <code>POST</code> method | doPost | {
"repo_name": "i3mainz/OpenBalloonMap",
"path": "openballoon/src/main/java/de/i3mainz/html/map.java",
"license": "mit",
"size": 3599
} | [
"java.io.IOException",
"javax.servlet.ServletException",
"javax.servlet.http.HttpServletRequest",
"javax.servlet.http.HttpServletResponse"
] | import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; | import java.io.*; import javax.servlet.*; import javax.servlet.http.*; | [
"java.io",
"javax.servlet"
] | java.io; javax.servlet; | 2,493,541 |
private CloseableHttpResponse executeRequest(Map<String, String> headers,
Map<String, String> params, RequestBuilder builder)
throws IOException, ClientProtocolException {
if (params != null) {
for (Map.Entry<String,String> param : params.entrySet()) {
builder.addParameter(new BasicNameValuePair(param.getKey(), param.getValue()));
}
}
HttpUriRequest request = builder.build();
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()){
request.setHeader(header.getKey(), header.getValue());
}
}
CloseableHttpResponse closeableresponse =
closeableHttpClient.execute(request);
return closeableresponse;
} | CloseableHttpResponse function(Map<String, String> headers, Map<String, String> params, RequestBuilder builder) throws IOException, ClientProtocolException { if (params != null) { for (Map.Entry<String,String> param : params.entrySet()) { builder.addParameter(new BasicNameValuePair(param.getKey(), param.getValue())); } } HttpUriRequest request = builder.build(); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()){ request.setHeader(header.getKey(), header.getValue()); } } CloseableHttpResponse closeableresponse = closeableHttpClient.execute(request); return closeableresponse; } | /**
* Executes a HTTP Client request using the given parameters.
*
* @param headers - request headers
* @param params - request query parameters
* @param builder - the {@link RequestBuilder} to be used for building the
* request.
* @return the {@link CloseableHttpResponse} returned by the server
* @throws IOException - in case of a problem or the connection was aborted
* @throws ClientProtocolException - in case of an http protocol error
*
*/ | Executes a HTTP Client request using the given parameters | executeRequest | {
"repo_name": "usdot-jpo-ode/jpo-ode",
"path": "jpo-ode-core/src/main/java/us/dot/its/jpo/ode/wrapper/HttpClientFactory.java",
"license": "apache-2.0",
"size": 11202
} | [
"java.io.IOException",
"java.util.Map",
"org.apache.http.client.ClientProtocolException",
"org.apache.http.client.methods.CloseableHttpResponse",
"org.apache.http.client.methods.HttpUriRequest",
"org.apache.http.client.methods.RequestBuilder",
"org.apache.http.message.BasicNameValuePair"
] | import java.io.IOException; import java.util.Map; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.message.BasicNameValuePair; | import java.io.*; import java.util.*; import org.apache.http.client.*; import org.apache.http.client.methods.*; import org.apache.http.message.*; | [
"java.io",
"java.util",
"org.apache.http"
] | java.io; java.util; org.apache.http; | 1,066,040 |
protected LogChannelInterface getGeneralLogger() {
return LogChannel.GENERAL;
} | LogChannelInterface function() { return LogChannel.GENERAL; } | /**
* For testing
*/ | For testing | getGeneralLogger | {
"repo_name": "bmorrise/pentaho-kettle",
"path": "core/src/main/java/org/pentaho/di/core/database/DatabaseMeta.java",
"license": "apache-2.0",
"size": 96894
} | [
"org.pentaho.di.core.logging.LogChannel",
"org.pentaho.di.core.logging.LogChannelInterface"
] | import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.logging.LogChannelInterface; | import org.pentaho.di.core.logging.*; | [
"org.pentaho.di"
] | org.pentaho.di; | 1,584,339 |
Map<String, Map<String, String>> getProxySettings(String... protocols); | Map<String, Map<String, String>> getProxySettings(String... protocols); | /**
* Returns the active proxy settings from settings.xml
* The fields are user, pass, host, port, nonProxyHosts, protocol.
*
* @param protocols protocols to be recognized.
*
* @return the active proxy settings
*/ | Returns the active proxy settings from settings.xml The fields are user, pass, host, port, nonProxyHosts, protocol | getProxySettings | {
"repo_name": "avano/fabric8",
"path": "fabric/fabric-maven/src/main/java/io/fabric8/maven/util/MavenConfiguration.java",
"license": "apache-2.0",
"size": 4344
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 565,461 |
@Test(groups={"ut"})
public void testFindElementOverride() {
Assert.assertEquals(testPage.textElement.toString(), "HtmlElement , by={By.id: text2}");
}
| @Test(groups={"ut"}) void function() { Assert.assertEquals(testPage.textElement.toString(), STR); } | /**
* Check we have an HtmlElement and not a WebElement
*/ | Check we have an HtmlElement and not a WebElement | testFindElementOverride | {
"repo_name": "bhecquet/seleniumRobot",
"path": "core/src/test/java/com/seleniumtests/ut/uipage/TestOverridePageObjectFactory.java",
"license": "apache-2.0",
"size": 9645
} | [
"org.testng.Assert",
"org.testng.annotations.Test"
] | import org.testng.Assert; import org.testng.annotations.Test; | import org.testng.*; import org.testng.annotations.*; | [
"org.testng",
"org.testng.annotations"
] | org.testng; org.testng.annotations; | 257,604 |
private void destroyAllMonitors() {
if (monitors == null)
return;
CAJMonitor[] monitorsArray;
synchronized (monitors)
{
monitorsArray = new CAJMonitor[monitors.size()];
monitors.values().toArray(monitorsArray);
monitors.clear();
}
for (int i = 0; i < monitorsArray.length; i++)
{
try
{
monitorsArray[i].clear();
}
catch (Throwable th)
{
logger.log(Level.SEVERE, "", th);
}
}
} | void function() { if (monitors == null) return; CAJMonitor[] monitorsArray; synchronized (monitors) { monitorsArray = new CAJMonitor[monitors.size()]; monitors.values().toArray(monitorsArray); monitors.clear(); } for (int i = 0; i < monitorsArray.length; i++) { try { monitorsArray[i].clear(); } catch (Throwable th) { logger.log(Level.SEVERE, "", th); } } } | /**
* Destroy all monitors.
*/ | Destroy all monitors | destroyAllMonitors | {
"repo_name": "epicsdeb/caj",
"path": "src/com/cosylab/epics/caj/CAJChannel.java",
"license": "gpl-2.0",
"size": 34365
} | [
"java.util.logging.Level"
] | import java.util.logging.Level; | import java.util.logging.*; | [
"java.util"
] | java.util; | 735,617 |
public static int validateCaptchaWiredDots(Context context, int v) {
if (v <= 0 || v > 9)
v = context
.getResources()
.getInteger(
R.integer.pkey_display_captcha_wired_dots_default);
return v;
}// validateCaptchaWiredDots() | static int function(Context context, int v) { if (v <= 0 v > 9) v = context .getResources() .getInteger( R.integer.pkey_display_captcha_wired_dots_default); return v; } | /**
* Validates CAPTCHA wired dots.
*
* @param context the context.
* @param v the input value.
* @return the correct value.
*/ | Validates CAPTCHA wired dots | validateCaptchaWiredDots | {
"repo_name": "xdtianyu/NeoAuthenticator",
"path": "AuthenticatorApp/src/main/java/org/xdty/authenticator/androidlockpattern/util/Settings.java",
"license": "apache-2.0",
"size": 16249
} | [
"android.content.Context"
] | import android.content.Context; | import android.content.*; | [
"android.content"
] | android.content; | 834,226 |
public T setInternalProviderFlag1(long flag) {
mValues.put(ProgramColumns.COLUMN_INTERNAL_PROVIDER_FLAG1, flag);
return (T) this;
} | T function(long flag) { mValues.put(ProgramColumns.COLUMN_INTERNAL_PROVIDER_FLAG1, flag); return (T) this; } | /**
* Sets the internal provider flag1 for the program.
*
* @param flag The first internal provider flag for the program.
* @return This Builder object to allow for chaining of calls to builder methods.
* @see androidx.tvprovider.media.tv.TvContractCompat.Programs#COLUMN_INTERNAL_PROVIDER_FLAG1
*/ | Sets the internal provider flag1 for the program | setInternalProviderFlag1 | {
"repo_name": "AndroidX/androidx",
"path": "tvprovider/tvprovider/src/main/java/androidx/tvprovider/media/tv/BaseProgram.java",
"license": "apache-2.0",
"size": 39227
} | [
"androidx.tvprovider.media.tv.TvContractCompat"
] | import androidx.tvprovider.media.tv.TvContractCompat; | import androidx.tvprovider.media.tv.*; | [
"androidx.tvprovider"
] | androidx.tvprovider; | 1,237,404 |
private void mobileBrowserAide(WebDriver driver, String cssSel, String assertString, String correctStr) {
WebElement element = driver.findElement(By.cssSelector("button[class*='" + LAUNCH_DIALOG + "']"));
element.click();
// Opening dialog box
waitForComponentToChangeStatus("div[class*='dialog']", "className", "hidden", true);
// Find and click on specific element to close dialog box
element = driver.findElement(By.cssSelector(cssSel));
element.click();
// Wait for it to close
waitForComponentToChangeStatus("div[class*='dialog']", "className", "hidden", false);
// Make sure that that closes the dialog box sent in the correct data
element = driver.findElement(By.cssSelector(RESULT_LABEL));
assertEquals(assertString, correctStr, element.getAttribute("value"));
} | void function(WebDriver driver, String cssSel, String assertString, String correctStr) { WebElement element = driver.findElement(By.cssSelector(STR + LAUNCH_DIALOG + "']")); element.click(); waitForComponentToChangeStatus(STR, STR, STR, true); element = driver.findElement(By.cssSelector(cssSel)); element.click(); waitForComponentToChangeStatus(STR, STR, STR, false); element = driver.findElement(By.cssSelector(RESULT_LABEL)); assertEquals(assertString, correctStr, element.getAttribute("value")); } | /***********************************************************************************************
************************** MODAL/NON-MODAL MOBILE TESTS*****************************************
***********************************************************************************************/ | MODAL/NON-MODAL MOBILE TESTS | mobileBrowserAide | {
"repo_name": "igor-sfdc/aura",
"path": "aura/src/test/java/org/auraframework/components/ui/dialogUITest/DialogUITest.java",
"license": "apache-2.0",
"size": 17761
} | [
"org.openqa.selenium.By",
"org.openqa.selenium.WebDriver",
"org.openqa.selenium.WebElement"
] | import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; | import org.openqa.selenium.*; | [
"org.openqa.selenium"
] | org.openqa.selenium; | 2,451,374 |
@Test
public void passwordRequiresUsername() {
User user = new User();
user.password = "password";
try {
user.validate();
fail("expected to fail");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("user: cannot specify a password without a username"));
}
} | void function() { User user = new User(); user.password = STR; try { user.validate(); fail(STR); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is(STR)); } } | /**
* Specyfing a password requires a username.
*/ | Specyfing a password requires a username | passwordRequiresUsername | {
"repo_name": "elastisys/scale.cloudpool",
"path": "kubernetes/src/test/java/com/elastisys/scale/cloudpool/kubernetes/config/kubeconfig/TestUser.java",
"license": "apache-2.0",
"size": 9465
} | [
"org.hamcrest.CoreMatchers",
"org.junit.Assert"
] | import org.hamcrest.CoreMatchers; import org.junit.Assert; | import org.hamcrest.*; import org.junit.*; | [
"org.hamcrest",
"org.junit"
] | org.hamcrest; org.junit; | 388,984 |
public Cidr networkOnly() {
BigInteger mask = BigInteger.ONE.shiftLeft(ipLength - prefixBits).subtract(BigInteger.ONE);
InetAddress network = NetMath.inetAddressFromBigInteger(ipBits.andNot(mask), ipLength);
return new Cidr(network, prefixBits);
} | Cidr function() { BigInteger mask = BigInteger.ONE.shiftLeft(ipLength - prefixBits).subtract(BigInteger.ONE); InetAddress network = NetMath.inetAddressFromBigInteger(ipBits.andNot(mask), ipLength); return new Cidr(network, prefixBits); } | /**
* Returns the Cidr corresponding to the network portion of the CIDR.
*
* <p>For example, for "192.168.1.100/24" this would return "192.168.1.0/24".
*/ | Returns the Cidr corresponding to the network portion of the CIDR. For example, for "192.168.1.100/24" this would return "192.168.1.0/24" | networkOnly | {
"repo_name": "google/vpn-libraries",
"path": "android/src/main/java/com/google/android/libraries/privacy/ppn/internal/service/netmath/Cidr.java",
"license": "apache-2.0",
"size": 5227
} | [
"java.math.BigInteger",
"java.net.InetAddress"
] | import java.math.BigInteger; import java.net.InetAddress; | import java.math.*; import java.net.*; | [
"java.math",
"java.net"
] | java.math; java.net; | 1,439,089 |
public void newFile(String type) {
if (type != null) {
jTextPane.setContentType(type);
}
vecTables.clear();
vecTableModels.clear();
vecMarkersBefore.clear();
vecMarkersAfter.clear();
Document document = jTextPane.getEditorKit().createDefaultDocument();
document.addDocumentListener(lpDocumentListener);
if (document instanceof AbstractDocument) {
((AbstractDocument) document).setDocumentFilter(lpDocumentFilter);
}
if (document instanceof StyledDocument) {
vecTableModels.clear();
document.putProperty("i18n", Boolean.TRUE);
document.putProperty(LpEditor.TABLE_MODELS_PROP, vecTableModels);
document.putProperty(LpEditor.COLUMN_TEXT_ATTRIBUTES,
vecColTextAttributes);
}
if (textPaneAttributes == null) {
textPaneAttributes = new TextBlockAttributes();
}
currentTextBlockAttributes = textPaneAttributes;
jTextPane.setDocument(document);
undoManager = new LpCompoundUndoManager(jTextPane);
jTextPane.updateUI();
actualFile = null;
bFileIsEdited = false;
updateBufferStatus(textPaneAttributes, 0, true);
updateFileName();
} | void function(String type) { if (type != null) { jTextPane.setContentType(type); } vecTables.clear(); vecTableModels.clear(); vecMarkersBefore.clear(); vecMarkersAfter.clear(); Document document = jTextPane.getEditorKit().createDefaultDocument(); document.addDocumentListener(lpDocumentListener); if (document instanceof AbstractDocument) { ((AbstractDocument) document).setDocumentFilter(lpDocumentFilter); } if (document instanceof StyledDocument) { vecTableModels.clear(); document.putProperty("i18n", Boolean.TRUE); document.putProperty(LpEditor.TABLE_MODELS_PROP, vecTableModels); document.putProperty(LpEditor.COLUMN_TEXT_ATTRIBUTES, vecColTextAttributes); } if (textPaneAttributes == null) { textPaneAttributes = new TextBlockAttributes(); } currentTextBlockAttributes = textPaneAttributes; jTextPane.setDocument(document); undoManager = new LpCompoundUndoManager(jTextPane); jTextPane.updateUI(); actualFile = null; bFileIsEdited = false; updateBufferStatus(textPaneAttributes, 0, true); updateFileName(); } | /**
* Initialisiert den Editor mit einem leeren Dokument. Erstellt ein neues
* Dokument und verwirft das alte. Der Filename gilt daraufhin als unbekannt
* und das Dokument als nicht editiert.
*
* @param type
* Der content-type fuer die neue Datei. null bedeutet keine
* Aenderung des Typs.
*
* @see #openFile
* @see #openFile(String)
* @see #saveFile(File)
* @see #saveFile(String)
*/ | Initialisiert den Editor mit einem leeren Dokument. Erstellt ein neues Dokument und verwirft das alte. Der Filename gilt daraufhin als unbekannt und das Dokument als nicht editiert | newFile | {
"repo_name": "erdincay/lpclientpc",
"path": "src/com/lp/editor/LpEditor.java",
"license": "agpl-3.0",
"size": 115188
} | [
"com.lp.editor.util.TextBlockAttributes",
"javax.swing.text.AbstractDocument",
"javax.swing.text.Document",
"javax.swing.text.StyledDocument"
] | import com.lp.editor.util.TextBlockAttributes; import javax.swing.text.AbstractDocument; import javax.swing.text.Document; import javax.swing.text.StyledDocument; | import com.lp.editor.util.*; import javax.swing.text.*; | [
"com.lp.editor",
"javax.swing"
] | com.lp.editor; javax.swing; | 358,552 |
protected SpriteIndex getSpriteIndex(URL baseUrl) throws IOException {
SpriteIndex spriteIndex = indexCache.get(baseUrl);
if (spriteIndex == null) {
String indexUrlStr = baseUrl.toExternalForm() + ".json";
URL url = new URL(indexUrlStr);
HTTPClient client = getHttpClient();
HTTPResponse response = client.get(url);
String charset = Optional.ofNullable(response.getResponseCharset()).orElse("UTF-8");
try (BufferedReader reader =
new BufferedReader(
new InputStreamReader(response.getResponseStream(), charset))) {
Object parsed = jsonParser.parse(reader);
if (parsed instanceof JSONObject) {
spriteIndex = new SpriteIndex(indexUrlStr, (JSONObject) parsed);
indexCache.put(baseUrl, spriteIndex);
} else {
throw new MBSpriteException(
"Exception parsing sprite index file from: "
+ indexUrlStr
+ ". Expected JSONObject, but was: "
+ parsed.getClass().getSimpleName());
}
} catch (ParseException e) {
throw new MBSpriteException(
"Exception parsing sprite index file from: " + indexUrlStr, e);
}
}
return spriteIndex;
} | SpriteIndex function(URL baseUrl) throws IOException { SpriteIndex spriteIndex = indexCache.get(baseUrl); if (spriteIndex == null) { String indexUrlStr = baseUrl.toExternalForm() + ".json"; URL url = new URL(indexUrlStr); HTTPClient client = getHttpClient(); HTTPResponse response = client.get(url); String charset = Optional.ofNullable(response.getResponseCharset()).orElse("UTF-8"); try (BufferedReader reader = new BufferedReader( new InputStreamReader(response.getResponseStream(), charset))) { Object parsed = jsonParser.parse(reader); if (parsed instanceof JSONObject) { spriteIndex = new SpriteIndex(indexUrlStr, (JSONObject) parsed); indexCache.put(baseUrl, spriteIndex); } else { throw new MBSpriteException( STR + indexUrlStr + STR + parsed.getClass().getSimpleName()); } } catch (ParseException e) { throw new MBSpriteException( STR + indexUrlStr, e); } } return spriteIndex; } | /**
* Retrieve the sprite sheet index for the provided sprite base url. The base url should have no
* extension.
*
* @param baseUrl The base URL of the Mapbox sprite source (no extension).
* @return The sprite sheet index
*/ | Retrieve the sprite sheet index for the provided sprite base url. The base url should have no extension | getSpriteIndex | {
"repo_name": "geotools/geotools",
"path": "modules/extension/mbstyle/src/main/java/org/geotools/mbstyle/sprite/SpriteGraphicFactory.java",
"license": "lgpl-2.1",
"size": 14063
} | [
"java.io.BufferedReader",
"java.io.IOException",
"java.io.InputStreamReader",
"java.util.Optional",
"org.geotools.http.HTTPClient",
"org.geotools.http.HTTPResponse",
"org.json.simple.JSONObject",
"org.json.simple.parser.ParseException"
] | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Optional; import org.geotools.http.HTTPClient; import org.geotools.http.HTTPResponse; import org.json.simple.JSONObject; import org.json.simple.parser.ParseException; | import java.io.*; import java.util.*; import org.geotools.http.*; import org.json.simple.*; import org.json.simple.parser.*; | [
"java.io",
"java.util",
"org.geotools.http",
"org.json.simple"
] | java.io; java.util; org.geotools.http; org.json.simple; | 753,201 |
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
} | static ImageDescriptor function(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } | /**
* Returns an image descriptor for the image file at the given
* plug-in relative path
*
* @param path the path
* @return the image descriptor
*/ | Returns an image descriptor for the image file at the given plug-in relative path | getImageDescriptor | {
"repo_name": "simonhoo/eclipse-plugins",
"path": "com.cottsoft.plugin.explorer/src/main/java/com/cottsoft/plugin/explorer/Activator.java",
"license": "apache-2.0",
"size": 1378
} | [
"org.eclipse.jface.resource.ImageDescriptor"
] | import org.eclipse.jface.resource.ImageDescriptor; | import org.eclipse.jface.resource.*; | [
"org.eclipse.jface"
] | org.eclipse.jface; | 742,782 |
@Override
public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, Object javaObject, Class<?> staticType) {
return new SecureObjectWrapper(scope, javaObject, staticType);
} | Scriptable function(Context cx, Scriptable scope, Object javaObject, Class<?> staticType) { return new SecureObjectWrapper(scope, javaObject, staticType); } | /**
* Wrap Java object as Scriptable instance to allow full access to its
* methods and fields from JavaScript. This implementation uses a custom wrappers
* that checks the SecurityManager for permission each time a Java member is
* accessed.
*
* @param cx the current Context for this thread
* @param scope the scope of the executing script
* @param javaObject the object to be wrapped
* @param staticType type hint. If security restrictions prevent to wrap
* object based on its class, staticType will be used instead.
* @return the wrapped value which shall not be null
*/ | Wrap Java object as Scriptable instance to allow full access to its methods and fields from JavaScript. This implementation uses a custom wrappers that checks the SecurityManager for permission each time a Java member is accessed | wrapAsJavaObject | {
"repo_name": "geosolutions-it/ringojs",
"path": "src/org/ringojs/security/SecureWrapFactory.java",
"license": "apache-2.0",
"size": 4199
} | [
"org.mozilla.javascript.Context",
"org.mozilla.javascript.Scriptable"
] | import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; | import org.mozilla.javascript.*; | [
"org.mozilla.javascript"
] | org.mozilla.javascript; | 2,789,830 |
private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
ResultPoint[] points = rawResult.getResultPoints();
if (points != null && points.length > 0) {
Canvas canvas = new Canvas(barcode);
Paint paint = new Paint();
paint.setColor(getResources().getColor(R.color.result_points));
if (points.length == 2) {
paint.setStrokeWidth(4.0f);
drawLine(canvas, paint, points[0], points[1], scaleFactor);
} else if (points.length == 4 &&
(rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
// Hacky special case -- draw two lines, for the barcode and metadata
drawLine(canvas, paint, points[0], points[1], scaleFactor);
drawLine(canvas, paint, points[2], points[3], scaleFactor);
} else {
paint.setStrokeWidth(10.0f);
for (ResultPoint point : points) {
if (point != null) {
canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
}
}
}
}
} | void function(Bitmap barcode, float scaleFactor, Result rawResult) { ResultPoint[] points = rawResult.getResultPoints(); if (points != null && points.length > 0) { Canvas canvas = new Canvas(barcode); Paint paint = new Paint(); paint.setColor(getResources().getColor(R.color.result_points)); if (points.length == 2) { paint.setStrokeWidth(4.0f); drawLine(canvas, paint, points[0], points[1], scaleFactor); } else if (points.length == 4 && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) { drawLine(canvas, paint, points[0], points[1], scaleFactor); drawLine(canvas, paint, points[2], points[3], scaleFactor); } else { paint.setStrokeWidth(10.0f); for (ResultPoint point : points) { if (point != null) { canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint); } } } } } | /**
* Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
*
* @param barcode A bitmap of the captured image.
* @param scaleFactor amount by which thumbnail was scaled
* @param rawResult The decoded results which contains the points to draw.
*/ | Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode | drawResultPoints | {
"repo_name": "liulixiang1988/android_demo",
"path": "CaptureActivity/src/com/google/zxing/client/android/CaptureActivity.java",
"license": "apache-2.0",
"size": 27949
} | [
"android.graphics.Bitmap",
"android.graphics.Canvas",
"android.graphics.Paint",
"com.google.zxing.BarcodeFormat",
"com.google.zxing.Result",
"com.google.zxing.ResultPoint"
] | import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import com.google.zxing.BarcodeFormat; import com.google.zxing.Result; import com.google.zxing.ResultPoint; | import android.graphics.*; import com.google.zxing.*; | [
"android.graphics",
"com.google.zxing"
] | android.graphics; com.google.zxing; | 295,312 |
void createAllProxies(DistributedMember member, Region<String, Object> monitoringRegion) {
if (logger.isDebugEnabled()) {
logger.debug("Creating proxy for: {}", member.getId());
}
Set<Map.Entry<String, Object>> mbeans = monitoringRegion.entrySet();
for (Map.Entry<String, Object> mbean : mbeans) {
try {
ObjectName objectName = ObjectName.getInstance(mbean.getKey());
if (logger.isDebugEnabled()) {
logger.debug("Creating proxy for ObjectName {}", objectName);
}
createProxy(member, objectName, monitoringRegion, mbean.getValue());
} catch (Exception e) {
logger.warn("Create Proxy failed for {} with exception {}", mbean.getKey(), e.getMessage(),
e);
}
}
} | void createAllProxies(DistributedMember member, Region<String, Object> monitoringRegion) { if (logger.isDebugEnabled()) { logger.debug(STR, member.getId()); } Set<Map.Entry<String, Object>> mbeans = monitoringRegion.entrySet(); for (Map.Entry<String, Object> mbean : mbeans) { try { ObjectName objectName = ObjectName.getInstance(mbean.getKey()); if (logger.isDebugEnabled()) { logger.debug(STR, objectName); } createProxy(member, objectName, monitoringRegion, mbean.getValue()); } catch (Exception e) { logger.warn(STR, mbean.getKey(), e.getMessage(), e); } } } | /**
* This method will create all the proxies for a given DistributedMember. It does not throw any
* exception to its caller. It handles the error and logs error messages
*
* <p>
* It will be called from GII or when a member joins the system
*/ | This method will create all the proxies for a given DistributedMember. It does not throw any exception to its caller. It handles the error and logs error messages It will be called from GII or when a member joins the system | createAllProxies | {
"repo_name": "davinash/geode",
"path": "geode-core/src/main/java/org/apache/geode/management/internal/MBeanProxyFactory.java",
"license": "apache-2.0",
"size": 8629
} | [
"java.util.Map",
"java.util.Set",
"javax.management.ObjectName",
"org.apache.geode.cache.Region",
"org.apache.geode.distributed.DistributedMember"
] | import java.util.Map; import java.util.Set; import javax.management.ObjectName; import org.apache.geode.cache.Region; import org.apache.geode.distributed.DistributedMember; | import java.util.*; import javax.management.*; import org.apache.geode.cache.*; import org.apache.geode.distributed.*; | [
"java.util",
"javax.management",
"org.apache.geode"
] | java.util; javax.management; org.apache.geode; | 1,281,550 |
public static void assertStatementInInstance(final String description, final int verifyResultCount, final RyaStatement matchStatement, final AccumuloRyaDAO dao, final AccumuloRdfConfiguration config) throws RyaDAOException {
final CloseableIteration<RyaStatement, RyaDAOException> iter = dao.getQueryEngine().query(matchStatement, config);
int count = 0;
while (iter.hasNext()) {
final RyaStatement statement = iter.next();
assertTrue(description + " - match subject: " + matchStatement, matchStatement.getSubject().equals(statement.getSubject()));
assertTrue(description + " - match predicate: " + matchStatement, matchStatement.getPredicate().equals(statement.getPredicate()));
assertTrue(description + " - match object match: " + matchStatement, matchStatement.getObject().equals(statement.getObject()));
count++;
}
iter.close();
assertEquals(description+" - Match Counts.", verifyResultCount, count);
} | static void function(final String description, final int verifyResultCount, final RyaStatement matchStatement, final AccumuloRyaDAO dao, final AccumuloRdfConfiguration config) throws RyaDAOException { final CloseableIteration<RyaStatement, RyaDAOException> iter = dao.getQueryEngine().query(matchStatement, config); int count = 0; while (iter.hasNext()) { final RyaStatement statement = iter.next(); assertTrue(description + STR + matchStatement, matchStatement.getSubject().equals(statement.getSubject())); assertTrue(description + STR + matchStatement, matchStatement.getPredicate().equals(statement.getPredicate())); assertTrue(description + STR + matchStatement, matchStatement.getObject().equals(statement.getObject())); count++; } iter.close(); assertEquals(description+STR, verifyResultCount, count); } | /**
* Checks if a {@link RyaStatement} is in the specified instance's DAO.
* @param description the description message for the statement.
* @param verifyResultCount the expected number of matches.
* @param matchStatement the {@link RyaStatement} to match.
* @param dao the {@link AccumuloRyaDAO}.
* @param config the {@link AccumuloRdfConfiguration} for the instance.
* @throws RyaDAOException
*/ | Checks if a <code>RyaStatement</code> is in the specified instance's DAO | assertStatementInInstance | {
"repo_name": "meiercaleb/incubator-rya",
"path": "extras/rya.merger/src/test/java/org/apache/rya/accumulo/mr/merge/util/TestUtils.java",
"license": "apache-2.0",
"size": 10364
} | [
"info.aduna.iteration.CloseableIteration",
"org.apache.rya.accumulo.AccumuloRdfConfiguration",
"org.apache.rya.accumulo.AccumuloRyaDAO",
"org.apache.rya.api.domain.RyaStatement",
"org.apache.rya.api.persist.RyaDAOException",
"org.junit.Assert"
] | import info.aduna.iteration.CloseableIteration; import org.apache.rya.accumulo.AccumuloRdfConfiguration; import org.apache.rya.accumulo.AccumuloRyaDAO; import org.apache.rya.api.domain.RyaStatement; import org.apache.rya.api.persist.RyaDAOException; import org.junit.Assert; | import info.aduna.iteration.*; import org.apache.rya.accumulo.*; import org.apache.rya.api.domain.*; import org.apache.rya.api.persist.*; import org.junit.*; | [
"info.aduna.iteration",
"org.apache.rya",
"org.junit"
] | info.aduna.iteration; org.apache.rya; org.junit; | 96,215 |
EClass getUiXbaseValidator(); | EClass getUiXbaseValidator(); | /**
* Returns the meta object for class '{@link org.lunifera.ecview.semantic.uimodel.UiXbaseValidator <em>Ui Xbase Validator</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Ui Xbase Validator</em>'.
* @see org.lunifera.ecview.semantic.uimodel.UiXbaseValidator
* @generated
*/ | Returns the meta object for class '<code>org.lunifera.ecview.semantic.uimodel.UiXbaseValidator Ui Xbase Validator</code>'. | getUiXbaseValidator | {
"repo_name": "lunifera/lunifera-ecview-addons",
"path": "org.lunifera.ecview.semantic.uimodel/src/org/lunifera/ecview/semantic/uimodel/UiModelPackage.java",
"license": "epl-1.0",
"size": 498897
} | [
"org.eclipse.emf.ecore.EClass"
] | import org.eclipse.emf.ecore.EClass; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 1,419,425 |
private ValueNode getValueNode(Object value) {
// TODO: is there a more flexible way of doing this?
// Probably should use the ValueNodeBuilderHelper.
PreludeTypeConstants preludeTypeConstants = calServices.getPreludeTypeConstants();
if (value instanceof Character) {
return new LiteralValueNode(value, preludeTypeConstants.getCharType());
}
else if (value instanceof Boolean) {
return new LiteralValueNode(value, preludeTypeConstants.getBooleanType());
}
else if (value instanceof Byte) {
return new LiteralValueNode(value, preludeTypeConstants.getByteType());
}
else if (value instanceof Short) {
return new LiteralValueNode(value, preludeTypeConstants.getShortType());
}
else if (value instanceof Integer) {
return new LiteralValueNode(value, preludeTypeConstants.getIntType());
}
else if (value instanceof Long) {
return new LiteralValueNode(value, preludeTypeConstants.getLongType());
}
else if (value instanceof Float) {
return new LiteralValueNode(value, preludeTypeConstants.getFloatType());
}
else if (value instanceof Double) {
return new LiteralValueNode(value, preludeTypeConstants.getDoubleType());
}
else if (value instanceof String) {
return new LiteralValueNode(value, preludeTypeConstants.getStringType());
}
else if (value instanceof Color) {
TypeExpr colourType = calServices.getTypeFromQualifiedName(CAL_Color.TypeConstructors.Color);
if (colourType == null) {
return null;
}
return new ColourValueNode((Color) value, colourType);
}
else if (value instanceof Time) {
TypeExpr timeType = calServices.getTypeFromQualifiedName(CAL_Time.TypeConstructors.Time);
if (timeType == null) {
return null;
}
return new JTimeValueNode((Time) value, timeType);
}
return null;
}
| ValueNode function(Object value) { PreludeTypeConstants preludeTypeConstants = calServices.getPreludeTypeConstants(); if (value instanceof Character) { return new LiteralValueNode(value, preludeTypeConstants.getCharType()); } else if (value instanceof Boolean) { return new LiteralValueNode(value, preludeTypeConstants.getBooleanType()); } else if (value instanceof Byte) { return new LiteralValueNode(value, preludeTypeConstants.getByteType()); } else if (value instanceof Short) { return new LiteralValueNode(value, preludeTypeConstants.getShortType()); } else if (value instanceof Integer) { return new LiteralValueNode(value, preludeTypeConstants.getIntType()); } else if (value instanceof Long) { return new LiteralValueNode(value, preludeTypeConstants.getLongType()); } else if (value instanceof Float) { return new LiteralValueNode(value, preludeTypeConstants.getFloatType()); } else if (value instanceof Double) { return new LiteralValueNode(value, preludeTypeConstants.getDoubleType()); } else if (value instanceof String) { return new LiteralValueNode(value, preludeTypeConstants.getStringType()); } else if (value instanceof Color) { TypeExpr colourType = calServices.getTypeFromQualifiedName(CAL_Color.TypeConstructors.Color); if (colourType == null) { return null; } return new ColourValueNode((Color) value, colourType); } else if (value instanceof Time) { TypeExpr timeType = calServices.getTypeFromQualifiedName(CAL_Time.TypeConstructors.Time); if (timeType == null) { return null; } return new JTimeValueNode((Time) value, timeType); } return null; } | /**
* Returns a simple value node for the specified value, or null
* if it cannot be represented as a simple value node.
* This supports the following types:
* Color, Character, Boolean, Byte, Short, Integer, Long, Float, Double, String, and Time.
* @param value a value
* @return a value node for this value, or null if it cannot be expressed as a simple value node
*/ | Returns a simple value node for the specified value, or null if it cannot be represented as a simple value node. This supports the following types: Color, Character, Boolean, Byte, Short, Integer, Long, Float, Double, String, and Time | getValueNode | {
"repo_name": "levans/Open-Quark",
"path": "src/Quark_Gems/src/org/openquark/gems/client/services/GemFactory.java",
"license": "bsd-3-clause",
"size": 6512
} | [
"java.awt.Color",
"org.openquark.cal.compiler.PreludeTypeConstants",
"org.openquark.cal.compiler.TypeExpr",
"org.openquark.cal.valuenode.ColourValueNode",
"org.openquark.cal.valuenode.JTimeValueNode",
"org.openquark.cal.valuenode.LiteralValueNode",
"org.openquark.cal.valuenode.ValueNode",
"org.openquark.util.time.Time"
] | import java.awt.Color; import org.openquark.cal.compiler.PreludeTypeConstants; import org.openquark.cal.compiler.TypeExpr; import org.openquark.cal.valuenode.ColourValueNode; import org.openquark.cal.valuenode.JTimeValueNode; import org.openquark.cal.valuenode.LiteralValueNode; import org.openquark.cal.valuenode.ValueNode; import org.openquark.util.time.Time; | import java.awt.*; import org.openquark.cal.compiler.*; import org.openquark.cal.valuenode.*; import org.openquark.util.time.*; | [
"java.awt",
"org.openquark.cal",
"org.openquark.util"
] | java.awt; org.openquark.cal; org.openquark.util; | 373,286 |
@Override
public void session(String username, SecureString password, ActionListener<LdapSession> listener) {
try {
new AbstractRunnable() {
final LDAPConnection connection = LdapUtils.privilegedConnect(serverSet::getConnection);
final byte[] passwordBytes = CharArrays.toUtf8Bytes(password.getChars());
Exception containerException = null;
int loopIndex = 0; | void function(String username, SecureString password, ActionListener<LdapSession> listener) { try { new AbstractRunnable() { final LDAPConnection connection = LdapUtils.privilegedConnect(serverSet::getConnection); final byte[] passwordBytes = CharArrays.toUtf8Bytes(password.getChars()); Exception containerException = null; int loopIndex = 0; | /**
* This iterates through the configured user templates attempting to open. If all attempts fail, the last exception
* is kept as the cause of the thrown exception
*
* @param username a relative name, Not a distinguished name, that will be inserted into the template.
*/ | This iterates through the configured user templates attempting to open. If all attempts fail, the last exception is kept as the cause of the thrown exception | session | {
"repo_name": "coding0011/elasticsearch",
"path": "x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactory.java",
"license": "apache-2.0",
"size": 6081
} | [
"com.unboundid.ldap.sdk.LDAPConnection",
"org.elasticsearch.action.ActionListener",
"org.elasticsearch.common.CharArrays",
"org.elasticsearch.common.settings.SecureString",
"org.elasticsearch.common.util.concurrent.AbstractRunnable",
"org.elasticsearch.xpack.security.authc.ldap.support.LdapSession",
"org.elasticsearch.xpack.security.authc.ldap.support.LdapUtils"
] | import com.unboundid.ldap.sdk.LDAPConnection; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.CharArrays; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession; import org.elasticsearch.xpack.security.authc.ldap.support.LdapUtils; | import com.unboundid.ldap.sdk.*; import org.elasticsearch.action.*; import org.elasticsearch.common.*; import org.elasticsearch.common.settings.*; import org.elasticsearch.common.util.concurrent.*; import org.elasticsearch.xpack.security.authc.ldap.support.*; | [
"com.unboundid.ldap",
"org.elasticsearch.action",
"org.elasticsearch.common",
"org.elasticsearch.xpack"
] | com.unboundid.ldap; org.elasticsearch.action; org.elasticsearch.common; org.elasticsearch.xpack; | 1,688,099 |
private void updateTypeOfParameters(Node n, FunctionType fnType) {
int i = 0;
int childCount = n.getChildCount();
for (Node iParameter : fnType.getParameters()) {
if (i + 1 >= childCount) {
// TypeCheck#visitParametersList will warn so we bail.
return;
}
JSType iParameterType = getJSType(iParameter);
Node iArgument = n.getChildAtIndex(i + 1);
JSType iArgumentType = getJSType(iArgument);
inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType);
// TODO(johnlenz): Filter out non-function types
// (such as null and undefined) as
// we only care about FUNCTION subtypes here.
JSType restrictedParameter = iParameterType
.restrictByNotNullOrUndefined()
.toMaybeFunctionType();
if (restrictedParameter != null) {
if (iArgument.isFunction() &&
iArgumentType.isFunctionType() &&
iArgument.getJSDocInfo() == null) {
iArgument.setJSType(restrictedParameter);
}
}
i++;
}
} | void function(Node n, FunctionType fnType) { int i = 0; int childCount = n.getChildCount(); for (Node iParameter : fnType.getParameters()) { if (i + 1 >= childCount) { return; } JSType iParameterType = getJSType(iParameter); Node iArgument = n.getChildAtIndex(i + 1); JSType iArgumentType = getJSType(iArgument); inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType); JSType restrictedParameter = iParameterType .restrictByNotNullOrUndefined() .toMaybeFunctionType(); if (restrictedParameter != null) { if (iArgument.isFunction() && iArgumentType.isFunctionType() && iArgument.getJSDocInfo() == null) { iArgument.setJSType(restrictedParameter); } } i++; } } | /**
* For functions with function parameters, type inference will set the type of
* a function literal argument from the function parameter type.
*/ | For functions with function parameters, type inference will set the type of a function literal argument from the function parameter type | updateTypeOfParameters | {
"repo_name": "dound/google-closure-compiler",
"path": "src/com/google/javascript/jscomp/TypeInference.java",
"license": "apache-2.0",
"size": 51764
} | [
"com.google.javascript.rhino.Node",
"com.google.javascript.rhino.jstype.FunctionType",
"com.google.javascript.rhino.jstype.JSType"
] | import com.google.javascript.rhino.Node; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; | import com.google.javascript.rhino.*; import com.google.javascript.rhino.jstype.*; | [
"com.google.javascript"
] | com.google.javascript; | 536,328 |
private static long lookupRawId(ContentResolver resolver, String moduleName, String beanId) {
long rawId = 0;
Uri contentUri = ContentUtils.getModuleUri(moduleName);
String[] projection = new String[] { SugarCRMContent.RECORD_ID };
final Cursor c = resolver.query(contentUri, projection, mSelection, new String[] { beanId }, null);
try {
if (c.moveToFirst()) {
rawId = c.getLong(0);
}
} finally {
if (c != null) {
c.close();
}
}
return rawId;
} | static long function(ContentResolver resolver, String moduleName, String beanId) { long rawId = 0; Uri contentUri = ContentUtils.getModuleUri(moduleName); String[] projection = new String[] { SugarCRMContent.RECORD_ID }; final Cursor c = resolver.query(contentUri, projection, mSelection, new String[] { beanId }, null); try { if (c.moveToFirst()) { rawId = c.getLong(0); } } finally { if (c != null) { c.close(); } } return rawId; } | /**
* Returns the Raw Module item id for a sugar crm SyncAdapter , or 0 if the item is not found.
*
* @param context
* the Authenticator Activity context
* @param userId
* the SyncAdapter bean ID to lookup
* @return the Raw item id, or 0 if not found
*/ | Returns the Raw Module item id for a sugar crm SyncAdapter , or 0 if the item is not found | lookupRawId | {
"repo_name": "Imaginea/pancake-android",
"path": "src/com/imaginea/android/sugarcrm/sync/SugarSyncManager.java",
"license": "apache-2.0",
"size": 50197
} | [
"android.content.ContentResolver",
"android.database.Cursor",
"android.net.Uri",
"com.imaginea.android.sugarcrm.provider.ContentUtils",
"com.imaginea.android.sugarcrm.provider.SugarCRMContent"
] | import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import com.imaginea.android.sugarcrm.provider.ContentUtils; import com.imaginea.android.sugarcrm.provider.SugarCRMContent; | import android.content.*; import android.database.*; import android.net.*; import com.imaginea.android.sugarcrm.provider.*; | [
"android.content",
"android.database",
"android.net",
"com.imaginea.android"
] | android.content; android.database; android.net; com.imaginea.android; | 1,280,739 |
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mSlidingMenu.isMenuShowing()) {
showContent();
return true;
}
return false;
} | boolean function(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mSlidingMenu.isMenuShowing()) { showContent(); return true; } return false; } | /**
* On key up.
*
* @param keyCode the key code
* @param event the event
* @return true, if successful
*/ | On key up | onKeyUp | {
"repo_name": "jjhesk/BringItBackAdvanceSlidingMenu",
"path": "AdvancedSlidingMenu/slidingmenulib/src/main/java/com/hkm/slidingmenulib/gestured/app/SlidingActivityHelper.java",
"license": "apache-2.0",
"size": 7193
} | [
"android.view.KeyEvent"
] | import android.view.KeyEvent; | import android.view.*; | [
"android.view"
] | android.view; | 2,122,997 |
EReference getNavigation_DiagramDescription(); | EReference getNavigation_DiagramDescription(); | /**
* Returns the meta object for the reference '
* {@link org.eclipse.sirius.diagram.description.tool.Navigation#getDiagramDescription
* <em>Diagram Description</em>}'. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @return the meta object for the reference '<em>Diagram Description</em>'.
* @see org.eclipse.sirius.diagram.description.tool.Navigation#getDiagramDescription()
* @see #getNavigation()
* @generated
*/ | Returns the meta object for the reference ' <code>org.eclipse.sirius.diagram.description.tool.Navigation#getDiagramDescription Diagram Description</code>'. | getNavigation_DiagramDescription | {
"repo_name": "FTSRG/iq-sirius-integration",
"path": "host/org.eclipse.sirius.diagram/src-gen/org/eclipse/sirius/diagram/description/tool/ToolPackage.java",
"license": "epl-1.0",
"size": 180886
} | [
"org.eclipse.emf.ecore.EReference"
] | import org.eclipse.emf.ecore.EReference; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,445,904 |
private char[] zeros(int count) {
char[] zz;
zz = new char[count];
Arrays.fill(zz, '0');
return zz;
} | char[] function(int count) { char[] zz; zz = new char[count]; Arrays.fill(zz, '0'); return zz; } | /**
* Creates a character array with zeros.
*
* @param count
* @return
*/ | Creates a character array with zeros | zeros | {
"repo_name": "hmetaxa/MixLDA",
"path": "src/org/knowceans/util/ExpDouble.java",
"license": "epl-1.0",
"size": 10164
} | [
"java.util.Arrays"
] | import java.util.Arrays; | import java.util.*; | [
"java.util"
] | java.util; | 1,238,077 |
public static double[] readDoubleArray(DataInput in) throws IOException {
int length = in.readInt();
double[] array = new double[length];
for (int index = 0; index < length; index++) {
array[index] = in.readDouble();
}
return array;
} | static double[] function(DataInput in) throws IOException { int length = in.readInt(); double[] array = new double[length]; for (int index = 0; index < length; index++) { array[index] = in.readDouble(); } return array; } | /**
* Reads a double[] from a DataInput
* @throws java.io.IOException
*/ | Reads a double[] from a DataInput | readDoubleArray | {
"repo_name": "saradelrio/Chi-FRBCS-BigDataCS",
"path": "src/org/apache/mahout/classifier/chi_rwcs/Chi_RWCSUtils.java",
"license": "apache-2.0",
"size": 4808
} | [
"java.io.DataInput",
"java.io.IOException"
] | import java.io.DataInput; import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 2,265,058 |
@Transactional
public List<AlertCurrentEntity> findAll(AlertCurrentRequest request) {
EntityManager entityManager = m_entityManagerProvider.get();
// convert the Ambari predicate into a JPA predicate
CurrentPredicateVisitor visitor = new CurrentPredicateVisitor();
PredicateHelper.visit(request.Predicate, visitor);
CriteriaQuery<AlertCurrentEntity> query = visitor.getCriteriaQuery();
javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate();
if (null != jpaPredicate) {
query.where(jpaPredicate);
}
// sorting
JpaSortBuilder<AlertCurrentEntity> sortBuilder = new JpaSortBuilder<AlertCurrentEntity>();
List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor);
query.orderBy(sortOrders);
// pagination
TypedQuery<AlertCurrentEntity> typedQuery = entityManager.createQuery(query);
if( null != request.Pagination ){
// prevent JPA errors when -1 is passed in by accident
int offset = request.Pagination.getOffset();
if (offset < 0) {
offset = 0;
}
typedQuery.setFirstResult(offset);
typedQuery.setMaxResults(request.Pagination.getPageSize());
}
return m_daoUtils.selectList(typedQuery);
} | List<AlertCurrentEntity> function(AlertCurrentRequest request) { EntityManager entityManager = m_entityManagerProvider.get(); CurrentPredicateVisitor visitor = new CurrentPredicateVisitor(); PredicateHelper.visit(request.Predicate, visitor); CriteriaQuery<AlertCurrentEntity> query = visitor.getCriteriaQuery(); javax.persistence.criteria.Predicate jpaPredicate = visitor.getJpaPredicate(); if (null != jpaPredicate) { query.where(jpaPredicate); } JpaSortBuilder<AlertCurrentEntity> sortBuilder = new JpaSortBuilder<AlertCurrentEntity>(); List<Order> sortOrders = sortBuilder.buildSortOrders(request.Sort, visitor); query.orderBy(sortOrders); TypedQuery<AlertCurrentEntity> typedQuery = entityManager.createQuery(query); if( null != request.Pagination ){ int offset = request.Pagination.getOffset(); if (offset < 0) { offset = 0; } typedQuery.setFirstResult(offset); typedQuery.setMaxResults(request.Pagination.getPageSize()); } return m_daoUtils.selectList(typedQuery); } | /**
* Finds all {@link AlertCurrentEntity} that match the provided
* {@link AlertCurrentRequest}. This method will make JPA do the heavy lifting
* of providing a slice of the result set.
*
* @param request
* @return
*/ | Finds all <code>AlertCurrentEntity</code> that match the provided <code>AlertCurrentRequest</code>. This method will make JPA do the heavy lifting of providing a slice of the result set | findAll | {
"repo_name": "zouzhberk/ambaridemo",
"path": "demo-server/src/main/java/org/apache/ambari/server/orm/dao/AlertsDAO.java",
"license": "apache-2.0",
"size": 33168
} | [
"java.util.List",
"javax.persistence.EntityManager",
"javax.persistence.TypedQuery",
"javax.persistence.criteria.CriteriaQuery",
"javax.persistence.criteria.Order",
"org.apache.ambari.server.api.query.JpaSortBuilder",
"org.apache.ambari.server.controller.AlertCurrentRequest",
"org.apache.ambari.server.controller.spi.Predicate",
"org.apache.ambari.server.controller.utilities.PredicateHelper",
"org.apache.ambari.server.orm.entities.AlertCurrentEntity"
] | import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Order; import org.apache.ambari.server.api.query.JpaSortBuilder; import org.apache.ambari.server.controller.AlertCurrentRequest; import org.apache.ambari.server.controller.spi.Predicate; import org.apache.ambari.server.controller.utilities.PredicateHelper; import org.apache.ambari.server.orm.entities.AlertCurrentEntity; | import java.util.*; import javax.persistence.*; import javax.persistence.criteria.*; import org.apache.ambari.server.api.query.*; import org.apache.ambari.server.controller.*; import org.apache.ambari.server.controller.spi.*; import org.apache.ambari.server.controller.utilities.*; import org.apache.ambari.server.orm.entities.*; | [
"java.util",
"javax.persistence",
"org.apache.ambari"
] | java.util; javax.persistence; org.apache.ambari; | 441,727 |
public Dialog show() {
return CustomAlertDialogue.getInstance().show(((Activity) context), this);
} | Dialog function() { return CustomAlertDialogue.getInstance().show(((Activity) context), this); } | /**
* Display the Dialogue with Builder parameters.
* @return
*/ | Display the Dialogue with Builder parameters | show | {
"repo_name": "pennlabs/penn-mobile-android",
"path": "PennMobile/src/main/java/com/pennapps/labs/pennmobile/components/dialog/CustomAlertDialogue.java",
"license": "mit",
"size": 42841
} | [
"android.app.Activity",
"android.app.Dialog"
] | import android.app.Activity; import android.app.Dialog; | import android.app.*; | [
"android.app"
] | android.app; | 712,707 |
@SuppressWarnings("null") // the method was designed to play with fire
public static void setConfiguration( URL serviceConfigurationUrl )
throws InvalidConfigurationException {
try {
WMSConfigurationDocument doc = new WMSConfigurationDocument();
WMSConfigurationDocument_1_3_0 doc130 = new WMSConfigurationDocument_1_3_0();
// changes start here
int dc = 50;
boolean configured = false;
while ( !configured ) {
try {
doc.load( serviceConfigurationUrl );
if ( "1.3.0".equals( doc.getRootElement().getAttribute( "version" ) ) ) {
LOG.logInfo( Messages.getMessage( "WMS_VERSION130" ) );
doc130.load( serviceConfigurationUrl );
doc = null;
} else {
LOG.logInfo( Messages.getMessage( "WMS_VERSIONDEFAULT" ) );
doc130 = null;
}
configured = true;
} catch ( IOException ioe ) {
if ( serviceConfigurationUrl.getProtocol().startsWith( "http" ) && dc > 0 ) {
LOG.logWarning( "No successful connection to the WMS-Configuration-URL, "
+ "trying again in 10 seconds. Will try " + dc + " more times to connect." );
Thread.sleep( 10000 );
dc--;
} else {
throw ( ioe );
}
}
}
// changes end here
WMSConfigurationType conf;
if ( doc != null ) {
conf = doc.parseConfiguration();
} else {
conf = doc130.parseConfiguration();
}
WMServiceFactory.setConfiguration( conf );
} catch ( Exception e ) {
LOG.logError( e.getMessage(), e );
throw new InvalidConfigurationException( "WMServiceFactory", e.getMessage() );
}
}
| @SuppressWarnings("null") static void function( URL serviceConfigurationUrl ) throws InvalidConfigurationException { try { WMSConfigurationDocument doc = new WMSConfigurationDocument(); WMSConfigurationDocument_1_3_0 doc130 = new WMSConfigurationDocument_1_3_0(); int dc = 50; boolean configured = false; while ( !configured ) { try { doc.load( serviceConfigurationUrl ); if ( "1.3.0".equals( doc.getRootElement().getAttribute( STR ) ) ) { LOG.logInfo( Messages.getMessage( STR ) ); doc130.load( serviceConfigurationUrl ); doc = null; } else { LOG.logInfo( Messages.getMessage( STR ) ); doc130 = null; } configured = true; } catch ( IOException ioe ) { if ( serviceConfigurationUrl.getProtocol().startsWith( "http" ) && dc > 0 ) { LOG.logWarning( STR + STR + dc + STR ); Thread.sleep( 10000 ); dc--; } else { throw ( ioe ); } } } WMSConfigurationType conf; if ( doc != null ) { conf = doc.parseConfiguration(); } else { conf = doc130.parseConfiguration(); } WMServiceFactory.setConfiguration( conf ); } catch ( Exception e ) { LOG.logError( e.getMessage(), e ); throw new InvalidConfigurationException( STR, e.getMessage() ); } } | /**
* Sets the default configuration by URL.
*
* @param serviceConfigurationUrl
* @throws InvalidConfigurationException
*/ | Sets the default configuration by URL | setConfiguration | {
"repo_name": "lat-lon/deegree2-base",
"path": "deegree2-core/src/main/java/org/deegree/ogcwebservices/wms/WMServiceFactory.java",
"license": "lgpl-2.1",
"size": 5904
} | [
"java.io.IOException",
"org.deegree.i18n.Messages",
"org.deegree.ogcwebservices.wcs.configuration.InvalidConfigurationException",
"org.deegree.ogcwebservices.wms.configuration.WMSConfigurationDocument",
"org.deegree.ogcwebservices.wms.configuration.WMSConfigurationType"
] | import java.io.IOException; import org.deegree.i18n.Messages; import org.deegree.ogcwebservices.wcs.configuration.InvalidConfigurationException; import org.deegree.ogcwebservices.wms.configuration.WMSConfigurationDocument; import org.deegree.ogcwebservices.wms.configuration.WMSConfigurationType; | import java.io.*; import org.deegree.i18n.*; import org.deegree.ogcwebservices.wcs.configuration.*; import org.deegree.ogcwebservices.wms.configuration.*; | [
"java.io",
"org.deegree.i18n",
"org.deegree.ogcwebservices"
] | java.io; org.deegree.i18n; org.deegree.ogcwebservices; | 1,458,323 |
@Generated
@Selector("type")
@NInt
public native long type(); | @Selector("type") native long function(); | /**
* Type of the value for which the corresponding property below is held
*/ | Type of the value for which the corresponding property below is held | type | {
"repo_name": "multi-os-engine/moe-core",
"path": "moe.apple/moe.platform.ios/src/main/java/apple/coreml/MLFeatureValue.java",
"license": "apache-2.0",
"size": 13298
} | [
"org.moe.natj.objc.ann.Selector"
] | import org.moe.natj.objc.ann.Selector; | import org.moe.natj.objc.ann.*; | [
"org.moe.natj"
] | org.moe.natj; | 713,468 |
//-----------------------------------------------------------------------
public ImmutableList<CalculationResult> getCells() {
return cells;
} | ImmutableList<CalculationResult> function() { return cells; } | /**
* Gets the calculated cells.
* Each entry contains a calculation result for a single cell.
* @return the value of the property, not null
*/ | Gets the calculated cells. Each entry contains a calculation result for a single cell | getCells | {
"repo_name": "OpenGamma/Strata",
"path": "modules/calc/src/main/java/com/opengamma/strata/calc/runner/CalculationResults.java",
"license": "apache-2.0",
"size": 4610
} | [
"com.google.common.collect.ImmutableList"
] | import com.google.common.collect.ImmutableList; | import com.google.common.collect.*; | [
"com.google.common"
] | com.google.common; | 2,584,679 |
BaseCollectionReader getCollectionReader(); | BaseCollectionReader getCollectionReader(); | /**
* Gets the Collection Reader for this CPE.
*
* @return the collection reader
*/ | Gets the Collection Reader for this CPE | getCollectionReader | {
"repo_name": "apache/uima-uimaj",
"path": "uimaj-core/src/main/java/org/apache/uima/collection/CollectionProcessingEngine.java",
"license": "apache-2.0",
"size": 7532
} | [
"org.apache.uima.collection.base_cpm.BaseCollectionReader"
] | import org.apache.uima.collection.base_cpm.BaseCollectionReader; | import org.apache.uima.collection.base_cpm.*; | [
"org.apache.uima"
] | org.apache.uima; | 2,084,903 |
protected void doFetch(SocketTimeout timeout) throws IOException {
_headersRead = false;
_aborted = false;
try {
readHeaders();
} finally {
_headersRead = true;
}
if (_aborted)
throw new IOException("Timed out reading the HTTP headers");
if (timeout != null) {
timeout.resetTimer();
if (_fetchInactivityTimeout > 0)
timeout.setInactivityTimeout(_fetchInactivityTimeout);
else
timeout.setInactivityTimeout(INACTIVITY_TIMEOUT);
}
// _proxy is null when extended by I2PSocketEepGet
if (_proxy != null && !_shouldProxy) {
// we only set the soTimeout before the headers if not proxied
if (_fetchInactivityTimeout > 0)
_proxy.setSoTimeout(_fetchInactivityTimeout);
else
_proxy.setSoTimeout(INACTIVITY_TIMEOUT);
}
if (_redirectLocation != null) {
// we also are here after a 407
//try {
if (_redirectLocation.startsWith("http://")) {
_actualURL = _redirectLocation;
} else {
// the Location: field has been required to be an absolute URI at least since
// RFC 1945 (HTTP/1.0 1996), so it isn't clear what the point of this is.
// This oddly adds a ":" even if no port, but that seems to work.
URL url = new URL(_actualURL);
if (_redirectLocation.startsWith("/"))
_actualURL = "http://" + url.getHost() + ":" + url.getPort() + _redirectLocation;
else
// this blows up completely on a redirect to https://, for example
_actualURL = "http://" + url.getHost() + ":" + url.getPort() + "/" + _redirectLocation;
}
// an MUE is an IOE
//} catch (MalformedURLException mue) {
// throw new IOException("Redirected from an invalid URL");
//}
AuthState as = _authState;
if (_responseCode == 407) {
if (!_shouldProxy)
throw new IOException("Proxy auth response from non-proxy");
if (as == null)
throw new IOException("Proxy requires authentication");
if (as.authSent)
throw new IOException("Proxy authentication failed"); // ignore stale
if (_log.shouldLog(Log.INFO)) _log.info("Adding auth");
// actually happens in getRequest()
} else {
_redirects++;
if (_redirects > 5)
throw new IOException("Too many redirects: to " + _redirectLocation);
if (_log.shouldLog(Log.INFO)) _log.info("Redirecting to " + _redirectLocation);
if (as != null)
as.authSent = false;
}
// reset some important variables, we don't want to save the values from the redirect
_bytesRemaining = -1;
_redirectLocation = null;
_etag = _etagOrig;
_lastModified = _lastModifiedOrig;
_contentType = null;
_encodingChunked = false;
sendRequest(timeout);
doFetch(timeout);
return;
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("Headers read completely, reading " + _bytesRemaining);
boolean strictSize = (_bytesRemaining >= 0);
// If minimum or maximum size defined, ensure they aren't exceeded
if ((_minSize > 0) && (_bytesRemaining < _minSize))
throw new IOException("HTTP response size " + _bytesRemaining + " violates minimum of " + _minSize + " bytes");
if ((_maxSize > -1) && (_bytesRemaining > _maxSize))
throw new IOException("HTTP response size " + _bytesRemaining + " violates maximum of " + _maxSize + " bytes");
Thread pusher = null;
_decompressException = null;
if (_isGzippedResponse) {
PipedInputStream pi = BigPipedInputStream.getInstance();
PipedOutputStream po = new PipedOutputStream(pi);
pusher = new I2PAppThread(new Gunzipper(pi, _out), "EepGet Decompressor");
_out = po;
pusher.start();
}
int remaining = (int)_bytesRemaining;
byte buf[] = new byte[16*1024];
while (_keepFetching && ( (remaining > 0) || !strictSize ) && !_aborted) {
int toRead = buf.length;
if (strictSize && toRead > remaining)
toRead = remaining;
int read = _proxyIn.read(buf, 0, toRead);
if (read == -1)
break;
if (timeout != null)
timeout.resetTimer();
_out.write(buf, 0, read);
_bytesTransferred += read;
if ((_maxSize > -1) && (_alreadyTransferred + read > _maxSize)) // could transfer a little over maxSize
throw new IOException("Bytes transferred " + (_alreadyTransferred + read) + " violates maximum of " + _maxSize + " bytes");
remaining -= read;
if (remaining==0 && _encodingChunked) {
int char1 = _proxyIn.read();
if (char1 == '\r') {
int char2 = _proxyIn.read();
if (char2 == '\n') {
remaining = (int) readChunkLength();
} else {
_out.write(char1);
_out.write(char2);
_bytesTransferred += 2;
remaining -= 2;
read += 2;
}
} else {
_out.write(char1);
_bytesTransferred++;
remaining--;
read++;
}
}
if (timeout != null)
timeout.resetTimer();
if (_bytesRemaining >= read) // else chunked?
_bytesRemaining -= read;
if (read > 0) {
for (int i = 0; i < _listeners.size(); i++)
_listeners.get(i).bytesTransferred(
_alreadyTransferred,
read,
_bytesTransferred,
_encodingChunked?-1:_bytesRemaining,
_url);
// This seems necessary to properly resume a partial download into a stream,
// as nothing else increments _alreadyTransferred, and there's no file length to check.
// Do this after calling the listeners to keep the total correct
_alreadyTransferred += read;
}
}
if (_out != null)
_out.close();
_out = null;
if (_isGzippedResponse) {
try {
pusher.join();
} catch (InterruptedException ie) {}
pusher = null;
if (_decompressException != null) {
// we can't resume from here
_keepFetching = false;
throw _decompressException;
}
}
if (_aborted)
throw new IOException("Timed out reading the HTTP data");
if (timeout != null)
timeout.cancel();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Done transferring " + _bytesTransferred + " (ok? " + !_transferFailed + ")");
if (_transferFailed) {
// 404, etc - transferFailed is called after all attempts fail, by fetch() above
if (!_listeners.isEmpty()) {
String s;
if (_responseText != null)
s = "Attempt failed: " + _responseCode + ' ' + _responseText;
else
s = "Attempt failed: " + _responseCode;
Exception e = new IOException(s);
for (int i = 0; i < _listeners.size(); i++) {
_listeners.get(i).attemptFailed(_url, _bytesTransferred, _bytesRemaining, _currentAttempt,
_numRetries, e);
}
}
} else if ((_minSize > 0) && (_alreadyTransferred < _minSize)) {
throw new IOException("Bytes transferred " + _alreadyTransferred + " violates minimum of " + _minSize + " bytes");
} else if ( (_bytesRemaining == -1) || (remaining == 0) ) {
for (int i = 0; i < _listeners.size(); i++)
_listeners.get(i).transferComplete(
_alreadyTransferred,
_bytesTransferred,
_encodingChunked?-1:_bytesRemaining,
_url,
_outputFile,
_notModified);
} else {
throw new IOException("Disconnection on attempt " + _currentAttempt + " after " + _bytesTransferred);
}
} | void function(SocketTimeout timeout) throws IOException { _headersRead = false; _aborted = false; try { readHeaders(); } finally { _headersRead = true; } if (_aborted) throw new IOException(STR); if (timeout != null) { timeout.resetTimer(); if (_fetchInactivityTimeout > 0) timeout.setInactivityTimeout(_fetchInactivityTimeout); else timeout.setInactivityTimeout(INACTIVITY_TIMEOUT); } if (_proxy != null && !_shouldProxy) { if (_fetchInactivityTimeout > 0) _proxy.setSoTimeout(_fetchInactivityTimeout); else _proxy.setSoTimeout(INACTIVITY_TIMEOUT); } if (_redirectLocation != null) { if (_redirectLocation.startsWith(STR/STRhttp: else _actualURL = STRProxy auth response from non-proxySTRProxy requires authenticationSTRProxy authentication failedSTRAdding authSTRToo many redirects: to STRRedirecting to STRHeaders read completely, reading STRHTTP response size STR violates minimum of STR bytesSTRHTTP response size STR violates maximum of STR bytesSTREepGet DecompressorSTRBytes transferred STR violates maximum of STR bytesSTRTimed out reading the HTTP dataSTRDone transferring STR (ok? STR)STRAttempt failed: STRAttempt failed: STRBytes transferred STR violates minimum of STR bytesSTRDisconnection on attempt STR after " + _bytesTransferred); } } | /**
* single fetch
* @param timeout may be null
*/ | single fetch | doFetch | {
"repo_name": "NoYouShutup/CryptMeme",
"path": "CryptMeme/core/java/src/net/i2p/util/EepGet.java",
"license": "mit",
"size": 70298
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,079,164 |
@Override
protected void setAttributes()
{
attributes.put(ACTIVE_PROJECT_ATTR, PortalUIPlugin.getActiveProject());
} | void function() { attributes.put(ACTIVE_PROJECT_ATTR, PortalUIPlugin.getActiveProject()); } | /**
* Set the attributes for this dialog.<br>
* By default, the active project is set.
*/ | Set the attributes for this dialog. By default, the active project is set | setAttributes | {
"repo_name": "HossainKhademian/Studio3",
"path": "plugins/com.aptana.portal.ui/src/com/aptana/portal/ui/dispatch/configurationProcessors/installer/JavaScriptImporterOptionsDialog.java",
"license": "gpl-3.0",
"size": 12596
} | [
"com.aptana.portal.ui.PortalUIPlugin"
] | import com.aptana.portal.ui.PortalUIPlugin; | import com.aptana.portal.ui.*; | [
"com.aptana.portal"
] | com.aptana.portal; | 837,574 |
public static void extractIDocSegmentIntoSegment(IDocSegment idocSegment, Segment segment) {
if (segment == null || idocSegment == null) {
LOG.warn("IDoc Document '" + idocSegment + "' not extracted to segment '" + segment + "'");
return;
}
// Fill segment fields
Iterator<String> it = segment.keySet().iterator();
while (it.hasNext()) {
String fieldName = it.next();
try {
Object value = idocSegment.getValue(fieldName);
setValue(segment, fieldName, value);
} catch (Exception e) {
LOG.warn("Failed to extract value from field '" + fieldName + "' from IDoc segment to segment");
}
}
// Fill child segments
SegmentChildren segmentChildren = ((SegmentImpl) segment).getSegmentChildren();
for (String segmentType : segmentChildren.getTypes()) {
for (IDocSegment childIDocSegment : idocSegment.getChildren(segmentType)) {
Segment childSegment = segmentChildren.get(segmentType).add();
extractIDocSegmentIntoSegment(childIDocSegment, childSegment);
}
}
}
| static void function(IDocSegment idocSegment, Segment segment) { if (segment == null idocSegment == null) { LOG.warn(STR + idocSegment + STR + segment + "'"); return; } Iterator<String> it = segment.keySet().iterator(); while (it.hasNext()) { String fieldName = it.next(); try { Object value = idocSegment.getValue(fieldName); setValue(segment, fieldName, value); } catch (Exception e) { LOG.warn(STR + fieldName + STR); } } SegmentChildren segmentChildren = ((SegmentImpl) segment).getSegmentChildren(); for (String segmentType : segmentChildren.getTypes()) { for (IDocSegment childIDocSegment : idocSegment.getChildren(segmentType)) { Segment childSegment = segmentChildren.get(segmentType).add(); extractIDocSegmentIntoSegment(childIDocSegment, childSegment); } } } | /**
* Extract values from <code>idocSegment</code> to <code>segment</code>.
*
* @param idocSegment
* - the IDoc segment containing the values.
* @param segment
* - the segment to fill.
*/ | Extract values from <code>idocSegment</code> to <code>segment</code> | extractIDocSegmentIntoSegment | {
"repo_name": "DaemonSu/fuse-master",
"path": "components/camel-sap/org.fusesource.camel.component.sap/src/org/fusesource/camel/component/sap/util/IDocUtil.java",
"license": "apache-2.0",
"size": 58577
} | [
"com.sap.conn.idoc.IDocSegment",
"java.util.Iterator",
"org.fusesource.camel.component.sap.model.idoc.Segment",
"org.fusesource.camel.component.sap.model.idoc.SegmentChildren",
"org.fusesource.camel.component.sap.model.idoc.impl.SegmentImpl"
] | import com.sap.conn.idoc.IDocSegment; import java.util.Iterator; import org.fusesource.camel.component.sap.model.idoc.Segment; import org.fusesource.camel.component.sap.model.idoc.SegmentChildren; import org.fusesource.camel.component.sap.model.idoc.impl.SegmentImpl; | import com.sap.conn.idoc.*; import java.util.*; import org.fusesource.camel.component.sap.model.idoc.*; import org.fusesource.camel.component.sap.model.idoc.impl.*; | [
"com.sap.conn",
"java.util",
"org.fusesource.camel"
] | com.sap.conn; java.util; org.fusesource.camel; | 2,456,715 |
protected boolean isStringType(Object o) {
boolean result = (o instanceof String);
if (o instanceof JsonElement) {
JsonElement json = (JsonElement) o;
if (json.isJsonPrimitive()) {
JsonPrimitive primitive = json.getAsJsonPrimitive();
result = primitive.isString();
}
}
return result;
} | boolean function(Object o) { boolean result = (o instanceof String); if (o instanceof JsonElement) { JsonElement json = (JsonElement) o; if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); result = primitive.isString(); } } return result; } | /**
* Validates if the object represents a string value.
*
* @param o
* @return
*/ | Validates if the object represents a string value | isStringType | {
"repo_name": "daemun/azure-mobile-services",
"path": "sdk/android/src/sdk/src/main/java/com/microsoft/windowsazure/mobileservices/table/MobileServiceTableBase.java",
"license": "apache-2.0",
"size": 34721
} | [
"com.google.gson.JsonElement",
"com.google.gson.JsonPrimitive"
] | import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; | import com.google.gson.*; | [
"com.google.gson"
] | com.google.gson; | 1,835,894 |
public static void executesFieldOutjecting(Field[] fields,
Provider provider, Object target, Definition definition)
throws IllegalArgumentException, IllegalAccessException {
if (fields != null) {
for (int i = 0; i < fields.length; i++) {
Object outjectObj = null;
Definition defField = definition.getMemberDefinition(fields[i]);
if (defField != null
&& defField.isAnnotationPresent(Outject.class)) {
Outject outject = defField.getAnnotation(Outject.class);
fields[i].setAccessible(true);
outjectObj = fields[i].get(target);
if (ReflectUtils.isCast(Builder.class, target)) {
Builder builder = (Builder) target;
if (builder.getOutjectValue(fields[i]) != null)
outjectObj = builder.getOutjectValue(fields[i]);
}
InOutExecutor.setOutjectedDependency(outject, outjectObj,
provider, fields[i].getClass());
}
else
continue;
}
}
}
| static void function(Field[] fields, Provider provider, Object target, Definition definition) throws IllegalArgumentException, IllegalAccessException { if (fields != null) { for (int i = 0; i < fields.length; i++) { Object outjectObj = null; Definition defField = definition.getMemberDefinition(fields[i]); if (defField != null && defField.isAnnotationPresent(Outject.class)) { Outject outject = defField.getAnnotation(Outject.class); fields[i].setAccessible(true); outjectObj = fields[i].get(target); if (ReflectUtils.isCast(Builder.class, target)) { Builder builder = (Builder) target; if (builder.getOutjectValue(fields[i]) != null) outjectObj = builder.getOutjectValue(fields[i]); } InOutExecutor.setOutjectedDependency(outject, outjectObj, provider, fields[i].getClass()); } else continue; } } } | /**
* Executes field outject.
*
* @param fields
* the fields
* @param provider
* the provider
* @param target
* the target
* @param definition
* the definition
* @throws IllegalArgumentException
* the illegal argument exception
* @throws IllegalAccessException
* the illegal access exception
*/ | Executes field outject | executesFieldOutjecting | {
"repo_name": "haint/jgentle",
"path": "src/org/jgentleframework/core/factory/InOutExecutor.java",
"license": "apache-2.0",
"size": 14972
} | [
"java.lang.reflect.Field",
"org.jgentleframework.configure.annotation.Outject",
"org.jgentleframework.context.beans.Builder",
"org.jgentleframework.context.injecting.Provider",
"org.jgentleframework.reflection.metadata.Definition",
"org.jgentleframework.utils.ReflectUtils"
] | import java.lang.reflect.Field; import org.jgentleframework.configure.annotation.Outject; import org.jgentleframework.context.beans.Builder; import org.jgentleframework.context.injecting.Provider; import org.jgentleframework.reflection.metadata.Definition; import org.jgentleframework.utils.ReflectUtils; | import java.lang.reflect.*; import org.jgentleframework.configure.annotation.*; import org.jgentleframework.context.beans.*; import org.jgentleframework.context.injecting.*; import org.jgentleframework.reflection.metadata.*; import org.jgentleframework.utils.*; | [
"java.lang",
"org.jgentleframework.configure",
"org.jgentleframework.context",
"org.jgentleframework.reflection",
"org.jgentleframework.utils"
] | java.lang; org.jgentleframework.configure; org.jgentleframework.context; org.jgentleframework.reflection; org.jgentleframework.utils; | 1,256,192 |
public FieldFactoryContext setFieldFilters(Map<String, SerializablePredicate<?>> fieldFilters) {
this.fieldFilters = fieldFilters;
return this;
} | FieldFactoryContext function(Map<String, SerializablePredicate<?>> fieldFilters) { this.fieldFilters = fieldFilters; return this; } | /**
* Sets the field filters to use during field construction
*
* @param fieldFilters the field filters
* @return
*/ | Sets the field filters to use during field construction | setFieldFilters | {
"repo_name": "opencirclesolutions/dynamo",
"path": "dynamo-frontend/src/main/java/com/ocs/dynamo/domain/model/FieldFactoryContext.java",
"license": "apache-2.0",
"size": 4854
} | [
"com.vaadin.flow.function.SerializablePredicate",
"java.util.Map"
] | import com.vaadin.flow.function.SerializablePredicate; import java.util.Map; | import com.vaadin.flow.function.*; import java.util.*; | [
"com.vaadin.flow",
"java.util"
] | com.vaadin.flow; java.util; | 592,591 |
protected void computeRect(Raster[] sources,
WritableRaster dest,
Rectangle destRect) {
// Retrieve format tags.
RasterFormatTag[] formatTags = getFormatTags();
Rectangle srcRect = mapDestRect(destRect, 0);
RasterAccessor dst = new RasterAccessor(dest, destRect,
formatTags[1], getColorModel());
RasterAccessor src = new RasterAccessor(sources[0], srcRect,
formatTags[0],
getSource(0).getColorModel());
switch (dst.getDataType()) {
case DataBuffer.TYPE_BYTE:
computeRectByte(src, dst);
break;
case DataBuffer.TYPE_USHORT:
case DataBuffer.TYPE_SHORT:
computeRectShort(src, dst);
break;
case DataBuffer.TYPE_INT:
computeRectInt(src, dst);
break;
}
dst.copyDataToRaster();
}
| void function(Raster[] sources, WritableRaster dest, Rectangle destRect) { RasterFormatTag[] formatTags = getFormatTags(); Rectangle srcRect = mapDestRect(destRect, 0); RasterAccessor dst = new RasterAccessor(dest, destRect, formatTags[1], getColorModel()); RasterAccessor src = new RasterAccessor(sources[0], srcRect, formatTags[0], getSource(0).getColorModel()); switch (dst.getDataType()) { case DataBuffer.TYPE_BYTE: computeRectByte(src, dst); break; case DataBuffer.TYPE_USHORT: case DataBuffer.TYPE_SHORT: computeRectShort(src, dst); break; case DataBuffer.TYPE_INT: computeRectInt(src, dst); break; } dst.copyDataToRaster(); } | /**
* Logically "ors" a constant with the pixel values within a specified
* rectangle.
*
* @param sources Cobbled sources, guaranteed to provide all the
* source data necessary for computing the rectangle.
* @param dest The tile containing the rectangle to be computed.
* @param destRect The rectangle within the tile to be computed.
*/ | Logically "ors" a constant with the pixel values within a specified rectangle | computeRect | {
"repo_name": "RoProducts/rastertheque",
"path": "JAILibrary/src/com/sun/media/jai/opimage/OrConstOpImage.java",
"license": "gpl-2.0",
"size": 9125
} | [
"java.awt.Rectangle",
"java.awt.image.DataBuffer",
"java.awt.image.Raster",
"java.awt.image.WritableRaster",
"javax.media.jai.RasterAccessor",
"javax.media.jai.RasterFormatTag"
] | import java.awt.Rectangle; import java.awt.image.DataBuffer; import java.awt.image.Raster; import java.awt.image.WritableRaster; import javax.media.jai.RasterAccessor; import javax.media.jai.RasterFormatTag; | import java.awt.*; import java.awt.image.*; import javax.media.jai.*; | [
"java.awt",
"javax.media"
] | java.awt; javax.media; | 1,544,736 |
@Test
public void testIsNumericWithNumeric() {
Assert.assertTrue(Strings.isNumeric("0987654321"));
}
| void function() { Assert.assertTrue(Strings.isNumeric(STR)); } | /**
* Verify isNumeric works with a numeric string.
*/ | Verify isNumeric works with a numeric string | testIsNumericWithNumeric | {
"repo_name": "TroyHisted/relib",
"path": "src/test/java/org/relib/util/StringsTest.java",
"license": "apache-2.0",
"size": 7086
} | [
"org.junit.Assert"
] | import org.junit.Assert; | import org.junit.*; | [
"org.junit"
] | org.junit; | 1,488,694 |
// WARNING! This method shouldn't call in UI Thread, write loader in your own class
@WorkerThread
public void addLastEmote(String id, Context context) {
if (lastEmotes == null) {
lastEmotes = getLastEmotes(context);
lastEmotes = lastEmotes == null ? new ArrayList<>() : lastEmotes;
}
if (lastEmotes.contains(id)) {
lastEmotes.remove(id);
}
lastEmotes.add(0, id);
} | void function(String id, Context context) { if (lastEmotes == null) { lastEmotes = getLastEmotes(context); lastEmotes = lastEmotes == null ? new ArrayList<>() : lastEmotes; } if (lastEmotes.contains(id)) { lastEmotes.remove(id); } lastEmotes.add(0, id); } | /**
* Methods to store last emotes order
*/ | Methods to store last emotes order | addLastEmote | {
"repo_name": "DimaStoyanov/Twitch-Chat",
"path": "app/src/main/java/ru/ifmo/android_2016/irc/client/Channel.java",
"license": "mit",
"size": 8723
} | [
"android.content.Context",
"java.util.ArrayList"
] | import android.content.Context; import java.util.ArrayList; | import android.content.*; import java.util.*; | [
"android.content",
"java.util"
] | android.content; java.util; | 2,267,961 |
public void test943985() {
Millisecond ms = new Millisecond(new java.util.Date(4));
assertEquals(ms.getFirstMillisecond(), ms.getMiddleMillisecond());
assertEquals(ms.getMiddleMillisecond(), ms.getLastMillisecond());
ms = new Millisecond(new java.util.Date(5));
assertEquals(ms.getFirstMillisecond(), ms.getMiddleMillisecond());
assertEquals(ms.getMiddleMillisecond(), ms.getLastMillisecond());
} | void function() { Millisecond ms = new Millisecond(new java.util.Date(4)); assertEquals(ms.getFirstMillisecond(), ms.getMiddleMillisecond()); assertEquals(ms.getMiddleMillisecond(), ms.getLastMillisecond()); ms = new Millisecond(new java.util.Date(5)); assertEquals(ms.getFirstMillisecond(), ms.getMiddleMillisecond()); assertEquals(ms.getMiddleMillisecond(), ms.getLastMillisecond()); } | /**
* A test for bug report 943985 - the calculation for the middle
* millisecond is incorrect for odd milliseconds.
*/ | A test for bug report 943985 - the calculation for the middle millisecond is incorrect for odd milliseconds | test943985 | {
"repo_name": "raedle/univis",
"path": "lib/jfreechart-1.0.1/src/org/jfree/data/time/junit/MillisecondTests.java",
"license": "lgpl-2.1",
"size": 7229
} | [
"java.util.Date",
"org.jfree.data.time.Millisecond"
] | import java.util.Date; import org.jfree.data.time.Millisecond; | import java.util.*; import org.jfree.data.time.*; | [
"java.util",
"org.jfree.data"
] | java.util; org.jfree.data; | 2,589,039 |
public QueryEntity setNotNullFields(@Nullable Set<String> notNullFields) {
this._notNullFields = notNullFields;
return this;
} | QueryEntity function(@Nullable Set<String> notNullFields) { this._notNullFields = notNullFields; return this; } | /**
* Sets names of fields that must checked for null.
*
* @param notNullFields Set of names of fields that must have non-null values.
* @return {@code this} for chaining.
*/ | Sets names of fields that must checked for null | setNotNullFields | {
"repo_name": "andrey-kuznetsov/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/cache/QueryEntity.java",
"license": "apache-2.0",
"size": 31017
} | [
"java.util.Set",
"org.jetbrains.annotations.Nullable"
] | import java.util.Set; import org.jetbrains.annotations.Nullable; | import java.util.*; import org.jetbrains.annotations.*; | [
"java.util",
"org.jetbrains.annotations"
] | java.util; org.jetbrains.annotations; | 1,851,607 |
void joinGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface); | void joinGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface); | /**
* Joins the specified multicast group at the specified interface.
*/ | Joins the specified multicast group at the specified interface | joinGroup | {
"repo_name": "aperepel/netty",
"path": "src/main/java/org/jboss/netty/channel/socket/DatagramChannel.java",
"license": "apache-2.0",
"size": 1923
} | [
"java.net.InetSocketAddress",
"java.net.NetworkInterface"
] | import java.net.InetSocketAddress; import java.net.NetworkInterface; | import java.net.*; | [
"java.net"
] | java.net; | 23,931 |
public boolean isErrorSet(Model model, RedirectAttributes redirectAttributes) {
boolean result = false;
if (model!=null) {
result = model.asMap().containsValue(VAL_NOTIFICATION_SEVERITY_ERROR);
}
if (redirectAttributes!=null) {
result |= redirectAttributes.getFlashAttributes().containsValue(VAL_NOTIFICATION_SEVERITY_ERROR);
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////// | boolean function(Model model, RedirectAttributes redirectAttributes) { boolean result = false; if (model!=null) { result = model.asMap().containsValue(VAL_NOTIFICATION_SEVERITY_ERROR); } if (redirectAttributes!=null) { result = redirectAttributes.getFlashAttributes().containsValue(VAL_NOTIFICATION_SEVERITY_ERROR); } return result; } | /**
* Return true if error() has been called before
* @param model can be null
* @param redirectAttributes can be null
* @return
*/ | Return true if error() has been called before | isErrorSet | {
"repo_name": "xtianus/yadaframework",
"path": "YadaWeb/src/main/java/net/yadaframework/components/YadaNotify.java",
"license": "mit",
"size": 20029
} | [
"org.springframework.ui.Model",
"org.springframework.web.servlet.mvc.support.RedirectAttributes"
] | import org.springframework.ui.Model; import org.springframework.web.servlet.mvc.support.RedirectAttributes; | import org.springframework.ui.*; import org.springframework.web.servlet.mvc.support.*; | [
"org.springframework.ui",
"org.springframework.web"
] | org.springframework.ui; org.springframework.web; | 2,385,299 |
private static boolean isAnalyzableObjectDefinePropertiesDefinition(Node n) {
// TODO(blickly): Move this code to CodingConvention so that
// it's possible to define alternate ways of defining properties.
return NodeUtil.isObjectDefinePropertiesDefinition(n)
&& n.getParent().isExprResult()
&& n.getFirstChild().getNext().isQualifiedName()
&& n.getLastChild().isObjectLit();
} | static boolean function(Node n) { return NodeUtil.isObjectDefinePropertiesDefinition(n) && n.getParent().isExprResult() && n.getFirstChild().getNext().isQualifiedName() && n.getLastChild().isObjectLit(); } | /**
* Check if {@code n} is an Object.defineProperties definition
* that is static enough for this pass to understand and remove.
*/ | Check if n is an Object.defineProperties definition that is static enough for this pass to understand and remove | isAnalyzableObjectDefinePropertiesDefinition | {
"repo_name": "LorenzoDV/closure-compiler",
"path": "src/com/google/javascript/jscomp/NameAnalyzer.java",
"license": "apache-2.0",
"size": 67296
} | [
"com.google.javascript.rhino.Node"
] | import com.google.javascript.rhino.Node; | import com.google.javascript.rhino.*; | [
"com.google.javascript"
] | com.google.javascript; | 2,621,165 |
public static long randomSeed() {
long seed;
try {
seed= java.security.SecureRandom.getInstance("SHA1PRNG").nextLong(); //findbugs DMI_RANDOM_USED_ONLY_ONCE suggests this.
} catch ( NoSuchAlgorithmException ex ) {
seed= 0;
}
random= new Random(seed);
return seed;
} | static long function() { long seed; try { seed= java.security.SecureRandom.getInstance(STR).nextLong(); } catch ( NoSuchAlgorithmException ex ) { seed= 0; } random= new Random(seed); return seed; } | /**
* restart the random sequence used by randu and randn. Note if there
* if there are multiple threads using random functions, this becomes
* unpredictable.
* @return the seed is returned.
*/ | restart the random sequence used by randu and randn. Note if there if there are multiple threads using random functions, this becomes unpredictable | randomSeed | {
"repo_name": "autoplot/app",
"path": "QDataSet/src/org/das2/qds/ops/Ops.java",
"license": "gpl-2.0",
"size": 492716
} | [
"java.security.NoSuchAlgorithmException",
"java.util.Random"
] | import java.security.NoSuchAlgorithmException; import java.util.Random; | import java.security.*; import java.util.*; | [
"java.security",
"java.util"
] | java.security; java.util; | 524,942 |
public void accept(final MethodVisitor mv) {
mv.visitParameter(name, access);
} | void function(final MethodVisitor mv) { mv.visitParameter(name, access); } | /**
* Makes the given visitor visit this parameter declaration.
*
* @param mv
* a method visitor.
*/ | Makes the given visitor visit this parameter declaration | accept | {
"repo_name": "gameduell/eclipselink.runtime",
"path": "plugins/org.eclipse.persistence.asm/src/org/eclipse/persistence/internal/libraries/asm/tree/ParameterNode.java",
"license": "epl-1.0",
"size": 2986
} | [
"org.eclipse.persistence.internal.libraries.asm.MethodVisitor"
] | import org.eclipse.persistence.internal.libraries.asm.MethodVisitor; | import org.eclipse.persistence.internal.libraries.asm.*; | [
"org.eclipse.persistence"
] | org.eclipse.persistence; | 2,666,067 |
private void printTxInfoResult(Map<ClusterNode, VisorTxTaskResult> res) {
String lb = null;
Map<Integer, String> usedCaches = new HashMap<>();
Map<Integer, String> usedCacheGroups = new HashMap<>();
VisorTxInfo firstInfo = null;
TxVerboseInfo firstVerboseInfo = null;
Set<TransactionState> states = new HashSet<>();
for (Map.Entry<ClusterNode, VisorTxTaskResult> entry : res.entrySet()) {
for (VisorTxInfo info : entry.getValue().getInfos()) {
assert info.getTxVerboseInfo() != null;
if (lb == null)
lb = info.getLabel();
if (firstInfo == null) {
firstInfo = info;
firstVerboseInfo = info.getTxVerboseInfo();
}
usedCaches.putAll(info.getTxVerboseInfo().usedCaches());
usedCacheGroups.putAll(info.getTxVerboseInfo().usedCacheGroups());
states.add(info.getState());
}
}
String indent = "";
logger.info("");
logger.info(indent + "Transaction detailed info:");
printTransactionDetailedInfo(
res, usedCaches, usedCacheGroups, firstInfo, firstVerboseInfo, states, indent + DOUBLE_INDENT);
} | void function(Map<ClusterNode, VisorTxTaskResult> res) { String lb = null; Map<Integer, String> usedCaches = new HashMap<>(); Map<Integer, String> usedCacheGroups = new HashMap<>(); VisorTxInfo firstInfo = null; TxVerboseInfo firstVerboseInfo = null; Set<TransactionState> states = new HashSet<>(); for (Map.Entry<ClusterNode, VisorTxTaskResult> entry : res.entrySet()) { for (VisorTxInfo info : entry.getValue().getInfos()) { assert info.getTxVerboseInfo() != null; if (lb == null) lb = info.getLabel(); if (firstInfo == null) { firstInfo = info; firstVerboseInfo = info.getTxVerboseInfo(); } usedCaches.putAll(info.getTxVerboseInfo().usedCaches()); usedCacheGroups.putAll(info.getTxVerboseInfo().usedCacheGroups()); states.add(info.getState()); } } String indent = STRSTRTransaction detailed info:"); printTransactionDetailedInfo( res, usedCaches, usedCacheGroups, firstInfo, firstVerboseInfo, states, indent + DOUBLE_INDENT); } | /**
* Prints result of --tx --info command to output.
*
* @param res Response.
*/ | Prints result of --tx --info command to output | printTxInfoResult | {
"repo_name": "ascherbakoff/ignite",
"path": "modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/TxCommands.java",
"license": "apache-2.0",
"size": 20366
} | [
"java.util.HashMap",
"java.util.HashSet",
"java.util.Map",
"java.util.Set",
"org.apache.ignite.cluster.ClusterNode",
"org.apache.ignite.internal.visor.tx.TxVerboseInfo",
"org.apache.ignite.internal.visor.tx.VisorTxInfo",
"org.apache.ignite.internal.visor.tx.VisorTxTaskResult",
"org.apache.ignite.transactions.TransactionState"
] | import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.internal.visor.tx.TxVerboseInfo; import org.apache.ignite.internal.visor.tx.VisorTxInfo; import org.apache.ignite.internal.visor.tx.VisorTxTaskResult; import org.apache.ignite.transactions.TransactionState; | import java.util.*; import org.apache.ignite.cluster.*; import org.apache.ignite.internal.visor.tx.*; import org.apache.ignite.transactions.*; | [
"java.util",
"org.apache.ignite"
] | java.util; org.apache.ignite; | 1,584,591 |
RequestSpecification queryParam(String parameterName, List<String> parameterValues);
/**
* Specify the form parameters that'll be sent with the request. Note that this method is the same as {@link #parameters(String, String...)} | RequestSpecification queryParam(String parameterName, List<String> parameterValues); /** * Specify the form parameters that'll be sent with the request. Note that this method is the same as {@link #parameters(String, String...)} | /**
* A slightly shorter version of {@link #queryParameter(String, java.util.List)}.
*
* @see #queryParam(String, java.util.List)
* @param parameterName The parameter key
* @param parameterValues The parameter values
* @return The request specification
*/ | A slightly shorter version of <code>#queryParameter(String, java.util.List)</code> | queryParam | {
"repo_name": "VoldemarLeGrand/rest-assured",
"path": "rest-assured/src/main/java/com/jayway/restassured/specification/RequestSpecification.java",
"license": "apache-2.0",
"size": 40725
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,021,159 |
public PermissionDTO getDTO() {
final PermissionDTO p = new PermissionDTO();
p.setId(id);
if(group != null)
p.setGroup(group.getDTO());
if(user != null)
p.setUser(user.getDTO());
p.setRead(read);
p.setWrite(write);
p.setModifyACL(modifyACL);
return p;
}
| PermissionDTO function() { final PermissionDTO p = new PermissionDTO(); p.setId(id); if(group != null) p.setGroup(group.getDTO()); if(user != null) p.setUser(user.getDTO()); p.setRead(read); p.setWrite(write); p.setModifyACL(modifyACL); return p; } | /**
* Return a new Data Transfer Object for this object.
*
* @return a new DTO with the same contents as this object
*/ | Return a new Data Transfer Object for this object | getDTO | {
"repo_name": "andrewbissada/gss",
"path": "src/org/gss_project/gss/server/domain/Permission.java",
"license": "gpl-3.0",
"size": 6149
} | [
"org.gss_project.gss.common.dto.PermissionDTO"
] | import org.gss_project.gss.common.dto.PermissionDTO; | import org.gss_project.gss.common.dto.*; | [
"org.gss_project.gss"
] | org.gss_project.gss; | 2,348,538 |
@Override
protected void initialize() {
super.initialize();
m_BackgroundColor = getBackground();
m_Modified = false;
m_ImageProperties = new Report();
m_AdditionalProperties = null;
m_DependentDialogs = new ArrayList<>();
m_DependentFlows = new ArrayList<>();
m_Scale = -1;
m_FileChooser = new ImageFileChooser();
} | void function() { super.initialize(); m_BackgroundColor = getBackground(); m_Modified = false; m_ImageProperties = new Report(); m_AdditionalProperties = null; m_DependentDialogs = new ArrayList<>(); m_DependentFlows = new ArrayList<>(); m_Scale = -1; m_FileChooser = new ImageFileChooser(); } | /**
* Initializes the members.
*/ | Initializes the members | initialize | {
"repo_name": "automenta/adams-core",
"path": "src/main/java/adams/gui/visualization/image/ImagePanel.java",
"license": "gpl-3.0",
"size": 45877
} | [
"java.util.ArrayList"
] | import java.util.ArrayList; | import java.util.*; | [
"java.util"
] | java.util; | 985,993 |
protected Dimension getMinimumSizeFor(CreateRequest request) {
return IFigure.MIN_DIMENSION;
} | Dimension function(CreateRequest request) { return IFigure.MIN_DIMENSION; } | /**
* Determines the <em>minimum</em> size for CreateRequest's size on drop. It
* is called from
* {@link #enforceConstraintsForSizeOnDropCreate(CreateRequest)} during
* creation. By default, a small <code>Dimension</code> is returned.
*
* @param request
* the request.
* @return the minimum size
* @since 3.7
*/ | Determines the minimum size for CreateRequest's size on drop. It is called from <code>#enforceConstraintsForSizeOnDropCreate(CreateRequest)</code> during creation. By default, a small <code>Dimension</code> is returned | getMinimumSizeFor | {
"repo_name": "archimatetool/archi",
"path": "org.eclipse.gef/src/org/eclipse/gef/tools/CreationTool.java",
"license": "mit",
"size": 13626
} | [
"org.eclipse.draw2d.IFigure",
"org.eclipse.draw2d.geometry.Dimension",
"org.eclipse.gef.requests.CreateRequest"
] | import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.gef.requests.CreateRequest; | import org.eclipse.draw2d.*; import org.eclipse.draw2d.geometry.*; import org.eclipse.gef.requests.*; | [
"org.eclipse.draw2d",
"org.eclipse.gef"
] | org.eclipse.draw2d; org.eclipse.gef; | 1,487,368 |
@Test
public void testWithNoOutliers() throws Exception {
DataNodePeerMetrics peerMetrics = new DataNodePeerMetrics(
"PeerMetrics-For-Test", WINDOW_INTERVAL_SECONDS,
ROLLING_AVERAGE_WINDOWS);
injectFastNodesSamples(peerMetrics);
// Trigger a snapshot.
peerMetrics.dumpSendPacketDownstreamAvgInfoAsJson();
// Ensure that we get back the outlier.
assertTrue(peerMetrics.getOutliers().isEmpty());
} | void function() throws Exception { DataNodePeerMetrics peerMetrics = new DataNodePeerMetrics( STR, WINDOW_INTERVAL_SECONDS, ROLLING_AVERAGE_WINDOWS); injectFastNodesSamples(peerMetrics); peerMetrics.dumpSendPacketDownstreamAvgInfoAsJson(); assertTrue(peerMetrics.getOutliers().isEmpty()); } | /**
* Test that when there are no outliers, we get back nothing.
*/ | Test that when there are no outliers, we get back nothing | testWithNoOutliers | {
"repo_name": "WIgor/hadoop",
"path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/metrics/TestDataNodeOutlierDetectionViaMetrics.java",
"license": "apache-2.0",
"size": 4604
} | [
"org.junit.Assert"
] | import org.junit.Assert; | import org.junit.*; | [
"org.junit"
] | org.junit; | 2,571,293 |
public static <TNode> Result<TNode> run(ITargetSelector selector, Iterable<ElementNode<TNode>> nodes) {
List<ElementNode<TNode>> candidates = new ArrayList<ElementNode<TNode>>();
ElementNode<TNode> exactMatch = TargetSelector.runSelector(selector, nodes, candidates);
return new Result<TNode>(exactMatch, candidates);
} | static <TNode> Result<TNode> function(ITargetSelector selector, Iterable<ElementNode<TNode>> nodes) { List<ElementNode<TNode>> candidates = new ArrayList<ElementNode<TNode>>(); ElementNode<TNode> exactMatch = TargetSelector.runSelector(selector, nodes, candidates); return new Result<TNode>(exactMatch, candidates); } | /**
* Run query on supplied target nodes
*
* @param selector Target selector
* @param nodes Node collection to enumerate
* @param <TNode> Node type
* @return query result
*/ | Run query on supplied target nodes | run | {
"repo_name": "SpongePowered/Mixin",
"path": "src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java",
"license": "mit",
"size": 22347
} | [
"java.util.ArrayList",
"java.util.List"
] | import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 608,064 |
public ListBucketResponse listBucket(String bucket, String prefix, String marker,
Integer maxKeys, String delimiter, Map headers) throws IOException {
Map pathArgs = Utils.paramsForListOptions(prefix, marker, maxKeys, delimiter);
return new ListBucketResponse(makeRequest("GET", bucket, "", pathArgs, headers));
} | ListBucketResponse function(String bucket, String prefix, String marker, Integer maxKeys, String delimiter, Map headers) throws IOException { Map pathArgs = Utils.paramsForListOptions(prefix, marker, maxKeys, delimiter); return new ListBucketResponse(makeRequest("GET", bucket, "", pathArgs, headers)); } | /**
* Lists the contents of a bucket.
*
* @param bucket The name of the bucket to list.
* @param prefix All returned keys will start with this string (can be null).
* @param marker All returned keys will be lexographically greater than this string (can be null).
* @param maxKeys The maximum number of keys to return (can be null).
* @param delimiter Keys that contain a string between the prefix and the first occurrence of the delimiter will
* be rolled up into a single element.
* @param headers A Map of String to List of Strings representing the http headers to pass (can be null).
*/ | Lists the contents of a bucket | listBucket | {
"repo_name": "jamezp/wildfly-core",
"path": "host-controller/src/main/java/org/jboss/as/host/controller/discovery/S3Util.java",
"license": "lgpl-2.1",
"size": 71207
} | [
"java.io.IOException",
"java.util.Map"
] | import java.io.IOException; import java.util.Map; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 130,384 |
public ListAdapter getListAdapter() {
return mAdapter;
}
/**
* Provides the Adapter for the ListView handled by this
* {@link GDListActivity} | ListAdapter function() { return mAdapter; } /** * Provides the Adapter for the ListView handled by this * {@link GDListActivity} | /**
* Get the ListAdapter associated with this activity's ListView.
*
* @return The ListAdapter currently associated to the underlying ListView
*/ | Get the ListAdapter associated with this activity's ListView | getListAdapter | {
"repo_name": "paristote/mobile-android-studio",
"path": "greenDroid/src/main/java/greendroid/app/GDListActivity.java",
"license": "lgpl-3.0",
"size": 6318
} | [
"android.widget.ListAdapter",
"android.widget.ListView"
] | import android.widget.ListAdapter; import android.widget.ListView; | import android.widget.*; | [
"android.widget"
] | android.widget; | 1,261,201 |
public static double midnightDateToJulianDate(Calendar calendar) {
return dateToJulianDate(truncateToMidnight(calendar));
} | static double function(Calendar calendar) { return dateToJulianDate(truncateToMidnight(calendar)); } | /**
* Returns the midnight julian date from the calendar object.
*/ | Returns the midnight julian date from the calendar object | midnightDateToJulianDate | {
"repo_name": "watou/openhab",
"path": "bundles/binding/org.openhab.binding.astro/src/main/java/org/openhab/binding/astro/internal/util/DateTimeUtils.java",
"license": "epl-1.0",
"size": 5273
} | [
"java.util.Calendar"
] | import java.util.Calendar; | import java.util.*; | [
"java.util"
] | java.util; | 1,466,962 |
private void defaultDialogSize( JFrame owner ) {
this.setBounds( owner.getX() + owner.getWidth(),
owner.getY(),
MQTTFrame.FRAME_WIDTH,
MQTTFrame.FRAME_HEIGHT );
}
| void function( JFrame owner ) { this.setBounds( owner.getX() + owner.getWidth(), owner.getY(), MQTTFrame.FRAME_WIDTH, MQTTFrame.FRAME_HEIGHT ); } | /**
* Size the window and positioning it relative to the
* parent frame.
*/ | Size the window and positioning it relative to the parent frame | defaultDialogSize | {
"repo_name": "gulliverrr/hestia-engine-dev",
"path": "src/opt/boilercontrol/libs/org.eclipse.paho.sample.utility/src/main/java/org/eclipse/paho/sample/utility/MQTTHist.java",
"license": "gpl-3.0",
"size": 6559
} | [
"javax.swing.JFrame"
] | import javax.swing.JFrame; | import javax.swing.*; | [
"javax.swing"
] | javax.swing; | 1,515,193 |
@Override
public List<String> getCfTypeNames() {
List<String> cfTypeNames = new ArrayList<>();
for (CfType cfType : getCfTypes()) {
cfTypeNames.add(cfType.getName());
}
return cfTypeNames;
} | List<String> function() { List<String> cfTypeNames = new ArrayList<>(); for (CfType cfType : getCfTypes()) { cfTypeNames.add(cfType.getName()); } return cfTypeNames; } | /**
* Retrieves a list of all the names from the persisted CfType objects.
*
* @return A list of CF type names.
*/ | Retrieves a list of all the names from the persisted CfType objects | getCfTypeNames | {
"repo_name": "Unidata/rosetta",
"path": "src/main/java/edu/ucar/unidata/rosetta/service/ResourceManagerImpl.java",
"license": "bsd-3-clause",
"size": 7762
} | [
"edu.ucar.unidata.rosetta.domain.resources.CfType",
"java.util.ArrayList",
"java.util.List"
] | import edu.ucar.unidata.rosetta.domain.resources.CfType; import java.util.ArrayList; import java.util.List; | import edu.ucar.unidata.rosetta.domain.resources.*; import java.util.*; | [
"edu.ucar.unidata",
"java.util"
] | edu.ucar.unidata; java.util; | 622,569 |
public void starting(final Description descr) {
if (getLog() != null) {
final String logIntro = getShortTestMethodName(descr) + " starting...";
getLog().info("------------- " + logIntro + "-------------");
}
} | void function(final Description descr) { if (getLog() != null) { final String logIntro = getShortTestMethodName(descr) + STR; getLog().info(STR + logIntro + STR); } } | /**
* Invoked when a test method is about to start
*/ | Invoked when a test method is about to start | starting | {
"repo_name": "alorchenkov/spring-data-openjpa-example",
"path": "ws-simulator-core/src/test/java/com/cpwr/gdo/simulator/UnitTestBase.java",
"license": "apache-2.0",
"size": 4817
} | [
"org.junit.runner.Description"
] | import org.junit.runner.Description; | import org.junit.runner.*; | [
"org.junit.runner"
] | org.junit.runner; | 2,013,225 |
static void createOptimizationPlan() {
_options = new OptOptions();
int optLevel = Controller.options.INVOCATION_COUNT_OPT_LEVEL;
String[] optCompilerOptions = Controller.getOptCompilerOptions();
_options.setOptLevel(optLevel);
RecompilationStrategy.processCommandLineOptions(_options, optLevel, optLevel, optCompilerOptions);
_optPlan = OptimizationPlanner.createOptimizationPlan(_options);
} | static void createOptimizationPlan() { _options = new OptOptions(); int optLevel = Controller.options.INVOCATION_COUNT_OPT_LEVEL; String[] optCompilerOptions = Controller.getOptCompilerOptions(); _options.setOptLevel(optLevel); RecompilationStrategy.processCommandLineOptions(_options, optLevel, optLevel, optCompilerOptions); _optPlan = OptimizationPlanner.createOptimizationPlan(_options); } | /**
* Create the default set of <optimization plan, options> pairs
* Process optimizing compiler command line options.
*/ | Create the default set of pairs Process optimizing compiler command line options | createOptimizationPlan | {
"repo_name": "ut-osa/laminar",
"path": "jikesrvm-3.0.0/rvm/src/org/jikesrvm/adaptive/recompilation/InvocationCounts.java",
"license": "bsd-3-clause",
"size": 4549
} | [
"org.jikesrvm.adaptive.controller.Controller",
"org.jikesrvm.adaptive.controller.RecompilationStrategy",
"org.jikesrvm.compilers.opt.OptOptions",
"org.jikesrvm.compilers.opt.driver.OptimizationPlanner"
] | import org.jikesrvm.adaptive.controller.Controller; import org.jikesrvm.adaptive.controller.RecompilationStrategy; import org.jikesrvm.compilers.opt.OptOptions; import org.jikesrvm.compilers.opt.driver.OptimizationPlanner; | import org.jikesrvm.adaptive.controller.*; import org.jikesrvm.compilers.opt.*; import org.jikesrvm.compilers.opt.driver.*; | [
"org.jikesrvm.adaptive",
"org.jikesrvm.compilers"
] | org.jikesrvm.adaptive; org.jikesrvm.compilers; | 1,525,590 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.