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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
static NativePeer getNativePeer (ClassInfo ci) {
String clsName = ci.getName();
NativePeer peer = peers.get(ci);
Class<?> peerCls = null;
if (peer == null) {
peerCls = locatePeerCls(clsName);
if (peerCls != null) {
initializePeerClass( peerCls);
if (logger.isLoggable(Level.INFO)) {
logger.info("load peer: ", peerCls.getName());
}
peer = getInstance(peerCls, NativePeer.class);
peer.initialize(peerCls, ci, true);
peers.put(ci, peer);
}
}
return peer;
} | static NativePeer getNativePeer (ClassInfo ci) { String clsName = ci.getName(); NativePeer peer = peers.get(ci); Class<?> peerCls = null; if (peer == null) { peerCls = locatePeerCls(clsName); if (peerCls != null) { initializePeerClass( peerCls); if (logger.isLoggable(Level.INFO)) { logger.info(STR, peerCls.getName()); } peer = getInstance(peerCls, NativePeer.class); peer.initialize(peerCls, ci, true); peers.put(ci, peer); } } return peer; } | /**
* this becomes the factory method to load either a plain (slow)
* reflection-based peer (a NativePeer object), or some speed optimized
* derived class object.
* Watch out - this gets called before the ClassInfo is fully initialized
* (we shouldn't rely on more than just its name here)
*/ | this becomes the factory method to load either a plain (slow) reflection-based peer (a NativePeer object), or some speed optimized derived class object. Watch out - this gets called before the ClassInfo is fully initialized (we shouldn't rely on more than just its name here) | getNativePeer | {
"repo_name": "grzesuav/jpf-core",
"path": "src/main/gov/nasa/jpf/vm/NativePeer.java",
"license": "apache-2.0",
"size": 13721
} | [
"java.util.logging.Level"
] | import java.util.logging.Level; | import java.util.logging.*; | [
"java.util"
] | java.util; | 1,879,625 |
protected void initialize(CardServiceScheduler scheduler, SmartCard card, boolean blocking) throws CardServiceException {
super.initialize(HEALTH_CARD_AID, scheduler, card, blocking);
System.out.println("HealthCardProxy.initialize");
try {
// Allocate the card channel. This gives us exclusive access to the card until we
// release the channel.
allocateCardChannel();
// Get the card state.
Hashtable cardState = (Hashtable) getCardChannel().getState();
// Get the health card applet state. If not already there, create it.
HealthCardState state = (HealthCardState) cardState.get(HEALTH_CARD_AID);
if (state == null) {
state = new HealthCardState();
state.setCHVPerformed(false);
cardState.put(HEALTH_CARD_AID, state);
System.out.println("HealthCardProxy.initialize - created HealthCardState");
}
} finally {
releaseCardChannel();
}
}
| void function(CardServiceScheduler scheduler, SmartCard card, boolean blocking) throws CardServiceException { super.initialize(HEALTH_CARD_AID, scheduler, card, blocking); System.out.println(STR); try { allocateCardChannel(); Hashtable cardState = (Hashtable) getCardChannel().getState(); HealthCardState state = (HealthCardState) cardState.get(HEALTH_CARD_AID); if (state == null) { state = new HealthCardState(); state.setCHVPerformed(false); cardState.put(HEALTH_CARD_AID, state); System.out.println(STR); } } finally { releaseCardChannel(); } } | /**
* Create a <tt>HealthCardProxy</tt> instance.
*
* @param scheduler The Scheduler from which channels have to be obtained.
* @param card The SmartCard object to which this service belongs.
* @param blocking Currently not used.
*
* @throws opencard.core.service.CardServiceException
* Thrown when instantiation fails.
*/ | Create a HealthCardProxy instance | initialize | {
"repo_name": "popovici-gabriel/projects",
"path": "electronic-health-card/offCard/health/HealthCardProxy.java",
"license": "gpl-2.0",
"size": 23114
} | [
"java.util.Hashtable"
] | import java.util.Hashtable; | import java.util.*; | [
"java.util"
] | java.util; | 2,878,758 |
public Set<String> getKeys(){
return Collections.unmodifiableSet(map.keySet());
}
| Set<String> function(){ return Collections.unmodifiableSet(map.keySet()); } | /**
* Fetches a set of strings which represent the keys for this
* config section. This set is immutable.
* @return the set of strings
*/ | Fetches a set of strings which represent the keys for this config section. This set is immutable | getKeys | {
"repo_name": "tehnewb/Titan",
"path": "src/org/maxgamer/rs/structure/configs/ConfigSection.java",
"license": "gpl-3.0",
"size": 15001
} | [
"java.util.Collections",
"java.util.Set"
] | import java.util.Collections; import java.util.Set; | import java.util.*; | [
"java.util"
] | java.util; | 140,536 |
public void populateRandomMoveableTileArray() {
//_arrayOfMoveTiles contains a total of 34 MoveableTile instances
//6 T type tiles, 15 L type tiles, and 13 I type tiles
//The tiles are rotated at random to simulate them jumbled in a
//bag, so they have random rotation on the board
//there will be one MoveableTile left in the ArrayList
//after using up 33 to populate the _board (of type AbstractTile[][])
for(int i = 1; i <= 6; i++){
MoveableTile mT = new MoveableTile("T");
mT.rotate(randomDegree());
_arrayOfMoveTiles.add(mT);
}
for(int i = 1; i <= 15; i++){
MoveableTile mT = new MoveableTile("L");
mT.rotate(randomDegree());
_arrayOfMoveTiles.add(mT);
}
for(int i = 1; i <= 13; i++){
MoveableTile mT = new MoveableTile("I");
mT.rotate(randomDegree());
_arrayOfMoveTiles.add(mT);
}
Collections.shuffle(_arrayOfMoveTiles);
//System.out.println("Initial Size of array: " + _arrayOfMoveTiles.size());
}
| void function() { for(int i = 1; i <= 6; i++){ MoveableTile mT = new MoveableTile("T"); mT.rotate(randomDegree()); _arrayOfMoveTiles.add(mT); } for(int i = 1; i <= 15; i++){ MoveableTile mT = new MoveableTile("L"); mT.rotate(randomDegree()); _arrayOfMoveTiles.add(mT); } for(int i = 1; i <= 13; i++){ MoveableTile mT = new MoveableTile("I"); mT.rotate(randomDegree()); _arrayOfMoveTiles.add(mT); } Collections.shuffle(_arrayOfMoveTiles); } | /**
* The method randomly populates board with movable tiles
* _arrayOfMoveTiles contains a total of 34 MoveableTile instances
* 6 T type tiles, 15 L type tiles, and 13 I type tiles
* These tiles are randomly rotated by calling .rotate(randomDegree())
* @author Ken, Ian
*/ | The method randomly populates board with movable tiles _arrayOfMoveTiles contains a total of 34 MoveableTile instances 6 T type tiles, 15 L type tiles, and 13 I type tiles These tiles are randomly rotated by calling .rotate(randomDegree()) | populateRandomMoveableTileArray | {
"repo_name": "anandimous/Master_Labyrinth-Game",
"path": "Stage_2/src/code/model/GameBoard.java",
"license": "apache-2.0",
"size": 36758
} | [
"java.util.Collections"
] | import java.util.Collections; | import java.util.*; | [
"java.util"
] | java.util; | 733,711 |
private void sendDemoReminder()
{
if (this.field_73104_e > 100)
{
this.thisPlayerMP.addChatMessage(new ChatComponentTranslation("demo.reminder", new Object[0]));
this.field_73104_e = 0;
}
} | void function() { if (this.field_73104_e > 100) { this.thisPlayerMP.addChatMessage(new ChatComponentTranslation(STR, new Object[0])); this.field_73104_e = 0; } } | /**
* Sends a message to the player reminding them that this is the demo version
*/ | Sends a message to the player reminding them that this is the demo version | sendDemoReminder | {
"repo_name": "dogjaw2233/tiu-s-mod",
"path": "build/tmp/recompileMc/sources/net/minecraft/world/demo/DemoWorldManager.java",
"license": "lgpl-2.1",
"size": 4228
} | [
"net.minecraft.util.ChatComponentTranslation"
] | import net.minecraft.util.ChatComponentTranslation; | import net.minecraft.util.*; | [
"net.minecraft.util"
] | net.minecraft.util; | 550,478 |
public boolean hasGeoRssWhere() {
return hasExtension(GeoRssWhere.class);
} | boolean function() { return hasExtension(GeoRssWhere.class); } | /**
* Returns whether it has the geolocation as a georss:where.
*
* @return whether it has the geolocation as a georss:where
*/ | Returns whether it has the geolocation as a georss:where | hasGeoRssWhere | {
"repo_name": "simonrrr/gdata-java-client",
"path": "java/src/com/google/gdata/data/photos/PhotoEntry.java",
"license": "apache-2.0",
"size": 38896
} | [
"com.google.gdata.data.geo.impl.GeoRssWhere"
] | import com.google.gdata.data.geo.impl.GeoRssWhere; | import com.google.gdata.data.geo.impl.*; | [
"com.google.gdata"
] | com.google.gdata; | 2,220,680 |
public StateMustBePublicMatch newMatch(final State pSt) {
return StateMustBePublicMatch.newMatch(pSt);
}
| StateMustBePublicMatch function(final State pSt) { return StateMustBePublicMatch.newMatch(pSt); } | /**
* Returns a new (partial) match.
* This can be used e.g. to call the matcher with a partial match.
* <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
* @param pSt the fixed value of pattern parameter st, or null if not bound.
* @return the (partial) match object.
*
*/ | Returns a new (partial) match. This can be used e.g. to call the matcher with a partial match. The returned match will be immutable. Use <code>#newEmptyMatch()</code> to obtain a mutable match object | newMatch | {
"repo_name": "ELTE-Soft/xUML-RT-Executor",
"path": "plugins/hu.eltesoft.modelexecution.validation/src-gen/hu/eltesoft/modelexecution/validation/StateMustBePublicMatcher.java",
"license": "epl-1.0",
"size": 10240
} | [
"hu.eltesoft.modelexecution.validation.StateMustBePublicMatch",
"org.eclipse.uml2.uml.State"
] | import hu.eltesoft.modelexecution.validation.StateMustBePublicMatch; import org.eclipse.uml2.uml.State; | import hu.eltesoft.modelexecution.validation.*; import org.eclipse.uml2.uml.*; | [
"hu.eltesoft.modelexecution",
"org.eclipse.uml2"
] | hu.eltesoft.modelexecution; org.eclipse.uml2; | 1,703,577 |
@SuppressWarnings("rawtypes")
private void sendResponse( String status, String mime, Properties header, InputStream data )
{
try
{
if ( status == null )
throw new Error( "sendResponse(): Status can't be null." );
OutputStream out = mySocket.getOutputStream();
PrintWriter pw = new PrintWriter( out );
pw.print("HTTP/1.0 " + status + " \r\n");
if ( mime != null )
pw.print("Content-Type: " + mime + "\r\n");
if ( header == null || header.getProperty( "Date" ) == null )
pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n");
if ( header != null )
{
Enumeration e = header.keys();
while ( e.hasMoreElements())
{
String key = (String)e.nextElement();
String value = header.getProperty( key );
pw.print( key + ": " + value + "\r\n");
}
}
pw.print("\r\n");
pw.flush();
if ( data != null )
{
int pending = data.available(); // This is to support partial sends, see serveFile()
byte[] buff = new byte[theBufferSize];
while (pending>0)
{
int read = data.read( buff, 0, ( (pending>theBufferSize) ? theBufferSize : pending ));
if (read <= 0) break;
out.write( buff, 0, read );
pending -= read;
}
}
out.flush();
out.close();
if ( data != null )
data.close();
}
catch( IOException ioe )
{
// Couldn't write? No can do.
try { mySocket.close(); } catch( Throwable t ) {}
}
}
private Socket mySocket;
}
| @SuppressWarnings(STR) void function( String status, String mime, Properties header, InputStream data ) { try { if ( status == null ) throw new Error( STR ); OutputStream out = mySocket.getOutputStream(); PrintWriter pw = new PrintWriter( out ); pw.print(STR + status + STR); if ( mime != null ) pw.print(STR + mime + "\r\n"); if ( header == null header.getProperty( "Date" ) == null ) pw.print( STR + gmtFrmt.format( new Date()) + "\r\n"); if ( header != null ) { Enumeration e = header.keys(); while ( e.hasMoreElements()) { String key = (String)e.nextElement(); String value = header.getProperty( key ); pw.print( key + STR + value + "\r\n"); } } pw.print("\r\n"); pw.flush(); if ( data != null ) { int pending = data.available(); byte[] buff = new byte[theBufferSize]; while (pending>0) { int read = data.read( buff, 0, ( (pending>theBufferSize) ? theBufferSize : pending )); if (read <= 0) break; out.write( buff, 0, read ); pending -= read; } } out.flush(); out.close(); if ( data != null ) data.close(); } catch( IOException ioe ) { try { mySocket.close(); } catch( Throwable t ) {} } } private Socket mySocket; } | /**
* Sends given response to the socket.
*/ | Sends given response to the socket | sendResponse | {
"repo_name": "goje87/bsafe-cap",
"path": "plugins/com.rjfun.cordova.httpd/src/android/NanoHTTPD.java",
"license": "mit",
"size": 36046
} | [
"java.io.IOException",
"java.io.InputStream",
"java.io.OutputStream",
"java.io.PrintWriter",
"java.net.Socket",
"java.util.Date",
"java.util.Enumeration",
"java.util.Properties"
] | import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.util.Date; import java.util.Enumeration; import java.util.Properties; | import java.io.*; import java.net.*; import java.util.*; | [
"java.io",
"java.net",
"java.util"
] | java.io; java.net; java.util; | 1,743,514 |
@Test
public void testSetRows_StringArr() {
System.out.println("Testing AbstractmatrixModel's setRows(String[] Array)");
String[] rowNames = new String[2];
MatrixTester instance=new MatrixTester("why");
rowNames[0]="hello";
rowNames[1]="there";
instance.setRows(rowNames);
assertEquals("{0=hello, 1=there}",instance.getRows().toString());
} | void function() { System.out.println(STR); String[] rowNames = new String[2]; MatrixTester instance=new MatrixTester("why"); rowNames[0]="hello"; rowNames[1]="there"; instance.setRows(rowNames); assertEquals(STR,instance.getRows().toString()); } | /**
* Test of set_Rows method, of class AbstractMatrixModel.
*/ | Test of set_Rows method, of class AbstractMatrixModel | testSetRows_StringArr | {
"repo_name": "clementparizot/ET_Redux",
"path": "src/test/java/org/earthtime/matrices/matrixModels/AbstractMatrixModelTest.java",
"license": "apache-2.0",
"size": 15973
} | [
"org.junit.Assert"
] | import org.junit.Assert; | import org.junit.*; | [
"org.junit"
] | org.junit; | 1,828,803 |
EList<IfcRelDefinesByProperties> getDefinesOccurrence(); | EList<IfcRelDefinesByProperties> getDefinesOccurrence(); | /**
* Returns the value of the '<em><b>Defines Occurrence</b></em>' reference list.
* The list contents are of type {@link cn.dlb.bim.models.ifc4.IfcRelDefinesByProperties}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Defines Occurrence</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Defines Occurrence</em>' reference list.
* @see #isSetDefinesOccurrence()
* @see #unsetDefinesOccurrence()
* @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcPropertySetDefinition_DefinesOccurrence()
* @model unsettable="true" upper="2"
* @generated
*/ | Returns the value of the 'Defines Occurrence' reference list. The list contents are of type <code>cn.dlb.bim.models.ifc4.IfcRelDefinesByProperties</code>. If the meaning of the 'Defines Occurrence' reference list isn't clear, there really should be more of a description here... | getDefinesOccurrence | {
"repo_name": "shenan4321/BIMplatform",
"path": "generated/cn/dlb/bim/models/ifc4/IfcPropertySetDefinition.java",
"license": "agpl-3.0",
"size": 6380
} | [
"org.eclipse.emf.common.util.EList"
] | import org.eclipse.emf.common.util.EList; | import org.eclipse.emf.common.util.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,675,380 |
public void scheduleDownload(WebContents webContents, String nameSpace, String url,
int uiAction, OfflinePageOrigin origin) {
org.chromium.chrome.browser.offlinepages.OfflinePageBridgeJni.get().scheduleDownload(
mNativeOfflinePageBridge, OfflinePageBridge.this, webContents, nameSpace, url,
uiAction, origin.encodeAsJsonString());
} | void function(WebContents webContents, String nameSpace, String url, int uiAction, OfflinePageOrigin origin) { org.chromium.chrome.browser.offlinepages.OfflinePageBridgeJni.get().scheduleDownload( mNativeOfflinePageBridge, OfflinePageBridge.this, webContents, nameSpace, url, uiAction, origin.encodeAsJsonString()); } | /**
* Schedules to download a page from |url| and categorize under |namespace| from |origin|.
* The duplicate pages or requests will be checked.
*
* @param webContents Web contents upon which the infobar is shown.
* @param nameSpace Namespace of the page to save.
* @param url URL of the page to save.
* @param uiAction UI action, like showing infobar or toast on certain case.
* @param origin Origin of the page.
*/ | Schedules to download a page from |url| and categorize under |namespace| from |origin|. The duplicate pages or requests will be checked | scheduleDownload | {
"repo_name": "chromium/chromium",
"path": "chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridge.java",
"license": "bsd-3-clause",
"size": 33049
} | [
"org.chromium.content_public.browser.WebContents"
] | import org.chromium.content_public.browser.WebContents; | import org.chromium.content_public.browser.*; | [
"org.chromium.content_public"
] | org.chromium.content_public; | 57,449 |
//-----------------------------------------------------------------------
public CurrencyAmount getTickValue() {
return tickValue;
} | CurrencyAmount function() { return tickValue; } | /**
* Gets the monetary value of one tick.
* <p>
* When the price changes by one tick, this amount is gained/lost.
* @return the value of the property, not null
*/ | Gets the monetary value of one tick. When the price changes by one tick, this amount is gained/lost | getTickValue | {
"repo_name": "nssales/Strata",
"path": "modules/finance/src/main/java/com/opengamma/strata/finance/future/GenericFutureOption.java",
"license": "apache-2.0",
"size": 36115
} | [
"com.opengamma.strata.basics.currency.CurrencyAmount"
] | import com.opengamma.strata.basics.currency.CurrencyAmount; | import com.opengamma.strata.basics.currency.*; | [
"com.opengamma.strata"
] | com.opengamma.strata; | 2,035,807 |
public Converter getNewsItemFieldConverter() {
return new NewsItemFieldConverter();
}
| Converter function() { return new NewsItemFieldConverter(); } | /**
* Gets a {@link Converter} for NewsItemFields
*
* @return {@link Converter} for NewsItemFields
*/ | Gets a <code>Converter</code> for NewsItemFields | getNewsItemFieldConverter | {
"repo_name": "getconverge/converge-1.x",
"path": "modules/converge-war/src/main/java/dk/i2m/converge/jsf/beans/Converters.java",
"license": "gpl-3.0",
"size": 9492
} | [
"dk.i2m.converge.jsf.converters.NewsItemFieldConverter",
"javax.faces.convert.Converter"
] | import dk.i2m.converge.jsf.converters.NewsItemFieldConverter; import javax.faces.convert.Converter; | import dk.i2m.converge.jsf.converters.*; import javax.faces.convert.*; | [
"dk.i2m.converge",
"javax.faces"
] | dk.i2m.converge; javax.faces; | 2,797,704 |
public static void saveInputStreamToFile(InputStream inputStream, String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = null;
try {
int len = 4096;
int readCount = 0, readSum = 0;
byte[] buffer = new byte[len];
fos = new FileOutputStream(filePath);
while ((readCount = inputStream.read(buffer)) != -1) {
readSum += readCount;
fos.write(buffer, 0, readCount);
}
fos.flush();
} finally {
if (fos != null) fos.close();
}
} | static void function(InputStream inputStream, String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = null; try { int len = 4096; int readCount = 0, readSum = 0; byte[] buffer = new byte[len]; fos = new FileOutputStream(filePath); while ((readCount = inputStream.read(buffer)) != -1) { readSum += readCount; fos.write(buffer, 0, readCount); } fos.flush(); } finally { if (fos != null) fos.close(); } } | /**
* save inputStream to file
*
* @param inputStream inputStream
* @param filePath file path (include file name)
* @throws IOException save failure
*/ | save inputStream to file | saveInputStreamToFile | {
"repo_name": "ChinaSunHZ/ProjectUtils",
"path": "app/src/main/java/com/sunhz/projectutils/fileutils/FileUtils.java",
"license": "apache-2.0",
"size": 24009
} | [
"java.io.File",
"java.io.FileOutputStream",
"java.io.IOException",
"java.io.InputStream"
] | import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; | import java.io.*; | [
"java.io"
] | java.io; | 2,165,697 |
@Override
public void dispose() {
owlOntology.getOWLOntologyManager().removeOntologyChangeListener(
ontologyChangeListener);
rawChanges.clear();
reasoner = new SnorocketReasoner();
}
// //////////////////////////////////////////////////////////////////////////
// Main method to use stand alone
// //////////////////////////////////////////////////////////////////////////
| void function() { owlOntology.getOWLOntologyManager().removeOntologyChangeListener( ontologyChangeListener); rawChanges.clear(); reasoner = new SnorocketReasoner(); } | /**
* Disposes of this reasoner. This frees up any resources used by the
* reasoner and detaches the reasoner as an
* {@link org.semanticweb.owlapi.model.OWLOntologyChangeListener} from the
* {@link org.semanticweb.owlapi.model.OWLOntologyManager} that manages the
* ontologies contained within the reasoner.
*/ | Disposes of this reasoner. This frees up any resources used by the reasoner and detaches the reasoner as an <code>org.semanticweb.owlapi.model.OWLOntologyChangeListener</code> from the <code>org.semanticweb.owlapi.model.OWLOntologyManager</code> that manages the ontologies contained within the reasoner | dispose | {
"repo_name": "aehrc/snorocket",
"path": "snorocket-owlapi/src/main/java/au/csiro/snorocket/owlapi/SnorocketOWLReasoner.java",
"license": "apache-2.0",
"size": 98531
} | [
"au.csiro.snorocket.core.SnorocketReasoner"
] | import au.csiro.snorocket.core.SnorocketReasoner; | import au.csiro.snorocket.core.*; | [
"au.csiro.snorocket"
] | au.csiro.snorocket; | 133,693 |
protected void prepare()
{
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("AD_Client_ID"))
m_AD_Client_ID = ((BigDecimal)para[i].getParameter()).intValue();
else if (name.equals("PA_ReportLineSet_ID"))
m_PA_ReportLineSet_ID = ((BigDecimal)para[i].getParameter()).intValue();
else if (name.equals("DeleteOldImported"))
m_deleteOldImported = "Y".equals(para[i].getParameter());
else
log.log(Level.SEVERE, "Unknown Parameter: " + name);
}
if (m_DateValue == null)
m_DateValue = new Timestamp (System.currentTimeMillis());
} // prepare
| void function() { ProcessInfoParameter[] para = getParameter(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals(STR)) m_AD_Client_ID = ((BigDecimal)para[i].getParameter()).intValue(); else if (name.equals(STR)) m_PA_ReportLineSet_ID = ((BigDecimal)para[i].getParameter()).intValue(); else if (name.equals(STR)) m_deleteOldImported = "Y".equals(para[i].getParameter()); else log.log(Level.SEVERE, STR + name); } if (m_DateValue == null) m_DateValue = new Timestamp (System.currentTimeMillis()); } | /**
* Prepare - e.g., get Parameters.
*/ | Prepare - e.g., get Parameters | prepare | {
"repo_name": "erpcya/adempierePOS",
"path": "base/src/org/compiere/process/ImportReportLine.java",
"license": "gpl-2.0",
"size": 21976
} | [
"java.math.BigDecimal",
"java.sql.Timestamp",
"java.util.logging.Level"
] | import java.math.BigDecimal; import java.sql.Timestamp; import java.util.logging.Level; | import java.math.*; import java.sql.*; import java.util.logging.*; | [
"java.math",
"java.sql",
"java.util"
] | java.math; java.sql; java.util; | 2,452,433 |
@SuppressWarnings("unchecked")
public <T> T readValue(JsonParser jp, JavaType valueType)
throws IOException, JsonParseException, JsonMappingException {
return (T) _readValue(getDeserializationConfig(), jp, valueType);
}
/**
* Method to deserialize JSON content as tree expressed using set of
* {@link JsonNode} instances. Returns root of the resulting tree (where
* root can consist of just a single node if the current event is a value
* event, not container).
*
* @return a {@link JsonNode}, if valid JSON content found; null if input
* has no content to bind -- note, however, that if JSON
* <code>null</code> token is found, it will be represented as a
* non-null {@link JsonNode} (one that returns <code>true</code> for
* {@link JsonNode#isNull()} | @SuppressWarnings(STR) <T> T function(JsonParser jp, JavaType valueType) throws IOException, JsonParseException, JsonMappingException { return (T) _readValue(getDeserializationConfig(), jp, valueType); } /** * Method to deserialize JSON content as tree expressed using set of * {@link JsonNode} instances. Returns root of the resulting tree (where * root can consist of just a single node if the current event is a value * event, not container). * * @return a {@link JsonNode}, if valid JSON content found; null if input * has no content to bind -- note, however, that if JSON * <code>null</code> token is found, it will be represented as a * non-null {@link JsonNode} (one that returns <code>true</code> for * {@link JsonNode#isNull()} | /**
* Type-safe overloaded method, basically alias for
* {@link #readValue(JsonParser, Class)}.
*
* @throws IOException
* if a low-level I/O problem (unexpected end-of-input, network
* error) occurs (passed through as-is without additional
* wrapping -- note that this is one case where
* {@link DeserializationFeature#WRAP_EXCEPTIONS} does NOT
* result in wrapping of exception even if enabled)
* @throws JsonParseException
* if underlying input contains invalid content of type
* {@link JsonParser} supports (JSON for default case)
* @throws JsonMappingException
* if the input JSON structure does not match structure expected
* for result type (or has other mismatch issues)
*/ | Type-safe overloaded method, basically alias for <code>#readValue(JsonParser, Class)</code> | readValue | {
"repo_name": "magidc/trevin-json",
"path": "src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java",
"license": "mit",
"size": 149768
} | [
"com.fasterxml.jackson.core.JsonParseException",
"com.fasterxml.jackson.core.JsonParser",
"java.io.IOException"
] | import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import java.io.IOException; | import com.fasterxml.jackson.core.*; import java.io.*; | [
"com.fasterxml.jackson",
"java.io"
] | com.fasterxml.jackson; java.io; | 543,855 |
List<SqlElasticPool> listBySqlServer(String resourceGroupName, String sqlServerName); | List<SqlElasticPool> listBySqlServer(String resourceGroupName, String sqlServerName); | /**
* Lists resources of the specified type in the specified resource group and SQLServer.
*
* @param resourceGroupName the name of the resource group to list the resources from
* @param sqlServerName the name of SQLServer
* @return the list of SQLElasticPools in a SQLServer
*/ | Lists resources of the specified type in the specified resource group and SQLServer | listBySqlServer | {
"repo_name": "jianghaolu/azure-sdk-for-java",
"path": "azure-mgmt-sql/src/main/java/com/microsoft/azure/management/sql/SqlElasticPools.java",
"license": "mit",
"size": 3332
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,275,114 |
public static Model removeConnected(Model model, Resource resource) {
Model remainingStmts = new LinkedHashModel(model);
Set<Value> connectedValues = new HashSet<Value>();
Model stmtsMatchingSubject = model.filter(resource, null, null);
connectedValues.addAll(stmtsMatchingSubject.objects());
remainingStmts.removeAll(stmtsMatchingSubject);
Model stmtsMatchingObject = model.filter(null, null, resource);
connectedValues.addAll(stmtsMatchingObject.subjects());
remainingStmts.removeAll(stmtsMatchingObject);
connectedValues = connectedValues.stream().filter(node -> node instanceof Resource).collect(Collectors.toSet());
for (Value node: connectedValues) {
if (remainingStmts.size()==0) {
return remainingStmts;
}
remainingStmts = removeConnected(remainingStmts, (Resource)node);
}
return remainingStmts;
}
private static class Identifiers {
private Resource officalId;
private Resource assertedId;
private Identifiers(Resource officalId, Resource assertedId) {
this.officalId = officalId;
this.assertedId = assertedId;
}
} | static Model function(Model model, Resource resource) { Model remainingStmts = new LinkedHashModel(model); Set<Value> connectedValues = new HashSet<Value>(); Model stmtsMatchingSubject = model.filter(resource, null, null); connectedValues.addAll(stmtsMatchingSubject.objects()); remainingStmts.removeAll(stmtsMatchingSubject); Model stmtsMatchingObject = model.filter(null, null, resource); connectedValues.addAll(stmtsMatchingObject.subjects()); remainingStmts.removeAll(stmtsMatchingObject); connectedValues = connectedValues.stream().filter(node -> node instanceof Resource).collect(Collectors.toSet()); for (Value node: connectedValues) { if (remainingStmts.size()==0) { return remainingStmts; } remainingStmts = removeConnected(remainingStmts, (Resource)node); } return remainingStmts; } private static class Identifiers { private Resource officalId; private Resource assertedId; private Identifiers(Resource officalId, Resource assertedId) { this.officalId = officalId; this.assertedId = assertedId; } } | /**
* Remove from model any statements that are connected directly or indirectly to the resource specified
* @param model
* @param resource
* @return
*/ | Remove from model any statements that are connected directly or indirectly to the resource specified | removeConnected | {
"repo_name": "rmap-project/rmap",
"path": "core/src/main/java/info/rmapproject/core/model/impl/rdf4j/OStatementsAdapter.java",
"license": "apache-2.0",
"size": 28793
} | [
"java.util.HashSet",
"java.util.Set",
"java.util.stream.Collectors",
"org.eclipse.rdf4j.model.Model",
"org.eclipse.rdf4j.model.Resource",
"org.eclipse.rdf4j.model.Value",
"org.eclipse.rdf4j.model.impl.LinkedHashModel"
] | import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.impl.LinkedHashModel; | import java.util.*; import java.util.stream.*; import org.eclipse.rdf4j.model.*; import org.eclipse.rdf4j.model.impl.*; | [
"java.util",
"org.eclipse.rdf4j"
] | java.util; org.eclipse.rdf4j; | 2,043,871 |
public final boolean readBoolean() throws IOException {
return readBoolean(readByte());
} | final boolean function() throws IOException { return readBoolean(readByte()); } | /**
* Reads a boolean.
*/ | Reads a boolean | readBoolean | {
"repo_name": "crate/crate",
"path": "server/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java",
"license": "apache-2.0",
"size": 44326
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 2,627,642 |
private List<Link> createResourceStateMachineForNotes(String resourceEntityName) {
String entityName = "Note";
ResourceState initialState = new ResourceState(entityName, "note", new ArrayList<Action>(), "/notes({noteId})");
initialState.setInitial(true);
Map<String, String> uriLinkageMap = new HashMap<String, String>();
uriLinkageMap.put("id", "{noteId}");
ResourceState noteEditState = new ResourceState(entityName, "note_edit", new ArrayList<Action>(), "/edit");
initialState.addTransition(new Transition.Builder().target(noteEditState).uriParameters(uriLinkageMap).build());
ResourceStateMachine stateMachine = new ResourceStateMachine(initialState, new BeanTransformer());
HTTPHypermediaRIM rimHandler = mockRIMHandler(stateMachine);
HttpHeaders headers = mock(HttpHeaders.class);
Metadata metadata = mock(Metadata.class);
Collection<Link> unsortedLinks = stateMachine.injectLinks(rimHandler, createMockInteractionContext(initialState), new EntityResource<Object>(createTestNote(resourceEntityName)), headers, metadata);
List<Link> links = new ArrayList<Link>(unsortedLinks);
// sort the links so we have a predictable order for this test
Collections.sort(links, new Comparator<Link>() { | List<Link> function(String resourceEntityName) { String entityName = "Note"; ResourceState initialState = new ResourceState(entityName, "note", new ArrayList<Action>(), STR); initialState.setInitial(true); Map<String, String> uriLinkageMap = new HashMap<String, String>(); uriLinkageMap.put("id", STR); ResourceState noteEditState = new ResourceState(entityName, STR, new ArrayList<Action>(), "/edit"); initialState.addTransition(new Transition.Builder().target(noteEditState).uriParameters(uriLinkageMap).build()); ResourceStateMachine stateMachine = new ResourceStateMachine(initialState, new BeanTransformer()); HTTPHypermediaRIM rimHandler = mockRIMHandler(stateMachine); HttpHeaders headers = mock(HttpHeaders.class); Metadata metadata = mock(Metadata.class); Collection<Link> unsortedLinks = stateMachine.injectLinks(rimHandler, createMockInteractionContext(initialState), new EntityResource<Object>(createTestNote(resourceEntityName)), headers, metadata); List<Link> links = new ArrayList<Link>(unsortedLinks); Collections.sort(links, new Comparator<Link>() { | /**
* Creates a Resource State Machine for Note with one transition and Injects Links with the supplied resource entity
* name
*
* @param resourceEntityName
* @return List of sorted links
*/ | Creates a Resource State Machine for Note with one transition and Injects Links with the supplied resource entity name | createResourceStateMachineForNotes | {
"repo_name": "mjangid/IRIS",
"path": "interaction-core/src/test/java/com/temenos/interaction/core/hypermedia/TestResourceStateMachine.java",
"license": "agpl-3.0",
"size": 149598
} | [
"com.temenos.interaction.core.entity.Metadata",
"com.temenos.interaction.core.resource.EntityResource",
"com.temenos.interaction.core.rim.HTTPHypermediaRIM",
"java.util.ArrayList",
"java.util.Collection",
"java.util.Collections",
"java.util.Comparator",
"java.util.HashMap",
"java.util.List",
"java.util.Map",
"javax.ws.rs.core.HttpHeaders",
"org.mockito.Mockito"
] | import com.temenos.interaction.core.entity.Metadata; import com.temenos.interaction.core.resource.EntityResource; import com.temenos.interaction.core.rim.HTTPHypermediaRIM; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.core.HttpHeaders; import org.mockito.Mockito; | import com.temenos.interaction.core.entity.*; import com.temenos.interaction.core.resource.*; import com.temenos.interaction.core.rim.*; import java.util.*; import javax.ws.rs.core.*; import org.mockito.*; | [
"com.temenos.interaction",
"java.util",
"javax.ws",
"org.mockito"
] | com.temenos.interaction; java.util; javax.ws; org.mockito; | 1,395,112 |
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 57, value = "No deployment content with hash %s is available in the deployment content repository for deployment %s. Because this Host Controller is booting in ADMIN-ONLY mode, boot will be allowed to proceed to provide administrators an opportunity to correct this problem. If this Host Controller were not in ADMIN-ONLY mode this would be a fatal boot failure.")
void reportAdminOnlyMissingDeploymentContent(String contentHash, String deploymentName); | @LogMessage(level = Logger.Level.ERROR) @Message(id = 57, value = STR) void reportAdminOnlyMissingDeploymentContent(String contentHash, String deploymentName); | /**
* Logs an error message indicating the content for a configured deployment was unavailable at boot but boot
* was allowed to proceed because the HC is in admin-only mode.
*
* @param contentHash the content hash that could not be found.
* @param deploymentName the deployment name.
*/ | Logs an error message indicating the content for a configured deployment was unavailable at boot but boot was allowed to proceed because the HC is in admin-only mode | reportAdminOnlyMissingDeploymentContent | {
"repo_name": "darranl/wildfly-core",
"path": "server/src/main/java/org/jboss/as/server/logging/ServerLogger.java",
"license": "lgpl-2.1",
"size": 68179
} | [
"org.jboss.logging.Logger",
"org.jboss.logging.annotations.LogMessage",
"org.jboss.logging.annotations.Message"
] | import org.jboss.logging.Logger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; | import org.jboss.logging.*; import org.jboss.logging.annotations.*; | [
"org.jboss.logging"
] | org.jboss.logging; | 2,856,680 |
private boolean handleConnectionException(Throwable e)
{
ConnectionExceptionHandler handler = new ConnectionExceptionHandler();
int index = handler.handleConnectionException(e);
if (index < 0) return true;
log("Handle Exception:"+index);
context.getTaskBar().sessionExpired(index);
return index == ConnectionExceptionHandler.LOST_CONNECTION;
} | boolean function(Throwable e) { ConnectionExceptionHandler handler = new ConnectionExceptionHandler(); int index = handler.handleConnectionException(e); if (index < 0) return true; log(STR+index); context.getTaskBar().sessionExpired(index); return index == ConnectionExceptionHandler.LOST_CONNECTION; } | /**
* Handles only connection error. Returns <code>true</code> if it is not a
* connection error, <code>false</code> otherwise.
*
* @param e The exception to handle.
* @return See above.
*/ | Handles only connection error. Returns <code>true</code> if it is not a connection error, <code>false</code> otherwise | handleConnectionException | {
"repo_name": "stelfrich/openmicroscopy",
"path": "components/insight/SRC/org/openmicroscopy/shoola/env/rnd/RenderingControlProxy.java",
"license": "gpl-2.0",
"size": 64513
} | [
"org.openmicroscopy.shoola.env.data.ConnectionExceptionHandler"
] | import org.openmicroscopy.shoola.env.data.ConnectionExceptionHandler; | import org.openmicroscopy.shoola.env.data.*; | [
"org.openmicroscopy.shoola"
] | org.openmicroscopy.shoola; | 1,746,337 |
protected List<Method> getDtoMethods() {
return dtoMethods;
} | List<Method> function() { return dtoMethods; } | /**
* Returns public methods specified in DTO interface.
* <p/>
* <p>For compact DTO (see {@link org.eclipse.che.dto.shared.CompactJsonDto}) methods are ordered corresponding to {@link
* org.eclipse.che.dto.shared.SerializationIndex} annotation.
* <p/>
* <p>Gaps in index sequence are filled with {@code null}s.
*/ | Returns public methods specified in DTO interface. For compact DTO (see <code>org.eclipse.che.dto.shared.CompactJsonDto</code>) methods are ordered corresponding to <code>org.eclipse.che.dto.shared.SerializationIndex</code> annotation. Gaps in index sequence are filled with nulls | getDtoMethods | {
"repo_name": "kaloyan-raev/che",
"path": "core/che-core-api-dto/src/main/java/org/eclipse/che/dto/generator/DtoImpl.java",
"license": "epl-1.0",
"size": 16596
} | [
"java.lang.reflect.Method",
"java.util.List"
] | import java.lang.reflect.Method; import java.util.List; | import java.lang.reflect.*; import java.util.*; | [
"java.lang",
"java.util"
] | java.lang; java.util; | 1,982,565 |
@VisibleForTesting
static Map<byte[], BloomType> createFamilyBloomTypeMap(Configuration conf) {
Map<byte[], String> stringMap = createFamilyConfValueMap(conf,
BLOOM_TYPE_FAMILIES_CONF_KEY);
Map<byte[], BloomType> bloomTypeMap = new TreeMap<>(Bytes.BYTES_COMPARATOR);
for (Map.Entry<byte[], String> e : stringMap.entrySet()) {
BloomType bloomType = BloomType.valueOf(e.getValue());
bloomTypeMap.put(e.getKey(), bloomType);
}
return bloomTypeMap;
} | static Map<byte[], BloomType> createFamilyBloomTypeMap(Configuration conf) { Map<byte[], String> stringMap = createFamilyConfValueMap(conf, BLOOM_TYPE_FAMILIES_CONF_KEY); Map<byte[], BloomType> bloomTypeMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); for (Map.Entry<byte[], String> e : stringMap.entrySet()) { BloomType bloomType = BloomType.valueOf(e.getValue()); bloomTypeMap.put(e.getKey(), bloomType); } return bloomTypeMap; } | /**
* Runs inside the task to deserialize column family to bloom filter type
* map from the configuration.
*
* @param conf to read the serialized values from
* @return a map from column family to the the configured bloom filter type
*/ | Runs inside the task to deserialize column family to bloom filter type map from the configuration | createFamilyBloomTypeMap | {
"repo_name": "ultratendency/hbase",
"path": "hbase-mapreduce/src/main/java/org/apache/hadoop/hbase/mapreduce/HFileOutputFormat2.java",
"license": "apache-2.0",
"size": 42247
} | [
"java.util.Map",
"java.util.TreeMap",
"org.apache.hadoop.conf.Configuration",
"org.apache.hadoop.hbase.regionserver.BloomType",
"org.apache.hadoop.hbase.util.Bytes"
] | import java.util.Map; import java.util.TreeMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.regionserver.BloomType; import org.apache.hadoop.hbase.util.Bytes; | import java.util.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.hbase.regionserver.*; import org.apache.hadoop.hbase.util.*; | [
"java.util",
"org.apache.hadoop"
] | java.util; org.apache.hadoop; | 2,287,677 |
public void setLabeler(DateSlider.Labeler labeler, long time, int objwidth, int objheight) {
this.labeler = labeler;
currentTime = time;
objWidth = (int)(objwidth*getContext().getResources().getDisplayMetrics().density);
objHeight = (int)(objheight*getContext().getResources().getDisplayMetrics().density);
// TODO: make it not dependent on the display width but rather on the layout width
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int displayWidth = display.getWidth();
while (displayWidth>childrenWidth-0*objWidth && labeler!=null) {
LayoutParams lp = new LayoutParams(objWidth, objHeight);
if (childrenWidth==0) {
TimeView ttv = labeler.createView(getContext(),true);
ttv.setVals(labeler.getElem(currentTime));
addView((View)ttv,lp);
mCenterView = ttv;
childrenWidth += objWidth;
}
TimeView ttv = labeler.createView(getContext(),false);
ttv.setVals(labeler.add(((TimeView)getChildAt(getChildCount()-1)).getEndTime(),1));
addView((View)ttv,lp);
ttv = labeler.createView(getContext(),false);
ttv.setVals(labeler.add(((TimeView)getChildAt(0)).getEndTime(),-1));
addView((View)ttv,0,lp);
childrenWidth += objWidth+objWidth;
}
}
| void function(DateSlider.Labeler labeler, long time, int objwidth, int objheight) { this.labeler = labeler; currentTime = time; objWidth = (int)(objwidth*getContext().getResources().getDisplayMetrics().density); objHeight = (int)(objheight*getContext().getResources().getDisplayMetrics().density); Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int displayWidth = display.getWidth(); while (displayWidth>childrenWidth-0*objWidth && labeler!=null) { LayoutParams lp = new LayoutParams(objWidth, objHeight); if (childrenWidth==0) { TimeView ttv = labeler.createView(getContext(),true); ttv.setVals(labeler.getElem(currentTime)); addView((View)ttv,lp); mCenterView = ttv; childrenWidth += objWidth; } TimeView ttv = labeler.createView(getContext(),false); ttv.setVals(labeler.add(((TimeView)getChildAt(getChildCount()-1)).getEndTime(),1)); addView((View)ttv,lp); ttv = labeler.createView(getContext(),false); ttv.setVals(labeler.add(((TimeView)getChildAt(0)).getEndTime(),-1)); addView((View)ttv,0,lp); childrenWidth += objWidth+objWidth; } } | /**
* This method is called usually after a ScrollLayout is instanciated, it provides the scroller
* with all necessary information
*
* @param labeler the labeler instance which will provide the ScrollLayout with time
* unit information
* @param time the start time as timestamp representation
* @param objwidth the width of an TimeTextView in dps
* @param objheight the height of an TimeTextView in dps
*/ | This method is called usually after a ScrollLayout is instanciated, it provides the scroller with all necessary information | setLabeler | {
"repo_name": "OreOreDa/rsmonitor-heartrate",
"path": "src/com/googlecode/android/widgets/DateSlider/ScrollLayout.java",
"license": "gpl-2.0",
"size": 10170
} | [
"android.content.Context",
"android.view.Display",
"android.view.View",
"android.view.WindowManager"
] | import android.content.Context; import android.view.Display; import android.view.View; import android.view.WindowManager; | import android.content.*; import android.view.*; | [
"android.content",
"android.view"
] | android.content; android.view; | 1,365,217 |
public static NameComponent read(InputStream istream)
{
NameComponent value = new NameComponent();
value.id = istream.read_string();
value.kind = istream.read_string();
return value;
} | static NameComponent function(InputStream istream) { NameComponent value = new NameComponent(); value.id = istream.read_string(); value.kind = istream.read_string(); return value; } | /**
* Read the name component from the given CDR input stream.
*/ | Read the name component from the given CDR input stream | read | {
"repo_name": "shaotuanchen/sunflower_exp",
"path": "tools/source/gcc-4.2.4/libjava/classpath/org/omg/CosNaming/NameComponentHelper.java",
"license": "bsd-3-clause",
"size": 4153
} | [
"org.omg.CORBA"
] | import org.omg.CORBA; | import org.omg.*; | [
"org.omg"
] | org.omg; | 630,402 |
static String getPkName(List<Pair<Enum<?>, String>> defns)
{
for (Pair<Enum<?>, String> item : defns)
{
Enum<?> first = item.getFirst();
String colName = SchemaTable.getName(first);
if (SchemaTable.isPrimaryKey(first))
{
return colName;
}
}
return null;
} | static String getPkName(List<Pair<Enum<?>, String>> defns) { for (Pair<Enum<?>, String> item : defns) { Enum<?> first = item.getFirst(); String colName = SchemaTable.getName(first); if (SchemaTable.isPrimaryKey(first)) { return colName; } } return null; } | /**
* Returns the name of the primary key found in a table's column definitions
* @param defns Column definitions
* @return The primary key name or <tt>null</tt> if none is defined for the table.
*/ | Returns the name of the primary key found in a table's column definitions | getPkName | {
"repo_name": "DerekFangming/ProjectNingServer",
"path": "src/main/java/com/projectning/service/dao/SchemaTable.java",
"license": "mit",
"size": 5034
} | [
"com.projectning.util.Pair",
"java.util.List"
] | import com.projectning.util.Pair; import java.util.List; | import com.projectning.util.*; import java.util.*; | [
"com.projectning.util",
"java.util"
] | com.projectning.util; java.util; | 1,110,229 |
public String endMatch(){
_boucle = true;
List<WarAgentsAbstract> maListe = getAgents();
PanelControl.InitTeam();
_panelControl.setVisible(false);
SingletonAffichage.getInstance(mySelf()).releaseRefresh();
if(_victoryTeam.equals("#draw#")){
_resultDialog = new DrawDialog((Team)_listeTeam.values().toArray()[0], (Team)_listeTeam.values().toArray()[1]);
_resultDialog.setVisible(true);
}else{
_resultDialog = new VictoryDialog(_listeTeam.get(_victoryTeam));
_resultDialog.setVisible(true);
}
while(_boucle){
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
}
}
for(WarAgentsAbstract waa : maListe){
waa.die();
}
return "init";
}
| String function(){ _boucle = true; List<WarAgentsAbstract> maListe = getAgents(); PanelControl.InitTeam(); _panelControl.setVisible(false); SingletonAffichage.getInstance(mySelf()).releaseRefresh(); if(_victoryTeam.equals(STR)){ _resultDialog = new DrawDialog((Team)_listeTeam.values().toArray()[0], (Team)_listeTeam.values().toArray()[1]); _resultDialog.setVisible(true); }else{ _resultDialog = new VictoryDialog(_listeTeam.get(_victoryTeam)); _resultDialog.setVisible(true); } while(_boucle){ try { Thread.sleep(1); } catch (InterruptedException ex) { System.err.println(ex.getMessage()); } } for(WarAgentsAbstract waa : maListe){ waa.die(); } return "init"; } | /**
* Methode permettant la gestion de la fin du match.
*
* @return {@code String} - la prochaine action a effectuer,
* c'est a dire que l'on a la premiere methode appelee
*/ | Methode permettant la gestion de la fin du match | endMatch | {
"repo_name": "slvrgauthier/archives",
"path": "Fac/Master/IN207/Warbot/src/edu/turtlekit2/warbot/controller/Controller.java",
"license": "apache-2.0",
"size": 20983
} | [
"edu.turtlekit2.warbot.SingletonAffichage",
"edu.turtlekit2.warbot.WarAgentsAbstract",
"java.util.List"
] | import edu.turtlekit2.warbot.SingletonAffichage; import edu.turtlekit2.warbot.WarAgentsAbstract; import java.util.List; | import edu.turtlekit2.warbot.*; import java.util.*; | [
"edu.turtlekit2.warbot",
"java.util"
] | edu.turtlekit2.warbot; java.util; | 1,963,884 |
public static com.intellij.openapi.vcs.changes.ContentRevision createRevision(VirtualFile vcsRoot,
String path,
VcsRevisionNumber revisionNumber,
Project project,
boolean isDeleted, final boolean canBeDeleted) throws VcsException {
final FilePath file = createPath(vcsRoot, path, isDeleted, canBeDeleted);
if (revisionNumber != null) {
return new ContentRevision(file, (VcsRevisionNumber)revisionNumber, project);
}
else {
return CurrentContentRevision.create(file);
}
} | static com.intellij.openapi.vcs.changes.ContentRevision function(VirtualFile vcsRoot, String path, VcsRevisionNumber revisionNumber, Project project, boolean isDeleted, final boolean canBeDeleted) throws VcsException { final FilePath file = createPath(vcsRoot, path, isDeleted, canBeDeleted); if (revisionNumber != null) { return new ContentRevision(file, (VcsRevisionNumber)revisionNumber, project); } else { return CurrentContentRevision.create(file); } } | /**
* Create revision
*
* @param vcsRoot a vcs root for the repository
* @param path an path inside with possibly escape sequences
* @param revisionNumber a revision number, if null the current revision will be created
* @param project the context project
* @param isDeleted if true, the file is deleted
* @return a created revision
* @throws com.intellij.openapi.vcs.VcsException
* if there is a problem with creating revision
*/ | Create revision | createRevision | {
"repo_name": "sszym0n/CommunityCase",
"path": "src/org/community/intellij/plugins/communitycase/ContentRevision.java",
"license": "gpl-3.0",
"size": 6197
} | [
"com.intellij.openapi.project.Project",
"com.intellij.openapi.vcs.FilePath",
"com.intellij.openapi.vcs.VcsException",
"com.intellij.openapi.vcs.changes.CurrentContentRevision",
"com.intellij.openapi.vcs.history.VcsRevisionNumber",
"com.intellij.openapi.vfs.VirtualFile"
] | import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.CurrentContentRevision; import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.openapi.vfs.VirtualFile; | import com.intellij.openapi.project.*; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.history.*; import com.intellij.openapi.vfs.*; | [
"com.intellij.openapi"
] | com.intellij.openapi; | 1,025,010 |
public ConditionHLAPI getContainerConditionHLAPI() {
if (item.getContainerCondition() == null)
return null;
return new ConditionHLAPI(item.getContainerCondition());
} | ConditionHLAPI function() { if (item.getContainerCondition() == null) return null; return new ConditionHLAPI(item.getContainerCondition()); } | /**
* This accessor automatically encapsulate an element of the current object.
* WARNING : this creates a new object in memory.
*
* @return : null if the element is null
*/ | This accessor automatically encapsulate an element of the current object. WARNING : this creates a new object in memory | getContainerConditionHLAPI | {
"repo_name": "lhillah/pnmlframework",
"path": "pnmlFw-PT-HLPNG/src/fr/lip6/move/pnml/pthlpng/integers/hlapi/GreaterThanOrEqualHLAPI.java",
"license": "epl-1.0",
"size": 70100
} | [
"fr.lip6.move.pnml.pthlpng.hlcorestructure.hlapi.ConditionHLAPI"
] | import fr.lip6.move.pnml.pthlpng.hlcorestructure.hlapi.ConditionHLAPI; | import fr.lip6.move.pnml.pthlpng.hlcorestructure.hlapi.*; | [
"fr.lip6.move"
] | fr.lip6.move; | 128,292 |
public void deleteAccountContact(Integer accountId, Integer contactId) throws Exception
{
MozuClient client = com.mozu.api.clients.commerce.customer.accounts.CustomerContactClient.deleteAccountContactClient( accountId, contactId);
client.setContext(_apiContext);
client.executeRequest();
client.cleanupHttpConnection();
} | void function(Integer accountId, Integer contactId) throws Exception { MozuClient client = com.mozu.api.clients.commerce.customer.accounts.CustomerContactClient.deleteAccountContactClient( accountId, contactId); client.setContext(_apiContext); client.executeRequest(); client.cleanupHttpConnection(); } | /**
* Deletes a contact for the specified customer account.
* <p><pre><code>
* CustomerContact customercontact = new CustomerContact();
* customercontact.deleteAccountContact( accountId, contactId);
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param contactId Unique identifer of the customer account contact being updated.
* @return
*/ | Deletes a contact for the specified customer account. <code><code> CustomerContact customercontact = new CustomerContact(); customercontact.deleteAccountContact( accountId, contactId); </code></code> | deleteAccountContact | {
"repo_name": "sanjaymandadi/mozu-java",
"path": "mozu-java-core/src/main/java/com/mozu/api/resources/commerce/customer/accounts/CustomerContactResource.java",
"license": "mit",
"size": 11233
} | [
"com.mozu.api.MozuClient"
] | import com.mozu.api.MozuClient; | import com.mozu.api.*; | [
"com.mozu.api"
] | com.mozu.api; | 878,642 |
public void charactersRaw(String data) throws SAXException
{
write(data);
}
////////////////////////////////////////////////////////////////////
// Internal methods.
////////////////////////////////////////////////////////////////////
| void function(String data) throws SAXException { write(data); } | /**
* Write a raw string of character data, NO XML escaping!
* teo.sax extension.
*/ | Write a raw string of character data, NO XML escaping! teo.sax extension | charactersRaw | {
"repo_name": "forty3degrees/graphclasses",
"path": "K/p/src/teo/isgci/data/xml/XMLWriter.java",
"license": "gpl-3.0",
"size": 39040
} | [
"org.xml.sax.SAXException"
] | import org.xml.sax.SAXException; | import org.xml.sax.*; | [
"org.xml.sax"
] | org.xml.sax; | 1,254,754 |
private Object toSoyCompatibleObjects(Object obj) {
if (obj == null) {
return obj;
}
if (Primitives.isWrapperType(obj.getClass())
|| obj.getClass().isPrimitive()
|| obj instanceof String) {
return obj;
}
if (obj instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) obj;
Map<String, Object> newMap = new HashMap<>(map.size());
for (String key : map.keySet()) {
newMap.put(key, toSoyCompatibleObjects(map.get(key)));
}
return newMap;
}
if (obj instanceof Iterable<?>) {
List<Object> list = Lists.newArrayList();
for (Object subValue : ((Iterable<?>) obj)) {
list.add(toSoyCompatibleObjects(subValue));
}
return list;
}
if (obj.getClass().isArray()) {
return obj;
}
if (obj.getClass().isEnum()) {
return ((Enum) obj).name();
}
// At this point we must assume it's a POJO so map-it.
{
@SuppressWarnings("unchecked")
Map<String, Object> pojoMap = (Map<String, Object>) pojoToMap(obj);
Map<String, Object> newMap = new HashMap<>(pojoMap.size());
for (String key : pojoMap.keySet()) {
newMap.put(key, toSoyCompatibleObjects(pojoMap.get(key)));
}
return newMap;
}
} | Object function(Object obj) { if (obj == null) { return obj; } if (Primitives.isWrapperType(obj.getClass()) obj.getClass().isPrimitive() obj instanceof String) { return obj; } if (obj instanceof Map) { @SuppressWarnings(STR) Map<String, Object> map = (Map<String, Object>) obj; Map<String, Object> newMap = new HashMap<>(map.size()); for (String key : map.keySet()) { newMap.put(key, toSoyCompatibleObjects(map.get(key))); } return newMap; } if (obj instanceof Iterable<?>) { List<Object> list = Lists.newArrayList(); for (Object subValue : ((Iterable<?>) obj)) { list.add(toSoyCompatibleObjects(subValue)); } return list; } if (obj.getClass().isArray()) { return obj; } if (obj.getClass().isEnum()) { return ((Enum) obj).name(); } { @SuppressWarnings(STR) Map<String, Object> pojoMap = (Map<String, Object>) pojoToMap(obj); Map<String, Object> newMap = new HashMap<>(pojoMap.size()); for (String key : pojoMap.keySet()) { newMap.put(key, toSoyCompatibleObjects(pojoMap.get(key))); } return newMap; } } | /**
* Convert an object (or graph of objects) to types compatible with Soy (data able to be stored in SoyDataMap).
* This will convert:
* - POJOs to Maps
* - Iterables to Lists
* - all strings and primitives remain as is.
*
* @param obj The object to convert.
* @return The object converted (in applicable).
*/ | Convert an object (or graph of objects) to types compatible with Soy (data able to be stored in SoyDataMap). This will convert: - POJOs to Maps - Iterables to Lists - all strings and primitives remain as is | toSoyCompatibleObjects | {
"repo_name": "jivesoftware/upena",
"path": "upena-deployable/src/main/java/com/jivesoftware/os/upena/deployable/soy/SoyDataUtils.java",
"license": "apache-2.0",
"size": 4915
} | [
"com.google.common.collect.Lists",
"com.google.common.primitives.Primitives",
"java.util.HashMap",
"java.util.List",
"java.util.Map"
] | import com.google.common.collect.Lists; import com.google.common.primitives.Primitives; import java.util.HashMap; import java.util.List; import java.util.Map; | import com.google.common.collect.*; import com.google.common.primitives.*; import java.util.*; | [
"com.google.common",
"java.util"
] | com.google.common; java.util; | 2,417,347 |
public boolean removeUserInterceptor(String username, PacketInterceptor interceptor) {
boolean answer = false;
List<PacketInterceptor> userInterceptors = usersInterceptors.get(username);
if (userInterceptors != null) {
answer = userInterceptors.remove(interceptor);
// Remove the entry for this username if the list is now empty
if (userInterceptors.isEmpty()) {
usersInterceptors.remove(username);
}
}
return answer;
} | boolean function(String username, PacketInterceptor interceptor) { boolean answer = false; List<PacketInterceptor> userInterceptors = usersInterceptors.get(username); if (userInterceptors != null) { answer = userInterceptors.remove(interceptor); if (userInterceptors.isEmpty()) { usersInterceptors.remove(username); } } return answer; } | /**
* Removes the interceptor from the list of interceptors that are related to a specific
* username.
*
* @param username the name of the user.
* @param interceptor the interceptor to remove.
* @return true if the item was present in the list
*/ | Removes the interceptor from the list of interceptors that are related to a specific username | removeUserInterceptor | {
"repo_name": "saveendhiman/OpenfirePluginSample",
"path": "openfiresource/src/org/jivesoftware/openfire/interceptor/InterceptorManager.java",
"license": "apache-2.0",
"size": 11727
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,873,057 |
public void setEnabled(boolean enabled) {
View view = (View) targetObject;
view.setEnabled(enabled);
} | void function(boolean enabled) { View view = (View) targetObject; view.setEnabled(enabled); } | /**
* Set the enabled state of this view.
* @param enabled
* True if this view is enabled. False otherwise.
*/ | Set the enabled state of this view | setEnabled | {
"repo_name": "debdattabasu/RoboMVVM",
"path": "library/src/main/java/org/dbasu/robomvvm/componentadapter/view/ViewAdapter.java",
"license": "bsd-3-clause",
"size": 4823
} | [
"android.view.View"
] | import android.view.View; | import android.view.*; | [
"android.view"
] | android.view; | 1,170,697 |
private double getBinWidth(int series) {
Map map = (Map) this.list.get(series);
return ((Double) map.get("bin width")).doubleValue();
}
| double function(int series) { Map map = (Map) this.list.get(series); return ((Double) map.get(STR)).doubleValue(); } | /**
* Returns the bin width for a series.
*
* @param series the series index (zero based).
*
* @return The bin width.
*/ | Returns the bin width for a series | getBinWidth | {
"repo_name": "Mr-Steve/LTSpice_Library_Manager",
"path": "libs/jfreechart-1.0.16/source/org/jfree/data/statistics/HistogramDataset.java",
"license": "gpl-2.0",
"size": 17656
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 258,083 |
ActionFuture<GetMappingsResponse> getMappings(GetMappingsRequest request); | ActionFuture<GetMappingsResponse> getMappings(GetMappingsRequest request); | /**
* Get the complete mappings of one or more types
*/ | Get the complete mappings of one or more types | getMappings | {
"repo_name": "gfyoung/elasticsearch",
"path": "server/src/main/java/org/elasticsearch/client/IndicesAdminClient.java",
"license": "apache-2.0",
"size": 31239
} | [
"org.elasticsearch.action.ActionFuture",
"org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest",
"org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse"
] | import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse; | import org.elasticsearch.action.*; import org.elasticsearch.action.admin.indices.mapping.get.*; | [
"org.elasticsearch.action"
] | org.elasticsearch.action; | 1,582,386 |
private static int uariminLt(double value, double[] bv, int[] bvi, BinaryOperator bOp) {
int ixMin = 1;
if(value < bv[0] || value >= bv[bv.length-1])
return ixMin;
int ix = Arrays.binarySearch(bv, value);
if (ix < 0)
ix = Math.abs(ix)-2;
ixMin = bvi[ix]+1;
return ixMin;
} | static int function(double value, double[] bv, int[] bvi, BinaryOperator bOp) { int ixMin = 1; if(value < bv[0] value >= bv[bv.length-1]) return ixMin; int ix = Arrays.binarySearch(bv, value); if (ix < 0) ix = Math.abs(ix)-2; ixMin = bvi[ix]+1; return ixMin; } | /**
* Find out rowIndexMin for LessThan operator.
*
* @param value ?
* @param bv ?
* @param bOp binary operator
*/ | Find out rowIndexMin for LessThan operator | uariminLt | {
"repo_name": "nakul02/incubator-systemml",
"path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixOuterAgg.java",
"license": "apache-2.0",
"size": 42804
} | [
"java.util.Arrays",
"org.apache.sysml.runtime.matrix.operators.BinaryOperator"
] | import java.util.Arrays; import org.apache.sysml.runtime.matrix.operators.BinaryOperator; | import java.util.*; import org.apache.sysml.runtime.matrix.operators.*; | [
"java.util",
"org.apache.sysml"
] | java.util; org.apache.sysml; | 2,406,217 |
static void createHFile(
Configuration conf,
FileSystem fs, Path path,
byte[] family, byte[] qualifier,
byte[] startKey, byte[] endKey, int numRows) throws IOException
{
HFile.Writer writer = HFile.getWriterFactory(conf, new CacheConfig(conf))
.withPath(fs, path)
.withBlockSize(BLOCKSIZE)
.withCompression(COMPRESSION)
.withComparator(KeyValue.KEY_COMPARATOR)
.create();
long now = System.currentTimeMillis();
try {
// subtract 2 since iterateOnSplits doesn't include boundary keys
for (byte[] key : Bytes.iterateOnSplits(startKey, endKey, numRows-2)) {
KeyValue kv = new KeyValue(key, family, qualifier, now, key);
writer.append(kv);
}
} finally {
writer.close();
}
} | static void createHFile( Configuration conf, FileSystem fs, Path path, byte[] family, byte[] qualifier, byte[] startKey, byte[] endKey, int numRows) throws IOException { HFile.Writer writer = HFile.getWriterFactory(conf, new CacheConfig(conf)) .withPath(fs, path) .withBlockSize(BLOCKSIZE) .withCompression(COMPRESSION) .withComparator(KeyValue.KEY_COMPARATOR) .create(); long now = System.currentTimeMillis(); try { for (byte[] key : Bytes.iterateOnSplits(startKey, endKey, numRows-2)) { KeyValue kv = new KeyValue(key, family, qualifier, now, key); writer.append(kv); } } finally { writer.close(); } } | /**
* Create an HFile with the given number of rows between a given
* start key and end key.
* TODO put me in an HFileTestUtil or something?
*/ | Create an HFile with the given number of rows between a given start key and end key. TODO put me in an HFileTestUtil or something | createHFile | {
"repo_name": "axfcampos/hbase-0.94.19",
"path": "src/test/java/org/apache/hadoop/hbase/mapreduce/TestLoadIncrementalHFiles.java",
"license": "apache-2.0",
"size": 13895
} | [
"java.io.IOException",
"org.apache.hadoop.conf.Configuration",
"org.apache.hadoop.fs.FileSystem",
"org.apache.hadoop.fs.Path",
"org.apache.hadoop.hbase.KeyValue",
"org.apache.hadoop.hbase.io.hfile.CacheConfig",
"org.apache.hadoop.hbase.io.hfile.HFile",
"org.apache.hadoop.hbase.util.Bytes"
] | import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.io.hfile.CacheConfig; import org.apache.hadoop.hbase.io.hfile.HFile; import org.apache.hadoop.hbase.util.Bytes; | import java.io.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.io.hfile.*; import org.apache.hadoop.hbase.util.*; | [
"java.io",
"org.apache.hadoop"
] | java.io; org.apache.hadoop; | 2,634,208 |
@Test
public void testWarn() {
Logger mock = Mockito.mock(Logger.class);
FixedLogger logger = new FixedLogger(mock, VTNLogLevel.WARN);
assertSame(mock, logger.getLogger());
// isEnabled()
Mockito.when(mock.isWarnEnabled()).thenReturn(true).thenReturn(false);
assertEquals(true, logger.isEnabled());
assertEquals(false, logger.isEnabled());
Mockito.verify(mock, Mockito.times(2)).isWarnEnabled();
Mockito.reset(mock);
// log(Throwable, String, Object[])
Mockito.when(mock.isWarnEnabled()).thenReturn(true).thenReturn(true).
thenReturn(false).thenReturn(false).thenReturn(true);
IllegalArgumentException iae = new IllegalArgumentException();
String msg = "Illegal argument";
logger.log(iae, msg);
Mockito.verify(mock).isWarnEnabled();
Mockito.verify(mock).warn(msg, iae);
logger.log(iae, "Illegal argument: i=%d, str=%s", 10, "test message");
String formatted = "Illegal argument: i=10, str=test message";
Mockito.verify(mock, Mockito.times(2)).isWarnEnabled();
Mockito.verify(mock).warn(msg, iae);
Mockito.verify(mock).warn(formatted, iae);
logger.log(iae, msg);
Mockito.verify(mock, Mockito.times(3)).isWarnEnabled();
Mockito.verify(mock).warn(msg, iae);
Mockito.verify(mock).warn(formatted, iae);
logger.log(iae, "This should not be logger: %d", 12345);
Mockito.verify(mock, Mockito.times(4)).isWarnEnabled();
Mockito.verify(mock).warn(msg, iae);
Mockito.verify(mock).warn(formatted, iae);
String msg1 = "Another message";
logger.log((Throwable)null, msg1, (Object[])null);
Mockito.verify(mock, Mockito.times(5)).isWarnEnabled();
Mockito.verify(mock).warn(msg, iae);
Mockito.verify(mock).warn(formatted, iae);
Mockito.verify(mock).warn(msg1);
Mockito.reset(mock);
// log(String)
msg = "This is a log message.";
logger.log(msg);
Mockito.verify(mock).warn(msg);
// log(String, Throwable)
Exception e = new Exception();
logger.log(msg, e);
Mockito.verify(mock).warn(msg);
Mockito.verify(mock).warn(msg, e);
// log(String, Object ...)
String format = "This a log message: {}, {}, {}";
logger.log(format, 123, "test", 99999999L);
Mockito.verify(mock).warn(msg);
Mockito.verify(mock).warn(msg, e);
Mockito.verify(mock).warn(format, 123, "test", 99999999L);
} | void function() { Logger mock = Mockito.mock(Logger.class); FixedLogger logger = new FixedLogger(mock, VTNLogLevel.WARN); assertSame(mock, logger.getLogger()); Mockito.when(mock.isWarnEnabled()).thenReturn(true).thenReturn(false); assertEquals(true, logger.isEnabled()); assertEquals(false, logger.isEnabled()); Mockito.verify(mock, Mockito.times(2)).isWarnEnabled(); Mockito.reset(mock); Mockito.when(mock.isWarnEnabled()).thenReturn(true).thenReturn(true). thenReturn(false).thenReturn(false).thenReturn(true); IllegalArgumentException iae = new IllegalArgumentException(); String msg = STR; logger.log(iae, msg); Mockito.verify(mock).isWarnEnabled(); Mockito.verify(mock).warn(msg, iae); logger.log(iae, STR, 10, STR); String formatted = STR; Mockito.verify(mock, Mockito.times(2)).isWarnEnabled(); Mockito.verify(mock).warn(msg, iae); Mockito.verify(mock).warn(formatted, iae); logger.log(iae, msg); Mockito.verify(mock, Mockito.times(3)).isWarnEnabled(); Mockito.verify(mock).warn(msg, iae); Mockito.verify(mock).warn(formatted, iae); logger.log(iae, STR, 12345); Mockito.verify(mock, Mockito.times(4)).isWarnEnabled(); Mockito.verify(mock).warn(msg, iae); Mockito.verify(mock).warn(formatted, iae); String msg1 = STR; logger.log((Throwable)null, msg1, (Object[])null); Mockito.verify(mock, Mockito.times(5)).isWarnEnabled(); Mockito.verify(mock).warn(msg, iae); Mockito.verify(mock).warn(formatted, iae); Mockito.verify(mock).warn(msg1); Mockito.reset(mock); msg = STR; logger.log(msg); Mockito.verify(mock).warn(msg); Exception e = new Exception(); logger.log(msg, e); Mockito.verify(mock).warn(msg); Mockito.verify(mock).warn(msg, e); String format = STR; logger.log(format, 123, "test", 99999999L); Mockito.verify(mock).warn(msg); Mockito.verify(mock).warn(msg, e); Mockito.verify(mock).warn(format, 123, "test", 99999999L); } | /**
* Test case for WARN level.
*/ | Test case for WARN level | testWarn | {
"repo_name": "opendaylight/vtn",
"path": "manager/implementation/src/test/java/org/opendaylight/vtn/manager/internal/util/log/FixedLoggerTest.java",
"license": "epl-1.0",
"size": 13882
} | [
"org.mockito.Mockito",
"org.slf4j.Logger"
] | import org.mockito.Mockito; import org.slf4j.Logger; | import org.mockito.*; import org.slf4j.*; | [
"org.mockito",
"org.slf4j"
] | org.mockito; org.slf4j; | 453,958 |
@BeforeClass
public static void init() {
SearchModule searchModule = new SearchModule(Settings.EMPTY, false, emptyList());
namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables());
xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents());
} | static void function() { SearchModule searchModule = new SearchModule(Settings.EMPTY, false, emptyList()); namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables()); xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents()); } | /**
* setup for the whole base test class
*/ | setup for the whole base test class | init | {
"repo_name": "gfyoung/elasticsearch",
"path": "server/src/test/java/org/elasticsearch/search/suggest/AbstractSuggestionBuilderTestCase.java",
"license": "apache-2.0",
"size": 13291
} | [
"java.util.Collections",
"org.elasticsearch.common.io.stream.NamedWriteableRegistry",
"org.elasticsearch.common.settings.Settings",
"org.elasticsearch.common.xcontent.NamedXContentRegistry",
"org.elasticsearch.search.SearchModule"
] | import java.util.Collections; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.search.SearchModule; | import java.util.*; import org.elasticsearch.common.io.stream.*; import org.elasticsearch.common.settings.*; import org.elasticsearch.common.xcontent.*; import org.elasticsearch.search.*; | [
"java.util",
"org.elasticsearch.common",
"org.elasticsearch.search"
] | java.util; org.elasticsearch.common; org.elasticsearch.search; | 905,000 |
@Override
public void messageLogged(final BuildEvent event) {
// Not significant for the class loader.
} | void function(final BuildEvent event) { } | /**
* Empty implementation to satisfy the BuildListener interface.
*
* @param event the messageLogged event
*/ | Empty implementation to satisfy the BuildListener interface | messageLogged | {
"repo_name": "pjanouse/jenkins",
"path": "core/src/main/java/jenkins/util/AntClassLoader.java",
"license": "mit",
"size": 60541
} | [
"org.apache.tools.ant.BuildEvent"
] | import org.apache.tools.ant.BuildEvent; | import org.apache.tools.ant.*; | [
"org.apache.tools"
] | org.apache.tools; | 317,052 |
private void retransmitSegment(Segment segment)
throws IOException
{
if (_profile.maxRetrans() > 0) {
segment.setRetxCounter(segment.getRetxCounter()+1);
}
if (_profile.maxRetrans() != 0 && segment.getRetxCounter() > _profile.maxRetrans()) {
connectionFailure();
return;
}
sendSegment(segment);
if (segment instanceof DATSegment) {
synchronized (_listeners) {
Iterator<ReliableSocketListener> it = _listeners.iterator();
while (it.hasNext()) {
ReliableSocketListener l = (ReliableSocketListener) it.next();
l.packetRetransmitted();
}
}
}
} | void function(Segment segment) throws IOException { if (_profile.maxRetrans() > 0) { segment.setRetxCounter(segment.getRetxCounter()+1); } if (_profile.maxRetrans() != 0 && segment.getRetxCounter() > _profile.maxRetrans()) { connectionFailure(); return; } sendSegment(segment); if (segment instanceof DATSegment) { synchronized (_listeners) { Iterator<ReliableSocketListener> it = _listeners.iterator(); while (it.hasNext()) { ReliableSocketListener l = (ReliableSocketListener) it.next(); l.packetRetransmitted(); } } } } | /**
* Sends a segment and increments its retransmission counter.
*
* @param segment the segment to be retransmitted.
* @throws IOException if an I/O error occurs in the
* underlying UDP socket.
*/ | Sends a segment and increments its retransmission counter | retransmitSegment | {
"repo_name": "CiNC0/Cartier",
"path": "cartier-rudp/src/main/java/xyz/vopen/cartier/net/rudp/ReliableSocket.java",
"license": "apache-2.0",
"size": 67440
} | [
"java.io.IOException",
"java.util.Iterator",
"xyz.vopen.cartier.net.rudp.impl.DATSegment",
"xyz.vopen.cartier.net.rudp.impl.Segment"
] | import java.io.IOException; import java.util.Iterator; import xyz.vopen.cartier.net.rudp.impl.DATSegment; import xyz.vopen.cartier.net.rudp.impl.Segment; | import java.io.*; import java.util.*; import xyz.vopen.cartier.net.rudp.impl.*; | [
"java.io",
"java.util",
"xyz.vopen.cartier"
] | java.io; java.util; xyz.vopen.cartier; | 2,113,138 |
@Override
public EndPoint buildEndPoint(final String fullyQualifiedEndPoint)
{
EndPoint endPoint = null;
try
{
endPoint = new EndPointImpl(fullyQualifiedEndPoint);
}
catch (final IllegalArgumentException e)
{
logger.warn(e, e);
}
return endPoint;
} | EndPoint function(final String fullyQualifiedEndPoint) { EndPoint endPoint = null; try { endPoint = new EndPointImpl(fullyQualifiedEndPoint); } catch (final IllegalArgumentException e) { logger.warn(e, e); } return endPoint; } | /**
* Builds an end point from a fully qualified end point name. If the
* endpoint name doesn't have a tech then it is considered invalid and null
* is returned.
*/ | Builds an end point from a fully qualified end point name. If the endpoint name doesn't have a tech then it is considered invalid and null is returned | buildEndPoint | {
"repo_name": "asterisk-java/asterisk-java",
"path": "src/main/java/org/asteriskjava/pbx/internal/core/AsteriskPBX.java",
"license": "apache-2.0",
"size": 33750
} | [
"org.asteriskjava.pbx.EndPoint"
] | import org.asteriskjava.pbx.EndPoint; | import org.asteriskjava.pbx.*; | [
"org.asteriskjava.pbx"
] | org.asteriskjava.pbx; | 628,934 |
private void waitForBuildToFinish(IProject project) throws CoreException {
// Wait for build to complete.
IJobManager jobManager = Job.getJobManager();
try {
jobManager.join(ResourcesPlugin.FAMILY_MANUAL_BUILD, null);
jobManager.join(ResourcesPlugin.FAMILY_AUTO_BUILD, null);
if (!prebuilderOnly) {
while(ResourcesPlugin.getWorkspace().isTreeLocked()) {
PlatformUI.getWorkbench().getDisplay().readAndDispatch();
}
}
project.refreshLocal(IProject.DEPTH_INFINITE, null);
} catch (OperationCanceledException e) {
} catch (InterruptedException e) {
}
}
| void function(IProject project) throws CoreException { IJobManager jobManager = Job.getJobManager(); try { jobManager.join(ResourcesPlugin.FAMILY_MANUAL_BUILD, null); jobManager.join(ResourcesPlugin.FAMILY_AUTO_BUILD, null); if (!prebuilderOnly) { while(ResourcesPlugin.getWorkspace().isTreeLocked()) { PlatformUI.getWorkbench().getDisplay().readAndDispatch(); } } project.refreshLocal(IProject.DEPTH_INFINITE, null); } catch (OperationCanceledException e) { } catch (InterruptedException e) { } } | /**
* Wait for the build complete.
* @throws CoreException
*/ | Wait for the build complete | waitForBuildToFinish | {
"repo_name": "john-tornblom/bridgepoint",
"path": "src/org.xtuml.bp.cli/src/org/xtuml/bp/cli/BuildWorkbenchAdvisor.java",
"license": "apache-2.0",
"size": 10438
} | [
"org.eclipse.core.resources.IProject",
"org.eclipse.core.resources.ResourcesPlugin",
"org.eclipse.core.runtime.CoreException",
"org.eclipse.core.runtime.OperationCanceledException",
"org.eclipse.core.runtime.jobs.IJobManager",
"org.eclipse.core.runtime.jobs.Job",
"org.eclipse.ui.PlatformUI"
] | import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.jobs.IJobManager; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.PlatformUI; | import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.*; import org.eclipse.ui.*; | [
"org.eclipse.core",
"org.eclipse.ui"
] | org.eclipse.core; org.eclipse.ui; | 1,197,144 |
long testHighlighting(boolean checkWarnings,
boolean checkInfos,
boolean checkWeakWarnings,
@TestDataFile @NonNls @NotNull String... filePaths); | long testHighlighting(boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings, @TestDataFile @NonNls @NotNull String... filePaths); | /**
* Runs highlighting test for the given files.
* Checks for {@link #ERROR_MARKER} markers by default.
* <p/>
* Double quotes in "descr" attribute of markers must be escaped by either one or two backslashes
* (see {@link ExpectedHighlightingData#extractExpectedHighlightsSet(Document)}).
*
* @param checkWarnings enables {@link #WARNING_MARKER} support.
* @param checkInfos enables {@link #INFO_MARKER} support.
* @param checkWeakWarnings enables {@link #INFORMATION_MARKER} support.
* @param filePaths the first file is tested only; the others are just copied along the first.
* @return highlighting duration in milliseconds.
*/ | Runs highlighting test for the given files. Checks for <code>#ERROR_MARKER</code> markers by default. Double quotes in "descr" attribute of markers must be escaped by either one or two backslashes (see <code>ExpectedHighlightingData#extractExpectedHighlightsSet(Document)</code>) | testHighlighting | {
"repo_name": "supersven/intellij-community",
"path": "platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestFixture.java",
"license": "apache-2.0",
"size": 22637
} | [
"com.intellij.testFramework.TestDataFile",
"org.jetbrains.annotations.NonNls",
"org.jetbrains.annotations.NotNull"
] | import com.intellij.testFramework.TestDataFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; | import com.intellij.*; import org.jetbrains.annotations.*; | [
"com.intellij",
"org.jetbrains.annotations"
] | com.intellij; org.jetbrains.annotations; | 1,448,732 |
public void addProfile(Profile profile)
{ String id = profile.getId();
ids.add(id);
PredefinedColor color = profile.getSpriteColor();
colors.add(color);
int controlsIndex = 0;
controls.add(controlsIndex);
String hero[] = {profile.getSpritePack(),profile.getSpriteFolder()};
heroes.add(hero);
}
| void function(Profile profile) { String id = profile.getId(); ids.add(id); PredefinedColor color = profile.getSpriteColor(); colors.add(color); int controlsIndex = 0; controls.add(controlsIndex); String hero[] = {profile.getSpritePack(),profile.getSpriteFolder()}; heroes.add(hero); } | /**
* for the network mode
* @param profile the profile to be added
*/ | for the network mode | addProfile | {
"repo_name": "vlabatut/totalboumboum",
"path": "src/org/totalboumboum/configuration/profiles/ProfilesSelection.java",
"license": "gpl-2.0",
"size": 4755
} | [
"org.totalboumboum.game.profile.Profile",
"org.totalboumboum.tools.images.PredefinedColor"
] | import org.totalboumboum.game.profile.Profile; import org.totalboumboum.tools.images.PredefinedColor; | import org.totalboumboum.game.profile.*; import org.totalboumboum.tools.images.*; | [
"org.totalboumboum.game",
"org.totalboumboum.tools"
] | org.totalboumboum.game; org.totalboumboum.tools; | 443,563 |
@NotNull
@ObjectiveCName("getGroupTypingWithGid:")
public ValueModel<int[]> getGroupTyping(int gid) {
return modules.getTypingModule().getGroupTyping(gid).getActive();
} | @ObjectiveCName(STR) ValueModel<int[]> function(int gid) { return modules.getTypingModule().getGroupTyping(gid).getActive(); } | /**
* Get group chat ViewModel
*
* @param gid chat's Group Id
* @return ValueModel of int[] for typing state
*/ | Get group chat ViewModel | getGroupTyping | {
"repo_name": "EaglesoftZJ/actor-platform",
"path": "actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java",
"license": "agpl-3.0",
"size": 86315
} | [
"com.google.j2objc.annotations.ObjectiveCName",
"im.actor.runtime.mvvm.ValueModel"
] | import com.google.j2objc.annotations.ObjectiveCName; import im.actor.runtime.mvvm.ValueModel; | import com.google.j2objc.annotations.*; import im.actor.runtime.mvvm.*; | [
"com.google.j2objc",
"im.actor.runtime"
] | com.google.j2objc; im.actor.runtime; | 1,247,246 |
@Test
public void whenPopStringThenGetFirstObjectAndDel() {
QueueList<String> list = new QueueList<>();
list.push("first");
list.push("second");
list.push("third");
String result = list.pop();
assertThat(result, is("first"));
result = list.getLinkedArray().get(0);
assertThat(result, is("second"));
result = list.getLinkedArray().get(1);
assertThat(result, is("third"));
} | void function() { QueueList<String> list = new QueueList<>(); list.push("first"); list.push(STR); list.push("third"); String result = list.pop(); assertThat(result, is("first")); result = list.getLinkedArray().get(0); assertThat(result, is(STR)); result = list.getLinkedArray().get(1); assertThat(result, is("third")); } | /**
* test method pop <String>.
*/ | test method pop | whenPopStringThenGetFirstObjectAndDel | {
"repo_name": "rvkhaustov/rkhaustov",
"path": "chapter_005/src/test/java/ru/rkhaustov/list/QueueListTest.java",
"license": "apache-2.0",
"size": 1148
} | [
"org.hamcrest.core.Is",
"org.junit.Assert"
] | import org.hamcrest.core.Is; import org.junit.Assert; | import org.hamcrest.core.*; import org.junit.*; | [
"org.hamcrest.core",
"org.junit"
] | org.hamcrest.core; org.junit; | 2,095,105 |
private static String trimLeadingCharacter(String str, char leadingCharacter) {
if (StringUtils.isEmpty(str)) {
return str;
}
StringBuffer buf = new StringBuffer(str);
while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) {
buf.deleteCharAt(0);
}
return buf.toString();
} | static String function(String str, char leadingCharacter) { if (StringUtils.isEmpty(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) { buf.deleteCharAt(0); } return buf.toString(); } | /**
* Trim all occurences of the supplied leading character from the given String.
*
* @param str the String to check
* @param leadingCharacter the leading character to be trimmed
* @return the trimmed String
*/ | Trim all occurences of the supplied leading character from the given String | trimLeadingCharacter | {
"repo_name": "clstoulouse/motu",
"path": "motu-library-converter/src/main/java/fr/cls/atoll/motu/library/converter/jaxb/LocaleAdapter.java",
"license": "lgpl-3.0",
"size": 5784
} | [
"org.apache.commons.lang3.StringUtils"
] | import org.apache.commons.lang3.StringUtils; | import org.apache.commons.lang3.*; | [
"org.apache.commons"
] | org.apache.commons; | 2,143,115 |
@Override
public Color valueToColor(double value) {
Range r = getRange();
if (value < r.getMin()) {
return valueToColor(r.getMin());
}
if (value > r.getMax()) {
return valueToColor(r.getMax());
}
double fraction = getRange().percent(value);
int i = (int) (fraction * this.colors.length);
if(i==255)
i--;
if (this.colors[i] == null) {
float[] lrgba = this.lowColor.getRGBComponents(null);
float[] hrgba = this.highColor.getRGBComponents(null);
float p = (float) fraction;
this.colors[i] = new Color(lrgba[0] * (1 - p) + hrgba[0] * p,
lrgba[1] * (1 - p) + hrgba[1] * p,
lrgba[2] * (1 - p) + hrgba[2] * p,
lrgba[3] * (1 - p) + hrgba[3] * p);
}
return this.colors[i];
} | Color function(double value) { Range r = getRange(); if (value < r.getMin()) { return valueToColor(r.getMin()); } if (value > r.getMax()) { return valueToColor(r.getMax()); } double fraction = getRange().percent(value); int i = (int) (fraction * this.colors.length); if(i==255) i--; if (this.colors[i] == null) { float[] lrgba = this.lowColor.getRGBComponents(null); float[] hrgba = this.highColor.getRGBComponents(null); float p = (float) fraction; this.colors[i] = new Color(lrgba[0] * (1 - p) + hrgba[0] * p, lrgba[1] * (1 - p) + hrgba[1] * p, lrgba[2] * (1 - p) + hrgba[2] * p, lrgba[3] * (1 - p) + hrgba[3] * p); } return this.colors[i]; } | /**
* Returns the color corresponding to the specified data value. If this
*
* @param value the data value.
*
* @return The color (never {@code null}).
*/ | Returns the color corresponding to the specified data value. If this | valueToColor | {
"repo_name": "musaeed/Prism-gsoc16",
"path": "prism-trunk/prism/src/userinterface/graph/GradientColorScale.java",
"license": "gpl-2.0",
"size": 5106
} | [
"com.orsoncharts.Range",
"java.awt.Color"
] | import com.orsoncharts.Range; import java.awt.Color; | import com.orsoncharts.*; import java.awt.*; | [
"com.orsoncharts",
"java.awt"
] | com.orsoncharts; java.awt; | 2,349,468 |
public Builder addConnections(int numConnections, TransportRequestOptions.Type... types) {
if (types == null || types.length == 0) {
throw new IllegalArgumentException("types must not be null");
}
for (TransportRequestOptions.Type type : types) {
if (addedTypes.contains(type)) {
throw new IllegalArgumentException("type [" + type + "] is already registered");
}
}
addedTypes.addAll(Arrays.asList(types));
handles.add(new ConnectionTypeHandle(this.numConnections, numConnections, EnumSet.copyOf(Arrays.asList(types))));
this.numConnections += numConnections;
return this;
} | Builder function(int numConnections, TransportRequestOptions.Type... types) { if (types == null types.length == 0) { throw new IllegalArgumentException(STR); } for (TransportRequestOptions.Type type : types) { if (addedTypes.contains(type)) { throw new IllegalArgumentException(STR + type + STR); } } addedTypes.addAll(Arrays.asList(types)); handles.add(new ConnectionTypeHandle(this.numConnections, numConnections, EnumSet.copyOf(Arrays.asList(types)))); this.numConnections += numConnections; return this; } | /**
* Adds a number of connections for one or more types. Each type can only be added once.
* @param numConnections the number of connections to use in the pool for the given connection types
* @param types a set of types that should share the given number of connections
*/ | Adds a number of connections for one or more types. Each type can only be added once | addConnections | {
"repo_name": "EvilMcJerkface/crate",
"path": "server/src/main/java/org/elasticsearch/transport/ConnectionProfile.java",
"license": "apache-2.0",
"size": 14669
} | [
"java.util.Arrays",
"java.util.EnumSet"
] | import java.util.Arrays; import java.util.EnumSet; | import java.util.*; | [
"java.util"
] | java.util; | 836,172 |
interface WithEndOfLifeDate {
WithCreate withEndOfLifeDate(OffsetDateTime endOfLifeDate);
} | interface WithEndOfLifeDate { WithCreate withEndOfLifeDate(OffsetDateTime endOfLifeDate); } | /**
* Specifies end of life date of the image.
*
* @param endOfLifeDate the end of life of the gallery image
* @return the next definition stage
*/ | Specifies end of life date of the image | withEndOfLifeDate | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/resourcemanagerhybrid/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/GalleryImage.java",
"license": "mit",
"size": 23389
} | [
"java.time.OffsetDateTime"
] | import java.time.OffsetDateTime; | import java.time.*; | [
"java.time"
] | java.time; | 141,887 |
private void processSQL() throws SQLException {
Statement statement = curConn.createStatement();
// Really don't know whether to take the network latency hit here
// in order to check autoCommit in order to set
// possiblyUncommitteds more accurately.
// I'm going with "NO" for now, since autoCommit will usually be off.
// If we do ever check autocommit, we have to keep track of the
// autocommit state when every SQL statement is run, since I may
// be able to have uncommitted DML, turn autocommit on, then run
// other DDL with autocommit on. As a result, I could be running
// SQL commands with autotommit on but still have uncommitted mods.
possiblyUncommitteds.set(true);
statement.execute(plMode ? dereference(curCommand, true)
: curCommand);
displayResultSet(statement, statement.getResultSet(), null, null);
} | void function() throws SQLException { Statement statement = curConn.createStatement(); possiblyUncommitteds.set(true); statement.execute(plMode ? dereference(curCommand, true) : curCommand); displayResultSet(statement, statement.getResultSet(), null, null); } | /**
* Process the current command as an SQL Statement
*/ | Process the current command as an SQL Statement | processSQL | {
"repo_name": "simeshev/parabuild-ci",
"path": "3rdparty/hsqldb1733/src/org/hsqldb/util/SqlFile.java",
"license": "lgpl-3.0",
"size": 92903
} | [
"java.sql.SQLException",
"java.sql.Statement"
] | import java.sql.SQLException; import java.sql.Statement; | import java.sql.*; | [
"java.sql"
] | java.sql; | 450,514 |
@WebMethod(operationName = "StadiumInfo")
@WebResult(name = "StadiumInfoResult", targetNamespace = "http://footballpool.dataaccess.eu")
@RequestWrapper(localName = "StadiumInfo", targetNamespace = "http://footballpool.dataaccess.eu", className = "support.StadiumInfo")
@ResponseWrapper(localName = "StadiumInfoResponse", targetNamespace = "http://footballpool.dataaccess.eu", className = "support.StadiumInfoResponse")
public TStadiumInfo stadiumInfo(
@WebParam(name = "sStadiumName", targetNamespace = "http://footballpool.dataaccess.eu")
String sStadiumName); | @WebMethod(operationName = STR) @WebResult(name = STR, targetNamespace = "http: @RequestWrapper(localName = STR, targetNamespace = "http: @ResponseWrapper(localName = "StadiumInfoResponseSTRhttp: TStadiumInfo function( @WebParam(name = "sStadiumNameSTRhttp: String sStadiumName); | /**
* Returns the information we keep about a particular stadium, Pass the name of the stadium
*
* @param sStadiumName
* @return
* returns support.TStadiumInfo
*/ | Returns the information we keep about a particular stadium, Pass the name of the stadium | stadiumInfo | {
"repo_name": "pietrodn/middleware-exe",
"path": "webservices/TestFootballService/src/support/InfoSoapType.java",
"license": "gpl-3.0",
"size": 32295
} | [
"javax.jws.WebMethod",
"javax.jws.WebParam",
"javax.jws.WebResult",
"javax.xml.ws.RequestWrapper",
"javax.xml.ws.ResponseWrapper"
] | import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; | import javax.jws.*; import javax.xml.ws.*; | [
"javax.jws",
"javax.xml"
] | javax.jws; javax.xml; | 843,090 |
private int getInt(DatatypeConstants.Field field) {
Number n = getField(field);
if (n == null) {
return 0;
} else {
return n.intValue();
}
}
/**
* <p>Returns the length of the duration in milli-seconds.</p>
*
* <p>If the seconds field carries more digits than milli-second order,
* those will be simply discarded (or in other words, rounded to zero.)
* For example, for any Calendar value <code>x<code>,</p>
* <pre>
* <code>new Duration("PT10.00099S").getTimeInMills(x) == 10000</code>.
* <code>new Duration("-PT10.00099S").getTimeInMills(x) == -10000</code>.
* </pre>
*
* <p>
* Note that this method uses the {@link #addTo(Calendar)} method,
* which may work incorectly with {@link Duration} objects with
* very large values in its fields. See the {@link #addTo(Calendar)} | int function(DatatypeConstants.Field field) { Number n = getField(field); if (n == null) { return 0; } else { return n.intValue(); } } /** * <p>Returns the length of the duration in milli-seconds.</p> * * <p>If the seconds field carries more digits than milli-second order, * those will be simply discarded (or in other words, rounded to zero.) * For example, for any Calendar value <code>x<code>,</p> * <pre> * <code>new Duration(STR).getTimeInMills(x) == 10000</code>. * <code>new Duration(STR).getTimeInMills(x) == -10000</code>. * </pre> * * <p> * Note that this method uses the {@link #addTo(Calendar)} method, * which may work incorectly with {@link Duration} objects with * very large values in its fields. See the {@link #addTo(Calendar)} | /**
* <p>Return the requested field value as an int.</p>
*
* <p>If field is not set, i.e. == null, 0 is returned.</p>
*
* @param field To get value for.
*
* @return int value of field or 0 if field is not set.
*/ | Return the requested field value as an int. If field is not set, i.e. == null, 0 is returned | getInt | {
"repo_name": "PrincetonUniversity/NVJVM",
"path": "build/linux-amd64/jaxp/drop/jaxp_src/src/com/sun/org/apache/xerces/internal/jaxp/datatype/DurationImpl.java",
"license": "gpl-2.0",
"size": 72133
} | [
"java.util.Calendar",
"javax.xml.datatype.DatatypeConstants",
"javax.xml.datatype.Duration"
] | import java.util.Calendar; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.Duration; | import java.util.*; import javax.xml.datatype.*; | [
"java.util",
"javax.xml"
] | java.util; javax.xml; | 2,901,704 |
public void getConnection(Handler<AsyncResult<PgConnection>> replyHandler) {
getConnection().onComplete(replyHandler);
} | void function(Handler<AsyncResult<PgConnection>> replyHandler) { getConnection().onComplete(replyHandler); } | /**
* Get Vert.x {@link PgConnection}.
*
* @see #withConn(Function)
* @see #withConnection(Function)
* @see #withTrans(Function)
* @see #withTransaction(Function)
*/ | Get Vert.x <code>PgConnection</code> | getConnection | {
"repo_name": "folio-org/raml-module-builder",
"path": "domain-models-runtime/src/main/java/org/folio/rest/persist/PostgresClient.java",
"license": "apache-2.0",
"size": 164512
} | [
"io.vertx.core.AsyncResult",
"io.vertx.core.Handler",
"io.vertx.pgclient.PgConnection"
] | import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.pgclient.PgConnection; | import io.vertx.core.*; import io.vertx.pgclient.*; | [
"io.vertx.core",
"io.vertx.pgclient"
] | io.vertx.core; io.vertx.pgclient; | 367,347 |
// package protected, for access from FastDateFormat; do not make public or protected
F getDateInstance(final int dateStyle, final TimeZone timeZone, Locale locale) {
return getDateTimeInstance(Integer.valueOf(dateStyle), null, timeZone, locale);
} | F getDateInstance(final int dateStyle, final TimeZone timeZone, Locale locale) { return getDateTimeInstance(Integer.valueOf(dateStyle), null, timeZone, locale); } | /**
* <p>Gets a date formatter instance using the specified style,
* time zone and locale.</p>
*
* @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT
* @param timeZone optional time zone, overrides time zone of
* formatted date, null means use default Locale
* @param locale optional locale, overrides system locale
* @return a localized standard date/time formatter
* @throws IllegalArgumentException if the Locale has no date/time
* pattern defined
*/ | Gets a date formatter instance using the specified style, time zone and locale | getDateInstance | {
"repo_name": "DigitalLabApp/Gramy",
"path": "Telegram-master/TMessagesProj/src/main/java/org/telegram/messenger/time/FormatCache.java",
"license": "gpl-2.0",
"size": 11425
} | [
"java.util.Locale",
"java.util.TimeZone"
] | import java.util.Locale; import java.util.TimeZone; | import java.util.*; | [
"java.util"
] | java.util; | 1,964,262 |
RoutableChannelHandler getRoute(String address) {
return routes.get(address);
} | RoutableChannelHandler getRoute(String address) { return routes.get(address); } | /**
* Returns the route hosted by this node that is associated to the specified address.
*
* @param address the string representation of the JID associated to the route.
* @return the route hosted by this node that is associated to the specified address.
*/ | Returns the route hosted by this node that is associated to the specified address | getRoute | {
"repo_name": "saveendhiman/OpenfirePluginSample",
"path": "openfiresource/src/org/jivesoftware/openfire/spi/LocalRoutingTable.java",
"license": "apache-2.0",
"size": 7021
} | [
"org.jivesoftware.openfire.RoutableChannelHandler"
] | import org.jivesoftware.openfire.RoutableChannelHandler; | import org.jivesoftware.openfire.*; | [
"org.jivesoftware.openfire"
] | org.jivesoftware.openfire; | 2,590,080 |
public static float getFloat(Context context, String key) {
SharedPreferences mainPref =
context.getSharedPreferences(context.getResources()
.getString(R.string.shared_pref_package),
Context.MODE_PRIVATE
);
return mainPref.getFloat(key, DEFAULT_INDEX);
} | static float function(Context context, String key) { SharedPreferences mainPref = context.getSharedPreferences(context.getResources() .getString(R.string.shared_pref_package), Context.MODE_PRIVATE ); return mainPref.getFloat(key, DEFAULT_INDEX); } | /**
* Retrieve float data from shared preferences in private mode.
* @param context - The context of activity which is requesting to put data.
* @param key - Used to identify the value to to be retrieved.
*/ | Retrieve float data from shared preferences in private mode | getFloat | {
"repo_name": "dilee/product-mdm",
"path": "modules/mobile-agents/android/system-service/app/src/main/java/org/wso2/emm/system/service/utils/Preference.java",
"license": "apache-2.0",
"size": 5924
} | [
"android.content.Context",
"android.content.SharedPreferences"
] | import android.content.Context; import android.content.SharedPreferences; | import android.content.*; | [
"android.content"
] | android.content; | 677,294 |
public Font getTickLabelFont(Comparable category) {
if (category == null) {
throw new IllegalArgumentException("Null 'category' argument.");
}
Font result = (Font) this.tickLabelFontMap.get(category);
// if there is no specific font, use the general one...
if (result == null) {
result = getTickLabelFont();
}
return result;
}
| Font function(Comparable category) { if (category == null) { throw new IllegalArgumentException(STR); } Font result = (Font) this.tickLabelFontMap.get(category); if (result == null) { result = getTickLabelFont(); } return result; } | /**
* Returns the font for the tick label for the given category.
*
* @param category the category (<code>null</code> not permitted).
*
* @return The font (never <code>null</code>).
*
* @see #setTickLabelFont(Comparable, Font)
*/ | Returns the font for the tick label for the given category | getTickLabelFont | {
"repo_name": "nologic/nabs",
"path": "client/trunk/shared/libraries/jfreechart-1.0.5/source/org/jfree/chart/axis/CategoryAxis.java",
"license": "gpl-2.0",
"size": 49059
} | [
"java.awt.Font"
] | import java.awt.Font; | import java.awt.*; | [
"java.awt"
] | java.awt; | 2,423,278 |
public static String getExample (TypeDeclaration type) {
if (type == null || type.example() == null) {
return null;
} else {
return type.example().value();
}
}
| static String function (TypeDeclaration type) { if (type == null type.example() == null) { return null; } else { return type.example().value(); } } | /**
* Safely get example from a type with null checks
*
* @param type The RAML TypeDeclaration to check
* @return The example if defined or null if empty
*/ | Safely get example from a type with null checks | getExample | {
"repo_name": "rahulkavale/springmvc-raml-plugin",
"path": "springmvc-raml-parser/src/main/java/com/phoenixnap/oss/ramlapisync/naming/RamlTypeHelper.java",
"license": "apache-2.0",
"size": 11092
} | [
"org.raml.v2.api.model.v10.datamodel.TypeDeclaration"
] | import org.raml.v2.api.model.v10.datamodel.TypeDeclaration; | import org.raml.v2.api.model.v10.datamodel.*; | [
"org.raml.v2"
] | org.raml.v2; | 384,352 |
public Route getRoute();
| Route function(); | /**
* Get top-most parent route.
* @return
*/ | Get top-most parent route | getRoute | {
"repo_name": "valarion/JAGE",
"path": "JAGEgradle/JAGEmodules/src/main/java/com/valarion/gameengine/events/rpgmaker/FlowEventInterface.java",
"license": "mit",
"size": 2931
} | [
"com.valarion.gameengine.events.Route"
] | import com.valarion.gameengine.events.Route; | import com.valarion.gameengine.events.*; | [
"com.valarion.gameengine"
] | com.valarion.gameengine; | 1,142,958 |
@Test
public void testSemaphoreIsolatedBadRequestSyncExceptionObserve() {
testBadRequestExceptionObserve(ExecutionIsolationStrategy.SEMAPHORE, KnownHystrixBadRequestFailureTestCommand.SYNC_EXCEPTION);
} | void function() { testBadRequestExceptionObserve(ExecutionIsolationStrategy.SEMAPHORE, KnownHystrixBadRequestFailureTestCommand.SYNC_EXCEPTION); } | /**
* Test that a BadRequestException can be synchronously thrown from a semaphore-isolated command and not count towards errors and bypasses fallback.
*/ | Test that a BadRequestException can be synchronously thrown from a semaphore-isolated command and not count towards errors and bypasses fallback | testSemaphoreIsolatedBadRequestSyncExceptionObserve | {
"repo_name": "sasrin/Hystrix",
"path": "hystrix-core/src/test/java/com/netflix/hystrix/HystrixObservableCommandTest.java",
"license": "apache-2.0",
"size": 272384
} | [
"com.netflix.hystrix.HystrixCommandProperties"
] | import com.netflix.hystrix.HystrixCommandProperties; | import com.netflix.hystrix.*; | [
"com.netflix.hystrix"
] | com.netflix.hystrix; | 2,069,773 |
public boolean isSearcherCurrent() throws IOException {
final IndexSearcher searcher = acquire();
try {
final IndexReader r = searcher.getIndexReader();
assert r instanceof DirectoryReader: "searcher's IndexReader should be a DirectoryReader, but got " + r;
return ((DirectoryReader) r).isCurrent();
} finally {
release(searcher);
}
} | boolean function() throws IOException { final IndexSearcher searcher = acquire(); try { final IndexReader r = searcher.getIndexReader(); assert r instanceof DirectoryReader: STR + r; return ((DirectoryReader) r).isCurrent(); } finally { release(searcher); } } | /**
* Returns <code>true</code> if no changes have occured since this searcher
* ie. reader was opened, otherwise <code>false</code>.
* @see DirectoryReader#isCurrent()
*/ | Returns <code>true</code> if no changes have occured since this searcher ie. reader was opened, otherwise <code>false</code> | isSearcherCurrent | {
"repo_name": "yida-lxw/solr-5.3.1",
"path": "lucene/core/src/java/org/apache/lucene/search/SearcherManager.java",
"license": "apache-2.0",
"size": 7466
} | [
"java.io.IOException",
"org.apache.lucene.index.DirectoryReader",
"org.apache.lucene.index.IndexReader"
] | import java.io.IOException; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; | import java.io.*; import org.apache.lucene.index.*; | [
"java.io",
"org.apache.lucene"
] | java.io; org.apache.lucene; | 2,175,128 |
@Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class)
public List<ChildAssociationRef> getParentAssocs(
final NodeRef nodeRef,
final QNamePattern typeQNamePattern,
final QNamePattern qnamePattern)
{
// Get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
| @Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class) List<ChildAssociationRef> function( final NodeRef nodeRef, final QNamePattern typeQNamePattern, final QNamePattern qnamePattern) { Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef); Long nodeId = nodePair.getFirst(); | /**
* Filters out any associations if their qname is not a match to the given pattern.
*/ | Filters out any associations if their qname is not a match to the given pattern | getParentAssocs | {
"repo_name": "Alfresco/community-edition",
"path": "projects/repository/source/java/org/alfresco/repo/node/db/DbNodeServiceImpl.java",
"license": "lgpl-3.0",
"size": 141832
} | [
"java.util.List",
"org.alfresco.repo.node.db.traitextender.NodeServiceExtension",
"org.alfresco.repo.node.db.traitextender.NodeServiceTrait",
"org.alfresco.service.cmr.repository.ChildAssociationRef",
"org.alfresco.service.cmr.repository.NodeRef",
"org.alfresco.service.namespace.QNamePattern",
"org.alfresco.traitextender.Extend",
"org.alfresco.util.Pair"
] | import java.util.List; import org.alfresco.repo.node.db.traitextender.NodeServiceExtension; import org.alfresco.repo.node.db.traitextender.NodeServiceTrait; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.namespace.QNamePattern; import org.alfresco.traitextender.Extend; import org.alfresco.util.Pair; | import java.util.*; import org.alfresco.repo.node.db.traitextender.*; import org.alfresco.service.cmr.repository.*; import org.alfresco.service.namespace.*; import org.alfresco.traitextender.*; import org.alfresco.util.*; | [
"java.util",
"org.alfresco.repo",
"org.alfresco.service",
"org.alfresco.traitextender",
"org.alfresco.util"
] | java.util; org.alfresco.repo; org.alfresco.service; org.alfresco.traitextender; org.alfresco.util; | 869,683 |
public void waitForShutdown(long millis) {
LOGGER.info("Waiting for Shutdown");
if (_channel != null) {
LOGGER.info("Closing the server channel");
long endTime = System.currentTimeMillis() + millis;
ChannelFuture channelFuture = _channel.close();
Future<?> bossGroupFuture = _bossGroup.shutdownGracefully();
Future<?> workerGroupFuture = _workerGroup.shutdownGracefully();
long currentTime = System.currentTimeMillis();
if (endTime > currentTime) {
channelFuture.awaitUninterruptibly(endTime - currentTime, TimeUnit.MILLISECONDS);
}
currentTime = System.currentTimeMillis();
if (endTime > currentTime) {
bossGroupFuture.awaitUninterruptibly(endTime - currentTime, TimeUnit.MINUTES);
}
currentTime = System.currentTimeMillis();
if (endTime > currentTime) {
workerGroupFuture.awaitUninterruptibly(endTime - currentTime, TimeUnit.MINUTES);
}
Preconditions.checkState(channelFuture.isDone(), "Unable to close the channel in %s ms", millis);
Preconditions.checkState(bossGroupFuture.isDone(), "Unable to shutdown the boss group in %s ms", millis);
Preconditions.checkState(workerGroupFuture.isDone(), "Unable to shutdown the worker group in %s ms", millis);
}
}
public static class NettyChannelInboundHandler extends ChannelInboundHandlerAdapter {
private final long _defaultLargeQueryLatencyMs;
private final RequestHandler _handler;
private final NettyServerMetrics _metric;
public NettyChannelInboundHandler(RequestHandler handler, NettyServerMetrics metric, long defaultLargeQueryLatencyMs) {
_handler = handler;
_metric = metric;
_defaultLargeQueryLatencyMs = defaultLargeQueryLatencyMs;
}
public NettyChannelInboundHandler(RequestHandler handler, NettyServerMetrics metric) {
this(handler, metric, 100);
} | void function(long millis) { LOGGER.info(STR); if (_channel != null) { LOGGER.info(STR); long endTime = System.currentTimeMillis() + millis; ChannelFuture channelFuture = _channel.close(); Future<?> bossGroupFuture = _bossGroup.shutdownGracefully(); Future<?> workerGroupFuture = _workerGroup.shutdownGracefully(); long currentTime = System.currentTimeMillis(); if (endTime > currentTime) { channelFuture.awaitUninterruptibly(endTime - currentTime, TimeUnit.MILLISECONDS); } currentTime = System.currentTimeMillis(); if (endTime > currentTime) { bossGroupFuture.awaitUninterruptibly(endTime - currentTime, TimeUnit.MINUTES); } currentTime = System.currentTimeMillis(); if (endTime > currentTime) { workerGroupFuture.awaitUninterruptibly(endTime - currentTime, TimeUnit.MINUTES); } Preconditions.checkState(channelFuture.isDone(), STR, millis); Preconditions.checkState(bossGroupFuture.isDone(), STR, millis); Preconditions.checkState(workerGroupFuture.isDone(), STR, millis); } } public static class NettyChannelInboundHandler extends ChannelInboundHandlerAdapter { private final long _defaultLargeQueryLatencyMs; private final RequestHandler _handler; private final NettyServerMetrics _metric; public NettyChannelInboundHandler(RequestHandler handler, NettyServerMetrics metric, long defaultLargeQueryLatencyMs) { _handler = handler; _metric = metric; _defaultLargeQueryLatencyMs = defaultLargeQueryLatencyMs; } public NettyChannelInboundHandler(RequestHandler handler, NettyServerMetrics metric) { this(handler, metric, 100); } | /**
* Blocking call to wait for shutdown completely.
*/ | Blocking call to wait for shutdown completely | waitForShutdown | {
"repo_name": "sajavadi/pinot",
"path": "pinot-transport/src/main/java/com/linkedin/pinot/transport/netty/NettyServer.java",
"license": "apache-2.0",
"size": 12139
} | [
"com.google.common.base.Preconditions",
"com.linkedin.pinot.transport.metrics.NettyServerMetrics",
"io.netty.channel.ChannelFuture",
"io.netty.channel.ChannelInboundHandlerAdapter",
"io.netty.util.concurrent.Future",
"java.util.concurrent.TimeUnit"
] | import com.google.common.base.Preconditions; import com.linkedin.pinot.transport.metrics.NettyServerMetrics; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.concurrent.Future; import java.util.concurrent.TimeUnit; | import com.google.common.base.*; import com.linkedin.pinot.transport.metrics.*; import io.netty.channel.*; import io.netty.util.concurrent.*; import java.util.concurrent.*; | [
"com.google.common",
"com.linkedin.pinot",
"io.netty.channel",
"io.netty.util",
"java.util"
] | com.google.common; com.linkedin.pinot; io.netty.channel; io.netty.util; java.util; | 805,443 |
@Override
public int quantityDropped(Random par1Random)
{
return 1;
} | int function(Random par1Random) { return 1; } | /**
* Returns the quantity of items to drop on block destruction.
*/ | Returns the quantity of items to drop on block destruction | quantityDropped | {
"repo_name": "Wehavecookies56/Kingdom-Keys-1.8-",
"path": "java/wehavecookies56/kk/block/BlockBlastBlox.java",
"license": "gpl-3.0",
"size": 7561
} | [
"java.util.Random"
] | import java.util.Random; | import java.util.*; | [
"java.util"
] | java.util; | 1,693,861 |
@ServiceMethod(returns = ReturnType.SINGLE)
public void delete(String resourceGroupName, String accountName, String assetName) {
deleteAsync(resourceGroupName, accountName, assetName).block();
} | @ServiceMethod(returns = ReturnType.SINGLE) void function(String resourceGroupName, String accountName, String assetName) { deleteAsync(resourceGroupName, accountName, assetName).block(); } | /**
* Deletes an Asset in the Media Services account.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param assetName The Asset name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/ | Deletes an Asset in the Media Services account | delete | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/mediaservices/azure-resourcemanager-mediaservices/src/main/java/com/azure/resourcemanager/mediaservices/implementation/AssetsClientImpl.java",
"license": "mit",
"size": 84704
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; | import com.azure.core.annotation.*; | [
"com.azure.core"
] | com.azure.core; | 423,162 |
private void assertZipAndUnzipOfDirectoryMatchesOriginal(File sourceDir) throws IOException {
File[] sourceFiles = sourceDir.listFiles();
Arrays.sort(sourceFiles);
File zipFile = createZipFileHandle();
ZipFiles.zipDirectory(sourceDir, zipFile);
File outputDir = Files.createTempDir();
ZipFiles.unzipFile(zipFile, outputDir);
File[] outputFiles = outputDir.listFiles();
Arrays.sort(outputFiles);
assertThat(outputFiles, arrayWithSize(sourceFiles.length));
for (int i = 0; i < sourceFiles.length; i++) {
compareFileContents(sourceFiles[i], outputFiles[i]);
}
removeRecursive(outputDir.toPath());
assertTrue(zipFile.delete());
} | void function(File sourceDir) throws IOException { File[] sourceFiles = sourceDir.listFiles(); Arrays.sort(sourceFiles); File zipFile = createZipFileHandle(); ZipFiles.zipDirectory(sourceDir, zipFile); File outputDir = Files.createTempDir(); ZipFiles.unzipFile(zipFile, outputDir); File[] outputFiles = outputDir.listFiles(); Arrays.sort(outputFiles); assertThat(outputFiles, arrayWithSize(sourceFiles.length)); for (int i = 0; i < sourceFiles.length; i++) { compareFileContents(sourceFiles[i], outputFiles[i]); } removeRecursive(outputDir.toPath()); assertTrue(zipFile.delete()); } | /**
* zip and unzip a certain directory, and verify the content afterward to be
* identical.
* @param sourceDir the directory to zip
*/ | zip and unzip a certain directory, and verify the content afterward to be identical | assertZipAndUnzipOfDirectoryMatchesOriginal | {
"repo_name": "shakamunyi/beam",
"path": "sdk/src/test/java/com/google/cloud/dataflow/sdk/util/ZipFilesTest.java",
"license": "apache-2.0",
"size": 10585
} | [
"com.google.common.io.Files",
"java.io.File",
"java.io.IOException",
"java.util.Arrays",
"org.hamcrest.Matchers",
"org.junit.Assert"
] | import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.util.Arrays; import org.hamcrest.Matchers; import org.junit.Assert; | import com.google.common.io.*; import java.io.*; import java.util.*; import org.hamcrest.*; import org.junit.*; | [
"com.google.common",
"java.io",
"java.util",
"org.hamcrest",
"org.junit"
] | com.google.common; java.io; java.util; org.hamcrest; org.junit; | 2,377,624 |
public ArrayList<ContentValues> SelectData(String _tabla, String _campos, String _condicion){
ArrayList<ContentValues> _query = new ArrayList<ContentValues>();
_query.clear();
this.abrir();
try{
Cursor c = nBD.rawQuery("SELECT DISTINCT "+_campos+" FROM "+_tabla+" WHERE "+_condicion, null);
String[] _columnas = c.getColumnNames();
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
ContentValues _registro = new ContentValues();
for(int i=0;i<_columnas.length;i++){
_registro.put(_columnas[i], c.getString(i));
}
_query.add(_registro);
}
}
catch(Exception e){
Log.i("Error en SQLite", e.toString());
}
this.cerrar();
return _query;
}
| ArrayList<ContentValues> function(String _tabla, String _campos, String _condicion){ ArrayList<ContentValues> _query = new ArrayList<ContentValues>(); _query.clear(); this.abrir(); try{ Cursor c = nBD.rawQuery(STR+_campos+STR+_tabla+STR+_condicion, null); String[] _columnas = c.getColumnNames(); for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){ ContentValues _registro = new ContentValues(); for(int i=0;i<_columnas.length;i++){ _registro.put(_columnas[i], c.getString(i)); } _query.add(_registro); } } catch(Exception e){ Log.i(STR, e.toString()); } this.cerrar(); return _query; } | /**Funcion encargada de realizar una consulta y retornarla con un array list de content values, similar a un array de diccionarios
* @param _tabla ->tabla sobre la cual va a correr la consulta
* @param _campos ->campos que se van a consultar
* @param _condicion ->condicion para filtrar la consulta
* @return ->ArrayList de ContentValues con la informacion resultado de la consulta
*/ | Funcion encargada de realizar una consulta y retornarla con un array list de content values, similar a un array de diccionarios | SelectData | {
"repo_name": "JulianPoveda/movil_acrene",
"path": "src/miscelanea/SQLite.java",
"license": "gpl-2.0",
"size": 21650
} | [
"android.content.ContentValues",
"android.database.Cursor",
"android.util.Log",
"java.util.ArrayList"
] | import android.content.ContentValues; import android.database.Cursor; import android.util.Log; import java.util.ArrayList; | import android.content.*; import android.database.*; import android.util.*; import java.util.*; | [
"android.content",
"android.database",
"android.util",
"java.util"
] | android.content; android.database; android.util; java.util; | 1,367,632 |
private static byte[] l2b(final String l) throws UnsupportedEncodingException {
assert (l != null): "Supplied locator is null";
synchronized (HASHER) {
// FIXME: this may be an congestion point; maybe use a separate hasher for each call...
HASHER.update(l.getBytes( "UTF-8"));
return HASHER.digest();
}
} | static byte[] function(final String l) throws UnsupportedEncodingException { assert (l != null): STR; synchronized (HASHER) { HASHER.update(l.getBytes( "UTF-8")); return HASHER.digest(); } } | /**
* Converts a locator to a hash byte array.
*
* @param l locator.
*
* @return hash byte array.
*/ | Converts a locator to a hash byte array | l2b | {
"repo_name": "TheCount/jhilbert",
"path": "src/main/java/jhilbert/storage/hashstore/Storage.java",
"license": "gpl-3.0",
"size": 8287
} | [
"java.io.UnsupportedEncodingException"
] | import java.io.UnsupportedEncodingException; | import java.io.*; | [
"java.io"
] | java.io; | 974,284 |
private static String generateDescription(SoyMsg msg) {
String desc = msg.getDesc();
if (desc != null && desc.length() > 0) {
return "msgctxt \"" + desc + "\"\n";
}
return "";
} | static String function(SoyMsg msg) { String desc = msg.getDesc(); if (desc != null && desc.length() > 0) { return STRSTR\"\n"; } return ""; } | /**
* Generate a description line.
*
* Returns an empty string if the message has no description.
*/ | Generate a description line. Returns an empty string if the message has no description | generateDescription | {
"repo_name": "leapingbrainlabs/closure-templates",
"path": "java/src/com/google/template/soy/pomsgplugin/PoGenerator.java",
"license": "apache-2.0",
"size": 6829
} | [
"com.google.template.soy.msgs.restricted.SoyMsg"
] | import com.google.template.soy.msgs.restricted.SoyMsg; | import com.google.template.soy.msgs.restricted.*; | [
"com.google.template"
] | com.google.template; | 351,604 |
public static double calculateMedian(List values, boolean copyAndSort) {
double result = Double.NaN;
if (values != null) {
if (copyAndSort) {
int itemCount = values.size();
List copy = new ArrayList(itemCount);
for (int i = 0; i < itemCount; i++) {
copy.add(i, values.get(i));
}
Collections.sort(copy);
values = copy;
}
int count = values.size();
if (count > 0) {
if (count % 2 == 1) {
if (count > 1) {
Number value = (Number) values.get((count - 1) / 2);
result = value.doubleValue();
}
else {
Number value = (Number) values.get(0);
result = value.doubleValue();
}
}
else {
Number value1 = (Number) values.get(count / 2 - 1);
Number value2 = (Number) values.get(count / 2);
result = (value1.doubleValue() + value2.doubleValue())
/ 2.0;
}
}
}
return result;
}
| static double function(List values, boolean copyAndSort) { double result = Double.NaN; if (values != null) { if (copyAndSort) { int itemCount = values.size(); List copy = new ArrayList(itemCount); for (int i = 0; i < itemCount; i++) { copy.add(i, values.get(i)); } Collections.sort(copy); values = copy; } int count = values.size(); if (count > 0) { if (count % 2 == 1) { if (count > 1) { Number value = (Number) values.get((count - 1) / 2); result = value.doubleValue(); } else { Number value = (Number) values.get(0); result = value.doubleValue(); } } else { Number value1 = (Number) values.get(count / 2 - 1); Number value2 = (Number) values.get(count / 2); result = (value1.doubleValue() + value2.doubleValue()) / 2.0; } } } return result; } | /**
* Calculates the median for a list of values ({@code Number} objects).
* If {@code copyAndSort} is {@code false}, the list is assumed
* to be presorted in ascending order by value.
*
* @param values the values ({@code null} permitted).
* @param copyAndSort a flag that controls whether the list of values is
* copied and sorted.
*
* @return The median.
*/ | Calculates the median for a list of values (Number objects). If copyAndSort is false, the list is assumed to be presorted in ascending order by value | calculateMedian | {
"repo_name": "sebkur/JFreeChart",
"path": "src/main/java/org/jfree/data/statistics/Statistics.java",
"license": "lgpl-3.0",
"size": 16879
} | [
"java.util.ArrayList",
"java.util.Collections",
"java.util.List"
] | import java.util.ArrayList; import java.util.Collections; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,474,888 |
public long getRollingMaxValue(HystrixRollingNumberEvent type) {
long values[] = getValues(type);
if (values.length == 0) {
return 0;
} else {
Arrays.sort(values);
return values[values.length - 1];
}
}
private ReentrantLock newBucketLock = new ReentrantLock(); | long function(HystrixRollingNumberEvent type) { long values[] = getValues(type); if (values.length == 0) { return 0; } else { Arrays.sort(values); return values[values.length - 1]; } } private ReentrantLock newBucketLock = new ReentrantLock(); | /**
* Get the max value of values in all buckets for the given {@link HystrixRollingNumberEvent} type.
* <p>
* The {@link HystrixRollingNumberEvent} must be a "max updater" type <code>HystrixRollingNumberEvent.isMaxUpdater() == true</code>.
*
* @param type
* HystrixRollingNumberEvent defining which "max updater" to retrieve values from
* @return max value for given {@link HystrixRollingNumberEvent} type during rolling window
*/ | Get the max value of values in all buckets for the given <code>HystrixRollingNumberEvent</code> type. The <code>HystrixRollingNumberEvent</code> must be a "max updater" type <code>HystrixRollingNumberEvent.isMaxUpdater() == true</code> | getRollingMaxValue | {
"repo_name": "fluxcapacitor/pipeline",
"path": "predict/dashboard/hystrix-core/src/main/java/com/netflix/hystrix/util/HystrixRollingNumber.java",
"license": "apache-2.0",
"size": 32080
} | [
"java.util.Arrays",
"java.util.concurrent.locks.ReentrantLock"
] | import java.util.Arrays; import java.util.concurrent.locks.ReentrantLock; | import java.util.*; import java.util.concurrent.locks.*; | [
"java.util"
] | java.util; | 880,441 |
ActionFuture<AcknowledgedResponse> putPipeline(PutPipelineRequest request); | ActionFuture<AcknowledgedResponse> putPipeline(PutPipelineRequest request); | /**
* Stores an ingest pipeline
*/ | Stores an ingest pipeline | putPipeline | {
"repo_name": "ern/elasticsearch",
"path": "server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java",
"license": "apache-2.0",
"size": 28517
} | [
"org.elasticsearch.action.ActionFuture",
"org.elasticsearch.action.ingest.PutPipelineRequest",
"org.elasticsearch.action.support.master.AcknowledgedResponse"
] | import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.ingest.PutPipelineRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; | import org.elasticsearch.action.*; import org.elasticsearch.action.ingest.*; import org.elasticsearch.action.support.master.*; | [
"org.elasticsearch.action"
] | org.elasticsearch.action; | 737,653 |
public void setLoad(boolean val) {
if ( load == null ) {
load = (SFBool)getField( "load" );
}
load.setValue( val );
} | void function(boolean val) { if ( load == null ) { load = (SFBool)getField( "load" ); } load.setValue( val ); } | /** Set the load field.
* @param val The boolean to set. */ | Set the load field | setLoad | {
"repo_name": "Norkart/NK-VirtualGlobe",
"path": "Xj3D/src/java/org/xj3d/sai/external/node/networking/SAIInline.java",
"license": "gpl-2.0",
"size": 3790
} | [
"org.web3d.x3d.sai.SFBool"
] | import org.web3d.x3d.sai.SFBool; | import org.web3d.x3d.sai.*; | [
"org.web3d.x3d"
] | org.web3d.x3d; | 1,705,833 |
public void delete() throws IOException {
close();
Util.deleteContents(directory);
} | void function() throws IOException { close(); Util.deleteContents(directory); } | /**
* Closes the cache and deletes all of its stored values. This will delete
* all files in the cache directory including files that weren't created by
* the cache.
*/ | Closes the cache and deletes all of its stored values. This will delete all files in the cache directory including files that weren't created by the cache | delete | {
"repo_name": "davols/android-light-dasftp",
"path": "app/src/main/java/com/github/davols/dasftp/DiskLruCache.java",
"license": "apache-2.0",
"size": 34386
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,154,053 |
public static MozuClient<com.mozu.api.contracts.tenant.TenantCollection> getTenantScopesForUserClient(String userId) throws Exception
{
return getTenantScopesForUserClient( userId, null);
} | static MozuClient<com.mozu.api.contracts.tenant.TenantCollection> function(String userId) throws Exception { return getTenantScopesForUserClient( userId, null); } | /**
* Retrieves a list of the Mozu tenants or development stores for which the specified user has an assigned role.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.tenant.TenantCollection> mozuClient=GetTenantScopesForUserClient( userId);
* client.setBaseAddress(url);
* client.executeRequest();
* TenantCollection tenantCollection = client.Result();
* </code></pre></p>
* @param userId Unique identifier of the user whose tenant scopes you want to retrieve.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.tenant.TenantCollection>
* @see com.mozu.api.contracts.tenant.TenantCollection
*/ | Retrieves a list of the Mozu tenants or development stores for which the specified user has an assigned role. <code><code> MozuClient mozuClient=GetTenantScopesForUserClient( userId); client.setBaseAddress(url); client.executeRequest(); TenantCollection tenantCollection = client.Result(); </code></code> | getTenantScopesForUserClient | {
"repo_name": "sanjaymandadi/mozu-java",
"path": "mozu-javaasync-core/src/main/java/com/mozu/api/clients/platform/adminuser/AdminUserClient.java",
"license": "mit",
"size": 4828
} | [
"com.mozu.api.MozuClient"
] | import com.mozu.api.MozuClient; | import com.mozu.api.*; | [
"com.mozu.api"
] | com.mozu.api; | 363,840 |
@FXML
void newFileB(ActionEvent event) {
// Generates the basic planner information
File plannerFile = null;
try {
Account newAccount = MainController.ui.createAccount();
StudyPlannerController study = new StudyPlannerController(newAccount);
// Welcome notification:
Notification not = new Notification("Welcome!", new GregorianCalendar(),
"Thank you for using RaiderPlanner!");
study.getPlanner().addNotification(not);
MainController.setSpc(study);
plannerFile = MainController.ui.savePlannerFileDialog();
} catch (Exception e) {
// Apparently createAccount() throws a general exception when the user hits quit
// I know this isn't great coding practice, but if this fails the file should remain
// null and all should be fine. I just want this to return to the UI without breaking.
}
// Attempts to save planner file
if (plannerFile != null) {
if (plannerFile.getParentFile().exists()) {
if (plannerFile.getParentFile().canRead()) {
if (plannerFile.getParentFile().canWrite()) {
MainController.setPlannerFile(plannerFile);
MainController.save();
Stage stage = (Stage) this.openFileButton.getScene().getWindow();
stage.close();
} else {
UIManager.reportError("Directory can not be written to.");
}
} else {
UIManager.reportError("Directory cannot be read from.");
}
} else {
UIManager.reportError("Directory does not exist.");
}
}
} | void newFileB(ActionEvent event) { File plannerFile = null; try { Account newAccount = MainController.ui.createAccount(); StudyPlannerController study = new StudyPlannerController(newAccount); Notification not = new Notification(STR, new GregorianCalendar(), STR); study.getPlanner().addNotification(not); MainController.setSpc(study); plannerFile = MainController.ui.savePlannerFileDialog(); } catch (Exception e) { } if (plannerFile != null) { if (plannerFile.getParentFile().exists()) { if (plannerFile.getParentFile().canRead()) { if (plannerFile.getParentFile().canWrite()) { MainController.setPlannerFile(plannerFile); MainController.save(); Stage stage = (Stage) this.openFileButton.getScene().getWindow(); stage.close(); } else { UIManager.reportError(STR); } } else { UIManager.reportError(STR); } } else { UIManager.reportError(STR); } } } | /**
* Handles newFileButton's action event. Creates new profile and file.
*/ | Handles newFileButton's action event. Creates new profile and file | newFileB | {
"repo_name": "Fahad-n/RaiderPlanner",
"path": "src/edu/wright/cs/raiderplanner/controller/StartupController.java",
"license": "gpl-3.0",
"size": 3895
} | [
"edu.wright.cs.raiderplanner.model.Account",
"edu.wright.cs.raiderplanner.model.Notification",
"edu.wright.cs.raiderplanner.view.UIManager",
"java.io.File",
"java.util.GregorianCalendar"
] | import edu.wright.cs.raiderplanner.model.Account; import edu.wright.cs.raiderplanner.model.Notification; import edu.wright.cs.raiderplanner.view.UIManager; import java.io.File; import java.util.GregorianCalendar; | import edu.wright.cs.raiderplanner.model.*; import edu.wright.cs.raiderplanner.view.*; import java.io.*; import java.util.*; | [
"edu.wright.cs",
"java.io",
"java.util"
] | edu.wright.cs; java.io; java.util; | 2,632,557 |
private void processFile(String fileName) {
BufferedReader lineReader; // Reader for the input file
String srcEncoding = "UTF-8"; // Encoding of the input file
String line = null; // current line from text file
try {
if (fileName == null || fileName.length() <= 0 || fileName.equals("-")) {
lineReader = new BufferedReader(new InputStreamReader(System.in, srcEncoding));
} else {
ReadableByteChannel lineChannel = (new FileInputStream(fileName)).getChannel();
lineReader = new BufferedReader(Channels.newReader(lineChannel , srcEncoding));
}
while ((line = lineReader.readLine()) != null) { // read and process lines
if (! line.matches("\\s*#.*")) { // is not a comment
parms = line.split("\\t", -1);
if (sDebug >= 1) {
System.out.println(line); // repeat it unchanged
}
iparm = 0;
aseqno = parms[iparm ++];
callCode = parms[iparm ++];
try {
mOffset = 0;
mOffset = Integer.parseInt(parms[iparm ++]);
} catch (Exception exc) {
}
if (callCode.equals("holop")) {
getParameters(aseqno);
} else {
processRecord();
}
} // is not a comment
} // while ! eof
lineReader.close();
} catch (Exception exc) {
System.err.println(exc.getMessage());
exc.printStackTrace();
} // try
} // processFile | void function(String fileName) { BufferedReader lineReader; String srcEncoding = "UTF-8"; String line = null; try { if (fileName == null fileName.length() <= 0 fileName.equals("-")) { lineReader = new BufferedReader(new InputStreamReader(System.in, srcEncoding)); } else { ReadableByteChannel lineChannel = (new FileInputStream(fileName)).getChannel(); lineReader = new BufferedReader(Channels.newReader(lineChannel , srcEncoding)); } while ((line = lineReader.readLine()) != null) { if (! line.matches(STR)) { parms = line.split("\\t", -1); if (sDebug >= 1) { System.out.println(line); } iparm = 0; aseqno = parms[iparm ++]; callCode = parms[iparm ++]; try { mOffset = 0; mOffset = Integer.parseInt(parms[iparm ++]); } catch (Exception exc) { } if (callCode.equals("holop")) { getParameters(aseqno); } else { processRecord(); } } } lineReader.close(); } catch (Exception exc) { System.err.println(exc.getMessage()); exc.printStackTrace(); } } | /**
* Filters a file and writes the modified output lines.
* @param fileName name of the input file, or "-" for STDIN
*/ | Filters a file and writes the modified output lines | processFile | {
"repo_name": "gfis/ramath",
"path": "src/main/java/irvine/test/HolonomicRecurrenceTest.java",
"license": "apache-2.0",
"size": 23262
} | [
"java.io.BufferedReader",
"java.io.FileInputStream",
"java.io.InputStreamReader",
"java.nio.channels.Channels",
"java.nio.channels.ReadableByteChannel"
] | import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; | import java.io.*; import java.nio.channels.*; | [
"java.io",
"java.nio"
] | java.io; java.nio; | 1,915,927 |
private static boolean haveSameYear(ZonedDateTime actual, ZonedDateTime other) {
return actual.getYear() == other.getYear();
}
protected AbstractZonedDateTimeAssert(ZonedDateTime actual, Class<?> selfType) {
super(actual, selfType);
} | static boolean function(ZonedDateTime actual, ZonedDateTime other) { return actual.getYear() == other.getYear(); } protected AbstractZonedDateTimeAssert(ZonedDateTime actual, Class<?> selfType) { super(actual, selfType); } | /**
* Returns true if both datetime are in the same year, false otherwise.
*
* @param actual the actual datetime. expected not be null
* @param other the other datetime. expected not be null
* @return true if both datetime are in the same year, false otherwise
*/ | Returns true if both datetime are in the same year, false otherwise | haveSameYear | {
"repo_name": "ChrisA89/assertj-core",
"path": "src/main/java/org/assertj/core/api/AbstractZonedDateTimeAssert.java",
"license": "apache-2.0",
"size": 42303
} | [
"java.time.ZonedDateTime"
] | import java.time.ZonedDateTime; | import java.time.*; | [
"java.time"
] | java.time; | 2,148,811 |
public ServiceResponseWithHeaders<Void, LROsDeleteAsyncRetryFailedHeaders> beginDeleteAsyncRetryFailed() throws CloudException, IOException {
Call<ResponseBody> call = service.beginDeleteAsyncRetryFailed(this.client.getAcceptLanguage());
return beginDeleteAsyncRetryFailedDelegate(call.execute());
} | ServiceResponseWithHeaders<Void, LROsDeleteAsyncRetryFailedHeaders> function() throws CloudException, IOException { Call<ResponseBody> call = service.beginDeleteAsyncRetryFailed(this.client.getAcceptLanguage()); return beginDeleteAsyncRetryFailedDelegate(call.execute()); } | /**
* Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status.
*
* @throws CloudException exception thrown from REST call
* @throws IOException exception thrown from serialization/deserialization
* @return the {@link ServiceResponseWithHeaders} object if successful.
*/ | Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status | beginDeleteAsyncRetryFailed | {
"repo_name": "sharadagarwal/autorest",
"path": "AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsOperationsImpl.java",
"license": "mit",
"size": 315973
} | [
"com.microsoft.azure.CloudException",
"com.microsoft.rest.ServiceResponseWithHeaders",
"java.io.IOException"
] | import com.microsoft.azure.CloudException; import com.microsoft.rest.ServiceResponseWithHeaders; import java.io.IOException; | import com.microsoft.azure.*; import com.microsoft.rest.*; import java.io.*; | [
"com.microsoft.azure",
"com.microsoft.rest",
"java.io"
] | com.microsoft.azure; com.microsoft.rest; java.io; | 2,700,850 |
public void error(SAXParseException exception) throws SAXException {
log.error("Parse Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null) {
errorHandler.error(exception);
}
}
| void function(SAXParseException exception) throws SAXException { log.error(STR + exception.getLineNumber() + STR + exception.getColumnNumber() + STR + exception.getMessage(), exception); if (errorHandler != null) { errorHandler.error(exception); } } | /**
* Forward notification of a parsing error to the application supplied
* error handler (if any).
*
* @param exception The error information
*
* @exception SAXException if a parsing exception occurs
*/ | Forward notification of a parsing error to the application supplied error handler (if any) | error | {
"repo_name": "ProfilingLabs/Usemon2",
"path": "usemon-agent-commons-java/src/main/java/com/usemon/lib/org/apache/commons/digester/Digester.java",
"license": "mpl-2.0",
"size": 104184
} | [
"org.xml.sax.SAXException",
"org.xml.sax.SAXParseException"
] | import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; | import org.xml.sax.*; | [
"org.xml.sax"
] | org.xml.sax; | 1,606,522 |
public void setBatchApplicationsInstallationPath(File path) {
this.explicitBatchappsHomePath = path;
} | void function(File path) { this.explicitBatchappsHomePath = path; } | /**
* Sets the path to the batch applications installation location.
* @param path the path to the batch applications installation location, or {@code null} to reset location
* @since 0.6.1
*/ | Sets the path to the batch applications installation location | setBatchApplicationsInstallationPath | {
"repo_name": "cocoatomo/asakusafw",
"path": "testing-project/asakusa-test-driver/src/main/java/com/asakusafw/testdriver/TestDriverContext.java",
"license": "apache-2.0",
"size": 33349
} | [
"java.io.File"
] | import java.io.File; | import java.io.*; | [
"java.io"
] | java.io; | 1,757,705 |
public String completeIt()
{
MDocType dt = MDocType.get(getCtx(), getC_DocType_ID());
String DocSubTypeSO = dt.getDocSubTypeSO();
// Just prepare
if (DOCACTION_Prepare.equals(getDocAction()))
{
setProcessed(false);
return DocAction.STATUS_InProgress;
}
// Offers
if (MDocType.DOCSUBTYPESO_Proposal.equals(DocSubTypeSO)
|| MDocType.DOCSUBTYPESO_Quotation.equals(DocSubTypeSO))
{
// Binding
if (MDocType.DOCSUBTYPESO_Quotation.equals(DocSubTypeSO))
reserveStock(dt, getLines(true, MOrderLine.COLUMNNAME_M_Product_ID));
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE);
if (m_processMsg != null)
return DocAction.STATUS_Invalid;
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE);
if (m_processMsg != null)
return DocAction.STATUS_Invalid;
// Set the definite document number after completed (if needed)
setDefiniteDocumentNo();
setProcessed(true);
return DocAction.STATUS_Completed;
}
// Waiting Payment - until we have a payment
if (!m_forceCreation
&& MDocType.DOCSUBTYPESO_PrepayOrder.equals(DocSubTypeSO)
&& getC_Payment_ID() == 0 && getC_CashLine_ID() == 0)
{
setProcessed(true);
return DocAction.STATUS_WaitingPayment;
}
// Re-Check
if (!m_justPrepared)
{
String status = prepareIt();
if (!DocAction.STATUS_InProgress.equals(status))
return status;
}
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE);
if (m_processMsg != null)
return DocAction.STATUS_Invalid;
// Implicit Approval
if (!isApproved())
approveIt();
getLines(true,null);
log.info(toString());
StringBuffer info = new StringBuffer();
boolean realTimePOS = MSysConfig.getBooleanValue("REAL_TIME_POS", false , getAD_Client_ID());
// Create SO Shipment - Force Shipment
MInOut shipment = null;
if (MDocType.DOCSUBTYPESO_OnCreditOrder.equals(DocSubTypeSO) // (W)illCall(I)nvoice
|| MDocType.DOCSUBTYPESO_WarehouseOrder.equals(DocSubTypeSO) // (W)illCall(P)ickup
|| MDocType.DOCSUBTYPESO_POSOrder.equals(DocSubTypeSO) // (W)alkIn(R)eceipt
|| MDocType.DOCSUBTYPESO_PrepayOrder.equals(DocSubTypeSO))
{
if (!DELIVERYRULE_Force.equals(getDeliveryRule()))
setDeliveryRule(DELIVERYRULE_Force);
//
shipment = createShipment (dt, realTimePOS ? null : getDateOrdered());
if (shipment == null)
return DocAction.STATUS_Invalid;
info.append("@M_InOut_ID@: ").append(shipment.getDocumentNo());
String msg = shipment.getProcessMsg();
if (msg != null && msg.length() > 0)
info.append(" (").append(msg).append(")");
} // Shipment
// Create SO Invoice - Always invoice complete Order
if ( MDocType.DOCSUBTYPESO_POSOrder.equals(DocSubTypeSO)
|| MDocType.DOCSUBTYPESO_OnCreditOrder.equals(DocSubTypeSO)
|| MDocType.DOCSUBTYPESO_PrepayOrder.equals(DocSubTypeSO))
{
MInvoice invoice = createInvoice (dt, shipment, realTimePOS ? null : getDateOrdered());
if (invoice == null)
return DocAction.STATUS_Invalid;
info.append(" - @C_Invoice_ID@: ").append(invoice.getDocumentNo());
String msg = invoice.getProcessMsg();
if (msg != null && msg.length() > 0)
info.append(" (").append(msg).append(")");
} // Invoice
// Counter Documents
MOrder counter = createCounterDoc();
if (counter != null)
info.append(" - @CounterDoc@: @Order@=").append(counter.getDocumentNo());
// User Validation
String valid = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE);
if (valid != null)
{
if (info.length() > 0)
info.append(" - ");
info.append(valid);
m_processMsg = info.toString();
return DocAction.STATUS_Invalid;
}
// Set the definite document number after completed (if needed)
setDefiniteDocumentNo();
setProcessed(true);
m_processMsg = info.toString();
//
setDocAction(DOCACTION_Close);
return DocAction.STATUS_Completed;
} // completeIt
| String function() { MDocType dt = MDocType.get(getCtx(), getC_DocType_ID()); String DocSubTypeSO = dt.getDocSubTypeSO(); if (DOCACTION_Prepare.equals(getDocAction())) { setProcessed(false); return DocAction.STATUS_InProgress; } if (MDocType.DOCSUBTYPESO_Proposal.equals(DocSubTypeSO) MDocType.DOCSUBTYPESO_Quotation.equals(DocSubTypeSO)) { if (MDocType.DOCSUBTYPESO_Quotation.equals(DocSubTypeSO)) reserveStock(dt, getLines(true, MOrderLine.COLUMNNAME_M_Product_ID)); m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE); if (m_processMsg != null) return DocAction.STATUS_Invalid; m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE); if (m_processMsg != null) return DocAction.STATUS_Invalid; setDefiniteDocumentNo(); setProcessed(true); return DocAction.STATUS_Completed; } if (!m_forceCreation && MDocType.DOCSUBTYPESO_PrepayOrder.equals(DocSubTypeSO) && getC_Payment_ID() == 0 && getC_CashLine_ID() == 0) { setProcessed(true); return DocAction.STATUS_WaitingPayment; } if (!m_justPrepared) { String status = prepareIt(); if (!DocAction.STATUS_InProgress.equals(status)) return status; } m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE); if (m_processMsg != null) return DocAction.STATUS_Invalid; if (!isApproved()) approveIt(); getLines(true,null); log.info(toString()); StringBuffer info = new StringBuffer(); boolean realTimePOS = MSysConfig.getBooleanValue(STR, false , getAD_Client_ID()); MInOut shipment = null; if (MDocType.DOCSUBTYPESO_OnCreditOrder.equals(DocSubTypeSO) MDocType.DOCSUBTYPESO_WarehouseOrder.equals(DocSubTypeSO) MDocType.DOCSUBTYPESO_POSOrder.equals(DocSubTypeSO) MDocType.DOCSUBTYPESO_PrepayOrder.equals(DocSubTypeSO)) { if (!DELIVERYRULE_Force.equals(getDeliveryRule())) setDeliveryRule(DELIVERYRULE_Force); if (shipment == null) return DocAction.STATUS_Invalid; info.append(STR).append(shipment.getDocumentNo()); String msg = shipment.getProcessMsg(); if (msg != null && msg.length() > 0) info.append(STR).append(msg).append(")"); } if ( MDocType.DOCSUBTYPESO_POSOrder.equals(DocSubTypeSO) MDocType.DOCSUBTYPESO_OnCreditOrder.equals(DocSubTypeSO) MDocType.DOCSUBTYPESO_PrepayOrder.equals(DocSubTypeSO)) { MInvoice invoice = createInvoice (dt, shipment, realTimePOS ? null : getDateOrdered()); if (invoice == null) return DocAction.STATUS_Invalid; info.append(STR).append(invoice.getDocumentNo()); String msg = invoice.getProcessMsg(); if (msg != null && msg.length() > 0) info.append(STR).append(msg).append(")"); } MOrder counter = createCounterDoc(); if (counter != null) info.append(STR).append(counter.getDocumentNo()); String valid = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE); if (valid != null) { if (info.length() > 0) info.append(STR); info.append(valid); m_processMsg = info.toString(); return DocAction.STATUS_Invalid; } setDefiniteDocumentNo(); setProcessed(true); m_processMsg = info.toString(); return DocAction.STATUS_Completed; } | /**************************************************************************
* Complete Document
* @return new status (Complete, In Progress, Invalid, Waiting ..)
*/ | Complete Document | completeIt | {
"repo_name": "arthurmelo88/palmetalADP",
"path": "adempiere_360/base/src/org/compiere/model/MOrder.java",
"license": "gpl-2.0",
"size": 72218
} | [
"org.compiere.process.DocAction"
] | import org.compiere.process.DocAction; | import org.compiere.process.*; | [
"org.compiere.process"
] | org.compiere.process; | 475,737 |
public static void saveCourse(final Long resourceableId) {
if (resourceableId == null) { throw new AssertException("No resourceable ID found."); } | static void function(final Long resourceableId) { if (resourceableId == null) { throw new AssertException(STR); } | /**
* Stores the editor tree model AND the run structure (both xml files). Called at publish.
*
* @param resourceableId
*/ | Stores the editor tree model AND the run structure (both xml files). Called at publish | saveCourse | {
"repo_name": "RLDevOps/Demo",
"path": "src/main/java/org/olat/course/CourseFactory.java",
"license": "apache-2.0",
"size": 50856
} | [
"org.olat.core.logging.AssertException"
] | import org.olat.core.logging.AssertException; | import org.olat.core.logging.*; | [
"org.olat.core"
] | org.olat.core; | 602,631 |
public interface PDPEngine {
Response decide(Request pepRequest) throws PDPException; | interface PDPEngine { Response function(Request pepRequest) throws PDPException; | /**
* Evaluates the given {@link org.apache.openaz.xacml.api.Request} using this <code>PDPEngine</code>'s
* Policy Sets to determine if the given <code>Request</code> is allowed.
*
* @param pepRequest the <code>Request</code> to evaluate
* @return a {@link org.apache.openaz.xacml.api.Response} indicating the decision
*/ | Evaluates the given <code>org.apache.openaz.xacml.api.Request</code> using this <code>PDPEngine</code>'s Policy Sets to determine if the given <code>Request</code> is allowed | decide | {
"repo_name": "phrinx/incubator-openaz",
"path": "openaz-xacml/src/main/java/org/apache/openaz/xacml/api/pdp/PDPEngine.java",
"license": "apache-2.0",
"size": 2612
} | [
"org.apache.openaz.xacml.api.Request",
"org.apache.openaz.xacml.api.Response"
] | import org.apache.openaz.xacml.api.Request; import org.apache.openaz.xacml.api.Response; | import org.apache.openaz.xacml.api.*; | [
"org.apache.openaz"
] | org.apache.openaz; | 1,453,354 |
public void setDayFormatter(DateTimeFormat dayFormatter) {
this.dayFormatter = dayFormatter;
refresh();
} | void function(DateTimeFormat dayFormatter) { this.dayFormatter = dayFormatter; refresh(); } | /**
* Defines the formatter used to display the title of each cell.<br>
* <br>
* The default format is "<code>DayNumber</code>" (pattern : "d").
*
* @param dayFormatter
* The formatter to use to display the title of each cell.
*/ | Defines the formatter used to display the title of each cell. The default format is "<code>DayNumber</code>" (pattern : "d") | setDayFormatter | {
"repo_name": "Raphcal/sigmah",
"path": "src/main/java/org/sigmah/client/ui/widget/CalendarWidget.java",
"license": "gpl-3.0",
"size": 24453
} | [
"com.google.gwt.i18n.client.DateTimeFormat"
] | import com.google.gwt.i18n.client.DateTimeFormat; | import com.google.gwt.i18n.client.*; | [
"com.google.gwt"
] | com.google.gwt; | 153,681 |
public FloatBuffer calcFaceNormals() {
FloatBuffer normals = FloatBuffer.allocate((size.width-1)*(size.height-1)*
2*VERTICES_PER_FACE*3);
int i0, i1, i2, i3;
for (int z = 0; z < size.height-1; ++z) {
for (int x = 0; x < size.width-1; ++x) {
i0 = x + z * size.width;
i1 = i0 + size.width;
i2 = i0 + size.width + 1;
i3 = i0 + 1;
Vec3 normal1 = Vec3.getNormal(meshPositions.get(i0),
meshPositions.get(i1), meshPositions.get(i3));
Vec3 normal2 = Vec3.getNormal(meshPositions.get(i1),
meshPositions.get(i2), meshPositions.get(i3));
// For face normals, we must duplicate normals for each vertex
// of each face
float[] nf1 = normal1.normalise().toFloatArray();
float[] nf2 = normal2.normalise().toFloatArray();
normals.put(nf1).put(nf1).put(nf1);
normals.put(nf2).put(nf2).put(nf2);
}
}
normals.rewind();
return normals;
} | FloatBuffer function() { FloatBuffer normals = FloatBuffer.allocate((size.width-1)*(size.height-1)* 2*VERTICES_PER_FACE*3); int i0, i1, i2, i3; for (int z = 0; z < size.height-1; ++z) { for (int x = 0; x < size.width-1; ++x) { i0 = x + z * size.width; i1 = i0 + size.width; i2 = i0 + size.width + 1; i3 = i0 + 1; Vec3 normal1 = Vec3.getNormal(meshPositions.get(i0), meshPositions.get(i1), meshPositions.get(i3)); Vec3 normal2 = Vec3.getNormal(meshPositions.get(i1), meshPositions.get(i2), meshPositions.get(i3)); float[] nf1 = normal1.normalise().toFloatArray(); float[] nf2 = normal2.normalise().toFloatArray(); normals.put(nf1).put(nf1).put(nf1); normals.put(nf2).put(nf2).put(nf2); } } normals.rewind(); return normals; } | /**
* Calculates face normals and populates the normals buffer.
* Must be called after terrain mesh positions are all set.
*/ | Calculates face normals and populates the normals buffer. Must be called after terrain mesh positions are all set | calcFaceNormals | {
"repo_name": "kgkma/glenn-greenworld",
"path": "src/ass2/spec/Terrain.java",
"license": "mit",
"size": 12504
} | [
"java.nio.FloatBuffer"
] | import java.nio.FloatBuffer; | import java.nio.*; | [
"java.nio"
] | java.nio; | 323,895 |
public void accept(final SocketChannel socketChannel) throws IOException {
try {
if (socketChannel.isConnectionPending()) {
socketChannel.finishConnect();
} // end of if (socketChannel.isConnecyionPending())
socketIO = new SocketIO(socketChannel);
} catch (IOException e) {
String host = (String) sessionData.get("remote-hostname");
if (host == null) {
host = (String) sessionData.get("remote-host");
}
String sock_str = null;
try {
sock_str = socketChannel.socket().toString();
} catch (Exception ex) {
sock_str = ex.toString();
}
log.log(Level.FINER,
"Problem connecting to remote host: {0}, address: {1}, socket: {2} - exception: {3}, session data: {4}",
new Object[] { host,
remote_address, sock_str, e, sessionData });
throw e;
}
socketInputSize = socketIO.getSocketChannel().socket().getReceiveBufferSize();
socketInput = ByteBuffer.allocate(socketInputSize);
socketInput.order(byteOrder());
Socket sock = socketIO.getSocketChannel().socket();
local_address = sock.getLocalAddress().getHostAddress();
remote_address = sock.getInetAddress().getHostAddress();
id = local_address + "_" + sock.getLocalPort() + "_" + remote_address + "_" + sock
.getPort();
setLastTransferTime();
}
| void function(final SocketChannel socketChannel) throws IOException { try { if (socketChannel.isConnectionPending()) { socketChannel.finishConnect(); } socketIO = new SocketIO(socketChannel); } catch (IOException e) { String host = (String) sessionData.get(STR); if (host == null) { host = (String) sessionData.get(STR); } String sock_str = null; try { sock_str = socketChannel.socket().toString(); } catch (Exception ex) { sock_str = ex.toString(); } log.log(Level.FINER, STR, new Object[] { host, remote_address, sock_str, e, sessionData }); throw e; } socketInputSize = socketIO.getSocketChannel().socket().getReceiveBufferSize(); socketInput = ByteBuffer.allocate(socketInputSize); socketInput.order(byteOrder()); Socket sock = socketIO.getSocketChannel().socket(); local_address = sock.getLocalAddress().getHostAddress(); remote_address = sock.getInetAddress().getHostAddress(); id = local_address + "_" + sock.getLocalPort() + "_" + remote_address + "_" + sock .getPort(); setLastTransferTime(); } | /**
* Method
* <code>accept</code> is used to perform
*
* @param socketChannel a
* <code>SocketChannel</code> value
*
* @throws IOException
*/ | Method <code>accept</code> is used to perform | accept | {
"repo_name": "DanielYao/tigase-server",
"path": "src/main/java/tigase/net/IOService.java",
"license": "agpl-3.0",
"size": 37091
} | [
"java.io.IOException",
"java.net.Socket",
"java.nio.ByteBuffer",
"java.nio.channels.SocketChannel",
"java.util.logging.Level"
] | import java.io.IOException; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.logging.Level; | import java.io.*; import java.net.*; import java.nio.*; import java.nio.channels.*; import java.util.logging.*; | [
"java.io",
"java.net",
"java.nio",
"java.util"
] | java.io; java.net; java.nio; java.util; | 1,143,431 |
public static void writeInt16(OutputStream out, int int16) {
try {
out.write(int16 / 256);
out.write(int16 % 256);
} catch (Exception e) {
throw new InternalError("writing int16 in file," + e);
}
}
| static void function(OutputStream out, int int16) { try { out.write(int16 / 256); out.write(int16 % 256); } catch (Exception e) { throw new InternalError(STR + e); } } | /**
* Write the specified positive short coded on 2 bytes to the specified input
* stream
*
* @param out
* is the output stream where the specified integer would be written
* @param int16
* the 2 bytes integer to write
*/ | Write the specified positive short coded on 2 bytes to the specified input stream | writeInt16 | {
"repo_name": "JoeyLeeuwinga/Firemox",
"path": "src/main/java/net/sf/firemox/tools/MToolKit.java",
"license": "gpl-2.0",
"size": 41062
} | [
"java.io.OutputStream"
] | import java.io.OutputStream; | import java.io.*; | [
"java.io"
] | java.io; | 1,974,625 |
public Attribute withInnerSchema(Schema innerSchema) {
return new Attribute(this, getNamespace(), getName(), getValue(),
getCondition(), Preconditions.checkNotNull(innerSchema));
} | Attribute function(Schema innerSchema) { return new Attribute(this, getNamespace(), getName(), getValue(), getCondition(), Preconditions.checkNotNull(innerSchema)); } | /**
* Helper for transforming an {@code Attribute}'s innerSchema.
*/ | Helper for transforming an Attribute's innerSchema | withInnerSchema | {
"repo_name": "xenomachina/gxp",
"path": "java/src/com/google/gxp/compiler/reparent/Attribute.java",
"license": "apache-2.0",
"size": 6104
} | [
"com.google.common.base.Preconditions",
"com.google.gxp.compiler.schema.Schema"
] | import com.google.common.base.Preconditions; import com.google.gxp.compiler.schema.Schema; | import com.google.common.base.*; import com.google.gxp.compiler.schema.*; | [
"com.google.common",
"com.google.gxp"
] | com.google.common; com.google.gxp; | 2,665,153 |
private static BytesRef encodeBase64Id(String id) {
byte[] b = Base64.getUrlDecoder().decode(id);
if (Byte.toUnsignedInt(b[0]) >= BASE64_ESCAPE) {
byte[] newB = new byte[b.length + 1];
newB[0] = (byte) BASE64_ESCAPE;
System.arraycopy(b, 0, newB, 1, b.length);
b = newB;
}
return new BytesRef(b, 0, b.length);
} | static BytesRef function(String id) { byte[] b = Base64.getUrlDecoder().decode(id); if (Byte.toUnsignedInt(b[0]) >= BASE64_ESCAPE) { byte[] newB = new byte[b.length + 1]; newB[0] = (byte) BASE64_ESCAPE; System.arraycopy(b, 0, newB, 1, b.length); b = newB; } return new BytesRef(b, 0, b.length); } | /** With base64 ids, we decode and prepend an escape char in the cases that
* it could be mixed up with numeric or utf8 encoding. In the majority of
* cases (253/256) the encoded id is exactly the binary form. */ | With base64 ids, we decode and prepend an escape char in the cases that it could be mixed up with numeric or utf8 encoding. In the majority of | encodeBase64Id | {
"repo_name": "rajanm/elasticsearch",
"path": "server/src/main/java/org/elasticsearch/index/mapper/Uid.java",
"license": "apache-2.0",
"size": 9164
} | [
"java.util.Base64",
"org.apache.lucene.util.BytesRef"
] | import java.util.Base64; import org.apache.lucene.util.BytesRef; | import java.util.*; import org.apache.lucene.util.*; | [
"java.util",
"org.apache.lucene"
] | java.util; org.apache.lucene; | 1,173,503 |
private void writeAsterixConfig(Cluster cluster) throws FileNotFoundException, IOException {
String metadataNodeId = Utils.getMetadataNode(cluster).getId();
String asterixInstanceName = instanceName;
AsterixConfiguration configuration = locateConfig();
readConfigParams(configuration);
String version = Utils.getAsterixVersionFromClasspath();
configuration.setVersion(version);
configuration.setInstanceName(asterixInstanceName);
List<Store> stores = new ArrayList<Store>();
String storeDir = cluster.getStore().trim();
for (Node node : cluster.getNode()) {
String iodevices = node.getIodevices() == null ? cluster.getIodevices() : node.getIodevices();
String[] nodeIdDevice = iodevices.split(",");
StringBuilder nodeStores = new StringBuilder();
for (int i = 0; i < nodeIdDevice.length; i++) {
nodeStores.append(nodeIdDevice[i] + File.separator + storeDir + ",");
}
//remove last comma
nodeStores.deleteCharAt(nodeStores.length() - 1);
stores.add(new Store(node.getId(), nodeStores.toString()));
}
configuration.setStore(stores);
List<Coredump> coredump = new ArrayList<Coredump>();
String coredumpdir = null;
List<TransactionLogDir> txnLogDirs = new ArrayList<TransactionLogDir>();
String txnLogDir = null;
for (Node node : cluster.getNode()) {
coredumpdir = node.getLogDir() == null ? cluster.getLogDir() : node.getLogDir();
coredump.add(new Coredump(node.getId(), coredumpdir + "coredump" + File.separator));
txnLogDir = node.getTxnLogDir() == null ? cluster.getTxnLogDir() : node.getTxnLogDir(); //node or cluster-wide
txnLogDirs.add(new TransactionLogDir(node.getId(), txnLogDir
+ (txnLogDir.charAt(txnLogDir.length() - 1) == File.separatorChar ? File.separator : "")
+ "txnLogs" //if the string doesn't have a trailing / add one
+ File.separator));
}
configuration.setMetadataNode(metadataNodeId);
configuration.setCoredump(coredump);
configuration.setTransactionLogDir(txnLogDirs);
FileOutputStream os = new FileOutputStream(MERGED_PARAMETERS_PATH);
try {
JAXBContext ctx = JAXBContext.newInstance(AsterixConfiguration.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(configuration, os);
} catch (JAXBException e) {
throw new IOException(e);
} finally {
os.close();
}
} | void function(Cluster cluster) throws FileNotFoundException, IOException { String metadataNodeId = Utils.getMetadataNode(cluster).getId(); String asterixInstanceName = instanceName; AsterixConfiguration configuration = locateConfig(); readConfigParams(configuration); String version = Utils.getAsterixVersionFromClasspath(); configuration.setVersion(version); configuration.setInstanceName(asterixInstanceName); List<Store> stores = new ArrayList<Store>(); String storeDir = cluster.getStore().trim(); for (Node node : cluster.getNode()) { String iodevices = node.getIodevices() == null ? cluster.getIodevices() : node.getIodevices(); String[] nodeIdDevice = iodevices.split(","); StringBuilder nodeStores = new StringBuilder(); for (int i = 0; i < nodeIdDevice.length; i++) { nodeStores.append(nodeIdDevice[i] + File.separator + storeDir + ","); } nodeStores.deleteCharAt(nodeStores.length() - 1); stores.add(new Store(node.getId(), nodeStores.toString())); } configuration.setStore(stores); List<Coredump> coredump = new ArrayList<Coredump>(); String coredumpdir = null; List<TransactionLogDir> txnLogDirs = new ArrayList<TransactionLogDir>(); String txnLogDir = null; for (Node node : cluster.getNode()) { coredumpdir = node.getLogDir() == null ? cluster.getLogDir() : node.getLogDir(); coredump.add(new Coredump(node.getId(), coredumpdir + STR + File.separator)); txnLogDir = node.getTxnLogDir() == null ? cluster.getTxnLogDir() : node.getTxnLogDir(); txnLogDirs.add(new TransactionLogDir(node.getId(), txnLogDir + (txnLogDir.charAt(txnLogDir.length() - 1) == File.separatorChar ? File.separator : STRtxnLogs" + File.separator)); } configuration.setMetadataNode(metadataNodeId); configuration.setCoredump(coredump); configuration.setTransactionLogDir(txnLogDirs); FileOutputStream os = new FileOutputStream(MERGED_PARAMETERS_PATH); try { JAXBContext ctx = JAXBContext.newInstance(AsterixConfiguration.class); Marshaller marshaller = ctx.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(configuration, os); } catch (JAXBException e) { throw new IOException(e); } finally { os.close(); } } | /**
* Retrieves necessary information from the cluster configuration and splices it into the Asterix configuration parameters
*
* @param cluster
* @throws FileNotFoundException
* @throws IOException
*/ | Retrieves necessary information from the cluster configuration and splices it into the Asterix configuration parameters | writeAsterixConfig | {
"repo_name": "heriram/incubator-asterixdb",
"path": "asterixdb/asterix-yarn/src/main/java/org/apache/asterix/aoya/AsterixYARNClient.java",
"license": "apache-2.0",
"size": 60691
} | [
"java.io.File",
"java.io.FileNotFoundException",
"java.io.FileOutputStream",
"java.io.IOException",
"java.util.ArrayList",
"java.util.List",
"javax.xml.bind.JAXBContext",
"javax.xml.bind.JAXBException",
"javax.xml.bind.Marshaller",
"org.apache.asterix.common.configuration.AsterixConfiguration",
"org.apache.asterix.common.configuration.Coredump",
"org.apache.asterix.common.configuration.Store",
"org.apache.asterix.common.configuration.TransactionLogDir",
"org.apache.asterix.event.schema.yarnCluster.Cluster",
"org.apache.asterix.event.schema.yarnCluster.Node"
] | import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.apache.asterix.common.configuration.AsterixConfiguration; import org.apache.asterix.common.configuration.Coredump; import org.apache.asterix.common.configuration.Store; import org.apache.asterix.common.configuration.TransactionLogDir; import org.apache.asterix.event.schema.yarnCluster.Cluster; import org.apache.asterix.event.schema.yarnCluster.Node; | import java.io.*; import java.util.*; import javax.xml.bind.*; import org.apache.asterix.common.configuration.*; import org.apache.asterix.event.schema.*; | [
"java.io",
"java.util",
"javax.xml",
"org.apache.asterix"
] | java.io; java.util; javax.xml; org.apache.asterix; | 562,108 |
@Override
protected void setHeightAndWidth() {
stacks = MathHelper.ceiling_float_int(amount / (layers.getAmount() - 1) / maxPerRow);
stackSpace = Math.max(maxStackSpace - (stacks - 1), minStackSpace);
switch(orientation) {
case RIGHT:
case LEFT:
height = (stacks - 1)*stackSpace + layers.getHeight();
width = space*(maxPerRow - 1) + layers.getWidth();
break;
case DOWN:
case UP:
height = space*(maxPerRow - 1) + layers.getHeight();
width = (stacks - 1)*stackSpace + layers.getWidth();
break;
}
}
| void function() { stacks = MathHelper.ceiling_float_int(amount / (layers.getAmount() - 1) / maxPerRow); stackSpace = Math.max(maxStackSpace - (stacks - 1), minStackSpace); switch(orientation) { case RIGHT: case LEFT: height = (stacks - 1)*stackSpace + layers.getHeight(); width = space*(maxPerRow - 1) + layers.getWidth(); break; case DOWN: case UP: height = space*(maxPerRow - 1) + layers.getHeight(); width = (stacks - 1)*stackSpace + layers.getWidth(); break; } } | /**
* Sets Height and Width of the gauge based on the orientation.
* Also, sets Icon Gauge specific settings.
*/ | Sets Height and Width of the gauge based on the orientation. Also, sets Icon Gauge specific settings | setHeightAndWidth | {
"repo_name": "BinaryAura/Customize",
"path": "src/main/java/net/binaryaura/customize/client/gui/huditem/HudItemIconGauge.java",
"license": "mit",
"size": 11558
} | [
"net.minecraft.util.MathHelper"
] | import net.minecraft.util.MathHelper; | import net.minecraft.util.*; | [
"net.minecraft.util"
] | net.minecraft.util; | 635,255 |
private String getContentFromFile(String fileName) throws IOException {
StringBuilder contents = new StringBuilder(1024);
BufferedReader input = new BufferedReader(new InputStreamReader(TestDynamicValueReplacement.class
.getResourceAsStream(fileName), Charsets.UTF_8));
try {
String line = null;
while ((line = input.readLine()) != null) {
contents.append(line);
}
} finally {
input.close();
}
return contents.toString();
} | String function(String fileName) throws IOException { StringBuilder contents = new StringBuilder(1024); BufferedReader input = new BufferedReader(new InputStreamReader(TestDynamicValueReplacement.class .getResourceAsStream(fileName), Charsets.UTF_8)); try { String line = null; while ((line = input.readLine()) != null) { contents.append(line); } } finally { input.close(); } return contents.toString(); } | /**
* gets file content as a String
* @return String Object which contain file data
* @throws IOException
*/ | gets file content as a String | getContentFromFile | {
"repo_name": "NicolasEYSSERIC/Silverpeas-Core",
"path": "lib-core/src/test/java/com/silverpeas/wysiwyg/dynamicvalue/TestDynamicValueReplacement.java",
"license": "agpl-3.0",
"size": 3928
} | [
"java.io.BufferedReader",
"java.io.IOException",
"java.io.InputStreamReader",
"org.silverpeas.util.Charsets"
] | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.silverpeas.util.Charsets; | import java.io.*; import org.silverpeas.util.*; | [
"java.io",
"org.silverpeas.util"
] | java.io; org.silverpeas.util; | 1,016,070 |
public static byte[] tryDecompress(byte[] raw) throws Exception {
if (!isGzipStream(raw)) {
return raw;
}
GZIPInputStream gis = null;
ByteArrayOutputStream out = null;
try {
gis = new GZIPInputStream(new ByteArrayInputStream(raw));
out = new ByteArrayOutputStream();
IoUtils.copy(gis, out);
return out.toByteArray();
} finally {
closeQuietly(out);
closeQuietly(gis);
}
} | static byte[] function(byte[] raw) throws Exception { if (!isGzipStream(raw)) { return raw; } GZIPInputStream gis = null; ByteArrayOutputStream out = null; try { gis = new GZIPInputStream(new ByteArrayInputStream(raw)); out = new ByteArrayOutputStream(); IoUtils.copy(gis, out); return out.toByteArray(); } finally { closeQuietly(out); closeQuietly(gis); } } | /**
* Try decompress by GZIP from byte array.
*
* @param raw compressed byte array
* @return byte array after decompress
* @throws Exception exception
*/ | Try decompress by GZIP from byte array | tryDecompress | {
"repo_name": "alibaba/nacos",
"path": "common/src/main/java/com/alibaba/nacos/common/utils/IoUtils.java",
"license": "apache-2.0",
"size": 10944
} | [
"java.io.ByteArrayInputStream",
"java.io.ByteArrayOutputStream",
"java.util.zip.GZIPInputStream"
] | import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.zip.GZIPInputStream; | import java.io.*; import java.util.zip.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 1,799,396 |
public static void writeLong(long value, OutputStream out) throws IOException {
out.write((int) (value >>> 56));
out.write((int) (value >>> 48));
out.write((int) (value >>> 40));
out.write((int) (value >>> 32));
out.write((int) (value >>> 24));
out.write((int) (value >>> 16));
out.write((int) (value >>> 8));
out.write((int) value);
} | static void function(long value, OutputStream out) throws IOException { out.write((int) (value >>> 56)); out.write((int) (value >>> 48)); out.write((int) (value >>> 40)); out.write((int) (value >>> 32)); out.write((int) (value >>> 24)); out.write((int) (value >>> 16)); out.write((int) (value >>> 8)); out.write((int) value); } | /**
* Write an 8-byte integer value to the output stream.
* @param value The value to write.
* @param out The output stream to write to.
* @throws IOException If an error occurs writing to the stream.
*/ | Write an 8-byte integer value to the output stream | writeLong | {
"repo_name": "oranoceallaigh/smppapi",
"path": "src/main/java/com/adenki/smpp/util/SMPPIO.java",
"license": "bsd-3-clause",
"size": 10405
} | [
"java.io.IOException",
"java.io.OutputStream"
] | import java.io.IOException; import java.io.OutputStream; | import java.io.*; | [
"java.io"
] | java.io; | 314,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.