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
public ArrayList<String> parseEvent(String inString, String requiredObject, String[] keys) { String strippedString = inString.replaceAll("\\\\", ""); ArrayList<String> event = new ArrayList<String>(); try { JSONObject wholeObject = new JSONObject(strippedString); JSONObject extractedObject = wholeObject .getJSONObject(requiredObject); for (int i = 0; i < keys.length; i++) { event.add(extractedObject.getString(keys[i])); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return event; }
ArrayList<String> function(String inString, String requiredObject, String[] keys) { String strippedString = inString.replaceAll("\\\\", ""); ArrayList<String> event = new ArrayList<String>(); try { JSONObject wholeObject = new JSONObject(strippedString); JSONObject extractedObject = wholeObject .getJSONObject(requiredObject); for (int i = 0; i < keys.length; i++) { event.add(extractedObject.getString(keys[i])); } } catch (JSONException e) { e.printStackTrace(); } return event; }
/** * Extract event details e.g. Title, Start/End times, from String * * @param inString * @param keys * @return */
Extract event details e.g. Title, Start/End times, from String
parseEvent
{ "repo_name": "Adgillmore/MateyFindArr", "path": "src/co880/CAA/ServerUtils/JSONParser.java", "license": "mit", "size": 5220 }
[ "java.util.ArrayList", "org.json.JSONException", "org.json.JSONObject" ]
import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject;
import java.util.*; import org.json.*;
[ "java.util", "org.json" ]
java.util; org.json;
2,059,096
private static Field getField(String name, Object obj) { try { Class<?> clazz = obj.getClass(); Field field = null; while (clazz != null && field == null) { try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException e) { // check the parent to see if // the field was defined there clazz = clazz.getSuperclass(); } } if(field != null) { field.setAccessible(true); return field; } else { throw new NoSuchFieldException(); } } catch (ReflectiveOperationException e) { throw Throwables.propagate(e); } }
static Field function(String name, Object obj) { try { Class<?> clazz = obj.getClass(); Field field = null; while (clazz != null && field == null) { try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } if(field != null) { field.setAccessible(true); return field; } else { throw new NoSuchFieldException(); } } catch (ReflectiveOperationException e) { throw Throwables.propagate(e); } }
/** * Return the {@link Field} object} that holds the variable with * {@code name} in {@code obj}, if it exists. Otherwise a * NoSuchFieldException is thrown. * <p> * This method will take care of making the field accessible. * </p> * * @param name * @param obj * @return the Field object * @throws NoSuchFieldException */
Return the <code>Field</code> object} that holds the variable with name in obj, if it exists. Otherwise a NoSuchFieldException is thrown. This method will take care of making the field accessible.
getField
{ "repo_name": "bigtreeljc/concourse", "path": "concourse-driver-java/src/main/java/org/cinchapi/concourse/util/Reflection.java", "license": "apache-2.0", "size": 8275 }
[ "com.google.common.base.Throwables", "java.lang.reflect.Field" ]
import com.google.common.base.Throwables; import java.lang.reflect.Field;
import com.google.common.base.*; import java.lang.reflect.*;
[ "com.google.common", "java.lang" ]
com.google.common; java.lang;
961,810
if (dashboard == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } DashboardDto result = createDtoObject(DashboardDto.class, dashboard); result.setOwnerName(dashboard.getOwner().getUserName()); return result; }
if (dashboard == null) { throw new WebApplicationException(STR, Status.INTERNAL_SERVER_ERROR); } DashboardDto result = createDtoObject(DashboardDto.class, dashboard); result.setOwnerName(dashboard.getOwner().getUserName()); return result; }
/** * Converts dashboard entity to dashboardDto. * * @param dashboard The dashboard object. Cannot be null. * * @return DashboardDto object. * * @throws WebApplicationException If an error occurs. */
Converts dashboard entity to dashboardDto
transformToDto
{ "repo_name": "SalesforceEng/Argus", "path": "ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/DashboardDto.java", "license": "bsd-3-clause", "size": 8249 }
[ "javax.ws.rs.WebApplicationException", "javax.ws.rs.core.Response" ]
import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response;
import javax.ws.rs.*; import javax.ws.rs.core.*;
[ "javax.ws" ]
javax.ws;
2,186,771
public final PointF viewToSourceCoord(float vx, float vy, PointF sTarget) { if (vTranslate == null) { return null; } sTarget.set(viewToSourceX(vx), viewToSourceY(vy)); return sTarget; }
final PointF function(float vx, float vy, PointF sTarget) { if (vTranslate == null) { return null; } sTarget.set(viewToSourceX(vx), viewToSourceY(vy)); return sTarget; }
/** * Convert screen coordinate to source coordinate. */
Convert screen coordinate to source coordinate
viewToSourceCoord
{ "repo_name": "jovezhougang/subsampling-scale-image-view", "path": "library/src/com/davemorrissey/labs/subscaleview/SubsamplingScaleImageView.java", "license": "apache-2.0", "size": 112534 }
[ "android.graphics.PointF" ]
import android.graphics.PointF;
import android.graphics.*;
[ "android.graphics" ]
android.graphics;
308,383
ServiceFuture<Double> getBigDoubleAsync(final ServiceCallback<Double> serviceCallback);
ServiceFuture<Double> getBigDoubleAsync(final ServiceCallback<Double> serviceCallback);
/** * Get big double value 2.5976931e+101. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */
Get big double value 2.5976931e+101
getBigDoubleAsync
{ "repo_name": "sergey-shandar/autorest", "path": "src/generator/AutoRest.Java.Tests/src/main/java/fixtures/bodynumber/Numbers.java", "license": "mit", "size": 34974 }
[ "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,632,889
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller<PollResult<AgentPoolInner>, AgentPoolInner> beginUpdate( String resourceGroupName, String registryName, String agentPoolName, AgentPoolUpdateParameters updateParameters, Context context) { return beginUpdateAsync(resourceGroupName, registryName, agentPoolName, updateParameters, context) .getSyncPoller(); }
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<AgentPoolInner>, AgentPoolInner> function( String resourceGroupName, String registryName, String agentPoolName, AgentPoolUpdateParameters updateParameters, Context context) { return beginUpdateAsync(resourceGroupName, registryName, agentPoolName, updateParameters, context) .getSyncPoller(); }
/** * Updates an agent pool with the specified parameters. * * @param resourceGroupName The name of the resource group to which the container registry belongs. * @param registryName The name of the container registry. * @param agentPoolName The name of the agent pool. * @param updateParameters The parameters for updating an agent pool. * @param context The context to associate with this operation. * @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 agentpool that has the ARM resource and properties. */
Updates an agent pool with the specified parameters
beginUpdate
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/AgentPoolsClientImpl.java", "license": "mit", "size": 81743 }
[ "com.azure.core.annotation.ReturnType", "com.azure.core.annotation.ServiceMethod", "com.azure.core.management.polling.PollResult", "com.azure.core.util.Context", "com.azure.core.util.polling.SyncPoller", "com.azure.resourcemanager.containerregistry.fluent.models.AgentPoolInner", "com.azure.resourcemanager.containerregistry.models.AgentPoolUpdateParameters" ]
import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.containerregistry.fluent.models.AgentPoolInner; import com.azure.resourcemanager.containerregistry.models.AgentPoolUpdateParameters;
import com.azure.core.annotation.*; import com.azure.core.management.polling.*; import com.azure.core.util.*; import com.azure.core.util.polling.*; import com.azure.resourcemanager.containerregistry.fluent.models.*; import com.azure.resourcemanager.containerregistry.models.*;
[ "com.azure.core", "com.azure.resourcemanager" ]
com.azure.core; com.azure.resourcemanager;
1,726,198
public void setReplicating(boolean newState) throws KeeperException { ZKUtil.createWithParents(this.zookeeper, ZKUtil.joinZNode(this.replicationZNode, this.replicationStateNodeName)); ZKUtil.setData(this.zookeeper, ZKUtil.joinZNode(this.replicationZNode, this.replicationStateNodeName), Bytes.toBytes(Boolean.toString(newState))); }
void function(boolean newState) throws KeeperException { ZKUtil.createWithParents(this.zookeeper, ZKUtil.joinZNode(this.replicationZNode, this.replicationStateNodeName)); ZKUtil.setData(this.zookeeper, ZKUtil.joinZNode(this.replicationZNode, this.replicationStateNodeName), Bytes.toBytes(Boolean.toString(newState))); }
/** * Set the new replication state for this cluster * @param newState */
Set the new replication state for this cluster
setReplicating
{ "repo_name": "zqxjjj/NobidaBase", "path": "target/hbase-0.94.9/hbase-0.94.9/src/main/java/org/apache/hadoop/hbase/replication/ReplicationZookeeper.java", "license": "apache-2.0", "size": 34191 }
[ "org.apache.hadoop.hbase.util.Bytes", "org.apache.hadoop.hbase.zookeeper.ZKUtil", "org.apache.zookeeper.KeeperException" ]
import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.zookeeper.KeeperException;
import org.apache.hadoop.hbase.util.*; import org.apache.hadoop.hbase.zookeeper.*; import org.apache.zookeeper.*;
[ "org.apache.hadoop", "org.apache.zookeeper" ]
org.apache.hadoop; org.apache.zookeeper;
1,923,741
public LexiconEntry setLexiconPages(LexiconPage... pages) { this.pages.addAll(Arrays.asList(pages)); for(int i = 0; i < this.pages.size(); i++) { LexiconPage page = this.pages.get(i); if(!page.skipRegistry) page.onPageAdded(this, i); } return this; }
LexiconEntry function(LexiconPage... pages) { this.pages.addAll(Arrays.asList(pages)); for(int i = 0; i < this.pages.size(); i++) { LexiconPage page = this.pages.get(i); if(!page.skipRegistry) page.onPageAdded(this, i); } return this; }
/** * Sets what pages you want this entry to have. */
Sets what pages you want this entry to have
setLexiconPages
{ "repo_name": "Saereth/AstralSorcery", "path": "src/api/java/vazkii/botania/api/lexicon/LexiconEntry.java", "license": "gpl-3.0", "size": 4040 }
[ "java.util.Arrays" ]
import java.util.Arrays;
import java.util.*;
[ "java.util" ]
java.util;
1,252,259
private void updateDescription(TableItem item) { if (item != null) { Object data = item.getData(); if (data instanceof IAndroidTarget) { String newTooltip = ((IAndroidTarget) data).getDescription(); mDescription.setText(newTooltip == null ? "" : newTooltip); //$NON-NLS-1$ } } else { mDescription.setText(""); } }
void function(TableItem item) { if (item != null) { Object data = item.getData(); if (data instanceof IAndroidTarget) { String newTooltip = ((IAndroidTarget) data).getDescription(); mDescription.setText(newTooltip == null ? STR"); } }
/** * Updates the description label */
Updates the description label
updateDescription
{ "repo_name": "rex-xxx/mt6572_x201", "path": "tools/motodev/src/plugins/android/src/com/motorola/studio/android/wizards/elements/SdkTargetSelector.java", "license": "gpl-2.0", "size": 11270 }
[ "com.android.sdklib.IAndroidTarget", "org.eclipse.swt.widgets.TableItem" ]
import com.android.sdklib.IAndroidTarget; import org.eclipse.swt.widgets.TableItem;
import com.android.sdklib.*; import org.eclipse.swt.widgets.*;
[ "com.android.sdklib", "org.eclipse.swt" ]
com.android.sdklib; org.eclipse.swt;
1,714,154
public final void addStagingProcessor(AbstractStagingProcessor pProcessor) { stagingProcessors.add(pProcessor); }
final void function(AbstractStagingProcessor pProcessor) { stagingProcessors.add(pProcessor); }
/** * Add a staging processor. * * @param pProcessor The staging processor to add. */
Add a staging processor
addStagingProcessor
{ "repo_name": "kit-data-manager/base", "path": "Staging/DataTransferClient/src/main/java/edu/kit/dama/transfer/client/impl/AbstractTransferClient.java", "license": "apache-2.0", "size": 44750 }
[ "edu.kit.dama.staging.processor.AbstractStagingProcessor" ]
import edu.kit.dama.staging.processor.AbstractStagingProcessor;
import edu.kit.dama.staging.processor.*;
[ "edu.kit.dama" ]
edu.kit.dama;
2,783,309
public Date getDate(String parameterName) throws SQLException { throw Util.notImplemented(); }
Date function(String parameterName) throws SQLException { throw Util.notImplemented(); }
/** * JDBC 3.0 * * Retrieves the value of a JDBC DATE parameter as ajava.sql.Date object * * @param parameterName - the name of the parameter * @return the parameter value. If the value is SQL NULL, the result is null. * @exception SQLException Feature not implemented for now. */
JDBC 3.0 Retrieves the value of a JDBC DATE parameter as ajava.sql.Date object
getDate
{ "repo_name": "splicemachine/spliceengine", "path": "db-engine/src/main/java/com/splicemachine/db/impl/jdbc/EmbedCallableStatement20.java", "license": "agpl-3.0", "size": 37363 }
[ "java.sql.Date", "java.sql.SQLException" ]
import java.sql.Date; import java.sql.SQLException;
import java.sql.*;
[ "java.sql" ]
java.sql;
1,799,003
public static byte[] gzip(String input) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = null; try { gzos = new GZIPOutputStream(baos); gzos.write(input.getBytes("UTF-8")); } catch (IOException e) { e.printStackTrace(); } finally { if (gzos != null) try { gzos.close(); } catch (IOException ignore) { } } return baos.toByteArray(); }
static byte[] function(String input) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = null; try { gzos = new GZIPOutputStream(baos); gzos.write(input.getBytes("UTF-8")); } catch (IOException e) { e.printStackTrace(); } finally { if (gzos != null) try { gzos.close(); } catch (IOException ignore) { } } return baos.toByteArray(); }
/** * GZip compress a string of bytes * * @param input * @return */
GZip compress a string of bytes
gzip
{ "repo_name": "AydinE/GPTownship", "path": "GPTownship/src/com/OmniTekMC/GPTownship/Metrics.java", "license": "gpl-3.0", "size": 24832 }
[ "java.io.ByteArrayOutputStream", "java.io.IOException", "java.util.zip.GZIPOutputStream" ]
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPOutputStream;
import java.io.*; import java.util.zip.*;
[ "java.io", "java.util" ]
java.io; java.util;
1,926,914
public Dialect getDialect();
Dialect function();
/** * Get the SQL <tt>Dialect</tt> */
Get the SQL Dialect
getDialect
{ "repo_name": "raedle/univis", "path": "lib/hibernate-3.1.3/src/org/hibernate/engine/SessionFactoryImplementor.java", "license": "lgpl-2.1", "size": 5315 }
[ "org.hibernate.dialect.Dialect" ]
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.*;
[ "org.hibernate.dialect" ]
org.hibernate.dialect;
1,286,585
public static Date deserialiseDate(String date) throws ParseException { Date xmlDate = null; if (date != null) { SimpleDateFormat df = CachingDateFormat.getDateOnlyFormat(); xmlDate = df.parse(date); } return xmlDate; }
static Date function(String date) throws ParseException { Date xmlDate = null; if (date != null) { SimpleDateFormat df = CachingDateFormat.getDateOnlyFormat(); xmlDate = df.parse(date); } return xmlDate; }
/** * Convert XML date (of the form yyyy-MM-dd) to Date * * @param date the xml representation of the date * @return the date * @throws ParseException */
Convert XML date (of the form yyyy-MM-dd) to Date
deserialiseDate
{ "repo_name": "fxcebx/community-edition", "path": "projects/data-model/source/java/org/alfresco/repo/dictionary/M2XML.java", "license": "lgpl-3.0", "size": 2653 }
[ "java.text.ParseException", "java.text.SimpleDateFormat", "java.util.Date", "org.alfresco.util.CachingDateFormat" ]
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.alfresco.util.CachingDateFormat;
import java.text.*; import java.util.*; import org.alfresco.util.*;
[ "java.text", "java.util", "org.alfresco.util" ]
java.text; java.util; org.alfresco.util;
882,812
public static AbstractAlignmentJmol display(CeSymmResult symmResult) throws StructureException { if (symmResult.isSignificant() && symmResult.isRefined()) { // Show the structure colored by repeat (do not rotate) MultipleAlignment msa = symmResult.getMultipleAlignment(); List<Atom[]> atoms = msa.getAtomArrays(); // Add non polymer protein groups Atom[] allAtoms = atoms.get(0); List<Group> hetatms = StructureTools.getUnalignedGroups(allAtoms); allAtoms = Arrays .copyOf(allAtoms, allAtoms.length + hetatms.size()); for (int h = 0; h < hetatms.size(); h++) { int index = (allAtoms.length - hetatms.size()) + h; allAtoms[index] = hetatms.get(h).getAtom(0); } for (int s = 0; s < msa.size(); s++) atoms.set(s, allAtoms); MultipleAlignmentJmol jmol = new MultipleAlignmentJmol(msa, atoms); jmol.setTitle(jmol.getStructure().getPDBHeader().getTitle()); addSymmetryMenu(jmol, symmResult); jmol.evalString(printSymmetryGroup(symmResult)); jmol.evalString(printSymmetryAxes(symmResult)); jmol.setTitle(getSymmTitle(symmResult)); jmol.evalString("save STATE state_1"); return jmol; } else { // Show the optimal self-alignment logger.info("Showing optimal self-alignment"); Atom[] cloned = StructureTools .cloneAtomArray(symmResult.getAtoms()); AbstractAlignmentJmol jmol = StructureAlignmentDisplay.display( symmResult.getSelfAlignment(), symmResult.getAtoms(), cloned); RotationAxis axis = new RotationAxis(symmResult.getSelfAlignment()); jmol.evalString(axis.getJmolScript(symmResult.getAtoms())); jmol.evalString("save STATE state_1"); return jmol; } }
static AbstractAlignmentJmol function(CeSymmResult symmResult) throws StructureException { if (symmResult.isSignificant() && symmResult.isRefined()) { MultipleAlignment msa = symmResult.getMultipleAlignment(); List<Atom[]> atoms = msa.getAtomArrays(); Atom[] allAtoms = atoms.get(0); List<Group> hetatms = StructureTools.getUnalignedGroups(allAtoms); allAtoms = Arrays .copyOf(allAtoms, allAtoms.length + hetatms.size()); for (int h = 0; h < hetatms.size(); h++) { int index = (allAtoms.length - hetatms.size()) + h; allAtoms[index] = hetatms.get(h).getAtom(0); } for (int s = 0; s < msa.size(); s++) atoms.set(s, allAtoms); MultipleAlignmentJmol jmol = new MultipleAlignmentJmol(msa, atoms); jmol.setTitle(jmol.getStructure().getPDBHeader().getTitle()); addSymmetryMenu(jmol, symmResult); jmol.evalString(printSymmetryGroup(symmResult)); jmol.evalString(printSymmetryAxes(symmResult)); jmol.setTitle(getSymmTitle(symmResult)); jmol.evalString(STR); return jmol; } else { logger.info(STR); Atom[] cloned = StructureTools .cloneAtomArray(symmResult.getAtoms()); AbstractAlignmentJmol jmol = StructureAlignmentDisplay.display( symmResult.getSelfAlignment(), symmResult.getAtoms(), cloned); RotationAxis axis = new RotationAxis(symmResult.getSelfAlignment()); jmol.evalString(axis.getJmolScript(symmResult.getAtoms())); jmol.evalString(STR); return jmol; } }
/** * Displays a single structure in a cartoon representation with each * symmetric repeat colored differently. * * @param msa * the symmetry multiple alignment obtained from CeSymm * @throws StructureException */
Displays a single structure in a cartoon representation with each symmetric repeat colored differently
display
{ "repo_name": "pwrose/biojava", "path": "biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryDisplay.java", "license": "lgpl-2.1", "size": 9742 }
[ "java.util.Arrays", "java.util.List", "org.biojava.nbio.structure.Atom", "org.biojava.nbio.structure.Group", "org.biojava.nbio.structure.StructureException", "org.biojava.nbio.structure.StructureTools", "org.biojava.nbio.structure.align.gui.StructureAlignmentDisplay", "org.biojava.nbio.structure.align.gui.jmol.AbstractAlignmentJmol", "org.biojava.nbio.structure.align.gui.jmol.MultipleAlignmentJmol", "org.biojava.nbio.structure.align.multiple.MultipleAlignment", "org.biojava.nbio.structure.align.util.RotationAxis", "org.biojava.nbio.structure.symmetry.internal.CeSymmResult" ]
import java.util.Arrays; import java.util.List; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.gui.StructureAlignmentDisplay; import org.biojava.nbio.structure.align.gui.jmol.AbstractAlignmentJmol; import org.biojava.nbio.structure.align.gui.jmol.MultipleAlignmentJmol; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; import org.biojava.nbio.structure.align.util.RotationAxis; import org.biojava.nbio.structure.symmetry.internal.CeSymmResult;
import java.util.*; import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.gui.*; import org.biojava.nbio.structure.align.gui.jmol.*; import org.biojava.nbio.structure.align.multiple.*; import org.biojava.nbio.structure.align.util.*; import org.biojava.nbio.structure.symmetry.internal.*;
[ "java.util", "org.biojava.nbio" ]
java.util; org.biojava.nbio;
1,867,540
protected String findObjectAsLiteral(Resource s, URI p) throws RepositoryException { return findObject(s, p).stringValue(); }
String function(Resource s, URI p) throws RepositoryException { return findObject(s, p).stringValue(); }
/** * Finds the literal object matching the pattern <code>(s p _)</code>, asserts to find * exactly one result. * * @param s subject. * @param p predicate. * @return matching object. * @throws RepositoryException */
Finds the literal object matching the pattern <code>(s p _)</code>, asserts to find exactly one result
findObjectAsLiteral
{ "repo_name": "venukb/any23", "path": "any23-core/src/test/java/org/deri/any23/extractor/html/AbstractExtractorTestCase.java", "license": "apache-2.0", "size": 22853 }
[ "org.openrdf.model.Resource", "org.openrdf.repository.RepositoryException" ]
import org.openrdf.model.Resource; import org.openrdf.repository.RepositoryException;
import org.openrdf.model.*; import org.openrdf.repository.*;
[ "org.openrdf.model", "org.openrdf.repository" ]
org.openrdf.model; org.openrdf.repository;
274,408
TreeItem root = new TreeItem<>(dir); root.setValue(dir); if (parent == null) { root.setExpanded(true); } else { root.setExpanded(false); } File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { populateTree(file, root); } else { TreeItem item = new TreeItem<>(file); item.setValue(file); root.getChildren().add(item); } } if(parent == null){ treeView.setRoot(root); } else { parent.getChildren().add(root); } }
TreeItem root = new TreeItem<>(dir); root.setValue(dir); if (parent == null) { root.setExpanded(true); } else { root.setExpanded(false); } File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { populateTree(file, root); } else { TreeItem item = new TreeItem<>(file); item.setValue(file); root.getChildren().add(item); } } if(parent == null){ treeView.setRoot(root); } else { parent.getChildren().add(root); } }
/** * Create file tree * @param dir * @param parent */
Create file tree
populateTree
{ "repo_name": "Levis92/proton-text", "path": "src/main/java/edu/chl/proton/control/FileTree.java", "license": "agpl-3.0", "size": 2574 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
687,339
static <T> Set<T> toSet(Stream<T> stream) { return stream.collect(Collectors.toSet()); }
static <T> Set<T> toSet(Stream<T> stream) { return stream.collect(Collectors.toSet()); }
/** * Collect a Stream into a Set. */
Collect a Stream into a Set
toSet
{ "repo_name": "stephenh/jOOL", "path": "src/main/java/org/jooq/lambda/Seq.java", "license": "apache-2.0", "size": 198501 }
[ "java.util.Set", "java.util.stream.Collectors", "java.util.stream.Stream" ]
import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream;
import java.util.*; import java.util.stream.*;
[ "java.util" ]
java.util;
424,326
public IBlockState withRotation(IBlockState state, Rotation rot) { return state.getValue(HALF) != BlockDoor.EnumDoorHalf.LOWER ? state : state.withProperty(FACING, rot.rotate((EnumFacing)state.getValue(FACING))); }
IBlockState function(IBlockState state, Rotation rot) { return state.getValue(HALF) != BlockDoor.EnumDoorHalf.LOWER ? state : state.withProperty(FACING, rot.rotate((EnumFacing)state.getValue(FACING))); }
/** * Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed * blockstate. */
Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed blockstate
withRotation
{ "repo_name": "danielyc/test-1.9.4", "path": "build/tmp/recompileMc/sources/net/minecraft/block/BlockDoor.java", "license": "gpl-3.0", "size": 17104 }
[ "net.minecraft.block.state.IBlockState", "net.minecraft.util.EnumFacing", "net.minecraft.util.Rotation" ]
import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.Rotation;
import net.minecraft.block.state.*; import net.minecraft.util.*;
[ "net.minecraft.block", "net.minecraft.util" ]
net.minecraft.block; net.minecraft.util;
801,496
public static boolean exists() { Session session = ThreadContext.getSession(); if (session == null) { // no session is available via ThreadContext, so lookup in session store RequestCycle requestCycle = RequestCycle.get(); if (requestCycle != null) { session = Application.get().getSessionStore().lookup(requestCycle.getRequest()); if (session != null) { ThreadContext.setSession(session); } } } return session != null; }
static boolean function() { Session session = ThreadContext.getSession(); if (session == null) { RequestCycle requestCycle = RequestCycle.get(); if (requestCycle != null) { session = Application.get().getSessionStore().lookup(requestCycle.getRequest()); if (session != null) { ThreadContext.setSession(session); } } } return session != null; }
/** * Checks existence of a <code>Session</code> associated with the current thread. * * @return {@code true} if {@link Session#get()} can return the instance of session, * {@code false} otherwise */
Checks existence of a <code>Session</code> associated with the current thread
exists
{ "repo_name": "klopfdreh/wicket", "path": "wicket-core/src/main/java/org/apache/wicket/Session.java", "license": "apache-2.0", "size": 26282 }
[ "org.apache.wicket.request.cycle.RequestCycle" ]
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.cycle.*;
[ "org.apache.wicket" ]
org.apache.wicket;
951,663
@Generated @Selector("initWithDevice:") public native MPSNNSlice initWithDevice(@Mapped(ObjCObjectMapper.class) Object device);
@Selector(STR) native MPSNNSlice function(@Mapped(ObjCObjectMapper.class) Object device);
/** * Initialize a MPSNNSlice kernel * * @param device The device the filter will run on * @return A valid MPSNNSlice object or nil, if failure. */
Initialize a MPSNNSlice kernel
initWithDevice
{ "repo_name": "multi-os-engine/moe-core", "path": "moe.apple/moe.platform.ios/src/main/java/apple/metalperformanceshaders/MPSNNSlice.java", "license": "apache-2.0", "size": 6201 }
[ "org.moe.natj.general.ann.Mapped", "org.moe.natj.objc.ann.Selector", "org.moe.natj.objc.map.ObjCObjectMapper" ]
import org.moe.natj.general.ann.Mapped; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper;
import org.moe.natj.general.ann.*; import org.moe.natj.objc.ann.*; import org.moe.natj.objc.map.*;
[ "org.moe.natj" ]
org.moe.natj;
1,919,947
private String generateNewCookieId() { final byte[] keyBytes = new byte[30]; this.secureRandom.nextBytes(keyBytes); return Base64.encodeBase64URLSafeString(keyBytes); }
String function() { final byte[] keyBytes = new byte[30]; this.secureRandom.nextBytes(keyBytes); return Base64.encodeBase64URLSafeString(keyBytes); }
/** * Generates a 40 character unique value. * * @return */
Generates a 40 character unique value
generateNewCookieId
{ "repo_name": "GIP-RECIA/esco-portail", "path": "uPortal-web/src/main/java/org/apereo/portal/portlet/dao/jpa/JpaPortletCookieDaoImpl.java", "license": "apache-2.0", "size": 10993 }
[ "org.apache.commons.codec.binary.Base64" ]
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.*;
[ "org.apache.commons" ]
org.apache.commons;
1,102,369
public final class SetNotificationDestinationExtendedRequestTestCase extends LDAPSDKTestCase { @Test() public void testWithoutControls() throws Exception { SetNotificationDestinationExtendedRequest r = new SetNotificationDestinationExtendedRequest("test-manager-id", "test-dest-id", new ASN1OctetString("dest-detail-1")); r = new SetNotificationDestinationExtendedRequest(r); r = r.duplicate(); assertNotNull(r.getManagerID()); assertEquals(r.getManagerID(), "test-manager-id"); assertNotNull(r.getDestinationID()); assertEquals(r.getDestinationID(), "test-dest-id"); assertNotNull(r.getDestinationDetails()); assertFalse(r.getDestinationDetails().isEmpty()); assertEquals(r.getDestinationDetails().size(), 1); assertNotNull(r.getChangeType()); assertEquals(r.getChangeType(), SetNotificationDestinationChangeType.REPLACE); assertNotNull(r.getControls()); assertEquals(r.getControls().length, 0); assertNotNull(r.getExtendedRequestName()); assertNotNull(r.toString()); }
final class SetNotificationDestinationExtendedRequestTestCase extends LDAPSDKTestCase { @Test() public void function() throws Exception { SetNotificationDestinationExtendedRequest r = new SetNotificationDestinationExtendedRequest(STR, STR, new ASN1OctetString(STR)); r = new SetNotificationDestinationExtendedRequest(r); r = r.duplicate(); assertNotNull(r.getManagerID()); assertEquals(r.getManagerID(), STR); assertNotNull(r.getDestinationID()); assertEquals(r.getDestinationID(), STR); assertNotNull(r.getDestinationDetails()); assertFalse(r.getDestinationDetails().isEmpty()); assertEquals(r.getDestinationDetails().size(), 1); assertNotNull(r.getChangeType()); assertEquals(r.getChangeType(), SetNotificationDestinationChangeType.REPLACE); assertNotNull(r.getControls()); assertEquals(r.getControls().length, 0); assertNotNull(r.getExtendedRequestName()); assertNotNull(r.toString()); }
/** * Provides basic coverage for the extended request without any controls. * * @throws Exception If an unexpected problem occurs. */
Provides basic coverage for the extended request without any controls
testWithoutControls
{ "repo_name": "UnboundID/ldapsdk", "path": "tests/unit/src/com/unboundid/ldap/sdk/unboundidds/extensions/SetNotificationDestinationExtendedRequestTestCase.java", "license": "gpl-2.0", "size": 9967 }
[ "com.unboundid.asn1.ASN1OctetString", "com.unboundid.ldap.sdk.LDAPSDKTestCase", "org.testng.annotations.Test" ]
import com.unboundid.asn1.ASN1OctetString; import com.unboundid.ldap.sdk.LDAPSDKTestCase; import org.testng.annotations.Test;
import com.unboundid.asn1.*; import com.unboundid.ldap.sdk.*; import org.testng.annotations.*;
[ "com.unboundid.asn1", "com.unboundid.ldap", "org.testng.annotations" ]
com.unboundid.asn1; com.unboundid.ldap; org.testng.annotations;
413,863
public ServerInstanceList buildLogicalServer(final AgentHistogramList hostHistogram) { ServerInstanceList serverInstanceList = new ServerInstanceList(); for (AgentHistogram agentHistogram : hostHistogram.getAgentHistogramList()) { final String instanceName = agentHistogram.getId(); final String hostName = getHostName(agentHistogram.getId()); final ServiceType serviceType = agentHistogram.getServiceType(); final ServerInstance serverInstance = new ServerInstance(hostName, instanceName, serviceType.getCode()); serverInstanceList.addServerInstance(serverInstance); } return serverInstanceList; }
ServerInstanceList function(final AgentHistogramList hostHistogram) { ServerInstanceList serverInstanceList = new ServerInstanceList(); for (AgentHistogram agentHistogram : hostHistogram.getAgentHistogramList()) { final String instanceName = agentHistogram.getId(); final String hostName = getHostName(agentHistogram.getId()); final ServiceType serviceType = agentHistogram.getServiceType(); final ServerInstance serverInstance = new ServerInstance(hostName, instanceName, serviceType.getCode()); serverInstanceList.addServerInstance(serverInstance); } return serverInstanceList; }
/** * filled with application information of physical server and service instance * * @param hostHistogram */
filled with application information of physical server and service instance
buildLogicalServer
{ "repo_name": "dawidmalina/pinpoint", "path": "web/src/main/java/com/navercorp/pinpoint/web/applicationmap/ServerBuilder.java", "license": "apache-2.0", "size": 4018 }
[ "com.navercorp.pinpoint.common.trace.ServiceType", "com.navercorp.pinpoint.web.applicationmap.rawdata.AgentHistogram", "com.navercorp.pinpoint.web.applicationmap.rawdata.AgentHistogramList" ]
import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.web.applicationmap.rawdata.AgentHistogram; import com.navercorp.pinpoint.web.applicationmap.rawdata.AgentHistogramList;
import com.navercorp.pinpoint.common.trace.*; import com.navercorp.pinpoint.web.applicationmap.rawdata.*;
[ "com.navercorp.pinpoint" ]
com.navercorp.pinpoint;
2,602,049
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DistributionTypeEditForm myForm = (DistributionTypeEditForm) form; sessionContext.checkPermission(Right.DistributionTypeEdit); // Read operation to be performed String op = (myForm.getOp()!=null?myForm.getOp():request.getParameter("op")); Long sessionId = sessionContext.getUser().getCurrentAcademicSessionId(); if (op==null) { Long id = Long.valueOf(Long.parseLong(request.getParameter("id"))); myForm.setRefTableEntry((new DistributionTypeDAO()).get(id), sessionId); } if (request.getParameterValues("depts")!=null) { String[] depts = request.getParameterValues("depts"); for (int i=0;i<depts.length;i++) myForm.getDepartmentIds().add(Long.valueOf(depts[i])); } List list = (new DepartmentDAO()).getSession() .createCriteria(Department.class) .add(Restrictions.eq("session.uniqueId", sessionId)) .addOrder(Order.asc("deptCode")) .list(); Vector availableDepts = new Vector(); for (Iterator iter = list.iterator();iter.hasNext();) { Department d = (Department) iter.next(); availableDepts.add(new LabelValueBean(d.getDeptCode() + "-" + d.getName(), d.getUniqueId().toString())); } request.setAttribute(Department.DEPT_ATTR_NAME, availableDepts); if ("Save".equals(op)) { DistributionTypeDAO dao = new DistributionTypeDAO(); Transaction tx = null; try { org.hibernate.Session hibSession = dao.getSession(); if (hibSession.getTransaction()==null || !hibSession.getTransaction().isActive()) tx = hibSession.beginTransaction(); DistributionType distType = dao.get(myForm.getUniqueId()); DistributionType x = (DistributionType) myForm.getRefTableEntry(); distType.setAbbreviation(x.getAbbreviation()); distType.setAllowedPref(x.getAllowedPref()); distType.setDescr(x.getDescr()); distType.setInstructorPref(x.isInstructorPref()==null?Boolean.FALSE:x.isInstructorPref()); distType.setLabel(x.getLabel()); distType.setVisible(x.isVisible() == null ? Boolean.FALSE : x.isVisible()); HashSet oldDepts = new HashSet(distType.getDepartments()); for (Enumeration e=myForm.getDepartmentIds().elements();e.hasMoreElements();) { Long departmentId = (Long)e.nextElement(); Department d = (new DepartmentDAO()).get(departmentId,hibSession); if (d==null) continue; if (oldDepts.remove(d)) { //not changed -> do nothing } else { distType.getDepartments().add(d); } } for (Iterator i=oldDepts.iterator();i.hasNext();) { Department d = (Department)i.next(); if (!d.getSessionId().equals(sessionId)) continue; distType.getDepartments().remove(d); } hibSession.saveOrUpdate(distType); ChangeLog.addChange( hibSession, sessionContext, distType, ChangeLog.Source.DIST_TYPE_EDIT, ChangeLog.Operation.UPDATE, null, null); if (tx!=null) tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } return mapping.findForward("showDistributionTypeList"); } if ("Back".equals(op)) { return mapping.findForward("showDistributionTypeList"); } if ("Add Department".equals(op)) { ActionMessages errors = new ActionErrors(); if (myForm.getDepartmentId()==null || myForm.getDepartmentId().longValue()<0) errors.add("department", new ActionMessage("errors.generic", "No department selected.")); else { boolean contains = myForm.getDepartmentIds().contains(myForm.getDepartmentId()); if (contains) errors.add("department", new ActionMessage("errors.generic", "Department already present in the list of departments.")); } if(errors.size()>0) { saveErrors(request, errors); } else { myForm.getDepartmentIds().add(myForm.getDepartmentId()); } } if ("Remove Department".equals(op)) { ActionMessages errors = new ActionErrors(); if (myForm.getDepartmentId()==null || myForm.getDepartmentId().longValue()<0) errors.add("department", new ActionMessage("errors.generic", "No department selected.")); else { boolean contains = myForm.getDepartmentIds().contains(myForm.getDepartmentId()); if (!contains) errors.add("department", new ActionMessage("errors.generic", "Department not present in the list of departments.")); } if(errors.size()>0) { saveErrors(request, errors); } else { myForm.getDepartmentIds().remove(myForm.getDepartmentId()); } } return mapping.findForward("showEdit"); }
ActionForward function( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DistributionTypeEditForm myForm = (DistributionTypeEditForm) form; sessionContext.checkPermission(Right.DistributionTypeEdit); String op = (myForm.getOp()!=null?myForm.getOp():request.getParameter("op")); Long sessionId = sessionContext.getUser().getCurrentAcademicSessionId(); if (op==null) { Long id = Long.valueOf(Long.parseLong(request.getParameter("id"))); myForm.setRefTableEntry((new DistributionTypeDAO()).get(id), sessionId); } if (request.getParameterValues("depts")!=null) { String[] depts = request.getParameterValues("depts"); for (int i=0;i<depts.length;i++) myForm.getDepartmentIds().add(Long.valueOf(depts[i])); } List list = (new DepartmentDAO()).getSession() .createCriteria(Department.class) .add(Restrictions.eq(STR, sessionId)) .addOrder(Order.asc(STR)) .list(); Vector availableDepts = new Vector(); for (Iterator iter = list.iterator();iter.hasNext();) { Department d = (Department) iter.next(); availableDepts.add(new LabelValueBean(d.getDeptCode() + "-" + d.getName(), d.getUniqueId().toString())); } request.setAttribute(Department.DEPT_ATTR_NAME, availableDepts); if ("Save".equals(op)) { DistributionTypeDAO dao = new DistributionTypeDAO(); Transaction tx = null; try { org.hibernate.Session hibSession = dao.getSession(); if (hibSession.getTransaction()==null !hibSession.getTransaction().isActive()) tx = hibSession.beginTransaction(); DistributionType distType = dao.get(myForm.getUniqueId()); DistributionType x = (DistributionType) myForm.getRefTableEntry(); distType.setAbbreviation(x.getAbbreviation()); distType.setAllowedPref(x.getAllowedPref()); distType.setDescr(x.getDescr()); distType.setInstructorPref(x.isInstructorPref()==null?Boolean.FALSE:x.isInstructorPref()); distType.setLabel(x.getLabel()); distType.setVisible(x.isVisible() == null ? Boolean.FALSE : x.isVisible()); HashSet oldDepts = new HashSet(distType.getDepartments()); for (Enumeration e=myForm.getDepartmentIds().elements();e.hasMoreElements();) { Long departmentId = (Long)e.nextElement(); Department d = (new DepartmentDAO()).get(departmentId,hibSession); if (d==null) continue; if (oldDepts.remove(d)) { } else { distType.getDepartments().add(d); } } for (Iterator i=oldDepts.iterator();i.hasNext();) { Department d = (Department)i.next(); if (!d.getSessionId().equals(sessionId)) continue; distType.getDepartments().remove(d); } hibSession.saveOrUpdate(distType); ChangeLog.addChange( hibSession, sessionContext, distType, ChangeLog.Source.DIST_TYPE_EDIT, ChangeLog.Operation.UPDATE, null, null); if (tx!=null) tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } return mapping.findForward(STR); } if ("Back".equals(op)) { return mapping.findForward(STR); } if (STR.equals(op)) { ActionMessages errors = new ActionErrors(); if (myForm.getDepartmentId()==null myForm.getDepartmentId().longValue()<0) errors.add(STR, new ActionMessage(STR, STR)); else { boolean contains = myForm.getDepartmentIds().contains(myForm.getDepartmentId()); if (contains) errors.add(STR, new ActionMessage(STR, STR)); } if(errors.size()>0) { saveErrors(request, errors); } else { myForm.getDepartmentIds().add(myForm.getDepartmentId()); } } if (STR.equals(op)) { ActionMessages errors = new ActionErrors(); if (myForm.getDepartmentId()==null myForm.getDepartmentId().longValue()<0) errors.add(STR, new ActionMessage(STR, STR)); else { boolean contains = myForm.getDepartmentIds().contains(myForm.getDepartmentId()); if (!contains) errors.add(STR, new ActionMessage(STR, STR)); } if(errors.size()>0) { saveErrors(request, errors); } else { myForm.getDepartmentIds().remove(myForm.getDepartmentId()); } } return mapping.findForward(STR); }
/** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws HibernateException */
Method execute
execute
{ "repo_name": "UniTime/unitime", "path": "JavaSource/org/unitime/timetable/action/DistributionTypeEditAction.java", "license": "apache-2.0", "size": 8561 }
[ "java.util.Enumeration", "java.util.HashSet", "java.util.Iterator", "java.util.List", "java.util.Vector", "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse", "org.apache.struts.action.ActionErrors", "org.apache.struts.action.ActionForm", "org.apache.struts.action.ActionForward", "org.apache.struts.action.ActionMapping", "org.apache.struts.action.ActionMessage", "org.apache.struts.action.ActionMessages", "org.apache.struts.util.LabelValueBean", "org.hibernate.Transaction", "org.hibernate.criterion.Order", "org.hibernate.criterion.Restrictions", "org.unitime.timetable.form.DistributionTypeEditForm", "org.unitime.timetable.model.ChangeLog", "org.unitime.timetable.model.Department", "org.unitime.timetable.model.DistributionType", "org.unitime.timetable.model.dao.DepartmentDAO", "org.unitime.timetable.model.dao.DistributionTypeDAO", "org.unitime.timetable.security.rights.Right" ]
import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.util.LabelValueBean; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.unitime.timetable.form.DistributionTypeEditForm; import org.unitime.timetable.model.ChangeLog; import org.unitime.timetable.model.Department; import org.unitime.timetable.model.DistributionType; import org.unitime.timetable.model.dao.DepartmentDAO; import org.unitime.timetable.model.dao.DistributionTypeDAO; import org.unitime.timetable.security.rights.Right;
import java.util.*; import javax.servlet.http.*; import org.apache.struts.action.*; import org.apache.struts.util.*; import org.hibernate.*; import org.hibernate.criterion.*; import org.unitime.timetable.form.*; import org.unitime.timetable.model.*; import org.unitime.timetable.model.dao.*; import org.unitime.timetable.security.rights.*;
[ "java.util", "javax.servlet", "org.apache.struts", "org.hibernate", "org.hibernate.criterion", "org.unitime.timetable" ]
java.util; javax.servlet; org.apache.struts; org.hibernate; org.hibernate.criterion; org.unitime.timetable;
1,599,878
@Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "information_date" ) public LocalDateTime getInformationDate() { return this.informationDate; }
@Type(type=STR) @Basic( optional = true ) @Column( name = STR ) LocalDateTime function() { return this.informationDate; }
/** * Return the value associated with the column: informationDate. * @return A LocalDateTime object (this.informationDate) */
Return the value associated with the column: informationDate
getInformationDate
{ "repo_name": "servinglynk/hmis-lynk-open-source", "path": "hmis-model-v2014/src/main/java/com/servinglynk/hmis/warehouse/model/v2014/EnrollmentCoc.java", "license": "mpl-2.0", "size": 9404 }
[ "java.time.LocalDateTime", "javax.persistence.Basic", "javax.persistence.Column", "org.hibernate.annotations.Type" ]
import java.time.LocalDateTime; import javax.persistence.Basic; import javax.persistence.Column; import org.hibernate.annotations.Type;
import java.time.*; import javax.persistence.*; import org.hibernate.annotations.*;
[ "java.time", "javax.persistence", "org.hibernate.annotations" ]
java.time; javax.persistence; org.hibernate.annotations;
46,444
public void registerBatchContainerOverrideProperties(Properties properties) { logger.finer("Overriding properties file based config with programmatic config using properties: "+ properties); this.overrideProperties.putAll(properties); } private final byte[] databaseConfigurationCompleteLock = new byte[0]; private Boolean databaseConfigurationComplete = Boolean.FALSE; private DatabaseConfigurationBean dataBaseConfigurationBean = null;
void function(Properties properties) { logger.finer(STR+ properties); this.overrideProperties.putAll(properties); } private final byte[] databaseConfigurationCompleteLock = new byte[0]; private Boolean databaseConfigurationComplete = Boolean.FALSE; private DatabaseConfigurationBean dataBaseConfigurationBean = null;
/** * Override container properties read from META-INF * @param properties The {@link Properties} to use as overrides. */
Override container properties read from META-INF
registerBatchContainerOverrideProperties
{ "repo_name": "WASdev/standards.jsr352.jbatch", "path": "com.ibm.jbatch.spi/src/main/java/com/ibm/jbatch/spi/BatchSPIManager.java", "license": "apache-2.0", "size": 7701 }
[ "java.util.Properties" ]
import java.util.Properties;
import java.util.*;
[ "java.util" ]
java.util;
2,641,240
public static void exportRemote(Map<String, String> properties) { final int index = counter.getAndIncrement(); Perf perf = Perf.getPerf(); for (Map.Entry<String, String> entry : properties.entrySet()) { perf.createString(REMOTE_CONNECTOR_COUNTER_PREFIX + index + "." + entry.getKey(), 1, Units.STRING.intValue(), entry.getValue()); } }
static void function(Map<String, String> properties) { final int index = counter.getAndIncrement(); Perf perf = Perf.getPerf(); for (Map.Entry<String, String> entry : properties.entrySet()) { perf.createString(REMOTE_CONNECTOR_COUNTER_PREFIX + index + "." + entry.getKey(), 1, Units.STRING.intValue(), entry.getValue()); } }
/** * Exports the specified remote connector address and associated * configuration properties to the instrumentation buffer so that * it can be read by this or other Java virtual machines running * on the same system. * * @param properties The remote connector address properties. */
Exports the specified remote connector address and associated configuration properties to the instrumentation buffer so that it can be read by this or other Java virtual machines running on the same system
exportRemote
{ "repo_name": "openjdk/jdk7u", "path": "jdk/src/share/classes/sun/management/ConnectorAddressLink.java", "license": "gpl-2.0", "size": 7096 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,305,114
public static final void setDefaultTimeZoneNames(Map<String, DateTimeZone> names) { cZoneNames.set(Collections.unmodifiableMap(new HashMap<String, DateTimeZone>(names))); }
static final void function(Map<String, DateTimeZone> names) { cZoneNames.set(Collections.unmodifiableMap(new HashMap<String, DateTimeZone>(names))); }
/** * Sets the default map of time zone names. * <p> * The map is copied before storage. * * @param names the map of abbreviations to zones, not null * @since 2.2 */
Sets the default map of time zone names. The map is copied before storage
setDefaultTimeZoneNames
{ "repo_name": "Guardiola31337/joda-time", "path": "src/main/java/org/joda/time/DateTimeUtils.java", "license": "apache-2.0", "size": 22510 }
[ "java.util.Collections", "java.util.HashMap", "java.util.Map" ]
import java.util.Collections; import java.util.HashMap; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
1,754,132
@Override public void start(BundleContext bc) throws Exception { context = bc; logger.debug("Swegon ventilation binding has been started."); }
void function(BundleContext bc) throws Exception { context = bc; logger.debug(STR); }
/** * Called whenever the OSGi framework starts our bundle */
Called whenever the OSGi framework starts our bundle
start
{ "repo_name": "computergeek1507/openhab", "path": "bundles/binding/org.openhab.binding.swegonventilation/src/main/java/org/openhab/binding/swegonventilation/internal/SwegonVentilationActivator.java", "license": "epl-1.0", "size": 1579 }
[ "org.osgi.framework.BundleContext" ]
import org.osgi.framework.BundleContext;
import org.osgi.framework.*;
[ "org.osgi.framework" ]
org.osgi.framework;
2,901,961
void notifyAllAnimationsFinished(Item frontInfoBar); } public interface InfoBarContainerObserver { /** * Called when an {@link InfoBar} is about to be added (before the animation). * @param container The notifying {@link InfoBarContainer}
void notifyAllAnimationsFinished(Item frontInfoBar); } public interface InfoBarContainerObserver { /** * Called when an {@link InfoBar} is about to be added (before the animation). * @param container The notifying {@link InfoBarContainer}
/** * Notifies the subscriber when all animations are finished. * @param frontInfoBar The frontmost infobar or {@code null} if none are showing. */
Notifies the subscriber when all animations are finished
notifyAllAnimationsFinished
{ "repo_name": "mogoweb/365browser", "path": "app/src/main/java/org/chromium/chrome/browser/infobar/InfoBarContainer.java", "license": "apache-2.0", "size": 15317 }
[ "org.chromium.chrome.browser.infobar.InfoBarContainerLayout" ]
import org.chromium.chrome.browser.infobar.InfoBarContainerLayout;
import org.chromium.chrome.browser.infobar.*;
[ "org.chromium.chrome" ]
org.chromium.chrome;
2,458,122
public String[] getStrings(String name, String... defaultValue) { String valueString = get(name); if (valueString == null) { return defaultValue; } else { return StringUtils.getStrings(valueString); } }
String[] function(String name, String... defaultValue) { String valueString = get(name); if (valueString == null) { return defaultValue; } else { return StringUtils.getStrings(valueString); } }
/** * Get the comma delimited values of the <code>name</code> property as an * array of <code>String</code>s. If no such property is specified then * default value is returned. * * @param name * property name. * @param defaultValue * The default value * @return property value as an array of <code>String</code>s, or default * value. */
Get the comma delimited values of the <code>name</code> property as an array of <code>String</code>s. If no such property is specified then default value is returned
getStrings
{ "repo_name": "dongpf/hadoop-0.19.1", "path": "src/core/org/apache/hadoop/conf/Configuration.java", "license": "apache-2.0", "size": 43785 }
[ "org.apache.hadoop.util.StringUtils" ]
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
1,981,283
private boolean requiereBackup(String evento) { boolean requiere = false; try { String sql = "SELECT " + evento + " , backup_ruta FROM empresa"; CachedRowSet data; data = db.sqlDatos(sql); while (data.next()) { requiere = data.getBoolean(evento); if (requiere) { System.setProperty("backup_ruta", data.getString("backup_ruta")); } } } catch (SQLException ex) { Logger.getLogger(Utilidades.class.getName()).log(Level.SEVERE, "Error consultado si requiere backup", ex); } return requiere; }
boolean function(String evento) { boolean requiere = false; try { String sql = STR + evento + STR; CachedRowSet data; data = db.sqlDatos(sql); while (data.next()) { requiere = data.getBoolean(evento); if (requiere) { System.setProperty(STR, data.getString(STR)); } } } catch (SQLException ex) { Logger.getLogger(Utilidades.class.getName()).log(Level.SEVERE, STR, ex); } return requiere; }
/** * Verifica si de acuerdo al evento parametrizado se debe o no ejecutar * copias de seguridad. * * @param evento backup_sesion|backup_abrircaja|backup_cierrecaja * @return respuesta booleana */
Verifica si de acuerdo al evento parametrizado se debe o no ejecutar copias de seguridad
requiereBackup
{ "repo_name": "camilozuluaga/softGYM", "path": "src/logica/Utilidades.java", "license": "gpl-3.0", "size": 33510 }
[ "java.sql.SQLException", "java.util.logging.Level", "java.util.logging.Logger", "javax.sql.rowset.CachedRowSet" ]
import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.sql.rowset.CachedRowSet;
import java.sql.*; import java.util.logging.*; import javax.sql.rowset.*;
[ "java.sql", "java.util", "javax.sql" ]
java.sql; java.util; javax.sql;
458,735
Map<String, Object> getCapabilities();
Map<String, Object> getCapabilities();
/** * Describe the current webdriver session's capabilities. */
Describe the current webdriver session's capabilities
getCapabilities
{ "repo_name": "twalpole/selenium", "path": "java/server/src/org/openqa/selenium/grid/session/ActiveSession.java", "license": "apache-2.0", "size": 1433 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
1,793,598
private String createCheckLayersRequest(List<Long> ids, Long organizationId) { StringBuilder sb = new StringBuilder(); //This condition counts the existing layers count matches the count on the layers that were passed as arguments sb.append("select count(*) from "); sb.append(Constants.LAYER_TABLE_NAME); sb.append(" where "); sb.append(Constants.ID); sb.append(" IN ("); for(int i = 0; i < ids.size(); i++) { if(i != 0) { sb.append(","); } sb.append(ids.get(i)); } sb.append(")"); sb.append(" AND "); sb.append(Constants.ID); sb.append(" IN ("); //This condition checks that the id count only matches layers belonging to the same groupLayer organization // select lyrT.id // from gscdatacatalogue.gsc_001_organization orgT // inner join gscdatacatalogue.gsc_006_datasource dsT // on orgT.id = CAST((dsT.json->>'organization') AS integer) // inner join gscdatacatalogue.gsc_007_dataset dstT // on dsT.id = CAST((dstT.json->>'iddatasource') AS integer) // inner join gscdatacatalogue.gsc_008_layer lyrT // on dstT.id = CAST((lyrT.json->>'iddataset') AS integer) // where orgT.id = THIS_GROUP_ORGANIZATIONID sb.append("select lyrT.id from "); sb.append(Constants.ORGANIZATION_TABLE_NAME); sb.append(" orgT inner join "); sb.append(Constants.DATASOURCE_TABLE_NAME); sb.append(" dsT on orgT.id = CAST((dsT.json->>'organization') AS integer) inner join "); sb.append(Constants.DATASETS_TABLE_NAME); sb.append(" dstT on dsT.id = CAST((dstT.json->>'iddatasource') AS integer) inner join "); sb.append(Constants.LAYER_TABLE_NAME); sb.append(" lyrT on dstT.id = CAST((lyrT.json->>'iddataset') AS integer) "); sb.append(" where orgT.id = "); sb.append(organizationId); sb.append(")"); return sb.toString(); }
String function(List<Long> ids, Long organizationId) { StringBuilder sb = new StringBuilder(); sb.append(STR); sb.append(Constants.LAYER_TABLE_NAME); sb.append(STR); sb.append(Constants.ID); sb.append(STR); for(int i = 0; i < ids.size(); i++) { if(i != 0) { sb.append(","); } sb.append(ids.get(i)); } sb.append(")"); sb.append(STR); sb.append(Constants.ID); sb.append(STR); sb.append(STR); sb.append(Constants.ORGANIZATION_TABLE_NAME); sb.append(STR); sb.append(Constants.DATASOURCE_TABLE_NAME); sb.append(STR); sb.append(Constants.DATASETS_TABLE_NAME); sb.append(STR); sb.append(Constants.LAYER_TABLE_NAME); sb.append(STR); sb.append(STR); sb.append(organizationId); sb.append(")"); return sb.toString(); }
/** * Creates a query which * Checks that the layers to be added exist and belong to the same organization as the layerGroup thay are being added to * * @param ids * @param organizationId * @return */
Creates a query which Checks that the layers to be added exist and belong to the same organization as the layerGroup thay are being added to
createCheckLayersRequest
{ "repo_name": "GeoSmartCity-CIP/gsc-datacatalogue", "path": "server/src/main/java/it/sinergis/datacatalogue/services/GroupLayersService.java", "license": "mit", "size": 21413 }
[ "it.sinergis.datacatalogue.common.Constants", "java.util.List" ]
import it.sinergis.datacatalogue.common.Constants; import java.util.List;
import it.sinergis.datacatalogue.common.*; import java.util.*;
[ "it.sinergis.datacatalogue", "java.util" ]
it.sinergis.datacatalogue; java.util;
203,569
private Dispatcher setupDispatcher() { Dispatcher dispatcher = createDispatcher(); dispatcher.register(RMFatalEventType.class, new ResourceManager.RMFatalEventDispatcher()); return dispatcher; }
Dispatcher function() { Dispatcher dispatcher = createDispatcher(); dispatcher.register(RMFatalEventType.class, new ResourceManager.RMFatalEventDispatcher()); return dispatcher; }
/** * Register the handlers for alwaysOn services */
Register the handlers for alwaysOn services
setupDispatcher
{ "repo_name": "legend-hua/hadoop", "path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceManager.java", "license": "apache-2.0", "size": 55755 }
[ "org.apache.hadoop.yarn.event.Dispatcher" ]
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.event.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
1,858,497
public void BeforePicking() { EventDispatcher.dispatchEvent(this, "BeforePicking"); }
void function() { EventDispatcher.dispatchEvent(this, STR); }
/** * Simple event to raise when the component is clicked but before the * picker activity is started. */
Simple event to raise when the component is clicked but before the picker activity is started
BeforePicking
{ "repo_name": "roadlabs/alternate-java-bridge-library", "path": "src/com/xiledsystems/AlternateJavaBridgelib/components/altbridge/Picker.java", "license": "apache-2.0", "size": 1741 }
[ "com.xiledsystems.AlternateJavaBridgelib" ]
import com.xiledsystems.AlternateJavaBridgelib;
import com.xiledsystems.*;
[ "com.xiledsystems" ]
com.xiledsystems;
2,029,441
public TimeInstant getBeginOfNextEntry(TimeInstant now){ TimeUnit epsUnit = this.model.getExperiment().getEpsilonUnit(); TimeInstant big = new TimeInstant(Long.MAX_VALUE-1, epsUnit); TimeInstant min = big; for(int i=0; i<this.entryList.size(); i++){ EntityScheduleEntry entry = this.entryList.get(i); TimeInstant nextBegin = entry.getNextBegin(now); if(nextBegin != null && TimeInstant.isBefore(nextBegin, min)) min = nextBegin; } if(min.equals(big)) min = null; return min; }
TimeInstant function(TimeInstant now){ TimeUnit epsUnit = this.model.getExperiment().getEpsilonUnit(); TimeInstant big = new TimeInstant(Long.MAX_VALUE-1, epsUnit); TimeInstant min = big; for(int i=0; i<this.entryList.size(); i++){ EntityScheduleEntry entry = this.entryList.get(i); TimeInstant nextBegin = entry.getNextBegin(now); if(nextBegin != null && TimeInstant.isBefore(nextBegin, min)) min = nextBegin; } if(min.equals(big)) min = null; return min; }
/** * compute begin of next valid scheduleEntry. * @param now actual simulation time * @return null when no next entry exist. */
compute begin of next valid scheduleEntry
getBeginOfNextEntry
{ "repo_name": "muhd7rosli/desmoj", "path": "src/desmoj/extensions/scheduling/EntitySchedule.java", "license": "apache-2.0", "size": 9179 }
[ "java.util.concurrent.TimeUnit" ]
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
[ "java.util" ]
java.util;
1,935,905
private long createWorkerHelper(int workerIndex) throws Exception { WorkerNetAddress address = new WorkerNetAddress().setHost("host" + workerIndex).setRpcPort(1000) .setDataPort(2000).setWebPort(3000); long workerId = mBlockMaster.getWorkerId(address); if (!mKnownWorkers.contains(workerId)) { // Do not re-register works, otherwise added block will be removed mBlockMaster.workerRegister(workerId, ImmutableList.of("MEM"), ImmutableMap.of("MEM", 100L), ImmutableMap.of("MEM", 0L), NO_BLOCKS_ON_TIERS, new RegisterWorkerTOptions()); mKnownWorkers.add(workerId); } return workerId; }
long function(int workerIndex) throws Exception { WorkerNetAddress address = new WorkerNetAddress().setHost("host" + workerIndex).setRpcPort(1000) .setDataPort(2000).setWebPort(3000); long workerId = mBlockMaster.getWorkerId(address); if (!mKnownWorkers.contains(workerId)) { mBlockMaster.workerRegister(workerId, ImmutableList.of("MEM"), ImmutableMap.of("MEM", 100L), ImmutableMap.of("MEM", 0L), NO_BLOCKS_ON_TIERS, new RegisterWorkerTOptions()); mKnownWorkers.add(workerId); } return workerId; }
/** * Helper to register a new worker. * * @param workerIndex the index of the worker in all workers * @return the created worker ID */
Helper to register a new worker
createWorkerHelper
{ "repo_name": "apc999/alluxio", "path": "core/server/master/src/test/java/alluxio/master/file/replication/ReplicationCheckerTest.java", "license": "apache-2.0", "size": 14440 }
[ "com.google.common.collect.ImmutableList", "com.google.common.collect.ImmutableMap" ]
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.*;
[ "com.google.common" ]
com.google.common;
1,534,306
@Test public void testDelayedAllocation() throws Exception { BufferPool pool = new BufferPool(5 * 1024, 1024, metrics, time, metricGroup); ByteBuffer buffer = pool.allocate(1024, maxBlockTimeMs); CountDownLatch doDealloc = asyncDeallocate(pool, buffer); CountDownLatch allocation = asyncAllocate(pool, 5 * 1024); assertEquals("Allocation shouldn't have happened yet, waiting on memory.", 1L, allocation.getCount()); doDealloc.countDown(); // return the memory assertTrue("Allocation should succeed soon after de-allocation", allocation.await(1, TimeUnit.SECONDS)); }
void function() throws Exception { BufferPool pool = new BufferPool(5 * 1024, 1024, metrics, time, metricGroup); ByteBuffer buffer = pool.allocate(1024, maxBlockTimeMs); CountDownLatch doDealloc = asyncDeallocate(pool, buffer); CountDownLatch allocation = asyncAllocate(pool, 5 * 1024); assertEquals(STR, 1L, allocation.getCount()); doDealloc.countDown(); assertTrue(STR, allocation.await(1, TimeUnit.SECONDS)); }
/** * Test that delayed allocation blocks */
Test that delayed allocation blocks
testDelayedAllocation
{ "repo_name": "sslavic/kafka", "path": "clients/src/test/java/org/apache/kafka/clients/producer/internals/BufferPoolTest.java", "license": "apache-2.0", "size": 17853 }
[ "java.nio.ByteBuffer", "java.util.concurrent.CountDownLatch", "java.util.concurrent.TimeUnit", "org.junit.Assert" ]
import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Assert;
import java.nio.*; import java.util.concurrent.*; import org.junit.*;
[ "java.nio", "java.util", "org.junit" ]
java.nio; java.util; org.junit;
1,823,077
@Test public void checkMarkWhite() { String b = "000000\n"+ "001100\n"+ "000100\n"+ "000000\n"; String a = "022220\n"+ "021120\n"+ "022120\n"+ "002220\n"; ImageUInt8 before = stringToImage(b); ImageUInt8 after = stringToImage(a); ImageSInt32 label = new ImageSInt32(before.width,before.height); ContourTracer alg = new ContourTracer(ConnectRule.EIGHT); // process the image alg.setInputs(before,label,queue); alg.trace(2,2,1,true,found); for( int i = 0; i < before.height; i++ ) { for( int j = 0; j < before.width; j++ ) { if( after.get(j,i) == 2 ) assertEquals(255,before.get(j,i)); else assertEquals(after.get(j,i),before.get(j,i)); } } }
void function() { String b = STR+ STR+ STR+ STR; String a = STR+ STR+ STR+ STR; ImageUInt8 before = stringToImage(b); ImageUInt8 after = stringToImage(a); ImageSInt32 label = new ImageSInt32(before.width,before.height); ContourTracer alg = new ContourTracer(ConnectRule.EIGHT); alg.setInputs(before,label,queue); alg.trace(2,2,1,true,found); for( int i = 0; i < before.height; i++ ) { for( int j = 0; j < before.width; j++ ) { if( after.get(j,i) == 2 ) assertEquals(255,before.get(j,i)); else assertEquals(after.get(j,i),before.get(j,i)); } } }
/** * Make sure it is marking surrounding white pixels */
Make sure it is marking surrounding white pixels
checkMarkWhite
{ "repo_name": "pacozaa/BoofCV", "path": "main/ip/test/boofcv/alg/filter/binary/TestContourTracer.java", "license": "apache-2.0", "size": 6975 }
[ "org.junit.Assert" ]
import org.junit.Assert;
import org.junit.*;
[ "org.junit" ]
org.junit;
92,833
@Override public void write(byte[] b, int off, int len) throws IOException { final byte[] segment = new byte[len]; System.arraycopy(b, off, segment, 0, len); this.write(segment); }
void function(byte[] b, int off, int len) throws IOException { final byte[] segment = new byte[len]; System.arraycopy(b, off, segment, 0, len); this.write(segment); }
/** * Writes a byte waiting for a predefined amount of time writing. * * @param b the byte to be written. * @param off the byte offset * @param len the byte len to write * @throws IOException when if writing on the decorated stream fails or if the the * stream was not allowed to wait the specified amount of milliseconds * before writing the byte */
Writes a byte waiting for a predefined amount of time writing
write
{ "repo_name": "cpslabteam/codebase", "path": "src/main/java/codebase/streams/DelayedOutputStream.java", "license": "gpl-2.0", "size": 2788 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
2,181,443
private void serializeOCCColumn(Object fieldValue, PutAction putAction) { // OCC Version mapping, so serialize as a long to the version check // column qualifier in the system column family. Long currVersion = (Long) fieldValue; VersionCheckAction versionCheckAction = new VersionCheckAction(currVersion); putAction.getPut().add(Constants.SYS_COL_FAMILY, Constants.VERSION_CHECK_COL_QUALIFIER, Bytes.toBytes(currVersion + 1)); putAction.setVersionCheckAction(versionCheckAction); }
void function(Object fieldValue, PutAction putAction) { Long currVersion = (Long) fieldValue; VersionCheckAction versionCheckAction = new VersionCheckAction(currVersion); putAction.getPut().add(Constants.SYS_COL_FAMILY, Constants.VERSION_CHECK_COL_QUALIFIER, Bytes.toBytes(currVersion + 1)); putAction.setVersionCheckAction(versionCheckAction); }
/** * Serialize the OCC column value, and update the putAction with the * serialized bytes. * * @param fieldValue * The value to serialize * @param putAction * The PutAction to update. */
Serialize the OCC column value, and update the putAction with the serialized bytes
serializeOCCColumn
{ "repo_name": "stevek-ngdata/kite", "path": "kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/EntitySerDe.java", "license": "apache-2.0", "size": 13204 }
[ "org.apache.hadoop.hbase.util.Bytes" ]
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
2,137,364
@Deprecated public StepMeta findPrevStep( StepMeta stepMeta, int nr, boolean info ) { int count = 0; int i; for ( i = 0; i < nrTransHops(); i++ ) { // Look at all the hops; TransHopMeta hi = getTransHop( i ); if ( hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals( stepMeta ) ) { if ( info || !isStepInformative( stepMeta, hi.getFromStep() ) ) { if ( count == nr ) { return hi.getFromStep(); } count++; } } } return null; }
StepMeta function( StepMeta stepMeta, int nr, boolean info ) { int count = 0; int i; for ( i = 0; i < nrTransHops(); i++ ) { TransHopMeta hi = getTransHop( i ); if ( hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals( stepMeta ) ) { if ( info !isStepInformative( stepMeta, hi.getFromStep() ) ) { if ( count == nr ) { return hi.getFromStep(); } count++; } } } return null; }
/** * Find the previous step on a certain location taking into account the steps being informational or not. * * @param stepMeta * The step * @param nr * The index into the hops list * @param info * true if we only want the informational steps. * @return The preceding step information * @deprecated please use method findPreviousSteps */
Find the previous step on a certain location taking into account the steps being informational or not
findPrevStep
{ "repo_name": "alina-ipatina/pentaho-kettle", "path": "engine/src/org/pentaho/di/trans/TransMeta.java", "license": "apache-2.0", "size": 221917 }
[ "org.pentaho.di.trans.step.StepMeta" ]
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.*;
[ "org.pentaho.di" ]
org.pentaho.di;
124,642
public static File findFile(String fileName, File currentDir, int depth) { File ret = null; int i = 0; while (currentDir != null && (depth == -1 || i++ < depth)) { ret = new File(currentDir.getPath() + File.separator + fileName); if (ret != null && ret.exists()) { return ret; } currentDir = currentDir.getParentFile(); } return null; }
static File function(String fileName, File currentDir, int depth) { File ret = null; int i = 0; while (currentDir != null && (depth == -1 i++ < depth)) { ret = new File(currentDir.getPath() + File.separator + fileName); if (ret != null && ret.exists()) { return ret; } currentDir = currentDir.getParentFile(); } return null; }
/** * Find a file in currentDir or its parent directories * * @param fileName * @param currentDir * @param depth limit the number of parent directories to this depth, or -1 is infinite * @return the found file, or null */
Find a file in currentDir or its parent directories
findFile
{ "repo_name": "hholzgra/rasdaman", "path": "applications/petascope9/src/main/java/petascope/util/IOUtil.java", "license": "gpl-3.0", "size": 7100 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
1,076,107
protected void upgradeTable(String tableNameStr) throws IOException { byte[] tableName = Bytes.toBytes(tableNameStr); HTableDescriptor tableDescriptor = getAdmin().getTableDescriptor(tableName); // Upgrade any table properties if necessary boolean needUpgrade = upgradeTable(tableDescriptor); // Get the Tigon version from the table ProjectInfo.Version version = new ProjectInfo.Version(tableDescriptor.getValue(TIGON_VERSION)); if (!needUpgrade && version.compareTo(ProjectInfo.getVersion()) >= 0) { // If the table has greater than or same version, no need to upgrade. LOG.info("Table '{}' was upgraded with same or newer version '{}'. Current version is '{}'", tableNameStr, version, ProjectInfo.getVersion()); return; } // Generate the coprocessor jar CoprocessorJar coprocessorJar = createCoprocessorJar(); Location jarLocation = coprocessorJar.getJarLocation(); // Check if coprocessor upgrade is needed Map<String, HBaseTableUtil.CoprocessorInfo> coprocessorInfo = HBaseTableUtil.getCoprocessorInfo(tableDescriptor); // For all required coprocessors, check if they've need to be upgraded. for (Class<? extends Coprocessor> coprocessor : coprocessorJar.getCoprocessors()) { HBaseTableUtil.CoprocessorInfo info = coprocessorInfo.get(coprocessor.getName()); if (info != null) { // The same coprocessor has been configured, check by the file name hash to see if they are the same. if (!jarLocation.getName().equals(info.getPath().getName())) { needUpgrade = true; // Remove old one and add the new one. tableDescriptor.removeCoprocessor(info.getClassName()); addCoprocessor(tableDescriptor, coprocessor, jarLocation, coprocessorJar.getPriority(coprocessor)); } } else { // The coprocessor is missing from the table, add it. needUpgrade = true; addCoprocessor(tableDescriptor, coprocessor, jarLocation, coprocessorJar.getPriority(coprocessor)); } } // Removes all old coprocessors Set<String> coprocessorNames = ImmutableSet.copyOf(Iterables.transform(coprocessorJar.coprocessors, CLASS_TO_NAME)); for (String remove : Sets.difference(coprocessorInfo.keySet(), coprocessorNames)) { needUpgrade = true; tableDescriptor.removeCoprocessor(remove); } if (!needUpgrade) { LOG.info("No upgrade needed for table '{}'", tableNameStr); return; } // Add the current version as table properties only if the table needs upgrade tableDescriptor.setValue(TIGON_VERSION, ProjectInfo.getVersion().toString()); LOG.info("Upgrading table '{}'...", tableNameStr); boolean enableTable = false; try { getAdmin().disableTable(tableName); enableTable = true; } catch (TableNotEnabledException e) { LOG.debug("Table '{}' not enabled when try to disable it.", tableNameStr); } getAdmin().modifyTable(tableName, tableDescriptor); if (enableTable) { getAdmin().enableTable(tableName); } LOG.info("Table '{}' upgrade completed.", tableNameStr); }
void function(String tableNameStr) throws IOException { byte[] tableName = Bytes.toBytes(tableNameStr); HTableDescriptor tableDescriptor = getAdmin().getTableDescriptor(tableName); boolean needUpgrade = upgradeTable(tableDescriptor); ProjectInfo.Version version = new ProjectInfo.Version(tableDescriptor.getValue(TIGON_VERSION)); if (!needUpgrade && version.compareTo(ProjectInfo.getVersion()) >= 0) { LOG.info(STR, tableNameStr, version, ProjectInfo.getVersion()); return; } CoprocessorJar coprocessorJar = createCoprocessorJar(); Location jarLocation = coprocessorJar.getJarLocation(); Map<String, HBaseTableUtil.CoprocessorInfo> coprocessorInfo = HBaseTableUtil.getCoprocessorInfo(tableDescriptor); for (Class<? extends Coprocessor> coprocessor : coprocessorJar.getCoprocessors()) { HBaseTableUtil.CoprocessorInfo info = coprocessorInfo.get(coprocessor.getName()); if (info != null) { if (!jarLocation.getName().equals(info.getPath().getName())) { needUpgrade = true; tableDescriptor.removeCoprocessor(info.getClassName()); addCoprocessor(tableDescriptor, coprocessor, jarLocation, coprocessorJar.getPriority(coprocessor)); } } else { needUpgrade = true; addCoprocessor(tableDescriptor, coprocessor, jarLocation, coprocessorJar.getPriority(coprocessor)); } } Set<String> coprocessorNames = ImmutableSet.copyOf(Iterables.transform(coprocessorJar.coprocessors, CLASS_TO_NAME)); for (String remove : Sets.difference(coprocessorInfo.keySet(), coprocessorNames)) { needUpgrade = true; tableDescriptor.removeCoprocessor(remove); } if (!needUpgrade) { LOG.info(STR, tableNameStr); return; } tableDescriptor.setValue(TIGON_VERSION, ProjectInfo.getVersion().toString()); LOG.info(STR, tableNameStr); boolean enableTable = false; try { getAdmin().disableTable(tableName); enableTable = true; } catch (TableNotEnabledException e) { LOG.debug(STR, tableNameStr); } getAdmin().modifyTable(tableName, tableDescriptor); if (enableTable) { getAdmin().enableTable(tableName); } LOG.info(STR, tableNameStr); }
/** * Performs upgrade on a given HBase table. * * @param tableNameStr The HBase table name that upgrade will be performed on. * @throws java.io.IOException If upgrade failed. */
Performs upgrade on a given HBase table
upgradeTable
{ "repo_name": "caskdata/tigon", "path": "tigon-queue/src/main/java/co/cask/tigon/data/lib/hbase/AbstractHBaseDataSetAdmin.java", "license": "apache-2.0", "size": 9105 }
[ "co.cask.tigon.api.common.Bytes", "co.cask.tigon.data.util.hbase.HBaseTableUtil", "co.cask.tigon.utils.ProjectInfo", "com.google.common.collect.ImmutableSet", "com.google.common.collect.Iterables", "com.google.common.collect.Sets", "java.io.IOException", "java.util.Map", "java.util.Set", "org.apache.hadoop.hbase.Coprocessor", "org.apache.hadoop.hbase.HTableDescriptor", "org.apache.hadoop.hbase.TableNotEnabledException", "org.apache.twill.filesystem.Location" ]
import co.cask.tigon.api.common.Bytes; import co.cask.tigon.data.util.hbase.HBaseTableUtil; import co.cask.tigon.utils.ProjectInfo; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import java.io.IOException; import java.util.Map; import java.util.Set; import org.apache.hadoop.hbase.Coprocessor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableNotEnabledException; import org.apache.twill.filesystem.Location;
import co.cask.tigon.api.common.*; import co.cask.tigon.data.util.hbase.*; import co.cask.tigon.utils.*; import com.google.common.collect.*; import java.io.*; import java.util.*; import org.apache.hadoop.hbase.*; import org.apache.twill.filesystem.*;
[ "co.cask.tigon", "com.google.common", "java.io", "java.util", "org.apache.hadoop", "org.apache.twill" ]
co.cask.tigon; com.google.common; java.io; java.util; org.apache.hadoop; org.apache.twill;
2,350,647
@Test public void testReplaceValueUnequalStoreEntryUnequalCacheLoaderWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(fakeStore); final FakeCacheLoaderWriter fakeWriter = new FakeCacheLoaderWriter(Collections.singletonMap("key", "unequalValue")); final EhcacheWithLoaderWriter<String, String> ehcache = this.getEhcache(fakeWriter); assertFalse(ehcache.replace("key", "oldValue", "newValue")); verify(this.store).compute(eq("key"), getAnyBiFunction(), getBooleanNullaryFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), is(equalTo("unequalValue"))); assertThat(fakeWriter.getEntryMap().get("key"), is(equalTo("unequalValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.MISS_PRESENT)); }
void function() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", STR)); this.store = spy(fakeStore); final FakeCacheLoaderWriter fakeWriter = new FakeCacheLoaderWriter(Collections.singletonMap("key", STR)); final EhcacheWithLoaderWriter<String, String> ehcache = this.getEhcache(fakeWriter); assertFalse(ehcache.replace("key", STR, STR)); verify(this.store).compute(eq("key"), getAnyBiFunction(), getBooleanNullaryFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), is(equalTo(STR))); assertThat(fakeWriter.getEntryMap().get("key"), is(equalTo(STR))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.MISS_PRESENT)); }
/** * Tests the effect of a {@link EhcacheWithLoaderWriter#replace(Object, Object, Object)} for * <ul> * <li>key with unequal value present in {@code Store}</li> * <li>key with unequal value present via {@code CacheLoaderWriter}</li> * </ul> */
Tests the effect of a <code>EhcacheWithLoaderWriter#replace(Object, Object, Object)</code> for key with unequal value present in Store key with unequal value present via CacheLoaderWriter
testReplaceValueUnequalStoreEntryUnequalCacheLoaderWriterEntry
{ "repo_name": "akomakom/ehcache3", "path": "core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java", "license": "apache-2.0", "size": 43771 }
[ "java.util.Collections", "java.util.EnumSet", "org.ehcache.core.statistics.CacheOperationOutcomes", "org.hamcrest.CoreMatchers", "org.junit.Assert", "org.mockito.Mockito" ]
import java.util.Collections; import java.util.EnumSet; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.mockito.Mockito;
import java.util.*; import org.ehcache.core.statistics.*; import org.hamcrest.*; import org.junit.*; import org.mockito.*;
[ "java.util", "org.ehcache.core", "org.hamcrest", "org.junit", "org.mockito" ]
java.util; org.ehcache.core; org.hamcrest; org.junit; org.mockito;
149,268
public ModelNode asSubresource(ModelNode baseAddress, String... args) { int numWildCards = getNumWildCards(); int wildcards = (numWildCards - 1) > 0 ? numWildCards-1 : 0; assert wildcards == args.length : "Address arguments don't match number of wildcards: "+wildcards+" -> "+ Arrays.toString(args); ModelNode model = new ModelNode(); model.get(ADDRESS).set(baseAddress); int argsCounter = 0; for(int i=0; i<address.size()-1; i++) { String[] tuple = address.get(i); String parent = tuple[0]; String child = tuple[1]; if(parent.startsWith("{")) { parent = args[argsCounter]; argsCounter++; } if(child.startsWith("{")) { child = args[argsCounter]; argsCounter++; } model.get(ADDRESS).add(parent, child); } String[] lastTuple = address.get(address.size()-1); String childType = lastTuple[0]; if(childType.startsWith("{")) { childType = args[argsCounter]; argsCounter++; } model.get(CHILD_TYPE).set(childType); return model; }
ModelNode function(ModelNode baseAddress, String... args) { int numWildCards = getNumWildCards(); int wildcards = (numWildCards - 1) > 0 ? numWildCards-1 : 0; assert wildcards == args.length : STR+wildcards+STR+ Arrays.toString(args); ModelNode model = new ModelNode(); model.get(ADDRESS).set(baseAddress); int argsCounter = 0; for(int i=0; i<address.size()-1; i++) { String[] tuple = address.get(i); String parent = tuple[0]; String child = tuple[1]; if(parent.startsWith("{")) { parent = args[argsCounter]; argsCounter++; } if(child.startsWith("{")) { child = args[argsCounter]; argsCounter++; } model.get(ADDRESS).add(parent, child); } String[] lastTuple = address.get(address.size()-1); String childType = lastTuple[0]; if(childType.startsWith("{")) { childType = args[argsCounter]; argsCounter++; } model.get(CHILD_TYPE).set(childType); return model; }
/** * Turns this address into a subresource address, * including the address and child-type properties.<br/> * The child-type is derived from the last address token qualifier. * * This method allows to specify a base address prefix (i.e server vs. domain addressing). * * @param baseAddress * @param args parameters for address wildcards * @return ModelNode including address and child-type property */
Turns this address into a subresource address, including the address and child-type properties. The child-type is derived from the last address token qualifier. This method allows to specify a base address prefix (i.e server vs. domain addressing)
asSubresource
{ "repo_name": "hal/core", "path": "gui/src/main/java/org/jboss/as/console/client/widgets/forms/AddressBinding.java", "license": "lgpl-2.1", "size": 6511 }
[ "java.util.Arrays", "org.jboss.dmr.client.ModelNode" ]
import java.util.Arrays; import org.jboss.dmr.client.ModelNode;
import java.util.*; import org.jboss.dmr.client.*;
[ "java.util", "org.jboss.dmr" ]
java.util; org.jboss.dmr;
141,149
protected Collection<String> getInitialObjectNames() { if (initialObjectNames == null) { initialObjectNames = new ArrayList<String>(); for (EClassifier eClassifier : globalPackage.getEClassifiers()) { if (eClassifier instanceof EClass) { EClass eClass = (EClass)eClassifier; if (!eClass.isAbstract()) { initialObjectNames.add(eClass.getName()); } } } Collections.sort(initialObjectNames, CommonPlugin.INSTANCE.getComparator()); } return initialObjectNames; }
Collection<String> function() { if (initialObjectNames == null) { initialObjectNames = new ArrayList<String>(); for (EClassifier eClassifier : globalPackage.getEClassifiers()) { if (eClassifier instanceof EClass) { EClass eClass = (EClass)eClassifier; if (!eClass.isAbstract()) { initialObjectNames.add(eClass.getName()); } } } Collections.sort(initialObjectNames, CommonPlugin.INSTANCE.getComparator()); } return initialObjectNames; }
/** * Returns the names of the types that can be created as the root object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
Returns the names of the types that can be created as the root object.
getInitialObjectNames
{ "repo_name": "uppaal-emf/uppaal", "path": "metamodel/org.muml.uppaal.editor/src/org/muml/uppaal/declarations/global/presentation/GlobalModelWizard.java", "license": "epl-1.0", "size": 18337 }
[ "java.util.ArrayList", "java.util.Collection", "java.util.Collections", "org.eclipse.emf.common.CommonPlugin", "org.eclipse.emf.ecore.EClass", "org.eclipse.emf.ecore.EClassifier" ]
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import org.eclipse.emf.common.CommonPlugin; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier;
import java.util.*; import org.eclipse.emf.common.*; import org.eclipse.emf.ecore.*;
[ "java.util", "org.eclipse.emf" ]
java.util; org.eclipse.emf;
1,891,929
Future<WebSiteAppSettingsResult> updateAppSettingsAsync(String resourceGroupName, String webSiteName, String slotName, WebSiteNameValueParameters parameters);
Future<WebSiteAppSettingsResult> updateAppSettingsAsync(String resourceGroupName, String webSiteName, String slotName, WebSiteNameValueParameters parameters);
/** * You can retrieve the application settings for a web site by issuing an * HTTP GET request, or update them by using HTTP PUT with a request body * that contains the settings to be updated. (see * http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx for * more information) * * @param resourceGroupName Required. The name of the resource group * @param webSiteName Required. The name of the web site * @param slotName Optional. The name of the slot of the website * @param parameters Required. The Update Web Site app settings parameters * @return List of app settings for the website. */
You can retrieve the application settings for a web site by issuing an HTTP GET request, or update them by using HTTP PUT with a request body that contains the settings to be updated. (see HREF for more information)
updateAppSettingsAsync
{ "repo_name": "southworkscom/azure-sdk-for-java", "path": "resource-management/azure-mgmt-websites/src/main/java/com/microsoft/azure/management/websites/WebSiteOperations.java", "license": "apache-2.0", "size": 60715 }
[ "com.microsoft.azure.management.websites.models.WebSiteAppSettingsResult", "com.microsoft.azure.management.websites.models.WebSiteNameValueParameters", "java.util.concurrent.Future" ]
import com.microsoft.azure.management.websites.models.WebSiteAppSettingsResult; import com.microsoft.azure.management.websites.models.WebSiteNameValueParameters; import java.util.concurrent.Future;
import com.microsoft.azure.management.websites.models.*; import java.util.concurrent.*;
[ "com.microsoft.azure", "java.util" ]
com.microsoft.azure; java.util;
1,280,678
private URI getDevUrl(String command) { try { return getServerUrl().resolve(CHANNEL_URL + "dev?command=" + command + "&channel=" + URLEncoder.encode(getToken(), "UTF-8") + (getClientId() != null ? "&client=" + URLEncoder.encode(getClientId(), "UTF-8") : "")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return getServerUrl().resolve(CHANNEL_URL); } }
URI function(String command) { try { return getServerUrl().resolve(CHANNEL_URL + STR + command + STR + URLEncoder.encode(getToken(), "UTF-8") + (getClientId() != null ? STR + URLEncoder.encode(getClientId(), "UTF-8") : "")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return getServerUrl().resolve(CHANNEL_URL); } }
/** * Helper to get URL formatted for development server * * @param command channel operation * @return desired URL */
Helper to get URL formatted for development server
getDevUrl
{ "repo_name": "GautierLevert/GAE-Channel-API-Java-Client", "path": "library/src/main/java/org/mybop/gae/channelapi/dev/DevChannel.java", "license": "mit", "size": 3360 }
[ "java.io.UnsupportedEncodingException", "java.net.URLEncoder" ]
import java.io.UnsupportedEncodingException; import java.net.URLEncoder;
import java.io.*; import java.net.*;
[ "java.io", "java.net" ]
java.io; java.net;
2,129,157
public void setFtpClient(FTPClient ftpClient) { this.ftpClient = ftpClient; }
void function(FTPClient ftpClient) { this.ftpClient = ftpClient; }
/** * To use a custom instance of FTPClient */
To use a custom instance of FTPClient
setFtpClient
{ "repo_name": "DariusX/camel", "path": "components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpEndpoint.java", "license": "apache-2.0", "size": 15923 }
[ "org.apache.commons.net.ftp.FTPClient" ]
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.*;
[ "org.apache.commons" ]
org.apache.commons;
751,157
public String readAsciiEncodedString() throws IOException { return this.stream.available() == 0 ? EMPTY_STRING : new String(this.readFromStream(this.stream.available()), ASCII); }
String function() throws IOException { return this.stream.available() == 0 ? EMPTY_STRING : new String(this.readFromStream(this.stream.available()), ASCII); }
/** * Reads bytes from the underlying byte array and decodes the read bytes using the ASCII codepage 850. * @return the decoded ASCII string. * @throws IOException if there are less than the required bytes available in the underlying byte array. */
Reads bytes from the underlying byte array and decodes the read bytes using the ASCII codepage 850
readAsciiEncodedString
{ "repo_name": "michaelknigge/ipdsbox", "path": "ipdsbox/src/main/java/mk/ipdsbox/io/IpdsByteArrayInputStream.java", "license": "mpl-2.0", "size": 7237 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
2,898,056
private RecordingOutErr callConfigCommand(String... args) throws Exception { List<String> params = Lists.newArrayList("config"); params.add("--output=json"); Collections.addAll(params, args); RecordingOutErr recordingOutErr = new RecordingOutErr(); dispatcher.exec(params, "my client", recordingOutErr); return recordingOutErr; }
RecordingOutErr function(String... args) throws Exception { List<String> params = Lists.newArrayList(STR); params.add(STR); Collections.addAll(params, args); RecordingOutErr recordingOutErr = new RecordingOutErr(); dispatcher.exec(params, STR, recordingOutErr); return recordingOutErr; }
/** * Calls <cod>blaze config --output=json</code> with the given flags and returns the raw output. * * <p>Should be called after {@link #analyzeTarget} so there are actual configs to read. */
Calls blaze config --output=json</code> with the given flags and returns the raw output. Should be called after <code>#analyzeTarget</code> so there are actual configs to read
callConfigCommand
{ "repo_name": "perezd/bazel", "path": "src/test/java/com/google/devtools/build/lib/runtime/commands/ConfigCommandTest.java", "license": "apache-2.0", "size": 17907 }
[ "com.google.common.collect.Lists", "com.google.devtools.build.lib.util.io.RecordingOutErr", "java.util.Collections", "java.util.List" ]
import com.google.common.collect.Lists; import com.google.devtools.build.lib.util.io.RecordingOutErr; import java.util.Collections; import java.util.List;
import com.google.common.collect.*; import com.google.devtools.build.lib.util.io.*; import java.util.*;
[ "com.google.common", "com.google.devtools", "java.util" ]
com.google.common; com.google.devtools; java.util;
2,170,094
private static void applyModification(UnitEntry unit) { switch (unit.getUnitClass()) { case INFANTRY: case TANK: case RECON: case ANTI_TANK: case ARTILLERY: case FORT: case SUBMARINE: case DESTROYER: case CAPITAL: case CARRIER: unit.setAtkAir(-unit.getAtkAir()); break; case AIR_DEFENSE: unit.setAtkSoft(-unit.getAtkSoft()); unit.setAtkHard(-unit.getAtkHard()); unit.setAtkNaval(-unit.getAtkNaval()); break; case TACBOMBER: case LEVBOMBER: if (unit.isAirAttackFlag()) { unit.setAtkAir(-unit.getAtkAir()); } break; default: break; } }
static void function(UnitEntry unit) { switch (unit.getUnitClass()) { case INFANTRY: case TANK: case RECON: case ANTI_TANK: case ARTILLERY: case FORT: case SUBMARINE: case DESTROYER: case CAPITAL: case CARRIER: unit.setAtkAir(-unit.getAtkAir()); break; case AIR_DEFENSE: unit.setAtkSoft(-unit.getAtkSoft()); unit.setAtkHard(-unit.getAtkHard()); unit.setAtkNaval(-unit.getAtkNaval()); break; case TACBOMBER: case LEVBOMBER: if (unit.isAirAttackFlag()) { unit.setAtkAir(-unit.getAtkAir()); } break; default: break; } }
/** * apply modification, mostly on air unit to set a negative air attack for defense only. * @param unit the unit to modify, inline modification */
apply modification, mostly on air unit to set a negative air attack for defense only
applyModification
{ "repo_name": "fforjan/PGReader", "path": "Workspace/PGReader/src/com/pgreader/legacy/UnitReader.java", "license": "gpl-2.0", "size": 7361 }
[ "com.pgreader.data.UnitEntry" ]
import com.pgreader.data.UnitEntry;
import com.pgreader.data.*;
[ "com.pgreader.data" ]
com.pgreader.data;
2,306,209
private List<CheckpointEntry> retreiveHistory() throws IgniteCheckedException { if (!cpDir.exists()) return Collections.emptyList(); try (DirectoryStream<Path> cpFiles = Files.newDirectoryStream( cpDir.toPath(), path -> CP_FILE_NAME_PATTERN.matcher(path.toFile().getName()).matches()) ) { List<CheckpointEntry> checkpoints = new ArrayList<>(); ByteBuffer buf = ByteBuffer.allocate(FileWALPointer.POINTER_SIZE); buf.order(ByteOrder.nativeOrder()); for (Path cpFile : cpFiles) { CheckpointEntry cp = parseFromFile(buf, cpFile.toFile()); if (cp != null) checkpoints.add(cp); } return checkpoints; } catch (IOException e) { throw new IgniteCheckedException("Failed to load checkpoint history.", e); } }
List<CheckpointEntry> function() throws IgniteCheckedException { if (!cpDir.exists()) return Collections.emptyList(); try (DirectoryStream<Path> cpFiles = Files.newDirectoryStream( cpDir.toPath(), path -> CP_FILE_NAME_PATTERN.matcher(path.toFile().getName()).matches()) ) { List<CheckpointEntry> checkpoints = new ArrayList<>(); ByteBuffer buf = ByteBuffer.allocate(FileWALPointer.POINTER_SIZE); buf.order(ByteOrder.nativeOrder()); for (Path cpFile : cpFiles) { CheckpointEntry cp = parseFromFile(buf, cpFile.toFile()); if (cp != null) checkpoints.add(cp); } return checkpoints; } catch (IOException e) { throw new IgniteCheckedException(STR, e); } }
/** * Retreives checkpoint history form specified {@code dir}. * * @return List of checkpoints. */
Retreives checkpoint history form specified dir
retreiveHistory
{ "repo_name": "ilantukh/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/GridCacheDatabaseSharedManager.java", "license": "apache-2.0", "size": 208144 }
[ "java.io.IOException", "java.nio.ByteBuffer", "java.nio.ByteOrder", "java.nio.file.DirectoryStream", "java.nio.file.Files", "java.nio.file.Path", "java.util.ArrayList", "java.util.Collections", "java.util.List", "org.apache.ignite.IgniteCheckedException", "org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointEntry", "org.apache.ignite.internal.processors.cache.persistence.wal.FileWALPointer" ]
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointEntry; import org.apache.ignite.internal.processors.cache.persistence.wal.FileWALPointer;
import java.io.*; import java.nio.*; import java.nio.file.*; import java.util.*; import org.apache.ignite.*; import org.apache.ignite.internal.processors.cache.persistence.checkpoint.*; import org.apache.ignite.internal.processors.cache.persistence.wal.*;
[ "java.io", "java.nio", "java.util", "org.apache.ignite" ]
java.io; java.nio; java.util; org.apache.ignite;
1,961,116
private Node addNode(ParserRuleContext node, String text) { return this.graph.addNode(node.getStart().getLine() + ": " + text); }
Node function(ParserRuleContext node, String text) { return this.graph.addNode(node.getStart().getLine() + STR + text); }
/** Adds a node to he CGF, based on a given parse tree node. * Gives the CFG node a meaningful ID, consisting of line number and * a further indicator. */
Adds a node to he CGF, based on a given parse tree node. Gives the CFG node a meaningful ID, consisting of line number and a further indicator
addNode
{ "repo_name": "Pieterjaninfo/PP", "path": "src/pp/block4/cc/cfg/TopDownCFGBuilder.java", "license": "unlicense", "size": 5806 }
[ "org.antlr.v4.runtime.ParserRuleContext" ]
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.*;
[ "org.antlr.v4" ]
org.antlr.v4;
218,338
@SuppressWarnings("unlikely-arg-type") @Test public final void testHashCode() { String testName = new String("CollectionListe<String>.equals(Object)"); System.out.println(testName); int result1, result2; ArrayList<String> otherCollection = new ArrayList<String>(); // hashCode collection vide = 1 result1 = collection.hashCode(); result2 = otherCollection.hashCode(); assertEquals(testName + " hashCode collection vide", 1, result1); assertEquals(testName + " hashCodes collections vides", result2, result1); // Remplissages remplissage(collection); remplissage(otherCollection); // hasCode collections semblables result1 = collection.hashCode(); result2 = otherCollection.hashCode(); assertEquals(testName + " hashCode collections remplies", result2, result1); // hasCode collections dissemblables collection.add(extraElement); result1 = collection.hashCode(); assertTrue(testName + " hashCode collections remplies +", result2 != result1); // [Optionnel] // Les collections dissemblables ne sont plus égales assertFalse(testName + " hashCode + equals direct +", collection.equals(otherCollection)); }
@SuppressWarnings(STR) final void function() { String testName = new String(STR); System.out.println(testName); int result1, result2; ArrayList<String> otherCollection = new ArrayList<String>(); result1 = collection.hashCode(); result2 = otherCollection.hashCode(); assertEquals(testName + STR, 1, result1); assertEquals(testName + STR, result2, result1); remplissage(collection); remplissage(otherCollection); result1 = collection.hashCode(); result2 = otherCollection.hashCode(); assertEquals(testName + STR, result2, result1); collection.add(extraElement); result1 = collection.hashCode(); assertTrue(testName + STR, result2 != result1); assertFalse(testName + STR, collection.equals(otherCollection)); }
/** * Test method for {@link listes.CollectionListe#hashCode()}. */
Test method for <code>listes.CollectionListe#hashCode()</code>
testHashCode
{ "repo_name": "rpereira-dev/ENSIIE", "path": "UE/S2/ILO/TP Listes & Figures/src/tests/CollectionListeTest.java", "license": "gpl-3.0", "size": 22104 }
[ "java.util.ArrayList", "org.junit.Assert" ]
import java.util.ArrayList; import org.junit.Assert;
import java.util.*; import org.junit.*;
[ "java.util", "org.junit" ]
java.util; org.junit;
366,922
XYItemLabelGenerator getDefaultItemLabelGenerator();
XYItemLabelGenerator getDefaultItemLabelGenerator();
/** * Returns the default item label generator. * * @return The generator (possibly {@code null}). * * @see #setDefaultItemLabelGenerator(XYItemLabelGenerator) */
Returns the default item label generator
getDefaultItemLabelGenerator
{ "repo_name": "jfree/jfreechart", "path": "src/main/java/org/jfree/chart/renderer/xy/XYItemRenderer.java", "license": "lgpl-2.1", "size": 49520 }
[ "org.jfree.chart.labels.XYItemLabelGenerator" ]
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.chart.labels.*;
[ "org.jfree.chart" ]
org.jfree.chart;
1,703,999
private MigrationVersion applyMigration(final MigrationInfoImpl migration, boolean isOutOfOrder) { MigrationVersion version = migration.getVersion(); LOG.info("Migrating schema " + schema + " to version " + version + " - " + migration.getDescription() + (isOutOfOrder ? " (out of order)" : "")); StopWatch stopWatch = new StopWatch(); stopWatch.start();
MigrationVersion function(final MigrationInfoImpl migration, boolean isOutOfOrder) { MigrationVersion version = migration.getVersion(); LOG.info(STR + schema + STR + version + STR + migration.getDescription() + (isOutOfOrder ? STR : "")); StopWatch stopWatch = new StopWatch(); stopWatch.start();
/** * Applies this migration to the database. The migration state and the execution time are updated accordingly. * * @param migration The migration to apply. * @param isOutOfOrder If this migration is being applied out of order. * @return The result of the migration. */
Applies this migration to the database. The migration state and the execution time are updated accordingly
applyMigration
{ "repo_name": "chrsoo/flyway", "path": "flyway-core/src/main/java/org/flywaydb/core/internal/command/DbMigrate.java", "license": "apache-2.0", "size": 15314 }
[ "org.flywaydb.core.api.MigrationVersion", "org.flywaydb.core.internal.info.MigrationInfoImpl", "org.flywaydb.core.internal.util.StopWatch" ]
import org.flywaydb.core.api.MigrationVersion; import org.flywaydb.core.internal.info.MigrationInfoImpl; import org.flywaydb.core.internal.util.StopWatch;
import org.flywaydb.core.api.*; import org.flywaydb.core.internal.info.*; import org.flywaydb.core.internal.util.*;
[ "org.flywaydb.core" ]
org.flywaydb.core;
142,161
@Test public void testCorrectExecCmdWithVerboseInDiffParamsOrder() { injectTestSystemOut(); int resCode = EXIT_CODE_OK; assertEquals(resCode, execute(BASELINE.text(), CMD_VERBOSE)); assertNotContains(log, testOut.toString(), ERROR_STACK_TRACE_PREFIX); assertEquals(resCode, execute(CMD_VERBOSE, BASELINE.text())); assertNotContains(log, testOut.toString(), ERROR_STACK_TRACE_PREFIX); }
void function() { injectTestSystemOut(); int resCode = EXIT_CODE_OK; assertEquals(resCode, execute(BASELINE.text(), CMD_VERBOSE)); assertNotContains(log, testOut.toString(), ERROR_STACK_TRACE_PREFIX); assertEquals(resCode, execute(CMD_VERBOSE, BASELINE.text())); assertNotContains(log, testOut.toString(), ERROR_STACK_TRACE_PREFIX); }
/** * Test checks that there will be no error when executing the command with * option {@link CommonArgParser#CMD_VERBOSE}. */
Test checks that there will be no error when executing the command with option <code>CommonArgParser#CMD_VERBOSE</code>
testCorrectExecCmdWithVerboseInDiffParamsOrder
{ "repo_name": "ascherbakoff/ignite", "path": "modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerClusterByClassTest.java", "license": "apache-2.0", "size": 62940 }
[ "org.apache.ignite.internal.commandline.CommandList", "org.apache.ignite.testframework.GridTestUtils" ]
import org.apache.ignite.internal.commandline.CommandList; import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.internal.commandline.*; import org.apache.ignite.testframework.*;
[ "org.apache.ignite" ]
org.apache.ignite;
998,554
public void addPreferencesFromIntent(Intent intent) { requirePreferenceManager(); setPreferenceScreen(PreferenceManagerCompat.inflateFromIntent(mPreferenceManager, intent, getPreferenceScreen())); }
void function(Intent intent) { requirePreferenceManager(); setPreferenceScreen(PreferenceManagerCompat.inflateFromIntent(mPreferenceManager, intent, getPreferenceScreen())); }
/** * Adds preferences from activities that match the given {@link Intent}. * * @param intent The {@link Intent} to query activities. */
Adds preferences from activities that match the given <code>Intent</code>
addPreferencesFromIntent
{ "repo_name": "Yukarumya/Yukarum-Redfoxes", "path": "mobile/android/services/src/main/java/org/mozilla/gecko/background/preferences/PreferenceFragment.java", "license": "mpl-2.0", "size": 9962 }
[ "android.content.Intent" ]
import android.content.Intent;
import android.content.*;
[ "android.content" ]
android.content;
1,459,567
if (yFlowRepository.isSubFlow(request.getFirstFlow().getFlowId())) { sendForbiddenSubFlowOperationToNorthbound(request.getFirstFlow().getFlowId(), commandContext); return; } if (yFlowRepository.isSubFlow(request.getSecondFlow().getFlowId())) { sendForbiddenSubFlowOperationToNorthbound(request.getSecondFlow().getFlowId(), commandContext); return; } log.debug("Handling swap flow endpoints request with key {} and flow IDs: {}, {}", key, request.getFirstFlow().getFlowId(), request.getSecondFlow().getFlowId()); if (fsmRegister.hasRegisteredFsmWithKey(key)) { log.error("Attempt to create a FSM with key {}, while there's another active FSM with the same key.", key); return; } RequestedFlow firstFlow = RequestedFlowMapper.INSTANCE.toRequestedFlow(request.getFirstFlow()); RequestedFlow secondFlow = RequestedFlowMapper.INSTANCE.toRequestedFlow(request.getSecondFlow()); FlowSwapEndpointsFsm fsm = fsmFactory.newInstance(commandContext, firstFlow, secondFlow); fsmRegister.registerFsm(key, fsm); fsm.fire(Event.NEXT); removeIfFinished(fsm, key); }
if (yFlowRepository.isSubFlow(request.getFirstFlow().getFlowId())) { sendForbiddenSubFlowOperationToNorthbound(request.getFirstFlow().getFlowId(), commandContext); return; } if (yFlowRepository.isSubFlow(request.getSecondFlow().getFlowId())) { sendForbiddenSubFlowOperationToNorthbound(request.getSecondFlow().getFlowId(), commandContext); return; } log.debug(STR, key, request.getFirstFlow().getFlowId(), request.getSecondFlow().getFlowId()); if (fsmRegister.hasRegisteredFsmWithKey(key)) { log.error(STR, key); return; } RequestedFlow firstFlow = RequestedFlowMapper.INSTANCE.toRequestedFlow(request.getFirstFlow()); RequestedFlow secondFlow = RequestedFlowMapper.INSTANCE.toRequestedFlow(request.getSecondFlow()); FlowSwapEndpointsFsm fsm = fsmFactory.newInstance(commandContext, firstFlow, secondFlow); fsmRegister.registerFsm(key, fsm); fsm.fire(Event.NEXT); removeIfFinished(fsm, key); }
/** * Handles request for swap flow endpoints. */
Handles request for swap flow endpoints
handleRequest
{ "repo_name": "telstra/open-kilda", "path": "src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/service/FlowSwapEndpointsHubService.java", "license": "apache-2.0", "size": 5571 }
[ "org.openkilda.wfm.topology.flowhs.fsm.swapendpoints.FlowSwapEndpointsFsm", "org.openkilda.wfm.topology.flowhs.mapper.RequestedFlowMapper", "org.openkilda.wfm.topology.flowhs.model.RequestedFlow" ]
import org.openkilda.wfm.topology.flowhs.fsm.swapendpoints.FlowSwapEndpointsFsm; import org.openkilda.wfm.topology.flowhs.mapper.RequestedFlowMapper; import org.openkilda.wfm.topology.flowhs.model.RequestedFlow;
import org.openkilda.wfm.topology.flowhs.fsm.swapendpoints.*; import org.openkilda.wfm.topology.flowhs.mapper.*; import org.openkilda.wfm.topology.flowhs.model.*;
[ "org.openkilda.wfm" ]
org.openkilda.wfm;
2,678,100
bindScope(WORequestScoped.class, WOScopes.REQUEST); bindScope(WOSessionScoped.class, WOScopes.SESSION); @SuppressWarnings("unchecked") Class<WOSession> sessionClass = (Class<WOSession>) this.sessionClass; bind(sessionClass).annotatedWith(Current.class).toProvider(new TypeLiteral<WOSessionProvider<WOSession>>() { }); bind(ERXSession.class).annotatedWith(Current.class).toProvider(new TypeLiteral<WOSessionProvider<ERXSession>>() { }); bind(WOSession.class).annotatedWith(Current.class).toProvider(new TypeLiteral<WOSessionProvider<WOSession>>() { }); }
bindScope(WORequestScoped.class, WOScopes.REQUEST); bindScope(WOSessionScoped.class, WOScopes.SESSION); @SuppressWarnings(STR) Class<WOSession> sessionClass = (Class<WOSession>) this.sessionClass; bind(sessionClass).annotatedWith(Current.class).toProvider(new TypeLiteral<WOSessionProvider<WOSession>>() { }); bind(ERXSession.class).annotatedWith(Current.class).toProvider(new TypeLiteral<WOSessionProvider<ERXSession>>() { }); bind(WOSession.class).annotatedWith(Current.class).toProvider(new TypeLiteral<WOSessionProvider<WOSession>>() { }); }
/** * Make the binding of WOScopes. * * @see com.google.inject.AbstractModule#configure() */
Make the binding of WOScopes
configure
{ "repo_name": "hprange/woinject", "path": "src/main/java/com/woinject/WOInjectModule.java", "license": "apache-2.0", "size": 2591 }
[ "com.google.inject.TypeLiteral", "com.webobjects.appserver.WOSession" ]
import com.google.inject.TypeLiteral; import com.webobjects.appserver.WOSession;
import com.google.inject.*; import com.webobjects.appserver.*;
[ "com.google.inject", "com.webobjects.appserver" ]
com.google.inject; com.webobjects.appserver;
671,738
static public void registerClasses (final Kryo kryo) { kryo.register(Object[].class); kryo.register(InvokeMethod.class);
static void function (final Kryo kryo) { kryo.register(Object[].class); kryo.register(InvokeMethod.class);
/** Registers the classes needed to use ObjectSpaces. This should be called before any connections are opened. * @see Kryo#register(Class, Serializer) */
Registers the classes needed to use ObjectSpaces. This should be called before any connections are opened
registerClasses
{ "repo_name": "daniaki/projectZero", "path": "core/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java", "license": "gpl-2.0", "size": 26279 }
[ "com.esotericsoftware.kryo.Kryo" ]
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.*;
[ "com.esotericsoftware.kryo" ]
com.esotericsoftware.kryo;
2,637,992
@SmallTest public void testDataPipeTwoPhaseSend() { Random random = new Random(); Core core = CoreImpl.getInstance(); Pair<DataPipe.ProducerHandle, DataPipe.ConsumerHandle> handles = core.createDataPipe(null); addHandlePairToClose(handles); // Writing a random 8 bytes message. byte[] bytes = new byte[8]; random.nextBytes(bytes); ByteBuffer buffer = handles.first.beginWriteData(bytes.length, DataPipe.WriteFlags.NONE); assertTrue(buffer.capacity() >= bytes.length); buffer.put(bytes); handles.first.endWriteData(bytes.length); // Read into a buffer. ByteBuffer receiveBuffer = handles.second.beginReadData(bytes.length, DataPipe.ReadFlags.NONE); assertEquals(0, receiveBuffer.position()); assertEquals(bytes.length, receiveBuffer.limit()); byte[] receivedBytes = new byte[bytes.length]; receiveBuffer.get(receivedBytes); assertTrue(Arrays.equals(bytes, receivedBytes)); handles.second.endReadData(bytes.length); }
void function() { Random random = new Random(); Core core = CoreImpl.getInstance(); Pair<DataPipe.ProducerHandle, DataPipe.ConsumerHandle> handles = core.createDataPipe(null); addHandlePairToClose(handles); byte[] bytes = new byte[8]; random.nextBytes(bytes); ByteBuffer buffer = handles.first.beginWriteData(bytes.length, DataPipe.WriteFlags.NONE); assertTrue(buffer.capacity() >= bytes.length); buffer.put(bytes); handles.first.endWriteData(bytes.length); ByteBuffer receiveBuffer = handles.second.beginReadData(bytes.length, DataPipe.ReadFlags.NONE); assertEquals(0, receiveBuffer.position()); assertEquals(bytes.length, receiveBuffer.limit()); byte[] receivedBytes = new byte[bytes.length]; receiveBuffer.get(receivedBytes); assertTrue(Arrays.equals(bytes, receivedBytes)); handles.second.endReadData(bytes.length); }
/** * Testing {@link DataPipe}. */
Testing <code>DataPipe</code>
testDataPipeTwoPhaseSend
{ "repo_name": "junhuac/MQUIC", "path": "src/mojo/android/javatests/src/org/chromium/mojo/system/impl/CoreImplTest.java", "license": "mit", "size": 37021 }
[ "java.nio.ByteBuffer", "java.util.Arrays", "java.util.Random", "org.chromium.mojo.system.Core", "org.chromium.mojo.system.DataPipe", "org.chromium.mojo.system.Pair" ]
import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Random; import org.chromium.mojo.system.Core; import org.chromium.mojo.system.DataPipe; import org.chromium.mojo.system.Pair;
import java.nio.*; import java.util.*; import org.chromium.mojo.system.*;
[ "java.nio", "java.util", "org.chromium.mojo" ]
java.nio; java.util; org.chromium.mojo;
1,955,550
protected boolean canScroll(View v, boolean checkV, int dx, int dy, int x, int y) { if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int scrollX = v.getScrollX(); final int scrollY = v.getScrollY(); final int count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (int i = count - 1; i >= 0; i--) { // TODO: Add versioned support here for transformed views. // This will not work for transformed views in Honeycomb+ final View child = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && canScroll(child, true, dx, dy, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && (ViewCompat.canScrollHorizontally(v, -dx) || ViewCompat.canScrollVertically(v, -dy)); }
boolean function(View v, boolean checkV, int dx, int dy, int x, int y) { if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int scrollX = v.getScrollX(); final int scrollY = v.getScrollY(); final int count = group.getChildCount(); for (int i = count - 1; i >= 0; i--) { final View child = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && canScroll(child, true, dx, dy, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && (ViewCompat.canScrollHorizontally(v, -dx) ViewCompat.canScrollVertically(v, -dy)); }
/** * Tests scrollability within child views of v given a delta of dx. * * @param v View to test for horizontal scrollability * @param checkV Whether the view v passed should itself be checked for scrollability (true), * or just its children (false). * @param dx Delta scrolled in pixels along the X axis * @param dy Delta scrolled in pixels along the Y axis * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dx. */
Tests scrollability within child views of v given a delta of dx
canScroll
{ "repo_name": "axmadjon/AndroidLib", "path": "app/src/main/java/uz/support/v14/lib/slidingpanel/ViewDragHelper.java", "license": "apache-2.0", "size": 60196 }
[ "android.support.v4.view.ViewCompat", "android.view.View", "android.view.ViewGroup" ]
import android.support.v4.view.ViewCompat; import android.view.View; import android.view.ViewGroup;
import android.support.v4.view.*; import android.view.*;
[ "android.support", "android.view" ]
android.support; android.view;
1,995,359
public void unregisterRegion(ServerRegionProxy srp, boolean keepalive) { removeAllInterests(srp, InterestType.KEY, false, keepalive, false); removeAllInterests(srp, InterestType.FILTER_CLASS, false, keepalive, false); removeAllInterests(srp, InterestType.OQL_QUERY, false, keepalive, false); removeAllInterests(srp, InterestType.REGULAR_EXPRESSION, false, keepalive, false); removeAllInterests(srp, InterestType.KEY, false, keepalive, true); removeAllInterests(srp, InterestType.FILTER_CLASS, false, keepalive, true); removeAllInterests(srp, InterestType.OQL_QUERY, false, keepalive, true); removeAllInterests(srp, InterestType.REGULAR_EXPRESSION, false, keepalive, true); // durable if (srp.getPool().isDurableClient()) { removeAllInterests(srp, InterestType.KEY, true, keepalive, true); removeAllInterests(srp, InterestType.FILTER_CLASS, true, keepalive, true); removeAllInterests(srp, InterestType.OQL_QUERY, true, keepalive, true); removeAllInterests(srp, InterestType.REGULAR_EXPRESSION, true, keepalive, true); removeAllInterests(srp, InterestType.KEY, true, keepalive, false); removeAllInterests(srp, InterestType.FILTER_CLASS, true, keepalive, false); removeAllInterests(srp, InterestType.OQL_QUERY, true, keepalive, false); removeAllInterests(srp, InterestType.REGULAR_EXPRESSION, true, keepalive, false); } }
void function(ServerRegionProxy srp, boolean keepalive) { removeAllInterests(srp, InterestType.KEY, false, keepalive, false); removeAllInterests(srp, InterestType.FILTER_CLASS, false, keepalive, false); removeAllInterests(srp, InterestType.OQL_QUERY, false, keepalive, false); removeAllInterests(srp, InterestType.REGULAR_EXPRESSION, false, keepalive, false); removeAllInterests(srp, InterestType.KEY, false, keepalive, true); removeAllInterests(srp, InterestType.FILTER_CLASS, false, keepalive, true); removeAllInterests(srp, InterestType.OQL_QUERY, false, keepalive, true); removeAllInterests(srp, InterestType.REGULAR_EXPRESSION, false, keepalive, true); if (srp.getPool().isDurableClient()) { removeAllInterests(srp, InterestType.KEY, true, keepalive, true); removeAllInterests(srp, InterestType.FILTER_CLASS, true, keepalive, true); removeAllInterests(srp, InterestType.OQL_QUERY, true, keepalive, true); removeAllInterests(srp, InterestType.REGULAR_EXPRESSION, true, keepalive, true); removeAllInterests(srp, InterestType.KEY, true, keepalive, false); removeAllInterests(srp, InterestType.FILTER_CLASS, true, keepalive, false); removeAllInterests(srp, InterestType.OQL_QUERY, true, keepalive, false); removeAllInterests(srp, InterestType.REGULAR_EXPRESSION, true, keepalive, false); } }
/** * Unregisters everything registered on the given region name */
Unregisters everything registered on the given region name
unregisterRegion
{ "repo_name": "pivotal-amurmann/geode", "path": "geode-core/src/main/java/org/apache/geode/cache/client/internal/RegisterInterestTracker.java", "license": "apache-2.0", "size": 15000 }
[ "org.apache.geode.internal.cache.tier.InterestType" ]
import org.apache.geode.internal.cache.tier.InterestType;
import org.apache.geode.internal.cache.tier.*;
[ "org.apache.geode" ]
org.apache.geode;
648,672
Resolution resolve(MethodDescription methodDescription); enum NoOp implements MethodRebaseResolver { INSTANCE;
Resolution resolve(MethodDescription methodDescription); enum NoOp implements MethodRebaseResolver { INSTANCE;
/** * Checks if a method is eligible for rebasing and resolves this possibly rebased method. * * @param methodDescription A description of the method to resolve. * @return A resolution for the given method. */
Checks if a method is eligible for rebasing and resolves this possibly rebased method
resolve
{ "repo_name": "RobAustin/byte-buddy", "path": "byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/inline/MethodRebaseResolver.java", "license": "apache-2.0", "size": 16761 }
[ "net.bytebuddy.instrumentation.method.MethodDescription" ]
import net.bytebuddy.instrumentation.method.MethodDescription;
import net.bytebuddy.instrumentation.method.*;
[ "net.bytebuddy.instrumentation" ]
net.bytebuddy.instrumentation;
2,141,077
static Path getCompletedRecoveredEditsFilePath(Path srcPath, Long maximumEditLogSeqNum) { String fileName = formatRecoveredEditsFileName(maximumEditLogSeqNum); return new Path(srcPath.getParent(), fileName); }
static Path getCompletedRecoveredEditsFilePath(Path srcPath, Long maximumEditLogSeqNum) { String fileName = formatRecoveredEditsFileName(maximumEditLogSeqNum); return new Path(srcPath.getParent(), fileName); }
/** * Get the completed recovered edits file path, renaming it to be by last edit * in the file from its first edit. Then we could use the name to skip * recovered edits when doing {@link HRegion#replayRecoveredEditsIfAny}. * @param srcPath * @param maximumEditLogSeqNum * @return dstPath take file's last edit log seq num as the name */
Get the completed recovered edits file path, renaming it to be by last edit in the file from its first edit. Then we could use the name to skip recovered edits when doing <code>HRegion#replayRecoveredEditsIfAny</code>
getCompletedRecoveredEditsFilePath
{ "repo_name": "jyates/hbase", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogSplitter.java", "license": "apache-2.0", "size": 49758 }
[ "org.apache.hadoop.fs.Path" ]
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
652,482
@Override public void containerPropertySetChange( Container.PropertySetChangeEvent event) { firePropertySetChange(); }
void function( Container.PropertySetChangeEvent event) { firePropertySetChange(); }
/** * Notifies this listener that the Containers contents has changed. * * @see com.vaadin.data.Container.PropertySetChangeListener#containerPropertySetChange(com.vaadin.data.Container.PropertySetChangeEvent) */
Notifies this listener that the Containers contents has changed
containerPropertySetChange
{ "repo_name": "shahrzadmn/vaadin", "path": "server/src/com/vaadin/ui/AbstractSelect.java", "license": "apache-2.0", "size": 76691 }
[ "com.vaadin.data.Container" ]
import com.vaadin.data.Container;
import com.vaadin.data.*;
[ "com.vaadin.data" ]
com.vaadin.data;
2,806,143
@Test(dependsOnMethods = "testMultipleInmemoryJoinsSingleGroup") public void testSingleAggregatioinMultipleQueryJoins() throws InterruptedException { String siddhiApp = "@App:name('TestPlan10')" + "@App:description('Incremental aggregation distributed test cases.')\n" + "@source(type = 'http', receiver.url='http://localhost:8080/SweetProductionEP', " + "@map(type = 'json'))\n" + "define stream Test1Stream (symbol string, price float, lastClosingPrice float, volume long , " + "quantity int, timestamp long);\n" + "@source(type = 'http', receiver.url='http://localhost:8080/Stocks', @map(type = 'json'))\n" + "define stream Test2Stream (symbol string, price double, volume long, timestamp long);\n" + "@sink(type='log')\n" + "define stream Test4Stream (symbol string, avgPrice double, totalPrice double, lastTradeValue " + "float);\n" + "@source(type = 'http', receiver.url='http://localhost:8080/product', @map(type = 'json'))\n" + "define stream Test3Stream (symbol string, price double, volume long, timestamp long);\n" + "@store(type='rdbms', jdbc.url= '" + JDBC_URL + "', username='root', password= 'root', jdbc.driver" + ".name= '" + JDBC_DRIVER_NAME + "')\n" + "define aggregation queryAggregationTest1\n" + "from Test1Stream \n" + "select symbol, avg(price) as avgPrice, sum(price) as totalPrice, (price * quantity)" + "as lastTradeValue\n" + "group by symbol\n" + "aggregate by timestamp every sec...hour ;\n" + "@info(name = 'query-join1')@dist(execGroup='001', parallel = '2')\n" + "from Test3Stream as P join queryAggregationTest1 as Q\n" + "on P.symbol == Q.symbol\n" + "within '2017-06-** **:**:**'\n" + "per \"seconds\"\n" + "select P.symbol, Q.avgPrice, Q.totalPrice, Q.lastTradeValue\n" + "Insert into Test4Stream;\n" + "@info(name = 'query-join2')@dist(execGroup='002', parallel = '2')\n" + "from Test2Stream as P join queryAggregationTest1 as Q \n" + "on P.symbol == Q.symbol\n" + "within \"2014-02-15 00:00:00 +05:30\", \"2018-12-16 00:00:00 +05:30\"\n" + "per \"seconds\"\n" + "select P.symbol, Q.avgPrice, Q.totalPrice, Q.lastTradeValue\n" + "Insert into Test4Stream;"; SiddhiTopologyCreatorImpl siddhiTopologyCreator = new SiddhiTopologyCreatorImpl(); SiddhiTopology topology = siddhiTopologyCreator.createTopology(siddhiApp); SiddhiAppCreator appCreator = new JMSSiddhiAppCreator(); List<DeployableSiddhiQueryGroup> queryGroupList = appCreator.createApps(topology); SiddhiManager siddhiManager = new SiddhiManager(); Assert.assertEquals(queryGroupList.size(), 5); Assert.assertTrue(queryGroupList.get(0).getGroupName().contains("passthrough")); Assert.assertTrue(queryGroupList.get(1).getGroupName().contains("passthrough")); Assert.assertTrue(queryGroupList.get(2).getGroupName().contains("001")); Assert.assertTrue(queryGroupList.get(3).getGroupName().contains("002")); Assert.assertTrue(queryGroupList.get(4).getGroupName().contains("aggregation")); Map<String, List<SiddhiAppRuntime>> siddhiAppRuntimeMap = createSiddhiAppRuntimes(siddhiManager, queryGroupList); InputHandler test1StreamInputHandler = siddhiAppRuntimeMap.get(queryGroupList.get(4).getGroupName()).get(0) .getInputHandler("Test1Stream"); InputHandler test3StreamInputHandler = siddhiAppRuntimeMap.get(queryGroupList.get(2).getGroupName()).get(0) .getInputHandler("Test3Stream"); InputHandler test2StreamInputHandler = siddhiAppRuntimeMap.get(queryGroupList.get(3).getGroupName()).get(0) .getInputHandler("Test2Stream"); test1StreamInputHandler.send(new Object[]{"WSO2", 50f, 60f, 90L, 6, 1496289950000L}); test1StreamInputHandler.send(new Object[]{"WSO2", 70f, null, 40L, 10, 1496289950000L}); test1StreamInputHandler.send(new Object[]{"WSO2", 60f, 44f, 200L, 56, 1496289952000L}); test1StreamInputHandler.send(new Object[]{"WSO2", 100f, null, 200L, 16, 1496289952000L}); test1StreamInputHandler.send(new Object[]{"IBM", 100f, null, 200L, 26, 1496289954000L}); test1StreamInputHandler.send(new Object[]{"IBM", 100f, null, 200L, 96, 1496289954000L}); Thread.sleep(5000);
@Test(dependsOnMethods = STR) void function() throws InterruptedException { String siddhiApp = STR + STR + STR@map(type = 'json'))\nSTRdefine stream Test1Stream (symbol string, price float, lastClosingPrice float, volume long , STRquantity int, timestamp long);\n" + STRdefine stream Test2Stream (symbol string, price double, volume long, timestamp long);\nSTR@sink(type='log')\nSTRdefine stream Test4Stream (symbol string, avgPrice double, totalPrice double, lastTradeValue STRfloat);\n" + STRdefine stream Test3Stream (symbol string, price double, volume long, timestamp long);\nSTR@store(type='rdbms', jdbc.url= 'STR', username='root', password= 'root', jdbc.driverSTR.name= 'STR')\nSTRdefine aggregation queryAggregationTest1\nSTRfrom Test1Stream \nSTRselect symbol, avg(price) as avgPrice, sum(price) as totalPrice, (price * quantity)STRas lastTradeValue\nSTRgroup by symbol\nSTRaggregate by timestamp every sec...hour ;\nSTR@info(name = 'query-join1')@dist(execGroup='001', parallel = '2')\nSTRfrom Test3Stream as P join queryAggregationTest1 as Q\nSTRon P.symbol == Q.symbol\nSTRwithin '2017-06-** **:**:**'\nSTRper \STR\nSTRselect P.symbol, Q.avgPrice, Q.totalPrice, Q.lastTradeValue\nSTRInsert into Test4Stream;\nSTR@info(name = 'query-join2')@dist(execGroup='002', parallel = '2')\nSTRfrom Test2Stream as P join queryAggregationTest1 as Q \nSTRon P.symbol == Q.symbol\nSTRwithin \STR, \STR\nSTRper \STR\nSTRselect P.symbol, Q.avgPrice, Q.totalPrice, Q.lastTradeValue\nSTRInsert into Test4Stream;STRpassthroughSTRpassthroughSTR001STR002STRaggregationSTRTest1StreamSTRTest3StreamSTRTest2StreamSTRWSO2STRWSO2STRWSO2STRWSO2STRIBMSTRIBM", 100f, null, 200L, 96, 1496289954000L}); Thread.sleep(5000);
/** * Test the behavior when multiple queries joins with single aggregation. */
Test the behavior when multiple queries joins with single aggregation
testSingleAggregatioinMultipleQueryJoins
{ "repo_name": "minudika/carbon-analytics", "path": "components/org.wso2.carbon.sp.jobmanager.core/src/test/java/org/wso2/carbon/sp/jobmanager/core/DistributedAggregationTestCase.java", "license": "apache-2.0", "size": 98636 }
[ "org.testng.annotations.Test" ]
import org.testng.annotations.Test;
import org.testng.annotations.*;
[ "org.testng.annotations" ]
org.testng.annotations;
1,797,289
String notificationWarning(); } @Shared public interface I_CmsOpenerHoverCss extends CssResource {
String notificationWarning(); } public interface I_CmsOpenerHoverCss extends CssResource {
/** * Access method.<p> * * @return the CSS class name */
Access method
notificationWarning
{ "repo_name": "alkacon/opencms-core", "path": "src-gwt/org/opencms/gwt/client/ui/css/I_CmsLayoutBundle.java", "license": "lgpl-2.1", "size": 52204 }
[ "com.google.gwt.resources.client.CssResource" ]
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.*;
[ "com.google.gwt" ]
com.google.gwt;
2,869,520
@Override public synchronized void end(Xid xid, int flag) throws XAException { if (xid == null) { throw new NullPointerException("xid is null"); } if (!this.currentXid.equals(xid)) { throw new XAException("Invalid Xid: expected " + this.currentXid + ", but was " + xid); } // This notification tells us that the application server is done using this // connection for the time being. The connection is still associated with an // open transaction, so we must still wait for the commit or rollback method }
synchronized void function(Xid xid, int flag) throws XAException { if (xid == null) { throw new NullPointerException(STR); } if (!this.currentXid.equals(xid)) { throw new XAException(STR + this.currentXid + STR + xid); } }
/** * This method does nothing. * * @param xid the id of the transaction branch for this connection * @param flag ignored * @throws XAException if the connection is already enlisted in another transaction */
This method does nothing
end
{ "repo_name": "bbossgroups/bbossgroups-3.5", "path": "bboss-persistent/src-jdk7/com/frameworkset/commons/dbcp2/managed/LocalXAConnectionFactory.java", "license": "apache-2.0", "size": 13897 }
[ "javax.transaction.xa.XAException", "javax.transaction.xa.Xid" ]
import javax.transaction.xa.XAException; import javax.transaction.xa.Xid;
import javax.transaction.xa.*;
[ "javax.transaction" ]
javax.transaction;
2,351,027
default void afterCreateQueue(Queue queue) throws ActiveMQException { }
default void afterCreateQueue(Queue queue) throws ActiveMQException { }
/** * After a queue has been created * * @param queue The newly created queue * @throws ActiveMQException */
After a queue has been created
afterCreateQueue
{ "repo_name": "mnovak1/activemq-artemis", "path": "artemis-server/src/main/java/org/apache/activemq/artemis/core/server/plugin/ActiveMQServerPlugin.java", "license": "apache-2.0", "size": 16642 }
[ "org.apache.activemq.artemis.api.core.ActiveMQException", "org.apache.activemq.artemis.core.server.Queue" ]
import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.api.core.*; import org.apache.activemq.artemis.core.server.*;
[ "org.apache.activemq" ]
org.apache.activemq;
1,466,134
private int resolveConstructorArguments( String beanName, RootBeanDefinition mbd, BeanWrapper bw, ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) { TypeConverter converterToUse = (this.typeConverter != null ? this.typeConverter : bw); BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converterToUse); int minNrOfArgs = cargs.getArgumentCount(); for (Iterator it = cargs.getIndexedArgumentValues().entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); int index = ((Integer) entry.getKey()).intValue(); if (index < 0) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid constructor argument index: " + index); } if (index > minNrOfArgs) { minNrOfArgs = index + 1; } ConstructorArgumentValues.ValueHolder valueHolder = (ConstructorArgumentValues.ValueHolder) entry.getValue(); if (valueHolder.isConverted()) { resolvedValues.addIndexedArgumentValue(index, valueHolder); } else { Object resolvedValue = valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue()); ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType()); resolvedValueHolder.setSource(valueHolder); resolvedValues.addIndexedArgumentValue(index, resolvedValueHolder); } } for (Iterator it = cargs.getGenericArgumentValues().iterator(); it.hasNext();) { ConstructorArgumentValues.ValueHolder valueHolder = (ConstructorArgumentValues.ValueHolder) it.next(); if (valueHolder.isConverted()) { resolvedValues.addGenericArgumentValue(valueHolder); } else { Object resolvedValue = valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue()); ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType()); resolvedValueHolder.setSource(valueHolder); resolvedValues.addGenericArgumentValue(resolvedValueHolder); } } return minNrOfArgs; }
int function( String beanName, RootBeanDefinition mbd, BeanWrapper bw, ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) { TypeConverter converterToUse = (this.typeConverter != null ? this.typeConverter : bw); BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converterToUse); int minNrOfArgs = cargs.getArgumentCount(); for (Iterator it = cargs.getIndexedArgumentValues().entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); int index = ((Integer) entry.getKey()).intValue(); if (index < 0) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, STR + index); } if (index > minNrOfArgs) { minNrOfArgs = index + 1; } ConstructorArgumentValues.ValueHolder valueHolder = (ConstructorArgumentValues.ValueHolder) entry.getValue(); if (valueHolder.isConverted()) { resolvedValues.addIndexedArgumentValue(index, valueHolder); } else { Object resolvedValue = valueResolver.resolveValueIfNecessary(STR, valueHolder.getValue()); ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType()); resolvedValueHolder.setSource(valueHolder); resolvedValues.addIndexedArgumentValue(index, resolvedValueHolder); } } for (Iterator it = cargs.getGenericArgumentValues().iterator(); it.hasNext();) { ConstructorArgumentValues.ValueHolder valueHolder = (ConstructorArgumentValues.ValueHolder) it.next(); if (valueHolder.isConverted()) { resolvedValues.addGenericArgumentValue(valueHolder); } else { Object resolvedValue = valueResolver.resolveValueIfNecessary(STR, valueHolder.getValue()); ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType()); resolvedValueHolder.setSource(valueHolder); resolvedValues.addGenericArgumentValue(resolvedValueHolder); } } return minNrOfArgs; }
/** * Resolve the constructor arguments for this bean into the resolvedValues object. * This may involve looking up other beans. * This method is also used for handling invocations of static factory methods. */
Resolve the constructor arguments for this bean into the resolvedValues object. This may involve looking up other beans. This method is also used for handling invocations of static factory methods
resolveConstructorArguments
{ "repo_name": "cbeams-archive/spring-framework-2.5.x", "path": "src/org/springframework/beans/factory/support/ConstructorResolver.java", "license": "apache-2.0", "size": 26361 }
[ "java.util.Iterator", "java.util.Map", "org.springframework.beans.BeanWrapper", "org.springframework.beans.TypeConverter", "org.springframework.beans.factory.BeanCreationException", "org.springframework.beans.factory.config.ConstructorArgumentValues" ]
import java.util.Iterator; import java.util.Map; import org.springframework.beans.BeanWrapper; import org.springframework.beans.TypeConverter; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.ConstructorArgumentValues;
import java.util.*; import org.springframework.beans.*; import org.springframework.beans.factory.*; import org.springframework.beans.factory.config.*;
[ "java.util", "org.springframework.beans" ]
java.util; org.springframework.beans;
2,686,288
public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName) throws BeansException { CachedIntrospectionResults cr = CachedIntrospectionResults.forClass(clazz); return cr.getPropertyDescriptor(propertyName); }
static PropertyDescriptor function(Class<?> clazz, String propertyName) throws BeansException { CachedIntrospectionResults cr = CachedIntrospectionResults.forClass(clazz); return cr.getPropertyDescriptor(propertyName); }
/** * Retrieve the JavaBeans {@code PropertyDescriptors} for the given property. * @param clazz the Class to retrieve the PropertyDescriptor for * @param propertyName the name of the property * @return the corresponding PropertyDescriptor, or {@code null} if none * @throws BeansException if PropertyDescriptor lookup fails */
Retrieve the JavaBeans PropertyDescriptors for the given property
getPropertyDescriptor
{ "repo_name": "shivpun/spring-framework", "path": "spring-beans/java/org/springframework/beans/BeanUtils.java", "license": "apache-2.0", "size": 26557 }
[ "java.beans.PropertyDescriptor" ]
import java.beans.PropertyDescriptor;
import java.beans.*;
[ "java.beans" ]
java.beans;
1,241,302
public Page<Member> paginate(int page, int pageSize);
Page<Member> function(int page, int pageSize);
/** * paginate query * * @param page * @param pageSize * @return */
paginate query
paginate
{ "repo_name": "JpressProjects/jpress", "path": "jpress-service-api/src/main/java/io/jpress/service/MemberService.java", "license": "lgpl-3.0", "size": 1444 }
[ "com.jfinal.plugin.activerecord.Page", "io.jpress.model.Member" ]
import com.jfinal.plugin.activerecord.Page; import io.jpress.model.Member;
import com.jfinal.plugin.activerecord.*; import io.jpress.model.*;
[ "com.jfinal.plugin", "io.jpress.model" ]
com.jfinal.plugin; io.jpress.model;
1,223,690
private String getArgToolTipText(int argNum, Argument.Status argStatus) { Argument.NameTypePair[] arguments = codeGem.getArguments(); String argName = arguments[argNum].getName(); StringBuilder text = new StringBuilder(); text.append("<html><body>"); if (argStatus != Argument.Status.TYPE_CLASH) { TypeExpr argType = codeGem.getInputPart(argNum).getType(); String argTypeText = getArgTypeText(argType, argStatus); boolean separateText = false; // Check if argument name / type lines must be separated { String completeText = argName + " :: " + argTypeText; if (ToolTipHelpers.wrapTextToHTMLLines(completeText, gemCodePanel).length() != completeText.length()) { // Text cut because name or type is over the tooltip limit; // so display each on separate lines separateText = true; } } text.append("<b>" + ToolTipHelpers.wrapTextToHTMLLines(argName, gemCodePanel) + "</b> :: "); if (separateText) { text.append("<br>"); } text.append("<i>" + ToolTipHelpers.wrapTextToHTMLLines(argTypeText, gemCodePanel) + "</i>"); } else { PartInput input = codeGem.getInputPart(argNum); TypeExpr argType = arguments[argNum].getType(); TypeExpr inferredInputType = incompatiblePartToInferredTypeMap.get(input); text.append(GemCutterMessages.getString("CGE_WrongArgTypeToolTip", ToolTipHelpers.wrapTextToHTMLLines(inferredInputType.toString(), gemCodePanel), ToolTipHelpers.wrapTextToHTMLLines(argType.toString(), gemCodePanel))); } text.append("</body></html>"); return text.toString(); }
String function(int argNum, Argument.Status argStatus) { Argument.NameTypePair[] arguments = codeGem.getArguments(); String argName = arguments[argNum].getName(); StringBuilder text = new StringBuilder(); text.append(STR); if (argStatus != Argument.Status.TYPE_CLASH) { TypeExpr argType = codeGem.getInputPart(argNum).getType(); String argTypeText = getArgTypeText(argType, argStatus); boolean separateText = false; { String completeText = argName + STR + argTypeText; if (ToolTipHelpers.wrapTextToHTMLLines(completeText, gemCodePanel).length() != completeText.length()) { separateText = true; } } text.append("<b>" + ToolTipHelpers.wrapTextToHTMLLines(argName, gemCodePanel) + STR); if (separateText) { text.append("<br>"); } text.append("<i>" + ToolTipHelpers.wrapTextToHTMLLines(argTypeText, gemCodePanel) + "</i>"); } else { PartInput input = codeGem.getInputPart(argNum); TypeExpr argType = arguments[argNum].getType(); TypeExpr inferredInputType = incompatiblePartToInferredTypeMap.get(input); text.append(GemCutterMessages.getString(STR, ToolTipHelpers.wrapTextToHTMLLines(inferredInputType.toString(), gemCodePanel), ToolTipHelpers.wrapTextToHTMLLines(argType.toString(), gemCodePanel))); } text.append(STR); return text.toString(); }
/** * Get the tooltip text for a given argument. This takes the state of the * code gem (eg. connection, burn info) into account. * * @param argNum * the index of the argument * @param argStatus * the status of the argument * @return the tooltip text for the given argument. */
Get the tooltip text for a given argument. This takes the state of the code gem (eg. connection, burn info) into account
getArgToolTipText
{ "repo_name": "levans/Open-Quark", "path": "src/Quark_Gems/src/org/openquark/gems/client/CodeGemEditor.java", "license": "bsd-3-clause", "size": 145683 }
[ "org.openquark.cal.compiler.TypeExpr", "org.openquark.gems.client.Argument", "org.openquark.gems.client.Gem" ]
import org.openquark.cal.compiler.TypeExpr; import org.openquark.gems.client.Argument; import org.openquark.gems.client.Gem;
import org.openquark.cal.compiler.*; import org.openquark.gems.client.*;
[ "org.openquark.cal", "org.openquark.gems" ]
org.openquark.cal; org.openquark.gems;
410,783
@Test public void testAddFileExtensionSeparator() { String testValue = "abcxyz"; String actual = ExternalFilenames.addFileExtensionSeparator(testValue); assertEquals("." + testValue, actual); }
void function() { String testValue = STR; String actual = ExternalFilenames.addFileExtensionSeparator(testValue); assertEquals("." + testValue, actual); }
/** * Test method for {@link * com.sldeditor.common.utils.ExternalFilenames#addFileExtensionSeparator(java.lang.String)}. */
Test method for <code>com.sldeditor.common.utils.ExternalFilenames#addFileExtensionSeparator(java.lang.String)</code>
testAddFileExtensionSeparator
{ "repo_name": "robward-scisys/sldeditor", "path": "modules/application/src/test/java/com/sldeditor/test/unit/common/utils/ExternalFilenamesTest.java", "license": "gpl-3.0", "size": 9890 }
[ "com.sldeditor.common.utils.ExternalFilenames", "org.junit.jupiter.api.Assertions" ]
import com.sldeditor.common.utils.ExternalFilenames; import org.junit.jupiter.api.Assertions;
import com.sldeditor.common.utils.*; import org.junit.jupiter.api.*;
[ "com.sldeditor.common", "org.junit.jupiter" ]
com.sldeditor.common; org.junit.jupiter;
2,598,291
@Override public Dimension getPreferredSize() { return this.preferredSize; }
Dimension function() { return this.preferredSize; }
/** * Returns the preferred size of the component. * * @return the preferred size of the component. */
Returns the preferred size of the component
getPreferredSize
{ "repo_name": "jfree/jfreechart", "path": "src/main/java/org/jfree/chart/swing/editor/StrokeSample.java", "license": "lgpl-2.1", "size": 5001 }
[ "java.awt.Dimension" ]
import java.awt.Dimension;
import java.awt.*;
[ "java.awt" ]
java.awt;
1,400,125
public void notifyViews() { for (ViewInterface view : views) { view.update(); } }
void function() { for (ViewInterface view : views) { view.update(); } }
/** * updates views * */
updates views
notifyViews
{ "repo_name": "CMPUT301W15T03/Team3ScandalouStopwatch", "path": "ScandalouTravelTracker/ScandalouTravelTracker/src/ca/ualberta/cs/scandaloutraveltracker/models/SModel.java", "license": "apache-2.0", "size": 1462 }
[ "ca.ualberta.cs.scandaloutraveltracker.views.ViewInterface" ]
import ca.ualberta.cs.scandaloutraveltracker.views.ViewInterface;
import ca.ualberta.cs.scandaloutraveltracker.views.*;
[ "ca.ualberta.cs" ]
ca.ualberta.cs;
1,379,528
protected void scanPath(File file) { String path = file.getAbsolutePath(); if (StringUtil.endsWithIgnoreCase(path, JAR_FILE_EXT) == true) { if (acceptJar(file) == false) { return; } scanJarFile(file); } else if (file.isDirectory() == true) { scanClassPath(file); } } // ---------------------------------------------------------------- internal
void function(File file) { String path = file.getAbsolutePath(); if (StringUtil.endsWithIgnoreCase(path, JAR_FILE_EXT) == true) { if (acceptJar(file) == false) { return; } scanJarFile(file); } else if (file.isDirectory() == true) { scanClassPath(file); } }
/** * Scans single path. */
Scans single path
scanPath
{ "repo_name": "Artemish/jodd", "path": "jodd-core/src/main/java/jodd/io/findfile/ClassFinder.java", "license": "bsd-3-clause", "size": 13757 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
2,161,389
@Override public void init() throws ServletException { setDBManager(getClass().getClassLoader()); try { InitialContext initContext = new InitialContext(); this.ds = (DataSource) initContext.lookup("java:comp/env/jdbc/users"); } catch (NamingException e) { e.printStackTrace(); } }
void function() throws ServletException { setDBManager(getClass().getClassLoader()); try { InitialContext initContext = new InitialContext(); this.ds = (DataSource) initContext.lookup(STR); } catch (NamingException e) { e.printStackTrace(); } }
/** * Init servlet. * * @throws ServletException error */
Init servlet
init
{ "repo_name": "degauhta/dgagarsky", "path": "chapter_009/lesson_2/src/main/java/ru/dega/servlets/UsersServlet.java", "license": "apache-2.0", "size": 7098 }
[ "javax.naming.InitialContext", "javax.naming.NamingException", "javax.servlet.ServletException", "javax.sql.DataSource" ]
import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.sql.DataSource;
import javax.naming.*; import javax.servlet.*; import javax.sql.*;
[ "javax.naming", "javax.servlet", "javax.sql" ]
javax.naming; javax.servlet; javax.sql;
1,335,436
public HashMap<String, String> getDeviceCommands(String itemName);
HashMap<String, String> function(String itemName);
/** * Returns all commands to the given <code>itemName</code>. * * @param itemName * the item for which to find a command. * * @return the corresponding list of commands or <code>null</code> if no commands * could be found. */
Returns all commands to the given <code>itemName</code>
getDeviceCommands
{ "repo_name": "paolodenti/openhab", "path": "bundles/binding/org.openhab.binding.primare/src/main/java/org/openhab/binding/primare/PrimareBindingProvider.java", "license": "epl-1.0", "size": 2200 }
[ "java.util.HashMap" ]
import java.util.HashMap;
import java.util.*;
[ "java.util" ]
java.util;
943,869
public void stopReplicationService() throws Exception { if (false == isAutoRecoveryEnabled()) { return; } for (Entry<BookieServer, AutoRecoveryMain> autoRecoveryProcess : autoRecoveryProcesses.entrySet()) { autoRecoveryProcess.getValue().shutdown(); LOG.debug("Shutdown Auditor Recovery for the bookie:" + autoRecoveryProcess.getKey().getLocalAddress()); } }
void function() throws Exception { if (false == isAutoRecoveryEnabled()) { return; } for (Entry<BookieServer, AutoRecoveryMain> autoRecoveryProcess : autoRecoveryProcesses.entrySet()) { autoRecoveryProcess.getValue().shutdown(); LOG.debug(STR + autoRecoveryProcess.getKey().getLocalAddress()); } }
/** * Will stops all the auto recovery processes for the bookie cluster, if isAutoRecoveryEnabled is true. */
Will stops all the auto recovery processes for the bookie cluster, if isAutoRecoveryEnabled is true
stopReplicationService
{ "repo_name": "massakam/pulsar", "path": "managed-ledger/src/test/java/org/apache/bookkeeper/test/BookKeeperClusterTestCase.java", "license": "apache-2.0", "size": 19088 }
[ "java.util.Map", "org.apache.bookkeeper.proto.BookieServer", "org.apache.bookkeeper.replication.AutoRecoveryMain" ]
import java.util.Map; import org.apache.bookkeeper.proto.BookieServer; import org.apache.bookkeeper.replication.AutoRecoveryMain;
import java.util.*; import org.apache.bookkeeper.proto.*; import org.apache.bookkeeper.replication.*;
[ "java.util", "org.apache.bookkeeper" ]
java.util; org.apache.bookkeeper;
2,220,165
public StoredContext newStoredContext(boolean preserveResponseHeaders) { final ThreadContextStruct context = threadLocal.get(); return () -> { if (preserveResponseHeaders && threadLocal.get() != context) { threadLocal.set(context.putResponseHeaders(threadLocal.get().responseHeaders)); } else { threadLocal.set(context); } }; } /** * Returns a supplier that gathers a {@link #newStoredContext(boolean)} and restores it once the * returned supplier is invoked. The context returned from the supplier is a stored version of the * suppliers callers context that should be restored once the originally gathered context is not needed anymore. * For instance this method should be used like this: * * <pre> * Supplier&lt;ThreadContext.StoredContext&gt; restorable = context.newRestorableContext(true); * new Thread() { * public void run() { * try (ThreadContext.StoredContext ctx = restorable.get()) { * // execute with the parents context and restore the threads context afterwards * } * }
StoredContext function(boolean preserveResponseHeaders) { final ThreadContextStruct context = threadLocal.get(); return () -> { if (preserveResponseHeaders && threadLocal.get() != context) { threadLocal.set(context.putResponseHeaders(threadLocal.get().responseHeaders)); } else { threadLocal.set(context); } }; } /** * Returns a supplier that gathers a {@link #newStoredContext(boolean)} and restores it once the * returned supplier is invoked. The context returned from the supplier is a stored version of the * suppliers callers context that should be restored once the originally gathered context is not needed anymore. * For instance this method should be used like this: * * <pre> * Supplier&lt;ThreadContext.StoredContext&gt; restorable = context.newRestorableContext(true); * new Thread() { * public void run() { * try (ThreadContext.StoredContext ctx = restorable.get()) { * * } * }
/** * Just like {@link #stashContext()} but no default context is set. * @param preserveResponseHeaders if set to <code>true</code> the response headers of the restore thread will be preserved. */
Just like <code>#stashContext()</code> but no default context is set
newStoredContext
{ "repo_name": "artnowo/elasticsearch", "path": "core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java", "license": "apache-2.0", "size": 25042 }
[ "java.util.function.Supplier" ]
import java.util.function.Supplier;
import java.util.function.*;
[ "java.util" ]
java.util;
113,871
@Test public void indexTrackerUpdatesAndNRT() throws Exception{ LuceneIndexDefinitionBuilder idx = new LuceneIndexDefinitionBuilder(); idx.indexRule("nt:base").property("foo").propertyIndex(); idx.async("async", "nrt"); NRTIndexFactory nrtFactory = new NRTIndexFactory(indexCopier, Clock.SIMPLE, 0 , StatisticsProvider.NOOP); runMultiReaderScenario(idx, nrtFactory, true); }
void function() throws Exception{ LuceneIndexDefinitionBuilder idx = new LuceneIndexDefinitionBuilder(); idx.indexRule(STR).property("foo").propertyIndex(); idx.async("async", "nrt"); NRTIndexFactory nrtFactory = new NRTIndexFactory(indexCopier, Clock.SIMPLE, 0 , StatisticsProvider.NOOP); runMultiReaderScenario(idx, nrtFactory, true); }
/** * This test enables 1 more thread which updates the IndexTracker * This causes the IndexNodeManager to switch to newer indexes * and hence lead to creation and closing of older NRTIndexes */
This test enables 1 more thread which updates the IndexTracker This causes the IndexNodeManager to switch to newer indexes and hence lead to creation and closing of older NRTIndexes
indexTrackerUpdatesAndNRT
{ "repo_name": "trekawek/jackrabbit-oak", "path": "oak-lucene/src/test/java/org/apache/jackrabbit/oak/plugins/index/lucene/hybrid/ReaderRefCountIT.java", "license": "apache-2.0", "size": 8543 }
[ "org.apache.jackrabbit.oak.plugins.index.lucene.util.LuceneIndexDefinitionBuilder", "org.apache.jackrabbit.oak.stats.Clock", "org.apache.jackrabbit.oak.stats.StatisticsProvider" ]
import org.apache.jackrabbit.oak.plugins.index.lucene.util.LuceneIndexDefinitionBuilder; import org.apache.jackrabbit.oak.stats.Clock; import org.apache.jackrabbit.oak.stats.StatisticsProvider;
import org.apache.jackrabbit.oak.plugins.index.lucene.util.*; import org.apache.jackrabbit.oak.stats.*;
[ "org.apache.jackrabbit" ]
org.apache.jackrabbit;
1,877,457
public Object [] getScriptResults(User loggedInUser, Integer actionId) { ScriptRunAction action = lookupScriptRunAction(actionId, loggedInUser); ScriptActionDetails details = action.getScriptActionDetails(); if (details.getResults() == null) { return new Object [] {}; } List<ScriptResult> results = new LinkedList<ScriptResult>(); for (Iterator<ScriptResult> it = details.getResults().iterator(); it .hasNext();) { ScriptResult r = it.next(); results.add(r); } return results.toArray(); }
Object [] function(User loggedInUser, Integer actionId) { ScriptRunAction action = lookupScriptRunAction(actionId, loggedInUser); ScriptActionDetails details = action.getScriptActionDetails(); if (details.getResults() == null) { return new Object [] {}; } List<ScriptResult> results = new LinkedList<ScriptResult>(); for (Iterator<ScriptResult> it = details.getResults().iterator(); it .hasNext();) { ScriptResult r = it.next(); results.add(r); } return results.toArray(); }
/** * Fetch results from a script execution. Returns an empty array if no results are * yet available. * * @param loggedInUser The current user * @param actionId ID of the script run action. * @return Array of ScriptResult objects. * * @xmlrpc.doc Fetch results from a script execution. Returns an empty array if no * results are yet available. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("int", "actionId", "ID of the script run action.") * @xmlrpc.returntype * #array() * $ScriptResultSerializer * #array_end() */
Fetch results from a script execution. Returns an empty array if no results are yet available
getScriptResults
{ "repo_name": "jhutar/spacewalk", "path": "java/code/src/com/redhat/rhn/frontend/xmlrpc/system/SystemHandler.java", "license": "gpl-2.0", "size": 241022 }
[ "com.redhat.rhn.domain.action.script.ScriptActionDetails", "com.redhat.rhn.domain.action.script.ScriptResult", "com.redhat.rhn.domain.action.script.ScriptRunAction", "com.redhat.rhn.domain.user.User", "java.util.Iterator", "java.util.LinkedList", "java.util.List" ]
import com.redhat.rhn.domain.action.script.ScriptActionDetails; import com.redhat.rhn.domain.action.script.ScriptResult; import com.redhat.rhn.domain.action.script.ScriptRunAction; import com.redhat.rhn.domain.user.User; import java.util.Iterator; import java.util.LinkedList; import java.util.List;
import com.redhat.rhn.domain.action.script.*; import com.redhat.rhn.domain.user.*; import java.util.*;
[ "com.redhat.rhn", "java.util" ]
com.redhat.rhn; java.util;
182,528
//////////////////////////////////////// Private Methods /////////////////////////////////////// private String parseDDfile(URI raDDAddress) { final String methodName = "parseDDfile"; final boolean trace = TraceComponent.isAnyTracingEnabled(); boolean isIssue = false; StringWriter result = new StringWriter(); final AtomicReference<Exception> exceptionRef = new AtomicReference<Exception>(); final File file = new File(raDDAddress); BufferedInputStream bin = null; ZipFile zipFile = null; XMLStreamReader xmlStreamReader = null;
String function(URI raDDAddress) { final String methodName = STR; final boolean trace = TraceComponent.isAnyTracingEnabled(); boolean isIssue = false; StringWriter result = new StringWriter(); final AtomicReference<Exception> exceptionRef = new AtomicReference<Exception>(); final File file = new File(raDDAddress); BufferedInputStream bin = null; ZipFile zipFile = null; XMLStreamReader xmlStreamReader = null;
/** * parseDDfile will try to read the ra.xml and parse it into a String. If it fails, it will return null * or whatever it managed to read from the ra.xml. If the reading succeed partially, the returned value * will be tailed with a warning massage explaining what happened. * * @param raDDAddress String representing the full path to the directory of the RAR file. * @return The content of the ra.xml file as a String */
parseDDfile will try to read the ra.xml and parse it into a String. If it fails, it will return null or whatever it managed to read from the ra.xml. If the reading succeed partially, the returned value will be tailed with a warning massage explaining what happened
parseDDfile
{ "repo_name": "OpenLiberty/open-liberty", "path": "dev/com.ibm.ws.jca.management.j2ee/src/com/ibm/ws/jca/management/j2ee/internal/ResourceAdapterModuleMBeanImpl.java", "license": "epl-1.0", "size": 22294 }
[ "com.ibm.websphere.ras.TraceComponent", "java.io.BufferedInputStream", "java.io.File", "java.io.StringWriter", "java.util.concurrent.atomic.AtomicReference", "java.util.zip.ZipFile", "javax.xml.stream.XMLStreamReader" ]
import com.ibm.websphere.ras.TraceComponent; import java.io.BufferedInputStream; import java.io.File; import java.io.StringWriter; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.ZipFile; import javax.xml.stream.XMLStreamReader;
import com.ibm.websphere.ras.*; import java.io.*; import java.util.concurrent.atomic.*; import java.util.zip.*; import javax.xml.stream.*;
[ "com.ibm.websphere", "java.io", "java.util", "javax.xml" ]
com.ibm.websphere; java.io; java.util; javax.xml;
2,046,518
public void setMarkAllHighlightColor(Color color) { Color old = (Color)markAllHighlightPainter.getPaint(); if (old!=null && !old.equals(color)) { markAllHighlightPainter.setPaint(color); RTextAreaHighlighter h = (RTextAreaHighlighter)getHighlighter(); if (h.getMarkAllHighlightCount()>0) { repaint(); // Repaint if words are highlighted. } firePropertyChange(MARK_ALL_COLOR_PROPERTY, old, color); } }
void function(Color color) { Color old = (Color)markAllHighlightPainter.getPaint(); if (old!=null && !old.equals(color)) { markAllHighlightPainter.setPaint(color); RTextAreaHighlighter h = (RTextAreaHighlighter)getHighlighter(); if (h.getMarkAllHighlightCount()>0) { repaint(); } firePropertyChange(MARK_ALL_COLOR_PROPERTY, old, color); } }
/** * Sets the color used for "mark all." This fires a property change of * type {@link #MARK_ALL_COLOR_PROPERTY}. * * @param color The color to use for "mark all." * @see #getMarkAllHighlightColor() */
Sets the color used for "mark all." This fires a property change of type <code>#MARK_ALL_COLOR_PROPERTY</code>
setMarkAllHighlightColor
{ "repo_name": "intuit/Tank", "path": "tools/agent_debugger/src/main/java/org/fife/ui/rtextarea/RTextArea.java", "license": "epl-1.0", "size": 50361 }
[ "java.awt.Color" ]
import java.awt.Color;
import java.awt.*;
[ "java.awt" ]
java.awt;
1,805,795
private void sendCustomizedMessages(final CustomizedMessage customizedMessage) throws HttpException, InsufficientQuotaException { final Integer messageId = customizedMessage.getMessageId(); final Integer senderId = customizedMessage.getSenderId(); final Integer groupSenderId = customizedMessage.getGroupSenderId(); final Integer serviceId = customizedMessage.getServiceId(); final String recipiendPhoneNumber = customizedMessage.getRecipiendPhoneNumber(); final String userLabelAccount = customizedMessage.getUserAccountLabel(); final String message = customizedMessage.getMessage(); if (logger.isDebugEnabled()) { logger.debug("Sending to back office message with : " + " - message id = " + messageId + " - sender id = " + senderId + " - group sender id = " + groupSenderId + " - service id = " + serviceId + " - recipient phone number = " + recipiendPhoneNumber + " - user label account = " + userLabelAccount + " - message = " + message); } // send the message to the back office smsuapiWS.sendSMS(messageId, senderId, recipiendPhoneNumber, userLabelAccount, message); }
void function(final CustomizedMessage customizedMessage) throws HttpException, InsufficientQuotaException { final Integer messageId = customizedMessage.getMessageId(); final Integer senderId = customizedMessage.getSenderId(); final Integer groupSenderId = customizedMessage.getGroupSenderId(); final Integer serviceId = customizedMessage.getServiceId(); final String recipiendPhoneNumber = customizedMessage.getRecipiendPhoneNumber(); final String userLabelAccount = customizedMessage.getUserAccountLabel(); final String message = customizedMessage.getMessage(); if (logger.isDebugEnabled()) { logger.debug(STR + STR + messageId + STR + senderId + STR + groupSenderId + STR + serviceId + STR + recipiendPhoneNumber + STR + userLabelAccount + STR + message); } smsuapiWS.sendSMS(messageId, senderId, recipiendPhoneNumber, userLabelAccount, message); }
/** * Send the customized message to the back office. * @param customizedMessage * @throws InsufficientQuotaException * @throws HttpException */
Send the customized message to the back office
sendCustomizedMessages
{ "repo_name": "vbonamy/esup-smsu", "path": "src/main/java/org/esupportail/smsu/business/SendSmsManager.java", "license": "apache-2.0", "size": 37529 }
[ "org.esupportail.smsu.business.beans.CustomizedMessage", "org.esupportail.smsuapi.exceptions.InsufficientQuotaException", "org.esupportail.smsuapi.utils.HttpException" ]
import org.esupportail.smsu.business.beans.CustomizedMessage; import org.esupportail.smsuapi.exceptions.InsufficientQuotaException; import org.esupportail.smsuapi.utils.HttpException;
import org.esupportail.smsu.business.beans.*; import org.esupportail.smsuapi.exceptions.*; import org.esupportail.smsuapi.utils.*;
[ "org.esupportail.smsu", "org.esupportail.smsuapi" ]
org.esupportail.smsu; org.esupportail.smsuapi;
2,250,074
public static Object invokeStatic(final Class<?> clazz, final String methodName, final Class<?>[] argTypes, final Object[] args) throws Exception { final Method method = clazz.getMethod(methodName, argTypes); return method.invoke(null, args); }
static Object function(final Class<?> clazz, final String methodName, final Class<?>[] argTypes, final Object[] args) throws Exception { final Method method = clazz.getMethod(methodName, argTypes); return method.invoke(null, args); }
/** * Invokes a static method on a class. * * @param clazz the class to invoke the method on * @param methodName the method name * @param argTypes the method argument types * @param args the method arguments * * @return the method result * * @throws Exception if anything goes wrong */
Invokes a static method on a class
invokeStatic
{ "repo_name": "apigee/lembos", "path": "src/main/java/io/apigee/lembos/utils/ReflectionUtils.java", "license": "apache-2.0", "size": 1987 }
[ "java.lang.reflect.Method" ]
import java.lang.reflect.Method;
import java.lang.reflect.*;
[ "java.lang" ]
java.lang;
1,783,338
public final AttachProvider provider() { return provider; }
final AttachProvider function() { return provider; }
/** * Returns the provider that created this virtual machine. * * @return The provider that created this virtual machine. */
Returns the provider that created this virtual machine
provider
{ "repo_name": "34benma/openjdk", "path": "jdk/src/jdk.attach/share/classes/com/sun/tools/attach/VirtualMachine.java", "license": "gpl-2.0", "size": 30943 }
[ "com.sun.tools.attach.spi.AttachProvider" ]
import com.sun.tools.attach.spi.AttachProvider;
import com.sun.tools.attach.spi.*;
[ "com.sun.tools" ]
com.sun.tools;
870,341
public CommandLocator getCommandLocator(CommandContext context) { if (transactionId != null) { return new GeogitTransaction(context.getGeoGIT().getCommandLocator(), context .getGeoGIT().getRepository(), transactionId); } return context.getGeoGIT().getCommandLocator(); }
CommandLocator function(CommandContext context) { if (transactionId != null) { return new GeogitTransaction(context.getGeoGIT().getCommandLocator(), context .getGeoGIT().getRepository(), transactionId); } return context.getGeoGIT().getCommandLocator(); }
/** * This function either builds a GeoGitTransaction to run commands off of if there is a * transactionId to build off of or the GeoGit commandLocator otherwise. * * @param context - the context to get the information needed to get the commandLocator * @return */
This function either builds a GeoGitTransaction to run commands off of if there is a transactionId to build off of or the GeoGit commandLocator otherwise
getCommandLocator
{ "repo_name": "state-hiu/GeoGit", "path": "src/web/api/src/main/java/org/geogit/web/api/AbstractWebAPICommand.java", "license": "bsd-3-clause", "size": 1694 }
[ "org.geogit.api.CommandLocator", "org.geogit.api.GeogitTransaction" ]
import org.geogit.api.CommandLocator; import org.geogit.api.GeogitTransaction;
import org.geogit.api.*;
[ "org.geogit.api" ]
org.geogit.api;
2,428,621
public DcmElement putST(int tag) { return put(StringElement.createST(tag)); }
DcmElement function(int tag) { return put(StringElement.createST(tag)); }
/** * Description of the Method * * @param tag * Description of the Parameter * @return Description of the Return Value */
Description of the Method
putST
{ "repo_name": "medicayun/medicayundicom", "path": "dcm4che14/tags/DCM4CHE_1_4_30/src/java/org/dcm4cheri/data/DcmObjectImpl.java", "license": "apache-2.0", "size": 85555 }
[ "org.dcm4che.data.DcmElement" ]
import org.dcm4che.data.DcmElement;
import org.dcm4che.data.*;
[ "org.dcm4che.data" ]
org.dcm4che.data;
2,685,089
@Override public void onProductDataResponse(final ProductDataResponse response) { final ProductDataResponse.RequestStatus status = response.getRequestStatus(); Gdx.app.log(TAG, "onProductDataResponse: RequestStatus (" + status + ")"); switch (status) { case SUCCESSFUL: Gdx.app.log(TAG, "onProductDataResponse: successful"); // Store product information Map<String, Product> availableSkus = response.getProductData(); Gdx.app.log(TAG, "onProductDataResponse: " + availableSkus.size() + " available skus"); for (Entry<String, Product> entry : availableSkus.entrySet()) { informationMap.put(entry.getKey(), AmazonTransactionUtils.convertProductToInformation(entry.getValue())); } final Set<String> unavailableSkus = response.getUnavailableSkus(); Gdx.app.log(TAG, "onProductDataResponse: " + unavailableSkus.size() + " unavailable skus"); for (String sku : unavailableSkus) { Gdx.app.log(TAG, "onProductDataResponse: sku " + sku + " is not available"); } if (!productDataRetrieved) { productDataRetrieved = true; notifyObserverWhenInstalled(); } break; case FAILED: case NOT_SUPPORTED: Gdx.app.error(TAG, "onProductDataResponse: failed, should retry request"); if (!productDataRetrieved) { observer.handleInstallError(new FetchItemInformationException(String.valueOf(status))); } break; } }
void function(final ProductDataResponse response) { final ProductDataResponse.RequestStatus status = response.getRequestStatus(); Gdx.app.log(TAG, STR + status + ")"); switch (status) { case SUCCESSFUL: Gdx.app.log(TAG, STR); Map<String, Product> availableSkus = response.getProductData(); Gdx.app.log(TAG, STR + availableSkus.size() + STR); for (Entry<String, Product> entry : availableSkus.entrySet()) { informationMap.put(entry.getKey(), AmazonTransactionUtils.convertProductToInformation(entry.getValue())); } final Set<String> unavailableSkus = response.getUnavailableSkus(); Gdx.app.log(TAG, STR + unavailableSkus.size() + STR); for (String sku : unavailableSkus) { Gdx.app.log(TAG, STR + sku + STR); } if (!productDataRetrieved) { productDataRetrieved = true; notifyObserverWhenInstalled(); } break; case FAILED: case NOT_SUPPORTED: Gdx.app.error(TAG, STR); if (!productDataRetrieved) { observer.handleInstallError(new FetchItemInformationException(String.valueOf(status))); } break; } }
/** * This is the callback for {@link PurchasingService#getProductData}. */
This is the callback for <code>PurchasingService#getProductData</code>
onProductDataResponse
{ "repo_name": "squins/gdx-pay", "path": "gdx-pay-android-amazon/src/com/badlogic/gdx/pay/android/amazon/PurchaseManagerAndroidAmazon.java", "license": "apache-2.0", "size": 14290 }
[ "com.amazon.device.iap.model.Product", "com.amazon.device.iap.model.ProductDataResponse", "com.badlogic.gdx.Gdx", "com.badlogic.gdx.pay.FetchItemInformationException", "java.util.Map", "java.util.Set" ]
import com.amazon.device.iap.model.Product; import com.amazon.device.iap.model.ProductDataResponse; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.pay.FetchItemInformationException; import java.util.Map; import java.util.Set;
import com.amazon.device.iap.model.*; import com.badlogic.gdx.*; import com.badlogic.gdx.pay.*; import java.util.*;
[ "com.amazon.device", "com.badlogic.gdx", "java.util" ]
com.amazon.device; com.badlogic.gdx; java.util;
1,884,107
private void run() throws Exception { TransactionRunner runner = new TransactionRunner(db.getEnvironment()); runner.run(new PopulateDatabase()); runner.run(new PrintDatabase()); } private class PopulateDatabase implements TransactionWorker {
void function() throws Exception { TransactionRunner runner = new TransactionRunner(db.getEnvironment()); runner.run(new PopulateDatabase()); runner.run(new PrintDatabase()); } private class PopulateDatabase implements TransactionWorker {
/** * Run two transactions to populate and print the database. A * TransactionRunner is used to ensure consistent handling of transactions, * including deadlock retries. But the best transaction handling mechanism * to use depends on the application. */
Run two transactions to populate and print the database. A TransactionRunner is used to ensure consistent handling of transactions, including deadlock retries. But the best transaction handling mechanism to use depends on the application
run
{ "repo_name": "nologic/nabs", "path": "client/trunk/shared/libraries/je-3.2.74/examples/collections/ship/tuple/Sample.java", "license": "gpl-2.0", "size": 7930 }
[ "com.sleepycat.collections.TransactionRunner", "com.sleepycat.collections.TransactionWorker" ]
import com.sleepycat.collections.TransactionRunner; import com.sleepycat.collections.TransactionWorker;
import com.sleepycat.collections.*;
[ "com.sleepycat.collections" ]
com.sleepycat.collections;
2,731,341
public void setEvents(List<URI> events) { Set <URI> uniqueEvents = new HashSet<URI>(); uniqueEvents.addAll(events); events.clear(); events.addAll(uniqueEvents); this.events = events; }
void function(List<URI> events) { Set <URI> uniqueEvents = new HashSet<URI>(); uniqueEvents.addAll(events); events.clear(); events.addAll(uniqueEvents); this.events = events; }
/** * Sets the DiSCO Events list. * * @param events the new list of DiSCO Events */
Sets the DiSCO Events list
setEvents
{ "repo_name": "rmap-project/rmap", "path": "webapp/src/main/java/info/rmapproject/webapp/service/dto/DiSCODTO.java", "license": "apache-2.0", "size": 7790 }
[ "java.util.HashSet", "java.util.List", "java.util.Set" ]
import java.util.HashSet; import java.util.List; import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
2,003,922
public void go(OutputStream out) throws IOException { go(new JCardWriter(out, vcards.size() > 1)); }
void function(OutputStream out) throws IOException { go(new JCardWriter(out, vcards.size() > 1)); }
/** * Writes the jCards to an output stream. * @param out the output stream to write to * @throws IOException if there's a problem writing to the output stream */
Writes the jCards to an output stream
go
{ "repo_name": "hongnguyenpro/ez-vcard", "path": "src/main/java/ezvcard/Ezvcard.java", "license": "bsd-2-clause", "size": 48906 }
[ "java.io.IOException", "java.io.OutputStream" ]
import java.io.IOException; import java.io.OutputStream;
import java.io.*;
[ "java.io" ]
java.io;
2,741,677