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
sequence
imports_info
stringlengths
19
34.8k
cluster_imports_info
stringlengths
15
3.66k
libraries
sequence
libraries_info
stringlengths
6
661
id
int64
0
2.92M
protected long primitiveArrayRecurse(Object o) throws IOException { if (o == null) { return primitiveArrayCount; } String className = o.getClass().getName(); if (className.charAt(0) != '[') { throw new IOException("Invalid object passed to BufferedDataInputStream.readArray:" + className); } // Is this a multidimensional array? If so process recursively. if (className.charAt(1) == '[') { for (int i = 0; i < ((Object[]) o).length; i += 1) { primitiveArrayRecurse(((Object[]) o)[i]); } } else { // This is a one-d array. Process it using our special functions. switch (className.charAt(1)) { case 'Z': primitiveArrayCount += read((boolean[]) o, 0, ((boolean[]) o).length); break; case 'B': int len = read((byte[]) o, 0, ((byte[]) o).length); primitiveArrayCount += len; if (len < ((byte[]) o).length) { throw new EOFException(); } break; case 'C': primitiveArrayCount += read((char[]) o, 0, ((char[]) o).length); break; case 'S': primitiveArrayCount += read((short[]) o, 0, ((short[]) o).length); break; case 'I': primitiveArrayCount += read((int[]) o, 0, ((int[]) o).length); break; case 'J': primitiveArrayCount += read((long[]) o, 0, ((long[]) o).length); break; case 'F': primitiveArrayCount += read((float[]) o, 0, ((float[]) o).length); break; case 'D': primitiveArrayCount += read((double[]) o, 0, ((double[]) o).length); break; case 'L': // Handle an array of Objects by recursion. Anything // else is an error. if (className.equals("[Ljava.lang.Object;")) { for (int i = 0; i < ((Object[]) o).length; i += 1) { primitiveArrayRecurse(((Object[]) o)[i]); } } else { throw new IOException("Invalid object passed to BufferedDataInputStream.readArray: " + className); } break; default: throw new IOException("Invalid object passed to BufferedDataInputStream.readArray: " + className); } } return primitiveArrayCount; }
long function(Object o) throws IOException { if (o == null) { return primitiveArrayCount; } String className = o.getClass().getName(); if (className.charAt(0) != '[') { throw new IOException(STR + className); } if (className.charAt(1) == '[') { for (int i = 0; i < ((Object[]) o).length; i += 1) { primitiveArrayRecurse(((Object[]) o)[i]); } } else { switch (className.charAt(1)) { case 'Z': primitiveArrayCount += read((boolean[]) o, 0, ((boolean[]) o).length); break; case 'B': int len = read((byte[]) o, 0, ((byte[]) o).length); primitiveArrayCount += len; if (len < ((byte[]) o).length) { throw new EOFException(); } break; case 'C': primitiveArrayCount += read((char[]) o, 0, ((char[]) o).length); break; case 'S': primitiveArrayCount += read((short[]) o, 0, ((short[]) o).length); break; case 'I': primitiveArrayCount += read((int[]) o, 0, ((int[]) o).length); break; case 'J': primitiveArrayCount += read((long[]) o, 0, ((long[]) o).length); break; case 'F': primitiveArrayCount += read((float[]) o, 0, ((float[]) o).length); break; case 'D': primitiveArrayCount += read((double[]) o, 0, ((double[]) o).length); break; case 'L': if (className.equals(STR)) { for (int i = 0; i < ((Object[]) o).length; i += 1) { primitiveArrayRecurse(((Object[]) o)[i]); } } else { throw new IOException(STR + className); } break; default: throw new IOException(STR + className); } } return primitiveArrayCount; }
/** Read recursively over a multi-dimensional array. * @return The number of bytes read. */
Read recursively over a multi-dimensional array
primitiveArrayRecurse
{ "repo_name": "jankotek/asterope", "path": "skyview/nom/tam/util/BufferedDataInputStream.java", "license": "agpl-3.0", "size": 23604 }
[ "java.io.EOFException", "java.io.IOException" ]
import java.io.EOFException; import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
2,409,254
public SolrCore create(CoreDescriptor dcore) { if (isShutDown) { throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "Solr has shutdown."); } final String name = dcore.getName(); try { // Make the instanceDir relative to the cores instanceDir if not absolute File idir = new File(dcore.getInstanceDir()); String instanceDir = idir.getPath(); log.info("Creating SolrCore '{}' using instanceDir: {}", dcore.getName(), instanceDir); // Initialize the solr config SolrCore created = null; if (zkSys.getZkController() != null) { created = zkSys.createFromZk(instanceDir, dcore, loader); } else { created = createFromLocal(instanceDir, dcore); } solrCores.addCreated(created); // For persisting newly-created cores. return created; // :TODO: Java7... // http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html } catch (Exception ex) { throw recordAndThrow(name, "Unable to create core: " + name, ex); } }
SolrCore function(CoreDescriptor dcore) { if (isShutDown) { throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, STR); } final String name = dcore.getName(); try { File idir = new File(dcore.getInstanceDir()); String instanceDir = idir.getPath(); log.info(STR, dcore.getName(), instanceDir); SolrCore created = null; if (zkSys.getZkController() != null) { created = zkSys.createFromZk(instanceDir, dcore, loader); } else { created = createFromLocal(instanceDir, dcore); } solrCores.addCreated(created); return created; } catch (Exception ex) { throw recordAndThrow(name, STR + name, ex); } }
/** * Creates a new core based on a descriptor but does not register it. * * @param dcore a core descriptor * @return the newly created core */
Creates a new core based on a descriptor but does not register it
create
{ "repo_name": "pengzong1111/solr4", "path": "solr/core/src/java/org/apache/solr/core/CoreContainer.java", "license": "apache-2.0", "size": 35446 }
[ "java.io.File", "org.apache.solr.common.SolrException" ]
import java.io.File; import org.apache.solr.common.SolrException;
import java.io.*; import org.apache.solr.common.*;
[ "java.io", "org.apache.solr" ]
java.io; org.apache.solr;
488,578
boolean pressedOrFocused = false; for (int state : states) { if (state == android.R.attr.state_pressed || state == android.R.attr.state_focused) { pressedOrFocused = true; break; } } if (pressedOrFocused) { super.setColorFilter(getPressedColor(color), PorterDuff.Mode.SRC_ATOP); } else { super.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } return super.onStateChange(states); }
boolean pressedOrFocused = false; for (int state : states) { if (state == android.R.attr.state_pressed state == android.R.attr.state_focused) { pressedOrFocused = true; break; } } if (pressedOrFocused) { super.setColorFilter(getPressedColor(color), PorterDuff.Mode.SRC_ATOP); } else { super.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } return super.onStateChange(states); }
/** * Called when the drawable's state gets changed (pressed, focused, etc). * * @param states the array of the drawable's states * @return true if the state change has caused the appearance of * the Drawable to change (that is, it needs to be drawn), else false * if it looks the same and there is no need to redraw it since its the * last state. */
Called when the drawable's state gets changed (pressed, focused, etc)
onStateChange
{ "repo_name": "iluxonchik/markitdown", "path": "MarkItDown/colorpicker/src/main/java/io/github/iluxonchik/colorpicker/ColorStateDrawable.java", "license": "mit", "size": 2249 }
[ "android.graphics.PorterDuff" ]
import android.graphics.PorterDuff;
import android.graphics.*;
[ "android.graphics" ]
android.graphics;
94,167
void validateSubPartitionValues(List<String> subPartitionValues) throws IllegalArgumentException { int subPartitionValuesCount = CollectionUtils.size(subPartitionValues); Assert.isTrue(subPartitionValuesCount <= BusinessObjectDataEntity.MAX_SUBPARTITIONS, String.format("Exceeded maximum number of allowed subpartitions: %d.", BusinessObjectDataEntity.MAX_SUBPARTITIONS)); for (int i = 0; i < subPartitionValuesCount; i++) { subPartitionValues.set(i, alternateKeyHelper.validateStringParameter("subpartition value", subPartitionValues.get(i))); } }
void validateSubPartitionValues(List<String> subPartitionValues) throws IllegalArgumentException { int subPartitionValuesCount = CollectionUtils.size(subPartitionValues); Assert.isTrue(subPartitionValuesCount <= BusinessObjectDataEntity.MAX_SUBPARTITIONS, String.format(STR, BusinessObjectDataEntity.MAX_SUBPARTITIONS)); for (int i = 0; i < subPartitionValuesCount; i++) { subPartitionValues.set(i, alternateKeyHelper.validateStringParameter(STR, subPartitionValues.get(i))); } }
/** * Validates a list of sub-partition values. This method also trims the sub-partition values. * * @param subPartitionValues the list of sub-partition values * * @throws IllegalArgumentException if a sub-partition value is missing or not valid */
Validates a list of sub-partition values. This method also trims the sub-partition values
validateSubPartitionValues
{ "repo_name": "FINRAOS/herd", "path": "herd-code/herd-service/src/main/java/org/finra/herd/service/helper/BusinessObjectDataHelper.java", "license": "apache-2.0", "size": 47970 }
[ "java.util.List", "org.apache.commons.collections4.CollectionUtils", "org.finra.herd.model.jpa.BusinessObjectDataEntity", "org.springframework.util.Assert" ]
import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.finra.herd.model.jpa.BusinessObjectDataEntity; import org.springframework.util.Assert;
import java.util.*; import org.apache.commons.collections4.*; import org.finra.herd.model.jpa.*; import org.springframework.util.*;
[ "java.util", "org.apache.commons", "org.finra.herd", "org.springframework.util" ]
java.util; org.apache.commons; org.finra.herd; org.springframework.util;
457,009
public ProcessApplicationRegistration registerProcessApplicationForDeployment(String deploymentId, ProcessApplicationReference reference) { DefaultProcessApplicationRegistration registration = registrationsByDeploymentId.get(deploymentId); if(registration == null) { String processEngineName = Context.getProcessEngineConfiguration().getProcessEngineName(); registration = new DefaultProcessApplicationRegistration(reference, deploymentId, processEngineName); registrationsByDeploymentId.put(deploymentId, registration); return registration; } else { throw new ProcessEngineException("Cannot register process application for deploymentId '" + deploymentId + "' there already is a registration for the same deployment."); } }
ProcessApplicationRegistration function(String deploymentId, ProcessApplicationReference reference) { DefaultProcessApplicationRegistration registration = registrationsByDeploymentId.get(deploymentId); if(registration == null) { String processEngineName = Context.getProcessEngineConfiguration().getProcessEngineName(); registration = new DefaultProcessApplicationRegistration(reference, deploymentId, processEngineName); registrationsByDeploymentId.put(deploymentId, registration); return registration; } else { throw new ProcessEngineException(STR + deploymentId + STR); } }
/** * Register a deployment for a given {@link ProcessApplicationReference}. * * @param deploymentId * @param reference * @return */
Register a deployment for a given <code>ProcessApplicationReference</code>
registerProcessApplicationForDeployment
{ "repo_name": "clintmanning/new-empty", "path": "engine/src/main/java/org/camunda/bpm/engine/impl/application/ProcessApplicationManager.java", "license": "apache-2.0", "size": 3426 }
[ "org.camunda.bpm.application.ProcessApplicationReference", "org.camunda.bpm.application.ProcessApplicationRegistration", "org.camunda.bpm.engine.ProcessEngineException", "org.camunda.bpm.engine.impl.context.Context" ]
import org.camunda.bpm.application.ProcessApplicationReference; import org.camunda.bpm.application.ProcessApplicationRegistration; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.application.*; import org.camunda.bpm.engine.*; import org.camunda.bpm.engine.impl.context.*;
[ "org.camunda.bpm" ]
org.camunda.bpm;
200,108
protected int checkLockOwnership(HttpServletRequest request, SmbFile file) throws IOException { LockManager lockManager = getLockManager(); if (lockManager == null) return HttpServletResponse.SC_OK; Lock[] locks = lockManager.getActiveLocks(file); if (locks == null || locks.length == 0) { Log.log(Log.DEBUG, "No outstanding locks on resource - proceed."); return HttpServletResponse.SC_OK; } Principal requestor = getPrincipal(request); if (requestor == null) { Log.log(Log.DEBUG, "Outstanding locks, but unidentified requestor."); return SC_LOCKED; } if (Log.getThreshold() < Log.INFORMATION) { StringBuffer outstanding = new StringBuffer(); for (int i = 0; i < locks.length; i++) { outstanding.append(" ").append(locks[i]); if (i + 1 < locks.length) outstanding.append("\n"); } Log.log(Log.DEBUG, "Outstanding locks:\n{0}", outstanding); } String name = requestor.getName(); for (int i = locks.length - 1; i >= 0; i--) { Principal owner = locks[i].getPrincipal(); if (owner == null) continue; if (name.equals(owner.getName())) { Log.log(Log.DEBUG, "Found lock - proceed: {0}", locks[i]); return HttpServletResponse.SC_OK; } } Log.log(Log.DEBUG, "Outstanding locks, but none held by requestor."); return SC_LOCKED; }
int function(HttpServletRequest request, SmbFile file) throws IOException { LockManager lockManager = getLockManager(); if (lockManager == null) return HttpServletResponse.SC_OK; Lock[] locks = lockManager.getActiveLocks(file); if (locks == null locks.length == 0) { Log.log(Log.DEBUG, STR); return HttpServletResponse.SC_OK; } Principal requestor = getPrincipal(request); if (requestor == null) { Log.log(Log.DEBUG, STR); return SC_LOCKED; } if (Log.getThreshold() < Log.INFORMATION) { StringBuffer outstanding = new StringBuffer(); for (int i = 0; i < locks.length; i++) { outstanding.append(" ").append(locks[i]); if (i + 1 < locks.length) outstanding.append("\n"); } Log.log(Log.DEBUG, STR, outstanding); } String name = requestor.getName(); for (int i = locks.length - 1; i >= 0; i--) { Principal owner = locks[i].getPrincipal(); if (owner == null) continue; if (name.equals(owner.getName())) { Log.log(Log.DEBUG, STR, locks[i]); return HttpServletResponse.SC_OK; } } Log.log(Log.DEBUG, STR); return SC_LOCKED; }
/** * Checks lock ownership. This ensures that either no lock is outstanding * on the requested resource, or at least one of the outstanding locks on * the resource is held by the requesting principal * * @param request The request being serviced. * @param file The requested resource. * @return An <code>int</code> containing the return HTTP status code. * @throws IOException If an IO error occurs. */
Checks lock ownership. This ensures that either no lock is outstanding on the requested resource, or at least one of the outstanding locks on the resource is held by the requesting principal
checkLockOwnership
{ "repo_name": "yeonsh/davenport", "path": "src/java/smbdav/AbstractHandler.java", "license": "lgpl-2.1", "size": 38359 }
[ "java.io.IOException", "java.security.Principal", "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse", "jcifs.smb.SmbFile" ]
import java.io.IOException; import java.security.Principal; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jcifs.smb.SmbFile;
import java.io.*; import java.security.*; import javax.servlet.http.*; import jcifs.smb.*;
[ "java.io", "java.security", "javax.servlet", "jcifs.smb" ]
java.io; java.security; javax.servlet; jcifs.smb;
1,020,966
public PrivateGateway createVpcPrivateGateway(long vpcId, String ipAddress, String gateway, String netmask, long gatewayDomainId, Long networkId, Boolean isSourceNat, Long aclId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException;
PrivateGateway function(long vpcId, String ipAddress, String gateway, String netmask, long gatewayDomainId, Long networkId, Boolean isSourceNat, Long aclId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException;
/** * Persists VPC private gateway in the Database. * * @param vpcId * @param ipAddress * @param gateway * @param netmask * @param gatewayDomainId * @param networkId * @param aclId * @return * @throws InsufficientCapacityException * @throws ConcurrentOperationException * @throws ResourceAllocationException */
Persists VPC private gateway in the Database
createVpcPrivateGateway
{ "repo_name": "MissionCriticalCloud/cosmic", "path": "cosmic-core/api/src/main/java/com/cloud/network/vpc/VpcService.java", "license": "apache-2.0", "size": 8625 }
[ "com.cloud.legacymodel.exceptions.ConcurrentOperationException", "com.cloud.legacymodel.exceptions.InsufficientCapacityException", "com.cloud.legacymodel.exceptions.ResourceAllocationException", "com.cloud.legacymodel.network.vpc.PrivateGateway" ]
import com.cloud.legacymodel.exceptions.ConcurrentOperationException; import com.cloud.legacymodel.exceptions.InsufficientCapacityException; import com.cloud.legacymodel.exceptions.ResourceAllocationException; import com.cloud.legacymodel.network.vpc.PrivateGateway;
import com.cloud.legacymodel.exceptions.*; import com.cloud.legacymodel.network.vpc.*;
[ "com.cloud.legacymodel" ]
com.cloud.legacymodel;
2,636,244
static DbDataLinkInterfaceEntry get(int nid) throws SQLException { Connection db = null; try { db = DataSourceFactory.getInstance().getConnection(); return get(db, nid); } finally { try { if (db != null) db.close(); } catch (SQLException e) { LogUtils.warnf(DbDataLinkInterfaceEntry.class, e, "Exception closing JDBC connection"); } } }
static DbDataLinkInterfaceEntry get(int nid) throws SQLException { Connection db = null; try { db = DataSourceFactory.getInstance().getConnection(); return get(db, nid); } finally { try { if (db != null) db.close(); } catch (SQLException e) { LogUtils.warnf(DbDataLinkInterfaceEntry.class, e, STR); } } }
/** * Retreives a current record from the database based upon the * key field of <em>nodeID</em>. If the * record cannot be found then a null reference is returnd. * * @param nid The node id key * * @return The loaded entry or null if one could not be found. * */
Retreives a current record from the database based upon the key field of nodeID. If the record cannot be found then a null reference is returnd
get
{ "repo_name": "bugcy013/opennms-tmp-tools", "path": "opennms-services/src/main/java/org/opennms/netmgt/linkd/DbDataLinkInterfaceEntry.java", "license": "gpl-2.0", "size": 18311 }
[ "java.sql.Connection", "java.sql.SQLException", "org.opennms.core.db.DataSourceFactory", "org.opennms.core.utils.LogUtils" ]
import java.sql.Connection; import java.sql.SQLException; import org.opennms.core.db.DataSourceFactory; import org.opennms.core.utils.LogUtils;
import java.sql.*; import org.opennms.core.db.*; import org.opennms.core.utils.*;
[ "java.sql", "org.opennms.core" ]
java.sql; org.opennms.core;
461,125
private static void assertIllegalArguments(FsCommand cmd, String... args) { try { cmd.run(args); fail("Expected IllegalArgumentException from args: " + Arrays.toString(args)); } catch (IllegalArgumentException e) { } }
static void function(FsCommand cmd, String... args) { try { cmd.run(args); fail(STR + Arrays.toString(args)); } catch (IllegalArgumentException e) { } }
/** * Asserts that for the given command, the given arguments are considered * invalid. The expectation is that the command will throw * IllegalArgumentException. * * @param cmd FsCommand to check * @param args String... arguments to check */
Asserts that for the given command, the given arguments are considered invalid. The expectation is that the command will throw IllegalArgumentException
assertIllegalArguments
{ "repo_name": "robzor92/hops", "path": "hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestFsShellReturnCode.java", "license": "apache-2.0", "size": 18989 }
[ "java.util.Arrays", "org.apache.hadoop.fs.shell.FsCommand", "org.junit.Assert" ]
import java.util.Arrays; import org.apache.hadoop.fs.shell.FsCommand; import org.junit.Assert;
import java.util.*; import org.apache.hadoop.fs.shell.*; import org.junit.*;
[ "java.util", "org.apache.hadoop", "org.junit" ]
java.util; org.apache.hadoop; org.junit;
2,860,293
Set<Subtopology> subtopologies();
Set<Subtopology> subtopologies();
/** * All sub-topologies of the represented topology. * @return set of all sub-topologies */
All sub-topologies of the represented topology
subtopologies
{ "repo_name": "zzwlstarby/mykafka", "path": "streams/src/main/java/org/apache/kafka/streams/TopologyDescription.java", "license": "apache-2.0", "size": 5271 }
[ "java.util.Set" ]
import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
2,852,709
@Override public void eventDispatched(AWTEvent event) { boolean discard = disposedWindowMonitor.isDuplicateDispose(event); if (!discard && listener != null) { delegate(event); } }
void function(AWTEvent event) { boolean discard = disposedWindowMonitor.isDuplicateDispose(event); if (!discard && listener != null) { delegate(event); } }
/** * Event reception callback. * * @param event the dispatched event. */
Event reception callback
eventDispatched
{ "repo_name": "google/fest", "path": "third_party/fest-swing/src/main/java/org/fest/swing/input/EventNormalizer.java", "license": "apache-2.0", "size": 2839 }
[ "java.awt.AWTEvent" ]
import java.awt.AWTEvent;
import java.awt.*;
[ "java.awt" ]
java.awt;
870,982
EAttribute getInputDescriptionType_MinOccurs();
EAttribute getInputDescriptionType_MinOccurs();
/** * Returns the meta object for the attribute '{@link net.opengis.wps20.InputDescriptionType#getMinOccurs <em>Min Occurs</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Min Occurs</em>'. * @see net.opengis.wps20.InputDescriptionType#getMinOccurs() * @see #getInputDescriptionType() * @generated */
Returns the meta object for the attribute '<code>net.opengis.wps20.InputDescriptionType#getMinOccurs Min Occurs</code>'.
getInputDescriptionType_MinOccurs
{ "repo_name": "geotools/geotools", "path": "modules/ogc/net.opengis.wps/src/net/opengis/wps20/Wps20Package.java", "license": "lgpl-2.1", "size": 228745 }
[ "org.eclipse.emf.ecore.EAttribute" ]
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
173,220
public EmbeddedActiveMQ getServer() { return server; }
EmbeddedActiveMQ function() { return server; }
/** * Get the EmbeddedActiveMQ server. * * This may be required for advanced configuration of the EmbeddedActiveMQ server. * * @return the embedded ActiveMQ broker */
Get the EmbeddedActiveMQ server. This may be required for advanced configuration of the EmbeddedActiveMQ server
getServer
{ "repo_name": "okalmanRH/jboss-activemq-artemis", "path": "artemis-junit/src/main/java/org/apache/activemq/artemis/junit/EmbeddedActiveMQResource.java", "license": "apache-2.0", "size": 31465 }
[ "org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ" ]
import org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ;
import org.apache.activemq.artemis.core.server.embedded.*;
[ "org.apache.activemq" ]
org.apache.activemq;
737,259
public void create_board(IntBox p_bounding_box, LayerStructure p_layer_structure, PolylineShape[] p_outline_shapes, String p_outline_clearance_class_name, BoardRules p_rules, board.Communication p_board_communication, TestLevel p_test_level) { if (this.board != null) { System.out.println(" BoardHandling.create_board: board already created"); } int outline_cl_class_no = 0; if (p_rules != null) { if (p_outline_clearance_class_name != null && p_rules.clearance_matrix != null) { outline_cl_class_no = p_rules.clearance_matrix.get_no(p_outline_clearance_class_name); outline_cl_class_no = Math.max(outline_cl_class_no, 0); } else { outline_cl_class_no = p_rules.get_default_net_class().default_item_clearance_classes.get(rules.DefaultItemClearanceClasses.ItemClass.AREA); } } this.board = new RoutingBoard(p_bounding_box, p_layer_structure, p_outline_shapes, outline_cl_class_no, p_rules, p_board_communication, p_test_level); // create the interactive settings with default double unit_factor = p_board_communication.coordinate_transform.board_to_dsn(1); this.coordinate_transform = new CoordinateTransform(1, p_board_communication.unit, unit_factor, p_board_communication.unit); this.settings = new Settings(this.board, this.logfile); // create a graphics context for the board Dimension panel_size = panel.getPreferredSize(); graphics_context = new GraphicsContext(p_bounding_box, panel_size, p_layer_structure, this.locale); }
void function(IntBox p_bounding_box, LayerStructure p_layer_structure, PolylineShape[] p_outline_shapes, String p_outline_clearance_class_name, BoardRules p_rules, board.Communication p_board_communication, TestLevel p_test_level) { if (this.board != null) { System.out.println(STR); } int outline_cl_class_no = 0; if (p_rules != null) { if (p_outline_clearance_class_name != null && p_rules.clearance_matrix != null) { outline_cl_class_no = p_rules.clearance_matrix.get_no(p_outline_clearance_class_name); outline_cl_class_no = Math.max(outline_cl_class_no, 0); } else { outline_cl_class_no = p_rules.get_default_net_class().default_item_clearance_classes.get(rules.DefaultItemClearanceClasses.ItemClass.AREA); } } this.board = new RoutingBoard(p_bounding_box, p_layer_structure, p_outline_shapes, outline_cl_class_no, p_rules, p_board_communication, p_test_level); double unit_factor = p_board_communication.coordinate_transform.board_to_dsn(1); this.coordinate_transform = new CoordinateTransform(1, p_board_communication.unit, unit_factor, p_board_communication.unit); this.settings = new Settings(this.board, this.logfile); Dimension panel_size = panel.getPreferredSize(); graphics_context = new GraphicsContext(p_bounding_box, panel_size, p_layer_structure, this.locale); }
/** * Creates the Routingboard, the graphic context and the interactive settings. */
Creates the Routingboard, the graphic context and the interactive settings
create_board
{ "repo_name": "32bitmicro/Freerouting", "path": "sources/interactive/BoardHandling.java", "license": "gpl-3.0", "size": 56816 }
[ "java.awt.Dimension" ]
import java.awt.Dimension;
import java.awt.*;
[ "java.awt" ]
java.awt;
468,196
protected void setTextColor(Color color) { if (color.equals(mLastTextColor) == false) { mLastTextColor = color; float[] rgb = color.getRGBColorComponents(null); setTextColor(getPrintDC(), (int) (rgb[0] * MAX_WCOLOR), (int) (rgb[1] * MAX_WCOLOR), (int) (rgb[2] * MAX_WCOLOR)); } }
void function(Color color) { if (color.equals(mLastTextColor) == false) { mLastTextColor = color; float[] rgb = color.getRGBColorComponents(null); setTextColor(getPrintDC(), (int) (rgb[0] * MAX_WCOLOR), (int) (rgb[1] * MAX_WCOLOR), (int) (rgb[2] * MAX_WCOLOR)); } }
/** * Set the GDI color for text drawing. */
Set the GDI color for text drawing
setTextColor
{ "repo_name": "JetBrains/jdk8u_jdk", "path": "src/windows/classes/sun/awt/windows/WPrinterJob.java", "license": "gpl-2.0", "size": 77917 }
[ "java.awt.Color" ]
import java.awt.Color;
import java.awt.*;
[ "java.awt" ]
java.awt;
1,519,572
@Transactional public Artist findByName(final String name) { return this.query().from(artist) .where(artist.name.equalsIgnoreCase(name)) .singleResult(artist); }
Artist function(final String name) { return this.query().from(artist) .where(artist.name.equalsIgnoreCase(name)) .singleResult(artist); }
/** * Get an artist by name. * * @param name * The (case-ignored) name of the artist. * @return The artist, if found. */
Get an artist by name
findByName
{ "repo_name": "MoodCat/MoodCat.me-Core", "path": "src/main/java/me/moodcat/database/controllers/ArtistDAO.java", "license": "mit", "size": 1491 }
[ "me.moodcat.database.entities.Artist" ]
import me.moodcat.database.entities.Artist;
import me.moodcat.database.entities.*;
[ "me.moodcat.database" ]
me.moodcat.database;
748,628
@Test public void testFailedUnmarshallingLogging() throws Exception { OptimizedMarshaller marsh = new OptimizedMarshaller(true); marsh.setContext(CTX); try { marsh.unmarshal(marsh.marshal(new BadDeserializableObject()), null); } catch (IgniteCheckedException ex) { assertTrue(ex.getCause().getMessage().contains( "object [typeName=org.apache.ignite.internal.marshaller.optimized.OptimizedObjectStreamSelfTest$BadDeserializableObject]")); assertTrue(ex.getCause().getCause().getMessage().contains("field [name=val")); } }
void function() throws Exception { OptimizedMarshaller marsh = new OptimizedMarshaller(true); marsh.setContext(CTX); try { marsh.unmarshal(marsh.marshal(new BadDeserializableObject()), null); } catch (IgniteCheckedException ex) { assertTrue(ex.getCause().getMessage().contains( STR)); assertTrue(ex.getCause().getCause().getMessage().contains(STR)); } }
/** * Test informative exception message while failed object unmarshalling * * @throws Exception If failed. */
Test informative exception message while failed object unmarshalling
testFailedUnmarshallingLogging
{ "repo_name": "ilantukh/ignite", "path": "modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/OptimizedObjectStreamSelfTest.java", "license": "apache-2.0", "size": 64396 }
[ "org.apache.ignite.IgniteCheckedException" ]
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.*;
[ "org.apache.ignite" ]
org.apache.ignite;
22,605
public static Long generateCalendarInMillis(Command command) { return generateCalendar(command).getTimeInMillis(); }
static Long function(Command command) { return generateCalendar(command).getTimeInMillis(); }
/** * Given a command, it generates a calendar instance representing the event * timestamp in milliseconds <br> * <b>In case of errors it throws an unchecked exception</b> * * @param command * @return a long representing the event timestamp with milliseconds * precision set to zero */
Given a command, it generates a calendar instance representing the event timestamp in milliseconds In case of errors it throws an unchecked exception
generateCalendarInMillis
{ "repo_name": "abollaert/freedomotic", "path": "plugins/devices/persistence/src/main/java/com/freedomotic/plugins/devices/persistence/util/PersistenceUtility.java", "license": "gpl-2.0", "size": 2777 }
[ "com.freedomotic.reactions.Command" ]
import com.freedomotic.reactions.Command;
import com.freedomotic.reactions.*;
[ "com.freedomotic.reactions" ]
com.freedomotic.reactions;
2,301,352
protected HashEntry nextEntry() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } HashEntry newCurrent = next; if (newCurrent == null) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } HashEntry[] data = parent.data; int i = hashIndex; HashEntry n = newCurrent.next; while (n == null && i > 0) { n = data[--i]; } next = n; hashIndex = i; last = newCurrent; return newCurrent; }
HashEntry function() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } HashEntry newCurrent = next; if (newCurrent == null) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } HashEntry[] data = parent.data; int i = hashIndex; HashEntry n = newCurrent.next; while (n == null && i > 0) { n = data[--i]; } next = n; hashIndex = i; last = newCurrent; return newCurrent; }
/** * Next entry. * @return next entry. */
Next entry
nextEntry
{ "repo_name": "mobile-event-processing/Asper", "path": "source/src/com/espertech/esper/collection/apachecommons/AbstractHashedMap.java", "license": "gpl-2.0", "size": 46252 }
[ "java.util.ConcurrentModificationException", "java.util.NoSuchElementException" ]
import java.util.ConcurrentModificationException; import java.util.NoSuchElementException;
import java.util.*;
[ "java.util" ]
java.util;
1,398,397
protected void drawAxisSystem(boolean startDrawing) { Tessellator tessellator = Tessellator.instance; if (startDrawing) { tessellator.startDrawingQuads(); } tessellator.addVertexWithUV(-0.005F, 2, 0, 1, 0); tessellator.addVertexWithUV(0.005F, 2, 0, 0, 0); tessellator.addVertexWithUV(0.005F, -1, 0, 0, 1); tessellator.addVertexWithUV(-0.005F, -1, 0, 1, 1); tessellator.addVertexWithUV(2, -0.005F, 0, 1, 0); tessellator.addVertexWithUV(2, 0.005F, 0, 0, 0); tessellator.addVertexWithUV(-1, 0.005F, 0, 0, 1); tessellator.addVertexWithUV(-1, -0.005F, 0, 1, 1); tessellator.addVertexWithUV(0, -0.005F, 2, 1, 0); tessellator.addVertexWithUV(0, 0.005F, 2, 0, 0); tessellator.addVertexWithUV(0, 0.005F, -1, 0, 1); tessellator.addVertexWithUV(0, -0.005F, -1, 1, 1); if (startDrawing) { tessellator.draw(); } }
void function(boolean startDrawing) { Tessellator tessellator = Tessellator.instance; if (startDrawing) { tessellator.startDrawingQuads(); } tessellator.addVertexWithUV(-0.005F, 2, 0, 1, 0); tessellator.addVertexWithUV(0.005F, 2, 0, 0, 0); tessellator.addVertexWithUV(0.005F, -1, 0, 0, 1); tessellator.addVertexWithUV(-0.005F, -1, 0, 1, 1); tessellator.addVertexWithUV(2, -0.005F, 0, 1, 0); tessellator.addVertexWithUV(2, 0.005F, 0, 0, 0); tessellator.addVertexWithUV(-1, 0.005F, 0, 0, 1); tessellator.addVertexWithUV(-1, -0.005F, 0, 1, 1); tessellator.addVertexWithUV(0, -0.005F, 2, 1, 0); tessellator.addVertexWithUV(0, 0.005F, 2, 0, 0); tessellator.addVertexWithUV(0, 0.005F, -1, 0, 1); tessellator.addVertexWithUV(0, -0.005F, -1, 1, 1); if (startDrawing) { tessellator.draw(); } }
/** * Utility method helpful for debugging */
Utility method helpful for debugging
drawAxisSystem
{ "repo_name": "InfinityRaider/SteamPowerAdditions", "path": "src/main/java/com/InfinityRaider/SteamPowerAdditions/renderer/block/RenderBlockBase.java", "license": "mit", "size": 19558 }
[ "net.minecraft.client.renderer.Tessellator" ]
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.*;
[ "net.minecraft.client" ]
net.minecraft.client;
135,154
private void bindData(Contact data) { final ResolveCache cache = ResolveCache.getInstance(this); final Context context = this; ExtensionManager.getInstance().getContactAccountExtension().setCurrentSlot(data.getSlot(), ExtensionManager.COMMD_FOR_AAS); mOpenDetailsImage.setVisibility(isMimeExcluded(Contacts.CONTENT_ITEM_TYPE) ? View.GONE : View.VISIBLE); mDefaultsMap.clear(); mStopWatch.lap("sph"); // Start photo setting final ImageView photoView = (ImageView) mPhotoContainer.findViewById(R.id.photo); mPhotoSetter.setupContactPhoto(data, photoView); mStopWatch.lap("ph"); // Photo set for (RawContact rawContact : data.getRawContacts()) { for (DataItem dataItem : rawContact.getDataItems()) { final String mimeType = dataItem.getMimeType(); // Skip this data item if MIME-type excluded if (isMimeExcluded(mimeType)) continue; final long dataId = dataItem.getId(); final boolean isPrimary = dataItem.isPrimary(); final boolean isSuperPrimary = dataItem.isSuperPrimary(); DataKind kind = dataItem.getDataKind(); boolean reslut = ExtensionManager.getInstance().getContactDetailExtension() .getExtentionKind(mimeType, true, dataItem.getContentValues().getAsString(Contacts.DISPLAY_NAME), ExtensionManager.COMMD_FOR_RCS); if (reslut) { kind = new DataKind(mimeType, 0, 10, false, R.layout.text_fields_editor_view); kind.actionBody = new SimpleInflater(Data.DATA1); kind.titleRes = 0; } if (kind != null) { // Build an action for this data entry, find a mapping to a UI // element, build its summary from the cursor, and collect it // along with all others of this MIME-type. boolean isDirectoryEntry = !data.isDirectoryEntry(); final Action action = new QuickDataAction(context, dataItem, isDirectoryEntry); final boolean wasAdded = considerAdd(action, cache, isSuperPrimary); if (wasAdded) { // Remember the default if (isSuperPrimary || (isPrimary && (mDefaultsMap.get(mimeType) == null))) { mDefaultsMap.put(mimeType, action); } } } // Handle Email rows with presence data as Im entry final DataStatus status = data.getStatuses().get(dataId); if (status != null && dataItem instanceof EmailDataItem) { final EmailDataItem email = (EmailDataItem) dataItem; final ImDataItem im = ImDataItem.createFromEmail(email); if (im.getDataKind() != null) { final DataAction action = new DataAction(context, im); action.setPresence(status.getPresence()); considerAdd(action, cache, isSuperPrimary); } } } } mStopWatch.lap("e"); // Entities inflated // Collapse Action Lists (remove e.g. duplicate e-mail addresses from different sources) Iterator<String> iter = mActions.keySet().iterator(); while (iter.hasNext()) { final String mimeType = iter.next(); if (ExtensionManager.getInstance().getQuickContactExtension().collapseListPhone( mimeType, ContactPluginDefault.COMMD_FOR_OP01)) { Collapser.collapseList(mActions.get(mimeType)); } } mStopWatch.lap("c"); // List collapsed setHeaderNameText(R.id.name, data.getDisplayName()); // All the mime-types to add. final Set<String> containedTypes = new HashSet<String>(mActions.keySet()); mSortedActionMimeTypes.clear(); // First, add LEADING_MIMETYPES, which are most common. for (String mimeType : LEADING_MIMETYPES) { if (containedTypes.contains(mimeType)) { mSortedActionMimeTypes.add(mimeType); containedTypes.remove(mimeType); } } // Add all the remaining ones that are not TRAILING for (String mimeType : containedTypes.toArray(new String[containedTypes.size()])) { if (!TRAILING_MIMETYPES.contains(mimeType)) { mSortedActionMimeTypes.add(mimeType); containedTypes.remove(mimeType); } } // Then, add TRAILING_MIMETYPES, which are least common. for (String mimeType : TRAILING_MIMETYPES) { if (containedTypes.contains(mimeType)) { containedTypes.remove(mimeType); mSortedActionMimeTypes.add(mimeType); } } mStopWatch.lap("mt"); // Mime types initialized // Add buttons for each mimetype mTrack.removeAllViews(); for (String mimeType : mSortedActionMimeTypes) { final View actionView = inflateAction(mimeType, cache, mTrack); mTrack.addView(actionView); } mStopWatch.lap("mt"); // Buttons added final boolean hasData = !mSortedActionMimeTypes.isEmpty(); mTrackScroller.setVisibility(hasData ? View.VISIBLE : View.GONE); mSelectedTabRectangle.setVisibility(hasData ? View.VISIBLE : View.GONE); mLineAfterTrack.setVisibility(hasData ? View.VISIBLE : View.GONE); mListPager.setVisibility(hasData ? View.VISIBLE : View.GONE); }
void function(Contact data) { final ResolveCache cache = ResolveCache.getInstance(this); final Context context = this; ExtensionManager.getInstance().getContactAccountExtension().setCurrentSlot(data.getSlot(), ExtensionManager.COMMD_FOR_AAS); mOpenDetailsImage.setVisibility(isMimeExcluded(Contacts.CONTENT_ITEM_TYPE) ? View.GONE : View.VISIBLE); mDefaultsMap.clear(); mStopWatch.lap("sph"); final ImageView photoView = (ImageView) mPhotoContainer.findViewById(R.id.photo); mPhotoSetter.setupContactPhoto(data, photoView); mStopWatch.lap("ph"); for (RawContact rawContact : data.getRawContacts()) { for (DataItem dataItem : rawContact.getDataItems()) { final String mimeType = dataItem.getMimeType(); if (isMimeExcluded(mimeType)) continue; final long dataId = dataItem.getId(); final boolean isPrimary = dataItem.isPrimary(); final boolean isSuperPrimary = dataItem.isSuperPrimary(); DataKind kind = dataItem.getDataKind(); boolean reslut = ExtensionManager.getInstance().getContactDetailExtension() .getExtentionKind(mimeType, true, dataItem.getContentValues().getAsString(Contacts.DISPLAY_NAME), ExtensionManager.COMMD_FOR_RCS); if (reslut) { kind = new DataKind(mimeType, 0, 10, false, R.layout.text_fields_editor_view); kind.actionBody = new SimpleInflater(Data.DATA1); kind.titleRes = 0; } if (kind != null) { boolean isDirectoryEntry = !data.isDirectoryEntry(); final Action action = new QuickDataAction(context, dataItem, isDirectoryEntry); final boolean wasAdded = considerAdd(action, cache, isSuperPrimary); if (wasAdded) { if (isSuperPrimary (isPrimary && (mDefaultsMap.get(mimeType) == null))) { mDefaultsMap.put(mimeType, action); } } } final DataStatus status = data.getStatuses().get(dataId); if (status != null && dataItem instanceof EmailDataItem) { final EmailDataItem email = (EmailDataItem) dataItem; final ImDataItem im = ImDataItem.createFromEmail(email); if (im.getDataKind() != null) { final DataAction action = new DataAction(context, im); action.setPresence(status.getPresence()); considerAdd(action, cache, isSuperPrimary); } } } } mStopWatch.lap("e"); Iterator<String> iter = mActions.keySet().iterator(); while (iter.hasNext()) { final String mimeType = iter.next(); if (ExtensionManager.getInstance().getQuickContactExtension().collapseListPhone( mimeType, ContactPluginDefault.COMMD_FOR_OP01)) { Collapser.collapseList(mActions.get(mimeType)); } } mStopWatch.lap("c"); setHeaderNameText(R.id.name, data.getDisplayName()); final Set<String> containedTypes = new HashSet<String>(mActions.keySet()); mSortedActionMimeTypes.clear(); for (String mimeType : LEADING_MIMETYPES) { if (containedTypes.contains(mimeType)) { mSortedActionMimeTypes.add(mimeType); containedTypes.remove(mimeType); } } for (String mimeType : containedTypes.toArray(new String[containedTypes.size()])) { if (!TRAILING_MIMETYPES.contains(mimeType)) { mSortedActionMimeTypes.add(mimeType); containedTypes.remove(mimeType); } } for (String mimeType : TRAILING_MIMETYPES) { if (containedTypes.contains(mimeType)) { containedTypes.remove(mimeType); mSortedActionMimeTypes.add(mimeType); } } mStopWatch.lap("mt"); mTrack.removeAllViews(); for (String mimeType : mSortedActionMimeTypes) { final View actionView = inflateAction(mimeType, cache, mTrack); mTrack.addView(actionView); } mStopWatch.lap("mt"); final boolean hasData = !mSortedActionMimeTypes.isEmpty(); mTrackScroller.setVisibility(hasData ? View.VISIBLE : View.GONE); mSelectedTabRectangle.setVisibility(hasData ? View.VISIBLE : View.GONE); mLineAfterTrack.setVisibility(hasData ? View.VISIBLE : View.GONE); mListPager.setVisibility(hasData ? View.VISIBLE : View.GONE); }
/** * Handle the result from the ContactLoader */
Handle the result from the ContactLoader
bindData
{ "repo_name": "rex-xxx/mt6572_x201", "path": "packages/apps/Contacts/src/com/android/contacts/quickcontact/QuickContactActivity.java", "license": "gpl-2.0", "size": 31608 }
[ "android.content.Context", "android.provider.ContactsContract", "android.view.View", "android.widget.ImageView", "com.android.contacts.Collapser", "com.android.contacts.ext.ContactPluginDefault", "com.android.contacts.model.Contact", "com.android.contacts.model.RawContact", "com.android.contacts.model.account.BaseAccountType", "com.android.contacts.model.dataitem.DataItem", "com.android.contacts.model.dataitem.DataKind", "com.android.contacts.model.dataitem.EmailDataItem", "com.android.contacts.model.dataitem.ImDataItem", "com.android.contacts.util.DataStatus", "com.mediatek.contacts.ExtensionManager", "com.mediatek.contacts.quickcontact.QuickDataAction", "java.util.HashSet", "java.util.Iterator", "java.util.Set" ]
import android.content.Context; import android.provider.ContactsContract; import android.view.View; import android.widget.ImageView; import com.android.contacts.Collapser; import com.android.contacts.ext.ContactPluginDefault; import com.android.contacts.model.Contact; import com.android.contacts.model.RawContact; import com.android.contacts.model.account.BaseAccountType; import com.android.contacts.model.dataitem.DataItem; import com.android.contacts.model.dataitem.DataKind; import com.android.contacts.model.dataitem.EmailDataItem; import com.android.contacts.model.dataitem.ImDataItem; import com.android.contacts.util.DataStatus; import com.mediatek.contacts.ExtensionManager; import com.mediatek.contacts.quickcontact.QuickDataAction; import java.util.HashSet; import java.util.Iterator; import java.util.Set;
import android.content.*; import android.provider.*; import android.view.*; import android.widget.*; import com.android.contacts.*; import com.android.contacts.ext.*; import com.android.contacts.model.*; import com.android.contacts.model.account.*; import com.android.contacts.model.dataitem.*; import com.android.contacts.util.*; import com.mediatek.contacts.*; import com.mediatek.contacts.quickcontact.*; import java.util.*;
[ "android.content", "android.provider", "android.view", "android.widget", "com.android.contacts", "com.mediatek.contacts", "java.util" ]
android.content; android.provider; android.view; android.widget; com.android.contacts; com.mediatek.contacts; java.util;
2,105,795
public B setAcceptQueue(final Integer value) { _acceptQueue = value; return self(); } @NotNull @NotEmpty private String _host = "localhost"; @NotNull @Range(min = 1, max = 65535) private Integer _port; @NotNull @Min(0) private Integer _acceptQueue = 100; }
B function(final Integer value) { _acceptQueue = value; return self(); } private String _host = STR; @Range(min = 1, max = 65535) private Integer _port; @Min(0) private Integer _acceptQueue = 100; }
/** * Sets the accept queue length. Optional. Cannot be null. Must be at * least 0. Default is 100. * * @param value the port to listen on * @return This builder */
Sets the accept queue length. Optional. Cannot be null. Must be at least 0. Default is 100
setAcceptQueue
{ "repo_name": "ArpNetworking/metrics-aggregator-daemon", "path": "src/main/java/com/arpnetworking/metrics/common/sources/BaseTcpSource.java", "license": "apache-2.0", "size": 11413 }
[ "net.sf.oval.constraint.Min", "net.sf.oval.constraint.Range" ]
import net.sf.oval.constraint.Min; import net.sf.oval.constraint.Range;
import net.sf.oval.constraint.*;
[ "net.sf.oval" ]
net.sf.oval;
1,082,352
public void setBars(Collection<Bar> bars) { this.bars = bars; }
void function(Collection<Bar> bars) { this.bars = bars; }
/** * JAVADOC Method Level Comments * * @param bars JAVADOC. */
JAVADOC Method Level Comments
setBars
{ "repo_name": "cucina/opencucina", "path": "engine/src/test/java/org/cucina/engine/testassist/Baz.java", "license": "apache-2.0", "size": 1481 }
[ "java.util.Collection" ]
import java.util.Collection;
import java.util.*;
[ "java.util" ]
java.util;
2,201,623
private Pair<Integer, Long> getPeriodPosition(int windowIndex, long windowPositionUs) { return timeline.getPeriodPosition(window, period, windowIndex, windowPositionUs); }
Pair<Integer, Long> function(int windowIndex, long windowPositionUs) { return timeline.getPeriodPosition(window, period, windowIndex, windowPositionUs); }
/** * Calls {@link Timeline#getPeriodPosition(Timeline.Window, Timeline.Period, int, long)} using the * current timeline. */
Calls <code>Timeline#getPeriodPosition(Timeline.Window, Timeline.Period, int, long)</code> using the current timeline
getPeriodPosition
{ "repo_name": "gysgogo/levetube", "path": "lib/src/main/java/com/google/android/exoplayer2/ExoPlayerImplInternal.java", "license": "gpl-3.0", "size": 67415 }
[ "android.util.Pair" ]
import android.util.Pair;
import android.util.*;
[ "android.util" ]
android.util;
295,006
@Test public void testContainedRegionOverlap() throws Exception { String table = "tableContainedRegionOverlap"; try { setupTable(table); assertEquals(ROWKEYS.length, countRows()); // Mess it up by creating an overlap in the metadata HRegionInfo hriOverlap = createRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("A2"), Bytes.toBytes("B")); TEST_UTIL.getHBaseCluster().getMaster().assignRegion(hriOverlap); TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager() .waitForAssignment(hriOverlap); HBaseFsck hbck = doFsck(conf, false); assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.OVERLAP_IN_REGION_CHAIN }); assertEquals(2, hbck.getOverlapGroups(table).size()); assertEquals(ROWKEYS.length, countRows()); // fix the problem. doFsck(conf, true); // verify that overlaps are fixed HBaseFsck hbck2 = doFsck(conf,false); assertNoErrors(hbck2); assertEquals(0, hbck2.getOverlapGroups(table).size()); assertEquals(ROWKEYS.length, countRows()); } finally { deleteTable(table); } }
void function() throws Exception { String table = STR; try { setupTable(table); assertEquals(ROWKEYS.length, countRows()); HRegionInfo hriOverlap = createRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("A2"), Bytes.toBytes("B")); TEST_UTIL.getHBaseCluster().getMaster().assignRegion(hriOverlap); TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager() .waitForAssignment(hriOverlap); HBaseFsck hbck = doFsck(conf, false); assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.OVERLAP_IN_REGION_CHAIN }); assertEquals(2, hbck.getOverlapGroups(table).size()); assertEquals(ROWKEYS.length, countRows()); doFsck(conf, true); HBaseFsck hbck2 = doFsck(conf,false); assertNoErrors(hbck2); assertEquals(0, hbck2.getOverlapGroups(table).size()); assertEquals(ROWKEYS.length, countRows()); } finally { deleteTable(table); } }
/** * This creates and fixes a bad table where a region is completely contained * by another region. */
This creates and fixes a bad table where a region is completely contained by another region
testContainedRegionOverlap
{ "repo_name": "ay65535/hbase-0.94.0", "path": "src/test/java/org/apache/hadoop/hbase/util/TestHBaseFsck.java", "license": "apache-2.0", "size": 33952 }
[ "org.apache.hadoop.hbase.HRegionInfo", "org.apache.hadoop.hbase.util.hbck.HbckTestingUtil", "org.junit.Assert" ]
import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.util.hbck.HbckTestingUtil; import org.junit.Assert;
import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.util.hbck.*; import org.junit.*;
[ "org.apache.hadoop", "org.junit" ]
org.apache.hadoop; org.junit;
353,691
@ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> renewAsync( String resourceGroupName, String certificateOrderName, RenewCertificateOrderRequest renewCertificateOrderRequest) { return renewWithResponseAsync(resourceGroupName, certificateOrderName, renewCertificateOrderRequest) .flatMap((Response<Void> res) -> Mono.empty()); }
@ServiceMethod(returns = ReturnType.SINGLE) Mono<Void> function( String resourceGroupName, String certificateOrderName, RenewCertificateOrderRequest renewCertificateOrderRequest) { return renewWithResponseAsync(resourceGroupName, certificateOrderName, renewCertificateOrderRequest) .flatMap((Response<Void> res) -> Mono.empty()); }
/** * Renew an existing certificate order. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param certificateOrderName Name of the certificate order. * @param renewCertificateOrderRequest Renew parameters. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */
Renew an existing certificate order
renewAsync
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceCertificateOrdersClientImpl.java", "license": "mit", "size": 205075 }
[ "com.azure.core.annotation.ReturnType", "com.azure.core.annotation.ServiceMethod", "com.azure.core.http.rest.Response", "com.azure.resourcemanager.appservice.models.RenewCertificateOrderRequest" ]
import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.resourcemanager.appservice.models.RenewCertificateOrderRequest;
import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.resourcemanager.appservice.models.*;
[ "com.azure.core", "com.azure.resourcemanager" ]
com.azure.core; com.azure.resourcemanager;
1,360,440
private boolean hasHighPriority(Character ch, MyStack<Character> oStack) { Objects.requireNonNull(oStack); if (oStack.isEmpty()) { return true; } else { return getPriority(ch) > getPriority(oStack.lookUp()); } }
boolean function(Character ch, MyStack<Character> oStack) { Objects.requireNonNull(oStack); if (oStack.isEmpty()) { return true; } else { return getPriority(ch) > getPriority(oStack.lookUp()); } }
/** * Check is the current Operator has a higher Priority than the operator on * top of the oStack * * @param ch the current operator * @param oStack the MyStack instance storing operators that need to be * dealt with * @return true is the current operator is higher priority than the top * operator of oStack regarding */
Check is the current Operator has a higher Priority than the operator on top of the oStack
hasHighPriority
{ "repo_name": "pingzhang88/JavaLab", "path": "2016_DataStructure/Stack/MathCalculator.java", "license": "apache-2.0", "size": 6407 }
[ "java.util.Objects" ]
import java.util.Objects;
import java.util.*;
[ "java.util" ]
java.util;
2,154,624
public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String virtualNetworkName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, virtualNetworkName), serviceCallback); }
ServiceFuture<Void> function(String resourceGroupName, String virtualNetworkName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, virtualNetworkName), serviceCallback); }
/** * Deletes the specified virtual network. * * @param resourceGroupName The name of the resource group. * @param virtualNetworkName The name of the virtual network. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */
Deletes the specified virtual network
beginDeleteAsync
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/network/mgmt-v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworksInner.java", "license": "mit", "size": 103125 }
[ "com.microsoft.rest.ServiceCallback", "com.microsoft.rest.ServiceFuture" ]
import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.*;
[ "com.microsoft.rest" ]
com.microsoft.rest;
1,993,607
public boolean updateMap(MapItem mapForUpdate) { MapsDatabase mapsDatabase = new MapsDatabase(mContext); try { mapsDatabase.open(); } catch (Exception e) { return false; } return mapsDatabase.updateItem(mapForUpdate); }
boolean function(MapItem mapForUpdate) { MapsDatabase mapsDatabase = new MapsDatabase(mContext); try { mapsDatabase.open(); } catch (Exception e) { return false; } return mapsDatabase.updateItem(mapForUpdate); }
/** * Updates a map provider from the database. * The mapForDeletion argument must have a valid name in order to update the other values. * <p/> * This method always returns immediately. * * @param mapForUpdate MapItem object with the parameters that need to be updated * @return true if the update was successful, false otherwise */
Updates a map provider from the database. The mapForDeletion argument must have a valid name in order to update the other values. This method always returns immediately
updateMap
{ "repo_name": "tesera/andbtiles", "path": "library/src/main/java/com/tesera/andbtiles/Andbtiles.java", "license": "mit", "size": 32220 }
[ "com.tesera.andbtiles.databases.MapsDatabase", "com.tesera.andbtiles.pojos.MapItem" ]
import com.tesera.andbtiles.databases.MapsDatabase; import com.tesera.andbtiles.pojos.MapItem;
import com.tesera.andbtiles.databases.*; import com.tesera.andbtiles.pojos.*;
[ "com.tesera.andbtiles" ]
com.tesera.andbtiles;
2,117,633
public BigInteger getDifficultyTargetAsInteger() throws VerificationException { maybeParseHeader(); BigInteger target = Utils.decodeCompactBits(difficultyTarget); if (target.signum() <= 0 || target.compareTo(params.proofOfWorkLimit) > 0) throw new VerificationException("Difficulty target is bad: " + target.toString()); return target; }
BigInteger function() throws VerificationException { maybeParseHeader(); BigInteger target = Utils.decodeCompactBits(difficultyTarget); if (target.signum() <= 0 target.compareTo(params.proofOfWorkLimit) > 0) throw new VerificationException(STR + target.toString()); return target; }
/** * Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the * target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception * is thrown. */
Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception is thrown
getDifficultyTargetAsInteger
{ "repo_name": "casinocoin/CasinocoinJ", "path": "Core/src/main/java/org/casinocoin/core/Block.java", "license": "apache-2.0", "size": 46319 }
[ "java.math.BigInteger" ]
import java.math.BigInteger;
import java.math.*;
[ "java.math" ]
java.math;
1,687,489
@Override public Adapter createFilterMediatorAdapter() { if (filterMediatorItemProvider == null) { filterMediatorItemProvider = new FilterMediatorItemProvider(this); } return filterMediatorItemProvider; } protected FilterContainerItemProvider filterContainerItemProvider;
Adapter function() { if (filterMediatorItemProvider == null) { filterMediatorItemProvider = new FilterMediatorItemProvider(this); } return filterMediatorItemProvider; } protected FilterContainerItemProvider filterContainerItemProvider;
/** * This creates an adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.FilterMediator}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
This creates an adapter for a <code>org.wso2.developerstudio.eclipse.gmf.esb.FilterMediator</code>.
createFilterMediatorAdapter
{ "repo_name": "nwnpallewela/devstudio-tooling-esb", "path": "plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/EsbItemProviderAdapterFactory.java", "license": "apache-2.0", "size": 304469 }
[ "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,044,635
public void testGetScanner_WithRegionClosed() { byte[] tableName = Bytes.toBytes("testtable"); byte[] fam1 = Bytes.toBytes("fam1"); byte[] fam2 = Bytes.toBytes("fam2"); byte[][] families = {fam1, fam2}; //Setting up region String method = this.getName(); try { initHRegion(tableName, method, families); } catch (IOException e) { e.printStackTrace(); fail("Got IOException during initHRegion, " + e.getMessage()); } region.closed.set(true); try { region.getScanner(null); fail("Expected to get an exception during getScanner on a region that is closed"); } catch (org.apache.hadoop.hbase.NotServingRegionException e) { //this is the correct exception that is expected } catch (IOException e) { fail("Got wrong type of exception - should be a NotServingRegionException, but was an IOException: " + e.getMessage()); } }
void function() { byte[] tableName = Bytes.toBytes(STR); byte[] fam1 = Bytes.toBytes("fam1"); byte[] fam2 = Bytes.toBytes("fam2"); byte[][] families = {fam1, fam2}; String method = this.getName(); try { initHRegion(tableName, method, families); } catch (IOException e) { e.printStackTrace(); fail(STR + e.getMessage()); } region.closed.set(true); try { region.getScanner(null); fail(STR); } catch (org.apache.hadoop.hbase.NotServingRegionException e) { } catch (IOException e) { fail(STR + e.getMessage()); } }
/** * This method tests https://issues.apache.org/jira/browse/HBASE-2516. */
This method tests HREF
testGetScanner_WithRegionClosed
{ "repo_name": "Shmuma/hbase", "path": "src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java", "license": "apache-2.0", "size": 99966 }
[ "java.io.IOException", "org.apache.hadoop.hbase.util.Bytes" ]
import java.io.IOException; import org.apache.hadoop.hbase.util.Bytes;
import java.io.*; import org.apache.hadoop.hbase.util.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
2,654,190
public Set<Code> getCodes() { return codes; }
Set<Code> function() { return codes; }
/** * Gets the codes. * * @return the codes */
Gets the codes
getCodes
{ "repo_name": "JaLandry/MeasureAuthoringTool_LatestSprint", "path": "mat/src/mat/model/ListObject.java", "license": "apache-2.0", "size": 8571 }
[ "java.util.Set" ]
import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
1,030,119
private String fieldPropertyComment(Field field) { String commentType = fieldTypeCardinalityComment(field); String fieldName = wrapIfKeywordOrBuiltIn(field.getSimpleName()); return fieldComment(String.format("@property {%s} %s", commentType, fieldName), null, field); }
String function(Field field) { String commentType = fieldTypeCardinalityComment(field); String fieldName = wrapIfKeywordOrBuiltIn(field.getSimpleName()); return fieldComment(String.format(STR, commentType, fieldName), null, field); }
/** * Returns a JSDoc comment string for the field as an attribute of a message. */
Returns a JSDoc comment string for the field as an attribute of a message
fieldPropertyComment
{ "repo_name": "tcoffee-google/toolkit", "path": "src/main/java/com/google/api/codegen/nodejs/NodeJSGapicContext.java", "license": "apache-2.0", "size": 14597 }
[ "com.google.api.tools.framework.model.Field" ]
import com.google.api.tools.framework.model.Field;
import com.google.api.tools.framework.model.*;
[ "com.google.api" ]
com.google.api;
2,905,711
public RelDataType matchNullability( RelDataType type, RexNode value) { boolean typeNullability = type.isNullable(); boolean valueNullability = value.getType().isNullable(); if (typeNullability != valueNullability) { return getTypeFactory().createTypeWithNullability( type, valueNullability); } return type; }
RelDataType function( RelDataType type, RexNode value) { boolean typeNullability = type.isNullable(); boolean valueNullability = value.getType().isNullable(); if (typeNullability != valueNullability) { return getTypeFactory().createTypeWithNullability( type, valueNullability); } return type; }
/** * Ensures that a type's nullability matches a value's nullability. */
Ensures that a type's nullability matches a value's nullability
matchNullability
{ "repo_name": "YrAuYong/incubator-calcite", "path": "core/src/main/java/org/apache/calcite/rex/RexBuilder.java", "license": "apache-2.0", "size": 43815 }
[ "org.apache.calcite.rel.type.RelDataType" ]
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.*;
[ "org.apache.calcite" ]
org.apache.calcite;
2,224,731
return new FamilyOperandTypeChecker(ImmutableList.copyOf(families), i -> false); }
return new FamilyOperandTypeChecker(ImmutableList.copyOf(families), i -> false); }
/** * Creates a checker that passes if each operand is a member of a * corresponding family. */
Creates a checker that passes if each operand is a member of a corresponding family
family
{ "repo_name": "datametica/calcite", "path": "core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java", "license": "apache-2.0", "size": 28820 }
[ "com.google.common.collect.ImmutableList" ]
import com.google.common.collect.ImmutableList;
import com.google.common.collect.*;
[ "com.google.common" ]
com.google.common;
1,335,209
private final TxInfo isNewRM (XAResource xaRes) { try { synchronized (this) { Enumeration el = _resources.keys(); if (el != null) { while (el.hasMoreElements()) { XAResource x = (XAResource) el.nextElement(); if (x.isSameRM(xaRes)) { return (TxInfo) _resources.get(x); } } } el = _duplicateResources.keys(); if (el != null) { while (el.hasMoreElements()) { XAResource x = (XAResource) el.nextElement(); if (x.isSameRM(xaRes)) { return (TxInfo) _duplicateResources.get(x); } } } } } catch (XAException ex) { jtaxLogger.i18NLogger.warn_jtax_transaction_jts_xaerror("TransactionImple.isNewRM", XAHelper.printXAErrorCode(ex), ex); throw new com.arjuna.ats.arjuna.exceptions.FatalError(ex.toString(), ex); } catch (Exception e) { jtaxLogger.i18NLogger.warn_jtax_transaction_jts_rmerror(e); throw new com.arjuna.ats.arjuna.exceptions.FatalError(e.toString(), e); } return null; }
final TxInfo function (XAResource xaRes) { try { synchronized (this) { Enumeration el = _resources.keys(); if (el != null) { while (el.hasMoreElements()) { XAResource x = (XAResource) el.nextElement(); if (x.isSameRM(xaRes)) { return (TxInfo) _resources.get(x); } } } el = _duplicateResources.keys(); if (el != null) { while (el.hasMoreElements()) { XAResource x = (XAResource) el.nextElement(); if (x.isSameRM(xaRes)) { return (TxInfo) _duplicateResources.get(x); } } } } } catch (XAException ex) { jtaxLogger.i18NLogger.warn_jtax_transaction_jts_xaerror(STR, XAHelper.printXAErrorCode(ex), ex); throw new com.arjuna.ats.arjuna.exceptions.FatalError(ex.toString(), ex); } catch (Exception e) { jtaxLogger.i18NLogger.warn_jtax_transaction_jts_rmerror(e); throw new com.arjuna.ats.arjuna.exceptions.FatalError(e.toString(), e); } return null; }
/** * isNewRM returns an existing TxInfo for the same RM, if present. Null * otherwise. */
isNewRM returns an existing TxInfo for the same RM, if present. Null otherwise
isNewRM
{ "repo_name": "gytis/narayana", "path": "ArjunaJTS/jtax/classes/com/arjuna/ats/internal/jta/transaction/jts/TransactionImple.java", "license": "lgpl-2.1", "size": 55238 }
[ "com.arjuna.ats.internal.jta.xa.TxInfo", "com.arjuna.ats.jta.utils.XAHelper", "java.util.Enumeration", "javax.transaction.xa.XAException", "javax.transaction.xa.XAResource" ]
import com.arjuna.ats.internal.jta.xa.TxInfo; import com.arjuna.ats.jta.utils.XAHelper; import java.util.Enumeration; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource;
import com.arjuna.ats.internal.jta.xa.*; import com.arjuna.ats.jta.utils.*; import java.util.*; import javax.transaction.xa.*;
[ "com.arjuna.ats", "java.util", "javax.transaction" ]
com.arjuna.ats; java.util; javax.transaction;
2,506,385
public TraversedCOSElement appendTraversedElement(COSBase element) { if (element == null) { return this; } allObjects.add(element); TraversedCOSElement traversedElement = new TraversedCOSElement(allObjects, this, element); traversedElement.setPartOfStreamDictionary( isPartOfStreamDictionary() || getCurrentBaseObject() instanceof COSStream); this.traversedChildren.add(traversedElement); return traversedElement; }
TraversedCOSElement function(COSBase element) { if (element == null) { return this; } allObjects.add(element); TraversedCOSElement traversedElement = new TraversedCOSElement(allObjects, this, element); traversedElement.setPartOfStreamDictionary( isPartOfStreamDictionary() getCurrentBaseObject() instanceof COSStream); this.traversedChildren.add(traversedElement); return traversedElement; }
/** * Construct a new traversal node for the given element and append it as a child to the current node. * * @param element The element, that shall be traversed. * @return The resulting traversal node, that has been created. */
Construct a new traversal node for the given element and append it as a child to the current node
appendTraversedElement
{ "repo_name": "kalaspuffar/pdfbox", "path": "pdfbox/src/main/java/org/apache/pdfbox/pdfwriter/compress/TraversedCOSElement.java", "license": "apache-2.0", "size": 6680 }
[ "org.apache.pdfbox.cos.COSBase", "org.apache.pdfbox.cos.COSStream" ]
import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.cos.*;
[ "org.apache.pdfbox" ]
org.apache.pdfbox;
2,428,980
public void addOrReplaceSlaveServer( SlaveServer slaveServer ) { int index = slaveServers.indexOf( slaveServer ); if ( index < 0 ) { slaveServers.add( slaveServer ); } else { SlaveServer previous = slaveServers.get( index ); previous.replaceMeta( slaveServer ); } setChanged(); }
void function( SlaveServer slaveServer ) { int index = slaveServers.indexOf( slaveServer ); if ( index < 0 ) { slaveServers.add( slaveServer ); } else { SlaveServer previous = slaveServers.get( index ); previous.replaceMeta( slaveServer ); } setChanged(); }
/** * Add a new slave server to the transformation if that didn't exist yet. Otherwise, replace it. * * @param slaveServer * The slave server to be added. */
Add a new slave server to the transformation if that didn't exist yet. Otherwise, replace it
addOrReplaceSlaveServer
{ "repo_name": "GauravAshara/pentaho-kettle", "path": "engine/src/org/pentaho/di/base/AbstractMeta.java", "license": "apache-2.0", "size": 45990 }
[ "org.pentaho.di.cluster.SlaveServer" ]
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.cluster.*;
[ "org.pentaho.di" ]
org.pentaho.di;
2,236,945
public CSVReader reader(InputStream is) { return reader(new InputStreamReader(is, charset)); }
CSVReader function(InputStream is) { return reader(new InputStreamReader(is, charset)); }
/** * Constructs <code>CSVReader</code> using configured CSV format. * * @param is * the input stream of an underlying CSV. */
Constructs <code>CSVReader</code> using configured CSV format
reader
{ "repo_name": "kongch/OpenCSV-3.0", "path": "OpenCSV/src/au/com/bytecode/opencsv/CSV.java", "license": "apache-2.0", "size": 18888 }
[ "java.io.InputStream", "java.io.InputStreamReader" ]
import java.io.InputStream; import java.io.InputStreamReader;
import java.io.*;
[ "java.io" ]
java.io;
476,476
private void exercise6() throws IOException { try (BufferedReader reader = Files.newBufferedReader( Paths.get("SonnetI.txt"), StandardCharsets.UTF_8)) { reader.lines() .flatMap(word -> Stream.of(word.split(WORD_REGEXP))) .map(String::toLowerCase) .distinct() .sorted() .forEachOrdered(System.out::println); } }
void function() throws IOException { try (BufferedReader reader = Files.newBufferedReader( Paths.get(STR), StandardCharsets.UTF_8)) { reader.lines() .flatMap(word -> Stream.of(word.split(WORD_REGEXP))) .map(String::toLowerCase) .distinct() .sorted() .forEachOrdered(System.out::println); } }
/** * Using the BufferedReader to access the file create a list of words from * the file, converted to lower-case and with duplicates removed, which is * sorted by natural order. Print the contents of the list. */
Using the BufferedReader to access the file create a list of words from the file, converted to lower-case and with duplicates removed, which is sorted by natural order. Print the contents of the list
exercise6
{ "repo_name": "pepitooo/mooc", "path": "java8_lambdas_and_streams/src/Lesson2.java", "license": "gpl-2.0", "size": 5366 }
[ "java.io.BufferedReader", "java.io.IOException", "java.nio.charset.StandardCharsets", "java.nio.file.Files", "java.nio.file.Paths", "java.util.stream.Stream" ]
import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream;
import java.io.*; import java.nio.charset.*; import java.nio.file.*; import java.util.stream.*;
[ "java.io", "java.nio", "java.util" ]
java.io; java.nio; java.util;
181,275
protected Entity findPlayerToAttack() { float f = this.getBrightness(1.0F); if (f < 0.5F) { double d0 = 16.0D; return this.worldObj.getClosestVulnerablePlayerToEntity(this, d0); } else { return null; } }
Entity function() { float f = this.getBrightness(1.0F); if (f < 0.5F) { double d0 = 16.0D; return this.worldObj.getClosestVulnerablePlayerToEntity(this, d0); } else { return null; } }
/** * Finds the closest player within 16 blocks to attack, or null if this Entity isn't interested in attacking * (Animals, Spiders at day, peaceful PigZombies). */
Finds the closest player within 16 blocks to attack, or null if this Entity isn't interested in attacking (Animals, Spiders at day, peaceful PigZombies)
findPlayerToAttack
{ "repo_name": "wildex999/stjerncraft_mcpc", "path": "src/minecraft/net/minecraft/entity/monster/EntitySpider.java", "license": "gpl-3.0", "size": 7392 }
[ "net.minecraft.entity.Entity" ]
import net.minecraft.entity.Entity;
import net.minecraft.entity.*;
[ "net.minecraft.entity" ]
net.minecraft.entity;
773,672
private double getDamageRatio(float w, StrategicState s, Region r, UnitGroup ally) { if (w == 0) { return 0; } int allyDamage = getTotalDamage(ally); if (allyDamage == 0) { return 0; // new groups will have zero hitpoints // TODO: count specified units if group is at production base? } int enemyDamage = 0; int opponentId = playerId == 0 ? 1 : 0; Set<UnitGroup> gs = s.getGroups(opponentId, r); for (UnitGroup g : gs) { enemyDamage += getTotalDamage(g); } return w * (.5 * ((allyDamage - enemyDamage) / (enemyDamage + allyDamage) + 1)); }
double function(float w, StrategicState s, Region r, UnitGroup ally) { if (w == 0) { return 0; } int allyDamage = getTotalDamage(ally); if (allyDamage == 0) { return 0; } int enemyDamage = 0; int opponentId = playerId == 0 ? 1 : 0; Set<UnitGroup> gs = s.getGroups(opponentId, r); for (UnitGroup g : gs) { enemyDamage += getTotalDamage(g); } return w * (.5 * ((allyDamage - enemyDamage) / (enemyDamage + allyDamage) + 1)); }
/** * 1/2 [(ally-enemy)/total + 1] scale to [0,1]. * * High value gives high ally-target compatibility. */
1/2 [(ally-enemy)/total + 1] scale to [0,1]. High value gives high ally-target compatibility
getDamageRatio
{ "repo_name": "k1643/StratagusAI", "path": "projects/stratsim/src/main/java/orst/stratagusai/stratsim/planner/GoalDrivenPlanner.java", "license": "apache-2.0", "size": 44386 }
[ "java.util.Set" ]
import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
31,714
public ServerState start() { long startTime = System.currentTimeMillis(); if (isStartable()) { INSTANCE.compareAndSet(null, this); try { process = getControllableProcess(); if (!isDisableDefaultServer()) { assertPortAvailable(getServerBindAddress(), getServerPort()); } SystemFailure.setExitOK(true); ProcessLauncherContext.set(isRedirectingOutput(), getOverriddenDefaults(), (String statusMessage) -> { debug("Callback setStatus(String) called with message (%1$s)...", statusMessage); this.statusMessage = statusMessage; }); try { final Properties gemfireProperties = getDistributedSystemProperties(getProperties()); cache = createCache(gemfireProperties); // Set the resource manager options if (criticalHeapPercentage != null) { cache.getResourceManager().setCriticalHeapPercentage(getCriticalHeapPercentage()); } if (evictionHeapPercentage != null) { cache.getResourceManager().setEvictionHeapPercentage(getEvictionHeapPercentage()); } if (criticalOffHeapPercentage != null) { cache.getResourceManager() .setCriticalOffHeapPercentage(getCriticalOffHeapPercentage()); } if (evictionOffHeapPercentage != null) { cache.getResourceManager() .setEvictionOffHeapPercentage(getEvictionOffHeapPercentage()); } cache.setIsServer(true); startCacheServer(cache); assignBuckets(cache); rebalance(cache); } finally { ProcessLauncherContext.remove(); } awaitStartupTasks(cache, startTime); debug("Running Server on (%1$s) in (%2$s) as (%3$s)...", getId(), getWorkingDirectory(), getMember()); running.set(true); return new ServerState(this, Status.ONLINE); } catch (AuthenticationRequiredException e) { failOnStart(e); throw new AuthenticationRequiredException( "user/password required. Please start your server with --user and --password. " + e.getMessage()); } catch (GemFireSecurityException e) { failOnStart(e); throw new GemFireSecurityException(e.getMessage()); } catch (IOException e) { failOnStart(e); throw new RuntimeException( String.format("An IO error occurred while starting a %s in %s on %s: %s", getServiceName(), getWorkingDirectory(), getId(), e.getMessage()), e); } catch (FileAlreadyExistsException e) { failOnStart(e); throw new RuntimeException( String.format("A PID file already exists and a %s may be running in %s on %s.", getServiceName(), getWorkingDirectory(), getId()), e); } catch (PidUnavailableException e) { failOnStart(e); throw new RuntimeException( String.format("The process ID could not be determined while starting %s %s in %s: %s", getServiceName(), getId(), getWorkingDirectory(), e.getMessage()), e); } catch (RuntimeException | Error e) { failOnStart(e); throw e; } catch (Exception e) { failOnStart(e); throw new RuntimeException(e); } finally { starting.set(false); } } throw new IllegalStateException( String.format("A %s is already running in %s on %s.", getServiceName(), getWorkingDirectory(), getId())); }
ServerState function() { long startTime = System.currentTimeMillis(); if (isStartable()) { INSTANCE.compareAndSet(null, this); try { process = getControllableProcess(); if (!isDisableDefaultServer()) { assertPortAvailable(getServerBindAddress(), getServerPort()); } SystemFailure.setExitOK(true); ProcessLauncherContext.set(isRedirectingOutput(), getOverriddenDefaults(), (String statusMessage) -> { debug(STR, statusMessage); this.statusMessage = statusMessage; }); try { final Properties gemfireProperties = getDistributedSystemProperties(getProperties()); cache = createCache(gemfireProperties); if (criticalHeapPercentage != null) { cache.getResourceManager().setCriticalHeapPercentage(getCriticalHeapPercentage()); } if (evictionHeapPercentage != null) { cache.getResourceManager().setEvictionHeapPercentage(getEvictionHeapPercentage()); } if (criticalOffHeapPercentage != null) { cache.getResourceManager() .setCriticalOffHeapPercentage(getCriticalOffHeapPercentage()); } if (evictionOffHeapPercentage != null) { cache.getResourceManager() .setEvictionOffHeapPercentage(getEvictionOffHeapPercentage()); } cache.setIsServer(true); startCacheServer(cache); assignBuckets(cache); rebalance(cache); } finally { ProcessLauncherContext.remove(); } awaitStartupTasks(cache, startTime); debug(STR, getId(), getWorkingDirectory(), getMember()); running.set(true); return new ServerState(this, Status.ONLINE); } catch (AuthenticationRequiredException e) { failOnStart(e); throw new AuthenticationRequiredException( STR + e.getMessage()); } catch (GemFireSecurityException e) { failOnStart(e); throw new GemFireSecurityException(e.getMessage()); } catch (IOException e) { failOnStart(e); throw new RuntimeException( String.format(STR, getServiceName(), getWorkingDirectory(), getId(), e.getMessage()), e); } catch (FileAlreadyExistsException e) { failOnStart(e); throw new RuntimeException( String.format(STR, getServiceName(), getWorkingDirectory(), getId()), e); } catch (PidUnavailableException e) { failOnStart(e); throw new RuntimeException( String.format(STR, getServiceName(), getId(), getWorkingDirectory(), e.getMessage()), e); } catch (RuntimeException Error e) { failOnStart(e); throw e; } catch (Exception e) { failOnStart(e); throw new RuntimeException(e); } finally { starting.set(false); } } throw new IllegalStateException( String.format(STR, getServiceName(), getWorkingDirectory(), getId())); }
/** * Invokes the 'start' command and operation to startup a Geode server (a cache server). Note, * this method will cause the JVM to block upon server start, providing the calling Thread is a * non-daemon Thread. * * @see #run() */
Invokes the 'start' command and operation to startup a Geode server (a cache server). Note, this method will cause the JVM to block upon server start, providing the calling Thread is a non-daemon Thread
start
{ "repo_name": "smgoller/geode", "path": "geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java", "license": "apache-2.0", "size": 106858 }
[ "java.io.IOException", "java.util.Properties", "org.apache.geode.SystemFailure", "org.apache.geode.internal.process.FileAlreadyExistsException", "org.apache.geode.internal.process.PidUnavailableException", "org.apache.geode.internal.process.ProcessLauncherContext", "org.apache.geode.security.AuthenticationRequiredException", "org.apache.geode.security.GemFireSecurityException" ]
import java.io.IOException; import java.util.Properties; import org.apache.geode.SystemFailure; import org.apache.geode.internal.process.FileAlreadyExistsException; import org.apache.geode.internal.process.PidUnavailableException; import org.apache.geode.internal.process.ProcessLauncherContext; import org.apache.geode.security.AuthenticationRequiredException; import org.apache.geode.security.GemFireSecurityException;
import java.io.*; import java.util.*; import org.apache.geode.*; import org.apache.geode.internal.process.*; import org.apache.geode.security.*;
[ "java.io", "java.util", "org.apache.geode" ]
java.io; java.util; org.apache.geode;
1,296,097
void enterConstNull(@NotNull CQLParser.ConstNullContext ctx); void exitConstNull(@NotNull CQLParser.ConstNullContext ctx);
void enterConstNull(@NotNull CQLParser.ConstNullContext ctx); void exitConstNull(@NotNull CQLParser.ConstNullContext ctx);
/** * Exit a parse tree produced by {@link CQLParser#constNull}. */
Exit a parse tree produced by <code>CQLParser#constNull</code>
exitConstNull
{ "repo_name": "HuaweiBigData/StreamCQL", "path": "cql/src/main/java/com/huawei/streaming/cql/semanticanalyzer/parser/CQLParserListener.java", "license": "apache-2.0", "size": 58667 }
[ "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;
2,798,729
static void deleteContents(File dir) throws IOException { File[] files = dir.listFiles(); if (files == null) { throw new IOException("not a readable directory: " + dir); } for (File file : files) { if (file.isDirectory()) { deleteContents(file); } if (!file.delete()) { throw new IOException("failed to delete file: " + file); } } }
static void deleteContents(File dir) throws IOException { File[] files = dir.listFiles(); if (files == null) { throw new IOException(STR + dir); } for (File file : files) { if (file.isDirectory()) { deleteContents(file); } if (!file.delete()) { throw new IOException(STR + file); } } }
/** * Deletes the contents of {@code dir}. Throws an IOException if any file * could not be deleted, or if {@code dir} is not a readable directory. */
Deletes the contents of dir. Throws an IOException if any file could not be deleted, or if dir is not a readable directory
deleteContents
{ "repo_name": "jeasinlee/AndroidBasicLibs", "path": "common/src/main/java/cn/wwah/common/cache/DiskLruCache.java", "license": "mit", "size": 38017 }
[ "java.io.File", "java.io.IOException" ]
import java.io.File; import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
1,993,310
public static String getStringResource(String key) { return getStringResource(key, ContextHolder.getInstance().getContext()); }
static String function(String key) { return getStringResource(key, ContextHolder.getInstance().getContext()); }
/** * Gets string value from resource by key. Required {@link ContextHolder}. * * @param key * key of resource * @return String value */
Gets string value from resource by key. Required <code>ContextHolder</code>
getStringResource
{ "repo_name": "IstiN/android_xcore", "path": "xcore-library/xcore/src/main/java/by/istin/android/xcore/utils/StringUtil.java", "license": "apache-2.0", "size": 12066 }
[ "by.istin.android.xcore.ContextHolder" ]
import by.istin.android.xcore.ContextHolder;
import by.istin.android.xcore.*;
[ "by.istin.android" ]
by.istin.android;
1,581,197
public static Track getInfo(String artist, String trackOrMbid, String username, boolean autoCorrect, String apiKey) { Map<String, String> params = new HashMap<String, String>(); if (StringUtilities.isMbid(trackOrMbid)) { params.put("mbid", trackOrMbid); } else { params.put("artist", artist); params.put("track", trackOrMbid); } params.put("autocorrect", autoCorrect ? "1" : "0"); MapUtilities.nullSafePut(params, "username", username); Result result = Caller.getInstance().call("track.getInfo", apiKey, params); if (!result.isSuccessful()) { throw new LastFmException(result.getErrorCode(), result.getErrorMessage()); } DomElement content = result.getContentElement(); DomElement album = content.getChild("album"); Track track = FACTORY.createItemFromElement(content); if (album != null) { String pos = album.getAttribute("position"); if ((pos != null) && pos.length() != 0) { track.position = Integer.parseInt(pos); } track.album = album.getChildText("title"); track.albumMbid = album.getChildText("mbid"); ImageHolder.loadImages(track, album); } return track; }
static Track function(String artist, String trackOrMbid, String username, boolean autoCorrect, String apiKey) { Map<String, String> params = new HashMap<String, String>(); if (StringUtilities.isMbid(trackOrMbid)) { params.put("mbid", trackOrMbid); } else { params.put(STR, artist); params.put("track", trackOrMbid); } params.put(STR, autoCorrect ? "1" : "0"); MapUtilities.nullSafePut(params, STR, username); Result result = Caller.getInstance().call(STR, apiKey, params); if (!result.isSuccessful()) { throw new LastFmException(result.getErrorCode(), result.getErrorMessage()); } DomElement content = result.getContentElement(); DomElement album = content.getChild("album"); Track track = FACTORY.createItemFromElement(content); if (album != null) { String pos = album.getAttribute(STR); if ((pos != null) && pos.length() != 0) { track.position = Integer.parseInt(pos); } track.album = album.getChildText("title"); track.albumMbid = album.getChildText("mbid"); ImageHolder.loadImages(track, album); } return track; }
/** * Get the metadata for a track on Last.fm using the artist/track name or a musicbrainz id. * * @param artist The artist name in question or <code>null</code> if an mbid is specified * @param trackOrMbid The track name in question or the musicbrainz id for the track * @param username The username for the context of the request, or <code>null</code>. If supplied, the user's playcount for this track and whether they have loved the track is included in the response * @param autocorrect Transform misspelled artist and track names into correct artist and track names, returning the correct version instead. The corrected artist and track name will be returned in the response * @param apiKey A Last.fm API key. * @return Track information */
Get the metadata for a track on Last.fm using the artist/track name or a musicbrainz id
getInfo
{ "repo_name": "thomwiggers/lastfm-java", "path": "src/main/java/de/umass/lastfm/Track.java", "license": "bsd-2-clause", "size": 31926 }
[ "de.umass.lastfm.LastFmException", "de.umass.util.MapUtilities", "de.umass.util.StringUtilities", "de.umass.xml.DomElement", "java.util.HashMap", "java.util.Map" ]
import de.umass.lastfm.LastFmException; import de.umass.util.MapUtilities; import de.umass.util.StringUtilities; import de.umass.xml.DomElement; import java.util.HashMap; import java.util.Map;
import de.umass.lastfm.*; import de.umass.util.*; import de.umass.xml.*; import java.util.*;
[ "de.umass.lastfm", "de.umass.util", "de.umass.xml", "java.util" ]
de.umass.lastfm; de.umass.util; de.umass.xml; java.util;
2,231,756
Translate.setClientId(CLIENT_ID); Translate.setClientSecret(CLIENT_SECRET); try { Log.d(TAG, sourceLanguageCode + " -> " + targetLanguageCode); return Translate.execute(sourceText, Language.fromString(sourceLanguageCode), Language.fromString(targetLanguageCode)); } catch (Exception e) { Log.e(TAG, "Caught exeption in translation request."); e.printStackTrace(); return Translator.BAD_TRANSLATION_MSG; } }
Translate.setClientId(CLIENT_ID); Translate.setClientSecret(CLIENT_SECRET); try { Log.d(TAG, sourceLanguageCode + STR + targetLanguageCode); return Translate.execute(sourceText, Language.fromString(sourceLanguageCode), Language.fromString(targetLanguageCode)); } catch (Exception e) { Log.e(TAG, STR); e.printStackTrace(); return Translator.BAD_TRANSLATION_MSG; } }
/** * Translate using Microsoft Translate API * * @param sourceLanguageCode Source language code, for example, "en" * @param targetLanguageCode Target language code, for example, "es" * @param sourceText Text to send for translation * @return Translated text */
Translate using Microsoft Translate API
translate
{ "repo_name": "osandadeshan/mysight", "path": "app/src/main/java/com/osanda/ocr/language/TranslatorBing.java", "license": "apache-2.0", "size": 3256 }
[ "android.util.Log", "com.memetix.mst.language.Language", "com.memetix.mst.translate.Translate" ]
import android.util.Log; import com.memetix.mst.language.Language; import com.memetix.mst.translate.Translate;
import android.util.*; import com.memetix.mst.language.*; import com.memetix.mst.translate.*;
[ "android.util", "com.memetix.mst" ]
android.util; com.memetix.mst;
236,983
@Test public void testNameViolation() { Member member = createValidMember(); member.setName("Joe Doe-Dah"); Set<ConstraintViolation<Member>> violations = validator.validate(member); Assert.assertEquals("One violation was found", 1, violations.size()); Assert.assertEquals("Name was invalid", "must contain only letters and spaces", violations.iterator().next() .getMessage()); }
void function() { Member member = createValidMember(); member.setName(STR); Set<ConstraintViolation<Member>> violations = validator.validate(member); Assert.assertEquals(STR, 1, violations.size()); Assert.assertEquals(STR, STR, violations.iterator().next() .getMessage()); }
/** * Tests {@code @Pattern} constraint */
Tests @Pattern constraint
testNameViolation
{ "repo_name": "ssilvert/quickstart", "path": "richfaces-validation/src/test/java/org/jboss/as/quickstarts/richfaces_validation/test/MemberValidationTest.java", "license": "apache-2.0", "size": 5154 }
[ "java.util.Set", "javax.validation.ConstraintViolation", "org.jboss.as.quickstarts.richfaces_validation.Member", "org.junit.Assert" ]
import java.util.Set; import javax.validation.ConstraintViolation; import org.jboss.as.quickstarts.richfaces_validation.Member; import org.junit.Assert;
import java.util.*; import javax.validation.*; import org.jboss.as.quickstarts.richfaces_validation.*; import org.junit.*;
[ "java.util", "javax.validation", "org.jboss.as", "org.junit" ]
java.util; javax.validation; org.jboss.as; org.junit;
976,163
public void setQtyCalculated (BigDecimal QtyCalculated) { set_Value (COLUMNNAME_QtyCalculated, QtyCalculated); }
void function (BigDecimal QtyCalculated) { set_Value (COLUMNNAME_QtyCalculated, QtyCalculated); }
/** Set Calculated Quantity. @param QtyCalculated Calculated Quantity */
Set Calculated Quantity
setQtyCalculated
{ "repo_name": "erpcya/adempierePOS", "path": "base/src/org/compiere/model/X_M_DemandLine.java", "license": "gpl-2.0", "size": 6442 }
[ "java.math.BigDecimal" ]
import java.math.BigDecimal;
import java.math.*;
[ "java.math" ]
java.math;
1,066,944
public Date getLastModifiedDate() { if (lastModifiedDate != null) return lastModifiedDate; if (lastModified != -1L) { lastModifiedDate = new Date(lastModified); return lastModifiedDate; } if (attributes != null) { Attribute attribute = attributes.get(LAST_MODIFIED); if (attribute != null) { try { Object value = attribute.get(); if (value instanceof Long) { lastModified = ((Long) value).longValue(); lastModifiedDate = new Date(lastModified); } else if (value instanceof Date) { lastModified = ((Date) value).getTime(); lastModifiedDate = (Date) value; } else { String lastModifiedDateValue = value.toString(); Date result = null; // Parsing the HTTP Date for (int i = 0; (result == null) && (i < formats.length); i++) { try { result = formats[i].parse(lastModifiedDateValue); } catch (ParseException e) { ; } } if (result != null) { lastModified = result.getTime(); lastModifiedDate = result; } } } catch (NamingException e) { ; // No value for the attribute } } } return lastModifiedDate; }
Date function() { if (lastModifiedDate != null) return lastModifiedDate; if (lastModified != -1L) { lastModifiedDate = new Date(lastModified); return lastModifiedDate; } if (attributes != null) { Attribute attribute = attributes.get(LAST_MODIFIED); if (attribute != null) { try { Object value = attribute.get(); if (value instanceof Long) { lastModified = ((Long) value).longValue(); lastModifiedDate = new Date(lastModified); } else if (value instanceof Date) { lastModified = ((Date) value).getTime(); lastModifiedDate = (Date) value; } else { String lastModifiedDateValue = value.toString(); Date result = null; for (int i = 0; (result == null) && (i < formats.length); i++) { try { result = formats[i].parse(lastModifiedDateValue); } catch (ParseException e) { ; } } if (result != null) { lastModified = result.getTime(); lastModifiedDate = result; } } } catch (NamingException e) { ; } } } return lastModifiedDate; }
/** * Get lastModified date. * * @return LastModified date value */
Get lastModified date
getLastModifiedDate
{ "repo_name": "devjin24/howtomcatworks", "path": "bookrefer/jakarta-tomcat-4.1.12-src/catalina/src/share/org/apache/naming/resources/ResourceAttributes.java", "license": "apache-2.0", "size": 25767 }
[ "java.text.ParseException", "java.util.Date", "javax.naming.NamingException", "javax.naming.directory.Attribute" ]
import java.text.ParseException; import java.util.Date; import javax.naming.NamingException; import javax.naming.directory.Attribute;
import java.text.*; import java.util.*; import javax.naming.*; import javax.naming.directory.*;
[ "java.text", "java.util", "javax.naming" ]
java.text; java.util; javax.naming;
896,591
public static SqlFunction lookupRoutine(SqlOperatorTable opTab, SqlIdentifier funcName, List<RelDataType> argTypes, List<String> argNames, SqlFunctionCategory category) { List<SqlFunction> list = lookupSubjectRoutines( opTab, funcName, argTypes, argNames, category); if (list.isEmpty()) { return null; } else { // return first on schema path return list.get(0); } }
static SqlFunction function(SqlOperatorTable opTab, SqlIdentifier funcName, List<RelDataType> argTypes, List<String> argNames, SqlFunctionCategory category) { List<SqlFunction> list = lookupSubjectRoutines( opTab, funcName, argTypes, argNames, category); if (list.isEmpty()) { return null; } else { return list.get(0); } }
/** * Looks up a (possibly overloaded) routine based on name and argument * types. * * @param opTab operator table to search * @param funcName name of function being invoked * @param argTypes argument types * @param argNames argument names, or null if call by position * @param category whether a function or a procedure. (If a procedure is * being invoked, the overload rules are simpler.) * @return matching routine, or null if none found * @sql.99 Part 2 Section 10.4 */
Looks up a (possibly overloaded) routine based on name and argument types
lookupRoutine
{ "repo_name": "joshelser/incubator-calcite", "path": "core/src/main/java/org/apache/calcite/sql/SqlUtil.java", "license": "apache-2.0", "size": 29109 }
[ "java.util.List", "org.apache.calcite.rel.type.RelDataType" ]
import java.util.List; import org.apache.calcite.rel.type.RelDataType;
import java.util.*; import org.apache.calcite.rel.type.*;
[ "java.util", "org.apache.calcite" ]
java.util; org.apache.calcite;
2,095,550
public final long getBytesUsed() { // get current usage for old gen long bytesUsed = getBytesUsed(getTenuredMemoryPoolMXBean(), true); MemoryPoolMXBean pool = getEdenMemoryPoolMXBean(); if (pool != null) { // get last collection usage for eden space since there is likely // to be quite a bit of garbage in current usage bytesUsed += getBytesUsed(pool, false); } pool = getSurvivorPoolMXBean(); if (pool != null) { // get current usage for survivor pool bytesUsed += getBytesUsed(pool, true); } return bytesUsed; }
final long function() { long bytesUsed = getBytesUsed(getTenuredMemoryPoolMXBean(), true); MemoryPoolMXBean pool = getEdenMemoryPoolMXBean(); if (pool != null) { bytesUsed += getBytesUsed(pool, false); } pool = getSurvivorPoolMXBean(); if (pool != null) { bytesUsed += getBytesUsed(pool, true); } return bytesUsed; }
/** * Returns the number of bytes of memory reported by the tenured and eden * pools as currently in use. */
Returns the number of bytes of memory reported by the tenured and eden pools as currently in use
getBytesUsed
{ "repo_name": "SnappyDataInc/snappy-store", "path": "gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/control/HeapMemoryMonitor.java", "license": "apache-2.0", "size": 51314 }
[ "java.lang.management.MemoryPoolMXBean" ]
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.*;
[ "java.lang" ]
java.lang;
173,473
protected final void createConnectionPool() throws Exception { // Create the connection pool m_connPool = new DBConnectionPool(m_driver, m_dsn, m_userName, m_password, m_dbInitConns, m_dbMaxConns); // Set the online check interval, if specified if ( m_onlineCheckInterval != 0) m_connPool.setOnlineCheckInterval( m_onlineCheckInterval * 60); // Add the database interface as a connection pool event listener m_connPool.addConnectionPoolListener( this); }
final void function() throws Exception { m_connPool = new DBConnectionPool(m_driver, m_dsn, m_userName, m_password, m_dbInitConns, m_dbMaxConns); if ( m_onlineCheckInterval != 0) m_connPool.setOnlineCheckInterval( m_onlineCheckInterval * 60); m_connPool.addConnectionPoolListener( this); }
/** * Create the database connection pool * * @exception Exception */
Create the database connection pool
createConnectionPool
{ "repo_name": "loftuxab/community-edition-old", "path": "projects/alfresco-jlan/source/java/org/alfresco/jlan/server/filesys/db/JdbcDBInterface.java", "license": "lgpl-3.0", "size": 30984 }
[ "org.alfresco.jlan.util.db.DBConnectionPool" ]
import org.alfresco.jlan.util.db.DBConnectionPool;
import org.alfresco.jlan.util.db.*;
[ "org.alfresco.jlan" ]
org.alfresco.jlan;
2,506,429
private void updateLocalConfiguration(final JavaSparkContext sparkContext, final SparkConf sparkConfiguration) { final String[] validPropertyNames = { "spark.job.description", "spark.jobGroup.id", "spark.job.interruptOnCancel", "spark.scheduler.pool" }; for (String propertyName : validPropertyNames) { if (sparkConfiguration.contains(propertyName)) { String propertyValue = sparkConfiguration.get(propertyName); this.logger.info("Setting Thread Local SparkContext Property - " + propertyName + " : " + propertyValue); sparkContext.setLocalProperty(propertyName, sparkConfiguration.get(propertyName)); } } }
void function(final JavaSparkContext sparkContext, final SparkConf sparkConfiguration) { final String[] validPropertyNames = { STR, STR, STR, STR }; for (String propertyName : validPropertyNames) { if (sparkConfiguration.contains(propertyName)) { String propertyValue = sparkConfiguration.get(propertyName); this.logger.info(STR + propertyName + STR + propertyValue); sparkContext.setLocalProperty(propertyName, sparkConfiguration.get(propertyName)); } } }
/** * When using a persistent context the running Context's configuration will override a passed * in configuration. Spark allows us to override these inherited properties via * SparkContext.setLocalProperty */
When using a persistent context the running Context's configuration will override a passed in configuration. Spark allows us to override these inherited properties via SparkContext.setLocalProperty
updateLocalConfiguration
{ "repo_name": "RussellSpitzer/incubator-tinkerpop", "path": "spark-gremlin/src/main/java/org/apache/tinkerpop/gremlin/spark/process/computer/SparkGraphComputer.java", "license": "apache-2.0", "size": 25022 }
[ "org.apache.spark.SparkConf", "org.apache.spark.api.java.JavaSparkContext" ]
import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.*; import org.apache.spark.api.java.*;
[ "org.apache.spark" ]
org.apache.spark;
1,842,198
public boolean isFieldTypeString(Field field);
boolean function(Field field);
/** * Use to determine if if the field value is a String value withing the contentlet object * @param field * @return */
Use to determine if if the field value is a String value withing the contentlet object
isFieldTypeString
{ "repo_name": "guhb/core", "path": "src/com/dotmarketing/portlets/contentlet/business/ContentletAPI.java", "license": "gpl-3.0", "size": 64730 }
[ "com.dotmarketing.portlets.structure.model.Field" ]
import com.dotmarketing.portlets.structure.model.Field;
import com.dotmarketing.portlets.structure.model.*;
[ "com.dotmarketing.portlets" ]
com.dotmarketing.portlets;
290,520
public Image getSemiquaverDown();
Image function();
/** * Returns an Image representing a semiquaver with stem lowered. */
Returns an Image representing a semiquaver with stem lowered
getSemiquaverDown
{ "repo_name": "Armaxis/jmg", "path": "src/main/java/jm/gui/cpn/Images.java", "license": "gpl-2.0", "size": 6599 }
[ "java.awt.Image" ]
import java.awt.Image;
import java.awt.*;
[ "java.awt" ]
java.awt;
1,565,147
private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); writePaintMap(this.tickLabelPaintMap, stream); }
void function(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); writePaintMap(this.tickLabelPaintMap, stream); }
/** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */
Provides serialization support
writeObject
{ "repo_name": "SOCR/HTML5_WebSite", "path": "SOCR2.8/src/jfreechart/org/jfree/chart/axis/CategoryAxis.java", "license": "lgpl-3.0", "size": 51383 }
[ "java.io.IOException", "java.io.ObjectOutputStream" ]
import java.io.IOException; import java.io.ObjectOutputStream;
import java.io.*;
[ "java.io" ]
java.io;
762,010
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (tm == null) return; tm.checkServerTrusted(chain, authType); }
void function(X509Certificate[] chain, String authType) throws CertificateException { if (tm == null) return; tm.checkServerTrusted(chain, authType); }
/** * Pass method from x509TrustManager to this class... * * Given the partial or complete certificate chain provided by the peer, build * a certificate path to a trusted root and return if it can be validated and * is trusted for server SSL authentication based on the authentication type */
Pass method from x509TrustManager to this class... Given the partial or complete certificate chain provided by the peer, build a certificate path to a trusted root and return if it can be validated and is trusted for server SSL authentication based on the authentication type
checkServerTrusted
{ "repo_name": "jjeb/kettle-trunk", "path": "engine/src/org/pentaho/di/trans/steps/ldapinput/store/KettleTrustManager.java", "license": "apache-2.0", "size": 4738 }
[ "java.security.cert.CertificateException", "java.security.cert.X509Certificate" ]
import java.security.cert.CertificateException; import java.security.cert.X509Certificate;
import java.security.cert.*;
[ "java.security" ]
java.security;
2,596,818
public void stop() { for (Iterator<Entry<Long, ISwitch>> it = switches.entrySet().iterator(); it .hasNext();) { Entry<Long, ISwitch> entry = it.next(); ((SwitchHandler) entry.getValue()).stop(); it.remove(); } switchEventThread.interrupt(); try { controllerIO.shutDown(); } catch (IOException ex) { logger.error("Caught exception while stopping:", ex); } }
void function() { for (Iterator<Entry<Long, ISwitch>> it = switches.entrySet().iterator(); it .hasNext();) { Entry<Long, ISwitch> entry = it.next(); ((SwitchHandler) entry.getValue()).stop(); it.remove(); } switchEventThread.interrupt(); try { controllerIO.shutDown(); } catch (IOException ex) { logger.error(STR, ex); } }
/** * Function called by the dependency manager before the services exported by * the component are unregistered, this will be followed by a "destroy ()" * calls * */
Function called by the dependency manager before the services exported by the component are unregistered, this will be followed by a "destroy ()" calls
stop
{ "repo_name": "lbchen/odl-mod", "path": "opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/Controller.java", "license": "epl-1.0", "size": 13923 }
[ "java.io.IOException", "java.util.Iterator", "java.util.Map", "org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch" ]
import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch;
import java.io.*; import java.util.*; import org.opendaylight.controller.protocol_plugin.openflow.core.*;
[ "java.io", "java.util", "org.opendaylight.controller" ]
java.io; java.util; org.opendaylight.controller;
867,984
void setEmpty() { View v; ModuleDetailsFragment detailFragment = (ModuleDetailsFragment) getFragmentManager().findFragmentById(R.id.moduledetail); if(detailFragment != null) { detailFragment.setTitle(""); detailFragment.setDescription(""); v = detailFragment.getView(); if(v != null) v.setVisibility(View.GONE); } else Log.d("DEBUG", "ModuleDetailsFragment is null"); ButtonGridFragment buttonFragment = (ButtonGridFragment) getFragmentManager().findFragmentById(R.id.buttongrid); if(buttonFragment != null) { buttonFragment.initGrid(null); v = buttonFragment.getView(); if(v != null) v.setVisibility(View.GONE); } else Log.d("DEBUG", "ButtonGridFragment is null"); FeedbackBarFragment feedbackFragment = (FeedbackBarFragment) getFragmentManager().findFragmentById(R.id.feedbackbar); if(feedbackFragment != null) { feedbackFragment.setEmpty(); v = feedbackFragment.getView(); if(v != null) v.setVisibility(View.GONE); } else { Log.d("DEBUG", "FeedbackBarFragment is null"); } MediaFragment mediaFragment = (MediaFragment) getFragmentManager().findFragmentById(R.id.media); if(mediaFragment != null) { //mediaFragment.setEmpty(); v = mediaFragment.getView(); if(v != null) v.setVisibility(View.GONE); } else Log.d("DEBUG", "MediaFragment is null"); View fragmentView = getView(); if(fragmentView != null) { v = fragmentView.findViewById(R.id.feedbackbar_divider); if (v != null) v.setVisibility(View.GONE); v = fragmentView.findViewById(R.id.buttongrid_divider); if (v != null) v.setVisibility(View.GONE); v = fragmentView.findViewById(R.id.media_divider); if (v != null) v.setVisibility(View.GONE); v = fragmentView.findViewById(R.id.message_text); if(v != null) v.setVisibility(View.VISIBLE); } isEmpty = true; }
void setEmpty() { View v; ModuleDetailsFragment detailFragment = (ModuleDetailsFragment) getFragmentManager().findFragmentById(R.id.moduledetail); if(detailFragment != null) { detailFragment.setTitle(STRSTRDEBUGSTRModuleDetailsFragment is nullSTRDEBUGSTRButtonGridFragment is nullSTRDEBUGSTRFeedbackBarFragment is nullSTRDEBUGSTRMediaFragment is null"); View fragmentView = getView(); if(fragmentView != null) { v = fragmentView.findViewById(R.id.feedbackbar_divider); if (v != null) v.setVisibility(View.GONE); v = fragmentView.findViewById(R.id.buttongrid_divider); if (v != null) v.setVisibility(View.GONE); v = fragmentView.findViewById(R.id.media_divider); if (v != null) v.setVisibility(View.GONE); v = fragmentView.findViewById(R.id.message_text); if(v != null) v.setVisibility(View.VISIBLE); } isEmpty = true; }
/** * Hide the main UI of the fragment and display a single TextView instead. * Used on tablets when there is no {@link pk.contender.earmouse.Module} selected, instead of showing an empty layout * we show this TextView saying 'No Module Selected' */
Hide the main UI of the fragment and display a single TextView instead. Used on tablets when there is no <code>pk.contender.earmouse.Module</code> selected, instead of showing an empty layout we show this TextView saying 'No Module Selected'
setEmpty
{ "repo_name": "pklinken/Earmouse", "path": "Earmouse/src/pk/contender/earmouse/ExerciseFragment.java", "license": "apache-2.0", "size": 19568 }
[ "android.view.View" ]
import android.view.View;
import android.view.*;
[ "android.view" ]
android.view;
1,386,105
@Override public Date getDate() { return date; }
Date function() { return date; }
/** * return the Date of this SocialInfo * @return */
return the Date of this SocialInfo
getDate
{ "repo_name": "stephaneperry/Silverpeas-Core", "path": "lib-core/src/main/java/com/silverpeas/socialNetwork/relationShip/SocialInformationRelationShip.java", "license": "agpl-3.0", "size": 3354 }
[ "java.util.Date" ]
import java.util.Date;
import java.util.*;
[ "java.util" ]
java.util;
2,397,689
protected void undeployRegion(Connection conn, ServerName sn, RegionInfo hri) throws IOException, InterruptedException { try { HBaseFsckRepair.closeRegionSilentlyAndWait(conn, sn, hri); if (!hri.isMetaTable()) { admin.offline(hri.getRegionName()); } } catch (IOException ioe) { LOG.warn("Got exception when attempting to offline region " + Bytes.toString(hri.getRegionName()), ioe); } }
void function(Connection conn, ServerName sn, RegionInfo hri) throws IOException, InterruptedException { try { HBaseFsckRepair.closeRegionSilentlyAndWait(conn, sn, hri); if (!hri.isMetaTable()) { admin.offline(hri.getRegionName()); } } catch (IOException ioe) { LOG.warn(STR + Bytes.toString(hri.getRegionName()), ioe); } }
/** * This method is used to undeploy a region -- close it and attempt to * remove its state from the Master. */
This method is used to undeploy a region -- close it and attempt to remove its state from the Master
undeployRegion
{ "repo_name": "JingchengDu/hbase", "path": "hbase-server/src/test/java/org/apache/hadoop/hbase/util/BaseTestHBaseFsck.java", "license": "apache-2.0", "size": 23243 }
[ "java.io.IOException", "org.apache.hadoop.hbase.ServerName", "org.apache.hadoop.hbase.client.Connection", "org.apache.hadoop.hbase.client.RegionInfo" ]
import java.io.IOException; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.RegionInfo;
import java.io.*; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
469,608
public boolean acquire(long msecs) { try { return lock.tryLock(msecs, TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { return false; } }
boolean function(long msecs) { try { return lock.tryLock(msecs, TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { return false; } }
/** * Attempt to acquire lock. * * @param msecs the number of milliseconds to wait. * An argument less than or equal to zero means not to wait at all. * @return <code>true</code> if acquired, <code>false</code> othwerwise. */
Attempt to acquire lock
acquire
{ "repo_name": "csrg-utfsm/acscb", "path": "LGPL/CommonSoftware/jmanager/src/com/cosylab/acs/maci/manager/ManagerImpl.java", "license": "mit", "size": 309850 }
[ "java.util.concurrent.TimeUnit" ]
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
[ "java.util" ]
java.util;
2,046,832
public static RequestPostProcessor testSecurityContext() { return new TestSecurityContextHolderPostProcessor(); }
static RequestPostProcessor function() { return new TestSecurityContextHolderPostProcessor(); }
/** * Creates a {@link RequestPostProcessor} that can be used to ensure that the * resulting request is ran with the user in the {@link TestSecurityContextHolder}. * @return the {@link RequestPostProcessor} to sue */
Creates a <code>RequestPostProcessor</code> that can be used to ensure that the resulting request is ran with the user in the <code>TestSecurityContextHolder</code>
testSecurityContext
{ "repo_name": "fhanik/spring-security", "path": "test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java", "license": "apache-2.0", "size": 66514 }
[ "org.springframework.test.web.servlet.request.RequestPostProcessor" ]
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.request.*;
[ "org.springframework.test" ]
org.springframework.test;
2,883,596
protected SynapseClient createSynapseClient(String accessToken) { SynapseClient synapseClient = synapseProvider.createNewClient(); if (accessToken != null) { synapseClient.setBearerAuthorizationToken(accessToken); } synapseClient.setAuthEndpoint(StackEndpoints.getAuthenticationServicePublicEndpoint()); return synapseClient; }
SynapseClient function(String accessToken) { SynapseClient synapseClient = synapseProvider.createNewClient(); if (accessToken != null) { synapseClient.setBearerAuthorizationToken(accessToken); } synapseClient.setAuthEndpoint(StackEndpoints.getAuthenticationServicePublicEndpoint()); return synapseClient; }
/** * Creates a Synapse client */
Creates a Synapse client
createSynapseClient
{ "repo_name": "jay-hodgson/SynapseWebClient", "path": "src/main/java/org/sagebionetworks/web/server/servlet/oauth2/OAuth2Servlet.java", "license": "apache-2.0", "size": 3982 }
[ "org.sagebionetworks.client.SynapseClient", "org.sagebionetworks.web.client.StackEndpoints" ]
import org.sagebionetworks.client.SynapseClient; import org.sagebionetworks.web.client.StackEndpoints;
import org.sagebionetworks.client.*; import org.sagebionetworks.web.client.*;
[ "org.sagebionetworks.client", "org.sagebionetworks.web" ]
org.sagebionetworks.client; org.sagebionetworks.web;
855,439
CompletableFuture<HttpResponse> read(Executor fileReadExecutor, ByteBufAllocator alloc);
CompletableFuture<HttpResponse> read(Executor fileReadExecutor, ByteBufAllocator alloc);
/** * Starts to stream this file into the returned {@link HttpResponse}. * * @param fileReadExecutor the {@link Executor} which will perform the read operations against the file * @param alloc the {@link ByteBufAllocator} which will allocate the buffers that hold the content of * the file * @return the {@link CompletableFuture} that will be completed with the response. * It will be completed with {@code null} if the file does not exist. */
Starts to stream this file into the returned <code>HttpResponse</code>
read
{ "repo_name": "minwoox/armeria", "path": "core/src/main/java/com/linecorp/armeria/server/file/HttpFile.java", "license": "apache-2.0", "size": 11027 }
[ "com.linecorp.armeria.common.HttpResponse", "io.netty.buffer.ByteBufAllocator", "java.util.concurrent.CompletableFuture", "java.util.concurrent.Executor" ]
import com.linecorp.armeria.common.HttpResponse; import io.netty.buffer.ByteBufAllocator; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor;
import com.linecorp.armeria.common.*; import io.netty.buffer.*; import java.util.concurrent.*;
[ "com.linecorp.armeria", "io.netty.buffer", "java.util" ]
com.linecorp.armeria; io.netty.buffer; java.util;
1,047,804
private static void setIntermediateDocProps(UpdateOp intermediate, Revision maxRev) { setSplitDocMaxRev(intermediate, maxRev); setSplitDocType(intermediate, SplitDocType.INTERMEDIATE); } //----------------------------< internal modifiers >------------------------
static void function(UpdateOp intermediate, Revision maxRev) { setSplitDocMaxRev(intermediate, maxRev); setSplitDocType(intermediate, SplitDocType.INTERMEDIATE); }
/** * Set various properties for intermediate split document * * @param intermediate updateOp of the intermediate doc getting created * @param maxRev max revision stored in the intermediate */
Set various properties for intermediate split document
setIntermediateDocProps
{ "repo_name": "francescomari/jackrabbit-oak", "path": "oak-store-document/src/main/java/org/apache/jackrabbit/oak/plugins/document/SplitOperations.java", "license": "apache-2.0", "size": 25064 }
[ "org.apache.jackrabbit.oak.plugins.document.NodeDocument" ]
import org.apache.jackrabbit.oak.plugins.document.NodeDocument;
import org.apache.jackrabbit.oak.plugins.document.*;
[ "org.apache.jackrabbit" ]
org.apache.jackrabbit;
1,664,811
private JSONWriter end(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } this.pop(mode); try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; }
JSONWriter function(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' ? STR : STR); } this.pop(mode); try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; }
/** * End something. * * @param mode Mode * @param c Closing character * @return this * @throws JSONException If unbalanced. */
End something
end
{ "repo_name": "allantsai123/COSC310project", "path": "ChatBot/src/org/json/JSONWriter.java", "license": "gpl-2.0", "size": 10591 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
2,522,493
public Collection<Element> getConfigXML() { ArrayList<Element> config = new ArrayList<Element>(); Element element; // Title element = new Element("title"); element.setText(title); config.add(element); if (!speedLimitNone) { element = new Element("speedlimit"); element.setText("" + getSpeedLimit()); config.add(element); } // Random seed element = new Element("randomseed"); if (randomSeedGenerated) { element.setText("generated"); } else { element.setText(Long.toString(getRandomSeed())); } config.add(element); // Max mote startup delay element = new Element("motedelay_us"); element.setText(Long.toString(maxMoteStartupDelay)); config.add(element); // Radio Medium element = new Element("radiomedium"); element.setText(currentRadioMedium.getClass().getName()); Collection<Element> radioMediumXML = currentRadioMedium.getConfigXML(); if (radioMediumXML != null) { element.addContent(radioMediumXML); } config.add(element); element = new Element("events"); element.addContent(eventCentral.getConfigXML()); config.add(element); // Mote types for (MoteType moteType : getMoteTypes()) { element = new Element("motetype"); element.setText(moteType.getClass().getName()); Collection<Element> moteTypeXML = moteType.getConfigXML(this); if (moteTypeXML != null) { element.addContent(moteTypeXML); } config.add(element); } // Motes for (Mote mote : motes) { element = new Element("mote"); Collection<Element> moteConfig = mote.getConfigXML(); if (moteConfig == null) { moteConfig = new ArrayList<Element>(); } Element typeIdentifier = new Element("motetype_identifier"); typeIdentifier.setText(mote.getType().getIdentifier()); moteConfig.add(typeIdentifier); element.addContent(moteConfig); config.add(element); } return config; }
Collection<Element> function() { ArrayList<Element> config = new ArrayList<Element>(); Element element; element = new Element("title"); element.setText(title); config.add(element); if (!speedLimitNone) { element = new Element(STR); element.setText(STRrandomseedSTRgeneratedSTRmotedelay_usSTRradiomediumSTReventsSTRmotetypeSTRmoteSTRmotetype_identifier"); typeIdentifier.setText(mote.getType().getIdentifier()); moteConfig.add(typeIdentifier); element.addContent(moteConfig); config.add(element); } return config; }
/** * Returns the current simulation config represented by XML elements. This * config also includes the current radio medium, all mote types and motes. * * @return Current simulation config */
Returns the current simulation config represented by XML elements. This config also includes the current radio medium, all mote types and motes
getConfigXML
{ "repo_name": "vijaysrao/dipa", "path": "tools/cooja/java/org/contikios/cooja/Simulation.java", "license": "gpl-3.0", "size": 32179 }
[ "java.util.ArrayList", "java.util.Collection", "org.jdom.Element" ]
import java.util.ArrayList; import java.util.Collection; import org.jdom.Element;
import java.util.*; import org.jdom.*;
[ "java.util", "org.jdom" ]
java.util; org.jdom;
369,186
public StoredProcedureQuery setParameter(int position, Date value, TemporalType temporalType) { entityManager.verifyOpenWithSetRollbackOnly(); return setParameter(position, convertTemporalType(value, temporalType)); }
StoredProcedureQuery function(int position, Date value, TemporalType temporalType) { entityManager.verifyOpenWithSetRollbackOnly(); return setParameter(position, convertTemporalType(value, temporalType)); }
/** * Bind an instance of java.util.Date to a positional parameter. * * @param position * @param value * @param temporalType * @return the same query instance * @throws IllegalArgumentException if position does not correspond to a * positional parameter of the query or if the value argument is of * incorrect type */
Bind an instance of java.util.Date to a positional parameter
setParameter
{ "repo_name": "gameduell/eclipselink.runtime", "path": "jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/StoredProcedureQueryImpl.java", "license": "epl-1.0", "size": 46352 }
[ "java.util.Date", "javax.persistence.StoredProcedureQuery", "javax.persistence.TemporalType" ]
import java.util.Date; import javax.persistence.StoredProcedureQuery; import javax.persistence.TemporalType;
import java.util.*; import javax.persistence.*;
[ "java.util", "javax.persistence" ]
java.util; javax.persistence;
2,602,442
@Override protected Statement withBefores(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) { Statement junitBefores = super.withBefores(frameworkMethod, testInstance, statement); return new RunBeforeTestMethodCallbacks(junitBefores, testInstance, frameworkMethod.getMethod(), getTestContextManager()); }
Statement function(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) { Statement junitBefores = super.withBefores(frameworkMethod, testInstance, statement); return new RunBeforeTestMethodCallbacks(junitBefores, testInstance, frameworkMethod.getMethod(), getTestContextManager()); }
/** * Wrap the {@link Statement} returned by the parent implementation with a * {@code RunBeforeTestMethodCallbacks} statement, thus preserving the * default functionality while adding support for the Spring TestContext * Framework. * @see RunBeforeTestMethodCallbacks */
Wrap the <code>Statement</code> returned by the parent implementation with a RunBeforeTestMethodCallbacks statement, thus preserving the default functionality while adding support for the Spring TestContext Framework
withBefores
{ "repo_name": "boggad/jdk9-sample", "path": "sample-catalog/spring-jdk9/src/spring.test/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.java", "license": "mit", "size": 20346 }
[ "org.junit.runners.model.FrameworkMethod", "org.junit.runners.model.Statement", "org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks" ]
import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks;
import org.junit.runners.model.*; import org.springframework.test.context.junit4.statements.*;
[ "org.junit.runners", "org.springframework.test" ]
org.junit.runners; org.springframework.test;
2,622,265
private Map<ServerInstance, byte[]> gatherServerResponses(CompositeFuture<byte[]> compositeFuture, ScatterGatherStats scatterGatherStats, boolean isOfflineTable, String tableNameWithType, List<ProcessingException> processingExceptions) { try { Map<ServerInstance, byte[]> serverResponseMap = compositeFuture.get(); Iterator<Entry<ServerInstance, byte[]>> iterator = serverResponseMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<ServerInstance, byte[]> entry = iterator.next(); if (entry.getValue().length == 0) { LOGGER.warn("Got empty response from server: {]", entry.getKey().getShortHostName()); iterator.remove(); } } Map<ServerInstance, Long> responseTimes = compositeFuture.getResponseTimes(); scatterGatherStats.setResponseTimeMillis(responseTimes, isOfflineTable); return serverResponseMap; } catch (Exception e) { LOGGER.error("Caught exception while fetching responses for table: {}", tableNameWithType, e); _brokerMetrics.addMeteredTableValue(tableNameWithType, BrokerMeter.RESPONSE_FETCH_EXCEPTIONS, 1); processingExceptions.add(QueryException.getException(QueryException.BROKER_GATHER_ERROR, e)); return null; } }
Map<ServerInstance, byte[]> function(CompositeFuture<byte[]> compositeFuture, ScatterGatherStats scatterGatherStats, boolean isOfflineTable, String tableNameWithType, List<ProcessingException> processingExceptions) { try { Map<ServerInstance, byte[]> serverResponseMap = compositeFuture.get(); Iterator<Entry<ServerInstance, byte[]>> iterator = serverResponseMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<ServerInstance, byte[]> entry = iterator.next(); if (entry.getValue().length == 0) { LOGGER.warn(STR, entry.getKey().getShortHostName()); iterator.remove(); } } Map<ServerInstance, Long> responseTimes = compositeFuture.getResponseTimes(); scatterGatherStats.setResponseTimeMillis(responseTimes, isOfflineTable); return serverResponseMap; } catch (Exception e) { LOGGER.error(STR, tableNameWithType, e); _brokerMetrics.addMeteredTableValue(tableNameWithType, BrokerMeter.RESPONSE_FETCH_EXCEPTIONS, 1); processingExceptions.add(QueryException.getException(QueryException.BROKER_GATHER_ERROR, e)); return null; } }
/** * Gather responses from servers, append processing exceptions to the processing exception list passed in. * * @param compositeFuture composite future returned from scatter phase. * @param scatterGatherStats scatter-gather statistics. * @param isOfflineTable whether the scatter-gather target is an OFFLINE table. * @param tableNameWithType table name with type suffix. * @param processingExceptions list of processing exceptions. * @return server response map. */
Gather responses from servers, append processing exceptions to the processing exception list passed in
gatherServerResponses
{ "repo_name": "apucher/pinot", "path": "pinot-broker/src/main/java/com/linkedin/pinot/broker/requesthandler/ConnectionPoolBrokerRequestHandler.java", "license": "apache-2.0", "size": 18410 }
[ "com.linkedin.pinot.common.exception.QueryException", "com.linkedin.pinot.common.metrics.BrokerMeter", "com.linkedin.pinot.common.response.ProcessingException", "com.linkedin.pinot.common.response.ServerInstance", "com.linkedin.pinot.transport.common.CompositeFuture", "com.linkedin.pinot.transport.scattergather.ScatterGatherStats", "java.util.Iterator", "java.util.List", "java.util.Map" ]
import com.linkedin.pinot.common.exception.QueryException; import com.linkedin.pinot.common.metrics.BrokerMeter; import com.linkedin.pinot.common.response.ProcessingException; import com.linkedin.pinot.common.response.ServerInstance; import com.linkedin.pinot.transport.common.CompositeFuture; import com.linkedin.pinot.transport.scattergather.ScatterGatherStats; import java.util.Iterator; import java.util.List; import java.util.Map;
import com.linkedin.pinot.common.exception.*; import com.linkedin.pinot.common.metrics.*; import com.linkedin.pinot.common.response.*; import com.linkedin.pinot.transport.common.*; import com.linkedin.pinot.transport.scattergather.*; import java.util.*;
[ "com.linkedin.pinot", "java.util" ]
com.linkedin.pinot; java.util;
1,054,711
@Override protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) { boolean success = true; LOG.debug("Entering processCustomSaveDocumentBusinessRules()"); // process rules success &= checkRules(document); return success; }
boolean function(MaintenanceDocument document) { boolean success = true; LOG.debug(STR); success &= checkRules(document); return success; }
/** * Processes the rules * * @param document MaintenanceDocument type of document to be processed. * @return boolean true when success * @see org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase#processCustomSaveDocumentBusinessRules(org.kuali.rice.kns.document.MaintenanceDocument) */
Processes the rules
processCustomSaveDocumentBusinessRules
{ "repo_name": "Ariah-Group/Finance", "path": "af_webapp/src/main/java/org/kuali/kfs/module/ld/document/validation/impl/BenefitsCalculationDocumentRule.java", "license": "apache-2.0", "size": 7214 }
[ "org.kuali.rice.kns.document.MaintenanceDocument" ]
import org.kuali.rice.kns.document.MaintenanceDocument;
import org.kuali.rice.kns.document.*;
[ "org.kuali.rice" ]
org.kuali.rice;
1,988,424
public Box getBox (Bone boneOrObject) { ObjectInfo info = getObjectInfoFor(boneOrObject); this.prevBBox.calcFor(boneOrObject, info); return this.prevBBox; }
Box function (Bone boneOrObject) { ObjectInfo info = getObjectInfoFor(boneOrObject); this.prevBBox.calcFor(boneOrObject, info); return this.prevBBox; }
/** * Calculates and returns a {@link Box} for the given bone or object. * @param boneOrObject the bone or object to calculate the bounding box for * @return the box for the given bone or object * @throws NullPointerException if no object info for the given bone or object exists */
Calculates and returns a <code>Box</code> for the given bone or object
getBox
{ "repo_name": "piotr-j/VisEditor", "path": "plugins/vis-runtime-spriter/src/main/java/com/brashmonkey/spriter/Player.java", "license": "apache-2.0", "size": 38708 }
[ "com.brashmonkey.spriter.Entity", "com.brashmonkey.spriter.Timeline" ]
import com.brashmonkey.spriter.Entity; import com.brashmonkey.spriter.Timeline;
import com.brashmonkey.spriter.*;
[ "com.brashmonkey.spriter" ]
com.brashmonkey.spriter;
304,796
public Adapter createPaletteAdapter() { return null; }
Adapter function() { return null; }
/** * Creates a new adapter for an object of class '{@link org.casa.dsltesting.Qt48Xmlschema.Palette <em>Palette</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 org.casa.dsltesting.Qt48Xmlschema.Palette * @generated */
Creates a new adapter for an object of class '<code>org.casa.dsltesting.Qt48Xmlschema.Palette Palette</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.
createPaletteAdapter
{ "repo_name": "pedromateo/tug_qt_unit_testing_fw", "path": "qt48_model/src/org/casa/dsltesting/Qt48Xmlschema/util/Qt48XmlschemaAdapterFactory.java", "license": "gpl-3.0", "size": 46616 }
[ "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;
33,113
public static Stream<Package> packages() { return Arrays.stream(getSystemPackageNames()) .map(name -> getDefinedPackage(name.replace('/', '.'))); } static class PackageHelper { private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
static Stream<Package> function() { return Arrays.stream(getSystemPackageNames()) .map(name -> getDefinedPackage(name.replace('/', '.'))); } static class PackageHelper { private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
/** * Returns a stream of the packages defined to the boot loader. */
Returns a stream of the packages defined to the boot loader
packages
{ "repo_name": "google/desugar_jdk_libs", "path": "jdk11/src/java.base/share/classes/jdk/internal/loader/BootLoader.java", "license": "gpl-2.0", "size": 11796 }
[ "java.util.Arrays", "java.util.stream.Stream" ]
import java.util.Arrays; import java.util.stream.Stream;
import java.util.*; import java.util.stream.*;
[ "java.util" ]
java.util;
1,517,797
@ReturnNullAsFalse public ZipDirectory zip_open(Env env, @NotNull StringValue filename) { if (filename == null || filename.length() == 0) return null; BinaryStream s = FileModule.fopen(env, filename, "rb", false, null); if (s == null) return null; return new ZipDirectory((BinaryInput) s); }
ZipDirectory function(Env env, @NotNull StringValue filename) { if (filename == null filename.length() == 0) return null; BinaryStream s = FileModule.fopen(env, filename, "rb", false, null); if (s == null) return null; return new ZipDirectory((BinaryInput) s); }
/** * Opens stream to read zip entries. * Since we're only reading, fopen mode is always "rb". */
Opens stream to read zip entries. Since we're only reading, fopen mode is always "rb"
zip_open
{ "repo_name": "christianchristensen/resin", "path": "modules/quercus/src/com/caucho/quercus/lib/zip/ZipModule.java", "license": "gpl-2.0", "size": 5780 }
[ "com.caucho.quercus.annotation.NotNull", "com.caucho.quercus.env.Env", "com.caucho.quercus.env.StringValue", "com.caucho.quercus.lib.file.BinaryInput", "com.caucho.quercus.lib.file.BinaryStream", "com.caucho.quercus.lib.file.FileModule" ]
import com.caucho.quercus.annotation.NotNull; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.StringValue; import com.caucho.quercus.lib.file.BinaryInput; import com.caucho.quercus.lib.file.BinaryStream; import com.caucho.quercus.lib.file.FileModule;
import com.caucho.quercus.annotation.*; import com.caucho.quercus.env.*; import com.caucho.quercus.lib.file.*;
[ "com.caucho.quercus" ]
com.caucho.quercus;
2,080,665
@Generated @Selector("barStyle") @NInt public native long barStyle();
@Selector(STR) native long function();
/** * Valid bar styles are UIBarStyleDefault (default) and UIBarStyleBlack. */
Valid bar styles are UIBarStyleDefault (default) and UIBarStyleBlack
barStyle
{ "repo_name": "multi-os-engine/moe-core", "path": "moe.apple/moe.platform.ios/src/main/java/apple/uikit/UITabBar.java", "license": "apache-2.0", "size": 30961 }
[ "org.moe.natj.objc.ann.Selector" ]
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.ann.*;
[ "org.moe.natj" ]
org.moe.natj;
2,688,855
public static void sendHoverableCommandMessage(Player player, String message, String command, String hover, String color) throws Exception { sendChatPacket(player, constructHoverableCommandMessageJson(message, command, hover, color), CHAT_MESSAGE_BYTE); }
static void function(Player player, String message, String command, String hover, String color) throws Exception { sendChatPacket(player, constructHoverableCommandMessageJson(message, command, hover, color), CHAT_MESSAGE_BYTE); }
/** * Sends a clickable and hoverable message to the player. Only supported in Minecraft 1.8+. * * @param player Online player to send the message to. * @param message The text to display in the chat. * @param command The command that is entered when clicking on the message. * @param hover The text to display in the hover. * @param color The color of the hover text. * @throws Exception */
Sends a clickable and hoverable message to the player. Only supported in Minecraft 1.8+
sendHoverableCommandMessage
{ "repo_name": "PyvesB/MCShared", "path": "src/main/java/com/hm/mcshared/particle/FancyMessageSender.java", "license": "gpl-3.0", "size": 12441 }
[ "org.bukkit.entity.Player" ]
import org.bukkit.entity.Player;
import org.bukkit.entity.*;
[ "org.bukkit.entity" ]
org.bukkit.entity;
2,092,592
void beforeClickOn(WebElement element, WebDriver driver);
void beforeClickOn(WebElement element, WebDriver driver);
/** * Called before {@link WebElement#click WebElement.click()}. */
Called before <code>WebElement#click WebElement.click()</code>
beforeClickOn
{ "repo_name": "jerome-jacob/selenium", "path": "java/client/src/org/openqa/selenium/support/events/WebDriverEventListener.java", "license": "apache-2.0", "size": 4806 }
[ "org.openqa.selenium.WebDriver", "org.openqa.selenium.WebElement" ]
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.*;
[ "org.openqa.selenium" ]
org.openqa.selenium;
1,451,172
private void detectWTPDefaultServer( WorkspaceConfiguration workspaceConfiguration, String wtpDefaultServer, Log log ) { Map<String, String> servers = readDefinedServers( workspaceConfiguration, log ); if ( servers == null || servers.isEmpty() ) { return; } if ( wtpDefaultServer != null ) { Set<String> ids = servers.keySet(); // first we try the exact match Iterator<String> idIterator = ids.iterator(); while ( workspaceConfiguration.getDefaultDeployServerId() == null && idIterator.hasNext() ) { String id = idIterator.next(); String name = servers.get( id ); if ( wtpDefaultServer.equals( id ) || wtpDefaultServer.equals( name ) ) { workspaceConfiguration.setDefaultDeployServerId( id ); workspaceConfiguration.setDefaultDeployServerName( name ); } } if ( workspaceConfiguration.getDefaultDeployServerId() == null ) { log.info( "no exact wtp server match." ); // now we will try the substring match idIterator = ids.iterator(); while ( workspaceConfiguration.getDefaultDeployServerId() == null && idIterator.hasNext() ) { String id = idIterator.next(); String name = servers.get( id ); if ( id.contains( wtpDefaultServer ) || name.contains( wtpDefaultServer ) ) { workspaceConfiguration.setDefaultDeployServerId( id ); workspaceConfiguration.setDefaultDeployServerName( name ); } } } } if ( workspaceConfiguration.getDefaultDeployServerId() == null && servers.size() > 0 ) { // now take the default server log.info( "no substring wtp server match." ); workspaceConfiguration.setDefaultDeployServerId( servers.get( "" ) ); workspaceConfiguration.setDefaultDeployServerName( servers.get( workspaceConfiguration.getDefaultDeployServerId() ) ); } log.info( "Using as WTP server : " + workspaceConfiguration.getDefaultDeployServerName() ); }
void function( WorkspaceConfiguration workspaceConfiguration, String wtpDefaultServer, Log log ) { Map<String, String> servers = readDefinedServers( workspaceConfiguration, log ); if ( servers == null servers.isEmpty() ) { return; } if ( wtpDefaultServer != null ) { Set<String> ids = servers.keySet(); Iterator<String> idIterator = ids.iterator(); while ( workspaceConfiguration.getDefaultDeployServerId() == null && idIterator.hasNext() ) { String id = idIterator.next(); String name = servers.get( id ); if ( wtpDefaultServer.equals( id ) wtpDefaultServer.equals( name ) ) { workspaceConfiguration.setDefaultDeployServerId( id ); workspaceConfiguration.setDefaultDeployServerName( name ); } } if ( workspaceConfiguration.getDefaultDeployServerId() == null ) { log.info( STR ); idIterator = ids.iterator(); while ( workspaceConfiguration.getDefaultDeployServerId() == null && idIterator.hasNext() ) { String id = idIterator.next(); String name = servers.get( id ); if ( id.contains( wtpDefaultServer ) name.contains( wtpDefaultServer ) ) { workspaceConfiguration.setDefaultDeployServerId( id ); workspaceConfiguration.setDefaultDeployServerName( name ); } } } } if ( workspaceConfiguration.getDefaultDeployServerId() == null && servers.size() > 0 ) { log.info( STR ); workspaceConfiguration.setDefaultDeployServerId( servers.get( STRUsing as WTP server : " + workspaceConfiguration.getDefaultDeployServerName() ); }
/** * Detect WTP Default Server. Do nothing if tehre are no defined servers in the settings. * * @param workspaceConfiguration the workspace configuration * @param wtpDefaultServer Default server * @param log the log */
Detect WTP Default Server. Do nothing if tehre are no defined servers in the settings
detectWTPDefaultServer
{ "repo_name": "wcm-io-devops/maven-eclipse-plugin", "path": "src/main/java/org/apache/maven/plugin/eclipse/reader/ReadWorkspaceLocations.java", "license": "apache-2.0", "size": 26268 }
[ "java.util.Iterator", "java.util.Map", "java.util.Set", "org.apache.maven.plugin.eclipse.WorkspaceConfiguration", "org.apache.maven.plugin.logging.Log" ]
import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.maven.plugin.eclipse.WorkspaceConfiguration; import org.apache.maven.plugin.logging.Log;
import java.util.*; import org.apache.maven.plugin.eclipse.*; import org.apache.maven.plugin.logging.*;
[ "java.util", "org.apache.maven" ]
java.util; org.apache.maven;
303,350
public void resolveNextConflict(Action<ConflictResolutionResult> resolutionAction) { assert hasConflicts(); ConflictContainer.Conflict conflict = conflicts.popConflict(); ComponentResolutionState selected = compositeResolver.select(conflict.candidates); ConflictResolutionResult result = new DefaultConflictResolutionResult(potentialConflict(conflict), selected); resolutionAction.execute(result); LOGGER.debug("Selected {} from conflicting modules {}.", selected, conflict.candidates); }
void function(Action<ConflictResolutionResult> resolutionAction) { assert hasConflicts(); ConflictContainer.Conflict conflict = conflicts.popConflict(); ComponentResolutionState selected = compositeResolver.select(conflict.candidates); ConflictResolutionResult result = new DefaultConflictResolutionResult(potentialConflict(conflict), selected); resolutionAction.execute(result); LOGGER.debug(STR, selected, conflict.candidates); }
/** * Resolves the conflict by delegating to the conflict resolver who selects single version from given candidates. Executes provided action against the conflict resolution result object. */
Resolves the conflict by delegating to the conflict resolver who selects single version from given candidates. Executes provided action against the conflict resolution result object
resolveNextConflict
{ "repo_name": "cams7/gradle-samples", "path": "plugin/dependency-management/src/main/java/org/gradle/api/internal/artifacts/ivyservice/resolveengine/graph/conflicts/DefaultConflictHandler.java", "license": "gpl-2.0", "size": 3443 }
[ "org.gradle.api.Action", "org.gradle.api.internal.artifacts.ivyservice.resolveengine.ComponentResolutionState" ]
import org.gradle.api.Action; import org.gradle.api.internal.artifacts.ivyservice.resolveengine.ComponentResolutionState;
import org.gradle.api.*; import org.gradle.api.internal.artifacts.ivyservice.resolveengine.*;
[ "org.gradle.api" ]
org.gradle.api;
1,872,977
@Override public List<SootMethod> getHeads() { return heads; }
List<SootMethod> function() { return heads; }
/** * You get a List of SootMethod. * * @return */
You get a List of SootMethod
getHeads
{ "repo_name": "plast-lab/soot", "path": "src/main/java/soot/jimple/toolkits/annotation/purity/DirectedCallGraph.java", "license": "lgpl-2.1", "size": 5708 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
230,250
@Test public void testTestThrows() { try { assertTrue(P1.testThrows("v12", "v8", 1, "turbo", "t", "u", "r", "b")); } catch (IllegalArgumentException e) { fail("Predicate failed"); } try { P1.testThrows(null, "v2", 1, "turbo", "t", "u", "r", "b"); fail("Predicate has to fail"); } catch (IllegalArgumentException e) { assertNotNull(e); assertEquals(ERROR1, e.getMessage()); } }
void function() { try { assertTrue(P1.testThrows("v12", "v8", 1, "turbo", "t", "u", "r", "b")); } catch (IllegalArgumentException e) { fail(STR); } try { P1.testThrows(null, "v2", 1, "turbo", "t", "u", "r", "b"); fail(STR); } catch (IllegalArgumentException e) { assertNotNull(e); assertEquals(ERROR1, e.getMessage()); } }
/** * Test method for * {@link OctoPredicateThrowable#testThrows(java.lang.Object, java.lang.Object)}. */
Test method for <code>OctoPredicateThrowable#testThrows(java.lang.Object, java.lang.Object)</code>
testTestThrows
{ "repo_name": "Gilandel/utils-commons", "path": "src/test/java/fr/landel/utils/commons/function/OctoPredicateThrowableTest.java", "license": "apache-2.0", "size": 8015 }
[ "org.junit.Assert" ]
import org.junit.Assert;
import org.junit.*;
[ "org.junit" ]
org.junit;
530,756
public final void containsNoDuplicates() { List<Entry<T>> duplicates = Lists.newArrayList(); for (Multiset.Entry<T> entry : LinkedHashMultiset.create(getSubject()).entrySet()) { if (entry.getCount() > 1) { duplicates.add(entry); } } if (!duplicates.isEmpty()) { failWithRawMessage("%s has the following duplicates: <%s>", getDisplaySubject(), duplicates); } }
final void function() { List<Entry<T>> duplicates = Lists.newArrayList(); for (Multiset.Entry<T> entry : LinkedHashMultiset.create(getSubject()).entrySet()) { if (entry.getCount() > 1) { duplicates.add(entry); } } if (!duplicates.isEmpty()) { failWithRawMessage(STR, getDisplaySubject(), duplicates); } }
/** * Attests that the subject does not contain duplicate elements. */
Attests that the subject does not contain duplicate elements
containsNoDuplicates
{ "repo_name": "hcoles/truth", "path": "core/src/main/java/com/google/common/truth/IterableSubject.java", "license": "apache-2.0", "size": 18588 }
[ "com.google.common.collect.LinkedHashMultiset", "com.google.common.collect.Lists", "com.google.common.collect.Multiset", "java.util.List" ]
import com.google.common.collect.LinkedHashMultiset; import com.google.common.collect.Lists; import com.google.common.collect.Multiset; import java.util.List;
import com.google.common.collect.*; import java.util.*;
[ "com.google.common", "java.util" ]
com.google.common; java.util;
358,210
protected String getMetricUrl(String metricToAnnotate, long triggerFiredTime) { long start = triggerFiredTime - (6L * DateTimeConstants.MILLIS_PER_HOUR); long end = Math.min(System.currentTimeMillis(), triggerFiredTime + (6L * DateTimeConstants.MILLIS_PER_HOUR)); String expression = MessageFormat.format("{0,number,#}:{1,number,#}:{2}", start, end, metricToAnnotate); return getExpressionUrl(expression); }
String function(String metricToAnnotate, long triggerFiredTime) { long start = triggerFiredTime - (6L * DateTimeConstants.MILLIS_PER_HOUR); long end = Math.min(System.currentTimeMillis(), triggerFiredTime + (6L * DateTimeConstants.MILLIS_PER_HOUR)); String expression = MessageFormat.format(STR, start, end, metricToAnnotate); return getExpressionUrl(expression); }
/** * Returns the URL linking back to the metric for use in alert notification. * * @param metricToAnnotate The metric to annotate. * @param triggerFiredTime The epoch timestamp when the corresponding trigger fired. * * @return The fully constructed URL for the metric. */
Returns the URL linking back to the metric for use in alert notification
getMetricUrl
{ "repo_name": "dilipdevaraj-sfdc/Argus-1", "path": "ArgusCore/src/main/java/com/salesforce/dva/argus/service/alert/notifier/AuditNotifier.java", "license": "bsd-3-clause", "size": 12711 }
[ "java.text.MessageFormat", "org.joda.time.DateTimeConstants" ]
import java.text.MessageFormat; import org.joda.time.DateTimeConstants;
import java.text.*; import org.joda.time.*;
[ "java.text", "org.joda.time" ]
java.text; org.joda.time;
47,307
public SharedActivationGroupDescriptor getGroupDescriptor() { for (int i = 0; i < descriptors.length; i++) { if (descriptors[i] instanceof SharedActivationGroupDescriptor) { return (SharedActivationGroupDescriptor) descriptors[i]; } } return null; }
SharedActivationGroupDescriptor function() { for (int i = 0; i < descriptors.length; i++) { if (descriptors[i] instanceof SharedActivationGroupDescriptor) { return (SharedActivationGroupDescriptor) descriptors[i]; } } return null; }
/** * Return the <code>SharedActivationGroupDescriptor</code> contained in the * service starter configuration. Returns <code>null</code> if there is no * such descriptor, or if the command being analyzed does not invoke the * service starter. * * @return the <code>SharedActivationGroupDescriptor</code> or * <code>null</code> */
Return the <code>SharedActivationGroupDescriptor</code> contained in the service starter configuration. Returns <code>null</code> if there is no such descriptor, or if the command being analyzed does not invoke the service starter
getGroupDescriptor
{ "repo_name": "pfirmstone/JGDMS", "path": "JGDMS/tools/envcheck/src/main/java/org/apache/river/tool/envcheck/EnvCheck.java", "license": "apache-2.0", "size": 47937 }
[ "org.apache.river.start.SharedActivationGroupDescriptor" ]
import org.apache.river.start.SharedActivationGroupDescriptor;
import org.apache.river.start.*;
[ "org.apache.river" ]
org.apache.river;
496,604
// TODO: Rename and change types and number of parameters public static BM_FragmentInfo newInstance(String param1, String param2) { BM_FragmentInfo fragment = new BM_FragmentInfo(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public BM_FragmentInfo() { // Required empty public constructor }
static BM_FragmentInfo function(String param1, String param2) { BM_FragmentInfo fragment = new BM_FragmentInfo(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public BM_FragmentInfo() { }
/** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment BM_FragmentInfo. */
Use this factory method to create a new instance of this fragment using the provided parameters
newInstance
{ "repo_name": "thanhpd/BeMan", "path": "app/src/main/java/com/uet/beman/fragment/BM_FragmentInfo.java", "license": "mit", "size": 5005 }
[ "android.os.Bundle" ]
import android.os.Bundle;
import android.os.*;
[ "android.os" ]
android.os;
925,413
private void disposeServiceCollectors() { if (Log.isLoggable("jmdns", Log.VERBOSE)) { Log.d("jmdns", "disposeServiceCollectors()"); } for (String type : _serviceCollectors.keySet()) { ServiceCollector collector = _serviceCollectors.get(type); if (collector != null) { this.removeServiceListener(type, collector); _serviceCollectors.remove(type, collector); } } } private static class ServiceCollector implements ServiceListener { // private static Logger logger = Logger.getLogger(ServiceCollector.class.getName()); private final ConcurrentMap<String, ServiceInfo> _infos; private final ConcurrentMap<String, ServiceEvent> _events; private final String _type; private volatile boolean _needToWaitForInfos; public ServiceCollector(String type) { super(); _infos = new ConcurrentHashMap<String, ServiceInfo>(); _events = new ConcurrentHashMap<String, ServiceEvent>(); _type = type; _needToWaitForInfos = true; }
void function() { if (Log.isLoggable("jmdns", Log.VERBOSE)) { Log.d("jmdns", STR); } for (String type : _serviceCollectors.keySet()) { ServiceCollector collector = _serviceCollectors.get(type); if (collector != null) { this.removeServiceListener(type, collector); _serviceCollectors.remove(type, collector); } } } private static class ServiceCollector implements ServiceListener { private final ConcurrentMap<String, ServiceInfo> _infos; private final ConcurrentMap<String, ServiceEvent> _events; private final String _type; private volatile boolean _needToWaitForInfos; public ServiceCollector(String type) { super(); _infos = new ConcurrentHashMap<String, ServiceInfo>(); _events = new ConcurrentHashMap<String, ServiceEvent>(); _type = type; _needToWaitForInfos = true; }
/** * This method disposes all ServiceCollector instances which have been created by calls to method <code>list(type)</code>. * * @see #list */
This method disposes all ServiceCollector instances which have been created by calls to method <code>list(type)</code>
disposeServiceCollectors
{ "repo_name": "lhzheng880828/AndroidApp", "path": "AirPlay/src/javax/jmdns/impl/JmDNSImpl.java", "license": "apache-2.0", "size": 79029 }
[ "android.util.Log", "java.util.concurrent.ConcurrentHashMap", "java.util.concurrent.ConcurrentMap", "javax.jmdns.ServiceEvent", "javax.jmdns.ServiceInfo", "javax.jmdns.ServiceListener" ]
import android.util.Log; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener;
import android.util.*; import java.util.concurrent.*; import javax.jmdns.*;
[ "android.util", "java.util", "javax.jmdns" ]
android.util; java.util; javax.jmdns;
1,849,489
public SipAppDesc getSipApp(String appName) { return this.activeApp.get(appName); }
SipAppDesc function(String appName) { return this.activeApp.get(appName); }
/** * Gets the SIP App descriptor for the given application name. * @param appName The name of the SIP Application. * @return The SIP App Descriptor if available, otherwise null */
Gets the SIP App descriptor for the given application name
getSipApp
{ "repo_name": "OpenLiberty/open-liberty", "path": "dev/com.ibm.ws.sipcontainer/src/com/ibm/ws/sip/container/matching/SipServletsMatcher.java", "license": "epl-1.0", "size": 15088 }
[ "com.ibm.ws.sip.container.parser.SipAppDesc" ]
import com.ibm.ws.sip.container.parser.SipAppDesc;
import com.ibm.ws.sip.container.parser.*;
[ "com.ibm.ws" ]
com.ibm.ws;
401,688
public static boolean indexExists(Directory directory) throws IOException { return directory.fileExists("segments"); }
static boolean function(Directory directory) throws IOException { return directory.fileExists(STR); }
/** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise * @throws IOException if there is a problem with accessing the index */
Returns <code>true</code> if an index exists at the specified directory. If the directory does not exist or if there is no index in it
indexExists
{ "repo_name": "masterucm1617/botzzaroni", "path": "BotzzaroniDev/GATE_Developer_8.4/src/main/gate/creole/annic/apache/lucene/index/IndexReader.java", "license": "gpl-3.0", "size": 22458 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
2,101,094
public static JMSLogoutMessage createDecodedReplyMessage(final Message message) throws JMSException { JMSLogoutMessage msg = new JMSLogoutMessage(); msg.decodeReplyMessage(message); return msg; }
static JMSLogoutMessage function(final Message message) throws JMSException { JMSLogoutMessage msg = new JMSLogoutMessage(); msg.decodeReplyMessage(message); return msg; }
/** * Create a decoded reply message from inbound comming from chappy. * @param message received by JMS * @return decoded message * @throws JMSException */
Create a decoded reply message from inbound comming from chappy
createDecodedReplyMessage
{ "repo_name": "gdimitriu/chappy", "path": "chappy-clients-jms/src/main/java/chappy/clients/jms/protocol/JMSLogoutMessage.java", "license": "gpl-3.0", "size": 5421 }
[ "javax.jms.JMSException", "javax.jms.Message" ]
import javax.jms.JMSException; import javax.jms.Message;
import javax.jms.*;
[ "javax.jms" ]
javax.jms;
587,870
protected File getDifferencesReportFile(final String viewName, final String snapshotName) throws IOException { final String tempDir = System.getProperty("java.io.tmpdir"); final File regressionDir = new File(tempDir, "regression-report"); if (!regressionDir.exists()) { Preconditions.checkState(regressionDir.mkdirs(), "Unable to mkdir " + regressionDir.getPath()); } return new File(regressionDir, viewName + "-" + snapshotName + ".txt"); }
File function(final String viewName, final String snapshotName) throws IOException { final String tempDir = System.getProperty(STR); final File regressionDir = new File(tempDir, STR); if (!regressionDir.exists()) { Preconditions.checkState(regressionDir.mkdirs(), STR + regressionDir.getPath()); } return new File(regressionDir, viewName + "-" + snapshotName + ".txt"); }
/** * A {@link File} giving the location to write the difference report to. * * @param viewName * the view which ran * @param snapshotName * the snapshot which was run against * @return the location to write the differences report to * @throws IOException * if there is a problem getting the file */
A <code>File</code> giving the location to write the difference report to
getDifferencesReportFile
{ "repo_name": "McLeodMoores/starling", "path": "projects/integration/src/main/java/com/opengamma/integration/regression/AbstractRegressionTest.java", "license": "apache-2.0", "size": 8672 }
[ "com.google.common.base.Preconditions", "java.io.File", "java.io.IOException" ]
import com.google.common.base.Preconditions; import java.io.File; import java.io.IOException;
import com.google.common.base.*; import java.io.*;
[ "com.google.common", "java.io" ]
com.google.common; java.io;
1,072,492
@VisibleForTesting public static ImmutableMultimap<String, Path> parseExopackageInfoMetadata( Path metadataTxt, Path resolvePathAgainst, ProjectFilesystem filesystem) throws IOException { ImmutableMultimap.Builder<String, Path> builder = ImmutableMultimap.builder(); for (String line : filesystem.readLines(metadataTxt)) { // ignore lines that start with '.' if (line.startsWith(".")) { continue; } List<String> parts = Splitter.on(' ').splitToList(line); if (parts.size() < 2) { throw new RuntimeException("Illegal line in metadata file: " + line); } builder.put(parts.get(1), resolvePathAgainst.resolve(parts.get(0))); } return builder.build(); }
static ImmutableMultimap<String, Path> function( Path metadataTxt, Path resolvePathAgainst, ProjectFilesystem filesystem) throws IOException { ImmutableMultimap.Builder<String, Path> builder = ImmutableMultimap.builder(); for (String line : filesystem.readLines(metadataTxt)) { if (line.startsWith(".")) { continue; } List<String> parts = Splitter.on(' ').splitToList(line); if (parts.size() < 2) { throw new RuntimeException(STR + line); } builder.put(parts.get(1), resolvePathAgainst.resolve(parts.get(0))); } return builder.build(); }
/** * Parses a text file which is supposed to be in the following format: "file_path_without_spaces * file_hash ...." i.e. it parses the first two columns of each line and ignores the rest of it. * * @return A multi map from the file hash to its path, which equals the raw path resolved against * {@code resolvePathAgainst}. */
Parses a text file which is supposed to be in the following format: "file_path_without_spaces file_hash ...." i.e. it parses the first two columns of each line and ignores the rest of it
parseExopackageInfoMetadata
{ "repo_name": "marcinkwiatkowski/buck", "path": "src/com/facebook/buck/android/exopackage/ExopackageInstaller.java", "license": "apache-2.0", "size": 13294 }
[ "com.facebook.buck.io.ProjectFilesystem", "com.google.common.base.Splitter", "com.google.common.collect.ImmutableMultimap", "java.io.IOException", "java.nio.file.Path", "java.util.List" ]
import com.facebook.buck.io.ProjectFilesystem; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableMultimap; import java.io.IOException; import java.nio.file.Path; import java.util.List;
import com.facebook.buck.io.*; import com.google.common.base.*; import com.google.common.collect.*; import java.io.*; import java.nio.file.*; import java.util.*;
[ "com.facebook.buck", "com.google.common", "java.io", "java.nio", "java.util" ]
com.facebook.buck; com.google.common; java.io; java.nio; java.util;
1,262,588
@Restriction({RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) @FlakyTest public void testTapExpand() throws InterruptedException, TimeoutException { assertNoSearchesLoaded(); clickWordNode("states"); assertNoContentViewCore(); assertNoSearchesLoaded(); // Fake a search term resolution response. fakeResponse(false, 200, "states", "United States Intelligence", "alternate-term", false); assertContainsParameters("states", "alternate-term"); assertEquals(1, mFakeServer.loadedUrlCount()); assertLoadedLowPriorityUrl(); assertContentViewCoreCreated(); tapPeekingBarToExpandAndAssert(); assertLoadedLowPriorityUrl(); assertEquals(1, mFakeServer.loadedUrlCount()); // tap the base page to close. tapBasePage(); waitForPanelToCloseAndAssert(); assertEquals(1, mFakeServer.loadedUrlCount()); assertNoContentViewCore(); }
@Restriction({RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) void function() throws InterruptedException, TimeoutException { assertNoSearchesLoaded(); clickWordNode(STR); assertNoContentViewCore(); assertNoSearchesLoaded(); fakeResponse(false, 200, STR, STR, STR, false); assertContainsParameters(STR, STR); assertEquals(1, mFakeServer.loadedUrlCount()); assertLoadedLowPriorityUrl(); assertContentViewCoreCreated(); tapPeekingBarToExpandAndAssert(); assertLoadedLowPriorityUrl(); assertEquals(1, mFakeServer.loadedUrlCount()); tapBasePage(); waitForPanelToCloseAndAssert(); assertEquals(1, mFakeServer.loadedUrlCount()); assertNoContentViewCore(); }
/** * Tests tap to expand, after an initial tap to activate the peeking card. * * @SmallTest * @Feature({"ContextualSearch"}) */
Tests tap to expand, after an initial tap to activate the peeking card
testTapExpand
{ "repo_name": "Just-D/chromium-1", "path": "chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java", "license": "bsd-3-clause", "size": 70757 }
[ "java.util.concurrent.TimeoutException", "org.chromium.base.test.util.Restriction" ]
import java.util.concurrent.TimeoutException; import org.chromium.base.test.util.Restriction;
import java.util.concurrent.*; import org.chromium.base.test.util.*;
[ "java.util", "org.chromium.base" ]
java.util; org.chromium.base;
2,739,011
@Override public void exitModifier(@NotNull JavaParser.ModifierContext ctx) { }
@Override public void exitModifier(@NotNull JavaParser.ModifierContext ctx) { }
/** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */
The default implementation does nothing
enterModifier
{ "repo_name": "martinaguero/deep", "path": "src/org/trimatek/deep/lexer/JavaBaseListener.java", "license": "apache-2.0", "size": 39286 }
[ "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;
1,030,605
public final void xdrEncodeLongFixedVector(long [] value, int length) throws OncRpcException, IOException { if ( value.length != length ) { throw(new IllegalArgumentException("array size does not match protocol specification")); } for ( int i = 0; i < length; i++ ) { xdrEncodeLong(value[i]); } }
final void function(long [] value, int length) throws OncRpcException, IOException { if ( value.length != length ) { throw(new IllegalArgumentException(STR)); } for ( int i = 0; i < length; i++ ) { xdrEncodeLong(value[i]); } }
/** * Encodes (aka "serializes") a vector of long integers and writes it down * this XDR stream. * * @param value long vector to be encoded. * @param length of vector to write. This parameter is used as a sanity * check. * * @throws OncRpcException if an ONC/RPC error occurs. * @throws IOException if an I/O error occurs. * @throws IllegalArgumentException if the length of the vector does not * match the specified length. */
Encodes (aka "serializes") a vector of long integers and writes it down this XDR stream
xdrEncodeLongFixedVector
{ "repo_name": "kragniz/java-player", "path": "src/xdr/XdrEncodingStream.java", "license": "gpl-2.0", "size": 25737 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
667,381
public BTree getCars() { return cars; }
BTree function() { return cars; }
/** * Returns all cars that the dealer is currently offering * * @return all cars that the dealer is currently offering */
Returns all cars that the dealer is currently offering
getCars
{ "repo_name": "marcelherd/hochschule-mannheim", "path": "Workspace/TPE/src/com/marcelherd/uebung2/auto/CarDealer.java", "license": "apache-2.0", "size": 1142 }
[ "com.marcelherd.uebung1.model.BTree" ]
import com.marcelherd.uebung1.model.BTree;
import com.marcelherd.uebung1.model.*;
[ "com.marcelherd.uebung1" ]
com.marcelherd.uebung1;
2,678,204