method
stringlengths
13
441k
clean_method
stringlengths
7
313k
doc
stringlengths
17
17.3k
comment
stringlengths
3
1.42k
method_name
stringlengths
1
273
extra
dict
imports
list
imports_info
stringlengths
19
34.8k
cluster_imports_info
stringlengths
15
3.66k
libraries
list
libraries_info
stringlengths
6
661
id
int64
0
2.92M
DuplicationStorePolicy policy = new DuplicationStorePolicy(); policy.setDestStoreId("1"); policy.setSrcStoreId("0"); Morsel a = new DuplicationMorsel("subdomain-a", "space-a", "marker", policy); Morsel b = new DuplicationMorsel("subdomain-b", "space-a", "marker", policy); Morsel c = new DuplicationMorsel("subdomain-z", "space-a", null, policy); Morsel d = new DuplicationMorsel("subdomain-a", "space-b", null, policy); Morsel e = new DuplicationMorsel("subdomain-b", "space-c", "marker", policy); MorselComparator com = new MorselComparator(); Assert.assertTrue(com.compare(c, d) < 0); Assert.assertTrue(com.compare(d, a) < 0); Assert.assertEquals(1, com.compare(a, d)); Assert.assertTrue(com.compare(e, b) > 0); Assert.assertTrue(com.compare(a, b) < 0); }
DuplicationStorePolicy policy = new DuplicationStorePolicy(); policy.setDestStoreId("1"); policy.setSrcStoreId("0"); Morsel a = new DuplicationMorsel(STR, STR, STR, policy); Morsel b = new DuplicationMorsel(STR, STR, STR, policy); Morsel c = new DuplicationMorsel(STR, STR, null, policy); Morsel d = new DuplicationMorsel(STR, STR, null, policy); Morsel e = new DuplicationMorsel(STR, STR, STR, policy); MorselComparator com = new MorselComparator(); Assert.assertTrue(com.compare(c, d) < 0); Assert.assertTrue(com.compare(d, a) < 0); Assert.assertEquals(1, com.compare(a, d)); Assert.assertTrue(com.compare(e, b) > 0); Assert.assertTrue(com.compare(a, b) < 0); }
/** * Test method for * {@link org.duracloud.mill.ltp.MorselComparator#compare(org.duracloud.mill.ltp.Morsel, org.duracloud.mill.ltp.Morsel)}. */
Test method for <code>org.duracloud.mill.ltp.MorselComparator#compare(org.duracloud.mill.ltp.Morsel, org.duracloud.mill.ltp.Morsel)</code>
testCompare
{ "repo_name": "duracloud/mill", "path": "loopingduptaskproducer/src/test/java/org/duracloud/mill/ltp/dup/DuplicationMorselComparatorTest.java", "license": "apache-2.0", "size": 1640 }
[ "org.duracloud.mill.dup.DuplicationStorePolicy", "org.duracloud.mill.ltp.Morsel", "org.duracloud.mill.ltp.MorselComparator", "org.junit.Assert" ]
import org.duracloud.mill.dup.DuplicationStorePolicy; import org.duracloud.mill.ltp.Morsel; import org.duracloud.mill.ltp.MorselComparator; import org.junit.Assert;
import org.duracloud.mill.dup.*; import org.duracloud.mill.ltp.*; import org.junit.*;
[ "org.duracloud.mill", "org.junit" ]
org.duracloud.mill; org.junit;
779,301
private void initBPRMADetails(int C_BPartner_ID) { rmaField.removeActionListener(this); rmaField.removeAllItems(); // None KeyNamePair pp = new KeyNamePair(0,""); rmaField.addItem(pp); ArrayList<KeyNamePair> list = loadRMAData(C_BPartner_ID); for(KeyNamePair knp : list) rmaField.addItem(knp); rmaField.setSelectedIndex(0); rmaField.addActionListener(this); }
void function(int C_BPartner_ID) { rmaField.removeActionListener(this); rmaField.removeAllItems(); KeyNamePair pp = new KeyNamePair(0,""); rmaField.addItem(pp); ArrayList<KeyNamePair> list = loadRMAData(C_BPartner_ID); for(KeyNamePair knp : list) rmaField.addItem(knp); rmaField.setSelectedIndex(0); rmaField.addActionListener(this); }
/** * Load RMA that are candidates for shipment * @param C_BPartner_ID BPartner */
Load RMA that are candidates for shipment
initBPRMADetails
{ "repo_name": "erpcya/adempierePOS", "path": "zkwebui/WEB-INF/src/org/adempiere/webui/apps/form/WCreateFromShipmentUI.java", "license": "gpl-2.0", "size": 17851 }
[ "java.util.ArrayList", "org.compiere.util.KeyNamePair" ]
import java.util.ArrayList; import org.compiere.util.KeyNamePair;
import java.util.*; import org.compiere.util.*;
[ "java.util", "org.compiere.util" ]
java.util; org.compiere.util;
1,376,243
void beforeNavigateBack(WebDriver driver);
void beforeNavigateBack(WebDriver driver);
/** * Called before {@link org.openqa.selenium.WebDriver.Navigation#back navigate().back()}. */
Called before <code>org.openqa.selenium.WebDriver.Navigation#back navigate().back()</code>
beforeNavigateBack
{ "repo_name": "jerome-jacob/selenium", "path": "java/client/src/org/openqa/selenium/support/events/WebDriverEventListener.java", "license": "apache-2.0", "size": 4806 }
[ "org.openqa.selenium.WebDriver" ]
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.*;
[ "org.openqa.selenium" ]
org.openqa.selenium;
1,451,166
@Override public WebResponse openWebResponse(final URL location, boolean bufferStream) { return new WebResponse() {
WebResponse function(final URL location, boolean bufferStream) { return new WebResponse() {
/** * Only the path part of the URL is interpreted for retrieving resource from class path * @see org.cee.net.WebClient#openWebResponse(java.net.URL) */
Only the path part of the URL is interpreted for retrieving resource from class path
openWebResponse
{ "repo_name": "andreasbehnke/cee", "path": "cee-parser-impl/src/main/java/org/cee/net/impl/ClassResourceWebClient.java", "license": "apache-2.0", "size": 3144 }
[ "org.cee.net.WebResponse" ]
import org.cee.net.WebResponse;
import org.cee.net.*;
[ "org.cee.net" ]
org.cee.net;
2,860,965
private void drawSignal( Graphics2D g, int imageWidth, int imageHeight, VisibleSignal visibleSignal, int signalStartY, long markerPosition, WaveView view ) { { // Draw a signal name AbstractSignal signal = visibleSignal.getSignal(); TextLayout signalNameLayout = new TextLayout( signal.getFullPath(), signalNameFont, g .getFontRenderContext() ); g.setColor( new Color( 220, 220, 220 ) ); signalNameLayout.draw( g, 5, signalStartY + 15 ); // draw a bitNr if is a manybit signal if ( signal.getBitNr() != -1 ) { TextLayout bitNrLayout = new TextLayout( "bit #: " + (signal.getBitNr() + 1), bitNrFont, g.getFontRenderContext() ); g.setColor( new Color( 190, 190, 190 ) ); bitNrLayout.draw( g, 5, signalStartY + 30 ); } // Draw a signal value at selected marker if ( markerPosition != -1 ) { TextLayout signalValueAtMarkerLayout = new TextLayout( visibleSignal .getFormattedValueAt( markerPosition ), signalValueFont, g.getFontRenderContext() ); g.setColor( Color.white ); g.setFont( signalValueFont ); signalValueAtMarkerLayout.draw( g, signalValueAtMarkerPoint.x - (int) signalValueAtMarkerLayout.getBounds().getWidth(), signalStartY + signalValueAtMarkerPoint.y ); } // Draw images for numeral system int yNumeralSystemPosition = signalStartY + yNumeralSystemOffset; switch ( visibleSignal.getNumeralSystem() ) { case BINARY: imgB = binaryImageOn; imgD = unsignedDecimalImageOff; imgDs = signedDecimalImageOff; imgH = hexadecimalImageOff; break; case UNSIGNED_DECIMAL: imgB = binaryImageOff; imgD = unsignedDecimalImageOn; imgDs = signedDecimalImageOff; imgH = hexadecimalImageOff; break; case SIGNED_DECIMAL: imgB = binaryImageOff; imgD = unsignedDecimalImageOff; imgDs = signedDecimalImageOn; imgH = hexadecimalImageOff; break; case HEXADECIMAL: imgB = binaryImageOff; imgD = unsignedDecimalImageOff; imgDs = signedDecimalImageOff; imgH = hexadecimalImageOn; break; } g.drawImage( imgB, null, binaryOffset, yNumeralSystemPosition ); g.drawImage( imgD, null, unsignedDecimalOffset, yNumeralSystemPosition ); g.drawImage( imgDs, null, signedDecimalOffset, yNumeralSystemPosition ); g.drawImage( imgH, null, hexadecimalOffset, yNumeralSystemPosition ); // draw delete button g.drawImage( deleteSignalImgae, null, deleteSignalPoint.x, signalStartY + deleteSignalPoint.y ); // draw a signal g.setClip( infoWidth + 1, signalStartY, imageWidth - infoWidth - 1, signalHeight ); // get a last change time long currentTime = signal.getPreviousChangeTime( view.getStartVisibleTime() ); if ( currentTime < view.getStartVisibleTime() - 10 * view.getZoom() ) { currentTime = view.getStartVisibleTime() - 10 * view.getZoom(); } long nextChangeTime = 0; String lastValue = signal.getValueAt( currentTime ); String value; boolean stop = false; long lastChangeTime = signal.getLastChangeTime( view.getEndVisibleTime() ); while ( (currentTime <= lastChangeTime && (!stop)) ) { nextChangeTime = signal.getNextChangeTime( currentTime ); // Correct a time of the next change stop = (nextChangeTime == -1) || (nextChangeTime > view.getEndVisibleTime()); if (nextChangeTime == -1) { nextChangeTime = view.getEndVisibleTime() + 10 * view.getZoom(); } // Calc a width of change long pxDelta = view.getCoordFromTime( nextChangeTime ) - view.getCoordFromTime( currentTime ); if ( pxDelta >= signal.getNoChangeWidth() ) { value = signal.getValueAt( currentTime ); // Draw a signal line // Correct Values of X long startX = view.getCoordFromTime( currentTime ); startX = (startX < infoWidth) ? infoWidth - 10 : startX; long stopX = view.getCoordFromTime( nextChangeTime ); if ( stopX > imageWidth + 10 ) { stopX = imageWidth + 10; } isLastValue0 = lastValue.equals( "0" ); isLastValue1 = lastValue.equals( "1" ); isLastValueZ = lastValue.equals( AbstractSignal.SIGNAL_VALUE_Z ); isLastValueX = lastValue.equals( AbstractSignal.SIGNAL_VALUE_X ); isValue0 = value.equals( "0" ); isValue1 = value.equals( "1" ); isValueZ = value.equals( AbstractSignal.SIGNAL_VALUE_Z ); isValueX = value.equals( AbstractSignal.SIGNAL_VALUE_X ); drawSignalLine( g, (int)startX, (int)stopX, lastValue, value, signalStartY, signal, visibleSignal .getFormattedValueAt( currentTime ) ); // Changing current pixel currentTime = nextChangeTime; lastValue = value; } else { // Have a more changes on some px int countChanges = 10; long startTime = currentTime; long stopTime = currentTime; while ( (countChanges != 0) && (stopTime <= view.getEndVisibleTime()) ) { stopTime = startTime + (long) ((signal.getNoChangeWidth() - 1) * view .getZoom()); stopTime = signal.getNearestPreviousChangeTime( stopTime ); if ( stopTime == startTime ) { stopTime = signal.getNextChangeTime( stopTime ); } if ( stopTime > Application.signalManager .getSignalLength() ) { break; } if ( stopTime == -1 ) { stopTime = view.getEndVisibleTime(); break; } countChanges = signal.getCountChanges( startTime, stopTime ); startTime = stopTime; } // Draw a many changes g.setColor( Color.GREEN ); g.fillRect( (int)view.getCoordFromTime( currentTime ), signalStartY + highOffset, (int)(view .getCoordFromTime( stopTime ) - view.getCoordFromTime( currentTime )), lowOffset - highOffset ); // Changing current pixel currentTime = stopTime; lastValue = signal.getValueAt( stopTime ); } } // Remove Clip g.setClip( 0, 0, imageWidth, imageHeight ); } }
void function( Graphics2D g, int imageWidth, int imageHeight, VisibleSignal visibleSignal, int signalStartY, long markerPosition, WaveView view ) { { AbstractSignal signal = visibleSignal.getSignal(); TextLayout signalNameLayout = new TextLayout( signal.getFullPath(), signalNameFont, g .getFontRenderContext() ); g.setColor( new Color( 220, 220, 220 ) ); signalNameLayout.draw( g, 5, signalStartY + 15 ); if ( signal.getBitNr() != -1 ) { TextLayout bitNrLayout = new TextLayout( STR + (signal.getBitNr() + 1), bitNrFont, g.getFontRenderContext() ); g.setColor( new Color( 190, 190, 190 ) ); bitNrLayout.draw( g, 5, signalStartY + 30 ); } if ( markerPosition != -1 ) { TextLayout signalValueAtMarkerLayout = new TextLayout( visibleSignal .getFormattedValueAt( markerPosition ), signalValueFont, g.getFontRenderContext() ); g.setColor( Color.white ); g.setFont( signalValueFont ); signalValueAtMarkerLayout.draw( g, signalValueAtMarkerPoint.x - (int) signalValueAtMarkerLayout.getBounds().getWidth(), signalStartY + signalValueAtMarkerPoint.y ); } int yNumeralSystemPosition = signalStartY + yNumeralSystemOffset; switch ( visibleSignal.getNumeralSystem() ) { case BINARY: imgB = binaryImageOn; imgD = unsignedDecimalImageOff; imgDs = signedDecimalImageOff; imgH = hexadecimalImageOff; break; case UNSIGNED_DECIMAL: imgB = binaryImageOff; imgD = unsignedDecimalImageOn; imgDs = signedDecimalImageOff; imgH = hexadecimalImageOff; break; case SIGNED_DECIMAL: imgB = binaryImageOff; imgD = unsignedDecimalImageOff; imgDs = signedDecimalImageOn; imgH = hexadecimalImageOff; break; case HEXADECIMAL: imgB = binaryImageOff; imgD = unsignedDecimalImageOff; imgDs = signedDecimalImageOff; imgH = hexadecimalImageOn; break; } g.drawImage( imgB, null, binaryOffset, yNumeralSystemPosition ); g.drawImage( imgD, null, unsignedDecimalOffset, yNumeralSystemPosition ); g.drawImage( imgDs, null, signedDecimalOffset, yNumeralSystemPosition ); g.drawImage( imgH, null, hexadecimalOffset, yNumeralSystemPosition ); g.drawImage( deleteSignalImgae, null, deleteSignalPoint.x, signalStartY + deleteSignalPoint.y ); g.setClip( infoWidth + 1, signalStartY, imageWidth - infoWidth - 1, signalHeight ); long currentTime = signal.getPreviousChangeTime( view.getStartVisibleTime() ); if ( currentTime < view.getStartVisibleTime() - 10 * view.getZoom() ) { currentTime = view.getStartVisibleTime() - 10 * view.getZoom(); } long nextChangeTime = 0; String lastValue = signal.getValueAt( currentTime ); String value; boolean stop = false; long lastChangeTime = signal.getLastChangeTime( view.getEndVisibleTime() ); while ( (currentTime <= lastChangeTime && (!stop)) ) { nextChangeTime = signal.getNextChangeTime( currentTime ); stop = (nextChangeTime == -1) (nextChangeTime > view.getEndVisibleTime()); if (nextChangeTime == -1) { nextChangeTime = view.getEndVisibleTime() + 10 * view.getZoom(); } long pxDelta = view.getCoordFromTime( nextChangeTime ) - view.getCoordFromTime( currentTime ); if ( pxDelta >= signal.getNoChangeWidth() ) { value = signal.getValueAt( currentTime ); long startX = view.getCoordFromTime( currentTime ); startX = (startX < infoWidth) ? infoWidth - 10 : startX; long stopX = view.getCoordFromTime( nextChangeTime ); if ( stopX > imageWidth + 10 ) { stopX = imageWidth + 10; } isLastValue0 = lastValue.equals( "0" ); isLastValue1 = lastValue.equals( "1" ); isLastValueZ = lastValue.equals( AbstractSignal.SIGNAL_VALUE_Z ); isLastValueX = lastValue.equals( AbstractSignal.SIGNAL_VALUE_X ); isValue0 = value.equals( "0" ); isValue1 = value.equals( "1" ); isValueZ = value.equals( AbstractSignal.SIGNAL_VALUE_Z ); isValueX = value.equals( AbstractSignal.SIGNAL_VALUE_X ); drawSignalLine( g, (int)startX, (int)stopX, lastValue, value, signalStartY, signal, visibleSignal .getFormattedValueAt( currentTime ) ); currentTime = nextChangeTime; lastValue = value; } else { int countChanges = 10; long startTime = currentTime; long stopTime = currentTime; while ( (countChanges != 0) && (stopTime <= view.getEndVisibleTime()) ) { stopTime = startTime + (long) ((signal.getNoChangeWidth() - 1) * view .getZoom()); stopTime = signal.getNearestPreviousChangeTime( stopTime ); if ( stopTime == startTime ) { stopTime = signal.getNextChangeTime( stopTime ); } if ( stopTime > Application.signalManager .getSignalLength() ) { break; } if ( stopTime == -1 ) { stopTime = view.getEndVisibleTime(); break; } countChanges = signal.getCountChanges( startTime, stopTime ); startTime = stopTime; } g.setColor( Color.GREEN ); g.fillRect( (int)view.getCoordFromTime( currentTime ), signalStartY + highOffset, (int)(view .getCoordFromTime( stopTime ) - view.getCoordFromTime( currentTime )), lowOffset - highOffset ); currentTime = stopTime; lastValue = signal.getValueAt( stopTime ); } } g.setClip( 0, 0, imageWidth, imageHeight ); } }
/** * Draw a signal * * @param g * a graphics2D to draw * @param imageWidth * width of the graphics * @param imageHeight * height of the graphics * @param signal * signal to draw * @param signalStartY * startPosition of the signal * @param view * a WaveFormView */
Draw a signal
drawSignal
{ "repo_name": "Rubbiroid/VVIDE", "path": "src/vvide/ui/views/wave/SignalRender.java", "license": "gpl-3.0", "size": 27532 }
[ "java.awt.Color", "java.awt.Graphics2D", "java.awt.font.TextLayout" ]
import java.awt.Color; import java.awt.Graphics2D; import java.awt.font.TextLayout;
import java.awt.*; import java.awt.font.*;
[ "java.awt" ]
java.awt;
1,633,553
public void drawAxis(Graphics g, double a, double b, double w, double c, int orientation){ this.drawAxis(g, a, b, w, c, orientation, BOUNDS, null); }
void function(Graphics g, double a, double b, double w, double c, int orientation){ this.drawAxis(g, a, b, w, c, orientation, BOUNDS, null); }
/**This method draws an axis corresponding to the partition of [a, b] into subintervals of width w, with tick marks at the partition bounds*/
This method draws an axis corresponding to the partition of [a, b] into subintervals of width w
drawAxis
{ "repo_name": "SOCR/HTML5_WebSite", "path": "SOCR2.8/src/edu/ucla/stat/SOCR/util/Graph.java", "license": "lgpl-3.0", "size": 18789 }
[ "java.awt.Graphics" ]
import java.awt.Graphics;
import java.awt.*;
[ "java.awt" ]
java.awt;
2,273,304
public void removeReader(TransactionImpl tx, Object obj) { try { LockEntry lock = new LockEntry(new Identity(obj,getBroker()).toString(), tx.getGUID()); removeReaderRemote(lock); } catch (Throwable t) { log.error("Cannot remove LockEntry for object " + obj + " in transaction " + tx); } }
void function(TransactionImpl tx, Object obj) { try { LockEntry lock = new LockEntry(new Identity(obj,getBroker()).toString(), tx.getGUID()); removeReaderRemote(lock); } catch (Throwable t) { log.error(STR + obj + STR + tx); } }
/** * remove a reader lock entry for transaction tx on object obj * from the persistent storage. */
remove a reader lock entry for transaction tx on object obj from the persistent storage
removeReader
{ "repo_name": "kuali/ojb-1.0.4", "path": "src/java/org/apache/ojb/odmg/locking/RemoteLockMapImpl.java", "license": "apache-2.0", "size": 14137 }
[ "org.apache.ojb.broker.Identity", "org.apache.ojb.odmg.TransactionImpl" ]
import org.apache.ojb.broker.Identity; import org.apache.ojb.odmg.TransactionImpl;
import org.apache.ojb.broker.*; import org.apache.ojb.odmg.*;
[ "org.apache.ojb" ]
org.apache.ojb;
2,606,449
private void deleteJWTCondition(Connection connection, int conID) throws SQLException { final String query = "DELETE FROM AM_JWT_CLAIM_CONDITION WHERE CONDITION_GROUP_ID = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { preparedStatement.setInt(1, conID); preparedStatement.execute(); } }
void function(Connection connection, int conID) throws SQLException { final String query = STR; try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { preparedStatement.setInt(1, conID); preparedStatement.execute(); } }
/** * Delete JWT claim condition from database * * @param connection connection to the database * @param conID pipeline id of the jwt claim condition * @throws SQLException if error occurred when jwt claim is deleted */
Delete JWT claim condition from database
deleteJWTCondition
{ "repo_name": "lakmali/carbon-apimgt", "path": "components/apimgt/org.wso2.carbon.apimgt.core/src/main/java/org/wso2/carbon/apimgt/core/dao/impl/PolicyDAOImpl.java", "license": "apache-2.0", "size": 109019 }
[ "java.sql.Connection", "java.sql.PreparedStatement", "java.sql.SQLException" ]
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
import java.sql.*;
[ "java.sql" ]
java.sql;
1,241,617
public void mouseDown(MouseEvent e) { Control oldEditorControl = cellEditor.getEditor(); if (null != oldEditorControl) oldEditorControl.dispose(); } }); }
void function(MouseEvent e) { Control oldEditorControl = cellEditor.getEditor(); if (null != oldEditorControl) oldEditorControl.dispose(); } }); }
/** * Dispose cell editor control at mouse down (otherwise the control * keep showing). */
Dispose cell editor control at mouse down (otherwise the control keep showing)
mouseDown
{ "repo_name": "prabushi/devstudio-tooling-esb", "path": "plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/configure/ui/ConfigureXQueryMediatorDialog.java", "license": "apache-2.0", "size": 25806 }
[ "org.eclipse.swt.events.MouseEvent", "org.eclipse.swt.widgets.Control" ]
import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.events.*; import org.eclipse.swt.widgets.*;
[ "org.eclipse.swt" ]
org.eclipse.swt;
2,632,463
@XmlElement(name="params") public Parameters getParameters() { return parameters; }
@XmlElement(name=STR) Parameters function() { return parameters; }
/** * Gets the parameters. * * @return the parameters */
Gets the parameters
getParameters
{ "repo_name": "opennms-forge/poc-nms-core", "path": "opennms-rrd/opennms-rrd-model/src/main/java/org/opennms/netmgt/rrd/model/v3/RRA.java", "license": "gpl-2.0", "size": 4817 }
[ "javax.xml.bind.annotation.XmlElement" ]
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.*;
[ "javax.xml" ]
javax.xml;
1,267,690
try { temperature = temperatureConvertEJB.convert(Temperature.parse(sourceTemperature, defaultScale)).toString(); } catch (IllegalArgumentException e) { temperature = "0.0 Err"; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.toString())); } }
try { temperature = temperatureConvertEJB.convert(Temperature.parse(sourceTemperature, defaultScale)).toString(); } catch (IllegalArgumentException e) { temperature = STR; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.toString())); } }
/** * Invoke temperatureConvertEJB.convert() and store the temperature * * @param sourceTemperature The temperature to be converted * @param defaultScale The default source temperature scale */
Invoke temperatureConvertEJB.convert() and store the temperature
convert
{ "repo_name": "ivanthelad/jboss-eap-quickstarts", "path": "temperature-converter/src/main/java/org/jboss/as/quickstarts/temperatureconverter/controller/TemperatureConverter.java", "license": "apache-2.0", "size": 3114 }
[ "javax.faces.application.FacesMessage", "javax.faces.context.FacesContext", "org.jboss.as.quickstarts.temperatureconverter.ejb.Temperature" ]
import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.jboss.as.quickstarts.temperatureconverter.ejb.Temperature;
import javax.faces.application.*; import javax.faces.context.*; import org.jboss.as.quickstarts.temperatureconverter.ejb.*;
[ "javax.faces", "org.jboss.as" ]
javax.faces; org.jboss.as;
2,408,519
public Node insert(final String parentTreePath, final Feature feature) { final FeatureType featureType = feature.getType(); NodeRef treeRef; Optional<NodeRef> typeTreeRef = commandLocator.command(FindTreeChild.class).setIndex(true) .setParent(getTree()).setChildPath(parentTreePath).call(); ObjectId metadataId; if (typeTreeRef.isPresent()) { treeRef = typeTreeRef.get(); RevFeatureType newFeatureType = RevFeatureType.build(featureType); metadataId = newFeatureType.getId().equals(treeRef.getMetadataId()) ? ObjectId.NULL : newFeatureType.getId(); if (!newFeatureType.getId().equals(treeRef.getMetadataId())) { indexDatabase.put(newFeatureType); } } else { treeRef = createTypeTree(parentTreePath, featureType); metadataId = ObjectId.NULL;// treeRef.getMetadataId(); } // ObjectId metadataId = treeRef.getMetadataId(); final Node node = putInDatabase(feature, metadataId); RevTreeBuilder parentTree = commandLocator.command(FindOrCreateSubtree.class) .setIndex(true).setParent(Suppliers.ofInstance(Optional.of(getTree()))) .setChildPath(parentTreePath).call().builder(indexDatabase); parentTree.put(node); final ObjectId treeMetadataId = treeRef.getMetadataId(); ObjectId newTree = commandLocator.command(WriteBack.class).setAncestor(getTreeSupplier()) .setChildPath(parentTreePath).setToIndex(true).setTree(parentTree.build()) .setMetadataId(treeMetadataId).call(); updateWorkHead(newTree); final String featurePath = NodeRef.appendChild(parentTreePath, node.getName()); Optional<NodeRef> featureRef = commandLocator.command(FindTreeChild.class).setIndex(true) .setParent(getTree()).setChildPath(featurePath).call(); return featureRef.get().getNode(); }
Node function(final String parentTreePath, final Feature feature) { final FeatureType featureType = feature.getType(); NodeRef treeRef; Optional<NodeRef> typeTreeRef = commandLocator.command(FindTreeChild.class).setIndex(true) .setParent(getTree()).setChildPath(parentTreePath).call(); ObjectId metadataId; if (typeTreeRef.isPresent()) { treeRef = typeTreeRef.get(); RevFeatureType newFeatureType = RevFeatureType.build(featureType); metadataId = newFeatureType.getId().equals(treeRef.getMetadataId()) ? ObjectId.NULL : newFeatureType.getId(); if (!newFeatureType.getId().equals(treeRef.getMetadataId())) { indexDatabase.put(newFeatureType); } } else { treeRef = createTypeTree(parentTreePath, featureType); metadataId = ObjectId.NULL; } final Node node = putInDatabase(feature, metadataId); RevTreeBuilder parentTree = commandLocator.command(FindOrCreateSubtree.class) .setIndex(true).setParent(Suppliers.ofInstance(Optional.of(getTree()))) .setChildPath(parentTreePath).call().builder(indexDatabase); parentTree.put(node); final ObjectId treeMetadataId = treeRef.getMetadataId(); ObjectId newTree = commandLocator.command(WriteBack.class).setAncestor(getTreeSupplier()) .setChildPath(parentTreePath).setToIndex(true).setTree(parentTree.build()) .setMetadataId(treeMetadataId).call(); updateWorkHead(newTree); final String featurePath = NodeRef.appendChild(parentTreePath, node.getName()); Optional<NodeRef> featureRef = commandLocator.command(FindTreeChild.class).setIndex(true) .setParent(getTree()).setChildPath(featurePath).call(); return featureRef.get().getNode(); }
/** * Insert a single feature into the working tree and updates the WORK_HEAD ref. * * @param parentTreePath path of the parent tree to insert the feature into * @param feature the feature to insert */
Insert a single feature into the working tree and updates the WORK_HEAD ref
insert
{ "repo_name": "state-hiu/GeoGit", "path": "src/core/src/main/java/org/geogit/repository/WorkingTree.java", "license": "bsd-3-clause", "size": 37354 }
[ "com.google.common.base.Optional", "com.google.common.base.Suppliers", "org.geogit.api.Node", "org.geogit.api.NodeRef", "org.geogit.api.ObjectId", "org.geogit.api.RevFeatureType", "org.geogit.api.RevTreeBuilder", "org.geogit.api.plumbing.FindOrCreateSubtree", "org.geogit.api.plumbing.FindTreeChild", "org.geogit.api.plumbing.WriteBack", "org.opengis.feature.Feature", "org.opengis.feature.type.FeatureType" ]
import com.google.common.base.Optional; import com.google.common.base.Suppliers; import org.geogit.api.Node; import org.geogit.api.NodeRef; import org.geogit.api.ObjectId; import org.geogit.api.RevFeatureType; import org.geogit.api.RevTreeBuilder; import org.geogit.api.plumbing.FindOrCreateSubtree; import org.geogit.api.plumbing.FindTreeChild; import org.geogit.api.plumbing.WriteBack; import org.opengis.feature.Feature; import org.opengis.feature.type.FeatureType;
import com.google.common.base.*; import org.geogit.api.*; import org.geogit.api.plumbing.*; import org.opengis.feature.*; import org.opengis.feature.type.*;
[ "com.google.common", "org.geogit.api", "org.opengis.feature" ]
com.google.common; org.geogit.api; org.opengis.feature;
2,099,833
public static String backQuoteChars(String string, char[] find, String[] replace) { return OptionUtils.backQuoteChars(string, find, replace); }
static String function(String string, char[] find, String[] replace) { return OptionUtils.backQuoteChars(string, find, replace); }
/** * Converts specified characters into the string equivalents. * * @param string the string * @param find the characters to replace * @param replace the replacement strings for the characters * @return the converted string * @see #unbackQuoteChars(String, String[], char[]) */
Converts specified characters into the string equivalents
backQuoteChars
{ "repo_name": "waikato-datamining/adams-base", "path": "adams-core/src/main/java/adams/core/Utils.java", "license": "gpl-3.0", "size": 60884 }
[ "nz.ac.waikato.cms.jenericcmdline.core.OptionUtils" ]
import nz.ac.waikato.cms.jenericcmdline.core.OptionUtils;
import nz.ac.waikato.cms.jenericcmdline.core.*;
[ "nz.ac.waikato" ]
nz.ac.waikato;
1,998,845
private static Gender getGender(Element element) { Gender gender = Gender.unknown; boolean hasGender = element.hasAttribute("gender"); if (hasGender) { gender = Gender.valueOf(element.getAttribute("gender")); } return gender; }
static Gender function(Element element) { Gender gender = Gender.unknown; boolean hasGender = element.hasAttribute(STR); if (hasGender) { gender = Gender.valueOf(element.getAttribute(STR)); } return gender; }
/** * Returns the Gender present in the passed in element's attribute, defaults to unknown gender * @param element the element for which gender attribute is to be determined * @return gender present in the element and unknown gender if not */
Returns the Gender present in the passed in element's attribute, defaults to unknown gender
getGender
{ "repo_name": "mikekap/buck", "path": "src/com/facebook/buck/android/CompileStringsStep.java", "license": "apache-2.0", "size": 18162 }
[ "com.facebook.buck.android.StringResources", "org.w3c.dom.Element" ]
import com.facebook.buck.android.StringResources; import org.w3c.dom.Element;
import com.facebook.buck.android.*; import org.w3c.dom.*;
[ "com.facebook.buck", "org.w3c.dom" ]
com.facebook.buck; org.w3c.dom;
2,372,517
@SuppressWarnings("unchecked") final public void release() { if (parent == null) return; if (--n == 0) { n = batchSize; // lock for update on the parent. synchronized (parent) { parent.add((T) this); } // zero values on the child. clear(); } parent.locks[threadHash].unlock(); } public StripedCounters() { a = null; locks = null; parent = null; batchSize = n = 1; } public StripedCounters(final int batchSize) { this(SystemUtil.numProcessors() * 2, batchSize); } public StripedCounters(final int nstripes, final int batchSize) { if (nstripes < 1) throw new IllegalArgumentException(); if (batchSize < 1) throw new IllegalArgumentException(); a = new StripedCounters[nstripes]; locks = new ReentrantLock[nstripes]; for (int i = 0; i < nstripes; i++) { final T t = newStripedCounters(); t.parent = (T) this; t.batchSize = t.n = batchSize; a[i] = t; locks[i] = new ReentrantLock(); } this.parent = null; this.batchSize = n = batchSize; } // // protected StripedCounters(final StripedCounters parent, final int batchSize) { // a = null; // locks = null; // this.parent = parent; // this.batchSize = n = batchSize; // }
@SuppressWarnings(STR) final void function() { if (parent == null) return; if (--n == 0) { n = batchSize; synchronized (parent) { parent.add((T) this); } clear(); } parent.locks[threadHash].unlock(); } public StripedCounters() { a = null; locks = null; parent = null; batchSize = n = 1; } public StripedCounters(final int batchSize) { this(SystemUtil.numProcessors() * 2, batchSize); } public StripedCounters(final int nstripes, final int batchSize) { if (nstripes < 1) throw new IllegalArgumentException(); if (batchSize < 1) throw new IllegalArgumentException(); a = new StripedCounters[nstripes]; locks = new ReentrantLock[nstripes]; for (int i = 0; i < nstripes; i++) { final T t = newStripedCounters(); t.parent = (T) this; t.batchSize = t.n = batchSize; a[i] = t; locks[i] = new ReentrantLock(); } this.parent = null; this.batchSize = n = batchSize; }
/** * Release the counters. */
Release the counters
release
{ "repo_name": "smalyshev/blazegraph", "path": "bigdata/src/java/com/bigdata/counters/striped/StripedCounters.java", "license": "gpl-2.0", "size": 9624 }
[ "java.util.concurrent.locks.ReentrantLock", "org.apache.system.SystemUtil" ]
import java.util.concurrent.locks.ReentrantLock; import org.apache.system.SystemUtil;
import java.util.concurrent.locks.*; import org.apache.system.*;
[ "java.util", "org.apache.system" ]
java.util; org.apache.system;
586,508
@Test public void testListApplicationsGroupApplication() throws IOException { Group group = new Group(); group.setId(123); Application application = new Application(); application.setName("swf-booking-mvc"); EasyMock.expect(applicationRepository.getApplications(group, application)).andReturn(getExpectedResponse()); EasyMock.replay(applicationRepository); int exitCode = listApplicationsCommand.execute(new String[] { "--groupid=123", "--application=swf-booking-mvc" }); EasyMock.verify(applicationRepository); assertEquals(0, exitCode); final String output = outputStringWriter.getBuffer().toString().trim(); assertEquals("Catalina|localhost|swf-booking-mvc|0|Stopped|0", output); }
void function() throws IOException { Group group = new Group(); group.setId(123); Application application = new Application(); application.setName(STR); EasyMock.expect(applicationRepository.getApplications(group, application)).andReturn(getExpectedResponse()); EasyMock.replay(applicationRepository); int exitCode = listApplicationsCommand.execute(new String[] { STR, STR }); EasyMock.verify(applicationRepository); assertEquals(0, exitCode); final String output = outputStringWriter.getBuffer().toString().trim(); assertEquals(STR, output); }
/** * Verifies that applications are listed when the group and application are specified * * @throws IOException */
Verifies that applications are listed when the group and application are specified
testListApplicationsGroupApplication
{ "repo_name": "pivotal/tcs-hq-management-plugin", "path": "com.springsource.hq.plugin.tcserver.cli/com.springsource.hq.plugin.tcserver.cli.commandline/src/test/java/com/springsource/hq/plugin/tcserver/cli/commandline/application/ListApplicationsCommandTest.java", "license": "gpl-2.0", "size": 29367 }
[ "com.springsource.hq.plugin.tcserver.cli.client.schema.Application", "com.springsource.hq.plugin.tcserver.cli.client.schema.Group", "java.io.IOException", "org.easymock.EasyMock", "org.junit.Assert" ]
import com.springsource.hq.plugin.tcserver.cli.client.schema.Application; import com.springsource.hq.plugin.tcserver.cli.client.schema.Group; import java.io.IOException; import org.easymock.EasyMock; import org.junit.Assert;
import com.springsource.hq.plugin.tcserver.cli.client.schema.*; import java.io.*; import org.easymock.*; import org.junit.*;
[ "com.springsource.hq", "java.io", "org.easymock", "org.junit" ]
com.springsource.hq; java.io; org.easymock; org.junit;
1,582,861
private void initMapsGoogleReverse() { //process a cached result file of half of the scripted data set containing reference and hypothesis new FileProcessor( "heinrichLab.google.refhyp", new FileLoop() { PhonemeCreator pc = PhonemeCreator.getInstance(); final NISTAlign alignerPhonemesReverse = new NISTAlign( true, true); ArrayList<PhonemeContainer> phonemesSpeech = null; Result r; HashMap<String, Integer> hm = new HashMap<String, Integer>();
void function() { new FileProcessor( STR, new FileLoop() { PhonemeCreator pc = PhonemeCreator.getInstance(); final NISTAlign alignerPhonemesReverse = new NISTAlign( true, true); ArrayList<PhonemeContainer> phonemesSpeech = null; Result r; HashMap<String, Integer> hm = new HashMap<String, Integer>();
/** * initializes the score map for Derived IPA */
initializes the score map for Derived IPA
initMapsGoogleReverse
{ "repo_name": "knowledgetechnologyuhh/docks_nightly", "path": "src/Phoneme/PhonemeSubstitution.java", "license": "agpl-3.0", "size": 19975 }
[ "edu.cmu.sphinx.util.NISTAlign", "java.util.ArrayList", "java.util.HashMap" ]
import edu.cmu.sphinx.util.NISTAlign; import java.util.ArrayList; import java.util.HashMap;
import edu.cmu.sphinx.util.*; import java.util.*;
[ "edu.cmu.sphinx", "java.util" ]
edu.cmu.sphinx; java.util;
2,544,727
@Override public void initialize(BSFManager mgr, String lang, @SuppressWarnings("rawtypes") // superclass does not support types Vector declaredBeans) throws BSFException { super.initialize(mgr, lang, declaredBeans); // Initialize context and global scope object try { Context cx = Context.enter(); global = new ImporterTopLevel(cx); Scriptable bsf = Context.toObject(new BSFFunctions(mgr, this), global); global.put("bsf", global, bsf); for( @SuppressWarnings("unchecked") Iterator<BSFDeclaredBean> it = declaredBeans.iterator(); it.hasNext();) { declareBean(it.next()); } } catch (Throwable t) { handleError(t); } finally { Context.exit(); } }
void function(BSFManager mgr, String lang, @SuppressWarnings(STR) Vector declaredBeans) throws BSFException { super.initialize(mgr, lang, declaredBeans); try { Context cx = Context.enter(); global = new ImporterTopLevel(cx); Scriptable bsf = Context.toObject(new BSFFunctions(mgr, this), global); global.put("bsf", global, bsf); for( @SuppressWarnings(STR) Iterator<BSFDeclaredBean> it = declaredBeans.iterator(); it.hasNext();) { declareBean(it.next()); } } catch (Throwable t) { handleError(t); } finally { Context.exit(); } }
/** * Initialize the engine. * Put the manager into the context-manager * map hashtable too. */
Initialize the engine. Put the manager into the context-manager map hashtable too
initialize
{ "repo_name": "tuanhq/jmeter", "path": "src/core/org/apache/jmeter/util/BSFJavaScriptEngine.java", "license": "apache-2.0", "size": 8143 }
[ "java.util.Iterator", "java.util.Vector", "org.apache.bsf.BSFDeclaredBean", "org.apache.bsf.BSFException", "org.apache.bsf.BSFManager", "org.apache.bsf.util.BSFFunctions", "org.mozilla.javascript.Context", "org.mozilla.javascript.ImporterTopLevel", "org.mozilla.javascript.Scriptable" ]
import java.util.Iterator; import java.util.Vector; import org.apache.bsf.BSFDeclaredBean; import org.apache.bsf.BSFException; import org.apache.bsf.BSFManager; import org.apache.bsf.util.BSFFunctions; import org.mozilla.javascript.Context; import org.mozilla.javascript.ImporterTopLevel; import org.mozilla.javascript.Scriptable;
import java.util.*; import org.apache.bsf.*; import org.apache.bsf.util.*; import org.mozilla.javascript.*;
[ "java.util", "org.apache.bsf", "org.mozilla.javascript" ]
java.util; org.apache.bsf; org.mozilla.javascript;
2,768,527
public void onScroll(AdapterView<?> view, int firstVisibleItem, int visibleItemCount, int totalItemCount);
void function(AdapterView<?> view, int firstVisibleItem, int visibleItemCount, int totalItemCount);
/** * Callback method to be invoked when the list has been scrolled or flown. This will be * called after the scroll or fly has completed * * @param view The view whose scroll state is being reported * @param firstVisibleItem the index of the first visible cell (ignore if * visibleItemCount == 0) * @param visibleItemCount the number of visible cells * @param totalItemCount the number of items in the list adaptor */
Callback method to be invoked when the list has been scrolled or flown. This will be called after the scroll or fly has completed
onScroll
{ "repo_name": "NarendraDodiya/NDScaleView", "path": "ndscaleviewlib/src/main/java/com/nd/scaleview/HorizontalScaleView.java", "license": "apache-2.0", "size": 29230 }
[ "android.widget.AdapterView" ]
import android.widget.AdapterView;
import android.widget.*;
[ "android.widget" ]
android.widget;
2,052,936
public List<String> ptrLookup (CharSequence addr) throws NamingException { return ptrLookup(addr, 0, (null == addr) ? 0 : addr.length()); }
List<String> function (CharSequence addr) throws NamingException { return ptrLookup(addr, 0, (null == addr) ? 0 : addr.length()); }
/** * Attempts to find all names of specified (IPv4) address * @param addr (IPv4) address * @return A {@link List} of all available aliases (may be null/empty) * @throws NamingException if problems encountered * @see #PTRAttribute */
Attempts to find all names of specified (IPv4) address
ptrLookup
{ "repo_name": "lgoldstein/communitychest", "path": "chest/net/common/src/main/java/net/community/chest/net/dns/DNSAccess.java", "license": "apache-2.0", "size": 14821 }
[ "java.util.List", "javax.naming.NamingException" ]
import java.util.List; import javax.naming.NamingException;
import java.util.*; import javax.naming.*;
[ "java.util", "javax.naming" ]
java.util; javax.naming;
483,671
private Node constructStringExprNode(Iterator<CharSequence> parts, Node objLitNode) throws MalformedException { CharSequence part = parts.next(); Node partNode = null; if (part instanceof JsMessage.PlaceholderReference) { JsMessage.PlaceholderReference phRef = (JsMessage.PlaceholderReference) part; for (Node n = objLitNode.getFirstChild(); n != null; n = n.getNext().getNext()) { if (n.getString().equals(phRef.getName())) { Node valueNode = n.getNext(); partNode = valueNode.cloneTree(); } } if (partNode == null) { throw new MalformedException( "Unrecognized message placeholder referenced: " + phRef.getName(), objLitNode); } } else { // The part is just a string literal. partNode = Node.newString(part.toString()); } if (parts.hasNext()) { return new Node(Token.ADD, partNode, constructStringExprNode(parts, objLitNode)); } else { return partNode; } }
Node function(Iterator<CharSequence> parts, Node objLitNode) throws MalformedException { CharSequence part = parts.next(); Node partNode = null; if (part instanceof JsMessage.PlaceholderReference) { JsMessage.PlaceholderReference phRef = (JsMessage.PlaceholderReference) part; for (Node n = objLitNode.getFirstChild(); n != null; n = n.getNext().getNext()) { if (n.getString().equals(phRef.getName())) { Node valueNode = n.getNext(); partNode = valueNode.cloneTree(); } } if (partNode == null) { throw new MalformedException( STR + phRef.getName(), objLitNode); } } else { partNode = Node.newString(part.toString()); } if (parts.hasNext()) { return new Node(Token.ADD, partNode, constructStringExprNode(parts, objLitNode)); } else { return partNode; } }
/** * Creates a parse tree corresponding to the remaining message parts in an * iteration. The result consists of one or more STRING nodes, placeholder * replacement value nodes (which can be arbitrary expressions), and ADD * nodes. * * @param parts an iterator over message parts * @param objLitNode an OBJLIT node mapping placeholder names to values * @return the root of the constructed parse tree * * @throws MalformedException if {@code parts} contains a placeholder * reference that does not correspond to a valid placeholder name */
Creates a parse tree corresponding to the remaining message parts in an iteration. The result consists of one or more STRING nodes, placeholder replacement value nodes (which can be arbitrary expressions), and ADD nodes
constructStringExprNode
{ "repo_name": "ehsan/js-symbolic-executor", "path": "closure-compiler/src/com/google/javascript/jscomp/ReplaceMessages.java", "license": "apache-2.0", "size": 12001 }
[ "com.google.javascript.rhino.Node", "com.google.javascript.rhino.Token", "java.util.Iterator" ]
import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.Iterator;
import com.google.javascript.rhino.*; import java.util.*;
[ "com.google.javascript", "java.util" ]
com.google.javascript; java.util;
1,879,973
private void validateContext() { Context context = Context.getContext(); StringBuffer errors = new StringBuffer(); if (context.getOutputGenerators() == null || context.getOutputGenerators().isEmpty()) { errors .append("No Output generators Specified in the Configuration\n"); }else{ if(context.getOutputGenerators().get(null)!=null){ errors .append("name attribute is required for Output generators Specified in the Configuration\n"); } } if (context.getOutputDir() == null || Utils.isEmpty(context.getOutputDir())) { errors.append("Output Folder Not specified in the Configuration\n"); } if (context.getDocuments() == null || context.getDocuments().isEmpty()) { errors .append("Input Documents Not specified in the Configuration\n"); } if (errors.length() > 0) { logger.severe("Configuration Exception"); throw new ConfigurationException(errors.toString() + "Run the tool with help=true argument for complete usage information"); } }
void function() { Context context = Context.getContext(); StringBuffer errors = new StringBuffer(); if (context.getOutputGenerators() == null context.getOutputGenerators().isEmpty()) { errors .append(STR); }else{ if(context.getOutputGenerators().get(null)!=null){ errors .append(STR); } } if (context.getOutputDir() == null Utils.isEmpty(context.getOutputDir())) { errors.append(STR); } if (context.getDocuments() == null context.getDocuments().isEmpty()) { errors .append(STR); } if (errors.length() > 0) { logger.severe(STR); throw new ConfigurationException(errors.toString() + STR); } }
/** * Validate context. */
Validate context
validateContext
{ "repo_name": "kingargyle/turmeric-wsdldoctool", "path": "wsdl-doc-tool/src/main/java/org/ebayopensource/turmeric/tools/annoparser/driver/Driver.java", "license": "apache-2.0", "size": 9292 }
[ "org.ebayopensource.turmeric.tools.annoparser.context.Context", "org.ebayopensource.turmeric.tools.annoparser.exception.ConfigurationException", "org.ebayopensource.turmeric.tools.annoparser.utils.Utils" ]
import org.ebayopensource.turmeric.tools.annoparser.context.Context; import org.ebayopensource.turmeric.tools.annoparser.exception.ConfigurationException; import org.ebayopensource.turmeric.tools.annoparser.utils.Utils;
import org.ebayopensource.turmeric.tools.annoparser.context.*; import org.ebayopensource.turmeric.tools.annoparser.exception.*; import org.ebayopensource.turmeric.tools.annoparser.utils.*;
[ "org.ebayopensource.turmeric" ]
org.ebayopensource.turmeric;
1,681,027
@Override public Adapter createCallQueryListAdapter() { if (callQueryListItemProvider == null) { callQueryListItemProvider = new CallQueryListItemProvider(this); } return callQueryListItemProvider; } protected ConfigurationPropertyItemProvider configurationPropertyItemProvider;
Adapter function() { if (callQueryListItemProvider == null) { callQueryListItemProvider = new CallQueryListItemProvider(this); } return callQueryListItemProvider; } protected ConfigurationPropertyItemProvider configurationPropertyItemProvider;
/** * This creates an adapter for a * {@link org.wso2.developerstudio.eclipse.ds.CallQueryList}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */
This creates an adapter for a <code>org.wso2.developerstudio.eclipse.ds.CallQueryList</code>.
createCallQueryListAdapter
{ "repo_name": "chanakaudaya/developer-studio", "path": "data-services/org.wso2.developerstudio.eclipse.ds.edit/src/org/wso2/developerstudio/eclipse/ds/provider/DsItemProviderAdapterFactory.java", "license": "apache-2.0", "size": 32467 }
[ "org.eclipse.emf.common.notify.Adapter" ]
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
1,921,320
public static void setParameterValuesToClassifier( ValidateableInterface classifier, HashMap<String, Object> paramValuesMap) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (classifier == null || paramValuesMap == null) { return; } Class clClass = classifier.getClass(); Set<String> paramNames = paramValuesMap.keySet(); for (String paramName: paramNames) { Object paramValue = paramValuesMap.get(paramName); Field fld = clClass.getDeclaredField(paramName); fld.setAccessible(true); if (paramValue != null) { try { if (fld.getType().equals(Float.TYPE) && paramValue.getClass().equals( Class.forName("java.lang.Double"))) { float fValue = ((Double) paramValue).floatValue(); fld.set(classifier, fValue); } else if (fld.getType().equals(Integer.TYPE) && (paramValue.getClass().equals( Class.forName("java.lang.Double")) || paramValue.getClass().equals( Class.forName("java.lang.Float")))) { int iValue = Math.round( ((Double) paramValue).floatValue()); fld.set(classifier, iValue); } else { fld.set(classifier, paramValue); } } catch (ClassNotFoundException ex) { Logger.getLogger( ClassifierParametrization.class.getName()).log( Level.SEVERE, null, ex); } } } }
static void function( ValidateableInterface classifier, HashMap<String, Object> paramValuesMap) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (classifier == null paramValuesMap == null) { return; } Class clClass = classifier.getClass(); Set<String> paramNames = paramValuesMap.keySet(); for (String paramName: paramNames) { Object paramValue = paramValuesMap.get(paramName); Field fld = clClass.getDeclaredField(paramName); fld.setAccessible(true); if (paramValue != null) { try { if (fld.getType().equals(Float.TYPE) && paramValue.getClass().equals( Class.forName(STR))) { float fValue = ((Double) paramValue).floatValue(); fld.set(classifier, fValue); } else if (fld.getType().equals(Integer.TYPE) && (paramValue.getClass().equals( Class.forName(STR)) paramValue.getClass().equals( Class.forName(STR)))) { int iValue = Math.round( ((Double) paramValue).floatValue()); fld.set(classifier, iValue); } else { fld.set(classifier, paramValue); } } catch (ClassNotFoundException ex) { Logger.getLogger( ClassifierParametrization.class.getName()).log( Level.SEVERE, null, ex); } } } }
/** * This method sets the provided parameter values to a classifier. It throws * an Exception if a wrong parameter name is provided, which does not exist * in the implementation. * * @param classifier ValidateableInterface that is the classifier to set the * parameter values to. * @param paramValuesMap HashMap<String, Object> that maps the parameter * values to set to the classifier. */
This method sets the provided parameter values to a classifier. It throws an Exception if a wrong parameter name is provided, which does not exist in the implementation
setParameterValuesToClassifier
{ "repo_name": "datapoet/hubminer", "path": "src/main/java/learning/supervised/evaluation/ClassifierParametrization.java", "license": "gpl-3.0", "size": 6378 }
[ "java.lang.reflect.Field", "java.util.HashMap", "java.util.Set", "java.util.logging.Level", "java.util.logging.Logger" ]
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger;
import java.lang.reflect.*; import java.util.*; import java.util.logging.*;
[ "java.lang", "java.util" ]
java.lang; java.util;
1,460,495
private void decodeParms(String parms, Map<String, String> p) { if (parms == null) { this.queryParameterString = ""; return; } this.queryParameterString = parms; StringTokenizer st = new StringTokenizer(parms, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); if (sep >= 0) { p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1))); } else { p.put(decodePercent(e).trim(), ""); } } }
void function(String parms, Map<String, String> p) { if (parms == null) { this.queryParameterString = STR&STR"); } } }
/** * Decodes parameters in percent-encoded URI-format ( e.g. * "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given * Map. NOTE: this doesn't support multiple identical keys due to the * simplicity of Map. */
Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given simplicity of Map
decodeParms
{ "repo_name": "vnnv/nanohttpd_vnnv", "path": "core/src/main/java/fi/iki/elonen/NanoHTTPD.java", "license": "bsd-3-clause", "size": 78692 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
267,491
void explain(ExplainRequest request, ActionListener<ExplainResponse> listener);
void explain(ExplainRequest request, ActionListener<ExplainResponse> listener);
/** * Computes a score explanation for the specified request. * * @param request The request encapsulating the query and document identifier to compute a score explanation for * @param listener A listener to be notified of the result */
Computes a score explanation for the specified request
explain
{ "repo_name": "ern/elasticsearch", "path": "server/src/main/java/org/elasticsearch/client/Client.java", "license": "apache-2.0", "size": 15097 }
[ "org.elasticsearch.action.ActionListener", "org.elasticsearch.action.explain.ExplainRequest", "org.elasticsearch.action.explain.ExplainResponse" ]
import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.explain.ExplainRequest; import org.elasticsearch.action.explain.ExplainResponse;
import org.elasticsearch.action.*; import org.elasticsearch.action.explain.*;
[ "org.elasticsearch.action" ]
org.elasticsearch.action;
344,591
@Override public ContainerRequest filter(ContainerRequest containerRequest) throws WebApplicationException { // GET, POST, PUT, DELETE, ... String method = containerRequest.getMethod(); // myresource/get/56bCA for example // String path = containerRequest.getPath(true); if (method.equals("OPTIONS")) { throw new WebApplicationException(Status.OK); } Action action = new Action(); action.put("method", method); // Get the authentification passed in HTTP headers parameters String auth = containerRequest.getHeaderValue("authorization"); GSClientProvider.setCredentials("dummy", "neh"); String userAgent = sr.getHeader(ContainerRequest.USER_AGENT); String remote = sr.getRemoteAddr(); String language = sr.getLocale().getLanguage(); action.put("remote", remote); action.put("request", sr.getRequestURI()); if (auth != null) { if (userAgent == null) { userAgent = ""; } // lap : loginAndPassword String[] lap = BasicAuth.decode(auth); // If login or password fail if (lap == null || lap.length != 2) { action.put("auth", "unauthorized"); throw new WebApplicationException(Status.UNAUTHORIZED); } if (lap[0].equals("public") && lap[1].equals("public")) { action.put("auth", "public"); return containerRequest; } UserEntry entry = null; String name = null; String actualPassword = null; try { entry = userAdapter.getUserInformationByToken(lap[1]); } catch (UserDataAdapterException e) { } boolean authenticated = false; if (entry != null && entry.getActive() > 0) { action.put("token", lap[1]); if (new Date().getTime() - entry.getTokenUpdateDate().getTime() < 10800000) { name = entry.getName(); actualPassword = entry.getPassword(); try { userAdapter.updateLastDate(entry.getToken()); authenticated = true; } catch (UserDataAdapterException e) { log.error(e.getMessage()); } } else { userAdapter.deactivateToken(entry.getToken()); } } if (!authenticated) { actualPassword = SHA1.encode(lap[1]); name = lap[0]; try { GSClientProvider.setCredentials(adminUsername, adminPassword); if (!userRepository.authenticateUser(name, actualPassword)) { if (!userRepository.authenticateUser(name, lap[1])) { throw new WebApplicationException( Status.UNAUTHORIZED); } else { actualPassword = lap[1]; } } if (language != null) { String[] languages = language.split(";"); if (languages.length > 0) { language = languages[0]; } } List<UserEntry> actives = userAdapter .getUserInformation(name); boolean newToken = true; String selectedToken = null; if (actives != null && actives.size() > 0) { for (UserEntry user : actives) { if (new Date().getTime() - user.getTokenUpdateDate().getTime() > 10800000) { userAdapter .deactivateToken(user.getToken()); } else { if (remote.equals(user.getRemote()) && userAgent.equals(user.getAgent())) { newToken = false; selectedToken = user.getToken(); } } } } if (newToken) { String token = userAdapter.createToken(name, actualPassword, language, userAgent, remote); userAdapter.activateToken(token); //userAdapter.deactivateOtherTokens(name, token); action.put("new-token", token); } else { userAdapter.updateLastDate(selectedToken); action.put("token", selectedToken); } sr.setAttribute("agent", userAgent); } catch (UserRepositoryException e) { log.error(e.getMessage()); } catch (UserDataAdapterException e) { log.error(e.getMessage()); } } sr.setAttribute("agent", userAgent); sr.setAttribute("remote", remote); sr.setAttribute("language", language); sr.setAttribute("user", name); action.put("user", name); sr.setAttribute("password", actualPassword); } else { action.put("auth", "empty"); } info(action); return containerRequest; }
ContainerRequest function(ContainerRequest containerRequest) throws WebApplicationException { String method = containerRequest.getMethod(); if (method.equals(STR)) { throw new WebApplicationException(Status.OK); } Action action = new Action(); action.put(STR, method); String auth = containerRequest.getHeaderValue(STR); GSClientProvider.setCredentials("dummySTRneh"); String userAgent = sr.getHeader(ContainerRequest.USER_AGENT); String remote = sr.getRemoteAddr(); String language = sr.getLocale().getLanguage(); action.put(STR, remote); action.put(STR, sr.getRequestURI()); if (auth != null) { if (userAgent == null) { userAgent = STRauthSTRunauthorizedSTRpublicSTRpublicSTRauthSTRpublicSTRtokenSTR;STRnew-tokenSTRtokenSTRagentSTRagent", userAgent); sr.setAttribute(STR, remote); sr.setAttribute("languageSTRuserSTRuserSTRpasswordSTRauthSTRempty"); } info(action); return containerRequest; }
/** * Apply the filter : check input request, validate or not with user auth * * @param containerRequest * The request from Tomcat server */
Apply the filter : check input request, validate or not with user auth
filter
{ "repo_name": "GLORIA-project/gloria-core", "path": "gloria-rest/src/main/java/eu/gloria/gs/services/api/security/AuthFilter.java", "license": "gpl-2.0", "size": 6957 }
[ "com.sun.jersey.spi.container.ContainerRequest", "eu.gloria.gs.services.core.client.GSClientProvider", "eu.gloria.gs.services.log.action.Action", "javax.ws.rs.WebApplicationException", "javax.ws.rs.core.Response" ]
import com.sun.jersey.spi.container.ContainerRequest; import eu.gloria.gs.services.core.client.GSClientProvider; import eu.gloria.gs.services.log.action.Action; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response;
import com.sun.jersey.spi.container.*; import eu.gloria.gs.services.core.client.*; import eu.gloria.gs.services.log.action.*; import javax.ws.rs.*; import javax.ws.rs.core.*;
[ "com.sun.jersey", "eu.gloria.gs", "javax.ws" ]
com.sun.jersey; eu.gloria.gs; javax.ws;
2,733,506
@Override public T visitElementValuePairList(@NotNull Java8Parser.ElementValuePairListContext ctx) { return visitChildren(ctx); }
@Override public T visitElementValuePairList(@NotNull Java8Parser.ElementValuePairListContext ctx) { return visitChildren(ctx); }
/** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */
The default implementation returns the result of calling <code>#visitChildren</code> on ctx
visitType
{ "repo_name": "IsThisThePayneResidence/intellidots", "path": "src/main/java/ua/edu/hneu/ast/parsers/Java8BaseVisitor.java", "license": "gpl-3.0", "size": 65479 }
[ "org.antlr.v4.runtime.misc.NotNull" ]
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.misc.*;
[ "org.antlr.v4" ]
org.antlr.v4;
1,462,831
public static String[] getTypeNamesById(Integer bronId) throws Exception { Session sess = HibernateUtil.getSessionFactory().getCurrentSession(); Bron bron = (Bron) sess.get(Bron.class, bronId); return getTypeNames(bron, true); }
static String[] function(Integer bronId) throws Exception { Session sess = HibernateUtil.getSessionFactory().getCurrentSession(); Bron bron = (Bron) sess.get(Bron.class, bronId); return getTypeNames(bron, true); }
/** * Haalt de mogelijke featureTypeNames van een bron op adhv het id van de * bron * */
Haalt de mogelijke featureTypeNames van een bron op adhv het id van de bron
getTypeNamesById
{ "repo_name": "B3Partners/b3p-gisviewerConfig", "path": "src/main/java/nl/b3p/gis/viewer/zoekconfiguratie/ZoekConfiguratieListUtil.java", "license": "lgpl-3.0", "size": 3394 }
[ "nl.b3p.gis.viewer.services.HibernateUtil", "nl.b3p.zoeker.configuratie.Bron", "org.hibernate.Session" ]
import nl.b3p.gis.viewer.services.HibernateUtil; import nl.b3p.zoeker.configuratie.Bron; import org.hibernate.Session;
import nl.b3p.gis.viewer.services.*; import nl.b3p.zoeker.configuratie.*; import org.hibernate.*;
[ "nl.b3p.gis", "nl.b3p.zoeker", "org.hibernate" ]
nl.b3p.gis; nl.b3p.zoeker; org.hibernate;
709,067
//----------------------------------------------------------------------- public final MetaProperty<DataSource> dataSource() { return _dataSource; }
final MetaProperty<DataSource> function() { return _dataSource; }
/** * The meta-property for the {@code dataSource} property. * @return the meta-property, not null */
The meta-property for the dataSource property
dataSource
{ "repo_name": "DevStreet/FinanceAnalytics", "path": "projects/OG-Component/src/main/java/com/opengamma/component/factory/infrastructure/DbConnectorComponentFactory.java", "license": "apache-2.0", "size": 31862 }
[ "javax.sql.DataSource", "org.joda.beans.MetaProperty" ]
import javax.sql.DataSource; import org.joda.beans.MetaProperty;
import javax.sql.*; import org.joda.beans.*;
[ "javax.sql", "org.joda.beans" ]
javax.sql; org.joda.beans;
2,533,193
@Override public String toString() { StringBuilder result = new StringBuilder(256); sortFields(); int sumPositions = 0; int sumTerms = 0; final BytesRef spare = new BytesRef(); for (int i=0; i < sortedFields.length; i++) { Map.Entry<String,Info> entry = sortedFields[i]; String fieldName = entry.getKey(); Info info = entry.getValue(); info.sortTerms(); result.append(fieldName + ":\n"); SliceByteStartArray sliceArray = info.sliceArray; int numPositions = 0; SliceReader postingsReader = new SliceReader(intBlockPool); for (int j=0; j < info.terms.size(); j++) { int ord = info.sortedTerms[j]; info.terms.get(ord, spare); int freq = sliceArray.freq[ord]; result.append("\t'" + spare + "':" + freq + ":"); postingsReader.reset(sliceArray.start[ord], sliceArray.end[ord]); result.append(" ["); final int iters = storeOffsets ? 3 : 1; while(!postingsReader.endOfSlice()) { result.append("("); for (int k = 0; k < iters; k++) { result.append(postingsReader.readInt()); if (k < iters-1) { result.append(", "); } } result.append(")"); if (!postingsReader.endOfSlice()) { result.append(","); } } result.append("]"); result.append("\n"); numPositions += freq; } result.append("\tterms=" + info.terms.size()); result.append(", positions=" + numPositions); result.append(", memory=" + RamUsageEstimator.humanReadableUnits(RamUsageEstimator.sizeOf(info))); result.append("\n"); sumPositions += numPositions; sumTerms += info.terms.size(); } result.append("\nfields=" + sortedFields.length); result.append(", terms=" + sumTerms); result.append(", positions=" + sumPositions); result.append(", memory=" + RamUsageEstimator.humanReadableUnits(getMemorySize())); return result.toString(); } private static final class Info { private final BytesRefHash terms; private final SliceByteStartArray sliceArray; private transient int[] sortedTerms; private final int numTokens; private final int numOverlapTokens; private final float boost; private final long sumTotalTermFreq; private int lastPosition; private int lastOffset; public Info(BytesRefHash terms, SliceByteStartArray sliceArray, int numTokens, int numOverlapTokens, float boost, int lastPosition, int lastOffset, long sumTotalTermFreq) { this.terms = terms; this.sliceArray = sliceArray; this.numTokens = numTokens; this.numOverlapTokens = numOverlapTokens; this.boost = boost; this.sumTotalTermFreq = sumTotalTermFreq; this.lastPosition = lastPosition; this.lastOffset = lastOffset; }
String function() { StringBuilder result = new StringBuilder(256); sortFields(); int sumPositions = 0; int sumTerms = 0; final BytesRef spare = new BytesRef(); for (int i=0; i < sortedFields.length; i++) { Map.Entry<String,Info> entry = sortedFields[i]; String fieldName = entry.getKey(); Info info = entry.getValue(); info.sortTerms(); result.append(fieldName + ":\n"); SliceByteStartArray sliceArray = info.sliceArray; int numPositions = 0; SliceReader postingsReader = new SliceReader(intBlockPool); for (int j=0; j < info.terms.size(); j++) { int ord = info.sortedTerms[j]; info.terms.get(ord, spare); int freq = sliceArray.freq[ord]; result.append("\t'" + spare + "':" + freq + ":"); postingsReader.reset(sliceArray.start[ord], sliceArray.end[ord]); result.append(STR); final int iters = storeOffsets ? 3 : 1; while(!postingsReader.endOfSlice()) { result.append("("); for (int k = 0; k < iters; k++) { result.append(postingsReader.readInt()); if (k < iters-1) { result.append(STR); } } result.append(")"); if (!postingsReader.endOfSlice()) { result.append(","); } } result.append("]"); result.append("\n"); numPositions += freq; } result.append(STR + info.terms.size()); result.append(STR + numPositions); result.append(STR + RamUsageEstimator.humanReadableUnits(RamUsageEstimator.sizeOf(info))); result.append("\n"); sumPositions += numPositions; sumTerms += info.terms.size(); } result.append(STR + sortedFields.length); result.append(STR + sumTerms); result.append(STR + sumPositions); result.append(STR + RamUsageEstimator.humanReadableUnits(getMemorySize())); return result.toString(); } private static final class Info { private final BytesRefHash terms; private final SliceByteStartArray sliceArray; private transient int[] sortedTerms; private final int numTokens; private final int numOverlapTokens; private final float boost; private final long sumTotalTermFreq; private int lastPosition; private int lastOffset; public Info(BytesRefHash terms, SliceByteStartArray sliceArray, int numTokens, int numOverlapTokens, float boost, int lastPosition, int lastOffset, long sumTotalTermFreq) { this.terms = terms; this.sliceArray = sliceArray; this.numTokens = numTokens; this.numOverlapTokens = numOverlapTokens; this.boost = boost; this.sumTotalTermFreq = sumTotalTermFreq; this.lastPosition = lastPosition; this.lastOffset = lastOffset; }
/** * Returns a String representation of the index data for debugging purposes. * * @return the string representation */
Returns a String representation of the index data for debugging purposes
toString
{ "repo_name": "yintaoxue/read-open-source-code", "path": "solr-4.7.2/src/org/apache/lucene/index/memory/MemoryIndex.java", "license": "apache-2.0", "size": 44614 }
[ "java.util.Map", "org.apache.lucene.util.BytesRef", "org.apache.lucene.util.BytesRefHash", "org.apache.lucene.util.IntBlockPool", "org.apache.lucene.util.RamUsageEstimator" ]
import java.util.Map; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.apache.lucene.util.IntBlockPool; import org.apache.lucene.util.RamUsageEstimator;
import java.util.*; import org.apache.lucene.util.*;
[ "java.util", "org.apache.lucene" ]
java.util; org.apache.lucene;
1,575,060
@Test public void testGet() { DiskImageDynamic result = dao.get(existingDynamic.getId()); assertNotNull(result); assertEquals(existingDynamic, result); }
void function() { DiskImageDynamic result = dao.get(existingDynamic.getId()); assertNotNull(result); assertEquals(existingDynamic, result); }
/** * Ensures that retrieving the dynamic image works as expected. */
Ensures that retrieving the dynamic image works as expected
testGet
{ "repo_name": "jbeecham/ovirt-engine", "path": "backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/DiskImageDynamicDAOTest.java", "license": "apache-2.0", "size": 5117 }
[ "org.junit.Assert", "org.ovirt.engine.core.common.businessentities.DiskImageDynamic" ]
import org.junit.Assert; import org.ovirt.engine.core.common.businessentities.DiskImageDynamic;
import org.junit.*; import org.ovirt.engine.core.common.businessentities.*;
[ "org.junit", "org.ovirt.engine" ]
org.junit; org.ovirt.engine;
81,634
public ScheduledEpochDataEntryStatus evaluateScheduledEpochDataEntryStatus(List<Error> errors) { boolean hasError= false; if (this.getEpoch().getStratificationIndicator()){ if (!this.evaluateStratificationIndicator()) { hasError= true; errors.add(new Error("The subject needs to be assgined a stratum group number on scheduled epoch :" + this.getEpoch().getName())); } } if (!this.getEligibilityIndicator()) { hasError= true; errors.add(new Error("The subject does not meet the eligibility criteria on scheduled epoch :" + this.getEpoch().getName())); } if (this.getRequiresArm() && !this.getRequiresRandomization() && (this.getScheduledArm() == null || this .getScheduledArm().getArm() == null)) { hasError= true; errors.add(new Error("The subject is not assigned to a scheduled arm")); } if(hasError){ return ScheduledEpochDataEntryStatus.INCOMPLETE; } return ScheduledEpochDataEntryStatus.COMPLETE; }
ScheduledEpochDataEntryStatus function(List<Error> errors) { boolean hasError= false; if (this.getEpoch().getStratificationIndicator()){ if (!this.evaluateStratificationIndicator()) { hasError= true; errors.add(new Error(STR + this.getEpoch().getName())); } } if (!this.getEligibilityIndicator()) { hasError= true; errors.add(new Error(STR + this.getEpoch().getName())); } if (this.getRequiresArm() && !this.getRequiresRandomization() && (this.getScheduledArm() == null this .getScheduledArm().getArm() == null)) { hasError= true; errors.add(new Error(STR)); } if(hasError){ return ScheduledEpochDataEntryStatus.INCOMPLETE; } return ScheduledEpochDataEntryStatus.COMPLETE; }
/** * Evaluate scheduled epoch data entry status. * * @param errors the errors * * @return the scheduled epoch data entry status */
Evaluate scheduled epoch data entry status
evaluateScheduledEpochDataEntryStatus
{ "repo_name": "NCIP/c3pr", "path": "codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/ScheduledEpoch.java", "license": "bsd-3-clause", "size": 23900 }
[ "edu.duke.cabig.c3pr.constants.ScheduledEpochDataEntryStatus", "java.util.List" ]
import edu.duke.cabig.c3pr.constants.ScheduledEpochDataEntryStatus; import java.util.List;
import edu.duke.cabig.c3pr.constants.*; import java.util.*;
[ "edu.duke.cabig", "java.util" ]
edu.duke.cabig; java.util;
2,758,203
public Player getEnchanter() { return enchanter; }
Player function() { return enchanter; }
/** * Gets the player enchanting the item * * @return enchanting player */
Gets the player enchanting the item
getEnchanter
{ "repo_name": "LapisBlue/Porekit", "path": "src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java", "license": "gpl-3.0", "size": 3135 }
[ "org.bukkit.entity.Player" ]
import org.bukkit.entity.Player;
import org.bukkit.entity.*;
[ "org.bukkit.entity" ]
org.bukkit.entity;
1,864,733
public void init(String ticket, String workspaceName, Map<String, Object> attributes) throws RepositoryException { // create appropriate strategy for handling session isolation // TODO: Support full session isolation as described in the JCR specification String trxId = AlfrescoTransactionSupport.getTransactionId(); sessionIsolation = (trxId == null) ? new InnerTransaction() : new OuterTransaction(); sessionIsolation.begin(); // initialise the session this.ticket = ticket; this.attributes = (attributes == null) ? new HashMap<String, Object>() : attributes; this.workspaceStore = getWorkspaceStore(workspaceName); }
void function(String ticket, String workspaceName, Map<String, Object> attributes) throws RepositoryException { String trxId = AlfrescoTransactionSupport.getTransactionId(); sessionIsolation = (trxId == null) ? new InnerTransaction() : new OuterTransaction(); sessionIsolation.begin(); this.ticket = ticket; this.attributes = (attributes == null) ? new HashMap<String, Object>() : attributes; this.workspaceStore = getWorkspaceStore(workspaceName); }
/** * Initialise Session * * @param ticket authentication ticket * @param workspaceName workspace name * @param attributes session attributes * @throws RepositoryException */
Initialise Session
init
{ "repo_name": "loftuxab/community-edition-old", "path": "projects/repository/source/java/org/alfresco/jcr/session/SessionImpl.java", "license": "lgpl-3.0", "size": 35135 }
[ "java.util.HashMap", "java.util.Map", "javax.jcr.RepositoryException", "org.alfresco.repo.transaction.AlfrescoTransactionSupport" ]
import java.util.HashMap; import java.util.Map; import javax.jcr.RepositoryException; import org.alfresco.repo.transaction.AlfrescoTransactionSupport;
import java.util.*; import javax.jcr.*; import org.alfresco.repo.transaction.*;
[ "java.util", "javax.jcr", "org.alfresco.repo" ]
java.util; javax.jcr; org.alfresco.repo;
1,722,361
public Address[] getRecipients() { Address[] address = new InternetAddress[recipients.size()]; return this.recipients.toArray(address); }
Address[] function() { Address[] address = new InternetAddress[recipients.size()]; return this.recipients.toArray(address); }
/** * Get the list of recipients as an array * * @return The recipients */
Get the list of recipients as an array
getRecipients
{ "repo_name": "jaapgeurts/snap", "path": "src/main/java/snap/mail/Mailer.java", "license": "gpl-2.0", "size": 11691 }
[ "javax.mail.Address", "javax.mail.internet.InternetAddress" ]
import javax.mail.Address; import javax.mail.internet.InternetAddress;
import javax.mail.*; import javax.mail.internet.*;
[ "javax.mail" ]
javax.mail;
2,154,151
public static List<ExecutableElement> getAllMethodsIn(Elements elements, TypeElement type) { List<ExecutableElement> meths = new ArrayList<ExecutableElement>(); meths.addAll(ElementFilter.methodsIn(type.getEnclosedElements())); List<TypeElement> alltypes = getSuperTypes(elements, type); for (TypeElement atype : alltypes) { meths.addAll(ElementFilter.methodsIn(atype.getEnclosedElements())); } return Collections.unmodifiableList(meths); }
static List<ExecutableElement> function(Elements elements, TypeElement type) { List<ExecutableElement> meths = new ArrayList<ExecutableElement>(); meths.addAll(ElementFilter.methodsIn(type.getEnclosedElements())); List<TypeElement> alltypes = getSuperTypes(elements, type); for (TypeElement atype : alltypes) { meths.addAll(ElementFilter.methodsIn(atype.getEnclosedElements())); } return Collections.unmodifiableList(meths); }
/** * Return all methods declared in the given type or any superclass/interface. Note that no * constructors will be returned. TODO: should this use * javax.lang.model.util.Elements.getAllMembers(TypeElement) instead of our own getSuperTypes? */
Return all methods declared in the given type or any superclass/interface. Note that no javax.lang.model.util.Elements.getAllMembers(TypeElement) instead of our own getSuperTypes
getAllMethodsIn
{ "repo_name": "CharlesZ-Chen/checker-framework", "path": "javacutil/src/org/checkerframework/javacutil/ElementUtils.java", "license": "gpl-2.0", "size": 19493 }
[ "java.util.ArrayList", "java.util.Collections", "java.util.List", "javax.lang.model.element.ExecutableElement", "javax.lang.model.element.TypeElement", "javax.lang.model.util.ElementFilter", "javax.lang.model.util.Elements" ]
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements;
import java.util.*; import javax.lang.model.element.*; import javax.lang.model.util.*;
[ "java.util", "javax.lang" ]
java.util; javax.lang;
1,100,472
public void setShapes(ArrayList<Shape> shapes) { this.shapes = shapes; }
void function(ArrayList<Shape> shapes) { this.shapes = shapes; }
/** * set a new ArrayList<Shape> * * @param shapes * the shapes to set */
set a new ArrayList
setShapes
{ "repo_name": "MetSystem/jbpm-designer", "path": "jbpm-designer-backend/src/main/java/org/jbpm/designer/server/diagram/Diagram.java", "license": "apache-2.0", "size": 3656 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
124,442
Set<String> resourcePaths = scanForResourcePaths(location, null, nameFilter, null, null); if (resourcePaths.isEmpty()) { return null; } else { return resourcePaths.iterator().next(); } }
Set<String> resourcePaths = scanForResourcePaths(location, null, nameFilter, null, null); if (resourcePaths.isEmpty()) { return null; } else { return resourcePaths.iterator().next(); } }
/** * <p> * Finds the logical path of the first resource that matches the given * {@code resourceName} by scanning the classpath under the given * {@code location}. * </p> * <p> * By default, no other condition but the name will be applied to the * resource name. * </p> * * @param location * The classpath location where to scan. * @param nameFilter * The name of the resource to look for. * @return The logical path of the resource if found, otherwise {@code null} */
Finds the logical path of the first resource that matches the given resourceName by scanning the classpath under the given location. By default, no other condition but the name will be applied to the resource name.
findResourcePath
{ "repo_name": "pioto/dandelion", "path": "dandelion-core/src/main/java/com/github/dandelion/core/util/scanner/ClasspathResourceScanner.java", "license": "bsd-3-clause", "size": 14316 }
[ "java.util.Set" ]
import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
1,763,762
public void run() { try { // make the connection this.mURLConnection.connect(); } catch (UnknownHostException e) { this.mError = new ERMgmtUnknownHostException("Unknown/Invalid Host : " + e.getMessage()); } catch (ConnectException e) { this.mError = new ERMgmtConnectException("unable to connect: " + e.getMessage()); } catch (NoRouteToHostException e) { this.mError = new ERMgmtNoRouteToHostException("no route to host: " + e.getMessage()); } catch (SSLHandshakeException e){ Throwable nextE = e.getCause(); ERTrustManagerCertificateException mye; while((nextE != null) && !(nextE instanceof ERTrustManagerCertificateException)){ nextE = nextE.getCause(); } if(nextE == null){ this.mError = new ERMgmtException("Connection Exception: " + e.toString()); } else{ mye = (ERTrustManagerCertificateException) nextE; this.mError = new ERMgmtCertificateException(nextE.getMessage(), mye.getCertificate()); } }catch (Throwable e) { this.mError = new ERMgmtIOException("connection Exception: " + e.toString()); } // if time elapsed if (mTimedOut) { // no exception and just return mError = null; return; } // indicate connection was made this.mConnected = true; return; } } // the cached custom ssl factory private static SSLSocketFactory mCachedCustomSSLSocketFactory = null; // device profile private DeviceProfile mProfile; // device url private URL mURL;
void function() { try { this.mURLConnection.connect(); } catch (UnknownHostException e) { this.mError = new ERMgmtUnknownHostException(STR + e.getMessage()); } catch (ConnectException e) { this.mError = new ERMgmtConnectException(STR + e.getMessage()); } catch (NoRouteToHostException e) { this.mError = new ERMgmtNoRouteToHostException(STR + e.getMessage()); } catch (SSLHandshakeException e){ Throwable nextE = e.getCause(); ERTrustManagerCertificateException mye; while((nextE != null) && !(nextE instanceof ERTrustManagerCertificateException)){ nextE = nextE.getCause(); } if(nextE == null){ this.mError = new ERMgmtException(STR + e.toString()); } else{ mye = (ERTrustManagerCertificateException) nextE; this.mError = new ERMgmtCertificateException(nextE.getMessage(), mye.getCertificate()); } }catch (Throwable e) { this.mError = new ERMgmtIOException(STR + e.toString()); } if (mTimedOut) { mError = null; return; } this.mConnected = true; return; } } private static SSLSocketFactory mCachedCustomSSLSocketFactory = null; private DeviceProfile mProfile; private URL mURL;
/** * This thread actually make the connection * * @see java.lang.Runnable#run() */
This thread actually make the connection
run
{ "repo_name": "ibm-datapower/ertool", "path": "framework/src/com/ibm/datapower/er/mgmt/ERConnection.java", "license": "apache-2.0", "size": 24083 }
[ "java.net.ConnectException", "java.net.NoRouteToHostException", "java.net.UnknownHostException", "javax.net.ssl.SSLHandshakeException", "javax.net.ssl.SSLSocketFactory" ]
import java.net.ConnectException; import java.net.NoRouteToHostException; import java.net.UnknownHostException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory;
import java.net.*; import javax.net.ssl.*;
[ "java.net", "javax.net" ]
java.net; javax.net;
160,197
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { HttpSession httpSession = request.getSession(); String view = getFormView(); if (Context.isAuthenticated()) { String[] conversionIdList = request.getParameterValues("conceptStateConversionId"); ProgramWorkflowService pws = Context.getProgramWorkflowService(); StringBuilder success = new StringBuilder(""); StringBuilder error = new StringBuilder(""); int numDeleted = 0; MessageSourceAccessor msa = getMessageSourceAccessor(); String deleted = msa.getMessage("general.deleted"); String notDeleted = msa.getMessage("general.cannot.delete"); String textConversion = msa.getMessage("Program.conversion"); String noneDeleted = msa.getMessage("Program.conversion.nonedeleted"); if (conversionIdList != null) { for (String id : conversionIdList) { try { pws.purgeConceptStateConversion(pws.getConceptStateConversion(Integer.valueOf(id))); if (!"".equals(success)) { success.append("<br/>"); } success.append(textConversion).append(" ").append(id).append(" ").append(deleted); numDeleted++; } catch (APIException e) { log.warn("Error deleting concept state conversion", e); if (!"".equals(error)) { error.append("<br/>"); } error.append(textConversion).append(" ").append(id).append(" ").append(notDeleted); } } if (numDeleted > 3) { success = new StringBuilder(numDeleted).append(" ").append(deleted); } } else { success.append(noneDeleted); } view = getSuccessView(); if (!"".equals(success)) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success.toString()); } if (!"".equals(error)) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error.toString()); } } return new ModelAndView(new RedirectView(view)); }
ModelAndView function(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { HttpSession httpSession = request.getSession(); String view = getFormView(); if (Context.isAuthenticated()) { String[] conversionIdList = request.getParameterValues(STR); ProgramWorkflowService pws = Context.getProgramWorkflowService(); StringBuilder success = new StringBuilder(STRSTRgeneral.deletedSTRgeneral.cannot.deleteSTRProgram.conversionSTRProgram.conversion.nonedeletedSTRSTR<br/>STR STR STRError deleting concept state conversionSTRSTR<br/>STR STR STR STRSTR".equals(error)) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error.toString()); } } return new ModelAndView(new RedirectView(view)); }
/** * The onSubmit function receives the form/command object that was modified by the input form * and saves it to the db * * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) */
The onSubmit function receives the form/command object that was modified by the input form and saves it to the db
onSubmit
{ "repo_name": "nilusi/Legacy-UI", "path": "web/src/main/java/org/openmrs/web/controller/program/StateConversionListController.java", "license": "mpl-2.0", "size": 4598 }
[ "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse", "javax.servlet.http.HttpSession", "org.openmrs.api.ProgramWorkflowService", "org.openmrs.api.context.Context", "org.openmrs.web.WebConstants", "org.springframework.validation.BindException", "org.springframework.web.servlet.ModelAndView", "org.springframework.web.servlet.view.RedirectView" ]
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.openmrs.api.ProgramWorkflowService; import org.openmrs.api.context.Context; import org.openmrs.web.WebConstants; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.*; import org.openmrs.api.*; import org.openmrs.api.context.*; import org.openmrs.web.*; import org.springframework.validation.*; import org.springframework.web.servlet.*; import org.springframework.web.servlet.view.*;
[ "javax.servlet", "org.openmrs.api", "org.openmrs.web", "org.springframework.validation", "org.springframework.web" ]
javax.servlet; org.openmrs.api; org.openmrs.web; org.springframework.validation; org.springframework.web;
2,188,469
public static FacebookUser createFacebookUser(String accessToken) { FacebookClient facebookClient = new DefaultFacebookClient(accessToken); User user = facebookClient.fetchObject("me", User.class); FacebookUser facebookUser = new FacebookUser(facebookClient, user, accessToken); FacebookDataFetcher dataFetcher = new FacebookDataFetcher(facebookUser); dataFetcher.complete(); facebookUser.setFriendList(retrieveFriends(facebookUser)); assertNotNull(facebookUser); return facebookUser; }
static FacebookUser function(String accessToken) { FacebookClient facebookClient = new DefaultFacebookClient(accessToken); User user = facebookClient.fetchObject("me", User.class); FacebookUser facebookUser = new FacebookUser(facebookClient, user, accessToken); FacebookDataFetcher dataFetcher = new FacebookDataFetcher(facebookUser); dataFetcher.complete(); facebookUser.setFriendList(retrieveFriends(facebookUser)); assertNotNull(facebookUser); return facebookUser; }
/** * This class creates an FacebookUser object with given access token * * @param accessToken * accessToken of user to be created * @return */
This class creates an FacebookUser object with given access token
createFacebookUser
{ "repo_name": "GalaksiyaIT/socialcrawler", "path": "test/com/galaksiya/social/TestUtil.java", "license": "apache-2.0", "size": 6603 }
[ "com.galaksiya.social.entity.FacebookUser", "com.galaksiya.social.fetcher.FacebookDataFetcher", "com.restfb.DefaultFacebookClient", "com.restfb.FacebookClient", "com.restfb.types.User", "org.junit.Assert" ]
import com.galaksiya.social.entity.FacebookUser; import com.galaksiya.social.fetcher.FacebookDataFetcher; import com.restfb.DefaultFacebookClient; import com.restfb.FacebookClient; import com.restfb.types.User; import org.junit.Assert;
import com.galaksiya.social.entity.*; import com.galaksiya.social.fetcher.*; import com.restfb.*; import com.restfb.types.*; import org.junit.*;
[ "com.galaksiya.social", "com.restfb", "com.restfb.types", "org.junit" ]
com.galaksiya.social; com.restfb; com.restfb.types; org.junit;
2,684,485
HRegionLocation getRegionLocation(byte [] tableName, byte [] row, boolean reload) throws IOException;
HRegionLocation getRegionLocation(byte [] tableName, byte [] row, boolean reload) throws IOException;
/** * Find region location hosting passed row * @param tableName table name * @param row Row to find. * @param reload If true do not use cache, otherwise bypass. * @return Location of row. * @throws IOException if a remote or network exception occurs */
Find region location hosting passed row
getRegionLocation
{ "repo_name": "ddraj/hbase-trunk-mttr", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java", "license": "apache-2.0", "size": 15268 }
[ "java.io.IOException", "org.apache.hadoop.hbase.HRegionLocation" ]
import java.io.IOException; import org.apache.hadoop.hbase.HRegionLocation;
import java.io.*; import org.apache.hadoop.hbase.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
57,254
public static Calendar floor(Calendar calendar) { if (calendar == null) { return null; } calendar = (Calendar) calendar.clone(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; }
static Calendar function(Calendar calendar) { if (calendar == null) { return null; } calendar = (Calendar) calendar.clone(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; }
/** * Returns a calendar rounded down to the previous midnight. */
Returns a calendar rounded down to the previous midnight
floor
{ "repo_name": "inevo/mondrian", "path": "src/main/mondrian/util/Schedule.java", "license": "epl-1.0", "size": 31331 }
[ "java.util.Calendar" ]
import java.util.Calendar;
import java.util.*;
[ "java.util" ]
java.util;
2,448,198
public void setInputWidgetKeyListener(KeyListener input) { getInputWidget().setKeyListener(input); }
void function(KeyListener input) { getInputWidget().setKeyListener(input); }
/** * Delegate method for the input widget */
Delegate method for the input widget
setInputWidgetKeyListener
{ "repo_name": "awesome-niu/android-floatinglabel-widgets", "path": "library/src/main/java/com/marvinlabs/widget/floatinglabel/edittext/FloatingLabelEditText.java", "license": "apache-2.0", "size": 7203 }
[ "android.text.method.KeyListener" ]
import android.text.method.KeyListener;
import android.text.method.*;
[ "android.text" ]
android.text;
2,621,868
static public DataKeys getDataKeys() { return keys; } private final List<BasicAccount> accounts = new ArrayList<>(); final private AgentDataset agentDataset; final private BankCheque bankCheque = new BankCheque(); final private BankConstants cons; private long debtCancellationCount; private long debtCancellationValue; private final BasicAmount depositsAmount = new BasicAmount(); final private int id; private long installments = 0; private long interests = 0; private long interestsNormal = 0; private long interestsOverdue = 0; final private List<Loan> loans = new LinkedList<>(); private final BasicAmount outstandingDebtAmount = new BasicAmount(); private final BasicAmount overdueDebtAmount = new BasicAmount(); final private List<Loan> overdueDebts = new LinkedList<>(); final private List<Equity> ownership = new LinkedList<>(); private PeriodDataset periodDataset; private float rateNormal = 0; private float ratePenalty = 0; private Float realRate = 0f; final private Sector sector; public BasicBank(final Sector sector, final int id) { super(sector.getSimulation()); this.sector = sector; this.id = id; final Parameters params = this.sector.getParameters(); ArgChecks.nullNotPermitted(params, "params"); this.cons = new BankConstants(params); this.agentDataset = new BasicAgentDataset(this); }
static DataKeys function() { return keys; } private final List<BasicAccount> accounts = new ArrayList<>(); final private AgentDataset agentDataset; final private BankCheque bankCheque = new BankCheque(); final private BankConstants cons; private long debtCancellationCount; private long debtCancellationValue; private final BasicAmount depositsAmount = new BasicAmount(); final private int id; private long installments = 0; private long interests = 0; private long interestsNormal = 0; private long interestsOverdue = 0; final private List<Loan> loans = new LinkedList<>(); private final BasicAmount outstandingDebtAmount = new BasicAmount(); private final BasicAmount overdueDebtAmount = new BasicAmount(); final private List<Loan> overdueDebts = new LinkedList<>(); final private List<Equity> ownership = new LinkedList<>(); private PeriodDataset periodDataset; private float rateNormal = 0; private float ratePenalty = 0; private Float realRate = 0f; final private Sector sector; public BasicBank(final Sector sector, final int id) { super(sector.getSimulation()); this.sector = sector; this.id = id; final Parameters params = this.sector.getParameters(); ArgChecks.nullNotPermitted(params, STR); this.cons = new BankConstants(params); this.agentDataset = new BasicAgentDataset(this); }
/** * Returns the data keys. * * @return the data keys. */
Returns the data keys
getDataKeys
{ "repo_name": "pseppecher/jamel", "path": "src/jamel/models/m18/r02/banks/BasicBank.java", "license": "gpl-3.0", "size": 28216 }
[ "java.util.ArrayList", "java.util.LinkedList", "java.util.List" ]
import java.util.ArrayList; import java.util.LinkedList; import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
2,356,439
@SuppressWarnings("unchecked") public Type process(String ref) { ProcessDefinition answer = new ProcessDefinition(); answer.setRef(ref); addOutput(answer); return (Type) this; } /** * <a href="http://camel.apache.org/message-translator.html">Message Translator EIP:</a> * Adds the custom processor reference to this destination which could be a final * destination, or could be a transformation in a pipeline * * @param ref reference to a {@link Processor} to lookup in the registry * @return the builder * @deprecated use {@link #process(String)}
@SuppressWarnings(STR) Type function(String ref) { ProcessDefinition answer = new ProcessDefinition(); answer.setRef(ref); addOutput(answer); return (Type) this; } /** * <a href="http: * Adds the custom processor reference to this destination which could be a final * destination, or could be a transformation in a pipeline * * @param ref reference to a {@link Processor} to lookup in the registry * @return the builder * @deprecated use {@link #process(String)}
/** * <a href="http://camel.apache.org/message-translator.html">Message Translator EIP:</a> * Adds the custom processor reference to this destination which could be a final * destination, or could be a transformation in a pipeline * * @param ref reference to a {@link Processor} to lookup in the registry * @return the builder */
Adds the custom processor reference to this destination which could be a final destination, or could be a transformation in a pipeline
process
{ "repo_name": "oscerd/camel", "path": "camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java", "license": "apache-2.0", "size": 144870 }
[ "org.apache.camel.Processor" ]
import org.apache.camel.Processor;
import org.apache.camel.*;
[ "org.apache.camel" ]
org.apache.camel;
945,674
private String getAddressListFromTool(TestType type, HdfsConfiguration conf, boolean success) throws Exception { String[] args = new String[1]; switch (type) { case NAMENODE: args[0] = Command.NAMENODE.getName(); break; case NNRPCADDRESSES: args[0] = Command.NNRPCADDRESSES.getName(); break; } return runTool(conf, args, success); }
String function(TestType type, HdfsConfiguration conf, boolean success) throws Exception { String[] args = new String[1]; switch (type) { case NAMENODE: args[0] = Command.NAMENODE.getName(); break; case NNRPCADDRESSES: args[0] = Command.NNRPCADDRESSES.getName(); break; } return runTool(conf, args, success); }
/** * Get address list for a given type of address. Command expected to * fail if {@code success} is false. * * @return returns the success or error output from the tool. */
Get address list for a given type of address. Command expected to fail if success is false
getAddressListFromTool
{ "repo_name": "robzor92/hops", "path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/tools/TestGetConf.java", "license": "apache-2.0", "size": 9486 }
[ "org.apache.hadoop.hdfs.HdfsConfiguration", "org.apache.hadoop.hdfs.tools.GetConf" ]
import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.tools.GetConf;
import org.apache.hadoop.hdfs.*; import org.apache.hadoop.hdfs.tools.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
586,553
public VpnSiteLinkInner withBgpProperties(VpnLinkBgpSettings bgpProperties) { this.bgpProperties = bgpProperties; return this; }
VpnSiteLinkInner function(VpnLinkBgpSettings bgpProperties) { this.bgpProperties = bgpProperties; return this; }
/** * Set the set of bgp properties. * * @param bgpProperties the bgpProperties value to set * @return the VpnSiteLinkInner object itself. */
Set the set of bgp properties
withBgpProperties
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/network/mgmt-v2019_07_01/src/main/java/com/microsoft/azure/management/network/v2019_07_01/implementation/VpnSiteLinkInner.java", "license": "mit", "size": 5247 }
[ "com.microsoft.azure.management.network.v2019_07_01.VpnLinkBgpSettings" ]
import com.microsoft.azure.management.network.v2019_07_01.VpnLinkBgpSettings;
import com.microsoft.azure.management.network.v2019_07_01.*;
[ "com.microsoft.azure" ]
com.microsoft.azure;
865,049
public static void renamePatterns(Collection<Pattern> patterns, Map<String, Stop> stopById) { LOG.info("Generating unique names for patterns"); Map<String, PatternNamingInfo> namingInfoForRoute = new HashMap<>(); for (Pattern pattern : patterns) { if (pattern.associatedTrips.isEmpty() || pattern.orderedStops.isEmpty()) continue; // Each pattern within a route has a unique name (within that route, not across the entire feed) PatternNamingInfo namingInfo = namingInfoForRoute.get(pattern.route_id); if (namingInfo == null) { namingInfo = new PatternNamingInfo(); namingInfoForRoute.put(pattern.route_id, namingInfo); } // Pattern names are built using stop names rather than stop IDs. // Stop names, unlike IDs, are not guaranteed to be unique. // Therefore we must track used names carefully to avoid duplicates. String fromName = stopById.get(pattern.orderedStops.get(0)).stop_name; String toName = stopById.get(pattern.orderedStops.get(pattern.orderedStops.size() - 1)).stop_name; namingInfo.fromStops.put(fromName, pattern); namingInfo.toStops.put(toName, pattern); for (String stopId : pattern.orderedStops) { Stop stop = stopById.get(stopId); if (fromName.equals(stop.stop_name) || toName.equals(stop.stop_name)) continue; namingInfo.vias.put(stop.stop_name, pattern); } namingInfo.patternsOnRoute.add(pattern); } // name the patterns on each route for (PatternNamingInfo info : namingInfoForRoute.values()) { for (Pattern pattern : info.patternsOnRoute) { pattern.name = null; // clear this now so we don't get confused later on String fromName = stopById.get(pattern.orderedStops.get(0)).stop_name; String toName = stopById.get(pattern.orderedStops.get(pattern.orderedStops.size() - 1)).stop_name; // check if combination from, to is unique Set<Pattern> intersection = new HashSet<>(info.fromStops.get(fromName)); intersection.retainAll(info.toStops.get(toName)); if (intersection.size() == 1) { pattern.name = String.format(Locale.US, "from %s to %s", fromName, toName); continue; } // check for unique via stop pattern.orderedStops.stream().map(stopById::get).forEach(stop -> { Set<Pattern> viaIntersection = new HashSet<>(intersection); viaIntersection.retainAll(info.vias.get(stop.stop_name)); if (viaIntersection.size() == 1) { pattern.name = String.format(Locale.US, "from %s to %s via %s", fromName, toName, stop.stop_name); } }); if (pattern.name == null) { // no unique via, one pattern is subset of other. if (intersection.size() == 2) { Iterator<Pattern> it = intersection.iterator(); Pattern p0 = it.next(); Pattern p1 = it.next(); if (p0.orderedStops.size() > p1.orderedStops.size()) { p1.name = String.format(Locale.US, "from %s to %s express", fromName, toName); p0.name = String.format(Locale.US, "from %s to %s local", fromName, toName); } else if (p1.orderedStops.size() > p0.orderedStops.size()){ p0.name = String.format(Locale.US, "from %s to %s express", fromName, toName); p1.name = String.format(Locale.US, "from %s to %s local", fromName, toName); } } } if (pattern.name == null) { // give up pattern.name = String.format(Locale.US, "from %s to %s like trip %s", fromName, toName, pattern.associatedTrips.get(0)); } } // attach a stop and trip count to each for (Pattern pattern : info.patternsOnRoute) { pattern.name = String.format(Locale.US, "%s stops %s (%s trips)", pattern.orderedStops.size(), pattern.name, pattern.associatedTrips.size()); } } } private static class PatternNamingInfo { // These are all maps from ? // FIXME For type safety and clarity maybe we should have a parameterized ID type, i.e. EntityId<Stop> stopId. Multimap<String, Pattern> fromStops = HashMultimap.create(); Multimap<String, Pattern> toStops = HashMultimap.create(); Multimap<String, Pattern> vias = HashMultimap.create(); List<Pattern> patternsOnRoute = new ArrayList<>(); }
static void function(Collection<Pattern> patterns, Map<String, Stop> stopById) { LOG.info(STR); Map<String, PatternNamingInfo> namingInfoForRoute = new HashMap<>(); for (Pattern pattern : patterns) { if (pattern.associatedTrips.isEmpty() pattern.orderedStops.isEmpty()) continue; PatternNamingInfo namingInfo = namingInfoForRoute.get(pattern.route_id); if (namingInfo == null) { namingInfo = new PatternNamingInfo(); namingInfoForRoute.put(pattern.route_id, namingInfo); } String fromName = stopById.get(pattern.orderedStops.get(0)).stop_name; String toName = stopById.get(pattern.orderedStops.get(pattern.orderedStops.size() - 1)).stop_name; namingInfo.fromStops.put(fromName, pattern); namingInfo.toStops.put(toName, pattern); for (String stopId : pattern.orderedStops) { Stop stop = stopById.get(stopId); if (fromName.equals(stop.stop_name) toName.equals(stop.stop_name)) continue; namingInfo.vias.put(stop.stop_name, pattern); } namingInfo.patternsOnRoute.add(pattern); } for (PatternNamingInfo info : namingInfoForRoute.values()) { for (Pattern pattern : info.patternsOnRoute) { pattern.name = null; String fromName = stopById.get(pattern.orderedStops.get(0)).stop_name; String toName = stopById.get(pattern.orderedStops.get(pattern.orderedStops.size() - 1)).stop_name; Set<Pattern> intersection = new HashSet<>(info.fromStops.get(fromName)); intersection.retainAll(info.toStops.get(toName)); if (intersection.size() == 1) { pattern.name = String.format(Locale.US, STR, fromName, toName); continue; } pattern.orderedStops.stream().map(stopById::get).forEach(stop -> { Set<Pattern> viaIntersection = new HashSet<>(intersection); viaIntersection.retainAll(info.vias.get(stop.stop_name)); if (viaIntersection.size() == 1) { pattern.name = String.format(Locale.US, STR, fromName, toName, stop.stop_name); } }); if (pattern.name == null) { if (intersection.size() == 2) { Iterator<Pattern> it = intersection.iterator(); Pattern p0 = it.next(); Pattern p1 = it.next(); if (p0.orderedStops.size() > p1.orderedStops.size()) { p1.name = String.format(Locale.US, STR, fromName, toName); p0.name = String.format(Locale.US, STR, fromName, toName); } else if (p1.orderedStops.size() > p0.orderedStops.size()){ p0.name = String.format(Locale.US, STR, fromName, toName); p1.name = String.format(Locale.US, STR, fromName, toName); } } } if (pattern.name == null) { pattern.name = String.format(Locale.US, STR, fromName, toName, pattern.associatedTrips.get(0)); } } for (Pattern pattern : info.patternsOnRoute) { pattern.name = String.format(Locale.US, STR, pattern.orderedStops.size(), pattern.name, pattern.associatedTrips.size()); } } } private static class PatternNamingInfo { Multimap<String, Pattern> fromStops = HashMultimap.create(); Multimap<String, Pattern> toStops = HashMultimap.create(); Multimap<String, Pattern> vias = HashMultimap.create(); List<Pattern> patternsOnRoute = new ArrayList<>(); }
/** * Destructively rename the supplied collection of patterns. * This process requires access to all the stops in the feed. * Some validators already cache a map of all the stops. There's probably a cleaner way to do this. */
Destructively rename the supplied collection of patterns. This process requires access to all the stops in the feed. Some validators already cache a map of all the stops. There's probably a cleaner way to do this
renamePatterns
{ "repo_name": "conveyal/gtfs-lib", "path": "src/main/java/com/conveyal/gtfs/PatternFinder.java", "license": "bsd-2-clause", "size": 10986 }
[ "com.conveyal.gtfs.model.Pattern", "com.conveyal.gtfs.model.Stop", "com.google.common.collect.HashMultimap", "com.google.common.collect.Multimap", "java.util.ArrayList", "java.util.Collection", "java.util.HashMap", "java.util.HashSet", "java.util.Iterator", "java.util.List", "java.util.Locale", "java.util.Map", "java.util.Set" ]
import com.conveyal.gtfs.model.Pattern; import com.conveyal.gtfs.model.Stop; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set;
import com.conveyal.gtfs.model.*; import com.google.common.collect.*; import java.util.*;
[ "com.conveyal.gtfs", "com.google.common", "java.util" ]
com.conveyal.gtfs; com.google.common; java.util;
2,317,009
public void rmdir(String dirName) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(dirName, charsetName); sendMessage(Packet.SSH_FXP_RMDIR, req_id, tw.getBytes()); expectStatusOKMessage(req_id); }
void function(String dirName) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(dirName, charsetName); sendMessage(Packet.SSH_FXP_RMDIR, req_id, tw.getBytes()); expectStatusOKMessage(req_id); }
/** * Remove an empty directory. * * @param dirName See the {@link SFTPv3Client comment} for the class for more details. * @throws IOException */
Remove an empty directory
rmdir
{ "repo_name": "mattb243/AmazonEC2Matlab", "path": "third-party/ganymed-ssh2-build250/src/ch/ethz/ssh2/SFTPv3Client.java", "license": "bsd-3-clause", "size": 37607 }
[ "ch.ethz.ssh2.packets.TypesWriter", "ch.ethz.ssh2.sftp.Packet", "java.io.IOException" ]
import ch.ethz.ssh2.packets.TypesWriter; import ch.ethz.ssh2.sftp.Packet; import java.io.IOException;
import ch.ethz.ssh2.packets.*; import ch.ethz.ssh2.sftp.*; import java.io.*;
[ "ch.ethz.ssh2", "java.io" ]
ch.ethz.ssh2; java.io;
392,628
public Timestamp getUpdated(); public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
Timestamp function(); public static final String COLUMNNAME_UpdatedBy = STR;
/** Get Updated. * Date this record was updated */
Get Updated. Date this record was updated
getUpdated
{ "repo_name": "pplatek/adempiere", "path": "base/src/org/compiere/model/I_AD_PrintPaper.java", "license": "gpl-2.0", "size": 7598 }
[ "java.sql.Timestamp" ]
import java.sql.Timestamp;
import java.sql.*;
[ "java.sql" ]
java.sql;
87,118
protected BrowserUIPresenter constructAuxiliaryBrowsingContextUiController(WindowBrowsingContext windowContext) { return new SimpleBrowserUIPresenter(windowContext); }
BrowserUIPresenter function(WindowBrowsingContext windowContext) { return new SimpleBrowserUIPresenter(windowContext); }
/** * Constructs UI controller for given window context. * * @param windowContext Window context. * @return Constructed UI controller. */
Constructs UI controller for given window context
constructAuxiliaryBrowsingContextUiController
{ "repo_name": "ITman1/ScriptBox", "path": "src/main/java/org/fit/cssbox/scriptbox/demo/browser/SimpleBrowsingUnit.java", "license": "gpl-2.0", "size": 5042 }
[ "org.fit.cssbox.scriptbox.browser.WindowBrowsingContext" ]
import org.fit.cssbox.scriptbox.browser.WindowBrowsingContext;
import org.fit.cssbox.scriptbox.browser.*;
[ "org.fit.cssbox" ]
org.fit.cssbox;
1,105,245
public IDocuments[] ReadTheSVMXML(File testFile) { SaxParseService sax = new SaxParseService(); IDocuments[] categoryDocs = null; try { IDocuments[] docsArray = sax.ReadTheXML(testFile); // Put category name into CategoryDocument's category String fileName = testFile.getName(); String categoryName = fileName.substring(0, fileName.lastIndexOf(".")); Documents[] tempDocuments = new Documents[docsArray.length]; for (int i = 0; i < docsArray.length; ++i) { // Use the contentVector to calculate subsequently. Map<Long, Integer> temp = new TreeMap<Long, Integer>(); temp.putAll(docsArray[i].getTitleVector()); temp.putAll(docsArray[i].getContentVector()); docsArray[i].setContentVector(temp); // tempDocuments[i] = new Documents(); // tempDocuments[i].readFromDoc(docsArray[i]); docsArray[i].setCategory(categoryName); } categoryDocs = tempDocuments; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return categoryDocs; }
IDocuments[] function(File testFile) { SaxParseService sax = new SaxParseService(); IDocuments[] categoryDocs = null; try { IDocuments[] docsArray = sax.ReadTheXML(testFile); String fileName = testFile.getName(); String categoryName = fileName.substring(0, fileName.lastIndexOf(".")); Documents[] tempDocuments = new Documents[docsArray.length]; for (int i = 0; i < docsArray.length; ++i) { Map<Long, Integer> temp = new TreeMap<Long, Integer>(); temp.putAll(docsArray[i].getTitleVector()); temp.putAll(docsArray[i].getContentVector()); docsArray[i].setContentVector(temp); docsArray[i].setCategory(categoryName); } categoryDocs = tempDocuments; } catch (Exception e) { e.printStackTrace(); } return categoryDocs; }
/** * <p> * CreateDate : 2014-10-28 * </p> * <p> * Set the category name to every document's title. * </p> * <p> * Use the titleVector to calculate subsequently. * </p> */
CreateDate : 2014-10-28 Set the category name to every document's title. Use the titleVector to calculate subsequently.
ReadTheSVMXML
{ "repo_name": "xiaoliable/EssayClassifier", "path": "src/com/winga/xxl/classifier/data/exception/SaxParseService.java", "license": "apache-2.0", "size": 14540 }
[ "com.winga.xxl.classifier.data.store.Documents", "com.winga.xxl.classifier.data.store.IDocuments", "java.io.File", "java.util.Map", "java.util.TreeMap" ]
import com.winga.xxl.classifier.data.store.Documents; import com.winga.xxl.classifier.data.store.IDocuments; import java.io.File; import java.util.Map; import java.util.TreeMap;
import com.winga.xxl.classifier.data.store.*; import java.io.*; import java.util.*;
[ "com.winga.xxl", "java.io", "java.util" ]
com.winga.xxl; java.io; java.util;
126,840
public static <T extends GraphObject> T create(JSONObject json, Class<T> graphObjectClass) { return createGraphObjectProxy(graphObjectClass, json); }
static <T extends GraphObject> T function(JSONObject json, Class<T> graphObjectClass) { return createGraphObjectProxy(graphObjectClass, json); }
/** * Creates a GraphObject-derived proxy that provides typed access to the data in an underlying JSONObject. * @param json the JSONObject containing the data to be exposed * @param graphObjectClass the GraphObject-derived type to return * @return a graphObjectClass that represents the underlying data * * @throws com.facebook.FacebookException * If the passed in Class is not a valid GraphObject interface */
Creates a GraphObject-derived proxy that provides typed access to the data in an underlying JSONObject
create
{ "repo_name": "ashokslsk/yelo-android", "path": "libraries/facebookSDK/src/main/java/com/facebook/model/GraphObject.java", "license": "apache-2.0", "size": 39065 }
[ "org.json.JSONObject" ]
import org.json.JSONObject;
import org.json.*;
[ "org.json" ]
org.json;
1,355,006
private void fixEmptyMnc(List<CellInfo> cellInfo) { if (Build.VERSION.SDK_INT < 28 || cellInfo == null) { return; } String networkOperator = telephonyManager.getNetworkOperator(); if (networkOperator.length() < 5 || networkOperator.charAt(3) != '0') { return; } String mnc = networkOperator.substring(3); for (CellInfo info : cellInfo) { if (!info.isRegistered()) { continue; } Object identity = null; if (info instanceof CellInfoGsm) { identity = ((CellInfoGsm) info).getCellIdentity(); } else if (info instanceof CellInfoWcdma) { identity = ((CellInfoWcdma) info).getCellIdentity(); } else if (info instanceof CellInfoLte) { identity = ((CellInfoLte) info).getCellIdentity(); } if (identity == null) { continue; } try { Field mncField = CellIdentity.class.getDeclaredField("mMncStr"); mncField.setAccessible(true); if (mncField.get(identity) == null) { mncField.set(identity, mnc); } } catch (Exception ignored) { } } }
void function(List<CellInfo> cellInfo) { if (Build.VERSION.SDK_INT < 28 cellInfo == null) { return; } String networkOperator = telephonyManager.getNetworkOperator(); if (networkOperator.length() < 5 networkOperator.charAt(3) != '0') { return; } String mnc = networkOperator.substring(3); for (CellInfo info : cellInfo) { if (!info.isRegistered()) { continue; } Object identity = null; if (info instanceof CellInfoGsm) { identity = ((CellInfoGsm) info).getCellIdentity(); } else if (info instanceof CellInfoWcdma) { identity = ((CellInfoWcdma) info).getCellIdentity(); } else if (info instanceof CellInfoLte) { identity = ((CellInfoLte) info).getCellIdentity(); } if (identity == null) { continue; } try { Field mncField = CellIdentity.class.getDeclaredField(STR); mncField.setAccessible(true); if (mncField.get(identity) == null) { mncField.set(identity, mnc); } } catch (Exception ignored) { } } }
/** * This will fix empty MNC since Android 9 with 0-prefixed MNCs. * Issue: https://issuetracker.google.com/issues/113560852 */
This will fix empty MNC since Android 9 with 0-prefixed MNCs. Issue: HREF
fixEmptyMnc
{ "repo_name": "microg/android_packages_apps_UnifiedNlp", "path": "api/src/main/java/org/microg/nlp/api/CellBackendHelper.java", "license": "apache-2.0", "size": 22410 }
[ "android.os.Build", "android.telephony.CellIdentity", "android.telephony.CellInfo", "android.telephony.CellInfoGsm", "android.telephony.CellInfoLte", "android.telephony.CellInfoWcdma", "java.lang.reflect.Field", "java.util.List" ]
import android.os.Build; import android.telephony.CellIdentity; import android.telephony.CellInfo; import android.telephony.CellInfoGsm; import android.telephony.CellInfoLte; import android.telephony.CellInfoWcdma; import java.lang.reflect.Field; import java.util.List;
import android.os.*; import android.telephony.*; import java.lang.reflect.*; import java.util.*;
[ "android.os", "android.telephony", "java.lang", "java.util" ]
android.os; android.telephony; java.lang; java.util;
577,045
public static String readStringProperty(String processorType, String processorTag, Map<String, Object> configuration, String propertyName) { return readStringProperty(processorType, processorTag, configuration, propertyName, null); }
static String function(String processorType, String processorTag, Map<String, Object> configuration, String propertyName) { return readStringProperty(processorType, processorTag, configuration, propertyName, null); }
/** * Returns and removes the specified property from the specified configuration map. * * If the property value isn't of type string an {@link ElasticsearchParseException} is thrown. * If the property is missing an {@link ElasticsearchParseException} is thrown */
Returns and removes the specified property from the specified configuration map. If the property value isn't of type string an <code>ElasticsearchParseException</code> is thrown. If the property is missing an <code>ElasticsearchParseException</code> is thrown
readStringProperty
{ "repo_name": "sreeramjayan/elasticsearch", "path": "core/src/main/java/org/elasticsearch/ingest/ConfigurationUtils.java", "license": "apache-2.0", "size": 13104 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,469,186
public Element lastElementSibling() { List<Element> siblings = parent().childElementsList(); return siblings.size() > 1 ? siblings.get(siblings.size() - 1) : null; }
Element function() { List<Element> siblings = parent().childElementsList(); return siblings.size() > 1 ? siblings.get(siblings.size() - 1) : null; }
/** * Gets the last element sibling of this element * @return the last sibling that is an element (aka the parent's last element child) */
Gets the last element sibling of this element
lastElementSibling
{ "repo_name": "SpoonLabs/astor", "path": "examples/librepair-experiments-jhy-jsoup-285353482-20171009-062400_bugonly_with_package_info/src/main/java/org/jsoup/nodes/Element.java", "license": "gpl-2.0", "size": 50843 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,260,941
@Test public void testJongo() { // Loads the application context. load(); assertBeanExists(Jongo.class); final Jongo jongo = context.getBean(Jongo.class); Assert.assertNotNull("Any instance of the class has been created Jongo", jongo); Assert.assertEquals("The end point has not been defined when creating the object.", DATABASE_NAME, jongo.getDatabase().getName()); } //</editor-fold>
void function() { load(); assertBeanExists(Jongo.class); final Jongo jongo = context.getBean(Jongo.class); Assert.assertNotNull(STR, jongo); Assert.assertEquals(STR, DATABASE_NAME, jongo.getDatabase().getName()); }
/** * Test for using of Jongo class instance. */
Test for using of Jongo class instance
testJongo
{ "repo_name": "arhs/spring-boot-autoconfigure", "path": "src/test/java/com/arhs/spring/boot/autoconfigure/jongo/JongoAutoConfigurationTest.java", "license": "mit", "size": 2677 }
[ "org.jongo.Jongo", "org.junit.Assert" ]
import org.jongo.Jongo; import org.junit.Assert;
import org.jongo.*; import org.junit.*;
[ "org.jongo", "org.junit" ]
org.jongo; org.junit;
867,910
private void appendToPass(DetectorFactory factory, AnalysisPass pass) { pass.append(factory); }
void function(DetectorFactory factory, AnalysisPass pass) { pass.append(factory); }
/** * Append a DetectorFactory to the end position in an AnalysisPass. The * DetectorFactory must be a member of the pass. */
Append a DetectorFactory to the end position in an AnalysisPass. The DetectorFactory must be a member of the pass
appendToPass
{ "repo_name": "OpenNTF/FindBug-for-Domino-Designer", "path": "findBugsEclipsePlugin/src/edu/umd/cs/findbugs/plan/ExecutionPlan.java", "license": "lgpl-3.0", "size": 21670 }
[ "edu.umd.cs.findbugs.DetectorFactory" ]
import edu.umd.cs.findbugs.DetectorFactory;
import edu.umd.cs.findbugs.*;
[ "edu.umd.cs" ]
edu.umd.cs;
338,653
ArrayList getValues() { return this._values; }
ArrayList getValues() { return this._values; }
/** * Obtain values contained in this buckets. Values are ordered to match * their keys, which be be obtained by calling <code>getKeys()</code>. * * As an optimization, the Vector returned is the instance member * of this class. Please don't modify outside the scope of this class. */
Obtain values contained in this buckets. Values are ordered to match their keys, which be be obtained by calling <code>getKeys()</code>. As an optimization, the Vector returned is the instance member of this class. Please don't modify outside the scope of this class
getValues
{ "repo_name": "kcsl/immutability-benchmark", "path": "benchmark-applications/reiminfer-oopsla-2012/source/Jdbm/src/jdbm/htree/HashBucket.java", "license": "mit", "size": 9460 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
2,107,732
protected static final ELineType randomLineType(final Random rand) { return ChartExample.LINE_TYPES[rand .nextInt(ChartExample.LINE_TYPES.length)]; }
static final ELineType function(final Random rand) { return ChartExample.LINE_TYPES[rand .nextInt(ChartExample.LINE_TYPES.length)]; }
/** * Obtain a random line type * * @param rand * the random number generator * @return the line type */
Obtain a random line type
randomLineType
{ "repo_name": "optimizationBenchmarking/utils-base", "path": "src/test/java/examples/org/optimizationBenchmarking/utils/chart/ChartExample.java", "license": "gpl-3.0", "size": 6895 }
[ "java.util.Random" ]
import java.util.Random;
import java.util.*;
[ "java.util" ]
java.util;
1,919,678
public FileObject[] findJarFiles() throws KettleFileException;
FileObject[] function() throws KettleFileException;
/** * Find all the jar files in this plugin folder * * @return The jar files * @throws KettleFileException * In case there is a problem reading */
Find all the jar files in this plugin folder
findJarFiles
{ "repo_name": "apratkin/pentaho-kettle", "path": "core/src/org/pentaho/di/core/plugins/PluginFolderInterface.java", "license": "apache-2.0", "size": 1764 }
[ "org.apache.commons.vfs.FileObject", "org.pentaho.di.core.exception.KettleFileException" ]
import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.exception.KettleFileException;
import org.apache.commons.vfs.*; import org.pentaho.di.core.exception.*;
[ "org.apache.commons", "org.pentaho.di" ]
org.apache.commons; org.pentaho.di;
927,490
public void testSublistConcurrentModificationException() { ListMultimap<String, Integer> multimap = create(); multimap.putAll("foo", asList(1, 2, 3, 4, 5)); List<Integer> list = multimap.get("foo"); ASSERT.that(multimap.get("foo")).has().allOf(1, 2, 3, 4, 5).inOrder(); List<Integer> sublist = list.subList(0, 5); ASSERT.that(sublist).has().allOf(1, 2, 3, 4, 5).inOrder(); sublist.clear(); assertTrue(sublist.isEmpty()); multimap.put("foo", 6); try { sublist.isEmpty(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) {} }
void function() { ListMultimap<String, Integer> multimap = create(); multimap.putAll("foo", asList(1, 2, 3, 4, 5)); List<Integer> list = multimap.get("foo"); ASSERT.that(multimap.get("foo")).has().allOf(1, 2, 3, 4, 5).inOrder(); List<Integer> sublist = list.subList(0, 5); ASSERT.that(sublist).has().allOf(1, 2, 3, 4, 5).inOrder(); sublist.clear(); assertTrue(sublist.isEmpty()); multimap.put("foo", 6); try { sublist.isEmpty(); fail(STR); } catch (ConcurrentModificationException expected) {} }
/** * Test throwing ConcurrentModificationException when a sublist's ancestor's * delegate changes. */
Test throwing ConcurrentModificationException when a sublist's ancestor's delegate changes
testSublistConcurrentModificationException
{ "repo_name": "sensui/guava-libraries", "path": "guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java", "license": "apache-2.0", "size": 6398 }
[ "java.util.Arrays", "java.util.ConcurrentModificationException", "java.util.List", "org.truth0.Truth" ]
import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.List; import org.truth0.Truth;
import java.util.*; import org.truth0.*;
[ "java.util", "org.truth0" ]
java.util; org.truth0;
1,984,553
@TruffleBoundary public static void putRNGState() { int[] seeds = currentGenerator().getSeeds(); seeds[0] = currentKind().ordinal() + 100 * currentNormKind().ordinal(); RContext.getInstance().stateRNG.setCurrentSeeds(seeds); }
static void function() { int[] seeds = currentGenerator().getSeeds(); seeds[0] = currentKind().ordinal() + 100 * currentNormKind().ordinal(); RContext.getInstance().stateRNG.setCurrentSeeds(seeds); }
/** * Saves the state of RNG into global environment under {@code .Random.seed}. This should be * invoked after any random numbers generation. */
Saves the state of RNG into global environment under .Random.seed. This should be invoked after any random numbers generation
putRNGState
{ "repo_name": "akunft/fastr", "path": "com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/rng/RRNG.java", "license": "gpl-2.0", "size": 17998 }
[ "com.oracle.truffle.r.runtime.context.RContext" ]
import com.oracle.truffle.r.runtime.context.RContext;
import com.oracle.truffle.r.runtime.context.*;
[ "com.oracle.truffle" ]
com.oracle.truffle;
768,330
public void onActivityResult(int requestCode, int resultCode, Intent intent) { }
void function(int requestCode, int resultCode, Intent intent) { }
/** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */
Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it
onActivityResult
{ "repo_name": "gazeing/rebBackUp", "path": "CordovaLib/src/org/apache/cordova/CordovaPlugin.java", "license": "apache-2.0", "size": 6624 }
[ "android.content.Intent" ]
import android.content.Intent;
import android.content.*;
[ "android.content" ]
android.content;
2,017,605
private void initialize() { long totalSize = 0; final FileIterator i = new FileIterator( m_owningCache.getCacheDirectory(), FileCacheFilter.INSTANCE, true ); while ( i.hasNext() ) { if ( m_abortInitialize || m_stop ) return; final File file = i.next(); final long size = file.length(); if ( size > 0 ) try { addFile( file ); totalSize += size; } catch ( IOException e ) { // ignore? } } if ( totalSize > 0 ) m_owningCache.addToCacheSize( totalSize ); }
void function() { long totalSize = 0; final FileIterator i = new FileIterator( m_owningCache.getCacheDirectory(), FileCacheFilter.INSTANCE, true ); while ( i.hasNext() ) { if ( m_abortInitialize m_stop ) return; final File file = i.next(); final long size = file.length(); if ( size > 0 ) try { addFile( file ); totalSize += size; } catch ( IOException e ) { } } if ( totalSize > 0 ) m_owningCache.addToCacheSize( totalSize ); }
/** * Initialize by creating a set of all files in the cache, totaling their * sizes, and setting the cache's size to said total. */
Initialize by creating a set of all files in the cache, totaling their sizes, and setting the cache's size to said total
initialize
{ "repo_name": "MarinnaCole/LightZone", "path": "lightcrafts/src/com/lightcrafts/utils/filecache/FileCacheMonitor.java", "license": "bsd-3-clause", "size": 9905 }
[ "com.lightcrafts.utils.file.FileIterator", "java.io.File", "java.io.IOException" ]
import com.lightcrafts.utils.file.FileIterator; import java.io.File; import java.io.IOException;
import com.lightcrafts.utils.file.*; import java.io.*;
[ "com.lightcrafts.utils", "java.io" ]
com.lightcrafts.utils; java.io;
907,261
public ASTContainer parseQuery2(final String queryStr, final String baseURI) throws MalformedQueryException { final long startTime = System.nanoTime(); if(log.isInfoEnabled()) log.info(queryStr); try { final ASTQueryContainer qc = SyntaxTreeBuilder.parseQuery(queryStr); StringEscapesProcessor.process(qc); BaseDeclProcessor.process(qc, baseURI); final Map<String, String> prefixes = PrefixDeclProcessor.process(qc); // WildcardProjectionProcessor.process(qc); BlankNodeVarProcessor.process(qc); final ASTDeferredIVResolutionInitializer resolver = new ASTDeferredIVResolutionInitializer(); resolver.process(qc); final QueryRoot queryRoot = buildQueryModel(qc, resolver.getValues()); final ASTContainer ast = new ASTContainer(queryRoot); // Set the query string on the AST. ast.setQueryString(queryStr); // Set the parse tree on the AST. ast.setParseTree(qc); doQueryIdHint(ast, queryRoot); // final Properties queryHints = getQueryHints(qc); // // if (queryHints != null) { // // queryRoot.setQueryHints(queryHints); // // } queryRoot.setPrefixDecls(prefixes); VerifyAggregates.verifyAggregate(queryRoot); ast.setQueryParseTime(System.nanoTime() - startTime); return ast; } catch (final IllegalArgumentException e) { throw new MalformedQueryException(e.getMessage(), e); } catch (final VisitorException e) { throw new MalformedQueryException(e.getMessage(), e); } catch (final ParseException e) { throw new MalformedQueryException(e.getMessage(), e); } catch (final TokenMgrError e) { throw new MalformedQueryException(e.getMessage(), e); } }
ASTContainer function(final String queryStr, final String baseURI) throws MalformedQueryException { final long startTime = System.nanoTime(); if(log.isInfoEnabled()) log.info(queryStr); try { final ASTQueryContainer qc = SyntaxTreeBuilder.parseQuery(queryStr); StringEscapesProcessor.process(qc); BaseDeclProcessor.process(qc, baseURI); final Map<String, String> prefixes = PrefixDeclProcessor.process(qc); BlankNodeVarProcessor.process(qc); final ASTDeferredIVResolutionInitializer resolver = new ASTDeferredIVResolutionInitializer(); resolver.process(qc); final QueryRoot queryRoot = buildQueryModel(qc, resolver.getValues()); final ASTContainer ast = new ASTContainer(queryRoot); ast.setQueryString(queryStr); ast.setParseTree(qc); doQueryIdHint(ast, queryRoot); queryRoot.setPrefixDecls(prefixes); VerifyAggregates.verifyAggregate(queryRoot); ast.setQueryParseTime(System.nanoTime() - startTime); return ast; } catch (final IllegalArgumentException e) { throw new MalformedQueryException(e.getMessage(), e); } catch (final VisitorException e) { throw new MalformedQueryException(e.getMessage(), e); } catch (final ParseException e) { throw new MalformedQueryException(e.getMessage(), e); } catch (final TokenMgrError e) { throw new MalformedQueryException(e.getMessage(), e); } }
/** * Parse a SPARQL query. * * @param queryStr * The query. * @param baseURI * The base URI. * * @return The AST model for that query. * * @throws MalformedQueryException */
Parse a SPARQL query
parseQuery2
{ "repo_name": "blazegraph/database", "path": "bigdata-core/bigdata-sails/src/java/com/bigdata/rdf/sail/sparql/Bigdata2ASTSPARQLParser.java", "license": "gpl-2.0", "size": 18912 }
[ "com.bigdata.rdf.sail.sparql.ast.ASTQueryContainer", "com.bigdata.rdf.sail.sparql.ast.ParseException", "com.bigdata.rdf.sail.sparql.ast.SyntaxTreeBuilder", "com.bigdata.rdf.sail.sparql.ast.TokenMgrError", "com.bigdata.rdf.sail.sparql.ast.VisitorException", "com.bigdata.rdf.sparql.ast.ASTContainer", "com.bigdata.rdf.sparql.ast.QueryRoot", "java.util.Map", "org.openrdf.query.MalformedQueryException" ]
import com.bigdata.rdf.sail.sparql.ast.ASTQueryContainer; import com.bigdata.rdf.sail.sparql.ast.ParseException; import com.bigdata.rdf.sail.sparql.ast.SyntaxTreeBuilder; import com.bigdata.rdf.sail.sparql.ast.TokenMgrError; import com.bigdata.rdf.sail.sparql.ast.VisitorException; import com.bigdata.rdf.sparql.ast.ASTContainer; import com.bigdata.rdf.sparql.ast.QueryRoot; import java.util.Map; import org.openrdf.query.MalformedQueryException;
import com.bigdata.rdf.sail.sparql.ast.*; import com.bigdata.rdf.sparql.ast.*; import java.util.*; import org.openrdf.query.*;
[ "com.bigdata.rdf", "java.util", "org.openrdf.query" ]
com.bigdata.rdf; java.util; org.openrdf.query;
2,046,522
public boolean touchDown (int screenX, int screenY, int pointer, int button) { if (screenX < viewport.getScreenX() || screenX >= viewport.getScreenX() + viewport.getScreenWidth()) return false; if (Gdx.graphics.getHeight() - screenY < viewport.getScreenY() || Gdx.graphics.getHeight() - screenY >= viewport.getScreenY() + viewport.getScreenHeight()) return false; pointerTouched[pointer] = true; pointerScreenX[pointer] = screenX; pointerScreenY[pointer] = screenY; screenToStageCoordinates(tempCoords.set(screenX, screenY)); InputEvent event = Pools.obtain(InputEvent.class); event.setType(Type.touchDown); event.setStage(this); event.setStageX(tempCoords.x); event.setStageY(tempCoords.y); event.setPointer(pointer); event.setButton(button); Actor target = hit(tempCoords.x, tempCoords.y, true); if (target == null) { if (root.getTouchable() == Touchable.enabled) root.fire(event); } else { target.fire(event); } boolean handled = event.isHandled(); Pools.free(event); return handled; }
boolean function (int screenX, int screenY, int pointer, int button) { if (screenX < viewport.getScreenX() screenX >= viewport.getScreenX() + viewport.getScreenWidth()) return false; if (Gdx.graphics.getHeight() - screenY < viewport.getScreenY() Gdx.graphics.getHeight() - screenY >= viewport.getScreenY() + viewport.getScreenHeight()) return false; pointerTouched[pointer] = true; pointerScreenX[pointer] = screenX; pointerScreenY[pointer] = screenY; screenToStageCoordinates(tempCoords.set(screenX, screenY)); InputEvent event = Pools.obtain(InputEvent.class); event.setType(Type.touchDown); event.setStage(this); event.setStageX(tempCoords.x); event.setStageY(tempCoords.y); event.setPointer(pointer); event.setButton(button); Actor target = hit(tempCoords.x, tempCoords.y, true); if (target == null) { if (root.getTouchable() == Touchable.enabled) root.fire(event); } else { target.fire(event); } boolean handled = event.isHandled(); Pools.free(event); return handled; }
/** Applies a touch down event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the * event. */
Applies a touch down event to the stage and returns true if an actor in the scene <code>Event#handle() handled</code> the
touchDown
{ "repo_name": "czyzby/libgdx", "path": "gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java", "license": "apache-2.0", "size": 32028 }
[ "com.badlogic.gdx.Gdx", "com.badlogic.gdx.scenes.scene2d.InputEvent", "com.badlogic.gdx.utils.Pools" ]
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.utils.Pools;
import com.badlogic.gdx.*; import com.badlogic.gdx.scenes.scene2d.*; import com.badlogic.gdx.utils.*;
[ "com.badlogic.gdx" ]
com.badlogic.gdx;
2,220,557
boolean sniff(ExtractorInput input) throws IOException, InterruptedException;
boolean sniff(ExtractorInput input) throws IOException, InterruptedException;
/** * Returns whether this extractor can extract samples from the {@link ExtractorInput}, which must * provide data from the start of the stream. * <p> * If {@code true} is returned, the {@code input}'s reading position may have been modified. * Otherwise, only its peek position may have been modified. * * @param input The {@link ExtractorInput} from which data should be peeked/read. * @return Whether this extractor can read the provided input. * @throws IOException If an error occurred reading from the input. * @throws InterruptedException If the thread was interrupted. */
Returns whether this extractor can extract samples from the <code>ExtractorInput</code>, which must provide data from the start of the stream. If true is returned, the input's reading position may have been modified. Otherwise, only its peek position may have been modified
sniff
{ "repo_name": "saki4510t/ExoPlayer", "path": "library/core/src/main/java/com/google/android/exoplayer2/extractor/Extractor.java", "license": "apache-2.0", "size": 5216 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
512,890
public static sbasToType fromPerUnaligned(byte[] encodedBytes) { sbasToType result = new sbasToType(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; }
static sbasToType function(byte[] encodedBytes) { sbasToType result = new sbasToType(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; }
/** * Creates a new sbasToType from encoded stream. */
Creates a new sbasToType from encoded stream
fromPerUnaligned
{ "repo_name": "google/supl-client", "path": "src/main/java/com/google/location/suplclient/asn1/supl2/lpp/NavModel_SBAS_ECEF.java", "license": "apache-2.0", "size": 45283 }
[ "com.google.location.suplclient.asn1.base.BitStreamReader" ]
import com.google.location.suplclient.asn1.base.BitStreamReader;
import com.google.location.suplclient.asn1.base.*;
[ "com.google.location" ]
com.google.location;
348,347
List<String> tags = new ArrayList<String>(4); addActorPathTagsTo(actorPath, tags); addSystemTagsTo(actorPath, tags); addTypeTagsTo(actorPath, actorClassName, tags); return tags.toArray(new String[tags.size()]); }
List<String> tags = new ArrayList<String>(4); addActorPathTagsTo(actorPath, tags); addSystemTagsTo(actorPath, tags); addTypeTagsTo(actorPath, actorClassName, tags); return tags.toArray(new String[tags.size()]); }
/** * Computes the tags for the given {@code actorPath} and {@code actor} instances. * * @param actorPath the actor path; never {@code null} * @param actorClassName the actor instance; may be {@code null} * @return non-{@code null} array of tags */
Computes the tags for the given actorPath and actor instances
getTags
{ "repo_name": "eigengo/monitor", "path": "agent-akka/src/main/java/org/eigengo/monitor/agent/akka/ActorPathTagger.java", "license": "apache-2.0", "size": 1429 }
[ "java.util.ArrayList", "java.util.List" ]
import java.util.ArrayList; import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,697,793
@Deployment public void testVariableNamesScope() { // After starting the process, the task in the subprocess should be active Map<String, Object> varMap = new HashMap<String, Object>(); varMap.put("test", "test"); varMap.put("helloWorld", "helloWorld"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("simpleSubProcess", varMap); Task subProcessTask = taskService.createTaskQuery() .processInstanceId(pi.getId()) .singleResult(); runtimeService.setVariableLocal(pi.getProcessInstanceId(), "mainProcessLocalVariable", "Hello World"); assertEquals("Task in subprocess", subProcessTask.getName()); runtimeService.setVariableLocal(subProcessTask.getExecutionId(), "subProcessLocalVariable", "Hello SubProcess"); // Returns a set of local variablenames of pi List<String> result = processEngineConfiguration. getCommandExecutorTxRequired(). execute(new GetVariableNamesCommand(pi.getProcessInstanceId(), true)); // pi contains local the variablenames "test", "helloWorld" and "mainProcessLocalVariable" but not "subProcessLocalVariable" assertTrue(result.contains("test")); assertTrue(result.contains("helloWorld")); assertTrue(result.contains("mainProcessLocalVariable")); assertFalse(result.contains("subProcessLocalVariable")); // Returns a set of global variablenames of pi result = processEngineConfiguration. getCommandExecutorTxRequired(). execute(new GetVariableNamesCommand(pi.getProcessInstanceId(), false)); // pi contains global the variablenames "test", "helloWorld" and "mainProcessLocalVariable" but not "subProcessLocalVariable" assertTrue(result.contains("test")); assertTrue(result.contains("mainProcessLocalVariable")); assertTrue(result.contains("helloWorld")); assertFalse(result.contains("subProcessLocalVariable")); // Returns a set of local variablenames of subProcessTask execution result = processEngineConfiguration. getCommandExecutorTxRequired(). execute(new GetVariableNamesCommand(subProcessTask.getExecutionId(), true)); // subProcessTask execution contains local the variablenames "test", "subProcessLocalVariable" but not "helloWorld" and "mainProcessLocalVariable" assertTrue(result.contains("test")); // the variable "test" was set locally by SetLocalVariableTask assertTrue(result.contains("subProcessLocalVariable")); assertFalse(result.contains("helloWorld")); assertFalse(result.contains("mainProcessLocalVariable")); // Returns a set of global variablenames of subProcessTask execution result = processEngineConfiguration. getCommandExecutorTxRequired(). execute(new GetVariableNamesCommand(subProcessTask.getExecutionId(), false)); // subProcessTask execution contains global all defined variablenames assertTrue(result.contains("test")); // the variable "test" was set locally by SetLocalVariableTask assertTrue(result.contains("subProcessLocalVariable")); assertTrue(result.contains("helloWorld")); assertTrue(result.contains("mainProcessLocalVariable")); taskService.complete(subProcessTask.getId()); } private class GetVariableNamesCommand implements Command<List<String>> { private String executionId; private boolean isLocal; public GetVariableNamesCommand(String executionId, boolean isLocal) { this.executionId = executionId; this.isLocal = isLocal; }
void function() { Map<String, Object> varMap = new HashMap<String, Object>(); varMap.put("test", "test"); varMap.put(STR, STR); ProcessInstance pi = runtimeService.startProcessInstanceByKey(STR, varMap); Task subProcessTask = taskService.createTaskQuery() .processInstanceId(pi.getId()) .singleResult(); runtimeService.setVariableLocal(pi.getProcessInstanceId(), STR, STR); assertEquals(STR, subProcessTask.getName()); runtimeService.setVariableLocal(subProcessTask.getExecutionId(), STR, STR); List<String> result = processEngineConfiguration. getCommandExecutorTxRequired(). execute(new GetVariableNamesCommand(pi.getProcessInstanceId(), true)); assertTrue(result.contains("test")); assertTrue(result.contains(STR)); assertTrue(result.contains(STR)); assertFalse(result.contains(STR)); result = processEngineConfiguration. getCommandExecutorTxRequired(). execute(new GetVariableNamesCommand(pi.getProcessInstanceId(), false)); assertTrue(result.contains("test")); assertTrue(result.contains(STR)); assertTrue(result.contains(STR)); assertFalse(result.contains(STR)); result = processEngineConfiguration. getCommandExecutorTxRequired(). execute(new GetVariableNamesCommand(subProcessTask.getExecutionId(), true)); assertTrue(result.contains("test")); assertTrue(result.contains(STR)); assertFalse(result.contains(STR)); assertFalse(result.contains(STR)); result = processEngineConfiguration. getCommandExecutorTxRequired(). execute(new GetVariableNamesCommand(subProcessTask.getExecutionId(), false)); assertTrue(result.contains("test")); assertTrue(result.contains(STR)); assertTrue(result.contains(STR)); assertTrue(result.contains(STR)); taskService.complete(subProcessTask.getId()); } private class GetVariableNamesCommand implements Command<List<String>> { private String executionId; private boolean isLocal; public GetVariableNamesCommand(String executionId, boolean isLocal) { this.executionId = executionId; this.isLocal = isLocal; }
/** * A testcase to produce and fix issue ACT-862. * @author Roman Smirnov * @author Christian Lipphardt */
A testcase to produce and fix issue ACT-862
testVariableNamesScope
{ "repo_name": "LuisePufahl/camunda-bpm-platform_batchProcessing", "path": "engine/src/test/java/org/camunda/bpm/engine/test/db/VariableScopeTest.java", "license": "apache-2.0", "size": 8326 }
[ "java.util.HashMap", "java.util.List", "java.util.Map", "org.camunda.bpm.engine.impl.interceptor.Command", "org.camunda.bpm.engine.runtime.ProcessInstance", "org.camunda.bpm.engine.task.Task" ]
import java.util.HashMap; import java.util.List; import java.util.Map; import org.camunda.bpm.engine.impl.interceptor.Command; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.task.Task;
import java.util.*; import org.camunda.bpm.engine.impl.interceptor.*; import org.camunda.bpm.engine.runtime.*; import org.camunda.bpm.engine.task.*;
[ "java.util", "org.camunda.bpm" ]
java.util; org.camunda.bpm;
997,591
default Offset<Long> byLessThan(Long value) { return Assertions.byLessThan(value); }
default Offset<Long> byLessThan(Long value) { return Assertions.byLessThan(value); }
/** * Assertions entry point for Long {@link Offset} to use with isCloseTo assertions. * <p> * Typical usage : * <pre><code class='java'> assertThat(5l).isCloseTo(7l, byLessThan(2l));</code></pre> * * @param value the value of the offset. * @return the created {@code Offset}. * @throws NullPointerException if the given value is {@code null}. * @throws IllegalArgumentException if the given value is negative. * @since 3.9.0 */
Assertions entry point for Long <code>Offset</code> to use with isCloseTo assertions. Typical usage : <code> assertThat(5l).isCloseTo(7l, byLessThan(2l));</code></code>
byLessThan
{ "repo_name": "ChrisA89/assertj-core", "path": "src/main/java/org/assertj/core/api/WithAssertions.java", "license": "apache-2.0", "size": 102131 }
[ "org.assertj.core.data.Offset" ]
import org.assertj.core.data.Offset;
import org.assertj.core.data.*;
[ "org.assertj.core" ]
org.assertj.core;
242,332
public CoreAccountInfo addTestAccountThenSigninAndEnableSync( @Nullable SyncService syncService) { assert !mIsSignedIn : "An account is already signed in!"; CoreAccountInfo coreAccountInfo = addAccountAndWaitForSeeding(TEST_ACCOUNT_EMAIL); SigninTestUtil.signinAndEnableSync(coreAccountInfo, syncService); mIsSignedIn = true; return coreAccountInfo; }
CoreAccountInfo function( @Nullable SyncService syncService) { assert !mIsSignedIn : STR; CoreAccountInfo coreAccountInfo = addAccountAndWaitForSeeding(TEST_ACCOUNT_EMAIL); SigninTestUtil.signinAndEnableSync(coreAccountInfo, syncService); mIsSignedIn = true; return coreAccountInfo; }
/** * Adds and signs in an account with the default name and enables sync. * * This method invokes native code. It shouldn't be called in a Robolectric test. * * @param syncService SyncService object to set up sync, if null, sync won't * start. */
Adds and signs in an account with the default name and enables sync. This method invokes native code. It shouldn't be called in a Robolectric test
addTestAccountThenSigninAndEnableSync
{ "repo_name": "chromium/chromium", "path": "chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/signin/AccountManagerTestRule.java", "license": "bsd-3-clause", "size": 13911 }
[ "androidx.annotation.Nullable", "org.chromium.chrome.browser.sync.SyncService", "org.chromium.components.signin.base.CoreAccountInfo" ]
import androidx.annotation.Nullable; import org.chromium.chrome.browser.sync.SyncService; import org.chromium.components.signin.base.CoreAccountInfo;
import androidx.annotation.*; import org.chromium.chrome.browser.sync.*; import org.chromium.components.signin.base.*;
[ "androidx.annotation", "org.chromium.chrome", "org.chromium.components" ]
androidx.annotation; org.chromium.chrome; org.chromium.components;
2,237,432
private void updatePropertiesCache() { final Map<String, String> newProps = new HashMap<String, String>(); for(final ProviderInfo info : this.providerInfos) { newProps.putAll(info.properties); } this.cachedProperties = newProps; if ( this.logger.isDebugEnabled() ) { this.logger.debug("New properties: {}", this.cachedProperties); } }
void function() { final Map<String, String> newProps = new HashMap<String, String>(); for(final ProviderInfo info : this.providerInfos) { newProps.putAll(info.properties); } this.cachedProperties = newProps; if ( this.logger.isDebugEnabled() ) { this.logger.debug(STR, this.cachedProperties); } }
/** * Update the properties cache. */
Update the properties cache
updatePropertiesCache
{ "repo_name": "Nimco/sling", "path": "bundles/extensions/discovery/standalone/src/main/java/org/apache/sling/discovery/impl/standalone/NoClusterDiscoveryService.java", "license": "apache-2.0", "size": 8924 }
[ "java.util.HashMap", "java.util.Map" ]
import java.util.HashMap; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,733,268
public List<BasicDBObject> formAttackInsert(Champion champ) { List<BasicDBObject> attacks = new ArrayList<BasicDBObject>(); for (Attack a : champ.getAttacks()) { BasicDBObject attack = new BasicDBObject(); attack.put(StaticVariables.ID, a.getId()); attack.put(StaticVariables.NAME, a.getName()); attack.put(StaticVariables.DAMAGE, a.getDamage()); attack.put(StaticVariables.COOLDOWN, a.getCooldown()); attack.put(StaticVariables.COOLDOWN_REMAINING, a.getCooldownRemaining()); attack.put(StaticVariables.RANGE, a.getDistance()); attacks.add(attack); } return attacks; }
List<BasicDBObject> function(Champion champ) { List<BasicDBObject> attacks = new ArrayList<BasicDBObject>(); for (Attack a : champ.getAttacks()) { BasicDBObject attack = new BasicDBObject(); attack.put(StaticVariables.ID, a.getId()); attack.put(StaticVariables.NAME, a.getName()); attack.put(StaticVariables.DAMAGE, a.getDamage()); attack.put(StaticVariables.COOLDOWN, a.getCooldown()); attack.put(StaticVariables.COOLDOWN_REMAINING, a.getCooldownRemaining()); attack.put(StaticVariables.RANGE, a.getDistance()); attacks.add(attack); } return attacks; }
/** * * Attacks Section * */
Attacks Section
formAttackInsert
{ "repo_name": "klintT/throneofkings", "path": "KingsGame/src/main/java/com/starShipNub/KingsGame/utilities/BaseDAO.java", "license": "apache-2.0", "size": 13869 }
[ "com.mongodb.BasicDBObject", "java.util.ArrayList", "java.util.List" ]
import com.mongodb.BasicDBObject; import java.util.ArrayList; import java.util.List;
import com.mongodb.*; import java.util.*;
[ "com.mongodb", "java.util" ]
com.mongodb; java.util;
1,047,673
@CheckReturnValue public final FluentIterable<E> filter(Predicate<? super E> predicate) { return from(Iterables.filter(iterable, predicate)); }
final FluentIterable<E> function(Predicate<? super E> predicate) { return from(Iterables.filter(iterable, predicate)); }
/** * Returns the elements from this fluent iterable that satisfy a predicate. The * resulting fluent iterable's iterator does not support {@code remove()}. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate)} (same). */
Returns the elements from this fluent iterable that satisfy a predicate. The resulting fluent iterable's iterator does not support remove(). Stream equivalent: stream.filter(predicate) (same)
filter
{ "repo_name": "monokurobo/guava", "path": "guava/src/com/google/common/collect/FluentIterable.java", "license": "apache-2.0", "size": 26848 }
[ "com.google.common.base.Predicate" ]
import com.google.common.base.Predicate;
import com.google.common.base.*;
[ "com.google.common" ]
com.google.common;
2,788,377
@SuppressWarnings("unchecked") public void load() { if (recipes != null) unregisterAll(); List<?> r = plugin.getConfig().getList("recipes"); recipes = new ArrayList<CraftingRecipe>(); if (r == null) return; for (Object o : r) { recipes.add(CraftingRecipe.deserialize((Map<String, Object>) o)); } registerAll(); }
@SuppressWarnings(STR) void function() { if (recipes != null) unregisterAll(); List<?> r = plugin.getConfig().getList(STR); recipes = new ArrayList<CraftingRecipe>(); if (r == null) return; for (Object o : r) { recipes.add(CraftingRecipe.deserialize((Map<String, Object>) o)); } registerAll(); }
/** * Load all crafting recipes from the configuration file. */
Load all crafting recipes from the configuration file
load
{ "repo_name": "0x0000null/CraftingPlusPlus", "path": "src/me/nullcraft/craftingpp/RecipeManager.java", "license": "gpl-3.0", "size": 3681 }
[ "java.util.ArrayList", "java.util.List", "java.util.Map" ]
import java.util.ArrayList; import java.util.List; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
1,975,899
public static Type fromString(String string) { try { return Type.valueOf(string); } catch (Exception ex) { return invalid; } } } public enum StartTime { lasthour, lastday, lastweek, lastmonth, lastyear }; } interface Mail { String FOOTER_MESSAGE = "Note: This is a system generated email. Please do not reply to this message. For further assistance contact your Ankush administrator."; } interface Server { String CONFIG = "appConfig"; } interface Method_Type { String GET = "GET"; String POST = "POST"; String DELETE = "DELETE"; } class RoleProcessName { static Map<String, String> ROLE_PROCESS_MAP = new HashMap<String, String>(); static { Map<String, String> roleProcessMap = new HashMap<String, String>(); // Common Roles roleProcessMap.put(Role.NAMENODE, "NameNode"); roleProcessMap.put(Role.DATANODE, "DataNode"); roleProcessMap.put(Role.SECONDARYNAMENODE, "SecondaryNameNode"); // Roles for Hadoop 0.x & 1.x roleProcessMap.put(Role.JOBTRACKER, "JobTracker"); roleProcessMap.put(Role.TASKTRACKER, "TaskTracker"); // Roles for Hadoop 2.x roleProcessMap.put(Role.RESOURCEMANAGER, "ResourceManager"); roleProcessMap.put(Role.WEBAPPPROXYSERVER, "WebAppProxyServer"); roleProcessMap.put(Role.NODEMANAGER, "NodeManager"); roleProcessMap.put(Role.JOURNALNODE, "JournalNode"); roleProcessMap.put(Role.JOBHISTORYSERVER, "JobHistoryServer"); roleProcessMap.put(Role.DFSZKFAILOVERCONTROLLER, "DFSZKFailoverController"); roleProcessMap.put(Role.CASSANDRA_SEED, "CassandraDaemon"); roleProcessMap.put(Role.CASSANDRA_NON_SEED, "CassandraDaemon"); roleProcessMap.put(Role.ZOOKEEPER, "QuorumPeerMain"); roleProcessMap.put(Role.AGENT, "Agent"); // To be changed for // AnkushAgent as it // is hard-coded for // all technologies roleProcessMap.put(Role.GMETAD, "gmetad"); roleProcessMap.put(Role.GMOND, "gmond"); ROLE_PROCESS_MAP = roleProcessMap; }
static Type function(String string) { try { return Type.valueOf(string); } catch (Exception ex) { return invalid; } } } public enum StartTime { lasthour, lastday, lastweek, lastmonth, lastyear }; } interface Mail { String FOOTER_MESSAGE = STR; } interface Server { String CONFIG = STR; } interface Method_Type { String GET = "GET"; String POST = "POST"; String DELETE = STR; } class RoleProcessName { static Map<String, String> ROLE_PROCESS_MAP = new HashMap<String, String>(); static { Map<String, String> roleProcessMap = new HashMap<String, String>(); roleProcessMap.put(Role.NAMENODE, STR); roleProcessMap.put(Role.DATANODE, STR); roleProcessMap.put(Role.SECONDARYNAMENODE, STR); roleProcessMap.put(Role.JOBTRACKER, STR); roleProcessMap.put(Role.TASKTRACKER, STR); roleProcessMap.put(Role.RESOURCEMANAGER, STR); roleProcessMap.put(Role.WEBAPPPROXYSERVER, STR); roleProcessMap.put(Role.NODEMANAGER, STR); roleProcessMap.put(Role.JOURNALNODE, STR); roleProcessMap.put(Role.JOBHISTORYSERVER, STR); roleProcessMap.put(Role.DFSZKFAILOVERCONTROLLER, STR); roleProcessMap.put(Role.CASSANDRA_SEED, STR); roleProcessMap.put(Role.CASSANDRA_NON_SEED, STR); roleProcessMap.put(Role.ZOOKEEPER, STR); roleProcessMap.put(Role.AGENT, "Agent"); roleProcessMap.put(Role.GMETAD, STR); roleProcessMap.put(Role.GMOND, "gmond"); ROLE_PROCESS_MAP = roleProcessMap; }
/** * From string. * * @param string * the string * @return the operation */
From string
fromString
{ "repo_name": "zengzhaozheng/ankush", "path": "ankush/src/main/java/com/impetus/ankush2/constant/Constant.java", "license": "lgpl-3.0", "size": 18199 }
[ "java.util.HashMap", "java.util.Map" ]
import java.util.HashMap; import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,091,391
public EbToken getToken(AnBoardPosition p_position) { Set<EbToken> list = getAllToken( p_position ); EbToken token = null; for( Iterator<EbToken> it = list.iterator(); it.hasNext(); ) { EbToken nextToken = (EbToken)it.next(); if( (token == null) || (token.getType().getZIndex( token.getPosition().getSector() ) < nextToken.getType() .getZIndex( nextToken.getPosition().getSector() )) ) { token = nextToken; } } return token; }
EbToken function(AnBoardPosition p_position) { Set<EbToken> list = getAllToken( p_position ); EbToken token = null; for( Iterator<EbToken> it = list.iterator(); it.hasNext(); ) { EbToken nextToken = (EbToken)it.next(); if( (token == null) (token.getType().getZIndex( token.getPosition().getSector() ) < nextToken.getType() .getZIndex( nextToken.getPosition().getSector() )) ) { token = nextToken; } } return token; }
/** * search over m_token and m_tokenLocation for the most relevant token at a given position * @param p_position * @return the first colored (or by default the first colorless) token encountered at given position. */
search over m_token and m_tokenLocation for the most relevant token at a given position
getToken
{ "repo_name": "kroc702/fullmetalgalaxy", "path": "src/com/fullmetalgalaxy/model/persist/Game.java", "license": "agpl-3.0", "size": 47066 }
[ "java.util.Iterator", "java.util.Set" ]
import java.util.Iterator; import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
2,432,576
private synchronized void insertFileSummary(FileSummaryLN ln, long fileNum, int sequence) throws DatabaseException { byte[] keyBytes = FileSummaryLN.makeFullKey(fileNum, sequence); Locker locker = null; CursorImpl cursor = null; try { locker = new BasicLocker(env); cursor = new CursorImpl(fileSummaryDb, locker); cursor.setAllowEviction(false); OperationStatus status = cursor.putLN(keyBytes, ln, false); if (status == OperationStatus.KEYEXIST) { env.getLogger().log (Level.SEVERE, "Cleaner duplicate key sequence file=0x" + Long.toHexString(fileNum) + " sequence=0x" + Long.toHexString(sequence)); } cursor.evict(); } finally { if (cursor != null) { cursor.close(); } if (locker != null) { locker.operationEnd(); } } }
synchronized void function(FileSummaryLN ln, long fileNum, int sequence) throws DatabaseException { byte[] keyBytes = FileSummaryLN.makeFullKey(fileNum, sequence); Locker locker = null; CursorImpl cursor = null; try { locker = new BasicLocker(env); cursor = new CursorImpl(fileSummaryDb, locker); cursor.setAllowEviction(false); OperationStatus status = cursor.putLN(keyBytes, ln, false); if (status == OperationStatus.KEYEXIST) { env.getLogger().log (Level.SEVERE, STR + Long.toHexString(fileNum) + STR + Long.toHexString(sequence)); } cursor.evict(); } finally { if (cursor != null) { cursor.close(); } if (locker != null) { locker.operationEnd(); } } }
/** * Insert the given LN with the given key values. This method is * synchronized and may not perform eviction. */
Insert the given LN with the given key values. This method is synchronized and may not perform eviction
insertFileSummary
{ "repo_name": "ckaestne/CIDE", "path": "CIDE_Samples/cide_samples/Berkeley DB JE/src/com/sleepycat/je/cleaner/UtilizationProfile.java", "license": "gpl-3.0", "size": 47270 }
[ "com.sleepycat.je.DatabaseException", "com.sleepycat.je.OperationStatus", "com.sleepycat.je.dbi.CursorImpl", "com.sleepycat.je.tree.FileSummaryLN", "com.sleepycat.je.txn.BasicLocker", "com.sleepycat.je.txn.Locker", "java.util.logging.Level" ]
import com.sleepycat.je.DatabaseException; import com.sleepycat.je.OperationStatus; import com.sleepycat.je.dbi.CursorImpl; import com.sleepycat.je.tree.FileSummaryLN; import com.sleepycat.je.txn.BasicLocker; import com.sleepycat.je.txn.Locker; import java.util.logging.Level;
import com.sleepycat.je.*; import com.sleepycat.je.dbi.*; import com.sleepycat.je.tree.*; import com.sleepycat.je.txn.*; import java.util.logging.*;
[ "com.sleepycat.je", "java.util" ]
com.sleepycat.je; java.util;
1,466,433
boolean isUntranslated(LabelEntry e) { Set<String> strs = new HashSet<>(); strs.addAll(e.content.values()); return strs.size() != context.dataManager().languages().size(); }
boolean isUntranslated(LabelEntry e) { Set<String> strs = new HashSet<>(); strs.addAll(e.content.values()); return strs.size() != context.dataManager().languages().size(); }
/** * Are there labels with the same translation? * @param e the entry * @return true if untranslated present */
Are there labels with the same translation
isUntranslated
{ "repo_name": "p-smith/open-ig", "path": "src/hu/openig/editors/ce/CELabelsPanel.java", "license": "lgpl-3.0", "size": 16805 }
[ "java.util.HashSet", "java.util.Set" ]
import java.util.HashSet; import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
2,664,376
@javax.annotation.Nullable @ApiModelProperty( value = "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources") public String getApiVersion() { return apiVersion; }
@javax.annotation.Nullable @ApiModelProperty( value = "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https: String function() { return apiVersion; }
/** * APIVersion defines the versioned schema of this representation of an object. Servers should * convert recognized schemas to the latest internal value, and may reject unrecognized values. * More info: * https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources * * @return apiVersion */
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: HREF
getApiVersion
{ "repo_name": "kubernetes-client/java", "path": "client-java-contrib/cert-manager/src/main/java/io/cert/manager/models/V1beta1Challenge.java", "license": "apache-2.0", "size": 6478 }
[ "io.swagger.annotations.ApiModelProperty" ]
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.*;
[ "io.swagger.annotations" ]
io.swagger.annotations;
2,127,827
Builder addProperty(String name, SchemaOrgType value);
Builder addProperty(String name, SchemaOrgType value);
/** * Add a value to property. * * @param name The property name. * @param value The value of the property. */
Add a value to property
addProperty
{ "repo_name": "google/schemaorg-java", "path": "src/main/java/com/google/schemaorg/core/Service.java", "license": "apache-2.0", "size": 13699 }
[ "com.google.schemaorg.SchemaOrgType" ]
import com.google.schemaorg.SchemaOrgType;
import com.google.schemaorg.*;
[ "com.google.schemaorg" ]
com.google.schemaorg;
2,444,262
@SuppressWarnings("unused") private void setPadding(final JSONArray args, final CallbackContext callbackContext) throws JSONException { JSONObject padding = args.getJSONObject(1); int left = padding.getInt("left"); int top = padding.getInt("top"); int bottom = padding.getInt("bottom"); int right = padding.getInt("right"); map.setPadding(left, top, right, bottom); this.sendNoResult(callbackContext); }
@SuppressWarnings(STR) void function(final JSONArray args, final CallbackContext callbackContext) throws JSONException { JSONObject padding = args.getJSONObject(1); int left = padding.getInt("left"); int top = padding.getInt("top"); int bottom = padding.getInt(STR); int right = padding.getInt("right"); map.setPadding(left, top, right, bottom); this.sendNoResult(callbackContext); }
/** * Sets padding of the map * @param args * @param callbackContext * @throws JSONException */
Sets padding of the map
setPadding
{ "repo_name": "rickdana/phonegap-googlemaps-plugin-master", "path": "src/android/plugin/google/maps/PluginMap.java", "license": "apache-2.0", "size": 17927 }
[ "org.apache.cordova.CallbackContext", "org.json.JSONArray", "org.json.JSONException", "org.json.JSONObject" ]
import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
import org.apache.cordova.*; import org.json.*;
[ "org.apache.cordova", "org.json" ]
org.apache.cordova; org.json;
705,550
public JSONArray put(int index, Hashtable value) throws JSONException { put(index, new JSONObject(value)); return this; }
JSONArray function(int index, Hashtable value) throws JSONException { put(index, new JSONObject(value)); return this; }
/** * Put a value in the JSONArray, where the value will be a * JSONObject which is produced from a Map. * @param index The subscript. * @param value The Map value. * @return this. * @throws JSONException If the index is negative or if the the value is * an invalid number. */
Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map
put
{ "repo_name": "matias-pequeno/ikea-calc-j2me-java", "path": "lib/src/com/mxme/json/JSONArray.java", "license": "gpl-2.0", "size": 26204 }
[ "java.util.Hashtable" ]
import java.util.Hashtable;
import java.util.*;
[ "java.util" ]
java.util;
181,247
public static int getCurrentBandwidth() { return ConnectionClassManager.getInstance().getCurrentBandwidth(); }
static int function() { return ConnectionClassManager.getInstance().getCurrentBandwidth(); }
/** * Method to get currentBandwidth * * @return currentBandwidth */
Method to get currentBandwidth
getCurrentBandwidth
{ "repo_name": "weiwenqiang/GitHub", "path": "expert/Fast-Android-Networking/android-networking/src/main/java/com/androidnetworking/AndroidNetworking.java", "license": "apache-2.0", "size": 9403 }
[ "com.androidnetworking.common.ConnectionClassManager" ]
import com.androidnetworking.common.ConnectionClassManager;
import com.androidnetworking.common.*;
[ "com.androidnetworking.common" ]
com.androidnetworking.common;
1,024,143
public static GeoDBReader getInstance(PoolingDataSource source) { return new GeoDBReader(source); }
static GeoDBReader function(PoolingDataSource source) { return new GeoDBReader(source); }
/** * Static factory method return a GeoDBReader. * * @param source * the pooling data source will be use * @return a new GeoDBReader instance */
Static factory method return a GeoDBReader
getInstance
{ "repo_name": "smart-facility/TransMob", "path": "model/src/main/java/servlet/GeoDBReader.java", "license": "lgpl-3.0", "size": 17945 }
[ "org.postgresql.jdbc2.optional.PoolingDataSource" ]
import org.postgresql.jdbc2.optional.PoolingDataSource;
import org.postgresql.jdbc2.optional.*;
[ "org.postgresql.jdbc2" ]
org.postgresql.jdbc2;
1,167,847
@Test public void testMissingColocatedParentPR() throws Throwable { Host host = Host.getHost(0); VM vm0 = host.getVM(0); VM vm1 = host.getVM(1); vm0.invoke(createPRsColocatedPairThread); vm1.invoke(createPRsColocatedPairThread); createData(vm0, 0, NUM_BUCKETS, "a"); createData(vm0, 0, NUM_BUCKETS, "b", "region2"); Set<Integer> vm0Buckets = getBucketList(vm0, getPartitionedRegionName()); assertFalse(vm0Buckets.isEmpty()); assertEquals(vm0Buckets, getBucketList(vm0, "region2")); Set<Integer> vm1Buckets = getBucketList(vm1, getPartitionedRegionName()); assertEquals(vm1Buckets, getBucketList(vm1, "region2")); closeCache(vm0); closeCache(vm1); // The following should fail immediately with ISE on vm0, it's not necessary to also try the // operation on vm1. Object remoteException = null; remoteException = vm0.invoke(createPRsMissingParentRegionThread); assertEquals("Expected IllegalState Exception for missing colocated parent region", IllegalStateException.class, remoteException.getClass()); assertTrue("Expected IllegalState Exception for missing colocated parent region", remoteException.toString() .matches("java.lang.IllegalStateException: Region specified in 'colocated-with'.*")); }
void function() throws Throwable { Host host = Host.getHost(0); VM vm0 = host.getVM(0); VM vm1 = host.getVM(1); vm0.invoke(createPRsColocatedPairThread); vm1.invoke(createPRsColocatedPairThread); createData(vm0, 0, NUM_BUCKETS, "a"); createData(vm0, 0, NUM_BUCKETS, "b", STR); Set<Integer> vm0Buckets = getBucketList(vm0, getPartitionedRegionName()); assertFalse(vm0Buckets.isEmpty()); assertEquals(vm0Buckets, getBucketList(vm0, STR)); Set<Integer> vm1Buckets = getBucketList(vm1, getPartitionedRegionName()); assertEquals(vm1Buckets, getBucketList(vm1, STR)); closeCache(vm0); closeCache(vm1); Object remoteException = null; remoteException = vm0.invoke(createPRsMissingParentRegionThread); assertEquals(STR, IllegalStateException.class, remoteException.getClass()); assertTrue(STR, remoteException.toString() .matches(STR)); }
/** * Testing that missing colocated persistent PRs are logged as warning */
Testing that missing colocated persistent PRs are logged as warning
testMissingColocatedParentPR
{ "repo_name": "smanvi-pivotal/geode", "path": "geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/PersistentColocatedPartitionedRegionDUnitTest.java", "license": "apache-2.0", "size": 115275 }
[ "java.util.Set", "org.apache.geode.test.dunit.Host", "org.junit.Assert" ]
import java.util.Set; import org.apache.geode.test.dunit.Host; import org.junit.Assert;
import java.util.*; import org.apache.geode.test.dunit.*; import org.junit.*;
[ "java.util", "org.apache.geode", "org.junit" ]
java.util; org.apache.geode; org.junit;
1,103,818
public static Vector buildVectorFromMapElements(Map map) { Vector vector = new Vector(map.size()); Iterator iterator = map.values().iterator(); while (iterator.hasNext()) { vector.addElement(iterator.next()); } return vector; }
static Vector function(Map map) { Vector vector = new Vector(map.size()); Iterator iterator = map.values().iterator(); while (iterator.hasNext()) { vector.addElement(iterator.next()); } return vector; }
/** * Create a new Vector containing all of the map elements. */
Create a new Vector containing all of the map elements
buildVectorFromMapElements
{ "repo_name": "bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs", "path": "foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/helper/Helper.java", "license": "epl-1.0", "size": 92748 }
[ "java.util.Iterator", "java.util.Map", "java.util.Vector" ]
import java.util.Iterator; import java.util.Map; import java.util.Vector;
import java.util.*;
[ "java.util" ]
java.util;
1,286,213
return ArrayUtils.clone(CAUSE_METHOD_NAMES); }
return ArrayUtils.clone(CAUSE_METHOD_NAMES); }
/** * <p>Returns the default names used when searching for the cause of an exception.</p> * * <p>This may be modified and used in the overloaded getCause(Throwable, String[]) method.</p> * * @return cloned array of the default method names * @since 3.0 * @deprecated This feature will be removed in Lang 4.0 */
Returns the default names used when searching for the cause of an exception. This may be modified and used in the overloaded getCause(Throwable, String[]) method
getDefaultCauseMethodNames
{ "repo_name": "0x90sled/droidtowers", "path": "main/source/org/apach3/commons/lang3/exception/ExceptionUtils.java", "license": "mit", "size": 28318 }
[ "org.apach3.commons.lang3.ArrayUtils" ]
import org.apach3.commons.lang3.ArrayUtils;
import org.apach3.commons.lang3.*;
[ "org.apach3.commons" ]
org.apach3.commons;
2,859,455
public void kickPlayer(Player player, String reason) { checkNotNull(player, "player is null!"); checkNotNull(reason, "reason is null!"); this.channel.sendTo(player, buf -> buf.writeUTF("KickPlayer").writeUTF(player.getName()).writeUTF(reason)); }
void function(Player player, String reason) { checkNotNull(player, STR); checkNotNull(reason, STR); this.channel.sendTo(player, buf -> buf.writeUTF(STR).writeUTF(player.getName()).writeUTF(reason)); }
/** * Kicks the given {@link Player} for the given reason. * * @param player The player to kick from the network * @param reason The reason */
Kicks the given <code>Player</code> for the given reason
kickPlayer
{ "repo_name": "BlockJamMC/BlockJamCore", "path": "src/main/java/org/blockjam/core/bungee/BungeeManager.java", "license": "mit", "size": 5903 }
[ "com.google.common.base.Preconditions", "org.spongepowered.api.entity.living.player.Player" ]
import com.google.common.base.Preconditions; import org.spongepowered.api.entity.living.player.Player;
import com.google.common.base.*; import org.spongepowered.api.entity.living.player.*;
[ "com.google.common", "org.spongepowered.api" ]
com.google.common; org.spongepowered.api;
2,253,965
boolean isEditable(CmsObject cms, CmsResource resource) { try { return cms.hasPermissions(resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); } catch (CmsException e) { return false; } }
boolean isEditable(CmsObject cms, CmsResource resource) { try { return cms.hasPermissions(resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); } catch (CmsException e) { return false; } }
/** * Checks if the current user has write permissions on the given resource.<p> * * @param cms the current cms context * @param resource the resource to check * * @return <code>true</code> if the current user has write permissions on the given resource */
Checks if the current user has write permissions on the given resource
isEditable
{ "repo_name": "sbonoc/opencms-core", "path": "src/org/opencms/ade/galleries/CmsGalleryService.java", "license": "lgpl-2.1", "size": 100077 }
[ "org.opencms.file.CmsObject", "org.opencms.file.CmsResource", "org.opencms.file.CmsResourceFilter", "org.opencms.main.CmsException", "org.opencms.security.CmsPermissionSet" ]
import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.main.CmsException; import org.opencms.security.CmsPermissionSet;
import org.opencms.file.*; import org.opencms.main.*; import org.opencms.security.*;
[ "org.opencms.file", "org.opencms.main", "org.opencms.security" ]
org.opencms.file; org.opencms.main; org.opencms.security;
819,845
public ConcurrentMap<String, Object> getSessionData() { return sessionData; }
ConcurrentMap<String, Object> function() { return sessionData; }
/** * Method description * * * */
Method description
getSessionData
{ "repo_name": "amikey/tigase-server", "path": "src/main/java/tigase/net/IOService.java", "license": "agpl-3.0", "size": 37437 }
[ "java.util.concurrent.ConcurrentMap" ]
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.*;
[ "java.util" ]
java.util;
2,564,588
synchronized List<FsVolumeImpl> checkDirs() { ArrayList<FsVolumeImpl> removedVols = null; // Make a copy of volumes for performing modification final List<FsVolumeImpl> volumeList = new ArrayList<FsVolumeImpl>(volumes); for(Iterator<FsVolumeImpl> i = volumeList.iterator(); i.hasNext(); ) { final FsVolumeImpl fsv = i.next(); try { fsv.checkDirs(); } catch (DiskErrorException e) { FsDatasetImpl.LOG.warn("Removing failed volume " + fsv + ": ",e); if (removedVols == null) { removedVols = new ArrayList<FsVolumeImpl>(1); } removedVols.add(fsv); fsv.shutdown(); i.remove(); // Remove the volume numFailedVolumes++; } } if (removedVols != null && removedVols.size() > 0) { // Replace volume list volumes = Collections.unmodifiableList(volumeList); FsDatasetImpl.LOG.warn("Completed checkDirs. Removed " + removedVols.size() + " volumes. Current volumes: " + this); } return removedVols; }
synchronized List<FsVolumeImpl> checkDirs() { ArrayList<FsVolumeImpl> removedVols = null; final List<FsVolumeImpl> volumeList = new ArrayList<FsVolumeImpl>(volumes); for(Iterator<FsVolumeImpl> i = volumeList.iterator(); i.hasNext(); ) { final FsVolumeImpl fsv = i.next(); try { fsv.checkDirs(); } catch (DiskErrorException e) { FsDatasetImpl.LOG.warn(STR + fsv + STR,e); if (removedVols == null) { removedVols = new ArrayList<FsVolumeImpl>(1); } removedVols.add(fsv); fsv.shutdown(); i.remove(); numFailedVolumes++; } } if (removedVols != null && removedVols.size() > 0) { volumes = Collections.unmodifiableList(volumeList); FsDatasetImpl.LOG.warn(STR + removedVols.size() + STR + this); } return removedVols; }
/** * Calls {@link FsVolumeImpl#checkDirs()} on each volume, removing any * volumes from the active list that result in a DiskErrorException. * * This method is synchronized to allow only one instance of checkDirs() * call * @return list of all the removed volumes. */
Calls <code>FsVolumeImpl#checkDirs()</code> on each volume, removing any volumes from the active list that result in a DiskErrorException. This method is synchronized to allow only one instance of checkDirs() call
checkDirs
{ "repo_name": "ict-carch/hadoop-plus", "path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsVolumeList.java", "license": "apache-2.0", "size": 7217 }
[ "java.util.ArrayList", "java.util.Collections", "java.util.Iterator", "java.util.List", "org.apache.hadoop.util.DiskChecker" ]
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.hadoop.util.DiskChecker;
import java.util.*; import org.apache.hadoop.util.*;
[ "java.util", "org.apache.hadoop" ]
java.util; org.apache.hadoop;
1,914,181
public void createBoxTree(BoxTreeCreationStatus stat) { boolean generated = false; do { if (stat.parent.isDisplayed()) { //add previously created boxes (the rest from the last twin) if (stat.parent.preadd != null) { addToTree(stat.parent.preadd, stat); stat.parent.preadd = null; //don't need to keep this anymore } //create :before elements if (stat.parent.previousTwin == null) { Node n = createPseudoElement(stat.parent, PseudoDeclaration.BEFORE); if (n != null && (n.getNodeType() == Node.ELEMENT_NODE || n.getNodeType() == Node.TEXT_NODE)) { stat.curchild = -1; createSubtree(n, stat); } } //create normal elements NodeList children = stat.parent.getElement().getChildNodes(); for (int child = stat.parent.firstDOMChild; child < stat.parent.lastDOMChild; child++) { Node n = children.item(child); if (n.getNodeType() == Node.ELEMENT_NODE || n.getNodeType() == Node.TEXT_NODE) { stat.curchild = child; createSubtree(n, stat); } } //create :after elements if (stat.parent.nextTwin == null) { Node n = createPseudoElement(stat.parent, PseudoDeclaration.AFTER); if (n != null && (n.getNodeType() == Node.ELEMENT_NODE || n.getNodeType() == Node.TEXT_NODE)) { stat.curchild = children.getLength(); createSubtree(n, stat); } } normalizeBox(stat.parent); } //if a twin box has been created, continue creating the unprocessed boxes in the twin box if (stat.parent.nextTwin != null) { stat.parent = stat.parent.nextTwin; generated = true; } else generated = false; } while (generated); }
void function(BoxTreeCreationStatus stat) { boolean generated = false; do { if (stat.parent.isDisplayed()) { if (stat.parent.preadd != null) { addToTree(stat.parent.preadd, stat); stat.parent.preadd = null; } if (stat.parent.previousTwin == null) { Node n = createPseudoElement(stat.parent, PseudoDeclaration.BEFORE); if (n != null && (n.getNodeType() == Node.ELEMENT_NODE n.getNodeType() == Node.TEXT_NODE)) { stat.curchild = -1; createSubtree(n, stat); } } NodeList children = stat.parent.getElement().getChildNodes(); for (int child = stat.parent.firstDOMChild; child < stat.parent.lastDOMChild; child++) { Node n = children.item(child); if (n.getNodeType() == Node.ELEMENT_NODE n.getNodeType() == Node.TEXT_NODE) { stat.curchild = child; createSubtree(n, stat); } } if (stat.parent.nextTwin == null) { Node n = createPseudoElement(stat.parent, PseudoDeclaration.AFTER); if (n != null && (n.getNodeType() == Node.ELEMENT_NODE n.getNodeType() == Node.TEXT_NODE)) { stat.curchild = children.getLength(); createSubtree(n, stat); } } normalizeBox(stat.parent); } if (stat.parent.nextTwin != null) { stat.parent = stat.parent.nextTwin; generated = true; } else generated = false; } while (generated); }
/** * Creates the box subtrees for all the child nodes of the DOM node corresponding to the box creatin status. Recursively creates the child boxes * from the child nodes. * @param stat current tree creation status used for determining the parents */
Creates the box subtrees for all the child nodes of the DOM node corresponding to the box creatin status. Recursively creates the child boxes from the child nodes
createBoxTree
{ "repo_name": "dbmalkovsky/CSSBox", "path": "src/main/java/org/fit/cssbox/layout/BoxFactory.java", "license": "lgpl-3.0", "size": 40538 }
[ "cz.vutbr.web.css.Selector", "org.w3c.dom.Node", "org.w3c.dom.NodeList" ]
import cz.vutbr.web.css.Selector; import org.w3c.dom.Node; import org.w3c.dom.NodeList;
import cz.vutbr.web.css.*; import org.w3c.dom.*;
[ "cz.vutbr.web", "org.w3c.dom" ]
cz.vutbr.web; org.w3c.dom;
2,710,568
public void transferAgentPluginAsync(AuthzSubject subject, AppdefEntityID aid, String plugin) throws PermissionException, FileNotFoundException, AgentNotFoundException, InterruptedException;
void function(AuthzSubject subject, AppdefEntityID aid, String plugin) throws PermissionException, FileNotFoundException, AgentNotFoundException, InterruptedException;
/** * Transfer an agent plugin residing on the HQ server to an agent. The * transfer is performed asynchronously by placing on the Zevent queue and * results in an agent restart. * @param subject The subject issuing the request. * @param aid The agent id. * @param plugin The plugin name. * @throws PermissionException if the subject does not have proper * permissions to issue an agent plugin transfer. * @throws FileNotFoundException if the plugin is not found on the HQ * server. * @throws AgentNotFoundException if no agent exists with the given agent * id. * @throws InterruptedException if enqueuing the Zevent is interrupted. */
Transfer an agent plugin residing on the HQ server to an agent. The transfer is performed asynchronously by placing on the Zevent queue and results in an agent restart
transferAgentPluginAsync
{ "repo_name": "cc14514/hq6", "path": "hq-server/src/main/java/org/hyperic/hq/appdef/shared/AgentManager.java", "license": "unlicense", "size": 24936 }
[ "java.io.FileNotFoundException", "org.hyperic.hq.authz.server.session.AuthzSubject", "org.hyperic.hq.authz.shared.PermissionException" ]
import java.io.FileNotFoundException; import org.hyperic.hq.authz.server.session.AuthzSubject; import org.hyperic.hq.authz.shared.PermissionException;
import java.io.*; import org.hyperic.hq.authz.server.session.*; import org.hyperic.hq.authz.shared.*;
[ "java.io", "org.hyperic.hq" ]
java.io; org.hyperic.hq;
747,106
public static boolean cantStandAtBetter(Block block) { Block otherBlock = block.getRelative(BlockFace.DOWN); boolean center1 = otherBlock.getType() == Material.AIR; boolean north1 = otherBlock.getRelative(BlockFace.NORTH).getType() == Material.AIR; boolean east1 = otherBlock.getRelative(BlockFace.EAST).getType() == Material.AIR; boolean south1 = otherBlock.getRelative(BlockFace.SOUTH).getType() == Material.AIR; boolean west1 = otherBlock.getRelative(BlockFace.WEST).getType() == Material.AIR; boolean northeast1 = otherBlock.getRelative(BlockFace.NORTH_EAST).getType() == Material.AIR; boolean northwest1 = otherBlock.getRelative(BlockFace.NORTH_WEST).getType() == Material.AIR; boolean southeast1 = otherBlock.getRelative(BlockFace.SOUTH_EAST).getType() == Material.AIR; boolean southwest1 = otherBlock.getRelative(BlockFace.SOUTH_WEST).getType() == Material.AIR; boolean overAir1 = (otherBlock.getRelative(BlockFace.DOWN).getType() == Material.AIR || otherBlock.getRelative(BlockFace.DOWN).getType() == Material.WATER || otherBlock.getRelative(BlockFace.DOWN).getType() == Material.LAVA); return (center1 && north1 && east1 && south1 && west1 && northeast1 && southeast1 && northwest1 && southwest1 && overAir1); }
static boolean function(Block block) { Block otherBlock = block.getRelative(BlockFace.DOWN); boolean center1 = otherBlock.getType() == Material.AIR; boolean north1 = otherBlock.getRelative(BlockFace.NORTH).getType() == Material.AIR; boolean east1 = otherBlock.getRelative(BlockFace.EAST).getType() == Material.AIR; boolean south1 = otherBlock.getRelative(BlockFace.SOUTH).getType() == Material.AIR; boolean west1 = otherBlock.getRelative(BlockFace.WEST).getType() == Material.AIR; boolean northeast1 = otherBlock.getRelative(BlockFace.NORTH_EAST).getType() == Material.AIR; boolean northwest1 = otherBlock.getRelative(BlockFace.NORTH_WEST).getType() == Material.AIR; boolean southeast1 = otherBlock.getRelative(BlockFace.SOUTH_EAST).getType() == Material.AIR; boolean southwest1 = otherBlock.getRelative(BlockFace.SOUTH_WEST).getType() == Material.AIR; boolean overAir1 = (otherBlock.getRelative(BlockFace.DOWN).getType() == Material.AIR otherBlock.getRelative(BlockFace.DOWN).getType() == Material.WATER otherBlock.getRelative(BlockFace.DOWN).getType() == Material.LAVA); return (center1 && north1 && east1 && south1 && west1 && northeast1 && southeast1 && northwest1 && southwest1 && overAir1); }
/** * Determine whether or not a player can stand in a given location, * and do so correctly * * @param theBlock The block to be checked * @return true if the player should be unable to stand here */
Determine whether or not a player can stand in a given location, and do so correctly
cantStandAtBetter
{ "repo_name": "dmulloy2/AntiCheat", "path": "src/main/java/net/gravitydevelopment/anticheat/util/Util.java", "license": "gpl-3.0", "size": 27170 }
[ "org.bukkit.Material", "org.bukkit.block.Block", "org.bukkit.block.BlockFace" ]
import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace;
import org.bukkit.*; import org.bukkit.block.*;
[ "org.bukkit", "org.bukkit.block" ]
org.bukkit; org.bukkit.block;
831,233
private void showTypeChoice(Widget w, final ISingleFieldConstraint con) { final FormStylePopup form = new FormStylePopup( "images/newex_wiz.gif", "Field value" );
void function(Widget w, final ISingleFieldConstraint con) { final FormStylePopup form = new FormStylePopup( STR, STR );
/** * Show a list of possibilities for the value type. */
Show a list of possibilities for the value type
showTypeChoice
{ "repo_name": "bobmcwhirter/drools", "path": "drools-guvnor/src/main/java/org/drools/guvnor/client/modeldriven/ui/ConstraintValueEditor.java", "license": "apache-2.0", "size": 15181 }
[ "com.google.gwt.user.client.ui.Widget", "org.drools.guvnor.client.common.FormStylePopup", "org.drools.guvnor.client.modeldriven.brl.ISingleFieldConstraint" ]
import com.google.gwt.user.client.ui.Widget; import org.drools.guvnor.client.common.FormStylePopup; import org.drools.guvnor.client.modeldriven.brl.ISingleFieldConstraint;
import com.google.gwt.user.client.ui.*; import org.drools.guvnor.client.common.*; import org.drools.guvnor.client.modeldriven.brl.*;
[ "com.google.gwt", "org.drools.guvnor" ]
com.google.gwt; org.drools.guvnor;
1,874,213