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
public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String ddosCustomPolicyName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (ddosCustomPolicyName == null) { throw new IllegalArgumentException("Parameter ddosCustomPolicyName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); }
Observable<ServiceResponse<Void>> function(String resourceGroupName, String ddosCustomPolicyName) { if (resourceGroupName == null) { throw new IllegalArgumentException(STR); } if (ddosCustomPolicyName == null) { throw new IllegalArgumentException(STR); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException(STR); }
/** * Deletes the specified DDoS custom policy. * * @param resourceGroupName The name of the resource group. * @param ddosCustomPolicyName The name of the DDoS custom policy. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */
Deletes the specified DDoS custom policy
beginDeleteWithServiceResponseAsync
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/network/mgmt-v2020_03_01/src/main/java/com/microsoft/azure/management/network/v2020_03_01/implementation/DdosCustomPoliciesInner.java", "license": "mit", "size": 38765 }
[ "com.microsoft.rest.ServiceResponse" ]
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.*;
[ "com.microsoft.rest" ]
com.microsoft.rest;
1,310,498
public void removeLabelsFromNode(Map<NodeId, Set<String>> removeLabelsFromNode) throws IOException { if (!nodeLabelsEnabled) { LOG.error(NODE_LABELS_NOT_ENABLED_ERR); throw new IOException(NODE_LABELS_NOT_ENABLED_ERR); } removeLabelsFromNode = normalizeNodeIdToLabels(removeLabelsFromNode); checkRemoveLabelsFromNode(removeLabelsFromNode); internalUpdateLabelsOnNodes(removeLabelsFromNode, NodeLabelUpdateOperation.REMOVE); }
void function(Map<NodeId, Set<String>> removeLabelsFromNode) throws IOException { if (!nodeLabelsEnabled) { LOG.error(NODE_LABELS_NOT_ENABLED_ERR); throw new IOException(NODE_LABELS_NOT_ENABLED_ERR); } removeLabelsFromNode = normalizeNodeIdToLabels(removeLabelsFromNode); checkRemoveLabelsFromNode(removeLabelsFromNode); internalUpdateLabelsOnNodes(removeLabelsFromNode, NodeLabelUpdateOperation.REMOVE); }
/** * remove labels from nodes, labels being removed most be contained by these * nodes * * @param removeLabelsFromNode node {@literal ->} labels map */
remove labels from nodes, labels being removed most be contained by these nodes
removeLabelsFromNode
{ "repo_name": "plusplusjiajia/hadoop", "path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java", "license": "apache-2.0", "size": 35460 }
[ "java.io.IOException", "java.util.Map", "java.util.Set", "org.apache.hadoop.yarn.api.records.NodeId" ]
import java.io.IOException; import java.util.Map; import java.util.Set; import org.apache.hadoop.yarn.api.records.NodeId;
import java.io.*; import java.util.*; import org.apache.hadoop.yarn.api.records.*;
[ "java.io", "java.util", "org.apache.hadoop" ]
java.io; java.util; org.apache.hadoop;
1,177,822
public Cursor searchItems(long feedID, String searchQuery) { String[] queryWords = prepareSearchQuery(searchQuery); String queryFeedId; if (feedID != 0) { // search items in specific feed queryFeedId = KEY_FEED + " = " + feedID; } else { // search through all items queryFeedId = "1 = 1"; } String queryStart = SELECT_FEED_ITEMS_AND_MEDIA_WITH_DESCRIPTION + " WHERE " + queryFeedId + " AND ("; StringBuilder sb = new StringBuilder(queryStart); for (int i = 0; i < queryWords.length; i++) { sb .append("(") .append(KEY_DESCRIPTION + " LIKE '%").append(queryWords[i]) .append("%' OR ") .append(KEY_TITLE).append(" LIKE '%").append(queryWords[i]) .append("%') "); if (i != queryWords.length - 1) { sb.append("AND "); } } sb.append(") ORDER BY " + KEY_PUBDATE + " DESC LIMIT 300"); return db.rawQuery(sb.toString(), null); }
Cursor function(long feedID, String searchQuery) { String[] queryWords = prepareSearchQuery(searchQuery); String queryFeedId; if (feedID != 0) { queryFeedId = KEY_FEED + STR + feedID; } else { queryFeedId = STR; } String queryStart = SELECT_FEED_ITEMS_AND_MEDIA_WITH_DESCRIPTION + STR + queryFeedId + STR; StringBuilder sb = new StringBuilder(queryStart); for (int i = 0; i < queryWords.length; i++) { sb .append("(") .append(KEY_DESCRIPTION + STR).append(queryWords[i]) .append(STR) .append(KEY_TITLE).append(STR).append(queryWords[i]) .append(STR); if (i != queryWords.length - 1) { sb.append(STR); } } sb.append(STR + KEY_PUBDATE + STR); return db.rawQuery(sb.toString(), null); }
/** * Searches for the given query in various values of all items or the items * of a specified feed. * * @return A cursor with all search results in SEL_FI_EXTRA selection. */
Searches for the given query in various values of all items or the items of a specified feed
searchItems
{ "repo_name": "ByteHamster/AntennaPod", "path": "core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java", "license": "gpl-3.0", "size": 60899 }
[ "android.database.Cursor" ]
import android.database.Cursor;
import android.database.*;
[ "android.database" ]
android.database;
1,926,963
void visit(Modulus node);
void visit(Modulus node);
/** * Visits an AST node of type Modulus. * * @param node * The AST node to visit */
Visits an AST node of type Modulus
visit
{ "repo_name": "team-worthwhile/worthwhile", "path": "implementierung/src/worthwhile.model/src/edu/kit/iti/formal/pse/worthwhile/model/ast/visitor/IASTNodeVisitor.java", "license": "bsd-3-clause", "size": 13590 }
[ "edu.kit.iti.formal.pse.worthwhile.model.ast.Modulus" ]
import edu.kit.iti.formal.pse.worthwhile.model.ast.Modulus;
import edu.kit.iti.formal.pse.worthwhile.model.ast.*;
[ "edu.kit.iti" ]
edu.kit.iti;
494,738
public List<Integer> getUniverseConstellations(String datasource, String userAgent, String xUserAgent) throws ApiException { ApiResponse<List<Integer>> resp = getUniverseConstellationsWithHttpInfo(datasource, userAgent, xUserAgent); return resp.getData(); }
List<Integer> function(String datasource, String userAgent, String xUserAgent) throws ApiException { ApiResponse<List<Integer>> resp = getUniverseConstellationsWithHttpInfo(datasource, userAgent, xUserAgent); return resp.getData(); }
/** * Get constellations * Get a list of constellations --- Alternate route: &#x60;/v1/universe/constellations/&#x60; Alternate route: &#x60;/legacy/universe/constellations/&#x60; Alternate route: &#x60;/dev/universe/constellations/&#x60; --- This route expires daily at 11:05 * @param datasource The server name you would like data from (optional, default to tranquility) * @param userAgent Client identifier, takes precedence over headers (optional) * @param xUserAgent Client identifier, takes precedence over User-Agent (optional) * @return List&lt;Integer&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */
Get constellations Get a list of constellations --- Alternate route: &#x60;/v1/universe/constellations/&#x60; Alternate route: &#x60;/legacy/universe/constellations/&#x60; Alternate route: &#x60;/dev/universe/constellations/&#x60; --- This route expires daily at 11:05
getUniverseConstellations
{ "repo_name": "Tmin10/EVE-Security-Service", "path": "server-api/src/main/java/ru/tmin10/EVESecurityService/serverApi/api/UniverseApi.java", "license": "gpl-3.0", "size": 215688 }
[ "java.util.List", "ru.tmin10.EVESecurityService" ]
import java.util.List; import ru.tmin10.EVESecurityService;
import java.util.*; import ru.tmin10.*;
[ "java.util", "ru.tmin10" ]
java.util; ru.tmin10;
1,873,871
final Environment env = new Environment.Mock() .withFile("src/main/resources/invalid.xml", "<a></a>"); final Validator validator = new XmlValidator(); validator.validate(env); }
final Environment env = new Environment.Mock() .withFile(STR, STR); final Validator validator = new XmlValidator(); validator.validate(env); }
/** * Should fail validation in case of wrong XML. * @throws Exception If something wrong happens inside. */
Should fail validation in case of wrong XML
failsValidationOnWrongFile
{ "repo_name": "vkuchyn/qulice", "path": "qulice-xml/src/test/java/com/qulice/xml/XmlValidatorTest.java", "license": "bsd-3-clause", "size": 13925 }
[ "com.qulice.spi.Environment", "com.qulice.spi.Validator" ]
import com.qulice.spi.Environment; import com.qulice.spi.Validator;
import com.qulice.spi.*;
[ "com.qulice.spi" ]
com.qulice.spi;
1,964,180
public static boolean hasExternalCacheDir() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; }
static boolean function() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; }
/** * Check if OS version has built-in external cache dir method. */
Check if OS version has built-in external cache dir method
hasExternalCacheDir
{ "repo_name": "lovejjfg/MyBlogDemo", "path": "app/src/main/java/com/lovejjfg/blogdemo/utils/PhotoUtils.java", "license": "apache-2.0", "size": 12689 }
[ "android.os.Build" ]
import android.os.Build;
import android.os.*;
[ "android.os" ]
android.os;
1,137,396
public boolean generateRandomSpawnPoints(World world, int spawnCount, int regionDiameter, int minimalDistanceBetweenTwoPoints, double xCenter, double zCenter) { // If the surface of the map is too close of the sum of the surfaces of the private part // around each spawn point (a circle with, as radius, the minimal distance between two spawn // points), the generation will fail. double surfacePrivatePartsAroundSpawnPoints = (int) (spawnCount * (Math.PI * Math.pow(minimalDistanceBetweenTwoPoints, 2))); double surfaceRegion; if(p.getBorderManager().isCircularBorder()) { surfaceRegion = (Math.PI * Math.pow(regionDiameter, 2)) / 4; } else { surfaceRegion = Math.pow(regionDiameter, 2); } Double packingDensity = surfacePrivatePartsAroundSpawnPoints / surfaceRegion; // According to Lagrange and Thue's works on circle packagings, the highest density possible is // approximately 0.9069 (with an hexagonal arrangement of the circles). // Even with a packaging density very close to this limit, the generation time is correct. // So we uses this as a limit. if(packingDensity >= 0.9069) { return false; } LinkedList<Location> randomSpawnPoints = new LinkedList<Location>(); int generatedSpawnPoints = 0; // If the first points are badly located, and if the density is high, the generation may // be impossible to end. // So, after 15 generation fails of a point due to this point being placed too close // of other ones, we restarts all the generation. int currentErrorCount = 0; // With the "avoid above water" option, if there's a lot of water, the genaration may // fail even if the surface seems to be ok to host the requested spawn points. // So, after 2*{points requested} points above the water, we cancels the generation. int pointsAboveWater = 0; generationLoop: while(generatedSpawnPoints != spawnCount) { // "Too many fails" test if(currentErrorCount >= 16) { // restart randomSpawnPoints = new LinkedList<Location>(); generatedSpawnPoints = 0; currentErrorCount = 0; } // "Too many points above the water" test if(pointsAboveWater >= 2*spawnCount) { return false; } // We generates a point in the square of side regionDiameter. // In case of a circular world, if the point was generated out of the circle, it will be // excluded when his presence inside the region will be checked. Location randomPoint = new Location(world, random((int) (xCenter - Math.floor(regionDiameter / 2)), (int) (xCenter + (int) Math.floor(regionDiameter / 2))), 0, random((int) (zCenter - Math.floor(regionDiameter / 2)), (int) (zCenter + (int) Math.floor(regionDiameter / 2)))); // Inside the region? if(!p.getBorderManager().isInsideBorder(randomPoint, regionDiameter)) { continue generationLoop; // outside: nope } Block surfaceBlock = world.getHighestBlockAt(randomPoint); // Safe spot available? if(!UHUtils.isSafeSpot(surfaceBlock.getLocation())) { continue generationLoop; // not safe: nope } // Not above the water? if(avoidWater) { if(surfaceBlock.getType() == Material.WATER || surfaceBlock.getType() == Material.STATIONARY_WATER) { pointsAboveWater++; continue generationLoop; } } // Is that point at a correct distance of the other ones? for(Location spawn : randomSpawnPoints) { if(spawn.distance(randomPoint) < minimalDistanceBetweenTwoPoints) { currentErrorCount++; continue generationLoop; // too close: nope } } // Well, all done. randomSpawnPoints.add(randomPoint); generatedSpawnPoints++; currentErrorCount = 0; } // Generation done, let's register these points. for(Location spawn : randomSpawnPoints) { addSpawnPoint(spawn); } return true; } /** * Generates spawn points in a grid. * * @param world The world where the spawn points will be generated. * @param spawnCount The number of spawn points to generate. * @param regionDiameter The diameter of the region where the spawn points will be generated.<br> * This is limited by the size of the map. This will be seen as the diameter of a circular or * of a squared map, following the shape of the world set in the configuration. * @param minimalDistanceBetweenTwoPoints The minimal distance between two points. * @param xCenter The x coordinate of the point in the center of the region where the points will be generated. * @param zCenter The z coordinate of the point in the center of the region where the points will be generated.
boolean function(World world, int spawnCount, int regionDiameter, int minimalDistanceBetweenTwoPoints, double xCenter, double zCenter) { double surfacePrivatePartsAroundSpawnPoints = (int) (spawnCount * (Math.PI * Math.pow(minimalDistanceBetweenTwoPoints, 2))); double surfaceRegion; if(p.getBorderManager().isCircularBorder()) { surfaceRegion = (Math.PI * Math.pow(regionDiameter, 2)) / 4; } else { surfaceRegion = Math.pow(regionDiameter, 2); } Double packingDensity = surfacePrivatePartsAroundSpawnPoints / surfaceRegion; if(packingDensity >= 0.9069) { return false; } LinkedList<Location> randomSpawnPoints = new LinkedList<Location>(); int generatedSpawnPoints = 0; int currentErrorCount = 0; int pointsAboveWater = 0; generationLoop: while(generatedSpawnPoints != spawnCount) { if(currentErrorCount >= 16) { randomSpawnPoints = new LinkedList<Location>(); generatedSpawnPoints = 0; currentErrorCount = 0; } if(pointsAboveWater >= 2*spawnCount) { return false; } Location randomPoint = new Location(world, random((int) (xCenter - Math.floor(regionDiameter / 2)), (int) (xCenter + (int) Math.floor(regionDiameter / 2))), 0, random((int) (zCenter - Math.floor(regionDiameter / 2)), (int) (zCenter + (int) Math.floor(regionDiameter / 2)))); if(!p.getBorderManager().isInsideBorder(randomPoint, regionDiameter)) { continue generationLoop; } Block surfaceBlock = world.getHighestBlockAt(randomPoint); if(!UHUtils.isSafeSpot(surfaceBlock.getLocation())) { continue generationLoop; } if(avoidWater) { if(surfaceBlock.getType() == Material.WATER surfaceBlock.getType() == Material.STATIONARY_WATER) { pointsAboveWater++; continue generationLoop; } } for(Location spawn : randomSpawnPoints) { if(spawn.distance(randomPoint) < minimalDistanceBetweenTwoPoints) { currentErrorCount++; continue generationLoop; } } randomSpawnPoints.add(randomPoint); generatedSpawnPoints++; currentErrorCount = 0; } for(Location spawn : randomSpawnPoints) { addSpawnPoint(spawn); } return true; } /** * Generates spawn points in a grid. * * @param world The world where the spawn points will be generated. * @param spawnCount The number of spawn points to generate. * @param regionDiameter The diameter of the region where the spawn points will be generated.<br> * This is limited by the size of the map. This will be seen as the diameter of a circular or * of a squared map, following the shape of the world set in the configuration. * @param minimalDistanceBetweenTwoPoints The minimal distance between two points. * @param xCenter The x coordinate of the point in the center of the region where the points will be generated. * @param zCenter The z coordinate of the point in the center of the region where the points will be generated.
/** * Generates randomly some spawn points in the map, with a minimal distance. * * @param world The world where the spawn points will be generated. * @param spawnCount The number of spawn points to generate. * @param regionDiameter The diameter of the region where the spawn points will be generated.<br> * This is limited by the size of the map. This will be seen as the diameter of a circular or * of a squared map, following the shape of the world set in the configuration. * @param minimalDistanceBetweenTwoPoints The minimal distance between two points. * @param xCenter The x coordinate of the point in the center of the region where the points will be generated. * @param zCenter The z coordinate of the point in the center of the region where the points will be generated. * * @return False if there's too many spawn points / not enough surface to generate them. * True if the generation succeeded. */
Generates randomly some spawn points in the map, with a minimal distance
generateRandomSpawnPoints
{ "repo_name": "kyriog/UHPlugin", "path": "src/main/java/me/azenet/UHPlugin/UHSpawnsManager.java", "license": "gpl-3.0", "size": 20902 }
[ "java.util.LinkedList", "org.bukkit.Location", "org.bukkit.Material", "org.bukkit.World", "org.bukkit.block.Block" ]
import java.util.LinkedList; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block;
import java.util.*; import org.bukkit.*; import org.bukkit.block.*;
[ "java.util", "org.bukkit", "org.bukkit.block" ]
java.util; org.bukkit; org.bukkit.block;
537,176
public final Certificate getCertificate(String alias) throws KeyStoreException { if (!isInit) { throwNotInitialized(); } return implSpi.engineGetCertificate(alias); }
final Certificate function(String alias) throws KeyStoreException { if (!isInit) { throwNotInitialized(); } return implSpi.engineGetCertificate(alias); }
/** * Returns the trusted certificate for the entry with the given alias. * * @param alias * the alias for the entry. * @return the trusted certificate for the entry with the given alias, or * {@code null} if the specified alias is not bound to an entry. * @throws KeyStoreException * if this {@code KeyStore} is not initialized. */
Returns the trusted certificate for the entry with the given alias
getCertificate
{ "repo_name": "xdajog/samsung_sources_i927", "path": "libcore/luni/src/main/java/java/security/KeyStore.java", "license": "gpl-2.0", "size": 51725 }
[ "java.security.cert.Certificate" ]
import java.security.cert.Certificate;
import java.security.cert.*;
[ "java.security" ]
java.security;
1,504,196
@Override public int encodeASN(byte[] buf, int offset, AsnEncoder encoder) throws AsnEncodingException { return encoder.buildNull(buf, offset, typeId()); }
int function(byte[] buf, int offset, AsnEncoder encoder) throws AsnEncodingException { return encoder.buildNull(buf, offset, typeId()); }
/** * Used to encode the null value into an ASN.1 buffer. The passed encoder * defines the method for encoding the data. * * @param buf * The location to write the encoded data * @param offset * The start of the encoded buffer. * @param encoder * The ASN.1 encoder object * * @return The byte immediantly after the last encoded byte. * */
Used to encode the null value into an ASN.1 buffer. The passed encoder defines the method for encoding the data
encodeASN
{ "repo_name": "roskens/opennms-pre-github", "path": "core/snmp/joesnmp/src/main/java/org/opennms/protocols/snmp/SnmpNull.java", "license": "agpl-3.0", "size": 5143 }
[ "org.opennms.protocols.snmp.asn1.AsnEncoder", "org.opennms.protocols.snmp.asn1.AsnEncodingException" ]
import org.opennms.protocols.snmp.asn1.AsnEncoder; import org.opennms.protocols.snmp.asn1.AsnEncodingException;
import org.opennms.protocols.snmp.asn1.*;
[ "org.opennms.protocols" ]
org.opennms.protocols;
1,426,643
public static JavaSparkContext jsc() { return MLContextUtil.getJavaSparkContextFromProxy(); }
static JavaSparkContext function() { return MLContextUtil.getJavaSparkContextFromProxy(); }
/** * Obtain JavaSparkContext from MLContextProxy. * * @return the Java Spark Context */
Obtain JavaSparkContext from MLContextProxy
jsc
{ "repo_name": "dusenberrymw/systemml", "path": "src/main/java/org/apache/sysml/api/mlcontext/MLContextConversionUtil.java", "license": "apache-2.0", "size": 46961 }
[ "org.apache.spark.api.java.JavaSparkContext" ]
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.*;
[ "org.apache.spark" ]
org.apache.spark;
2,587,770
static ImmutableMap<Currency, Integer> loadOrdering() { try { IniFile ini = ResourceConfig.combinedIniFile(ResourceConfig.orderedResources(CURRENCY_DATA_INI)); PropertySet section = ini.section("marketConventionPriority"); String list = section.value("ordering"); // The currency ordering is defined as a comma-separated list List<Currency> currencies = Arrays.stream(list.split(",")) .map(String::trim) .map(Currency::of) .collect(toImmutableList()); ImmutableMap.Builder<Currency, Integer> orderBuilder = ImmutableMap.builder(); for (int i = 0; i < currencies.size(); i++) { orderBuilder.put(currencies.get(i), i + 1); } return orderBuilder.build(); } catch (Exception ex) { // logging used because this is loaded in a static variable log.severe(Throwables.getStackTraceAsString(ex)); // return an empty instance to avoid ExceptionInInitializerError return ImmutableMap.of(); } }
static ImmutableMap<Currency, Integer> loadOrdering() { try { IniFile ini = ResourceConfig.combinedIniFile(ResourceConfig.orderedResources(CURRENCY_DATA_INI)); PropertySet section = ini.section(STR); String list = section.value(STR); List<Currency> currencies = Arrays.stream(list.split(",")) .map(String::trim) .map(Currency::of) .collect(toImmutableList()); ImmutableMap.Builder<Currency, Integer> orderBuilder = ImmutableMap.builder(); for (int i = 0; i < currencies.size(); i++) { orderBuilder.put(currencies.get(i), i + 1); } return orderBuilder.build(); } catch (Exception ex) { log.severe(Throwables.getStackTraceAsString(ex)); return ImmutableMap.of(); } }
/** * Loads the priority order of currencies, used to determine the base currency of the market convention pair * for pairs that aren't explicitly configured. * * @return a map of currency to order */
Loads the priority order of currencies, used to determine the base currency of the market convention pair for pairs that aren't explicitly configured
loadOrdering
{ "repo_name": "ChinaQuants/Strata", "path": "modules/basics/src/main/java/com/opengamma/strata/basics/currency/CurrencyDataLoader.java", "license": "apache-2.0", "size": 5815 }
[ "com.google.common.base.Throwables", "com.google.common.collect.ImmutableMap", "com.opengamma.strata.collect.io.IniFile", "com.opengamma.strata.collect.io.PropertySet", "com.opengamma.strata.collect.io.ResourceConfig", "java.util.Arrays", "java.util.List" ]
import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.opengamma.strata.collect.io.IniFile; import com.opengamma.strata.collect.io.PropertySet; import com.opengamma.strata.collect.io.ResourceConfig; import java.util.Arrays; import java.util.List;
import com.google.common.base.*; import com.google.common.collect.*; import com.opengamma.strata.collect.io.*; import java.util.*;
[ "com.google.common", "com.opengamma.strata", "java.util" ]
com.google.common; com.opengamma.strata; java.util;
2,861,661
private Command getCommand (String commandName, Stack<Command> parameterStack) { if (Pattern.matches("-?[0-9]+\\.?[0-9]*", commandName)) { return new ConstantCommand(Double.parseDouble(commandName)); } else if (Pattern.matches(":[a-zA-Z]+", commandName)) { return new VariableCommand(commandName.substring(1)); } else if (commandName.equals("]")) { return makeListCommand(myCommandStack); } else { Class<?> cl; Command command; try { cl = Class.forName(commandName); try { command = (Command)cl.getConstructor().newInstance(); Command[] parameters = new Command[command.getNumParameters()]; for (int i = 0; i < parameters.length; i++) { parameters[i] = parameterStack.pop(); } command.setParameters(parameters); return command; } catch (Exception e) { e.printStackTrace(); String errorMessage = "[" + commandName + " : Invalid Input] Command class for this command could not be" + " constructed properly."; return new ErrorCommand(errorMessage); } } catch (ClassNotFoundException e) { String errorMessage = "[" + commandName + " : Invalid Command] Command class for this command does not exist"; return new ErrorCommand(errorMessage); } } }
Command function (String commandName, Stack<Command> parameterStack) { if (Pattern.matches(STR, commandName)) { return new ConstantCommand(Double.parseDouble(commandName)); } else if (Pattern.matches(STR, commandName)) { return new VariableCommand(commandName.substring(1)); } else if (commandName.equals("]")) { return makeListCommand(myCommandStack); } else { Class<?> cl; Command command; try { cl = Class.forName(commandName); try { command = (Command)cl.getConstructor().newInstance(); Command[] parameters = new Command[command.getNumParameters()]; for (int i = 0; i < parameters.length; i++) { parameters[i] = parameterStack.pop(); } command.setParameters(parameters); return command; } catch (Exception e) { e.printStackTrace(); String errorMessage = "[" + commandName + STR + STR; return new ErrorCommand(errorMessage); } } catch (ClassNotFoundException e) { String errorMessage = "[" + commandName + STR; return new ErrorCommand(errorMessage); } } }
/** * This method gets a string of command name and, using reflection, * returns command object or error, if it doesn't exist. * * @param commandName - a string of command name * @param parameterStack - stack of commands that contains parameters * @return either command or error */
This method gets a string of command name and, using reflection, returns command object or error, if it doesn't exist
getCommand
{ "repo_name": "aj148/slogo", "path": "src/parser/Parser.java", "license": "mit", "size": 6154 }
[ "java.util.Stack", "java.util.regex.Pattern" ]
import java.util.Stack; import java.util.regex.Pattern;
import java.util.*; import java.util.regex.*;
[ "java.util" ]
java.util;
281,481
public Document parseText(String text) throws SAXException, IOException, ParserConfigurationException { return parse(new StringReader(text)); } public DOMBuilder(Document document) { this.document = document; } public DOMBuilder(DocumentBuilder documentBuilder) { this.documentBuilder = documentBuilder; }
Document function(String text) throws SAXException, IOException, ParserConfigurationException { return parse(new StringReader(text)); } public DOMBuilder(Document document) { this.document = document; } public DOMBuilder(DocumentBuilder documentBuilder) { this.documentBuilder = documentBuilder; }
/** * A helper method to parse the given text as XML. * * @param text the XML text to parse * @return the root node of the parsed tree of Nodes * @throws SAXException Any SAX exception, possibly wrapping another exception. * @throws IOException An IO exception from the parser, possibly from a byte * stream or character stream supplied by the application. * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies * the configuration requested. * @see #parse(Reader) */
A helper method to parse the given text as XML
parseText
{ "repo_name": "rlovtangen/groovy-core", "path": "subprojects/groovy-xml/src/main/java/groovy/xml/DOMBuilder.java", "license": "apache-2.0", "size": 10970 }
[ "java.io.IOException", "java.io.StringReader", "javax.xml.parsers.DocumentBuilder", "javax.xml.parsers.ParserConfigurationException", "org.w3c.dom.Document", "org.xml.sax.SAXException" ]
import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException;
import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*;
[ "java.io", "javax.xml", "org.w3c.dom", "org.xml.sax" ]
java.io; javax.xml; org.w3c.dom; org.xml.sax;
1,201,561
@Test public void testSetMetric() throws Exception { ospfLsaLink.setMetric(100); assertThat(ospfLsaLink.metric(), is(100)); }
void function() throws Exception { ospfLsaLink.setMetric(100); assertThat(ospfLsaLink.metric(), is(100)); }
/** * Tests metric() setter method. */
Tests metric() setter method
testSetMetric
{ "repo_name": "sdnwiselab/onos", "path": "protocols/ospf/protocol/src/test/java/org/onosproject/ospf/protocol/lsa/subtypes/OspfLsaLinkTest.java", "license": "apache-2.0", "size": 3503 }
[ "org.hamcrest.MatcherAssert", "org.hamcrest.Matchers" ]
import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers;
import org.hamcrest.*;
[ "org.hamcrest" ]
org.hamcrest;
752,343
public static String formatUrl(final String endpoint) { if (endpoint.startsWith(Constants.HTTPS_PREFIX)) { return REPLACE.matcher(endpoint).replaceAll(Matcher.quoteReplacement(Constants.HTTP_PREFIX)); } else if (endpoint.startsWith(Constants.HTTP_PREFIX)) { return endpoint; } else { return "http://" + endpoint; } }
static String function(final String endpoint) { if (endpoint.startsWith(Constants.HTTPS_PREFIX)) { return REPLACE.matcher(endpoint).replaceAll(Matcher.quoteReplacement(Constants.HTTP_PREFIX)); } else if (endpoint.startsWith(Constants.HTTP_PREFIX)) { return endpoint; } else { return "http: } }
/** * Formats an URL string so that it always starts with 'http' */
Formats an URL string so that it always starts with 'http'
formatUrl
{ "repo_name": "SpectraLogic/ds3_java_browser", "path": "dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/util/CheckNetwork.java", "license": "apache-2.0", "size": 2483 }
[ "java.util.regex.Matcher" ]
import java.util.regex.Matcher;
import java.util.regex.*;
[ "java.util" ]
java.util;
2,843,677
public static boolean hasMetaAnnotationTypes(AnnotatedElement element, Class<? extends Annotation> annotationType) { Assert.notNull(element, "AnnotatedElement must not be null"); Assert.notNull(annotationType, "annotationType must not be null"); return hasMetaAnnotationTypes(element, annotationType, null); }
static boolean function(AnnotatedElement element, Class<? extends Annotation> annotationType) { Assert.notNull(element, STR); Assert.notNull(annotationType, STR); return hasMetaAnnotationTypes(element, annotationType, null); }
/** * Determine if the supplied {@link AnnotatedElement} is annotated with * a <em>composed annotation</em> that is meta-annotated with an * annotation of the specified {@code annotationType}. * <p>This method follows <em>get semantics</em> as described in the * {@linkplain AnnotatedElementUtils class-level javadoc}. * @param element the annotated element * @param annotationType the meta-annotation type to find * @return {@code true} if a matching meta-annotation is present * @since 4.2.3 * @see #getMetaAnnotationTypes */
Determine if the supplied <code>AnnotatedElement</code> is annotated with a composed annotation that is meta-annotated with an annotation of the specified annotationType. This method follows get semantics as described in the AnnotatedElementUtils class-level javadoc
hasMetaAnnotationTypes
{ "repo_name": "boggad/jdk9-sample", "path": "sample-catalog/spring-jdk9/src/spring.core/org/springframework/core/annotation/AnnotatedElementUtils.java", "license": "mit", "size": 73071 }
[ "java.lang.annotation.Annotation", "java.lang.reflect.AnnotatedElement", "org.springframework.util.Assert" ]
import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import org.springframework.util.Assert;
import java.lang.annotation.*; import java.lang.reflect.*; import org.springframework.util.*;
[ "java.lang", "org.springframework.util" ]
java.lang; org.springframework.util;
2,448,055
public void checkState(Set<T> allowedStates) { checkNotNull(allowedStates); checkArgument(!allowedStates.isEmpty(), "At least one possible state must be provided."); readLock.lock(); try { if (!allowedStates.contains(currentState)) { throw new IllegalStateException( String.format("In state %s, expected to be in %s.", currentState, allowedStates)); } } finally { readLock.unlock(); } }
void function(Set<T> allowedStates) { checkNotNull(allowedStates); checkArgument(!allowedStates.isEmpty(), STR); readLock.lock(); try { if (!allowedStates.contains(currentState)) { throw new IllegalStateException( String.format(STR, currentState, allowedStates)); } } finally { readLock.unlock(); } }
/** * Checks that the current state is one of the {@code allowedStates} and throws if it is not. * * @param allowedStates The allowed states. * @throws IllegalStateException if the current state is not the {@code expectedState}. */
Checks that the current state is one of the allowedStates and throws if it is not
checkState
{ "repo_name": "protochron/aurora", "path": "commons/src/main/java/org/apache/aurora/common/util/StateMachine.java", "license": "apache-2.0", "size": 17139 }
[ "com.google.common.base.Preconditions", "java.util.Set" ]
import com.google.common.base.Preconditions; import java.util.Set;
import com.google.common.base.*; import java.util.*;
[ "com.google.common", "java.util" ]
com.google.common; java.util;
2,027,724
try { return EdgeHidingMode.parseInt(type.getEdgeHidingMode()); } catch (final IllegalStateException e) { CUtilityFunctions.logException(e); return EdgeHidingMode.HIDE_ON_THRESHOLD; } }
try { return EdgeHidingMode.parseInt(type.getEdgeHidingMode()); } catch (final IllegalStateException e) { CUtilityFunctions.logException(e); return EdgeHidingMode.HIDE_ON_THRESHOLD; } }
/** * Converts the numerical value of a configuration file edge hiding mode to an enumeration value. * * @param type The configuration file settings type that provides the numerical value. * * @return The corresponding enumeration value or a default value if the value from the * configuration file is invalid. */
Converts the numerical value of a configuration file edge hiding mode to an enumeration value
getEdgeHidingMode
{ "repo_name": "chubbymaggie/binnavi", "path": "src/main/java/com/google/security/zynamics/binnavi/ZyGraph/Settings/ZyGraphEdgeSettings.java", "license": "apache-2.0", "size": 7700 }
[ "com.google.security.zynamics.binnavi.CUtilityFunctions", "com.google.security.zynamics.zylib.gui.zygraph.EdgeHidingMode" ]
import com.google.security.zynamics.binnavi.CUtilityFunctions; import com.google.security.zynamics.zylib.gui.zygraph.EdgeHidingMode;
import com.google.security.zynamics.binnavi.*; import com.google.security.zynamics.zylib.gui.zygraph.*;
[ "com.google.security" ]
com.google.security;
318,521
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } }
void function(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } }
/** * Util method to write an attribute without the ns prefix */
Util method to write an attribute without the ns prefix
writeQNameAttribute
{ "repo_name": "arunasujith/wso2-axis2", "path": "modules/adb/src/org/apache/axis2/databinding/types/xsd/NOTATION.java", "license": "apache-2.0", "size": 21385 }
[ "javax.xml.stream.XMLStreamWriter" ]
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.*;
[ "javax.xml" ]
javax.xml;
1,907,804
public static ConversionCategory union(ConversionCategory a, ConversionCategory b) { if (a == UNUSED || b == UNUSED) { return UNUSED; } if (a == GENERAL || b == GENERAL) { return GENERAL; } if ((a == CHAR_AND_INT && b == INT_AND_TIME) || (a == INT_AND_TIME && b == CHAR_AND_INT)) { // This is special-cased because the union of a.types and b.types // does not include BigInteger.class, whereas the types for INT does. // Returning INT here to prevent returning GENERAL below. return INT; } Set<Class<? extends Object>> as = arrayToSet(a.types); Set<Class<? extends Object>> bs = arrayToSet(b.types); as.addAll(bs); // union for (ConversionCategory v : new ConversionCategory[] { NULL, CHAR_AND_INT, INT_AND_TIME, CHAR, INT, FLOAT, TIME }) { Set<Class<? extends Object>> vs = arrayToSet(v.types); if (vs.equals(as)) { return v; } } return GENERAL; }
static ConversionCategory function(ConversionCategory a, ConversionCategory b) { if (a == UNUSED b == UNUSED) { return UNUSED; } if (a == GENERAL b == GENERAL) { return GENERAL; } if ((a == CHAR_AND_INT && b == INT_AND_TIME) (a == INT_AND_TIME && b == CHAR_AND_INT)) { return INT; } Set<Class<? extends Object>> as = arrayToSet(a.types); Set<Class<? extends Object>> bs = arrayToSet(b.types); as.addAll(bs); for (ConversionCategory v : new ConversionCategory[] { NULL, CHAR_AND_INT, INT_AND_TIME, CHAR, INT, FLOAT, TIME }) { Set<Class<? extends Object>> vs = arrayToSet(v.types); if (vs.equals(as)) { return v; } } return GENERAL; }
/** * Use this function to get the union of two categories. This is seldomly needed. * * <blockquote> * * <pre> * ConversionCategory.union(INT, TIME) == GENERAL; * </pre> * * </blockquote> */
Use this function to get the union of two categories. This is seldomly needed. <code> ConversionCategory.union(INT, TIME) == GENERAL; </code>
union
{ "repo_name": "CharlesZ-Chen/checker-framework", "path": "checker/src/org/checkerframework/checker/formatter/qual/ConversionCategory.java", "license": "gpl-2.0", "size": 9059 }
[ "java.util.Set" ]
import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
1,446,991
List<RoutePolicyFactory> getRoutePolicyFactories();
List<RoutePolicyFactory> getRoutePolicyFactories();
/** * Gets the route policy factories * * @return the list of current route policy factories */
Gets the route policy factories
getRoutePolicyFactories
{ "repo_name": "NickCis/camel", "path": "camel-core/src/main/java/org/apache/camel/CamelContext.java", "license": "apache-2.0", "size": 74001 }
[ "java.util.List", "org.apache.camel.spi.RoutePolicyFactory" ]
import java.util.List; import org.apache.camel.spi.RoutePolicyFactory;
import java.util.*; import org.apache.camel.spi.*;
[ "java.util", "org.apache.camel" ]
java.util; org.apache.camel;
1,112,078
public InjectionTargetType<ServiceRefType<T>> createInjectionTarget() { return new InjectionTargetTypeImpl<ServiceRefType<T>>(this, "injection-target", childNode); }
InjectionTargetType<ServiceRefType<T>> function() { return new InjectionTargetTypeImpl<ServiceRefType<T>>(this, STR, childNode); }
/** * Creates a new <code>injection-target</code> element * @return the new created instance of <code>InjectionTargetType<ServiceRefType<T>></code> */
Creates a new <code>injection-target</code> element
createInjectionTarget
{ "repo_name": "forge/javaee-descriptors", "path": "impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/javaeewebservicesclient12/ServiceRefTypeImpl.java", "license": "epl-1.0", "size": 25854 }
[ "org.jboss.shrinkwrap.descriptor.api.javaee5.InjectionTargetType", "org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12.ServiceRefType", "org.jboss.shrinkwrap.descriptor.impl.javaee5.InjectionTargetTypeImpl" ]
import org.jboss.shrinkwrap.descriptor.api.javaee5.InjectionTargetType; import org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12.ServiceRefType; import org.jboss.shrinkwrap.descriptor.impl.javaee5.InjectionTargetTypeImpl;
import org.jboss.shrinkwrap.descriptor.api.javaee5.*; import org.jboss.shrinkwrap.descriptor.api.javaeewebservicesclient12.*; import org.jboss.shrinkwrap.descriptor.impl.javaee5.*;
[ "org.jboss.shrinkwrap" ]
org.jboss.shrinkwrap;
78,617
@Nonnull Collection<AccessLevel> listAllAccessLevels(); /** * Get the {@link AccessLevel} access level from its {@code name}. * * @param name the desired access level name, as string * @return the {@link AccessLevel} associated with the provided {@code name}, or null if the provided {@code name}
Collection<AccessLevel> listAllAccessLevels(); /** * Get the {@link AccessLevel} access level from its {@code name}. * * @param name the desired access level name, as string * @return the {@link AccessLevel} associated with the provided {@code name}, or null if the provided {@code name}
/** * Get the access levels available, including un-assignable ones, {@link AccessLevel#isAssignable()}}. * * @return a collection of {@link AccessLevel} objects, may be empty if none are available */
Get the access levels available, including un-assignable ones, <code>AccessLevel#isAssignable()</code>}
listAllAccessLevels
{ "repo_name": "teyden/phenotips", "path": "components/entity-access-rules/api/src/main/java/org/phenotips/data/permissions/internal/EntityAccessManager.java", "license": "agpl-3.0", "size": 6046 }
[ "java.util.Collection", "org.phenotips.data.permissions.AccessLevel" ]
import java.util.Collection; import org.phenotips.data.permissions.AccessLevel;
import java.util.*; import org.phenotips.data.permissions.*;
[ "java.util", "org.phenotips.data" ]
java.util; org.phenotips.data;
139,200
final VertexFactory<TemporalVertex> vertexFactory = getConfig().getTemporalGraphFactory().getVertexFactory(); // Create vertex tuples for each accepted interval. List<TemporalVertex> tuplesAccepted = testIntervalsAccepted.stream() .map(i -> { TemporalVertex vertex = vertexFactory.createVertex(); vertex.setValidTime(i); return vertex; }) .collect(Collectors.toList()); List<TemporalVertex> inputTuples = new ArrayList<>(tuplesAccepted); // Create vertex tuples for other intervals. testIntervalsOther.stream().map(i -> { TemporalVertex vertex = vertexFactory.createVertex(); vertex.setValidTime(i); return vertex; }) .forEach(inputTuples::add); // Apply the filter to the input. List<TemporalVertex> result = getExecutionEnvironment() .fromCollection(inputTuples, TypeInformation.of(TemporalVertex.class)) .filter(new ByTemporalPredicate<>(testPredicate, TimeDimension.VALID_TIME)) .collect(); // Sort the result and expected results to allow for comparison. Comparator<TemporalVertex> comparator = Comparator.comparing(TemporalVertex::getId); result.sort(comparator); tuplesAccepted.sort(comparator); assertArrayEquals(tuplesAccepted.toArray(), result.toArray()); }
final VertexFactory<TemporalVertex> vertexFactory = getConfig().getTemporalGraphFactory().getVertexFactory(); List<TemporalVertex> tuplesAccepted = testIntervalsAccepted.stream() .map(i -> { TemporalVertex vertex = vertexFactory.createVertex(); vertex.setValidTime(i); return vertex; }) .collect(Collectors.toList()); List<TemporalVertex> inputTuples = new ArrayList<>(tuplesAccepted); testIntervalsOther.stream().map(i -> { TemporalVertex vertex = vertexFactory.createVertex(); vertex.setValidTime(i); return vertex; }) .forEach(inputTuples::add); List<TemporalVertex> result = getExecutionEnvironment() .fromCollection(inputTuples, TypeInformation.of(TemporalVertex.class)) .filter(new ByTemporalPredicate<>(testPredicate, TimeDimension.VALID_TIME)) .collect(); Comparator<TemporalVertex> comparator = Comparator.comparing(TemporalVertex::getId); result.sort(comparator); tuplesAccepted.sort(comparator); assertArrayEquals(tuplesAccepted.toArray(), result.toArray()); }
/** * Test the filter function on vertex tuples. * * @throws Exception when the execution in Flink fails. */
Test the filter function on vertex tuples
testForVertices
{ "repo_name": "galpha/gradoop", "path": "gradoop-temporal/src/test/java/org/gradoop/temporal/model/impl/operators/snapshot/ByTemporalPredicateTest.java", "license": "apache-2.0", "size": 5679 }
[ "java.util.ArrayList", "java.util.Comparator", "java.util.List", "java.util.stream.Collectors", "org.apache.flink.api.common.typeinfo.TypeInformation", "org.gradoop.common.model.api.entities.VertexFactory", "org.gradoop.temporal.model.api.TimeDimension", "org.gradoop.temporal.model.impl.operators.snap...
import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.gradoop.common.model.api.entities.VertexFactory; import org.gradoop.temporal.model.api.TimeDimension; import org.gradoop.temporal.model.impl.operators.snapshot.functions.ByTemporalPredicate; import org.gradoop.temporal.model.impl.pojo.TemporalVertex; import org.testng.AssertJUnit;
import java.util.*; import java.util.stream.*; import org.apache.flink.api.common.typeinfo.*; import org.gradoop.common.model.api.entities.*; import org.gradoop.temporal.model.api.*; import org.gradoop.temporal.model.impl.operators.snapshot.functions.*; import org.gradoop.temporal.model.impl.pojo.*; import org.testng.*;
[ "java.util", "org.apache.flink", "org.gradoop.common", "org.gradoop.temporal", "org.testng" ]
java.util; org.apache.flink; org.gradoop.common; org.gradoop.temporal; org.testng;
284,933
public BlendingOptions getNextBatchBlendingOptions() { return nextBatchBlendingOptions; }
BlendingOptions function() { return nextBatchBlendingOptions; }
/** * Returns the BlendingOptions that should be used to render the next batch. * * @return BlendingOptions */
Returns the BlendingOptions that should be used to render the next batch
getNextBatchBlendingOptions
{ "repo_name": "miviclin/droidengine2d", "path": "src/com/miviclin/droidengine2d/graphics/mesh/GraphicsBatchRenderer.java", "license": "apache-2.0", "size": 5752 }
[ "com.miviclin.droidengine2d.graphics.material.BlendingOptions" ]
import com.miviclin.droidengine2d.graphics.material.BlendingOptions;
import com.miviclin.droidengine2d.graphics.material.*;
[ "com.miviclin.droidengine2d" ]
com.miviclin.droidengine2d;
498,564
public Adapter createUniformAdapter() { return null; }
Adapter function() { return null; }
/** * Creates a new adapter for an object of class '{@link metamodel.Uniform <em>Uniform</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see metamodel.Uniform * @generated */
Creates a new adapter for an object of class '<code>metamodel.Uniform Uniform</code>'. This default implementation returns null so that we can easily ignore cases; it's useful to ignore a case when inheritance will catch all the cases anyway.
createUniformAdapter
{ "repo_name": "jesusc/bento", "path": "tests/bento.sirius.tests.metamodels/src/metamodel/util/MetamodelAdapterFactory.java", "license": "epl-1.0", "size": 13960 }
[ "org.eclipse.emf.common.notify.Adapter" ]
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
2,728,989
public Stream<Triple> notCommon() { return stream(spliteratorUnknownSize(notCommon.find(ANY, ANY, ANY), IMMUTABLE), false); }
Stream<Triple> function() { return stream(spliteratorUnknownSize(notCommon.find(ANY, ANY, ANY), IMMUTABLE), false); }
/** * This method will return null until the source iterator is exhausted. * * @return The elements that turned out not to be common to the two inputs. */
This method will return null until the source iterator is exhausted
notCommon
{ "repo_name": "ajs6f/fcrepo4", "path": "fcrepo-kernel-api/src/main/java/org/fcrepo/kernel/api/utils/GraphDifferencer.java", "license": "apache-2.0", "size": 3441 }
[ "com.hp.hpl.jena.graph.Triple", "java.util.stream.Stream", "java.util.stream.StreamSupport" ]
import com.hp.hpl.jena.graph.Triple; import java.util.stream.Stream; import java.util.stream.StreamSupport;
import com.hp.hpl.jena.graph.*; import java.util.stream.*;
[ "com.hp.hpl", "java.util" ]
com.hp.hpl; java.util;
2,906,063
private void storeProperty(final String propName, String propValue, String siteId) { ContentCollectionEdit contentCollection = null; try { contentCollection = podcastService.getContentCollectionEditable(siteId); ResourcePropertiesEdit rp = contentCollection.getPropertiesEdit(); if (rp.getProperty(propName) != null) { rp.removeProperty(propName); } rp.addProperty(propName, propValue); podcastService.commitContentCollection(contentCollection); } catch (Exception e) { // catches IdUnusedException, PermissionException LOG.error(e.getMessage() + " attempting to add property " + propName + " for site: " + siteId + ". " + e.getMessage(), e); podcastService.cancelContentCollection(contentCollection); throw new PodcastException(e); } }
void function(final String propName, String propValue, String siteId) { ContentCollectionEdit contentCollection = null; try { contentCollection = podcastService.getContentCollectionEditable(siteId); ResourcePropertiesEdit rp = contentCollection.getPropertiesEdit(); if (rp.getProperty(propName) != null) { rp.removeProperty(propName); } rp.addProperty(propName, propValue); podcastService.commitContentCollection(contentCollection); } catch (Exception e) { LOG.error(e.getMessage() + STR + propName + STR + siteId + STR + e.getMessage(), e); podcastService.cancelContentCollection(contentCollection); throw new PodcastException(e); } }
/** * Stores the property propValue in the Podcasts folder resource under the name propName * * @param propName * The name within the resource to store the value * * @param propValue * The value to store * * @param siteId * Which site's Podcasts folder to store this property within. */
Stores the property propValue in the Podcasts folder resource under the name propName
storeProperty
{ "repo_name": "eemirtekin/Sakai-10.6-TR", "path": "podcasts/podcasts-impl/impl/src/java/org/sakaiproject/component/app/podcasts/BasicPodfeedService.java", "license": "apache-2.0", "size": 29928 }
[ "org.sakaiproject.api.app.podcasts.exception.PodcastException", "org.sakaiproject.content.api.ContentCollectionEdit", "org.sakaiproject.entity.api.ResourcePropertiesEdit" ]
import org.sakaiproject.api.app.podcasts.exception.PodcastException; import org.sakaiproject.content.api.ContentCollectionEdit; import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.api.app.podcasts.exception.*; import org.sakaiproject.content.api.*; import org.sakaiproject.entity.api.*;
[ "org.sakaiproject.api", "org.sakaiproject.content", "org.sakaiproject.entity" ]
org.sakaiproject.api; org.sakaiproject.content; org.sakaiproject.entity;
796,368
public void visit(BinaryOperatorNode node) throws StandardException { WhereClauseVisitor wvisitor = new WhereClauseVisitor(); node.accept(wvisitor); Structure tmp = wvisitor.getConditionTree(); extendCol(tmp); }
void function(BinaryOperatorNode node) throws StandardException { WhereClauseVisitor wvisitor = new WhereClauseVisitor(); node.accept(wvisitor); Structure tmp = wvisitor.getConditionTree(); extendCol(tmp); }
/** * Sub visit function for binary operations. * * @param node * @throws StandardException */
Sub visit function for binary operations
visit
{ "repo_name": "UniversityOfWuerzburg-ChairCompSciVI/ueps", "path": "src/main/java/de/uniwue/info6/parser/visitors/ResultColumnListVisitor.java", "license": "apache-2.0", "size": 8216 }
[ "com.akiban.sql.StandardException", "com.akiban.sql.parser.BinaryOperatorNode", "de.uniwue.info6.parser.structures.Structure" ]
import com.akiban.sql.StandardException; import com.akiban.sql.parser.BinaryOperatorNode; import de.uniwue.info6.parser.structures.Structure;
import com.akiban.sql.*; import com.akiban.sql.parser.*; import de.uniwue.info6.parser.structures.*;
[ "com.akiban.sql", "de.uniwue.info6" ]
com.akiban.sql; de.uniwue.info6;
1,328,750
//----------------------------------------------------------------------- public Tenor getMaturityTenor() { return _maturityTenor; }
Tenor function() { return _maturityTenor; }
/** * Gets the (approximate) bill tenor. * @return the value of the property, not null */
Gets the (approximate) bill tenor
getMaturityTenor
{ "repo_name": "McLeodMoores/starling", "path": "projects/financial/src/main/java/com/opengamma/financial/analytics/ircurve/strips/BillNode.java", "license": "apache-2.0", "size": 7131 }
[ "com.opengamma.util.time.Tenor" ]
import com.opengamma.util.time.Tenor;
import com.opengamma.util.time.*;
[ "com.opengamma.util" ]
com.opengamma.util;
989,668
private Response.ResponseBuilder createViolationResponse( Set<ConstraintViolation<?>> violations) { log.fine("Validation completed. violations found: " + violations.size()); Map<String, String> responseObj = new HashMap<String, String>(); for (ConstraintViolation<?> violation : violations) { responseObj.put(violation.getPropertyPath().toString(), violation.getMessage()); } return Response.status(Response.Status.BAD_REQUEST).entity(responseObj); }
Response.ResponseBuilder function( Set<ConstraintViolation<?>> violations) { log.fine(STR + violations.size()); Map<String, String> responseObj = new HashMap<String, String>(); for (ConstraintViolation<?> violation : violations) { responseObj.put(violation.getPropertyPath().toString(), violation.getMessage()); } return Response.status(Response.Status.BAD_REQUEST).entity(responseObj); }
/** * Creates a JAX-RS "Bad Request" response including a map of all violation * fields, and their message. This can then be used by clients to show * violations. * * @param violations * A set of violations that needs to be reported * @return JAX-RS response containing all violations */
Creates a JAX-RS "Bad Request" response including a map of all violation fields, and their message. This can then be used by clients to show violations
createViolationResponse
{ "repo_name": "currying/molecule", "path": "platform2/src/main/java/com/jzsoft/platform2/rest/WorkTicketResourceRESTService.java", "license": "apache-2.0", "size": 5603 }
[ "java.util.HashMap", "java.util.Map", "java.util.Set", "javax.validation.ConstraintViolation", "javax.ws.rs.core.Response" ]
import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.validation.ConstraintViolation; import javax.ws.rs.core.Response;
import java.util.*; import javax.validation.*; import javax.ws.rs.core.*;
[ "java.util", "javax.validation", "javax.ws" ]
java.util; javax.validation; javax.ws;
2,803,879
private void setLoginPage(String loginPage) { this.loginPage = loginPage; this.authenticationEntryPoint = new LoginUrlAuthenticationEntryPoint(loginPage); }
void function(String loginPage) { this.loginPage = loginPage; this.authenticationEntryPoint = new LoginUrlAuthenticationEntryPoint(loginPage); }
/** * Sets the loginPage and updates the {@link AuthenticationEntryPoint}. * @param loginPage */
Sets the loginPage and updates the <code>AuthenticationEntryPoint</code>
setLoginPage
{ "repo_name": "jmnarloch/spring-security", "path": "config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.java", "license": "apache-2.0", "size": 13546 }
[ "org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint" ]
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.*;
[ "org.springframework.security" ]
org.springframework.security;
1,577,679
// // Configurations // public List<GwtConfigComponent> findDeviceConfigurations(GwtDevice device) throws GwtKapuaException;
List<GwtConfigComponent> function(GwtDevice device) throws GwtKapuaException;
/** * Returns the configuration of a Device as the list of all the configurable components. * * @param device * @return */
Returns the configuration of a Device as the list of all the configurable components
findDeviceConfigurations
{ "repo_name": "muros-ct/kapua", "path": "org.eclipse.kapua.app.console/src/main/java/org/eclipse/kapua/app/console/shared/service/GwtDeviceManagementService.java", "license": "epl-1.0", "size": 5695 }
[ "java.util.List", "org.eclipse.kapua.app.console.shared.GwtKapuaException", "org.eclipse.kapua.app.console.shared.model.GwtConfigComponent", "org.eclipse.kapua.app.console.shared.model.GwtDevice" ]
import java.util.List; import org.eclipse.kapua.app.console.shared.GwtKapuaException; import org.eclipse.kapua.app.console.shared.model.GwtConfigComponent; import org.eclipse.kapua.app.console.shared.model.GwtDevice;
import java.util.*; import org.eclipse.kapua.app.console.shared.*; import org.eclipse.kapua.app.console.shared.model.*;
[ "java.util", "org.eclipse.kapua" ]
java.util; org.eclipse.kapua;
1,778,200
@Override public Enumeration<Locale> getLocales() { return this.request.getLocales(); }
Enumeration<Locale> function() { return this.request.getLocales(); }
/** * The default behavior of this method is to return getLocales() on the * wrapped request object. */
The default behavior of this method is to return getLocales() on the wrapped request object
getLocales
{ "repo_name": "plumer/codana", "path": "tomcat_files/8.0.22/ServletRequestWrapper.java", "license": "mit", "size": 13745 }
[ "java.util.Enumeration", "java.util.Locale" ]
import java.util.Enumeration; import java.util.Locale;
import java.util.*;
[ "java.util" ]
java.util;
189,735
private void initServerSocket(ServerSocket ssocket) { SSLServerSocket socket = (SSLServerSocket) ssocket; if (attributes.get("ciphers") != null) { socket.setEnabledCipherSuites(enabledCiphers); } String requestedProtocols = (String) attributes.get("protocols"); setEnabledProtocols(socket, getEnabledProtocols(socket, requestedProtocols)); // we don't know if client auth is needed - // after parsing the request we may re-handshake socket.setNeedClientAuth(clientAuth); }
void function(ServerSocket ssocket) { SSLServerSocket socket = (SSLServerSocket) ssocket; if (attributes.get(STR) != null) { socket.setEnabledCipherSuites(enabledCiphers); } String requestedProtocols = (String) attributes.get(STR); setEnabledProtocols(socket, getEnabledProtocols(socket, requestedProtocols)); socket.setNeedClientAuth(clientAuth); }
/** * Configures the given SSL server socket with the requested cipher suites, * protocol versions, and need for client authentication */
Configures the given SSL server socket with the requested cipher suites, protocol versions, and need for client authentication
initServerSocket
{ "repo_name": "devjin24/howtomcatworks", "path": "bookrefer/jakarta-tomcat-5.0.18-src/jakarta-tomcat-connectors/util/java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.java", "license": "apache-2.0", "size": 13878 }
[ "java.net.ServerSocket", "javax.net.ssl.SSLServerSocket" ]
import java.net.ServerSocket; import javax.net.ssl.SSLServerSocket;
import java.net.*; import javax.net.ssl.*;
[ "java.net", "javax.net" ]
java.net; javax.net;
1,941,286
protected Task getTaskById(String id) { return engine.getTaskService().createTaskQuery().taskId(id).initializeFormKeys().singleResult(); }
Task function(String id) { return engine.getTaskService().createTaskQuery().taskId(id).initializeFormKeys().singleResult(); }
/** * Returns the task with the given id * * @param id * @return */
Returns the task with the given id
getTaskById
{ "repo_name": "falko/camunda-bpm-platform", "path": "engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskResourceImpl.java", "license": "apache-2.0", "size": 16452 }
[ "org.camunda.bpm.engine.task.Task" ]
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.*;
[ "org.camunda.bpm" ]
org.camunda.bpm;
1,498,328
public T jaxb(String contextPath) { JaxbDataFormat dataFormat = new JaxbDataFormat(); dataFormat.setContextPath(contextPath); return dataFormat(dataFormat); }
T function(String contextPath) { JaxbDataFormat dataFormat = new JaxbDataFormat(); dataFormat.setContextPath(contextPath); return dataFormat(dataFormat); }
/** * Uses the JAXB data format with context path */
Uses the JAXB data format with context path
jaxb
{ "repo_name": "rmarting/camel", "path": "camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java", "license": "apache-2.0", "size": 42614 }
[ "org.apache.camel.model.dataformat.JaxbDataFormat" ]
import org.apache.camel.model.dataformat.JaxbDataFormat;
import org.apache.camel.model.dataformat.*;
[ "org.apache.camel" ]
org.apache.camel;
2,066,855
public void setOvsdbProviderService(OvsdbProviderService ovsdbNodeDriver) { this.ovsdbProviderService = ovsdbNodeDriver; }
void function(OvsdbProviderService ovsdbNodeDriver) { this.ovsdbProviderService = ovsdbNodeDriver; }
/** * Sets the ovsdbProviderService instance. * * @param ovsdbNodeDriver the ovsdbNodeDriver to use */
Sets the ovsdbProviderService instance
setOvsdbProviderService
{ "repo_name": "jinlongliu/onos", "path": "ovsdb/ctl/src/main/java/org/onosproject/ovsdb/controller/impl/OvsdbJsonRpcHandler.java", "license": "apache-2.0", "size": 3912 }
[ "org.onosproject.ovsdb.controller.driver.OvsdbProviderService" ]
import org.onosproject.ovsdb.controller.driver.OvsdbProviderService;
import org.onosproject.ovsdb.controller.driver.*;
[ "org.onosproject.ovsdb" ]
org.onosproject.ovsdb;
767,912
public void startForegroundService(Intent intent) { ContextCompat.startForegroundService(ContextUtils.getApplicationContext(), intent); }
void function(Intent intent) { ContextCompat.startForegroundService(ContextUtils.getApplicationContext(), intent); }
/** * Starts a service from {@code intent} with the expectation that it will make itself a * foreground service with {@link android.app.Service#startForeground(int, Notification)}. * * @param intent The {@link Intent} to fire to start the service. */
Starts a service from intent with the expectation that it will make itself a foreground service with <code>android.app.Service#startForeground(int, Notification)</code>
startForegroundService
{ "repo_name": "endlessm/chromium-browser", "path": "chrome/android/java/src/org/chromium/chrome/browser/notifications/ForegroundServiceUtils.java", "license": "bsd-3-clause", "size": 3472 }
[ "android.content.Intent", "androidx.core.content.ContextCompat", "org.chromium.base.ContextUtils" ]
import android.content.Intent; import androidx.core.content.ContextCompat; import org.chromium.base.ContextUtils;
import android.content.*; import androidx.core.content.*; import org.chromium.base.*;
[ "android.content", "androidx.core", "org.chromium.base" ]
android.content; androidx.core; org.chromium.base;
975,421
public KualiDecimal getTotalAmount() { return totalAmount; }
KualiDecimal function() { return totalAmount; }
/** * Gets the totalAmount attribute. */
Gets the totalAmount attribute
getTotalAmount
{ "repo_name": "kuali/kfs", "path": "kfs-core/src/main/java/org/kuali/kfs/gl/batch/CollectorBatch.java", "license": "agpl-3.0", "size": 26781 }
[ "org.kuali.rice.core.api.util.type.KualiDecimal" ]
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.core.api.util.type.*;
[ "org.kuali.rice" ]
org.kuali.rice;
2,377,813
private FeedbackResultsResponseTable createResponseTable(FeedbackQuestionAttributes question, List<FeedbackResponseAttributes> responsesBundleForRecipient, String recipientNameParam) { List<FeedbackResultsResponse> responses = new ArrayList<FeedbackResultsResponse>(); FeedbackQuestionDetails questionDetails = question.getQuestionDetails(); String recipientName = recipientNameParam; for (FeedbackResponseAttributes response : responsesBundleForRecipient) { String giverName = bundle.getGiverNameForResponse(response); String displayedGiverName; boolean isUserGiver = student.email.equals(response.giver); boolean isUserPartOfGiverTeam = student.team.equals(giverName); if (question.giverType == FeedbackParticipantType.TEAMS && isUserPartOfGiverTeam) { displayedGiverName = "Your Team (" + giverName + ")"; } else if (isUserGiver) { displayedGiverName = "You"; } else { displayedGiverName = giverName; } boolean isUserRecipient = student.email.equals(response.recipient); if (isUserGiver && !isUserRecipient) { // If the giver is the user, show the real name of the recipient // since the giver would know which recipient he/she gave the response to recipientName = bundle.getNameForEmail(response.recipient); } else if (!isUserGiver && !bundle.isRecipientVisible(response)) { // Hide anonymous recipient entirely to prevent student from guessing the identity // based on responses from other response givers recipientName = bundle.getAnonNameWithoutNumericalId(question.recipientType); } String answer = response.getResponseDetails().getAnswerHtmlStudentView(questionDetails); List<FeedbackResponseCommentRow> comments = createStudentFeedbackResultsResponseComments( response.getId()); responses.add(new FeedbackResultsResponse(displayedGiverName, answer, comments)); } return new FeedbackResultsResponseTable(recipientName, responses); }
FeedbackResultsResponseTable function(FeedbackQuestionAttributes question, List<FeedbackResponseAttributes> responsesBundleForRecipient, String recipientNameParam) { List<FeedbackResultsResponse> responses = new ArrayList<FeedbackResultsResponse>(); FeedbackQuestionDetails questionDetails = question.getQuestionDetails(); String recipientName = recipientNameParam; for (FeedbackResponseAttributes response : responsesBundleForRecipient) { String giverName = bundle.getGiverNameForResponse(response); String displayedGiverName; boolean isUserGiver = student.email.equals(response.giver); boolean isUserPartOfGiverTeam = student.team.equals(giverName); if (question.giverType == FeedbackParticipantType.TEAMS && isUserPartOfGiverTeam) { displayedGiverName = STR + giverName + ")"; } else if (isUserGiver) { displayedGiverName = "You"; } else { displayedGiverName = giverName; } boolean isUserRecipient = student.email.equals(response.recipient); if (isUserGiver && !isUserRecipient) { recipientName = bundle.getNameForEmail(response.recipient); } else if (!isUserGiver && !bundle.isRecipientVisible(response)) { recipientName = bundle.getAnonNameWithoutNumericalId(question.recipientType); } String answer = response.getResponseDetails().getAnswerHtmlStudentView(questionDetails); List<FeedbackResponseCommentRow> comments = createStudentFeedbackResultsResponseComments( response.getId()); responses.add(new FeedbackResultsResponse(displayedGiverName, answer, comments)); } return new FeedbackResultsResponseTable(recipientName, responses); }
/** * Creates a feedback results responses table for a recipient. * @param question Question for which the responses are generated * @param responsesBundleForRecipient All responses for the question having a particular recipient * @return Feedback results responses table for a question and a recipient */
Creates a feedback results responses table for a recipient
createResponseTable
{ "repo_name": "kguo901/teammates", "path": "src/main/java/teammates/ui/pagedata/StudentFeedbackResultsPageData.java", "license": "gpl-2.0", "size": 12222 }
[ "java.util.ArrayList", "java.util.List" ]
import java.util.ArrayList; import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,217,511
void drawDrawableAtCenterWithKeepAspectRatio( Drawable drawable, int x, int y, int width, int height); } private static class SurfaceCanvasImpl implements SurfaceCanvas { private static final int CLEAR_COLOR = 0x00000000; private final Canvas canvas; SurfaceCanvasImpl(Canvas canvas) { this.canvas = canvas; }
void drawDrawableAtCenterWithKeepAspectRatio( Drawable drawable, int x, int y, int width, int height); } private static class SurfaceCanvasImpl implements SurfaceCanvas { private static final int CLEAR_COLOR = 0x00000000; private final Canvas canvas; SurfaceCanvasImpl(Canvas canvas) { this.canvas = canvas; }
/** * Draws the given {@code drawable} at the center of the given region, * and this method scales the drawable to fit the given {@code height}, but it scales * horizontal direction to keep its aspect ratio. */
Draws the given drawable at the center of the given region, and this method scales the drawable to fit the given height, but it scales horizontal direction to keep its aspect ratio
drawDrawableAtCenterWithKeepAspectRatio
{ "repo_name": "kishikawakatsumi/Mozc-for-iOS", "path": "src/android/src/com/google/android/inputmethod/japanese/keyboard/KeyboardViewBackgroundSurface.java", "license": "apache-2.0", "size": 16893 }
[ "android.graphics.Canvas", "android.graphics.drawable.Drawable" ]
import android.graphics.Canvas; import android.graphics.drawable.Drawable;
import android.graphics.*; import android.graphics.drawable.*;
[ "android.graphics" ]
android.graphics;
1,963,731
@FIXVersion(introduced="5.0") @TagNumRef(tagNum=TagNum.ManualOrderIndicator) public Boolean getManualOrderIndicator() { return manualOrderIndicator; }
@FIXVersion(introduced="5.0") @TagNumRef(tagNum=TagNum.ManualOrderIndicator) Boolean function() { return manualOrderIndicator; }
/** * Message field getter. * @return field value */
Message field getter
getManualOrderIndicator
{ "repo_name": "marvisan/HadesFIX", "path": "Model/src/main/java/net/hades/fix/message/OrderModificationRequestMsg.java", "license": "gpl-3.0", "size": 149491 }
[ "net.hades.fix.message.anno.FIXVersion", "net.hades.fix.message.anno.TagNumRef", "net.hades.fix.message.type.TagNum" ]
import net.hades.fix.message.anno.FIXVersion; import net.hades.fix.message.anno.TagNumRef; import net.hades.fix.message.type.TagNum;
import net.hades.fix.message.anno.*; import net.hades.fix.message.type.*;
[ "net.hades.fix" ]
net.hades.fix;
1,390,321
private List<DatanodeStorageInfo> getValidLocations(Block block) { final List<DatanodeStorageInfo> locations = new ArrayList<DatanodeStorageInfo>(blocksMap.numNodes(block)); for(DatanodeStorageInfo storage : blocksMap.getStorages(block)) { final String storageID = storage.getStorageID(); // filter invalidate replicas if(!invalidateBlocks.contains(storage.getDatanodeDescriptor(), block)) { locations.add(storage); } } return locations; }
List<DatanodeStorageInfo> function(Block block) { final List<DatanodeStorageInfo> locations = new ArrayList<DatanodeStorageInfo>(blocksMap.numNodes(block)); for(DatanodeStorageInfo storage : blocksMap.getStorages(block)) { final String storageID = storage.getStorageID(); if(!invalidateBlocks.contains(storage.getDatanodeDescriptor(), block)) { locations.add(storage); } } return locations; }
/** * Get all valid locations of the block */
Get all valid locations of the block
getValidLocations
{ "repo_name": "songweijia/fffs", "path": "sources/hadoop-2.4.1-src/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java", "license": "apache-2.0", "size": 138554 }
[ "java.util.ArrayList", "java.util.List", "org.apache.hadoop.hdfs.protocol.Block" ]
import java.util.ArrayList; import java.util.List; import org.apache.hadoop.hdfs.protocol.Block;
import java.util.*; import org.apache.hadoop.hdfs.protocol.*;
[ "java.util", "org.apache.hadoop" ]
java.util; org.apache.hadoop;
1,886,449
void enterClassBody(@NotNull Java8Parser.ClassBodyContext ctx);
void enterClassBody(@NotNull Java8Parser.ClassBodyContext ctx);
/** * Enter a parse tree produced by {@link Java8Parser#classBody}. * * @param ctx the parse tree */
Enter a parse tree produced by <code>Java8Parser#classBody</code>
enterClassBody
{ "repo_name": "BigDaddy-Germany/WHOAMI", "path": "WHOAMI/src/de/aima13/whoami/modules/syntaxcheck/languages/antlrgen/Java8Listener.java", "license": "mit", "size": 97945 }
[ "org.antlr.v4.runtime.misc.NotNull" ]
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.misc.*;
[ "org.antlr.v4" ]
org.antlr.v4;
100,290
public void testCosine() throws Throwable { final Random rand = new Random( 6666 ); for( int cnt = 0 ; cnt < 10000 ; cnt++ ) { System.out.println( cnt ); final double a = 20.0 * ( rand.nextDouble() ) - 10.0; final double as = Math.cos( a ); final BigFixedPointElem<LrgPrecision> da = new BigFixedPointElem<LrgPrecision>( a , lrgPrecision ); final BigFixedPointElem<LrgPrecision> das = da.cos( LEVEL ); Assert.assertTrue( Math.abs( as - das.toDouble() ) < 1E-3 ); } }
void function() throws Throwable { final Random rand = new Random( 6666 ); for( int cnt = 0 ; cnt < 10000 ; cnt++ ) { System.out.println( cnt ); final double a = 20.0 * ( rand.nextDouble() ) - 10.0; final double as = Math.cos( a ); final BigFixedPointElem<LrgPrecision> da = new BigFixedPointElem<LrgPrecision>( a , lrgPrecision ); final BigFixedPointElem<LrgPrecision> das = da.cos( LEVEL ); Assert.assertTrue( Math.abs( as - das.toDouble() ) < 1E-3 ); } }
/** * Tests the ability to calculate cosines * @throws Throwable */
Tests the ability to calculate cosines
testCosine
{ "repo_name": "viridian1138/SimpleAlgebra_V2", "path": "src/test_simplealgebra/TestAtan2BigFixed.java", "license": "gpl-3.0", "size": 18390 }
[ "java.util.Random", "junit.framework.Assert" ]
import java.util.Random; import junit.framework.Assert;
import java.util.*; import junit.framework.*;
[ "java.util", "junit.framework" ]
java.util; junit.framework;
1,796,440
@Test public void helpWithColonTest() { for (List<String> candidates : getCandidatesLists("help :", true, -1)) { assertTrue(candidates.toString(), candidates.contains("read-resource")); } }
void function() { for (List<String> candidates : getCandidatesLists(STR, true, -1)) { assertTrue(candidates.toString(), candidates.contains(STR)); } }
/** * Checks CLI completion for "help :" command */
Checks CLI completion for "help :" command
helpWithColonTest
{ "repo_name": "aloubyansky/wildfly-core", "path": "testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/CliCompletionTestCase.java", "license": "lgpl-2.1", "size": 135212 }
[ "java.util.List", "org.junit.Assert" ]
import java.util.List; import org.junit.Assert;
import java.util.*; import org.junit.*;
[ "java.util", "org.junit" ]
java.util; org.junit;
2,110,656
public boolean fling(int velocityX, int velocityY) { if (mLayout == null) { Log.e(TAG, "Cannot fling without a LayoutManager set. " + "Call setLayoutManager with a non-null argument."); return false; } if (mLayoutFrozen) { return false; } final boolean canScrollHorizontal = mLayout.canScrollHorizontally(); final boolean canScrollVertical = mLayout.canScrollVertically(); if (!canScrollHorizontal || Math.abs(velocityX) < mMinFlingVelocity) { velocityX = 0; } if (!canScrollVertical || Math.abs(velocityY) < mMinFlingVelocity) { velocityY = 0; } if (velocityX == 0 && velocityY == 0) { // If we don't have any velocity, return false return false; } if (!dispatchNestedPreFling(velocityX, velocityY)) { final boolean canScroll = canScrollHorizontal || canScrollVertical; dispatchNestedFling(velocityX, velocityY, canScroll); if (mOnFlingListener != null && mOnFlingListener.onFling(velocityX, velocityY)) { return true; } if (canScroll) { int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE; if (canScrollHorizontal) { nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL; } if (canScrollVertical) { nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL; } startNestedScroll(nestedScrollAxis, TYPE_NON_TOUCH); velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity)); velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity)); mViewFlinger.fling(velocityX, velocityY); return true; } } return false; }
boolean function(int velocityX, int velocityY) { if (mLayout == null) { Log.e(TAG, STR + STR); return false; } if (mLayoutFrozen) { return false; } final boolean canScrollHorizontal = mLayout.canScrollHorizontally(); final boolean canScrollVertical = mLayout.canScrollVertically(); if (!canScrollHorizontal Math.abs(velocityX) < mMinFlingVelocity) { velocityX = 0; } if (!canScrollVertical Math.abs(velocityY) < mMinFlingVelocity) { velocityY = 0; } if (velocityX == 0 && velocityY == 0) { return false; } if (!dispatchNestedPreFling(velocityX, velocityY)) { final boolean canScroll = canScrollHorizontal canScrollVertical; dispatchNestedFling(velocityX, velocityY, canScroll); if (mOnFlingListener != null && mOnFlingListener.onFling(velocityX, velocityY)) { return true; } if (canScroll) { int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE; if (canScrollHorizontal) { nestedScrollAxis = ViewCompat.SCROLL_AXIS_HORIZONTAL; } if (canScrollVertical) { nestedScrollAxis = ViewCompat.SCROLL_AXIS_VERTICAL; } startNestedScroll(nestedScrollAxis, TYPE_NON_TOUCH); velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity)); velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity)); mViewFlinger.fling(velocityX, velocityY); return true; } } return false; }
/** * Begin a standard fling with an initial velocity along each axis in pixels per second. * If the velocity given is below the system-defined minimum this method will return false * and no fling will occur. * * @param velocityX Initial horizontal velocity in pixels per second * @param velocityY Initial vertical velocity in pixels per second * @return true if the fling was started, false if the velocity was too low to fling or * LayoutManager does not support scrolling in the axis fling is issued. * * @see LayoutManager#canScrollVertically() * @see LayoutManager#canScrollHorizontally() */
Begin a standard fling with an initial velocity along each axis in pixels per second. If the velocity given is below the system-defined minimum this method will return false and no fling will occur
fling
{ "repo_name": "aosp-mirror/platform_frameworks_support", "path": "v7/recyclerview/src/main/java/androidx/recyclerview/widget/RecyclerView.java", "license": "apache-2.0", "size": 582575 }
[ "android.util.Log", "androidx.core.view.ViewCompat" ]
import android.util.Log; import androidx.core.view.ViewCompat;
import android.util.*; import androidx.core.view.*;
[ "android.util", "androidx.core" ]
android.util; androidx.core;
1,942,927
@Test public void updateChallengeActivityTest() throws ApiException { Long id = null; Long challengeId = null; ChallengeActivityResource challengeActivityResource = null; Boolean validateSettings = null; api.updateChallengeActivity(id, challengeId, challengeActivityResource, validateSettings); // TODO: test validations }
void function() throws ApiException { Long id = null; Long challengeId = null; ChallengeActivityResource challengeActivityResource = null; Boolean validateSettings = null; api.updateChallengeActivity(id, challengeId, challengeActivityResource, validateSettings); }
/** * Update a challenge activity * * A challenge can have multiple instances of the same activity and thus the id used is of the specific entry within the challenge. &lt;br&gt;&lt;br&gt;&lt;b&gt;Permissions Needed:&lt;/b&gt; CHALLENGES_ADMIN * * @throws ApiException * if the Api call fails */
Update a challenge activity A challenge can have multiple instances of the same activity and thus the id used is of the specific entry within the challenge. &lt;br&gt;&lt;br&gt;&lt;b&gt;Permissions Needed:&lt;/b&gt; CHALLENGES_ADMIN
updateChallengeActivityTest
{ "repo_name": "knetikmedia/knetikcloud-java-client", "path": "src/test/java/com/knetikcloud/api/CampaignsChallengesApiTest.java", "license": "apache-2.0", "size": 13659 }
[ "com.knetikcloud.client.ApiException", "com.knetikcloud.model.ChallengeActivityResource" ]
import com.knetikcloud.client.ApiException; import com.knetikcloud.model.ChallengeActivityResource;
import com.knetikcloud.client.*; import com.knetikcloud.model.*;
[ "com.knetikcloud.client", "com.knetikcloud.model" ]
com.knetikcloud.client; com.knetikcloud.model;
1,636,638
@RequestMapping(method = RequestMethod.GET, path = "/hello") public SampleRESTResource sayHello( @RequestParam(value = "name", required = true, defaultValue = "World") String name) { return new SampleRESTResource(counter.incrementAndGet(), String.format(HELLO_STR, name)); }
@RequestMapping(method = RequestMethod.GET, path = STR) SampleRESTResource function( @RequestParam(value = "name", required = true, defaultValue = "World") String name) { return new SampleRESTResource(counter.incrementAndGet(), String.format(HELLO_STR, name)); }
/** * For a given input 'name', output the JSON form of "Hello 'name'". * * @param name input * @return SampleRESTResource */
For a given input 'name', output the JSON form of "Hello 'name'"
sayHello
{ "repo_name": "sachinlala/SimplifyLearning", "path": "sample-rest-service/src/main/java/com/sl/sample/rest/service/SampleRESTController.java", "license": "mit", "size": 2118 }
[ "org.springframework.web.bind.annotation.RequestMapping", "org.springframework.web.bind.annotation.RequestMethod", "org.springframework.web.bind.annotation.RequestParam" ]
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.*;
[ "org.springframework.web" ]
org.springframework.web;
728,812
public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); }
void function(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); }
/** * Remove a property change listener from this component. * * @param listener The listener to remove */
Remove a property change listener from this component
removePropertyChangeListener
{ "repo_name": "NorthFacing/step-by-Java", "path": "fra-tomcat/fra-tomcat-analysis/source/book01/HowTomcatWorks/src/org/apache/catalina/core/StandardServer.java", "license": "gpl-2.0", "size": 64233 }
[ "java.beans.PropertyChangeListener" ]
import java.beans.PropertyChangeListener;
import java.beans.*;
[ "java.beans" ]
java.beans;
2,182,623
public static Current read(InputStream input) { throw new NO_IMPLEMENT(); }
static Current function(InputStream input) { throw new NO_IMPLEMENT(); }
/** * Not supported for compatibility reasons. * * @specnote Not supported by Sun at least till jdk 1.4 inclusive. * * @throws NO_IMPLEMENT always. */
Not supported for compatibility reasons
read
{ "repo_name": "shaotuanchen/sunflower_exp", "path": "tools/source/gcc-4.2.4/libjava/classpath/org/omg/PortableServer/CurrentHelper.java", "license": "bsd-3-clause", "size": 4156 }
[ "org.omg.CORBA" ]
import org.omg.CORBA;
import org.omg.*;
[ "org.omg" ]
org.omg;
2,258,387
public void btnCancel_Click (Button.ClickEvent event) { dialogResultSelected = DialogResult.CANCEL; this.parentWindow.removeWindow(this); }
void function (Button.ClickEvent event) { dialogResultSelected = DialogResult.CANCEL; this.parentWindow.removeWindow(this); }
/** * Cancel result button */
Cancel result button
btnCancel_Click
{ "repo_name": "thingtrack/konekti", "path": "core/konekti.view.web.form/src/main/java/com/thingtrack/konekti/view/web/form/selector/ProductSelectorWindow.java", "license": "apache-2.0", "size": 7914 }
[ "com.vaadin.ui.Button" ]
import com.vaadin.ui.Button;
import com.vaadin.ui.*;
[ "com.vaadin.ui" ]
com.vaadin.ui;
502,905
@Test public void pctEncodeWithReservedCharacters() { String withReserved = "/api/user@host:port#section[a-z]/data"; String encoded = UriUtils.encode(withReserved, UTF_8, true); assertThat(encoded).isEqualTo("/api/user@host:port#section[a-z]/data"); }
void function() { String withReserved = STR; String encoded = UriUtils.encode(withReserved, UTF_8, true); assertThat(encoded).isEqualTo(STR); }
/** * pct-encode preserving reserved characters. */
pct-encode preserving reserved characters
pctEncodeWithReservedCharacters
{ "repo_name": "Netflix/feign", "path": "core/src/test/java/feign/template/UriUtilsTest.java", "license": "apache-2.0", "size": 1522 }
[ "org.assertj.core.api.Assertions" ]
import org.assertj.core.api.Assertions;
import org.assertj.core.api.*;
[ "org.assertj.core" ]
org.assertj.core;
1,709,382
protected void handleEnd(Collection<T> results) throws IOException { // do nothing - overridable by subclass } //----------------------------------------------------------------------- public static class CancelException extends IOException { private static final long serialVersionUID = 1347339620135041008L; private final File file; private final int depth; public CancelException(File file, int depth) { this("Operation Cancelled", file, depth); } public CancelException(String message, File file, int depth) { super(message); this.file = file; this.depth = depth; }
void function(Collection<T> results) throws IOException { } public static class CancelException extends IOException { private static final long serialVersionUID = 1347339620135041008L; private final File file; private final int depth; public CancelException(File file, int depth) { this(STR, file, depth); } public CancelException(String message, File file, int depth) { super(message); this.file = file; this.depth = depth; }
/** * Overridable callback method invoked at the end of processing. * <p> * This implementation does nothing. * * @param results the collection of result objects, may be updated * @throws IOException if an I/O Error occurs */
Overridable callback method invoked at the end of processing. This implementation does nothing
handleEnd
{ "repo_name": "fesch/Moenagade", "path": "src/org/apache/commons/io/DirectoryWalker.java", "license": "gpl-3.0", "size": 26246 }
[ "java.io.File", "java.io.IOException", "java.util.Collection" ]
import java.io.File; import java.io.IOException; import java.util.Collection;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
1,319,414
public static List<Entity> getEntitiesFromID(World world, List<Integer> ids) { return ids.stream() .map(world::getEntityByID) .collect(Collectors.toList()); }
static List<Entity> function(World world, List<Integer> ids) { return ids.stream() .map(world::getEntityByID) .collect(Collectors.toList()); }
/** * Returns a list of loaded entities whose id's match the ones provided. * * @param world the world the entities are in. * @param ids List of Entity id's * @return list of Entity's */
Returns a list of loaded entities whose id's match the ones provided
getEntitiesFromID
{ "repo_name": "MinecoloniesDevs/Minecolonies", "path": "src/main/java/com/minecolonies/util/EntityUtils.java", "license": "gpl-3.0", "size": 7802 }
[ "java.util.List", "java.util.stream.Collectors", "net.minecraft.entity.Entity", "net.minecraft.world.World" ]
import java.util.List; import java.util.stream.Collectors; import net.minecraft.entity.Entity; import net.minecraft.world.World;
import java.util.*; import java.util.stream.*; import net.minecraft.entity.*; import net.minecraft.world.*;
[ "java.util", "net.minecraft.entity", "net.minecraft.world" ]
java.util; net.minecraft.entity; net.minecraft.world;
2,902,780
public static File getCameraStorageDirectory(Context ctx) { File albumDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), ctx.getResources().getString(R.string.camera_storage_directory_name)); if (!albumDir.exists()) { albumDir.mkdirs(); } return albumDir; }
static File function(Context ctx) { File albumDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), ctx.getResources().getString(R.string.camera_storage_directory_name)); if (!albumDir.exists()) { albumDir.mkdirs(); } return albumDir; }
/** * Returns the directory file where pictures are stored. */
Returns the directory file where pictures are stored
getCameraStorageDirectory
{ "repo_name": "alexjlockwood/scouting-manager-2013", "path": "ScoutingManager/src/edu/cmu/girlsofsteel/scouting/util/CameraUtil.java", "license": "mit", "size": 5697 }
[ "android.content.Context", "android.os.Environment", "java.io.File" ]
import android.content.Context; import android.os.Environment; import java.io.File;
import android.content.*; import android.os.*; import java.io.*;
[ "android.content", "android.os", "java.io" ]
android.content; android.os; java.io;
1,336,298
public void createModel() { URI resourceURI = EditUIUtil.getURI(getEditorInput(), editingDomain.getResourceSet().getURIConverter()); Exception exception = null; Resource resource = null; try { // Load the resource through the editing domain. // resource = editingDomain.getResourceSet().getResource(resourceURI, true); } catch (Exception e) { exception = e; resource = editingDomain.getResourceSet().getResource(resourceURI, false); } Diagnostic diagnostic = analyzeResourceProblems(resource, exception); if (diagnostic.getSeverity() != Diagnostic.OK) { resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception)); } editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter); }
void function() { URI resourceURI = EditUIUtil.getURI(getEditorInput(), editingDomain.getResourceSet().getURIConverter()); Exception exception = null; Resource resource = null; try { } catch (Exception e) { exception = e; resource = editingDomain.getResourceSet().getResource(resourceURI, false); } Diagnostic diagnostic = analyzeResourceProblems(resource, exception); if (diagnostic.getSeverity() != Diagnostic.OK) { resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception)); } editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter); }
/** * This is the method called to load a resource into the editing domain's resource set based on the editor's input. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
This is the method called to load a resource into the editing domain's resource set based on the editor's input.
createModel
{ "repo_name": "netuh/DecodePlatformPlugin", "path": "br.ufpe.ines.decode/bundles/br.ufpe.ines.decode.model.editor/src/br/ufpe/ines/decode/decode/artifacts/questionnaire/presentation/QuestionnaireEditor.java", "license": "gpl-3.0", "size": 46459 }
[ "org.eclipse.emf.common.util.Diagnostic", "org.eclipse.emf.ecore.resource.Resource", "org.eclipse.emf.edit.ui.util.EditUIUtil" ]
import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.emf.common.util.*; import org.eclipse.emf.ecore.resource.*; import org.eclipse.emf.edit.ui.util.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
2,270,611
ArrayList calls = (ArrayList)m_invocations.get(method); if (calls == null) { calls = new ArrayList(); m_invocations.put(method, calls); } return calls; }
ArrayList calls = (ArrayList)m_invocations.get(method); if (calls == null) { calls = new ArrayList(); m_invocations.put(method, calls); } return calls; }
/** * Returns a list of all recorded calls to the given method.<p> * * @param method the method to get the recorded calls for * * @return a list of all recorded calls to the given method */
Returns a list of all recorded calls to the given method
getCalls
{ "repo_name": "victos/opencms-core", "path": "test/org/opencms/flex/TestCmsFlexResponse.java", "license": "lgpl-2.1", "size": 13746 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
984,856
public void validatePublicVoidNoArg(boolean isStatic, List<Throwable> errors) { validatePublicVoid(isStatic, errors); if (fMethod.getParameterTypes().length != 0) { errors.add(new Exception("Method " + fMethod.getName() + " should have no parameters")); } }
void function(boolean isStatic, List<Throwable> errors) { validatePublicVoid(isStatic, errors); if (fMethod.getParameterTypes().length != 0) { errors.add(new Exception(STR + fMethod.getName() + STR)); } }
/** * Adds to {@code errors} if this method: * <ul> * <li>is not public, or * <li>takes parameters, or * <li>returns something other than void, or * <li>is static (given {@code isStatic is false}), or * <li>is not static (given {@code isStatic is true}). */
Adds to errors if this method: is not public, or takes parameters, or returns something other than void, or is static (given isStatic is false), or is not static (given isStatic is true)
validatePublicVoidNoArg
{ "repo_name": "berlinbrown/SourceCodeAnalysisDatabase", "path": "test-coverage-example/src/main/java/org/junit/runners/model/FrameworkMethod.java", "license": "bsd-3-clause", "size": 6361 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,215,449
public void clearCurrentUser(Context context) throws AuthException { synchronized (this) { clearUser(context); currentUser = null; } }
void function(Context context) throws AuthException { synchronized (this) { clearUser(context); currentUser = null; } }
/** * Clear current user. * * @param context * @throws AuthException in case it could not be cleared. */
Clear current user
clearCurrentUser
{ "repo_name": "BullshitPingu/Guide7", "path": "java-app/app/src/main/java/de/be/thaw/auth/Auth.java", "license": "apache-2.0", "size": 6345 }
[ "android.content.Context", "de.be.thaw.auth.exception.AuthException" ]
import android.content.Context; import de.be.thaw.auth.exception.AuthException;
import android.content.*; import de.be.thaw.auth.exception.*;
[ "android.content", "de.be.thaw" ]
android.content; de.be.thaw;
2,076,435
protected NodeFigure createMainFigure() { NodeFigure figure = createNodePlate(); figure.setLayoutManager(new ToolbarLayout(true)); IFigure shape = createNodeShape(); figure.add(shape); contentPane = setupContentPane(shape); return figure; }
NodeFigure function() { NodeFigure figure = createNodePlate(); figure.setLayoutManager(new ToolbarLayout(true)); IFigure shape = createNodeShape(); figure.add(shape); contentPane = setupContentPane(shape); return figure; }
/** * Creates figure for this edit part. * * Body of this method does not depend on settings in generation model * so you may safely remove <i>generated</i> tag and modify it. * * @generated NOT */
Creates figure for this edit part. Body of this method does not depend on settings in generation model so you may safely remove generated tag and modify it
createMainFigure
{ "repo_name": "rajeevanv89/developer-studio", "path": "esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/parts/DBReportMediatorEditPart.java", "license": "apache-2.0", "size": 11196 }
[ "org.eclipse.draw2d.IFigure", "org.eclipse.draw2d.ToolbarLayout", "org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure" ]
import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.ToolbarLayout; import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.draw2d.*; import org.eclipse.gmf.runtime.gef.ui.figures.*;
[ "org.eclipse.draw2d", "org.eclipse.gmf" ]
org.eclipse.draw2d; org.eclipse.gmf;
262,448
@VisibleForTesting State handleMessagingStartResponse(ChannelHandlerContext ctx, ByteBuf in) throws IOException { ThirdHandshakeMessage msg = ThirdHandshakeMessage.maybeDecode(in); if (msg == null) return State.AWAIT_MESSAGING_START_RESPONSE; logger.trace("received third handshake message from peer {}, message = {}", ctx.channel().remoteAddress(), msg); if (handshakeTimeout != null) { handshakeTimeout.cancel(false); handshakeTimeout = null; } int maxVersion = msg.messagingVersion; if (maxVersion > MessagingService.current_version) { logger.error("peer wants to use a messaging version higher ({}) than what this node supports ({})", maxVersion, MessagingService.current_version); ctx.close(); return State.HANDSHAKE_FAIL; } // record the (true) version of the endpoint InetAddressAndPort from = msg.address; MessagingService.instance().setVersion(from, maxVersion); if (logger.isTraceEnabled()) logger.trace("Set version for {} to {} (will use {})", from, maxVersion, MessagingService.instance().getVersion(from)); setupMessagingPipeline(ctx.pipeline(), from, compressed, version); return State.HANDSHAKE_COMPLETE; }
State handleMessagingStartResponse(ChannelHandlerContext ctx, ByteBuf in) throws IOException { ThirdHandshakeMessage msg = ThirdHandshakeMessage.maybeDecode(in); if (msg == null) return State.AWAIT_MESSAGING_START_RESPONSE; logger.trace(STR, ctx.channel().remoteAddress(), msg); if (handshakeTimeout != null) { handshakeTimeout.cancel(false); handshakeTimeout = null; } int maxVersion = msg.messagingVersion; if (maxVersion > MessagingService.current_version) { logger.error(STR, maxVersion, MessagingService.current_version); ctx.close(); return State.HANDSHAKE_FAIL; } InetAddressAndPort from = msg.address; MessagingService.instance().setVersion(from, maxVersion); if (logger.isTraceEnabled()) logger.trace(STR, from, maxVersion, MessagingService.instance().getVersion(from)); setupMessagingPipeline(ctx.pipeline(), from, compressed, version); return State.HANDSHAKE_COMPLETE; }
/** * Handles the third (and last) message in the internode messaging handshake protocol. Grabs the protocol version and * IP addr the peer wants to use. */
Handles the third (and last) message in the internode messaging handshake protocol. Grabs the protocol version and IP addr the peer wants to use
handleMessagingStartResponse
{ "repo_name": "aweisberg/cassandra", "path": "src/java/org/apache/cassandra/net/async/InboundHandshakeHandler.java", "license": "apache-2.0", "size": 12841 }
[ "io.netty.buffer.ByteBuf", "io.netty.channel.ChannelHandlerContext", "java.io.IOException", "org.apache.cassandra.locator.InetAddressAndPort", "org.apache.cassandra.net.MessagingService", "org.apache.cassandra.net.async.HandshakeProtocol" ]
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import org.apache.cassandra.locator.InetAddressAndPort; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.net.async.HandshakeProtocol;
import io.netty.buffer.*; import io.netty.channel.*; import java.io.*; import org.apache.cassandra.locator.*; import org.apache.cassandra.net.*; import org.apache.cassandra.net.async.*;
[ "io.netty.buffer", "io.netty.channel", "java.io", "org.apache.cassandra" ]
io.netty.buffer; io.netty.channel; java.io; org.apache.cassandra;
2,459,163
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) { Rect rect = getFramingRectInPreview(); if (rect == null) { return null; } // Go ahead and assume it's YUV rather than die. return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(), false); }
PlanarYUVLuminanceSource function(byte[] data, int width, int height) { Rect rect = getFramingRectInPreview(); if (rect == null) { return null; } return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(), false); }
/** * A factory method to build the appropriate LuminanceSource object based on * the format of the preview buffers, as described by Camera.Parameters. * * @param data * A preview frame. * @param width * The width of the image. * @param height * The height of the image. * @return A PlanarYUVLuminanceSource instance. */
A factory method to build the appropriate LuminanceSource object based on the format of the preview buffers, as described by Camera.Parameters
buildLuminanceSource
{ "repo_name": "YLBFDEV/zxing", "path": "android/src/com/google/zxing/client/android/camera/CameraManager.java", "license": "apache-2.0", "size": 11638 }
[ "android.graphics.Rect", "com.google.zxing.PlanarYUVLuminanceSource" ]
import android.graphics.Rect; import com.google.zxing.PlanarYUVLuminanceSource;
import android.graphics.*; import com.google.zxing.*;
[ "android.graphics", "com.google.zxing" ]
android.graphics; com.google.zxing;
1,988,417
public ScheduledExecutorConfig setCapacity(int capacity) { checkNotNegative(capacity, "capacity can't be smaller than 0"); this.capacity = capacity; return this; }
ScheduledExecutorConfig function(int capacity) { checkNotNegative(capacity, STR); this.capacity = capacity; return this; }
/** * Sets the capacity of the executor * The capacity represents the maximum number of tasks that a scheduler can have at any given point in time per partition. * If this is set to 0 then there is no limit * * @param capacity the capacity of the executor * @return This executor config instance. */
Sets the capacity of the executor The capacity represents the maximum number of tasks that a scheduler can have at any given point in time per partition. If this is set to 0 then there is no limit
setCapacity
{ "repo_name": "lmjacksoniii/hazelcast", "path": "hazelcast/src/main/java/com/hazelcast/config/ScheduledExecutorConfig.java", "license": "apache-2.0", "size": 6412 }
[ "com.hazelcast.util.Preconditions" ]
import com.hazelcast.util.Preconditions;
import com.hazelcast.util.*;
[ "com.hazelcast.util" ]
com.hazelcast.util;
1,326,260
public List<Replica> getReplicas(String nodeName) { return nodeNameReplicas.get(nodeName); }
List<Replica> function(String nodeName) { return nodeNameReplicas.get(nodeName); }
/** * Get the list of replicas hosted on the given node or <code>null</code> if none. */
Get the list of replicas hosted on the given node or <code>null</code> if none
getReplicas
{ "repo_name": "DavidGutknecht/elexis-3-base", "path": "bundles/org.apache.solr/src/org/apache/solr/common/cloud/DocCollection.java", "license": "epl-1.0", "size": 14101 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
802,442
public Set<Action> getStartActions(){ HashSet<Action> actionSet = new HashSet<Action>(); for(Action action : this.actionMap.values()){ if(action.getBeginStatId()==null) actionSet.add(action); } return actionSet; }
Set<Action> function(){ HashSet<Action> actionSet = new HashSet<Action>(); for(Action action : this.actionMap.values()){ if(action.getBeginStatId()==null) actionSet.add(action); } return actionSet; }
/** * (non-Javadoc) * <p> Title:getStartActions</p> * @return * @see com.sogou.qadev.service.cynthia.bean.Flow#getStartActions() */
(non-Javadoc) Title:getStartActions
getStartActions
{ "repo_name": "wendygithub2015/Cynthia", "path": "src/main/java/com/sogou/qadev/service/cynthia/bean/impl/FlowImpl.java", "license": "gpl-2.0", "size": 46365 }
[ "com.sogou.qadev.service.cynthia.bean.Action", "java.util.HashSet", "java.util.Set" ]
import com.sogou.qadev.service.cynthia.bean.Action; import java.util.HashSet; import java.util.Set;
import com.sogou.qadev.service.cynthia.bean.*; import java.util.*;
[ "com.sogou.qadev", "java.util" ]
com.sogou.qadev; java.util;
105,795
@Override public RevCommit getCommit(ObjectId id) { return database.getCommit(id); }
RevCommit function(ObjectId id) { return database.getCommit(id); }
/** * Pass through to the original {@link StagingDatabase}. */
Pass through to the original <code>StagingDatabase</code>
getCommit
{ "repo_name": "state-hiu/GeoGit", "path": "src/core/src/main/java/org/geogit/storage/TransactionStagingDatabase.java", "license": "bsd-3-clause", "size": 7545 }
[ "org.geogit.api.ObjectId", "org.geogit.api.RevCommit" ]
import org.geogit.api.ObjectId; import org.geogit.api.RevCommit;
import org.geogit.api.*;
[ "org.geogit.api" ]
org.geogit.api;
2,340,929
public void add(TableOperationError operationError) throws ParseException, MobileServiceLocalStoreException { this.mSyncLock.writeLock().lock(); try { this.mStore.upsert(OPERATION_ERROR_TABLE, serialize(operationError), false); this.mList.add(operationError); } finally { this.mSyncLock.writeLock().unlock(); } }
void function(TableOperationError operationError) throws ParseException, MobileServiceLocalStoreException { this.mSyncLock.writeLock().lock(); try { this.mStore.upsert(OPERATION_ERROR_TABLE, serialize(operationError), false); this.mList.add(operationError); } finally { this.mSyncLock.writeLock().unlock(); } }
/** * Adds a new table operation error * * @param operationError the table operation error * @throws java.text.ParseException * @throws MobileServiceLocalStoreException */
Adds a new table operation error
add
{ "repo_name": "cmatskas/azure-mobile-services", "path": "sdk/android/src/sdk/src/main/java/com/microsoft/windowsazure/mobileservices/table/sync/queue/OperationErrorList.java", "license": "apache-2.0", "size": 8704 }
[ "com.microsoft.windowsazure.mobileservices.table.sync.localstore.MobileServiceLocalStoreException", "com.microsoft.windowsazure.mobileservices.table.sync.operations.TableOperationError", "java.text.ParseException" ]
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.MobileServiceLocalStoreException; import com.microsoft.windowsazure.mobileservices.table.sync.operations.TableOperationError; import java.text.ParseException;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.*; import com.microsoft.windowsazure.mobileservices.table.sync.operations.*; import java.text.*;
[ "com.microsoft.windowsazure", "java.text" ]
com.microsoft.windowsazure; java.text;
950,084
public static long hashLong(final long in, final long seed) { return hash(in, seed); }
static long function(final long in, final long seed) { return hash(in, seed); }
/** * Returns a 64-bit hash from a single long. This method has been optimized for speed when only * a single hash of a long is required. * @param in A long. * @param seed A long valued seed. * @return the hash. */
Returns a 64-bit hash from a single long. This method has been optimized for speed when only a single hash of a long is required
hashLong
{ "repo_name": "DataSketches/memory", "path": "datasketches-memory-java8/src/main/java/org/apache/datasketches/memory/XxHash.java", "license": "apache-2.0", "size": 7411 }
[ "org.apache.datasketches.memory.internal.XxHash64" ]
import org.apache.datasketches.memory.internal.XxHash64;
import org.apache.datasketches.memory.internal.*;
[ "org.apache.datasketches" ]
org.apache.datasketches;
769,726
protected void init() { if (jobManager == null) { String jndiKey = componentID + ".jobManager"; // see AsyncServlet try { Context ctx = new InitialContext(); this.jobManager = (JobManager) ctx.lookup(jndiKey); if (jobManager != null) { log.debug("found: " + jndiKey +"=" + jobManager.getClass().getName()); } else { log.error("BUG: failed to find " + jndiKey + " via JNDI"); } } catch (NamingException ex) { log.error("BUG: failed to find " + jndiKey + " via JNDI", ex); } } }
void function() { if (jobManager == null) { String jndiKey = componentID + STR; try { Context ctx = new InitialContext(); this.jobManager = (JobManager) ctx.lookup(jndiKey); if (jobManager != null) { log.debug(STR + jndiKey +"=" + jobManager.getClass().getName()); } else { log.error(STR + jndiKey + STR); } } catch (NamingException ex) { log.error(STR + jndiKey + STR, ex); } } }
/** * Initialisation that cannot be performed in the constructor. This method must * be called at the start of doAction in all subclasses. */
Initialisation that cannot be performed in the constructor. This method must be called at the start of doAction in all subclasses
init
{ "repo_name": "opencadc/uws", "path": "cadc-uws-server/src/main/java/ca/nrc/cadc/uws/web/JobAction.java", "license": "agpl-3.0", "size": 8794 }
[ "ca.nrc.cadc.uws.server.JobManager", "javax.naming.Context", "javax.naming.InitialContext", "javax.naming.NamingException" ]
import ca.nrc.cadc.uws.server.JobManager; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException;
import ca.nrc.cadc.uws.server.*; import javax.naming.*;
[ "ca.nrc.cadc", "javax.naming" ]
ca.nrc.cadc; javax.naming;
161,777
public void addCoordListFrom(JsonBlock inChild) { if (_type == BlockType.NONE && _nextField == Expectation.COORDS && inChild._type == BlockType.ISPOINTLIST) { _coordList = inChild._coordList; _type = BlockType.HASPOINTLIST; } else if ((_type == BlockType.NONE || _type == BlockType.ISPOINTLIST) && !_hasNonNumbers && inChild._type == BlockType.ISPOINTLIST) { if (_coordList == null) { _coordList = new ArrayList<ArrayList<String>>(); } _coordList.addAll(inChild._coordList); _type = BlockType.ISPOINTLIST; } }
void function(JsonBlock inChild) { if (_type == BlockType.NONE && _nextField == Expectation.COORDS && inChild._type == BlockType.ISPOINTLIST) { _coordList = inChild._coordList; _type = BlockType.HASPOINTLIST; } else if ((_type == BlockType.NONE _type == BlockType.ISPOINTLIST) && !_hasNonNumbers && inChild._type == BlockType.ISPOINTLIST) { if (_coordList == null) { _coordList = new ArrayList<ArrayList<String>>(); } _coordList.addAll(inChild._coordList); _type = BlockType.ISPOINTLIST; } }
/** * Child block has finished processing a list of point coordinates * @param inChild child block */
Child block has finished processing a list of point coordinates
addCoordListFrom
{ "repo_name": "activityworkshop/GpsPrune", "path": "src/tim/prune/load/json/JsonBlock.java", "license": "gpl-2.0", "size": 6211 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
687,057
public static CharsetStrategy getCharsetStrategy(String charsetStrategy) { if (charsetStrategy == null || charsetStrategy.equalsIgnoreCase("systemdefault")) { return new FixedCharsetStrategy(Charset.defaultCharset()); } else if (charsetStrategy.equalsIgnoreCase("detect")) { return new DetectCharsetStrategy(); } else { return new FixedCharsetStrategy(Charset.forName(charsetStrategy)); } }
static CharsetStrategy function(String charsetStrategy) { if (charsetStrategy == null charsetStrategy.equalsIgnoreCase(STR)) { return new FixedCharsetStrategy(Charset.defaultCharset()); } else if (charsetStrategy.equalsIgnoreCase(STR)) { return new DetectCharsetStrategy(); } else { return new FixedCharsetStrategy(Charset.forName(charsetStrategy)); } }
/** * Returns a charset value based on the input string; meant to be used when reading from property files. * "systemdefault" means to use the default system * "detect" means to automatically detect * Otherwise, it will assume standard values from the Java encodings. */
Returns a charset value based on the input string; meant to be used when reading from property files. "systemdefault" means to use the default system "detect" means to automatically detect Otherwise, it will assume standard values from the Java encodings
getCharsetStrategy
{ "repo_name": "goldmansachs/obevo", "path": "obevo-core/src/main/java/com/gs/obevo/util/vfs/CharsetStrategyFactory.java", "license": "apache-2.0", "size": 1773 }
[ "java.nio.charset.Charset" ]
import java.nio.charset.Charset;
import java.nio.charset.*;
[ "java.nio" ]
java.nio;
528,900
public Vector<Object> getBCMPdelaysWithNonRationalServiceDistribution() { return BCMPdelaysWithNonRationalServiceDistribution; }
Vector<Object> function() { return BCMPdelaysWithNonRationalServiceDistribution; }
/** * Use it to get a Vector<Object> containing the keys of delays with * at least a service time distribution with a non rational Laplace * transform * @return a Vector<Object> containing the keys of delays with * at least a service time distribution with a non rational Laplace * transform */
Use it to get a Vector containing the keys of delays with at least a service time distribution with a non rational Laplace transform
getBCMPdelaysWithNonRationalServiceDistribution
{ "repo_name": "HOMlab/QN-ACTR-Release", "path": "QN-ACTR Java/src/jmt/gui/common/controller/ModelChecker.java", "license": "lgpl-3.0", "size": 87268 }
[ "java.util.Vector" ]
import java.util.Vector;
import java.util.*;
[ "java.util" ]
java.util;
1,200,120
@SynchronizedRpcRequest void syncDeleteResource(CmsUUID structureId, AsyncCallback<Void> callback);
void syncDeleteResource(CmsUUID structureId, AsyncCallback<Void> callback);
/** * Deletes a resource from the VFS.<p> * * @param structureId the structure id of the resource to delete * @param callback the callback */
Deletes a resource from the VFS
syncDeleteResource
{ "repo_name": "alkacon/opencms-core", "path": "src/org/opencms/gwt/shared/rpc/I_CmsVfsServiceAsync.java", "license": "lgpl-2.1", "size": 15689 }
[ "com.google.gwt.user.client.rpc.AsyncCallback", "org.opencms.util.CmsUUID" ]
import com.google.gwt.user.client.rpc.AsyncCallback; import org.opencms.util.CmsUUID;
import com.google.gwt.user.client.rpc.*; import org.opencms.util.*;
[ "com.google.gwt", "org.opencms.util" ]
com.google.gwt; org.opencms.util;
682,611
protected Cover labelPropagationPhase(CustomGraph graph, List<Node> leaders) throws InterruptedException { Map<Node, Map<Node, Integer>> communities = new HashMap<Node, Map<Node, Integer>>(); Map<Node, Integer> communityMemberships; Map<Node, Map<Node, Integer>> bestValidSolution = null; double upperProfitabilityBound = 1; double lowerProfitabilityBound = 0; for(int i=0; i<10; i++) { double profitabilityThreshold = (upperProfitabilityBound + lowerProfitabilityBound) / 2d; communities = new HashMap<Node, Map<Node, Integer>>(); for (Node leader : leaders) { communityMemberships = executeLabelPropagation(graph, leader, profitabilityThreshold); communities.put(leader, communityMemberships); } if(areAllNodesAssigned(graph, communities)) { bestValidSolution = communities; lowerProfitabilityBound = profitabilityThreshold; } else { upperProfitabilityBound = profitabilityThreshold; } } if(bestValidSolution == null) { for (Node leader : leaders) { communityMemberships = executeLabelPropagation(graph, leader, 0); communities.put(leader, communityMemberships); bestValidSolution = communities; } } return getMembershipDegrees(graph, bestValidSolution); }
Cover function(CustomGraph graph, List<Node> leaders) throws InterruptedException { Map<Node, Map<Node, Integer>> communities = new HashMap<Node, Map<Node, Integer>>(); Map<Node, Integer> communityMemberships; Map<Node, Map<Node, Integer>> bestValidSolution = null; double upperProfitabilityBound = 1; double lowerProfitabilityBound = 0; for(int i=0; i<10; i++) { double profitabilityThreshold = (upperProfitabilityBound + lowerProfitabilityBound) / 2d; communities = new HashMap<Node, Map<Node, Integer>>(); for (Node leader : leaders) { communityMemberships = executeLabelPropagation(graph, leader, profitabilityThreshold); communities.put(leader, communityMemberships); } if(areAllNodesAssigned(graph, communities)) { bestValidSolution = communities; lowerProfitabilityBound = profitabilityThreshold; } else { upperProfitabilityBound = profitabilityThreshold; } } if(bestValidSolution == null) { for (Node leader : leaders) { communityMemberships = executeLabelPropagation(graph, leader, 0); communities.put(leader, communityMemberships); bestValidSolution = communities; } } return getMembershipDegrees(graph, bestValidSolution); }
/** * Executes the label propagation phase. * * @param graph The graph which is being analyzed. * * @param leaders The list of global leader nodes detected during the random * walk phase. * * @return A cover containing the detected communities. * @throws InterruptedException if the thread was interrupted */
Executes the label propagation phase
labelPropagationPhase
{ "repo_name": "rwth-acis/REST-OCD-Services", "path": "rest_ocd_services/src/main/java/i5/las2peer/services/ocd/algorithms/BinarySearchRandomWalkLabelPropagationAlgorithm.java", "license": "apache-2.0", "size": 19979 }
[ "java.util.HashMap", "java.util.List", "java.util.Map" ]
import java.util.HashMap; import java.util.List; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,760,368
Resource move(@NotNull String srcAbsPath, @NotNull String destParentAbsPath, @Nullable String destChildName, @Nullable String order) throws PersistenceException;
Resource move(@NotNull String srcAbsPath, @NotNull String destParentAbsPath, @Nullable String destChildName, @Nullable String order) throws PersistenceException;
/** * move with optional rename and ordering * * @param srcAbsPath the absolute path of th resource to move * @param destParentAbsPath the absolute path of the designated parent resource * @param destChildName the designated name of the new resource * @param order an ordering rule as described for the SlingPostServlet */
move with optional rename and ordering
move
{ "repo_name": "ist-dresden/composum", "path": "console/src/main/java/com/composum/sling/nodes/mount/ExtendedResolver.java", "license": "mit", "size": 1746 }
[ "org.apache.sling.api.resource.PersistenceException", "org.apache.sling.api.resource.Resource", "org.jetbrains.annotations.NotNull", "org.jetbrains.annotations.Nullable" ]
import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
import org.apache.sling.api.resource.*; import org.jetbrains.annotations.*;
[ "org.apache.sling", "org.jetbrains.annotations" ]
org.apache.sling; org.jetbrains.annotations;
1,242,402
@Test(expected = IllegalArgumentException.class) public void collectionConstructorWithNull() { //noinspection CastToConcreteClass new WkbGeometryCollectionZM<>((Collection<WkbGeometryZM>)null); }
@Test(expected = IllegalArgumentException.class) void function() { new WkbGeometryCollectionZM<>((Collection<WkbGeometryZM>)null); }
/** * Test the collection constructor with a null collection */
Test the collection constructor with a null collection
collectionConstructorWithNull
{ "repo_name": "GitHubRGI/swagd", "path": "GeoPackage/src/test/java/com/rgi/geopackage/features/geometry/zm/WkbGeometryCollectionZMTest.java", "license": "mit", "size": 14558 }
[ "java.util.Collection", "org.junit.Test" ]
import java.util.Collection; import org.junit.Test;
import java.util.*; import org.junit.*;
[ "java.util", "org.junit" ]
java.util; org.junit;
899,992
public static <T, C extends JComponent> SimpleComponent<T, C> create( C component, Getter<C, T> getter, Setter<C, T> setter) { Property<T> property = Property.create(() -> component, getter, setter); return new SimpleComponent<>(component, property); }
static <T, C extends JComponent> SimpleComponent<T, C> function( C component, Getter<C, T> getter, Setter<C, T> setter) { Property<T> property = Property.create(() -> component, getter, setter); return new SimpleComponent<>(component, property); }
/** * Creates a {@link SimpleComponent} for the given Swing component. * * @param getter a {@link Getter} for accessing the component's value * @param setter a {@link Setter} for modifying the component's value */
Creates a <code>SimpleComponent</code> for the given Swing component
create
{ "repo_name": "bazelbuild/intellij", "path": "common/settings/src/com/google/idea/common/settings/SettingComponent.java", "license": "apache-2.0", "size": 7440 }
[ "com.google.idea.common.settings.Property", "javax.swing.JComponent" ]
import com.google.idea.common.settings.Property; import javax.swing.JComponent;
import com.google.idea.common.settings.*; import javax.swing.*;
[ "com.google.idea", "javax.swing" ]
com.google.idea; javax.swing;
664,126
@Override public boolean deleteDocument( IndexDefinition index, SearchDocumentId document_id ) { if ( index == null || document_id == null ) { logger.error("Null index or document id"); return false; } try { String delete_request = "/" + index.getSimpleValue() + "/" + document_id.getTypeName().getSimpleName() + "/" + document_id.getSimpleValue(); DeleteRequest del = new DeleteRequest(index.getSimpleValue(), ElasticSearchCommon.ELASTICSEARCH_DEFAULT_TYPE, document_id.getSimpleValue()).setRefreshPolicy(RefreshPolicy.IMMEDIATE); DeleteResponse response = high_level_rest_client.delete(del, RequestOptions.DEFAULT); boolean successfully_deleted = response.getResult().equals(Result.DELETED); if ( !successfully_deleted ) { logger.error("delete unsuccessful for: " + delete_request); } else { logger.info("successful delete for: " + delete_request); } return successfully_deleted; } catch ( Exception e ) { logger.error("Error", e); return false; } }
boolean function( IndexDefinition index, SearchDocumentId document_id ) { if ( index == null document_id == null ) { logger.error(STR); return false; } try { String delete_request = "/" + index.getSimpleValue() + "/" + document_id.getTypeName().getSimpleName() + "/" + document_id.getSimpleValue(); DeleteRequest del = new DeleteRequest(index.getSimpleValue(), ElasticSearchCommon.ELASTICSEARCH_DEFAULT_TYPE, document_id.getSimpleValue()).setRefreshPolicy(RefreshPolicy.IMMEDIATE); DeleteResponse response = high_level_rest_client.delete(del, RequestOptions.DEFAULT); boolean successfully_deleted = response.getResult().equals(Result.DELETED); if ( !successfully_deleted ) { logger.error(STR + delete_request); } else { logger.info(STR + delete_request); } return successfully_deleted; } catch ( Exception e ) { logger.error("Error", e); return false; } }
/** * Delete a document within an index * * @param index * @param document_id * @return */
Delete a document within an index
deleteDocument
{ "repo_name": "jimmutable/core", "path": "cloud/src/main/java/org/jimmutable/cloud/elasticsearch/ElasticSearchRESTClient.java", "license": "bsd-3-clause", "size": 41636 }
[ "org.elasticsearch.action.DocWriteResponse", "org.elasticsearch.action.delete.DeleteRequest", "org.elasticsearch.action.delete.DeleteResponse", "org.elasticsearch.action.support.WriteRequest", "org.elasticsearch.client.RequestOptions" ]
import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.action.*; import org.elasticsearch.action.delete.*; import org.elasticsearch.action.support.*; import org.elasticsearch.client.*;
[ "org.elasticsearch.action", "org.elasticsearch.client" ]
org.elasticsearch.action; org.elasticsearch.client;
40,426
public static String getRealFilePath(final String localFilePath, final String filename) throws IOException { final Path directory = Paths.get(localFilePath); final Path resolvedPath = directory.resolve(filename); return FileUtils.resolveForSymbolic(resolvedPath).toString(); }
static String function(final String localFilePath, final String filename) throws IOException { final Path directory = Paths.get(localFilePath); final Path resolvedPath = directory.resolve(filename); return FileUtils.resolveForSymbolic(resolvedPath).toString(); }
/** * Get the actual file path from the objectName received from BP * * @param localFilePath :path of local directory * @param filename : name of the file with logical folder * @return actualFilePath */
Get the actual file path from the objectName received from BP
getRealFilePath
{ "repo_name": "DenverM80/ds3_java_sdk", "path": "ds3-metadata/src/main/java/com/spectralogic/ds3client/metadata/MetaDataUtil.java", "license": "apache-2.0", "size": 1918 }
[ "com.spectralogic.ds3client.utils.FileUtils", "java.io.IOException", "java.nio.file.Path", "java.nio.file.Paths" ]
import com.spectralogic.ds3client.utils.FileUtils; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths;
import com.spectralogic.ds3client.utils.*; import java.io.*; import java.nio.file.*;
[ "com.spectralogic.ds3client", "java.io", "java.nio" ]
com.spectralogic.ds3client; java.io; java.nio;
1,925,226
void onChannelConnect(final String remoteAddr, final Channel channel);
void onChannelConnect(final String remoteAddr, final Channel channel);
/** * On channel connect. * * @param remoteAddr the remote addr * @param channel the channel */
On channel connect
onChannelConnect
{ "repo_name": "seata/seata", "path": "core/src/main/java/io/seata/core/rpc/netty/ChannelEventListener.java", "license": "apache-2.0", "size": 1618 }
[ "io.netty.channel.Channel" ]
import io.netty.channel.Channel;
import io.netty.channel.*;
[ "io.netty.channel" ]
io.netty.channel;
982,267
@Value.Lazy public String getPythonInterpreter(Optional<String> configPath, ExecutableFinder exeFinder) { PythonBuckConfig pyconfig = new PythonBuckConfig(getDelegate(), exeFinder); if (configPath.isPresent()) { return pyconfig.getPythonInterpreter(configPath); } // Fall back to the Python section configuration return pyconfig.getPythonInterpreter(); }
@Value.Lazy String function(Optional<String> configPath, ExecutableFinder exeFinder) { PythonBuckConfig pyconfig = new PythonBuckConfig(getDelegate(), exeFinder); if (configPath.isPresent()) { return pyconfig.getPythonInterpreter(configPath); } return pyconfig.getPythonInterpreter(); }
/** * Returns the path to python interpreter. If python is specified in the * 'python_interpreter' key of the 'parser' section that is used and an * error reported if invalid. * * If none has been specified, consult the PythonBuckConfig for an interpreter. * * @return The found python interpreter. */
Returns the path to python interpreter. If python is specified in the 'python_interpreter' key of the 'parser' section that is used and an error reported if invalid. If none has been specified, consult the PythonBuckConfig for an interpreter
getPythonInterpreter
{ "repo_name": "vschs007/buck", "path": "src/com/facebook/buck/parser/AbstractParserConfig.java", "license": "apache-2.0", "size": 7143 }
[ "com.facebook.buck.io.ExecutableFinder", "com.facebook.buck.python.PythonBuckConfig", "java.util.Optional", "org.immutables.value.Value" ]
import com.facebook.buck.io.ExecutableFinder; import com.facebook.buck.python.PythonBuckConfig; import java.util.Optional; import org.immutables.value.Value;
import com.facebook.buck.io.*; import com.facebook.buck.python.*; import java.util.*; import org.immutables.value.*;
[ "com.facebook.buck", "java.util", "org.immutables.value" ]
com.facebook.buck; java.util; org.immutables.value;
810,060
private void chooseAccount() { mState = STATE_CHOOSING_ACCOUNT; Intent intent = AccountPicker.newChooseAccountIntent(getPreferenceAccount(), null, ACCOUNT_TYPE, false, null, null, null, null); startActivityForResult(intent, CHOOSE_ACCOUNT); }
void function() { mState = STATE_CHOOSING_ACCOUNT; Intent intent = AccountPicker.newChooseAccountIntent(getPreferenceAccount(), null, ACCOUNT_TYPE, false, null, null, null, null); startActivityForResult(intent, CHOOSE_ACCOUNT); }
/** * Start an intent to prompt the user to choose the account to use with the * app. */
Start an intent to prompt the user to choose the account to use with the app
chooseAccount
{ "repo_name": "hotveryspicy/dredit", "path": "android/src/com/example/android/notepad/Preferences.java", "license": "apache-2.0", "size": 6927 }
[ "android.content.Intent", "com.google.android.gms.common.AccountPicker" ]
import android.content.Intent; import com.google.android.gms.common.AccountPicker;
import android.content.*; import com.google.android.gms.common.*;
[ "android.content", "com.google.android" ]
android.content; com.google.android;
952,482
public List<Long> readOffsets(int maximumNumber) { ArrayList<Long> offsets = new ArrayList<Long>(maximumNumber); for (int i = 0; i < maximumNumber || maximumNumber == 0; i++) { try { offsets.add(indexInputStream.readLong()); } catch (IOException e) { break; } } return offsets; }
List<Long> function(int maximumNumber) { ArrayList<Long> offsets = new ArrayList<Long>(maximumNumber); for (int i = 0; i < maximumNumber maximumNumber == 0; i++) { try { offsets.add(indexInputStream.readLong()); } catch (IOException e) { break; } } return offsets; }
/** * Attemps to read some number of image record offsets from the HIB index * file. * * @param maximumNumber * the maximum number of offsets that will be read from the HIB * index file. The actual number read may be less than this * number. * @return A list of file offsets read from the HIB index file. */
Attemps to read some number of image record offsets from the HIB index file
readOffsets
{ "repo_name": "AngelBanuelos/hipi", "path": "core/src/main/java/org/hipi/imagebundle/HipiImageBundle.java", "license": "bsd-3-clause", "size": 30777 }
[ "java.io.IOException", "java.util.ArrayList", "java.util.List" ]
import java.io.IOException; import java.util.ArrayList; import java.util.List;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
1,135,568
public List<TreeElement> injectVcsStatusTreeElements(List<TreeElement> treeElements) throws ServerException, NotFoundException { Optional<TreeElement> treeElementOptional = treeElements .stream() .filter(treeElement -> "file".equals(treeElement.getNode().getType())) .findAny(); if (treeElementOptional.isPresent()) { String project = normalizeProjectPath(treeElementOptional.get().getNode().getProject()); String projectWsPath = absolutize(project); Optional<VcsStatusProvider> vcsStatusProviderOptional = getVcsStatusProvider(projectWsPath); if (vcsStatusProviderOptional.isPresent()) { List<String> treeElementFiles = treeElements .stream() .filter(treeElement -> "file".equals(treeElement.getNode().getType())) .map(treeElement -> normalizeFilePath(treeElement.getNode().getPath())) .collect(Collectors.toList()); Map<String, VcsStatusProvider.VcsStatus> status = vcsStatusProviderOptional.get().getStatus(projectWsPath, treeElementFiles); treeElements .stream() .filter(itemReference -> "file".equals(itemReference.getNode().getType())) .forEach( itemReference -> { Map<String, String> attributes = new HashMap<>(itemReference.getNode().getAttributes()); attributes.put( "vcs.status", status.get(itemReference.getNode().getPath()).toString()); itemReference.getNode().setAttributes(attributes); }); } } return treeElements; }
List<TreeElement> function(List<TreeElement> treeElements) throws ServerException, NotFoundException { Optional<TreeElement> treeElementOptional = treeElements .stream() .filter(treeElement -> "file".equals(treeElement.getNode().getType())) .findAny(); if (treeElementOptional.isPresent()) { String project = normalizeProjectPath(treeElementOptional.get().getNode().getProject()); String projectWsPath = absolutize(project); Optional<VcsStatusProvider> vcsStatusProviderOptional = getVcsStatusProvider(projectWsPath); if (vcsStatusProviderOptional.isPresent()) { List<String> treeElementFiles = treeElements .stream() .filter(treeElement -> "file".equals(treeElement.getNode().getType())) .map(treeElement -> normalizeFilePath(treeElement.getNode().getPath())) .collect(Collectors.toList()); Map<String, VcsStatusProvider.VcsStatus> status = vcsStatusProviderOptional.get().getStatus(projectWsPath, treeElementFiles); treeElements .stream() .filter(itemReference -> "file".equals(itemReference.getNode().getType())) .forEach( itemReference -> { Map<String, String> attributes = new HashMap<>(itemReference.getNode().getAttributes()); attributes.put( STR, status.get(itemReference.getNode().getPath()).toString()); itemReference.getNode().setAttributes(attributes); }); } } return treeElements; }
/** * Find related VCS provider and set VCS status of {@link TreeElement} file to it's attributes to * each item of the given list, if VCS provider is present. * * @param treeElements list of {@link TreeElement} files to update */
Find related VCS provider and set VCS status of <code>TreeElement</code> file to it's attributes to each item of the given list, if VCS provider is present
injectVcsStatusTreeElements
{ "repo_name": "sleshchenko/che", "path": "wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/impl/ProjectServiceVcsStatusInjector.java", "license": "epl-1.0", "size": 7113 }
[ "java.util.HashMap", "java.util.List", "java.util.Map", "java.util.Optional", "java.util.stream.Collectors", "org.eclipse.che.api.core.NotFoundException", "org.eclipse.che.api.core.ServerException", "org.eclipse.che.api.fs.server.WsPathUtils", "org.eclipse.che.api.project.server.VcsStatusProvider", ...
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.eclipse.che.api.core.NotFoundException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.fs.server.WsPathUtils; import org.eclipse.che.api.project.server.VcsStatusProvider; import org.eclipse.che.api.project.shared.dto.TreeElement;
import java.util.*; import java.util.stream.*; import org.eclipse.che.api.core.*; import org.eclipse.che.api.fs.server.*; import org.eclipse.che.api.project.server.*; import org.eclipse.che.api.project.shared.dto.*;
[ "java.util", "org.eclipse.che" ]
java.util; org.eclipse.che;
646,689
public void testAddAll(){ try { LdapName x=new LdapName("t=test"); x.addAll(0,new CompositeName()); assertNotNull(x); } catch (InvalidNameException e) { fail("Failed with:"+e); } }
void function(){ try { LdapName x=new LdapName(STR); x.addAll(0,new CompositeName()); assertNotNull(x); } catch (InvalidNameException e) { fail(STR+e); } }
/** * <p>Test method for 'javax.naming.ldap.LdapName.add(int, String)'</p> * <p>Here we are testing if this method adds a single component at a specified position within this LDAP name.</p> * <p>Here we are testing if a naming exception is thrown if a name is trying of be added.</p> */
Test method for 'javax.naming.ldap.LdapName.add(int, String)' Here we are testing if this method adds a single component at a specified position within this LDAP name. Here we are testing if a naming exception is thrown if a name is trying of be added
testAddAll
{ "repo_name": "freeVM/freeVM", "path": "enhanced/archive/classlib/java6/modules/jndi/src/test/java/org/apache/harmony/jndi/tests/javax/naming/ldap/whitebox/TestLdapNameWhiteBoxDevelopment.java", "license": "apache-2.0", "size": 8553 }
[ "javax.naming.CompositeName", "javax.naming.InvalidNameException", "javax.naming.ldap.LdapName" ]
import javax.naming.CompositeName; import javax.naming.InvalidNameException; import javax.naming.ldap.LdapName;
import javax.naming.*; import javax.naming.ldap.*;
[ "javax.naming" ]
javax.naming;
48,872
@Gridify(igniteInstanceName="org.apache.ignite.p2p.GridP2PGridifySelfTest1") public Integer executeGridifyResource(int res) { String path = "org/apache/ignite/p2p/p2p.properties"; GridTestClassLoader tstClsLdr = new GridTestClassLoader( GridP2PTestTask.class.getName(), GridP2PTestJob.class.getName() ); // Test property file load. byte [] bytes = new byte[20]; try (InputStream in = tstClsLdr.getResourceAsStream(path)) { if (in == null) { System.out.println("Resource could not be loaded: " + path); return -2; } in.read(bytes); } catch (IOException e) { System.out.println("Failed to read from resource stream: " + e.getMessage()); return -3; } String rsrcVal = new String(bytes).trim(); System.out.println("Remote resource content is : " + rsrcVal); if (!rsrcVal.equals("resource=loaded")) { System.out.println("Invalid loaded resource value: " + rsrcVal); return -4; } return res; }
@Gridify(igniteInstanceName=STR) Integer function(int res) { String path = STR; GridTestClassLoader tstClsLdr = new GridTestClassLoader( GridP2PTestTask.class.getName(), GridP2PTestJob.class.getName() ); byte [] bytes = new byte[20]; try (InputStream in = tstClsLdr.getResourceAsStream(path)) { if (in == null) { System.out.println(STR + path); return -2; } in.read(bytes); } catch (IOException e) { System.out.println(STR + e.getMessage()); return -3; } String rsrcVal = new String(bytes).trim(); System.out.println(STR + rsrcVal); if (!rsrcVal.equals(STR)) { System.out.println(STR + rsrcVal); return -4; } return res; }
/** * Note that this method sends instance of test class to remote node. * Be sure that this instance does not have none-serializable fields or references * to the objects that could not be instantiated like class loaders and so on. * * @param res Result. * @return The same value as parameter has. */
Note that this method sends instance of test class to remote node. Be sure that this instance does not have none-serializable fields or references to the objects that could not be instantiated like class loaders and so on
executeGridifyResource
{ "repo_name": "irudyak/ignite", "path": "modules/aop/src/test/java/org/apache/ignite/p2p/P2PGridifySelfTest.java", "license": "apache-2.0", "size": 7582 }
[ "java.io.IOException", "java.io.InputStream", "org.apache.ignite.compute.gridify.Gridify", "org.apache.ignite.testframework.GridTestClassLoader" ]
import java.io.IOException; import java.io.InputStream; import org.apache.ignite.compute.gridify.Gridify; import org.apache.ignite.testframework.GridTestClassLoader;
import java.io.*; import org.apache.ignite.compute.gridify.*; import org.apache.ignite.testframework.*;
[ "java.io", "org.apache.ignite" ]
java.io; org.apache.ignite;
1,596,868
List<ApplicationEventFamilyMapDto> getApplicationEventFamilyMapsByIds(List<String> key);
List<ApplicationEventFamilyMapDto> getApplicationEventFamilyMapsByIds(List<String> key);
/** * Gets application event family maps by their ids. * * @param key list of ids * @return list of application event family maps */
Gets application event family maps by their ids
getApplicationEventFamilyMapsByIds
{ "repo_name": "Oleh-Kravchenko/kaa", "path": "server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/CacheService.java", "license": "apache-2.0", "size": 12774 }
[ "java.util.List", "org.kaaproject.kaa.common.dto.event.ApplicationEventFamilyMapDto" ]
import java.util.List; import org.kaaproject.kaa.common.dto.event.ApplicationEventFamilyMapDto;
import java.util.*; import org.kaaproject.kaa.common.dto.event.*;
[ "java.util", "org.kaaproject.kaa" ]
java.util; org.kaaproject.kaa;
2,183,812
@Test @Feature({"NFCTest"}) public void testNonNdefCompatibleTagFoundWithoutWatcher() { TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); mDelegate.invokeCallback(); nfc.setClient(mNfcClient); // Pass null tag handler to simulate that the tag is not NDEF compatible. nfc.processPendingOperationsForTesting(null); // An error is NOT notified. verify(mNfcClient, times(0)).onError(mErrorCaptor.capture()); // No watch. verify(mNfcClient, times(0)) .onWatch(mOnWatchCallbackCaptor.capture(), nullable(String.class), any(NdefMessage.class)); }
@Feature({STR}) void function() { TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); mDelegate.invokeCallback(); nfc.setClient(mNfcClient); nfc.processPendingOperationsForTesting(null); verify(mNfcClient, times(0)).onError(mErrorCaptor.capture()); verify(mNfcClient, times(0)) .onWatch(mOnWatchCallbackCaptor.capture(), nullable(String.class), any(NdefMessage.class)); }
/** * Test that when the tag in proximity is found to be not NDEF compatible, an error event will * not be dispatched to the client if there is no watcher present. */
Test that when the tag in proximity is found to be not NDEF compatible, an error event will not be dispatched to the client if there is no watcher present
testNonNdefCompatibleTagFoundWithoutWatcher
{ "repo_name": "chromium/chromium", "path": "services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java", "license": "bsd-3-clause", "size": 95069 }
[ "org.chromium.base.test.util.Feature", "org.chromium.device.mojom.NdefMessage", "org.mockito.ArgumentMatchers", "org.mockito.Mockito" ]
import org.chromium.base.test.util.Feature; import org.chromium.device.mojom.NdefMessage; import org.mockito.ArgumentMatchers; import org.mockito.Mockito;
import org.chromium.base.test.util.*; import org.chromium.device.mojom.*; import org.mockito.*;
[ "org.chromium.base", "org.chromium.device", "org.mockito" ]
org.chromium.base; org.chromium.device; org.mockito;
2,739,576
PropertyDescriptor[] getPropertyDescriptors();
PropertyDescriptor[] getPropertyDescriptors();
/** * Obtain the PropertyDescriptors for the wrapped object * (as determined by standard JavaBeans introspection). * @return the PropertyDescriptors for the wrapped object */
Obtain the PropertyDescriptors for the wrapped object (as determined by standard JavaBeans introspection)
getPropertyDescriptors
{ "repo_name": "cbeams-archive/spring-framework-2.5.x", "path": "src/org/springframework/beans/BeanWrapper.java", "license": "apache-2.0", "size": 3482 }
[ "java.beans.PropertyDescriptor" ]
import java.beans.PropertyDescriptor;
import java.beans.*;
[ "java.beans" ]
java.beans;
408,330
public static boolean available() { // this is only one of many ways this can be done List<String> ret = run(new String[] { "id", "echo -EOC-" }); if (ret == null) return false; for (String line : ret) { if (line.contains("uid=")) { // id command is working, let's see if we are actually root return line.contains("uid=0"); } else if (line.contains("-EOC-")) { // if we end up here, the id command isn't present, but at // least the su commands starts some kind of shell, let's // hope it has root priviliges - no way to know without // additional native binaries return true; } } return false; }
static boolean function() { List<String> ret = run(new String[] { "id", STR }); if (ret == null) return false; for (String line : ret) { if (line.contains("uid=")) { return line.contains("uid=0"); } else if (line.contains("-EOC-")) { return true; } } return false; }
/** * Detects whether or not superuser access is available, by checking the output * of the "id" command if available, checking if a shell runs at all otherwise * * @return True if superuser access available */
Detects whether or not superuser access is available, by checking the output of the "id" command if available, checking if a shell runs at all otherwise
available
{ "repo_name": "omnirom/android_packages_apps_Roadrunner", "path": "src/com/asksven/andoid/common/contrib/Shell.java", "license": "gpl-3.0", "size": 8902 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,618,161
@Deprecated public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { if (api >= Opcodes.ASM5) { boolean itf = opcode == Opcodes.INVOKEINTERFACE; visitMethodInsn(opcode, owner, name, desc, itf); return; } throw new RuntimeException("Must be overriden"); }
void function(final int opcode, final String owner, final String name, final String desc) { if (api >= Opcodes.ASM5) { boolean itf = opcode == Opcodes.INVOKEINTERFACE; visitMethodInsn(opcode, owner, name, desc, itf); return; } throw new RuntimeException(STR); }
/** * Method instruction. See * {@link org.objectweb.asm.MethodVisitor#visitMethodInsn}. */
Method instruction. See <code>org.objectweb.asm.MethodVisitor#visitMethodInsn</code>
visitMethodInsn
{ "repo_name": "trivium-io/trivium-core", "path": "src/io/trivium/dep/org/objectweb/asm/util/Printer.java", "license": "apache-2.0", "size": 20837 }
[ "io.trivium.dep.org.objectweb.asm.Opcodes" ]
import io.trivium.dep.org.objectweb.asm.Opcodes;
import io.trivium.dep.org.objectweb.asm.*;
[ "io.trivium.dep" ]
io.trivium.dep;
970,840
boolean updateMapping(IndexMetaData indexMetaData) throws IOException;
boolean updateMapping(IndexMetaData indexMetaData) throws IOException;
/** * Checks if index requires refresh from master. */
Checks if index requires refresh from master
updateMapping
{ "repo_name": "fernandozhu/elasticsearch", "path": "core/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java", "license": "apache-2.0", "size": 46029 }
[ "java.io.IOException", "org.elasticsearch.cluster.metadata.IndexMetaData" ]
import java.io.IOException; import org.elasticsearch.cluster.metadata.IndexMetaData;
import java.io.*; import org.elasticsearch.cluster.metadata.*;
[ "java.io", "org.elasticsearch.cluster" ]
java.io; org.elasticsearch.cluster;
589,416
public void transformClass(ClassNode cn) { AnnotationNode collector = null; for (AnnotationNode an : cn.getAnnotations()) { if (an.getClassNode().getName().equals(AnnotationCollector.class.getName())) { collector = an; break; } } if (collector == null) { return; } boolean legacySerialization = false; final Expression member = collector.getMember("serializeClass"); if (member instanceof ClassExpression) { ClassExpression ce = (ClassExpression) member; legacySerialization = ce.getType().getName().equals(cn.getName()); } ClassNode helper = cn; if (legacySerialization) { // force final class, remove interface, annotation, enum and abstract modifiers helper.setModifiers((ACC_FINAL | helper.getModifiers()) & ~(ACC_ENUM | ACC_INTERFACE | ACC_ANNOTATION | ACC_ABSTRACT)); // force Object super class helper.setSuperClass(ClassHelper.OBJECT_TYPE); // force no interfaces implemented helper.setInterfaces(ClassNode.EMPTY_ARRAY); } else { helper = new InnerClassNode(cn.getPlainNodeReference(), cn.getName() + "$CollectorHelper", ACC_PUBLIC | ACC_STATIC | ACC_FINAL, ClassHelper.OBJECT_TYPE.getPlainNodeReference()); cn.getModule().addClass(helper); helper.addAnnotation(new AnnotationNode(COMPILESTATIC_CLASSNODE)); collector.setMember("serializeClass", new ClassExpression(helper.getPlainNodeReference())); } // add static value():Object[][] method List<AnnotationNode> meta = getMeta(cn); List<Expression> outer = new ArrayList<>(meta.size()); for (AnnotationNode an : meta) { Expression serialized = serialize(an); outer.add(serialized); } ArrayExpression ae = new ArrayExpression(ClassHelper.OBJECT_TYPE.makeArray(), outer); Statement code = new ReturnStatement(ae); helper.addMethod("value", ACC_PUBLIC | ACC_STATIC, ClassHelper.OBJECT_TYPE.makeArray().makeArray(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, code); // remove annotations for (ListIterator<AnnotationNode> it = cn.getAnnotations().listIterator(); it.hasNext(); ) { AnnotationNode an = it.next(); if (an == collector || "java.lang.annotation".equals(an.getClassNode().getPackageName())) { continue; } it.remove(); } }
void function(ClassNode cn) { AnnotationNode collector = null; for (AnnotationNode an : cn.getAnnotations()) { if (an.getClassNode().getName().equals(AnnotationCollector.class.getName())) { collector = an; break; } } if (collector == null) { return; } boolean legacySerialization = false; final Expression member = collector.getMember(STR); if (member instanceof ClassExpression) { ClassExpression ce = (ClassExpression) member; legacySerialization = ce.getType().getName().equals(cn.getName()); } ClassNode helper = cn; if (legacySerialization) { helper.setModifiers((ACC_FINAL helper.getModifiers()) & ~(ACC_ENUM ACC_INTERFACE ACC_ANNOTATION ACC_ABSTRACT)); helper.setSuperClass(ClassHelper.OBJECT_TYPE); helper.setInterfaces(ClassNode.EMPTY_ARRAY); } else { helper = new InnerClassNode(cn.getPlainNodeReference(), cn.getName() + STR, ACC_PUBLIC ACC_STATIC ACC_FINAL, ClassHelper.OBJECT_TYPE.getPlainNodeReference()); cn.getModule().addClass(helper); helper.addAnnotation(new AnnotationNode(COMPILESTATIC_CLASSNODE)); collector.setMember(STR, new ClassExpression(helper.getPlainNodeReference())); } List<AnnotationNode> meta = getMeta(cn); List<Expression> outer = new ArrayList<>(meta.size()); for (AnnotationNode an : meta) { Expression serialized = serialize(an); outer.add(serialized); } ArrayExpression ae = new ArrayExpression(ClassHelper.OBJECT_TYPE.makeArray(), outer); Statement code = new ReturnStatement(ae); helper.addMethod("value", ACC_PUBLIC ACC_STATIC, ClassHelper.OBJECT_TYPE.makeArray().makeArray(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, code); for (ListIterator<AnnotationNode> it = cn.getAnnotations().listIterator(); it.hasNext(); ) { AnnotationNode an = it.next(); if (an == collector STR.equals(an.getClassNode().getPackageName())) { continue; } it.remove(); } }
/** * Method to transform the given ClassNode, if it is annotated with * {@link AnnotationCollector}. See class description for what the * transformation includes. */
Method to transform the given ClassNode, if it is annotated with <code>AnnotationCollector</code>. See class description for what the transformation includes
transformClass
{ "repo_name": "paulk-asert/groovy", "path": "src/main/java/org/codehaus/groovy/transform/AnnotationCollectorTransform.java", "license": "apache-2.0", "size": 17576 }
[ "groovy.transform.AnnotationCollector", "java.util.ArrayList", "java.util.List", "java.util.ListIterator", "org.codehaus.groovy.ast.AnnotationNode", "org.codehaus.groovy.ast.ClassHelper", "org.codehaus.groovy.ast.ClassNode", "org.codehaus.groovy.ast.InnerClassNode", "org.codehaus.groovy.ast.Paramete...
import groovy.transform.AnnotationCollector; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.expr.ArrayExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement;
import groovy.transform.*; import java.util.*; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*;
[ "groovy.transform", "java.util", "org.codehaus.groovy" ]
groovy.transform; java.util; org.codehaus.groovy;
258,185
public void addFieldMatchValidation(String firstProperty, String secondProperty) { if ( !this.initialized ) { initialize(); } ValidationStatusProvider provider = new FieldMatchesDatabindingValidator( getTargetObservable( firstProperty ), getTargetObservable( secondProperty ) ); addValidationStatusProvider( firstProperty, provider ); addValidationStatusProvider( secondProperty, provider ); }
void function(String firstProperty, String secondProperty) { if ( !this.initialized ) { initialize(); } ValidationStatusProvider provider = new FieldMatchesDatabindingValidator( getTargetObservable( firstProperty ), getTargetObservable( secondProperty ) ); addValidationStatusProvider( firstProperty, provider ); addValidationStatusProvider( secondProperty, provider ); }
/** * This method invocation will invoke {@link #initialize()} method. * FieldMatchesDatabindingValidator requires target observable for properties passed as * arguments * * @param firstProperty * @param secondProperty */
This method invocation will invoke <code>#initialize()</code> method. FieldMatchesDatabindingValidator requires target observable for properties passed as arguments
addFieldMatchValidation
{ "repo_name": "mferlan/rap.databinding.jsr303", "path": "org.eclipse.core.databinding.validation.jsr303.samples.rap/src/org/eclipse/core/databinding/validation/jsr303/samples/util/Jsr303DatabindingConfigurator.java", "license": "epl-1.0", "size": 21293 }
[ "org.eclipse.core.databinding.ValidationStatusProvider" ]
import org.eclipse.core.databinding.ValidationStatusProvider;
import org.eclipse.core.databinding.*;
[ "org.eclipse.core" ]
org.eclipse.core;
1,041,991
public HttpExchange asyncPost(String path, String args, FritzahaCallback callback) { if (!isAuthenticated()) authenticate(); HttpExchange postExchange = new FritzahaContentExchange(callback); postExchange.setMethod("POST"); postExchange.setURL(getURL(path)); try { postExchange.setRequestContent(new ByteArrayBuffer(addSID(args).getBytes("UTF-8"))); } catch (UnsupportedEncodingException e1) { logger.error("An encoding error occurred in the POST arguments"); return null; } postExchange.setRequestContentType("application/x-www-form-urlencoded;charset=utf-8"); try { asyncclient.send(postExchange); } catch (IOException e) { logger.error("An I/O error occurred while sending the POST request to " + getURL(path)); return null; } return postExchange; }
HttpExchange function(String path, String args, FritzahaCallback callback) { if (!isAuthenticated()) authenticate(); HttpExchange postExchange = new FritzahaContentExchange(callback); postExchange.setMethod("POST"); postExchange.setURL(getURL(path)); try { postExchange.setRequestContent(new ByteArrayBuffer(addSID(args).getBytes("UTF-8"))); } catch (UnsupportedEncodingException e1) { logger.error(STR); return null; } postExchange.setRequestContentType(STR); try { asyncclient.send(postExchange); } catch (IOException e) { logger.error(STR + getURL(path)); return null; } return postExchange; }
/** * Sends an HTTP POST request using the asynchronous client * * @param Path * Path of the requested resource * @param Args * Arguments for the request * @param Callback * Callback to handle the response with */
Sends an HTTP POST request using the asynchronous client
asyncPost
{ "repo_name": "Ole8700/openhab", "path": "bundles/binding/org.openhab.binding.fritzaha/src/main/java/org/openhab/binding/fritzaha/internal/hardware/FritzahaWebInterface.java", "license": "gpl-3.0", "size": 11062 }
[ "java.io.IOException", "java.io.UnsupportedEncodingException", "org.eclipse.jetty.client.HttpExchange", "org.eclipse.jetty.io.ByteArrayBuffer", "org.openhab.binding.fritzaha.internal.hardware.callbacks.FritzahaCallback" ]
import java.io.IOException; import java.io.UnsupportedEncodingException; import org.eclipse.jetty.client.HttpExchange; import org.eclipse.jetty.io.ByteArrayBuffer; import org.openhab.binding.fritzaha.internal.hardware.callbacks.FritzahaCallback;
import java.io.*; import org.eclipse.jetty.client.*; import org.eclipse.jetty.io.*; import org.openhab.binding.fritzaha.internal.hardware.callbacks.*;
[ "java.io", "org.eclipse.jetty", "org.openhab.binding" ]
java.io; org.eclipse.jetty; org.openhab.binding;
1,246,711
public List<Request> unmarshal(File importFile) throws StiebelHeatPumpException { Requests requests = new Requests(); JAXBContext context; try { context = JAXBContext.newInstance(Requests.class); Unmarshaller um = context.createUnmarshaller(); requests = (Requests) um.unmarshal(importFile); } catch (JAXBException e) { throw new StiebelHeatPumpException(e.toString(), e); } return requests.getRequests(); }
List<Request> function(File importFile) throws StiebelHeatPumpException { Requests requests = new Requests(); JAXBContext context; try { context = JAXBContext.newInstance(Requests.class); Unmarshaller um = context.createUnmarshaller(); requests = (Requests) um.unmarshal(importFile); } catch (JAXBException e) { throw new StiebelHeatPumpException(e.toString(), e); } return requests.getRequests(); }
/** * This method loads a List of Request objects from xml file * * @param importFile * file object to load the object from * @return List of Requests */
This method loads a List of Request objects from xml file
unmarshal
{ "repo_name": "steve-bate/openhab", "path": "bundles/binding/org.openhab.binding.stiebelheatpump/src/main/java/org/openhab/binding/stiebelheatpump/internal/ConfigParser.java", "license": "epl-1.0", "size": 4583 }
[ "java.io.File", "java.util.List", "javax.xml.bind.JAXBContext", "javax.xml.bind.JAXBException", "javax.xml.bind.Unmarshaller", "org.openhab.binding.stiebelheatpump.protocol.Request", "org.openhab.binding.stiebelheatpump.protocol.Requests" ]
import java.io.File; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.openhab.binding.stiebelheatpump.protocol.Request; import org.openhab.binding.stiebelheatpump.protocol.Requests;
import java.io.*; import java.util.*; import javax.xml.bind.*; import org.openhab.binding.stiebelheatpump.protocol.*;
[ "java.io", "java.util", "javax.xml", "org.openhab.binding" ]
java.io; java.util; javax.xml; org.openhab.binding;
1,227,511
private static boolean isSingleLineWhile(DetailAST literalWhile) { boolean result = false; if (literalWhile.getParent().getType() == TokenTypes.SLIST && literalWhile.getLastChild().getType() != TokenTypes.SLIST) { final DetailAST block = literalWhile.getLastChild().getPreviousSibling(); result = literalWhile.getLineNo() == block.getLineNo(); } return result; }
static boolean function(DetailAST literalWhile) { boolean result = false; if (literalWhile.getParent().getType() == TokenTypes.SLIST && literalWhile.getLastChild().getType() != TokenTypes.SLIST) { final DetailAST block = literalWhile.getLastChild().getPreviousSibling(); result = literalWhile.getLineNo() == block.getLineNo(); } return result; }
/** * Checks if current while statement is single-line statement, e.g.: * <p> * <code> * while (obj.isValid()) return true; * </code> * </p> * @param literalWhile {@link TokenTypes#LITERAL_WHILE while statement}. * @return true if current while statement is single-line statement. */
Checks if current while statement is single-line statement, e.g.: <code> while (obj.isValid()) return true; </code>
isSingleLineWhile
{ "repo_name": "another-dave/checkstyle", "path": "src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/NeedBracesCheck.java", "license": "lgpl-2.1", "size": 13229 }
[ "com.puppycrawl.tools.checkstyle.api.DetailAST", "com.puppycrawl.tools.checkstyle.api.TokenTypes" ]
import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.*;
[ "com.puppycrawl.tools" ]
com.puppycrawl.tools;
2,765,715