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
protected void checkWriter() { Assert.state(writer == null, "cannot create multiple writers for the same snapshot"); }
void function() { Assert.state(writer == null, STR); }
/** * Checks that the snapshot can be written. */
Checks that the snapshot can be written
checkWriter
{ "repo_name": "atomix/copycat", "path": "server/src/main/java/io/atomix/copycat/server/storage/snapshot/Snapshot.java", "license": "apache-2.0", "size": 6181 }
[ "io.atomix.catalyst.util.Assert" ]
import io.atomix.catalyst.util.Assert;
import io.atomix.catalyst.util.*;
[ "io.atomix.catalyst" ]
io.atomix.catalyst;
2,026,771
public final RecordValue fUnboxed2S(final RTValue recordDictionary, final RTValue x, final RTExecutionContext $ec) throws CALExecutorException { $ec.incrementNMethodCalls(); if (LECCMachineConfiguration.generateDebugCode() && $ec.isDebugProcessingNeeded(getQualifiedName())) { $ec.debugProcessing(getQualifiedName(), new RTValue[]{recordDictionary, x}); } //recordToJMapPrimitive recordDictionary x. //the compiler ensures that the 2 record arguments all have the same fields. //must iterate in a deterministic order over the field names (as specified by FieldName.CalSourceFormComparator) //so that the function is well-defined in the presence of side effects. //If f is a field, then recordDictionary.f is the dictionary for use when calling the class method Prelude.output on //the value x.f. final RTRecordValue recordDict = (RTRecordValue)recordDictionary; final RTRecordValue xRecord = (RTRecordValue)x; final RecordValue resultMap = RecordValueImpl.make(); final int nFields = recordDict.getNFields(); for (int i = 0; i < nFields; ++i) { final FieldName fieldName = recordDict.getNthFieldName(i); //RTValue fieldDict = recordDictionary.getNthValue(i); //RTValue xField = xRecord.getNthValue(i); //compute "Prelude.output fieldDict xField" //this is just (after inlining Prelude.output d = d" //fieldDict xField final Object fieldValue = recordDict.getNthValue(i).apply(xRecord.getNthValue(i)).evaluate($ec).getOpaqueValue(); resultMap.put(fieldName, fieldValue); } return resultMap; } /** * {@inheritDoc}
final RecordValue function(final RTValue recordDictionary, final RTValue x, final RTExecutionContext $ec) throws CALExecutorException { $ec.incrementNMethodCalls(); if (LECCMachineConfiguration.generateDebugCode() && $ec.isDebugProcessingNeeded(getQualifiedName())) { $ec.debugProcessing(getQualifiedName(), new RTValue[]{recordDictionary, x}); } final RTRecordValue recordDict = (RTRecordValue)recordDictionary; final RTRecordValue xRecord = (RTRecordValue)x; final RecordValue resultMap = RecordValueImpl.make(); final int nFields = recordDict.getNFields(); for (int i = 0; i < nFields; ++i) { final FieldName fieldName = recordDict.getNthFieldName(i); final Object fieldValue = recordDict.getNthValue(i).apply(xRecord.getNthValue(i)).evaluate($ec).getOpaqueValue(); resultMap.put(fieldName, fieldValue); } return resultMap; } /** * {@inheritDoc}
/** * This is the version of the function logic that directly returns an unboxed value. * All functions whose return types can be unboxed should have a version of the function * logic which returns an unboxed value. * @param recordDictionary * @param x * @param $ec * @return RecordValue * @throws CALExecutorException */
This is the version of the function logic that directly returns an unboxed value. All functions whose return types can be unboxed should have a version of the function logic which returns an unboxed value
fUnboxed2S
{ "repo_name": "levans/Open-Quark", "path": "src/CAL_Runtime/src/org/openquark/cal/internal/runtime/lecc/functions/RTRecordToJRecordValuePrimitive.java", "license": "bsd-3-clause", "size": 7342 }
[ "org.openquark.cal.compiler.FieldName", "org.openquark.cal.internal.runtime.RecordValueImpl", "org.openquark.cal.internal.runtime.lecc.LECCMachineConfiguration", "org.openquark.cal.internal.runtime.lecc.RTExecutionContext", "org.openquark.cal.internal.runtime.lecc.RTRecordValue", "org.openquark.cal.internal.runtime.lecc.RTValue", "org.openquark.cal.runtime.CALExecutorException", "org.openquark.cal.runtime.RecordValue" ]
import org.openquark.cal.compiler.FieldName; import org.openquark.cal.internal.runtime.RecordValueImpl; import org.openquark.cal.internal.runtime.lecc.LECCMachineConfiguration; import org.openquark.cal.internal.runtime.lecc.RTExecutionContext; import org.openquark.cal.internal.runtime.lecc.RTRecordValue; import org.openquark.cal.internal.runtime.lecc.RTValue; import org.openquark.cal.runtime.CALExecutorException; import org.openquark.cal.runtime.RecordValue;
import org.openquark.cal.compiler.*; import org.openquark.cal.internal.runtime.*; import org.openquark.cal.internal.runtime.lecc.*; import org.openquark.cal.runtime.*;
[ "org.openquark.cal" ]
org.openquark.cal;
1,486,586
public static List<String> getStringAsWords(String text) { return Arrays.asList(text.split("[\\s,;]+")); }
static List<String> function(String text) { return Arrays.asList(text.split(STR)); }
/** * Returns a list of words contained in the given text. * Whitespace, comma and semicolon are considered as separator between words. * * @param text the input * @return a list of words */
Returns a list of words contained in the given text. Whitespace, comma and semicolon are considered as separator between words
getStringAsWords
{ "repo_name": "jhshinn/jabref", "path": "src/main/java/org/jabref/model/strings/StringUtil.java", "license": "mit", "size": 23912 }
[ "java.util.Arrays", "java.util.List" ]
import java.util.Arrays; import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
2,574,213
public String getApiVersion() { return Optional.ofNullable(this.apiVersion).orElse(DEFAULT_API_VERSION); }
String function() { return Optional.ofNullable(this.apiVersion).orElse(DEFAULT_API_VERSION); }
/** * Version metadata intended for a parser. Typically "v1". * * @return */
Version metadata intended for a parser. Typically "v1"
getApiVersion
{ "repo_name": "elastisys/scale.cloudpool", "path": "kubernetes/src/main/java/com/elastisys/scale/cloudpool/kubernetes/config/kubeconfig/KubeConfig.java", "license": "apache-2.0", "size": 10829 }
[ "java.util.Optional" ]
import java.util.Optional;
import java.util.*;
[ "java.util" ]
java.util;
1,965,965
@Override public final void onWebsocketMessage( WebSocket conn, String message ) { onMessage( message ); }
final void function( WebSocket conn, String message ) { onMessage( message ); }
/** * Calls subclass' implementation of <var>onMessage</var>. * * @param conn * @param message */
Calls subclass' implementation of onMessage
onWebsocketMessage
{ "repo_name": "Foricher/Java-WebSocket-Android-SSL", "path": "src/main/java/org/java_websocket/client/WebSocketClient.java", "license": "mit", "size": 13762 }
[ "org.java_websocket.WebSocket" ]
import org.java_websocket.WebSocket;
import org.java_websocket.*;
[ "org.java_websocket" ]
org.java_websocket;
2,189,206
List<ParticipantId> getParticipants();
List<ParticipantId> getParticipants();
/** * An immutable list of this wave's participants, in the order in which * they were added. * * @return the wave's participants. */
An immutable list of this wave's participants, in the order in which they were added
getParticipants
{ "repo_name": "vega113/incubator-wave", "path": "wave/src/main/java/org/waveprotocol/wave/model/wave/data/core/CoreWaveletData.java", "license": "apache-2.0", "size": 2830 }
[ "java.util.List", "org.waveprotocol.wave.model.wave.ParticipantId" ]
import java.util.List; import org.waveprotocol.wave.model.wave.ParticipantId;
import java.util.*; import org.waveprotocol.wave.model.wave.*;
[ "java.util", "org.waveprotocol.wave" ]
java.util; org.waveprotocol.wave;
1,520,032
public String toString() { return Parm.getIndent() + "<item mark=\"" + markedSymbol.getEntity() + "\"" + " pos=\"" + position + "\"" + " act=\"" + parserActions[action] + "\"" + ((successor != null) ? (" successor=\"" + successor .getId() + "\"") : "") + ">" + ((production != null) ? (production.legible(position)) : "") + "</item>" + Parm.getNewline() ; } // toString
String function() { return Parm.getIndent() + STRSTR\STR pos=\STR\STR act=\STR\STR successor=\STR\STRSTR>STRSTR</item>" + Parm.getNewline() ; }
/** Returns an XML description of the object * @return XML element representing the item */
Returns an XML description of the object
toString
{ "repo_name": "gfis/jextra", "path": "src/main/java/org/teherba/jextra/gener/Item.java", "license": "apache-2.0", "size": 9063 }
[ "org.teherba.jextra.Parm" ]
import org.teherba.jextra.Parm;
import org.teherba.jextra.*;
[ "org.teherba.jextra" ]
org.teherba.jextra;
62,463
public int getStackTaskCount() { ArrayList<Task> tasks = mStackTaskList.getTasks(); int stackCount = 0; int taskCount = tasks.size(); for (int i = 0; i < taskCount; i++) { Task task = tasks.get(i); if (!task.isFreeformTask()) { stackCount++; } } return stackCount; }
int function() { ArrayList<Task> tasks = mStackTaskList.getTasks(); int stackCount = 0; int taskCount = tasks.size(); for (int i = 0; i < taskCount; i++) { Task task = tasks.get(i); if (!task.isFreeformTask()) { stackCount++; } } return stackCount; }
/** * Returns the number of stack tasks. */
Returns the number of stack tasks
getStackTaskCount
{ "repo_name": "xorware/android_frameworks_base", "path": "packages/SystemUI/src/com/android/systemui/recents/model/TaskStack.java", "license": "apache-2.0", "size": 41505 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
1,420,442
public void reset() { resetJobControl(); resetPageControl(); resetFontSelection(); resetFontManagement(); resetMacro(); resetRectangularAreaFill(); resetRasterGraphics(); resetTroubleshootingCommands(); resetStatusReadback(); _fontSet = PRIMARY_SET; _activeLanguage = Language.PCL5; _rasterMode = CommonPrinterState.RasterMode.PhysicalPage; _column = 0; _x = 0; _y = 0; _graphicsMode = false; _frameAnchorPoint = new Point(0, 0); _userDefinedPatterns = new HashMap(); _environment = new HashMap(); _rasterHeight = 0; _rasterWidth = 0; }
void function() { resetJobControl(); resetPageControl(); resetFontSelection(); resetFontManagement(); resetMacro(); resetRectangularAreaFill(); resetRasterGraphics(); resetTroubleshootingCommands(); resetStatusReadback(); _fontSet = PRIMARY_SET; _activeLanguage = Language.PCL5; _rasterMode = CommonPrinterState.RasterMode.PhysicalPage; _column = 0; _x = 0; _y = 0; _graphicsMode = false; _frameAnchorPoint = new Point(0, 0); _userDefinedPatterns = new HashMap(); _environment = new HashMap(); _rasterHeight = 0; _rasterWidth = 0; }
/** * Resets printer state Factory Default Print Environment Feature Settings * (PCL) * * @see bpl13205.pdf */
Resets printer state Factory Default Print Environment Feature Settings (PCL)
reset
{ "repo_name": "sigram/pcl-parser", "path": "src/java/org/getopt/pcl5/PrinterState.java", "license": "apache-2.0", "size": 37729 }
[ "java.awt.Point", "java.util.HashMap" ]
import java.awt.Point; import java.util.HashMap;
import java.awt.*; import java.util.*;
[ "java.awt", "java.util" ]
java.awt; java.util;
888,773
public CourseGroupManager getCourseGroupManager();
CourseGroupManager function();
/** * Get the course group management environment * * @return The course group management */
Get the course group management environment
getCourseGroupManager
{ "repo_name": "huihoo/olat", "path": "OLAT-LMS/src/main/java/org/olat/lms/course/run/environment/CourseEnvironment.java", "license": "apache-2.0", "size": 3907 }
[ "org.olat.lms.group.learn.CourseGroupManager" ]
import org.olat.lms.group.learn.CourseGroupManager;
import org.olat.lms.group.learn.*;
[ "org.olat.lms" ]
org.olat.lms;
1,890,269
public void react(long now, Simulator sim, Object todo) { // if an input has changed ... if (todo == null) { // find a matching row of the truth table int matchingRow = -1; int cols = inputNames.size(); for (int row=0; row<rows; row+=1) { boolean match = true; for (int col=0; col<cols; col+=1) { if (table[row][col] == 2) continue; BitSet inb = inputs.get(col).getValue(); if (inb == null) inb = new BitSet(); int inputValue = inb.get(0) ? 1 : 0; if (inputValue != table[row][col]) { match = false; break; } } if (match) { matchingRow = row; break; } } //System.out.println("matched row " + matchingRow); // for each output value... int offset = inputNames.size(); int pos = 0; for (int i = 0; i < outputs.size(); i++) { // if it is different than the value propagating through // this circuit, then post an event int outValue = table[matchingRow][pos+offset]; // don't care becomes false if (outValue == 2) outValue = 0; if (outValue != toBeValue[pos]) { toBeValue[pos] = outValue; BitSet val = new BitSet(1); if (outValue == 1) val.set(0); Out out = new Out(); out.position = pos; out.value = val; sim.post(new SimEvent(now+propDelay,this,out)); } pos += 1; } } else { // get the new output Out newOut = (Out)todo; // send to output Output out = outputs.get(newOut.position); BitSet val = newOut.value; BitSet newVal = (BitSet)val.clone(); out.propagate(newVal,now,sim); } } // end of react method
void function(long now, Simulator sim, Object todo) { if (todo == null) { int matchingRow = -1; int cols = inputNames.size(); for (int row=0; row<rows; row+=1) { boolean match = true; for (int col=0; col<cols; col+=1) { if (table[row][col] == 2) continue; BitSet inb = inputs.get(col).getValue(); if (inb == null) inb = new BitSet(); int inputValue = inb.get(0) ? 1 : 0; if (inputValue != table[row][col]) { match = false; break; } } if (match) { matchingRow = row; break; } } int offset = inputNames.size(); int pos = 0; for (int i = 0; i < outputs.size(); i++) { int outValue = table[matchingRow][pos+offset]; if (outValue == 2) outValue = 0; if (outValue != toBeValue[pos]) { toBeValue[pos] = outValue; BitSet val = new BitSet(1); if (outValue == 1) val.set(0); Out out = new Out(); out.position = pos; out.value = val; sim.post(new SimEvent(now+propDelay,this,out)); } pos += 1; } } else { Out newOut = (Out)todo; Output out = outputs.get(newOut.position); BitSet val = newOut.value; BitSet newVal = (BitSet)val.clone(); out.propagate(newVal,now,sim); } }
/** * React to an event. * * @param now The current simulation time. * @param sim The simulator to post events to. * @param todo If null, an input has changed, otherwise it is the value to output. */
React to an event
react
{ "repo_name": "anadon/JLS", "path": "src/jls/elem/TruthTable.java", "license": "gpl-3.0", "size": 38149 }
[ "java.util.BitSet" ]
import java.util.BitSet;
import java.util.*;
[ "java.util" ]
java.util;
2,874,973
public SerialMessage getMultiChannelCapabilityGetMessage(ZWaveEndpoint endpoint) { logger.debug("NODE {}: Creating new message for application command MULTI_CHANNEL_CAPABILITY_GET endpoint {}", this.getNode().getNodeId(), endpoint.getEndpointId()); SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); byte[] newPayload = { (byte) this.getNode().getNodeId(), 3, (byte) getCommandClass().getKey(), (byte) MULTI_CHANNEL_CAPABILITY_GET, (byte) endpoint.getEndpointId() }; result.setMessagePayload(newPayload); return result; }
SerialMessage function(ZWaveEndpoint endpoint) { logger.debug(STR, this.getNode().getNodeId(), endpoint.getEndpointId()); SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); byte[] newPayload = { (byte) this.getNode().getNodeId(), 3, (byte) getCommandClass().getKey(), (byte) MULTI_CHANNEL_CAPABILITY_GET, (byte) endpoint.getEndpointId() }; result.setMessagePayload(newPayload); return result; }
/** * Gets a SerialMessage with the MULTI CHANNEL CAPABILITY GET command. * Gets the capabilities for a specific endpoint. * @param the number of the endpoint to get the * @return the serial message. */
Gets a SerialMessage with the MULTI CHANNEL CAPABILITY GET command. Gets the capabilities for a specific endpoint
getMultiChannelCapabilityGetMessage
{ "repo_name": "woodrowbarlow/ZWaveManagement", "path": "src/org/openhab/binding/zwave/internal/protocol/commandclass/ZWaveMultiInstanceCommandClass.java", "license": "lgpl-3.0", "size": 24123 }
[ "org.openhab.binding.zwave.internal.protocol.SerialMessage", "org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint" ]
import org.openhab.binding.zwave.internal.protocol.SerialMessage; import org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint;
import org.openhab.binding.zwave.internal.protocol.*;
[ "org.openhab.binding" ]
org.openhab.binding;
1,808,400
private void saveImageToDisk( PrintMap printMap, BufferedImage image, String type, Envelope bbox ) throws IOException { PrintMapParam printMapParam = this.configuration.getDeegreeParams().getPrintMapParam(); String fileName = null; String templateName = printMap.getTemplate(); if ( type.equalsIgnoreCase( "MAP" ) ) { fileName = StringTools.concat( 200, "Map_", templateName, '_', printMap.getId(), this.FORMAT ); WorldFile wf = new WorldFile( bbox.getWidth() / image.getWidth(), bbox.getHeight() / image.getHeight(), 0, 0, bbox ); String wffn = StringTools.concat( 200, "Map_", templateName, '_', printMap.getId(), ".wld" ); URL url = new URL( printMapParam.getPlotImageDir() + '/' + wffn ); OutputStream os = null; try { os = new FileOutputStream( new File( url.toURI() ) ); } catch ( URISyntaxException e ) { // should never happen because each valid URL is a valid URI too LOG.logError( e.getMessage(), e ); } WorldFile.writeWorldFile( os, wf ); } else if ( type.equalsIgnoreCase( "LEGEND" ) ) { fileName = StringTools.concat( 200, "Legend_", templateName, '_', printMap.getId(), this.FORMAT ); } String path = printMapParam.getPlotImageDir() + '/' + fileName; URL downloadDirectory = new URL( path ); try { ImageUtils.saveImage( image, new File( downloadDirectory.toURI() ), 1 ); } catch ( URISyntaxException e ) { // should never happen because each valid URL is a valid URI too LOG.logError( e.getMessage(), e ); } }
void function( PrintMap printMap, BufferedImage image, String type, Envelope bbox ) throws IOException { PrintMapParam printMapParam = this.configuration.getDeegreeParams().getPrintMapParam(); String fileName = null; String templateName = printMap.getTemplate(); if ( type.equalsIgnoreCase( "MAP" ) ) { fileName = StringTools.concat( 200, "Map_", templateName, '_', printMap.getId(), this.FORMAT ); WorldFile wf = new WorldFile( bbox.getWidth() / image.getWidth(), bbox.getHeight() / image.getHeight(), 0, 0, bbox ); String wffn = StringTools.concat( 200, "Map_", templateName, '_', printMap.getId(), ".wld" ); URL url = new URL( printMapParam.getPlotImageDir() + '/' + wffn ); OutputStream os = null; try { os = new FileOutputStream( new File( url.toURI() ) ); } catch ( URISyntaxException e ) { LOG.logError( e.getMessage(), e ); } WorldFile.writeWorldFile( os, wf ); } else if ( type.equalsIgnoreCase( STR ) ) { fileName = StringTools.concat( 200, STR, templateName, '_', printMap.getId(), this.FORMAT ); } String path = printMapParam.getPlotImageDir() + '/' + fileName; URL downloadDirectory = new URL( path ); try { ImageUtils.saveImage( image, new File( downloadDirectory.toURI() ), 1 ); } catch ( URISyntaxException e ) { LOG.logError( e.getMessage(), e ); } }
/** * Save the GetMap image to the disk. * * @param printMap * @param image * @param type * @param bbox * @throws IOException */
Save the GetMap image to the disk
saveImageToDisk
{ "repo_name": "lat-lon/deegree2-base", "path": "deegree2-core/src/main/java/org/deegree/ogcwebservices/wmps/PrintMapHandler.java", "license": "lgpl-2.1", "size": 53232 }
[ "java.awt.image.BufferedImage", "java.io.File", "java.io.FileOutputStream", "java.io.IOException", "java.io.OutputStream", "java.net.URISyntaxException", "java.util.Map", "org.deegree.framework.util.ImageUtils", "org.deegree.framework.util.StringTools", "org.deegree.model.coverage.grid.WorldFile", "org.deegree.model.spatialschema.Envelope", "org.deegree.ogcwebservices.wmps.configuration.PrintMapParam", "org.deegree.ogcwebservices.wmps.operation.PrintMap" ]
import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URISyntaxException; import java.util.Map; import org.deegree.framework.util.ImageUtils; import org.deegree.framework.util.StringTools; import org.deegree.model.coverage.grid.WorldFile; import org.deegree.model.spatialschema.Envelope; import org.deegree.ogcwebservices.wmps.configuration.PrintMapParam; import org.deegree.ogcwebservices.wmps.operation.PrintMap;
import java.awt.image.*; import java.io.*; import java.net.*; import java.util.*; import org.deegree.framework.util.*; import org.deegree.model.coverage.grid.*; import org.deegree.model.spatialschema.*; import org.deegree.ogcwebservices.wmps.configuration.*; import org.deegree.ogcwebservices.wmps.operation.*;
[ "java.awt", "java.io", "java.net", "java.util", "org.deegree.framework", "org.deegree.model", "org.deegree.ogcwebservices" ]
java.awt; java.io; java.net; java.util; org.deegree.framework; org.deegree.model; org.deegree.ogcwebservices;
1,400,096
public File fileUnder(String packName, int vc) { File appRoot = new File(new File(root, APKDIR), packName.replace('.', '-')); return new File(appRoot, packName.replace('.', '_') + "-" + vc + ".apk"); }
File function(String packName, int vc) { File appRoot = new File(new File(root, APKDIR), packName.replace('.', '-')); return new File(appRoot, packName.replace('.', '_') + "-" + vc + ".apk"); }
/** * Figure out where to save an app * * @param packName * packagename of the app * @param vc * versioncode of the app * @return the file where to save this app. */
Figure out where to save an app
fileUnder
{ "repo_name": "onyxbits/Raccoon", "path": "src/main/java/de/onyxbits/raccoon/io/Archive.java", "license": "apache-2.0", "size": 8307 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
777,825
private void dbaTest() throws Exception { Connection conn = openUserConnection( TestConfiguration.TEST_DBO ); assertTrue( "Initially, should be able to read property.", canReadProperty() ); // Now prove that the DBO can reload the policy file. changePolicyFile( conn, RELOADABLE_MODIFIED_SOURCE_POLICY, true, null ); assertFalse( "Policy file changed. Should not be able to read the property.", canReadProperty() ); // Return to initial policy file. changePolicyFile( conn, RELOADABLE_INITIAL_SOURCE_POLICY, true, null ); assertTrue( "Reverted to initial policy. Should be able to read the property again.", canReadProperty() ); conn.close(); }
void function() throws Exception { Connection conn = openUserConnection( TestConfiguration.TEST_DBO ); assertTrue( STR, canReadProperty() ); changePolicyFile( conn, RELOADABLE_MODIFIED_SOURCE_POLICY, true, null ); assertFalse( STR, canReadProperty() ); changePolicyFile( conn, RELOADABLE_INITIAL_SOURCE_POLICY, true, null ); assertTrue( STR, canReadProperty() ); conn.close(); }
/** * Verify that the DBA has the power to reload the security policy file. */
Verify that the DBA has the power to reload the security policy file
dbaTest
{ "repo_name": "lpxz/grail-derby104", "path": "java/testing/org/apache/derbyTesting/functionTests/tests/lang/SecurityPolicyReloadingTest.java", "license": "apache-2.0", "size": 13743 }
[ "java.sql.Connection", "org.apache.derbyTesting.junit.TestConfiguration" ]
import java.sql.Connection; import org.apache.derbyTesting.junit.TestConfiguration;
import java.sql.*; import org.apache.*;
[ "java.sql", "org.apache" ]
java.sql; org.apache;
1,737,443
public static void main( String args[] ) { // Parse the command line. Want to replace this with something more powerful later. boolean debug = false; String defaultStateFileName = "../conf/default.desktop"; switch( args.length ) { case 0: break; case 1: if ( args[0].equalsIgnoreCase( "-debug" ) ) { debug = true; } else { defaultStateFileName = args[0]; } break; case 2: if ( args[0].equalsIgnoreCase( "-debug" ) ) { debug = true; } else { showUsage(); System.exit( 1 ); } defaultStateFileName = args[1]; break; default: showUsage(); System.exit( 1 ); } File defaultStateFile = new File( defaultStateFileName ); InstrumentClientFrame client = new InstrumentClientFrame( "Instrument Client" ); int logLevel = ( debug ? ConsoleLogger.LEVEL_DEBUG : ConsoleLogger.LEVEL_INFO ); client.enableLogging( new ConsoleLogger( logLevel ) ); client.initialize(); client.setDefaultStateFile( defaultStateFile ); client.show(); }
static void function( String args[] ) { boolean debug = false; String defaultStateFileName = STR; switch( args.length ) { case 0: break; case 1: if ( args[0].equalsIgnoreCase( STR ) ) { debug = true; } else { defaultStateFileName = args[0]; } break; case 2: if ( args[0].equalsIgnoreCase( STR ) ) { debug = true; } else { showUsage(); System.exit( 1 ); } defaultStateFileName = args[1]; break; default: showUsage(); System.exit( 1 ); } File defaultStateFile = new File( defaultStateFileName ); InstrumentClientFrame client = new InstrumentClientFrame( STR ); int logLevel = ( debug ? ConsoleLogger.LEVEL_DEBUG : ConsoleLogger.LEVEL_INFO ); client.enableLogging( new ConsoleLogger( logLevel ) ); client.initialize(); client.setDefaultStateFile( defaultStateFile ); client.show(); }
/** * Main method used to lauch an InstrumentClient application. */
Main method used to lauch an InstrumentClient application
main
{ "repo_name": "eva-xuyen/excalibur", "path": "containerkit/instrument/client/src/main/java/org/apache/excalibur/instrument/client/Main.java", "license": "apache-2.0", "size": 3433 }
[ "java.io.File", "org.apache.avalon.framework.logger.ConsoleLogger" ]
import java.io.File; import org.apache.avalon.framework.logger.ConsoleLogger;
import java.io.*; import org.apache.avalon.framework.logger.*;
[ "java.io", "org.apache.avalon" ]
java.io; org.apache.avalon;
1,614,846
public Method getMethod(final Class c, final String name, final Object[] params) throws IllegalArgumentException { try { return super.getMethod(c, name, params); } catch(MethodMap.AmbiguousException ae) { StringBuilder msg = new StringBuilder("Introspection Error : Ambiguous method invocation ") .append(name) .append("("); for (int i = 0; i < params.length; i++) { if (i > 0) { msg.append(", "); } if (params[i] == null) { msg.append("null"); } else { msg.append(params[i].getClass().getName()); } } msg.append(") for class ") .append(c); Logger.debug(this,msg.toString()); } return null; }
Method function(final Class c, final String name, final Object[] params) throws IllegalArgumentException { try { return super.getMethod(c, name, params); } catch(MethodMap.AmbiguousException ae) { StringBuilder msg = new StringBuilder(STR) .append(name) .append("("); for (int i = 0; i < params.length; i++) { if (i > 0) { msg.append(STR); } if (params[i] == null) { msg.append("null"); } else { msg.append(params[i].getClass().getName()); } } msg.append(STR) .append(c); Logger.debug(this,msg.toString()); } return null; }
/** * Gets the method defined by <code>name</code> and * <code>params</code> for the Class <code>c</code>. * * @param c Class in which the method search is taking place * @param name Name of the method being searched for * @param params An array of Objects (not Classes) that describe the * the parameters * * @return The desired Method object. * @throws IllegalArgumentException When the parameters passed in can not be used for introspection. */
Gets the method defined by <code>name</code> and <code>params</code> for the Class <code>c</code>
getMethod
{ "repo_name": "dotCMS/core", "path": "dotCMS/src/main/java/org/apache/velocity/util/introspection/Introspector.java", "license": "gpl-3.0", "size": 3980 }
[ "com.dotmarketing.util.Logger", "java.lang.reflect.Method" ]
import com.dotmarketing.util.Logger; import java.lang.reflect.Method;
import com.dotmarketing.util.*; import java.lang.reflect.*;
[ "com.dotmarketing.util", "java.lang" ]
com.dotmarketing.util; java.lang;
2,332,062
private static void deleteRecursive(File f) throws IOException { if (f.isDirectory()) { if (f.listFiles() != null) { for (File c : f.listFiles()) { deleteRecursive(c); } } } if (f.exists() && !f.delete()) { throw new IOException("Error while deleting the folders and files"); } }
static void function(File f) throws IOException { if (f.isDirectory()) { if (f.listFiles() != null) { for (File c : f.listFiles()) { deleteRecursive(c); } } } if (f.exists() && !f.delete()) { throw new IOException(STR); } }
/** * Recursively delete the files * * @param f File to be deleted * @throws IOException */
Recursively delete the files
deleteRecursive
{ "repo_name": "mohammadshahidkhan/incubator-carbondata", "path": "core/src/main/java/org/apache/carbondata/core/util/CarbonUtil.java", "license": "apache-2.0", "size": 50168 }
[ "java.io.File", "java.io.IOException" ]
import java.io.File; import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
1,675,226
public List<PathSegment> getPathSegments() { return getPathSegments(true); }
List<PathSegment> function() { return getPathSegments(true); }
/** * Get the path of the current request relative to the base URI as a list of * {@link PathSegment}. This method is useful when the path needs to be * parsed, particularly when matrix parameters may be present in the path. * All sequences of escaped octets are decoded, equivalent to * <code>getPathSegments(true)</code>. * * @return an unmodifiable list of {@link PathSegment}. The matrix parameter * map of each path segment is also unmodifiable. * @throws java.lang.IllegalStateException * if called outside the scope of a request * @see PathSegment * @see UriInfo#getPathSegments() */
Get the path of the current request relative to the base URI as a list of <code>PathSegment</code>. This method is useful when the path needs to be parsed, particularly when matrix parameters may be present in the path. All sequences of escaped octets are decoded, equivalent to <code>getPathSegments(true)</code>
getPathSegments
{ "repo_name": "alastrina123/debrief", "path": "org.mwc.asset.comms/docs/restlet_src/org.restlet.ext.jaxrs/org/restlet/ext/jaxrs/internal/core/CallContext.java", "license": "epl-1.0", "size": 46359 }
[ "java.util.List", "javax.ws.rs.core.PathSegment" ]
import java.util.List; import javax.ws.rs.core.PathSegment;
import java.util.*; import javax.ws.rs.core.*;
[ "java.util", "javax.ws" ]
java.util; javax.ws;
2,832,993
private void resetCorrelationId(byte[] request) { // correlation id is an int that comes after size (long), type (short) and version (short). int offsetOfCorrelationId = 8 + 2 + 2; ByteBuffer wrapped = ByteBuffer.wrap(request); wrapped.putInt(offsetOfCorrelationId, 0); } /** * Get the {@link ResponseInfo} for the given {@link RequestInfo} using the {@link MockServer}
void function(byte[] request) { int offsetOfCorrelationId = 8 + 2 + 2; ByteBuffer wrapped = ByteBuffer.wrap(request); wrapped.putInt(offsetOfCorrelationId, 0); } /** * Get the {@link ResponseInfo} for the given {@link RequestInfo} using the {@link MockServer}
/** * Reset the correlation id field of a {@link PutRequest} to 0. */
Reset the correlation id field of a <code>PutRequest</code> to 0
resetCorrelationId
{ "repo_name": "vgkholla/ambry", "path": "ambry-router/src/test/java/com.github.ambry.router/PutOperationTest.java", "license": "apache-2.0", "size": 15326 }
[ "com.github.ambry.network.RequestInfo", "com.github.ambry.network.ResponseInfo", "java.nio.ByteBuffer" ]
import com.github.ambry.network.RequestInfo; import com.github.ambry.network.ResponseInfo; import java.nio.ByteBuffer;
import com.github.ambry.network.*; import java.nio.*;
[ "com.github.ambry", "java.nio" ]
com.github.ambry; java.nio;
1,576,472
protected void initLocalizationContent(String configurationFileName) { CmsObject cms = null; try { // this will always be in the root site cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserGuest()); } catch (CmsException e) { // error initializing cms object, log error if (LOG.isErrorEnabled()) { LOG.error( Messages.get().getBundle().key( Messages.ERR_INVALID_INIT_USER_1, OpenCms.getDefaultUsers().getUserGuest())); } } if ((cms != null) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(configurationFileName)) { // try to get XML content from cache Object o = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().getCachedObject(cms, configurationFileName); if (o != null) { // found the cached XML content, use it m_localizationContent = (CmsXmlContent)o; return; } try { CmsFile configFile = cms.readFile(configurationFileName); m_localizationContent = CmsXmlContentFactory.unmarshal(cms, configFile); // store unmarshaled content in cache CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().putCachedObject( cms, configurationFileName, m_localizationContent); } catch (CmsException e) { // ignore, no configuration file found } } }
void function(String configurationFileName) { CmsObject cms = null; try { cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserGuest()); } catch (CmsException e) { if (LOG.isErrorEnabled()) { LOG.error( Messages.get().getBundle().key( Messages.ERR_INVALID_INIT_USER_1, OpenCms.getDefaultUsers().getUserGuest())); } } if ((cms != null) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(configurationFileName)) { Object o = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().getCachedObject(cms, configurationFileName); if (o != null) { m_localizationContent = (CmsXmlContent)o; return; } try { CmsFile configFile = cms.readFile(configurationFileName); m_localizationContent = CmsXmlContentFactory.unmarshal(cms, configFile); CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().putCachedObject( cms, configurationFileName, m_localizationContent); } catch (CmsException e) { } } }
/** * Initializes the content used for localizing the output.<p> * * @param configurationFileName the absolute path including site root to the configuration file containing localized keys */
Initializes the content used for localizing the output
initLocalizationContent
{ "repo_name": "mediaworx/opencms-core", "path": "src/org/opencms/xml/CmsXmlMessages.java", "license": "lgpl-2.1", "size": 11130 }
[ "org.opencms.cache.CmsVfsMemoryObjectCache", "org.opencms.file.CmsFile", "org.opencms.file.CmsObject", "org.opencms.main.CmsException", "org.opencms.main.OpenCms", "org.opencms.util.CmsStringUtil", "org.opencms.xml.content.CmsXmlContent", "org.opencms.xml.content.CmsXmlContentFactory" ]
import org.opencms.cache.CmsVfsMemoryObjectCache; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.util.CmsStringUtil; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.cache.*; import org.opencms.file.*; import org.opencms.main.*; import org.opencms.util.*; import org.opencms.xml.content.*;
[ "org.opencms.cache", "org.opencms.file", "org.opencms.main", "org.opencms.util", "org.opencms.xml" ]
org.opencms.cache; org.opencms.file; org.opencms.main; org.opencms.util; org.opencms.xml;
2,426,825
public List<HttpMethod> getAllowedMethods(String path) { List<Route> matchingRoutes = getMatchingRoutes(path); if (matchingRoutes.isEmpty()) return Collections.emptyList(); List<HttpMethod> methods = new ArrayList<HttpMethod>(); for (Route route : matchingRoutes) { methods.add(route.getMethod()); } return methods; }
List<HttpMethod> function(String path) { List<Route> matchingRoutes = getMatchingRoutes(path); if (matchingRoutes.isEmpty()) return Collections.emptyList(); List<HttpMethod> methods = new ArrayList<HttpMethod>(); for (Route route : matchingRoutes) { methods.add(route.getMethod()); } return methods; }
/** * Returns the supported HTTP methods for the given URL path. * * @param path the path portion of the URL (e.g. after the domain and port). * @return A list of appropriate HTTP methods for the given path. Never null. */
Returns the supported HTTP methods for the given URL path
getAllowedMethods
{ "repo_name": "layerhq/RestExpress", "path": "core/src/java/org/restexpress/route/RouteMapping.java", "license": "apache-2.0", "size": 5660 }
[ "java.util.ArrayList", "java.util.Collections", "java.util.List", "org.jboss.netty.handler.codec.http.HttpMethod" ]
import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jboss.netty.handler.codec.http.HttpMethod;
import java.util.*; import org.jboss.netty.handler.codec.http.*;
[ "java.util", "org.jboss.netty" ]
java.util; org.jboss.netty;
829,516
@ApiModelProperty(value = "") public Problem getProblem() { return problem; }
@ApiModelProperty(value = "") Problem function() { return problem; }
/** * Get problem * * @return problem */
Get problem
getProblem
{ "repo_name": "XeroAPI/Xero-Java", "path": "src/main/java/com/xero/models/payrollnz/EarningsRateObject.java", "license": "mit", "size": 3840 }
[ "io.swagger.annotations.ApiModelProperty" ]
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.*;
[ "io.swagger.annotations" ]
io.swagger.annotations;
1,882,448
public static KBucketEntry UnpackBucketEntry (byte[] buffer, int off, DHTtype type) { if (off + type.NODES_ENTRY_LENGTH > buffer.length) { throw new IllegalArgumentException("Not enough room in buffer"); } ByteBuffer bb = ByteBuffer.wrap(buffer, off, type.NODES_ENTRY_LENGTH); byte[] key = new byte[20]; bb.get(key); byte[] inetaddr = new byte[type.NODES_ENTRY_LENGTH - 20 - 2]; bb.get(inetaddr); InetSocketAddress addr = null; //UnknownHostException shouldn't occur since IP is provided try { addr = new InetSocketAddress(InetAddress.getByAddress(inetaddr), Short.toUnsignedInt(bb.getShort())); } catch (UnknownHostException e) { e.printStackTrace(); throw new RuntimeException(e); } return new KBucketEntry(addr, new Key(key), 0); }
static KBucketEntry function (byte[] buffer, int off, DHTtype type) { if (off + type.NODES_ENTRY_LENGTH > buffer.length) { throw new IllegalArgumentException(STR); } ByteBuffer bb = ByteBuffer.wrap(buffer, off, type.NODES_ENTRY_LENGTH); byte[] key = new byte[20]; bb.get(key); byte[] inetaddr = new byte[type.NODES_ENTRY_LENGTH - 20 - 2]; bb.get(inetaddr); InetSocketAddress addr = null; try { addr = new InetSocketAddress(InetAddress.getByAddress(inetaddr), Short.toUnsignedInt(bb.getShort())); } catch (UnknownHostException e) { e.printStackTrace(); throw new RuntimeException(e); } return new KBucketEntry(addr, new Key(key), 0); }
/** * Unpacks a Entry from a byte array * * @param buffer byte array with serialized entry * @param off the Offset to use * @return deserialized Entry * @throws IllegalArgumentException if buffer is to small */
Unpacks a Entry from a byte array
UnpackBucketEntry
{ "repo_name": "the8472/mldht", "path": "src/lbms/plugins/mldht/kad/utils/PackUtil.java", "license": "mpl-2.0", "size": 2751 }
[ "java.net.InetAddress", "java.net.InetSocketAddress", "java.net.UnknownHostException", "java.nio.ByteBuffer" ]
import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer;
import java.net.*; import java.nio.*;
[ "java.net", "java.nio" ]
java.net; java.nio;
1,342,687
User getUser(String identifier) throws AuthorizationAccessException;
User getUser(String identifier) throws AuthorizationAccessException;
/** * Retrieves the user with the given identifier. * * @param identifier the id of the user to retrieve * @return the user with the given id, or null if no matching user was found * @throws AuthorizationAccessException if there was an unexpected error performing the operation */
Retrieves the user with the given identifier
getUser
{ "repo_name": "MikeThomsen/nifi", "path": "nifi-framework-api/src/main/java/org/apache/nifi/authorization/UserGroupProvider.java", "license": "apache-2.0", "size": 5254 }
[ "org.apache.nifi.authorization.exception.AuthorizationAccessException" ]
import org.apache.nifi.authorization.exception.AuthorizationAccessException;
import org.apache.nifi.authorization.exception.*;
[ "org.apache.nifi" ]
org.apache.nifi;
701,144
public static OptionalInt mapToInt(OptionalDouble opt, DoubleToIntFunction mapper) { requireNonNull(mapper); return opt.isPresent() ? OptionalInt.of(mapper.applyAsInt(opt.getAsDouble())) : OptionalInt.empty(); }
static OptionalInt function(OptionalDouble opt, DoubleToIntFunction mapper) { requireNonNull(mapper); return opt.isPresent() ? OptionalInt.of(mapper.applyAsInt(opt.getAsDouble())) : OptionalInt.empty(); }
/** * map OptionalDouble to OptionalInt */
map OptionalDouble to OptionalInt
mapToInt
{ "repo_name": "kxbmap/lombok-java8-extensions", "path": "src/main/java/com/github/kxbmap/lombok/extension/OptionalDoubleExtensions.java", "license": "apache-2.0", "size": 5608 }
[ "java.util.Objects", "java.util.OptionalDouble", "java.util.OptionalInt", "java.util.function.DoubleToIntFunction" ]
import java.util.Objects; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.function.DoubleToIntFunction;
import java.util.*; import java.util.function.*;
[ "java.util" ]
java.util;
362,682
public static List<PermissionInfo> getAllDeclaredPlatformPermissions(Context context) { List<PermissionInfo> platformPermissions = new ArrayList<>(); List<PermissionInfo> declaredPermissions = getAllDeclaredPermissions(context); for (PermissionInfo permission : declaredPermissions) { if (permission.packageName.equals(Constants.PLATFORM_PACKAGE)) { platformPermissions.add(permission); } } return platformPermissions; }
static List<PermissionInfo> function(Context context) { List<PermissionInfo> platformPermissions = new ArrayList<>(); List<PermissionInfo> declaredPermissions = getAllDeclaredPermissions(context); for (PermissionInfo permission : declaredPermissions) { if (permission.packageName.equals(Constants.PLATFORM_PACKAGE)) { platformPermissions.add(permission); } } return platformPermissions; }
/** * Returns a {@link List} of {@link PermissionInfo} instances representing all permissions * declared by the platform on the device. */
Returns a <code>List</code> of <code>PermissionInfo</code> instances representing all permissions declared by the platform on the device
getAllDeclaredPlatformPermissions
{ "repo_name": "android/security-certification-resources", "path": "niap-cc/Permissions/Tester/app/src/main/java/com/android/certifications/niap/permissions/utils/PermissionUtils.java", "license": "apache-2.0", "size": 3202 }
[ "android.content.Context", "android.content.pm.PermissionInfo", "com.android.certifications.niap.permissions.Constants", "java.util.ArrayList", "java.util.List" ]
import android.content.Context; import android.content.pm.PermissionInfo; import com.android.certifications.niap.permissions.Constants; import java.util.ArrayList; import java.util.List;
import android.content.*; import android.content.pm.*; import com.android.certifications.niap.permissions.*; import java.util.*;
[ "android.content", "com.android.certifications", "java.util" ]
android.content; com.android.certifications; java.util;
2,562,048
public ClassFeatureSet initialize(JavaClass javaClass) { this.className = javaClass.getClassName(); this.isInterface = javaClass.isInterface(); addFeature(CLASS_NAME_KEY + transformClassName(javaClass.getClassName())); for (Method method : javaClass.getMethods()) { if (!isSynthetic(method)) { String transformedMethodSignature = transformMethodSignature(method.getSignature()); if (method.isStatic() || !overridesSuperclassMethod(javaClass, method)) { addFeature(METHOD_NAME_KEY + method.getName() + ":" + transformedMethodSignature); } Code code = method.getCode(); if (code != null && code.getCode() != null && code.getCode().length >= MIN_CODE_LENGTH) { addFeature(CODE_LENGTH_KEY + method.getName() + ":" + transformedMethodSignature + ":" + code.getCode().length); } } } for (Field field : javaClass.getFields()) { if (!isSynthetic(field)) { addFeature(FIELD_NAME_KEY + field.getName() + ":" + transformSignature(field.getSignature())); } } return this; }
ClassFeatureSet function(JavaClass javaClass) { this.className = javaClass.getClassName(); this.isInterface = javaClass.isInterface(); addFeature(CLASS_NAME_KEY + transformClassName(javaClass.getClassName())); for (Method method : javaClass.getMethods()) { if (!isSynthetic(method)) { String transformedMethodSignature = transformMethodSignature(method.getSignature()); if (method.isStatic() !overridesSuperclassMethod(javaClass, method)) { addFeature(METHOD_NAME_KEY + method.getName() + ":" + transformedMethodSignature); } Code code = method.getCode(); if (code != null && code.getCode() != null && code.getCode().length >= MIN_CODE_LENGTH) { addFeature(CODE_LENGTH_KEY + method.getName() + ":" + transformedMethodSignature + ":" + code.getCode().length); } } } for (Field field : javaClass.getFields()) { if (!isSynthetic(field)) { addFeature(FIELD_NAME_KEY + field.getName() + ":" + transformSignature(field.getSignature())); } } return this; }
/** * Initialize from given JavaClass. * * @param javaClass * the JavaClass * @return this object */
Initialize from given JavaClass
initialize
{ "repo_name": "johnscancella/spotbugs", "path": "spotbugs/src/main/java/edu/umd/cs/findbugs/model/ClassFeatureSet.java", "license": "lgpl-2.1", "size": 12087 }
[ "org.apache.bcel.classfile.Code", "org.apache.bcel.classfile.Field", "org.apache.bcel.classfile.JavaClass", "org.apache.bcel.classfile.Method" ]
import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.*;
[ "org.apache.bcel" ]
org.apache.bcel;
1,440,839
static Throwable translateException(Throwable t) throws DoNotRetryIOException { if (t instanceof UndeclaredThrowableException) { if (t.getCause() != null) { t = t.getCause(); } } if (t instanceof RemoteException) { t = ((RemoteException)t).unwrapRemoteException(); } if (t instanceof LinkageError) { throw new DoNotRetryIOException(t); } if (t instanceof ServiceException) { ServiceException se = (ServiceException)t; Throwable cause = se.getCause(); if (cause != null && cause instanceof DoNotRetryIOException) { throw (DoNotRetryIOException)cause; } // Don't let ServiceException out; its rpc specific. t = cause; // t could be a RemoteException so go aaround again. translateException(t); } else if (t instanceof DoNotRetryIOException) { throw (DoNotRetryIOException)t; } return t; }
static Throwable translateException(Throwable t) throws DoNotRetryIOException { if (t instanceof UndeclaredThrowableException) { if (t.getCause() != null) { t = t.getCause(); } } if (t instanceof RemoteException) { t = ((RemoteException)t).unwrapRemoteException(); } if (t instanceof LinkageError) { throw new DoNotRetryIOException(t); } if (t instanceof ServiceException) { ServiceException se = (ServiceException)t; Throwable cause = se.getCause(); if (cause != null && cause instanceof DoNotRetryIOException) { throw (DoNotRetryIOException)cause; } t = cause; translateException(t); } else if (t instanceof DoNotRetryIOException) { throw (DoNotRetryIOException)t; } return t; }
/** * Get the good or the remote exception if any, throws the DoNotRetryIOException. * @param t the throwable to analyze * @return the translated exception, if it's not a DoNotRetryIOException * @throws DoNotRetryIOException - if we find it, we throw it instead of translating. */
Get the good or the remote exception if any, throws the DoNotRetryIOException
translateException
{ "repo_name": "baishuo/hbase-1.0.0-cdh5.4.7_baishuo", "path": "hbase-client/src/main/java/org/apache/hadoop/hbase/client/RpcRetryingCaller.java", "license": "apache-2.0", "size": 9850 }
[ "com.google.protobuf.ServiceException", "java.lang.reflect.UndeclaredThrowableException", "org.apache.hadoop.hbase.DoNotRetryIOException", "org.apache.hadoop.ipc.RemoteException" ]
import com.google.protobuf.ServiceException; import java.lang.reflect.UndeclaredThrowableException; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.ipc.RemoteException;
import com.google.protobuf.*; import java.lang.reflect.*; import org.apache.hadoop.hbase.*; import org.apache.hadoop.ipc.*;
[ "com.google.protobuf", "java.lang", "org.apache.hadoop" ]
com.google.protobuf; java.lang; org.apache.hadoop;
2,509,849
public JsonParser setInput(final String inpfil, final String inpenc, final int bufsiz) { reset(false); inpName = inpfil; try { inpReader = new InputStreamReader(new BufferedInputStream(new FileInputStream(inpfil), bufsiz), inpenc); } catch (final UnsupportedEncodingException thr) { throw new Escape(Escape.BAD_ENCODING, "The encoding '" + inpenc + "' is not supported by this Java Runtime Engine", thr); } catch (final IOException thr) { throw new Escape(Escape.IOERROR, "Could not access file \"" + inpfil + "\": " + thr, thr); } inpClose = true; if (optPreloadInput) { inpReader = preloadInput(inpfil, inpReader, inpClose, Math.min(Integer.MAX_VALUE, (int) new File(inpfil).length())); inpClose = true; } return this; }
JsonParser function(final String inpfil, final String inpenc, final int bufsiz) { reset(false); inpName = inpfil; try { inpReader = new InputStreamReader(new BufferedInputStream(new FileInputStream(inpfil), bufsiz), inpenc); } catch (final UnsupportedEncodingException thr) { throw new Escape(Escape.BAD_ENCODING, STR + inpenc + STR, thr); } catch (final IOException thr) { throw new Escape(Escape.IOERROR, STRSTR\STR + thr, thr); } inpClose = true; if (optPreloadInput) { inpReader = preloadInput(inpfil, inpReader, inpClose, Math.min(Integer.MAX_VALUE, (int) new File(inpfil).length())); inpClose = true; } return this; }
/** * Construct a JSON parser from a file input source. * * @param inpfil Input source. * @param inpenc Character encoding used by the input source. * @param bufsiz Size of input buffer for reading from the file. * @return the current JSONParser object for chaining purposes */
Construct a JSON parser from a file input source
setInput
{ "repo_name": "Dyrcona/marc4j", "path": "src/org/marc4j/util/JsonParser.java", "license": "lgpl-2.1", "size": 56222 }
[ "java.io.BufferedInputStream", "java.io.File", "java.io.FileInputStream", "java.io.IOException", "java.io.InputStreamReader", "java.io.UnsupportedEncodingException" ]
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException;
import java.io.*;
[ "java.io" ]
java.io;
2,581,454
public static MozuClient<String> generateRandomCouponClient() throws Exception { return generateRandomCouponClient( null); }
static MozuClient<String> function() throws Exception { return generateRandomCouponClient( null); }
/** * * <p><pre><code> * MozuClient<String> mozuClient=GenerateRandomCouponClient(); * client.setBaseAddress(url); * client.executeRequest(); * string string = client.Result(); * </code></pre></p> * @return Mozu.Api.MozuClient <string> * @see string */
<code><code> MozuClient mozuClient=GenerateRandomCouponClient(); client.setBaseAddress(url); client.executeRequest(); string string = client.Result(); </code></code>
generateRandomCouponClient
{ "repo_name": "Mozu/mozu-java", "path": "mozu-java-core/src/main/java/com/mozu/api/clients/commerce/catalog/admin/DiscountClient.java", "license": "mit", "size": 19416 }
[ "com.mozu.api.MozuClient" ]
import com.mozu.api.MozuClient;
import com.mozu.api.*;
[ "com.mozu.api" ]
com.mozu.api;
477,864
public AcknowledgedResponse deleteCalendar(DeleteCalendarRequest request, RequestOptions options) throws IOException { return restHighLevelClient.performRequestAndParseEntity(request, MLRequestConverters::deleteCalendar, options, AcknowledgedResponse::fromXContent, Collections.emptySet()); }
AcknowledgedResponse function(DeleteCalendarRequest request, RequestOptions options) throws IOException { return restHighLevelClient.performRequestAndParseEntity(request, MLRequestConverters::deleteCalendar, options, AcknowledgedResponse::fromXContent, Collections.emptySet()); }
/** * Deletes the given Machine Learning Calendar * <p> * For additional info see * <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ml-delete-calendar.html"> * ML Delete calendar documentation</a> * * @param request The request to delete the calendar * @param options Additional request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized * @return action acknowledgement * @throws IOException when there is a serialization issue sending the request or receiving the response */
Deletes the given Machine Learning Calendar For additional info see ML Delete calendar documentation
deleteCalendar
{ "repo_name": "gingerwizard/elasticsearch", "path": "client/rest-high-level/src/main/java/org/elasticsearch/client/MachineLearningClient.java", "license": "apache-2.0", "size": 133077 }
[ "java.io.IOException", "java.util.Collections", "org.elasticsearch.action.support.master.AcknowledgedResponse", "org.elasticsearch.client.ml.DeleteCalendarRequest" ]
import java.io.IOException; import java.util.Collections; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.ml.DeleteCalendarRequest;
import java.io.*; import java.util.*; import org.elasticsearch.action.support.master.*; import org.elasticsearch.client.ml.*;
[ "java.io", "java.util", "org.elasticsearch.action", "org.elasticsearch.client" ]
java.io; java.util; org.elasticsearch.action; org.elasticsearch.client;
1,222,113
EClass getNamedElement();
EClass getNamedElement();
/** * Returns the meta object for class '{@link org.dresdenocl.pivotmodel.NamedElement <em>Named Element</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for class '<em>Named Element</em>'. * @see org.dresdenocl.pivotmodel.NamedElement * @generated */
Returns the meta object for class '<code>org.dresdenocl.pivotmodel.NamedElement Named Element</code>'.
getNamedElement
{ "repo_name": "dresden-ocl/dresdenocl", "path": "plugins/org.dresdenocl.pivotmodel/src/org/dresdenocl/pivotmodel/PivotModelPackage.java", "license": "lgpl-3.0", "size": 98285 }
[ "org.eclipse.emf.ecore.EClass" ]
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
672,006
private ResultSet[] getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { ResultSet[] rss = new ResultSet[2]; DatabaseMetaData dmd = getDMD(); rss[0]= dmd.getProcedureColumns(catalog, schemaPattern, procedureNamePattern, columnNamePattern); rss[1]= getProcedureColumnsODBC(catalog, schemaPattern, procedureNamePattern, columnNamePattern); String[] columnNames = new String[] { "PROCEDURE_CAT","PROCEDURE_SCHEM","PROCEDURE_NAME", "COLUMN_NAME", "COLUMN_TYPE", "DATA_TYPE", "TYPE_NAME", "PRECISION", "LENGTH", "SCALE", "RADIX", "NULLABLE", "REMARKS", "COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE", "SPECIFIC_NAME" //}; // interesting, we seem to have two extra columns vs the API ,"METHOD_ID", "PARAMETER_ID"}; int[] columnTypes = new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.SMALLINT, Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.VARCHAR //}; , Types.SMALLINT, Types.SMALLINT}; boolean[] nullability = new boolean[] { true, false, false, false, false, false, false, false, false, true, true, false, true, true, true, true, true, false, false, false//}; , false, false}; // JDBC result set assertMetaDataResultSet(rss[0], columnNames, columnTypes, nullability); // Change expected shape for ODBC // One less column for ODBC, (20) SPECIFIC_NAME is missing. String[] odbcColumnNames = new String[columnNames.length - 1]; System.arraycopy(columnNames, 0, odbcColumnNames, 0, 19); System.arraycopy(columnNames, 21 - 1, odbcColumnNames, 20 - 1, 2); int[] odbcColumnTypes = new int[columnTypes.length - 1]; System.arraycopy(columnTypes, 0, odbcColumnTypes, 0, 19); System.arraycopy(columnTypes, 21 - 1, odbcColumnTypes, 20 - 1, 2); // SQL_DATA_TYPE NULL in JDBC, valid type in ODBC. // otherwise the same as JDBC boolean[] odbcNullability = new boolean[] { true, false, false, false, false, false, false, false, false, true, true, false, true, true, false, true, true, false, false, false , false}; // And change some column names. odbcColumnNames[8 - 1] = "COLUMN_SIZE"; odbcColumnNames[9 - 1] = "BUFFER_LENGTH"; odbcColumnNames[10 - 1] = "DECIMAL_DIGITS"; odbcColumnNames[11 - 1] = "NUM_PREC_RADIX"; // And some column types. odbcColumnTypes[6 - 1] = Types.SMALLINT; odbcColumnTypes[15 - 1] = Types.SMALLINT; odbcColumnTypes[16 - 1] = Types.SMALLINT; // odbc result set assertMetaDataResultSet( rss[1], odbcColumnNames, odbcColumnTypes, odbcNullability); return rss; }
ResultSet[] function(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { ResultSet[] rss = new ResultSet[2]; DatabaseMetaData dmd = getDMD(); rss[0]= dmd.getProcedureColumns(catalog, schemaPattern, procedureNamePattern, columnNamePattern); rss[1]= getProcedureColumnsODBC(catalog, schemaPattern, procedureNamePattern, columnNamePattern); String[] columnNames = new String[] { STR,STR,STR, STR, STR, STR, STR, STR, STR, "SCALE", "RADIX", STR, STR, STR, STR, STR, STR, STR, STR, STR ,STR, STR}; int[] columnTypes = new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.SMALLINT, Types.SMALLINT, Types.SMALLINT, Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.VARCHAR , Types.SMALLINT, Types.SMALLINT}; boolean[] nullability = new boolean[] { true, false, false, false, false, false, false, false, false, true, true, false, true, true, true, true, true, false, false, false , false, false}; assertMetaDataResultSet(rss[0], columnNames, columnTypes, nullability); String[] odbcColumnNames = new String[columnNames.length - 1]; System.arraycopy(columnNames, 0, odbcColumnNames, 0, 19); System.arraycopy(columnNames, 21 - 1, odbcColumnNames, 20 - 1, 2); int[] odbcColumnTypes = new int[columnTypes.length - 1]; System.arraycopy(columnTypes, 0, odbcColumnTypes, 0, 19); System.arraycopy(columnTypes, 21 - 1, odbcColumnTypes, 20 - 1, 2); boolean[] odbcNullability = new boolean[] { true, false, false, false, false, false, false, false, false, true, true, false, true, true, false, true, true, false, false, false , false}; odbcColumnNames[8 - 1] = STR; odbcColumnNames[9 - 1] = STR; odbcColumnNames[10 - 1] = STR; odbcColumnNames[11 - 1] = STR; odbcColumnTypes[6 - 1] = Types.SMALLINT; odbcColumnTypes[15 - 1] = Types.SMALLINT; odbcColumnTypes[16 - 1] = Types.SMALLINT; assertMetaDataResultSet( rss[1], odbcColumnNames, odbcColumnTypes, odbcNullability); return rss; }
/** * Helper method for testing getProcedureColumns - calls * dmd.getProcedureColumns for the JDBC call, and * getProcedureColumnssODBC for the ODBC procedure * @param catalog * @param schemaPattern * @param procedureNamePattern * @param columnNamePattern * @return an array of two result sets corresponding to JDBC and ODBC * respectively * @throws SQLException */
Helper method for testing getProcedureColumns - calls dmd.getProcedureColumns for the JDBC call, and getProcedureColumnssODBC for the ODBC procedure
getProcedureColumns
{ "repo_name": "trejkaz/derby", "path": "java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/DatabaseMetaDataTest.java", "license": "apache-2.0", "size": 214556 }
[ "java.sql.DatabaseMetaData", "java.sql.ResultSet", "java.sql.SQLException", "java.sql.Types" ]
import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types;
import java.sql.*;
[ "java.sql" ]
java.sql;
1,243,554
public void addStats( DataStatistics<SimpleFeature> statsObj, EntryVisibilityHandler<SimpleFeature> visibilityHandler ) { int replaceStat = 0; // Go through stats list managed by this manager and look for a match for (DataStatistics<SimpleFeature> currentStat : statsObjList) { if (currentStat.getStatisticsId().equals( statsObj.getStatisticsId())) { // If a match was found for an existing stat object in list, // remove it now and replace it later. this.statsObjList.remove(replaceStat); break; } replaceStat++; // Not found, check next stat object } this.statsObjList.add(statsObj); this.visibilityHandlers.put( statsObj.getStatisticsId(), visibilityHandler); } // ----------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------
void function( DataStatistics<SimpleFeature> statsObj, EntryVisibilityHandler<SimpleFeature> visibilityHandler ) { int replaceStat = 0; for (DataStatistics<SimpleFeature> currentStat : statsObjList) { if (currentStat.getStatisticsId().equals( statsObj.getStatisticsId())) { this.statsObjList.remove(replaceStat); break; } replaceStat++; } this.statsObjList.add(statsObj); this.visibilityHandlers.put( statsObj.getStatisticsId(), visibilityHandler); }
/** * Adds/Replaces a stats object for the given adapter <br> * Supports object replacement. * * @param statsObj * - data stats object to be tracked by adding or replacement * @param visibilityHandler * - type of visibility required to access the stats object * */
Adds/Replaces a stats object for the given adapter Supports object replacement
addStats
{ "repo_name": "chizou/geowave", "path": "extensions/adapters/vector/src/main/java/mil/nga/giat/geowave/adapter/vector/stats/StatsManager.java", "license": "apache-2.0", "size": 10573 }
[ "mil.nga.giat.geowave.core.store.EntryVisibilityHandler", "mil.nga.giat.geowave.core.store.adapter.statistics.DataStatistics", "org.opengis.feature.simple.SimpleFeature" ]
import mil.nga.giat.geowave.core.store.EntryVisibilityHandler; import mil.nga.giat.geowave.core.store.adapter.statistics.DataStatistics; import org.opengis.feature.simple.SimpleFeature;
import mil.nga.giat.geowave.core.store.*; import mil.nga.giat.geowave.core.store.adapter.statistics.*; import org.opengis.feature.simple.*;
[ "mil.nga.giat", "org.opengis.feature" ]
mil.nga.giat; org.opengis.feature;
2,845,568
public void testHashCode() { MultipleXYSeriesLabelGenerator g1 = new MultipleXYSeriesLabelGenerator(); MultipleXYSeriesLabelGenerator g2 = new MultipleXYSeriesLabelGenerator(); assertTrue(g1.equals(g2)); assertTrue(g1.hashCode() == g2.hashCode()); }
void function() { MultipleXYSeriesLabelGenerator g1 = new MultipleXYSeriesLabelGenerator(); MultipleXYSeriesLabelGenerator g2 = new MultipleXYSeriesLabelGenerator(); assertTrue(g1.equals(g2)); assertTrue(g1.hashCode() == g2.hashCode()); }
/** * Simple check that hashCode is implemented. */
Simple check that hashCode is implemented
testHashCode
{ "repo_name": "JSansalone/JFreeChart", "path": "tests/org/jfree/chart/labels/junit/MultipleXYSeriesLabelGeneratorTests.java", "license": "lgpl-2.1", "size": 5660 }
[ "org.jfree.chart.labels.MultipleXYSeriesLabelGenerator" ]
import org.jfree.chart.labels.MultipleXYSeriesLabelGenerator;
import org.jfree.chart.labels.*;
[ "org.jfree.chart" ]
org.jfree.chart;
2,611,779
@Test public void testDocumentProcessorTopology() throws Exception { //clean up the document store LOG.info("Truncating Document and Index Store"); DocumentStoreUtils.truncate(getServiceRegistry()); IndexStoreUtils.truncate(getServiceRegistry()); //Validate that docStore is empty DocumentStore docStore = context.getBean(DocumentStore.class); List<String> docKeys = docStore.getAllDocumentKeys(); assertTrue(docKeys.isEmpty()); IndexStore indexStore = context.getBean(IndexStore.class); assertTrue(indexStore.getAllDocumentKeys().isEmpty()); //Now Deploy the topology DocumentProcessorTopology docProcessorTopology = new DocumentProcessorTopology(topologyConfig); stormLocalCluster.submitTopology( topologyConfig.getProperty("ecm.topology.name"), stormLocalCluster.getConf(), docProcessorTopology.buildTopology()); LOG.info("Waiting until Topology is fully initialized"); Thread.sleep(10000); LOG.info("Done Waiting. Hopefully Topology is Initialized"); //Push NewDocumentRequest to Kafka String kafkaTopic = topologyConfig.getProperty("ecm.kafka.topic"); sendNewDocRequestToKafka(kafkaTopic); LOG.info("Waiting document is processed"); Thread.sleep(10000); LOG.info("Done Waiting. Hopefully Document is processed"); //Validate that Doc was prpersisted into the Document Store docKeys = docStore.getAllDocumentKeys(); assertThat(docKeys.size(), is(1)); String docKey = docKeys.get(0); assertNotNull(docKey); //Get the Document Details and validates DocumentDetails docDetails = docStore.getDocument(docKey); assertNotNull(docDetails); assertNotNull(docDetails.getDocContent()); //Validate the Doc Properties got persisted DocumentProperties docProperties = docDetails.getDocProperties(); assertThat(docProperties.getMimeType(), is("application/pdf")); assertThat(docProperties.getName(), is("State Farm RFP")); assertThat(docProperties.getExtension(), is(".pdf")); //Validate the Doc was added to the index Store docKeys = null; docKeys = indexStore.getAllDocumentKeys(); assertThat(docKeys.size(), is(1)); RFIDocument rfiDoc = indexStore.getDocument(docKeys.get(0)); assertNotNull(rfiDoc); assertNotNull(rfiDoc.getId()); assertNotNull(rfiDoc.getBody()); // Validate the Metadata was persisted assertThat(rfiDoc.getCustomername(), is("StateFarm")); assertThat(rfiDoc.getMimetype(), is("application/pdf")); assertThat(rfiDoc.getDocumentclass(), is(DocumentClass.RFP.getValue())); assertThat(rfiDoc.getDocumentname(), is("State Farm RFP")); }
void function() throws Exception { LOG.info(STR); DocumentStoreUtils.truncate(getServiceRegistry()); IndexStoreUtils.truncate(getServiceRegistry()); DocumentStore docStore = context.getBean(DocumentStore.class); List<String> docKeys = docStore.getAllDocumentKeys(); assertTrue(docKeys.isEmpty()); IndexStore indexStore = context.getBean(IndexStore.class); assertTrue(indexStore.getAllDocumentKeys().isEmpty()); DocumentProcessorTopology docProcessorTopology = new DocumentProcessorTopology(topologyConfig); stormLocalCluster.submitTopology( topologyConfig.getProperty(STR), stormLocalCluster.getConf(), docProcessorTopology.buildTopology()); LOG.info(STR); Thread.sleep(10000); LOG.info(STR); String kafkaTopic = topologyConfig.getProperty(STR); sendNewDocRequestToKafka(kafkaTopic); LOG.info(STR); Thread.sleep(10000); LOG.info(STR); docKeys = docStore.getAllDocumentKeys(); assertThat(docKeys.size(), is(1)); String docKey = docKeys.get(0); assertNotNull(docKey); DocumentDetails docDetails = docStore.getDocument(docKey); assertNotNull(docDetails); assertNotNull(docDetails.getDocContent()); DocumentProperties docProperties = docDetails.getDocProperties(); assertThat(docProperties.getMimeType(), is(STR)); assertThat(docProperties.getName(), is(STR)); assertThat(docProperties.getExtension(), is(".pdf")); docKeys = null; docKeys = indexStore.getAllDocumentKeys(); assertThat(docKeys.size(), is(1)); RFIDocument rfiDoc = indexStore.getDocument(docKeys.get(0)); assertNotNull(rfiDoc); assertNotNull(rfiDoc.getId()); assertNotNull(rfiDoc.getBody()); assertThat(rfiDoc.getCustomername(), is(STR)); assertThat(rfiDoc.getMimetype(), is(STR)); assertThat(rfiDoc.getDocumentclass(), is(DocumentClass.RFP.getValue())); assertThat(rfiDoc.getDocumentname(), is(STR)); }
/** * Tests the document processor topology by passing a DocRequest through the topology * and validating that it was persisted into the Index and Document Store. * @throws Exception */
Tests the document processor topology by passing a DocRequest through the topology and validating that it was persisted into the Index and Document Store
testDocumentProcessorTopology
{ "repo_name": "abeym/incubator", "path": "Trials/hdp/reference-apps/ecm-app/ecm-streaming/src/test/java/hortonworks/hdp/refapp/ecm/streaming/topology/DocumentProcessorTopologyLocalClusterTest.java", "license": "gpl-3.0", "size": 7560 }
[ "java.util.List", "org.hamcrest.CoreMatchers", "org.junit.Assert" ]
import java.util.List; import org.hamcrest.CoreMatchers; import org.junit.Assert;
import java.util.*; import org.hamcrest.*; import org.junit.*;
[ "java.util", "org.hamcrest", "org.junit" ]
java.util; org.hamcrest; org.junit;
2,108,124
@Symmetric public double[][] rndSymmetricMatrix(final int n) { final double emin = Randomizer.rndBox(getEvMin(), getEvMax()); final double emax = Randomizer.rndBox(getEvMin(), getEvMax()); return rndMatrix(n, emin, emax, true); }
double[][] function(final int n) { final double emin = Randomizer.rndBox(getEvMin(), getEvMax()); final double emax = Randomizer.rndBox(getEvMin(), getEvMax()); return rndMatrix(n, emin, emax, true); }
/** * Create a n times n random matrix with random eigenvalues between -5 and 5 (or the setter * values). * * @param n the dimension of the matrix * @return symmetric matrix with arbitrary random eigenvalues */
Create a n times n random matrix with random eigenvalues between -5 and 5 (or the setter values)
rndSymmetricMatrix
{ "repo_name": "axkr/symja_android_library", "path": "symja_android_library/matheclipse-external/src/main/java/de/lab4inf/math/lapack/Matrices.java", "license": "gpl-3.0", "size": 12560 }
[ "de.lab4inf.math.util.Randomizer" ]
import de.lab4inf.math.util.Randomizer;
import de.lab4inf.math.util.*;
[ "de.lab4inf.math" ]
de.lab4inf.math;
1,282,516
public InputStream getStream();
InputStream function();
/** * Gets stream. * * @return the stream */
Gets stream
getStream
{ "repo_name": "MSOpenTech/orc-for-java-shared", "path": "orc-engine-core/src/main/java/com/microsoft/services/orc/interfaces/Response.java", "license": "mit", "size": 848 }
[ "java.io.InputStream" ]
import java.io.InputStream;
import java.io.*;
[ "java.io" ]
java.io;
2,784,981
public static void main(String[] args) throws Exception { File inFile = new File(args[0]); float[] arr1; float[] arr2; try (BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(inFile)))) { // Processing the first line. int numLines = Integer.parseInt(br.readLine()); arr1 = new float[numLines]; arr2 = new float[numLines]; String[] pair; String s; // Processing the remaining lines. for (int i = 0; i < numLines; i++) { s = br.readLine(); pair = s.split(","); arr1[i] = Float.parseFloat(pair[0]); arr2[i] = Float.parseFloat(pair[1]); } TTests tt = new TTests(); int retVal = tt.pairedTwoTailedCorrectedResampled( arr1, arr2, 0.9f, 0.1f); switch (retVal) { case NO_SIGNIFICANCE: { System.out.println("no significance"); break; } case SIGNIFICANCE_5: { System.out.println("significance level 0.5"); break; } case SIGNIFICANCE_1: { System.out.println("significance level 0.01"); break; } } } catch (Exception e) { throw e; } }
static void function(String[] args) throws Exception { File inFile = new File(args[0]); float[] arr1; float[] arr2; try (BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(inFile)))) { int numLines = Integer.parseInt(br.readLine()); arr1 = new float[numLines]; arr2 = new float[numLines]; String[] pair; String s; for (int i = 0; i < numLines; i++) { s = br.readLine(); pair = s.split(","); arr1[i] = Float.parseFloat(pair[0]); arr2[i] = Float.parseFloat(pair[1]); } TTests tt = new TTests(); int retVal = tt.pairedTwoTailedCorrectedResampled( arr1, arr2, 0.9f, 0.1f); switch (retVal) { case NO_SIGNIFICANCE: { System.out.println(STR); break; } case SIGNIFICANCE_5: { System.out.println(STR); break; } case SIGNIFICANCE_1: { System.out.println(STR); break; } } } catch (Exception e) { throw e; } }
/** * arg0: One csv file with two columns to be compared by the corrected * re-sampled t-test. First line in the file is the number of rows. * * @param args Command line arguments. A single argument pointing to the csv * file that contains the columns to be compared, preceded by a number of * rows on a separate line. * @throws Exception */
arg0: One csv file with two columns to be compared by the corrected re-sampled t-test. First line in the file is the number of rows
main
{ "repo_name": "datapoet/hubminer", "path": "src/main/java/statistics/tests/TTests.java", "license": "gpl-3.0", "size": 9582 }
[ "java.io.BufferedReader", "java.io.File", "java.io.FileInputStream", "java.io.InputStreamReader" ]
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader;
import java.io.*;
[ "java.io" ]
java.io;
658,827
protected void responseReady(EndpointInvocationContext eic) { List<InvocationListener> listenerList = eic.getInvocationListeners(); if(listenerList != null) { InvocationListenerBean bean = new InvocationListenerBean(eic, InvocationListenerBean.State.RESPONSE); for(InvocationListener listener : listenerList) { try { listener.notify(bean); } catch(Exception e) { throw ExceptionFactory.makeWebServiceException(e); } } } }
void function(EndpointInvocationContext eic) { List<InvocationListener> listenerList = eic.getInvocationListeners(); if(listenerList != null) { InvocationListenerBean bean = new InvocationListenerBean(eic, InvocationListenerBean.State.RESPONSE); for(InvocationListener listener : listenerList) { try { listener.notify(bean); } catch(Exception e) { throw ExceptionFactory.makeWebServiceException(e); } } } }
/** * This will call the InvocationListener instances that were called during * the request processing for this message. */
This will call the InvocationListener instances that were called during the request processing for this message
responseReady
{ "repo_name": "Everteam-Software/axis2", "path": "modules/jaxws/src/org/apache/axis2/jaxws/server/EndpointCallback.java", "license": "apache-2.0", "size": 7539 }
[ "java.util.List", "org.apache.axis2.jaxws.ExceptionFactory" ]
import java.util.List; import org.apache.axis2.jaxws.ExceptionFactory;
import java.util.*; import org.apache.axis2.jaxws.*;
[ "java.util", "org.apache.axis2" ]
java.util; org.apache.axis2;
2,119,120
public void sendButton(short code, boolean repeat, boolean down, boolean queue, short amount, byte axis) throws IOException;
void function(short code, boolean repeat, boolean down, boolean queue, short amount, byte axis) throws IOException;
/** * Sends a Button event * * @param code Raw button code (default: 0) * @param repeat This key press should repeat until released (default: 1) * Note that queued pressed cannot repeat. * @param down If this is 1, it implies a press event, 0 implies a * release event. (default: 1) * @param queue A queued key press means that the button event is executed * just once after which the next key press is processed. It * can be used for macros. Currently there is no support for * time delays between queued presses. (default: 0) * @param amount Unimplemented for now; in the future it will be used for * specifying magnitude of analog key press events * @param axis */
Sends a Button event
sendButton
{ "repo_name": "freezy/android-xbmcremote", "path": "src/org/xbmc/api/business/IEventClientManager.java", "license": "gpl-2.0", "size": 4884 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
2,507,831
default void postScannerClose(final ObserverContext<RegionCoprocessorEnvironment> ctx, final InternalScanner s) throws IOException {}
default void postScannerClose(final ObserverContext<RegionCoprocessorEnvironment> ctx, final InternalScanner s) throws IOException {}
/** * Called after the client closes a scanner. * <p> * Call CoprocessorEnvironment#complete to skip any subsequent chained * coprocessors * @param ctx the environment provided by the region server * @param s the scanner */
Called after the client closes a scanner. Call CoprocessorEnvironment#complete to skip any subsequent chained coprocessors
postScannerClose
{ "repo_name": "gustavoanatoly/hbase", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/RegionObserver.java", "license": "apache-2.0", "size": 67737 }
[ "java.io.IOException", "org.apache.hadoop.hbase.regionserver.InternalScanner" ]
import java.io.IOException; import org.apache.hadoop.hbase.regionserver.InternalScanner;
import java.io.*; import org.apache.hadoop.hbase.regionserver.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
2,521,568
EngineSession get(long id);
EngineSession get(long id);
/** * Retrieves the session with the specified id. * * @param id the id * @return the engine session */
Retrieves the session with the specified id
get
{ "repo_name": "jtux270/translate", "path": "ovirt/3.6_source/backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/EngineSessionDao.java", "license": "gpl-3.0", "size": 1055 }
[ "org.ovirt.engine.core.common.businessentities.EngineSession" ]
import org.ovirt.engine.core.common.businessentities.EngineSession;
import org.ovirt.engine.core.common.businessentities.*;
[ "org.ovirt.engine" ]
org.ovirt.engine;
2,676,701
@ApiModelProperty(example = "null", value = "This section contains the transcript in a variety of formats") public VbTranscript getTranscript() { return transcript; }
@ApiModelProperty(example = "null", value = STR) VbTranscript function() { return transcript; }
/** * This section contains the transcript in a variety of formats * @return transcript **/
This section contains the transcript in a variety of formats
getTranscript
{ "repo_name": "jbocharov/voicebase-java-samples", "path": "v3-upload-transcribe/src/main/java/com/voicebase/sample/v3client/model/VbMedia.java", "license": "mit", "size": 11899 }
[ "com.voicebase.sample.v3client.model.VbTranscript", "io.swagger.annotations.ApiModelProperty" ]
import com.voicebase.sample.v3client.model.VbTranscript; import io.swagger.annotations.ApiModelProperty;
import com.voicebase.sample.v3client.model.*; import io.swagger.annotations.*;
[ "com.voicebase.sample", "io.swagger.annotations" ]
com.voicebase.sample; io.swagger.annotations;
2,554,866
public VirtualMachineRunCommandUpdate withParameters(List<RunCommandInputParameter> parameters) { if (this.innerProperties() == null) { this.innerProperties = new VirtualMachineRunCommandProperties(); } this.innerProperties().withParameters(parameters); return this; }
VirtualMachineRunCommandUpdate function(List<RunCommandInputParameter> parameters) { if (this.innerProperties() == null) { this.innerProperties = new VirtualMachineRunCommandProperties(); } this.innerProperties().withParameters(parameters); return this; }
/** * Set the parameters property: The parameters used by the script. * * @param parameters the parameters value to set. * @return the VirtualMachineRunCommandUpdate object itself. */
Set the parameters property: The parameters used by the script
withParameters
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/resourcemanagerhybrid/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/VirtualMachineRunCommandUpdate.java", "license": "mit", "size": 10271 }
[ "com.azure.resourcemanager.compute.fluent.models.VirtualMachineRunCommandProperties", "java.util.List" ]
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineRunCommandProperties; import java.util.List;
import com.azure.resourcemanager.compute.fluent.models.*; import java.util.*;
[ "com.azure.resourcemanager", "java.util" ]
com.azure.resourcemanager; java.util;
355,098
public static <E> ArrayDeque<E> newArrayDeque(final E first, final E... rest) { checkNotNull(first); checkNotNull(rest); final ArrayDeque<E> arrayDeque = new ArrayDeque<E>(rest.length + 1); arrayDeque.add(first); Collections.addAll(arrayDeque, rest); return arrayDeque; }
static <E> ArrayDeque<E> function(final E first, final E... rest) { checkNotNull(first); checkNotNull(rest); final ArrayDeque<E> arrayDeque = new ArrayDeque<E>(rest.length + 1); arrayDeque.add(first); Collections.addAll(arrayDeque, rest); return arrayDeque; }
/** * Creates an {@code ArrayDeque} containing the specified initial elements. * * @param first * the first element * @param rest * an array of additional elements, possibly empty * @return an {@code ArrayDeque} containing the specified initial elements */
Creates an ArrayDeque containing the specified initial elements
newArrayDeque
{ "repo_name": "google-code/biscotti", "path": "src/com/palamida/util/collect/MoreQueues.java", "license": "apache-2.0", "size": 6233 }
[ "com.google.common.base.Preconditions", "java.util.ArrayDeque", "java.util.Collections" ]
import com.google.common.base.Preconditions; import java.util.ArrayDeque; import java.util.Collections;
import com.google.common.base.*; import java.util.*;
[ "com.google.common", "java.util" ]
com.google.common; java.util;
391,634
public HstsConfig httpStrictTransportSecurity() { return this.hsts.enable(); } /** * Allows customizing the {@link HstsHeaderWriter} which provides support for * <a href="https://tools.ietf.org/html/rfc6797">HTTP Strict Transport Security * (HSTS)</a>. * @param hstsCustomizer the {@link Customizer} to provide more options for the * {@link HstsConfig}
HstsConfig function() { return this.hsts.enable(); } /** * Allows customizing the {@link HstsHeaderWriter} which provides support for * <a href="https: * (HSTS)</a>. * @param hstsCustomizer the {@link Customizer} to provide more options for the * {@link HstsConfig}
/** * Allows customizing the {@link HstsHeaderWriter} which provides support for * <a href="https://tools.ietf.org/html/rfc6797">HTTP Strict Transport Security * (HSTS)</a>. * @return the {@link HstsConfig} for additional customizations */
Allows customizing the <code>HstsHeaderWriter</code> which provides support for HTTP Strict Transport Security (HSTS)
httpStrictTransportSecurity
{ "repo_name": "fhanik/spring-security", "path": "config/src/main/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurer.java", "license": "apache-2.0", "size": 33246 }
[ "org.springframework.security.config.Customizer", "org.springframework.security.web.header.writers.HstsHeaderWriter" ]
import org.springframework.security.config.Customizer; import org.springframework.security.web.header.writers.HstsHeaderWriter;
import org.springframework.security.config.*; import org.springframework.security.web.header.writers.*;
[ "org.springframework.security" ]
org.springframework.security;
1,963,813
public boolean offer(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { boolean ok = q.offer(e); assert ok; notEmpty.signal(); return true; } finally { lock.unlock(); } }
boolean function(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { boolean ok = q.offer(e); assert ok; notEmpty.signal(); return true; } finally { lock.unlock(); } }
/** * Inserts the specified element into this priority queue. * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Queue#offer}) * @throws ClassCastException if the specified element cannot be compared * with elements currently in the priority queue according to the * priority queue's ordering * @throws NullPointerException if the specified element is null */
Inserts the specified element into this priority queue
offer
{ "repo_name": "openweave/openweave-core", "path": "third_party/android/platform-libcore/android-platform-libcore/luni/src/main/java/java/util/concurrent/PriorityBlockingQueue.java", "license": "apache-2.0", "size": 19895 }
[ "java.util.concurrent.locks.ReentrantLock" ]
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.*;
[ "java.util" ]
java.util;
2,186,979
public DeviceAddGroupPage addNewGroup() throws IOException { driver.findElement(By.xpath("iot.home.page.uuf-menu.xpath")).click(); driver.findElement(By.xpath("iot.home.page.uuf-menu.groupmgt.xpath")).click(); driver.findElement(By.xpath("iot.device.viewGroup.empty.addGroup.xpath")).click(); return new DeviceAddGroupPage(driver); } //ToDo : To add policies
DeviceAddGroupPage function() throws IOException { driver.findElement(By.xpath(STR)).click(); driver.findElement(By.xpath(STR)).click(); driver.findElement(By.xpath(STR)).click(); return new DeviceAddGroupPage(driver); }
/** * Performs the navigation to Add device group page. * @return : Add Device Group page. */
Performs the navigation to Add device group page
addNewGroup
{ "repo_name": "madhawap/product-iots", "path": "modules/integration/tests-common/web-ui-pages/src/main/java/org/wso2/iot/integration/ui/pages/home/IOTHomePage.java", "license": "apache-2.0", "size": 3713 }
[ "java.io.IOException", "org.openqa.selenium.By", "org.wso2.iot.integration.ui.pages.groups.DeviceAddGroupPage" ]
import java.io.IOException; import org.openqa.selenium.By; import org.wso2.iot.integration.ui.pages.groups.DeviceAddGroupPage;
import java.io.*; import org.openqa.selenium.*; import org.wso2.iot.integration.ui.pages.groups.*;
[ "java.io", "org.openqa.selenium", "org.wso2.iot" ]
java.io; org.openqa.selenium; org.wso2.iot;
409,288
@ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<ResourceSkuInner> list();
@ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<ResourceSkuInner> list();
/** * Gets the list of Microsoft.Compute SKUs available for your Subscription. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the list of Microsoft.Compute SKUs available for your Subscription. */
Gets the list of Microsoft.Compute SKUs available for your Subscription
list
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/resourcemanagerhybrid/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/fluent/ResourceSkusClient.java", "license": "mit", "size": 3139 }
[ "com.azure.core.annotation.ReturnType", "com.azure.core.annotation.ServiceMethod", "com.azure.core.http.rest.PagedIterable", "com.azure.resourcemanager.compute.fluent.models.ResourceSkuInner" ]
import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.resourcemanager.compute.fluent.models.ResourceSkuInner;
import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.resourcemanager.compute.fluent.models.*;
[ "com.azure.core", "com.azure.resourcemanager" ]
com.azure.core; com.azure.resourcemanager;
53,002
@Override public void contextInitialized(ServletContextEvent context) { logger.info("** Initializing DnsServiceListener"); System.out.println("*** Initializing DnsServiceListener"); // Only create a route53 service config if its not running in // a system master node. if (! createRoute53Config()) { loadRoute53Service(); } logger.info("** Initialized DnsServiceListener"); System.out.println("*** Initialized DnsServiceListener"); }
void function(ServletContextEvent context) { logger.info(STR); System.out.println(STR); if (! createRoute53Config()) { loadRoute53Service(); } logger.info(STR); System.out.println(STR); }
/** * Context initialization method. */
Context initialization method
contextInitialized
{ "repo_name": "deleidos/digitaledge-platform", "path": "webapp-dnsapi/src/main/java/com/deleidos/rtws/webapp/dnsapi/listener/DNSServiceListener.java", "license": "apache-2.0", "size": 13889 }
[ "javax.servlet.ServletContextEvent" ]
import javax.servlet.ServletContextEvent;
import javax.servlet.*;
[ "javax.servlet" ]
javax.servlet;
387,384
@Override public void executeSymbolically(Frame frame) throws NoExceptionHandlerFoundException, SymbolicExecutionException { try { Object object = provideSymbolicObject(frame); if (object == null) throw new ExecutionException("Wrong type fetched from constant_pool for " + getName() + " instruction."); frame.getOperandStack().push(object); } catch (VmRuntimeException e) { SymbolicExceptionHandler handler = new SymbolicExceptionHandler(frame, e); try { handler.handleException(); } catch (ExecutionException e2) { executionFailedSymbolically(e2); } } catch (ExecutionException e) { symbolicExecutionFailedWithAnExecutionException(e); } }
void function(Frame frame) throws NoExceptionHandlerFoundException, SymbolicExecutionException { try { Object object = provideSymbolicObject(frame); if (object == null) throw new ExecutionException(STR + getName() + STR); frame.getOperandStack().push(object); } catch (VmRuntimeException e) { SymbolicExceptionHandler handler = new SymbolicExceptionHandler(frame, e); try { handler.handleException(); } catch (ExecutionException e2) { executionFailedSymbolically(e2); } } catch (ExecutionException e) { symbolicExecutionFailedWithAnExecutionException(e); } }
/** * Execute the inheriting instruction symbolically. * * @param frame The currently executed frame. * @throws NoExceptionHandlerFoundException If no handler could be found. * @throws SymbolicExecutionException Thrown in case of fatal problems during the symbolic execution. */
Execute the inheriting instruction symbolically
executeSymbolically
{ "repo_name": "wwu-pi/muggl", "path": "muggl-core/src/de/wwu/muggl/instructions/general/PushFromConstantPool.java", "license": "gpl-3.0", "size": 14660 }
[ "de.wwu.muggl.vm.Frame", "de.wwu.muggl.vm.exceptions.NoExceptionHandlerFoundException", "de.wwu.muggl.vm.exceptions.VmRuntimeException", "de.wwu.muggl.vm.execution.ExecutionException", "de.wwu.muggl.vm.impl.symbolic.SymbolicExecutionException", "de.wwu.muggl.vm.impl.symbolic.exceptions.SymbolicExceptionHandler" ]
import de.wwu.muggl.vm.Frame; import de.wwu.muggl.vm.exceptions.NoExceptionHandlerFoundException; import de.wwu.muggl.vm.exceptions.VmRuntimeException; import de.wwu.muggl.vm.execution.ExecutionException; import de.wwu.muggl.vm.impl.symbolic.SymbolicExecutionException; import de.wwu.muggl.vm.impl.symbolic.exceptions.SymbolicExceptionHandler;
import de.wwu.muggl.vm.*; import de.wwu.muggl.vm.exceptions.*; import de.wwu.muggl.vm.execution.*; import de.wwu.muggl.vm.impl.symbolic.*; import de.wwu.muggl.vm.impl.symbolic.exceptions.*;
[ "de.wwu.muggl" ]
de.wwu.muggl;
2,103,534
public static void disableExpiredAlarms(final Context context) { Cursor cur = getFilteredAlarmsCursor(context.getContentResolver()); long now = System.currentTimeMillis(); try { if (cur.moveToFirst()) { do { Alarm alarm = new Alarm(cur); // A time of 0 means this alarm repeats. If the time is // non-zero, check if the time is before now. if (alarm.time != 0 && alarm.time < now) { Log.v(TAG, "Disabling expired alarm set for " + formatTime(alarm.time)); enableAlarmInternal(context, alarm, false); } } while (cur.moveToNext()); } } finally { cur.close(); } }
static void function(final Context context) { Cursor cur = getFilteredAlarmsCursor(context.getContentResolver()); long now = System.currentTimeMillis(); try { if (cur.moveToFirst()) { do { Alarm alarm = new Alarm(cur); if (alarm.time != 0 && alarm.time < now) { Log.v(TAG, STR + formatTime(alarm.time)); enableAlarmInternal(context, alarm, false); } } while (cur.moveToNext()); } } finally { cur.close(); } }
/** * Disables non-repeating alarms that have passed. Called at * boot. */
Disables non-repeating alarms that have passed. Called at boot
disableExpiredAlarms
{ "repo_name": "rex-xxx/mt6572_x201", "path": "mediatek/frameworks-ext/base/policy/java/com/android/internal/policy/impl/keyguard/Alarms.java", "license": "gpl-2.0", "size": 25201 }
[ "android.content.Context", "android.database.Cursor", "android.util.Log" ]
import android.content.Context; import android.database.Cursor; import android.util.Log;
import android.content.*; import android.database.*; import android.util.*;
[ "android.content", "android.database", "android.util" ]
android.content; android.database; android.util;
407,516
@Override public void loadDataFromDB() throws InitializationException { int Index; ResultSetMetaData Rsmd; int ColumnCount; int ObjectLinesLoaded = 0; String tmpGroup; long tmpRangeFrom; long tmpRangeTo; long tmpValidityFrom; long tmpValidityTo; // Find the location of the zone configuration file OpenRate.getOpenRateFrameworkLog().info("Starting Zone Cache Loading from DB"); // Try to open the DS JDBCcon = DBUtil.getConnection(cacheDataSourceName); // Now prepare the statements prepareStatements(); // Execute the query try { mrs = StmtCacheDataSelectQuery.executeQuery(); } catch (SQLException ex) { message = "Error performing SQL for retieving Indexed Matchdata"; throw new InitializationException(message,ex,getSymbolicName()); } // loop through the results for the customer login cache try { Rsmd = mrs.getMetaData(); ColumnCount = Rsmd.getColumnCount(); mrs.beforeFirst(); while (mrs.next()) { ObjectLinesLoaded++; tmpGroup = mrs.getString(1); tmpRangeFrom = mrs.getLong(2); tmpRangeTo = mrs.getLong(3); tmpValidityFrom = mrs.getLong(4); tmpValidityTo = mrs.getLong(5); ArrayList<String> tmpResults = new ArrayList<>(); for (Index = 6 ; Index <= ColumnCount ; Index++) { tmpResults.add(mrs.getString(Index)); } // Add into the cache addEntry(tmpGroup,tmpRangeFrom,tmpRangeTo,tmpValidityFrom,tmpValidityTo,tmpResults); // Update to the log file if ((ObjectLinesLoaded % loadingLogNotificationStep) == 0) { message = "Number Range Data Loading: <" + ObjectLinesLoaded + "> configurations loaded for <" + getSymbolicName() + "> from <" + cacheDataSourceName + ">"; OpenRate.getOpenRateFrameworkLog().info(message); } } } catch (SQLException ex) { message = "Error opening Search Map Data for <" + cacheDataSourceName + ">"; throw new InitializationException(message,ex,getSymbolicName()); } // Close down stuff try { mrs.close(); StmtCacheDataSelectQuery.close(); JDBCcon.close(); } catch (SQLException ex) { message = "Error closing Search Map Data connection for <" + cacheDataSourceName + ">"; throw new InitializationException(message,ex,getSymbolicName()); } OpenRate.getOpenRateFrameworkLog().info( "Number Range Data Loading completed. <" + ObjectLinesLoaded + "> configuration lines loaded from <" + cacheDataSourceName + ">"); }
void function() throws InitializationException { int Index; ResultSetMetaData Rsmd; int ColumnCount; int ObjectLinesLoaded = 0; String tmpGroup; long tmpRangeFrom; long tmpRangeTo; long tmpValidityFrom; long tmpValidityTo; OpenRate.getOpenRateFrameworkLog().info(STR); JDBCcon = DBUtil.getConnection(cacheDataSourceName); prepareStatements(); try { mrs = StmtCacheDataSelectQuery.executeQuery(); } catch (SQLException ex) { message = STR; throw new InitializationException(message,ex,getSymbolicName()); } try { Rsmd = mrs.getMetaData(); ColumnCount = Rsmd.getColumnCount(); mrs.beforeFirst(); while (mrs.next()) { ObjectLinesLoaded++; tmpGroup = mrs.getString(1); tmpRangeFrom = mrs.getLong(2); tmpRangeTo = mrs.getLong(3); tmpValidityFrom = mrs.getLong(4); tmpValidityTo = mrs.getLong(5); ArrayList<String> tmpResults = new ArrayList<>(); for (Index = 6 ; Index <= ColumnCount ; Index++) { tmpResults.add(mrs.getString(Index)); } addEntry(tmpGroup,tmpRangeFrom,tmpRangeTo,tmpValidityFrom,tmpValidityTo,tmpResults); if ((ObjectLinesLoaded % loadingLogNotificationStep) == 0) { message = STR + ObjectLinesLoaded + STR + getSymbolicName() + STR + cacheDataSourceName + ">"; OpenRate.getOpenRateFrameworkLog().info(message); } } } catch (SQLException ex) { message = STR + cacheDataSourceName + ">"; throw new InitializationException(message,ex,getSymbolicName()); } try { mrs.close(); StmtCacheDataSelectQuery.close(); JDBCcon.close(); } catch (SQLException ex) { message = STR + cacheDataSourceName + ">"; throw new InitializationException(message,ex,getSymbolicName()); } OpenRate.getOpenRateFrameworkLog().info( STR + ObjectLinesLoaded + STR + cacheDataSourceName + ">"); }
/** * Load the data from the defined Data Source */
Load the data from the defined Data Source
loadDataFromDB
{ "repo_name": "isparkes/OpenRate", "path": "src/main/java/OpenRate/cache/NumberRangeCache.java", "license": "apache-2.0", "size": 19807 }
[ "java.sql.ResultSetMetaData", "java.sql.SQLException", "java.util.ArrayList" ]
import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList;
import java.sql.*; import java.util.*;
[ "java.sql", "java.util" ]
java.sql; java.util;
2,245,283
public void save(final File file, final CSVSyntax config) throws IOException { checkReleased(); final CSVDataOutput output = new CSVDataOutput(file, config); output.write(iterator()); }
void function(final File file, final CSVSyntax config) throws IOException { checkReleased(); final CSVDataOutput output = new CSVDataOutput(file, config); output.write(iterator()); }
/** * Writes the data to a CSV file. * * @param file the file * @param config the config * @throws IOException Signals that an I/O exception has occurred. */
Writes the data to a CSV file
save
{ "repo_name": "arx-deidentifier/arx", "path": "src/main/org/deidentifier/arx/DataHandle.java", "license": "apache-2.0", "size": 36257 }
[ "java.io.File", "java.io.IOException", "org.deidentifier.arx.io.CSVDataOutput", "org.deidentifier.arx.io.CSVSyntax" ]
import java.io.File; import java.io.IOException; import org.deidentifier.arx.io.CSVDataOutput; import org.deidentifier.arx.io.CSVSyntax;
import java.io.*; import org.deidentifier.arx.io.*;
[ "java.io", "org.deidentifier.arx" ]
java.io; org.deidentifier.arx;
403,413
public void runTest(RestTest restTest, String baseApiUrl) throws Error { String requestPath = TestUtil.doPropertyReplacement(restTest.getRequestPath()); URI uri = null; try { uri = getUri(baseApiUrl, requestPath); } catch (URISyntaxException e) { throw new RuntimeException("Invalid URI", e); } log("Sending HTTP request to: " + uri); Request request = new ApacheRequest(uri.toString()).method(restTest.getRequestMethod()); try { Map<String, String> requestHeaders = restTest.getRequestHeaders(); for (Entry<String, String> entry : requestHeaders.entrySet()) { String value = TestUtil.doPropertyReplacement(entry.getValue()); // Handle system properties that may be configured in the rest-test itself if (entry.getKey().startsWith("X-RestTest-System-Property")) { String[] split = value.split("="); System.setProperty(split[0], split[1]); continue; } if (entry.getKey().equals("Content-Type")) { String contentType = entry.getKey() != null ? StringUtils.appendIfMissing(value, "; charset=UTF-8") : "text/plain; charset=UTF-8"; request = request.header(entry.getKey(), contentType); } else { request = request.header(entry.getKey(), value); } } // Set up basic auth String authorization = createBasicAuthorization(restTest.getUsername(), restTest.getPassword()); if (authorization != null) { request = request.header("Authorization", authorization); } if (restTest.getRequestPayload() != null && !restTest.getRequestPayload().isEmpty()) { request = request.body().set(restTest.getRequestPayload()).back(); } assertResponse(restTest, request.fetch()); } catch (Error e) { logPlain("[ERROR] " + e.getMessage()); throw e; } catch (ProtocolException e) { logPlain("[HTTP PROTOCOL EXCEPTION] " + e.getMessage()); throw new Error(e); } catch (IOException e) { logPlain("[IO EXCEPTION] " + e.getMessage()); throw new Error(e); } catch (Exception e) { logPlain("[EXCEPTION] " + e.getMessage()); throw new Error(e); } }
void function(RestTest restTest, String baseApiUrl) throws Error { String requestPath = TestUtil.doPropertyReplacement(restTest.getRequestPath()); URI uri = null; try { uri = getUri(baseApiUrl, requestPath); } catch (URISyntaxException e) { throw new RuntimeException(STR, e); } log(STR + uri); Request request = new ApacheRequest(uri.toString()).method(restTest.getRequestMethod()); try { Map<String, String> requestHeaders = restTest.getRequestHeaders(); for (Entry<String, String> entry : requestHeaders.entrySet()) { String value = TestUtil.doPropertyReplacement(entry.getValue()); if (entry.getKey().startsWith(STR)) { String[] split = value.split("="); System.setProperty(split[0], split[1]); continue; } if (entry.getKey().equals(STR)) { String contentType = entry.getKey() != null ? StringUtils.appendIfMissing(value, STR) : STR; request = request.header(entry.getKey(), contentType); } else { request = request.header(entry.getKey(), value); } } String authorization = createBasicAuthorization(restTest.getUsername(), restTest.getPassword()); if (authorization != null) { request = request.header(STR, authorization); } if (restTest.getRequestPayload() != null && !restTest.getRequestPayload().isEmpty()) { request = request.body().set(restTest.getRequestPayload()).back(); } assertResponse(restTest, request.fetch()); } catch (Error e) { logPlain(STR + e.getMessage()); throw e; } catch (ProtocolException e) { logPlain(STR + e.getMessage()); throw new Error(e); } catch (IOException e) { logPlain(STR + e.getMessage()); throw new Error(e); } catch (Exception e) { logPlain(STR + e.getMessage()); throw new Error(e); } }
/** * Runs a single REST test. * * @param restTest * @param baseApiUrl * @throws Error */
Runs a single REST test
runTest
{ "repo_name": "kahboom/apiman", "path": "test/common/src/main/java/io/apiman/test/common/util/TestPlanRunner.java", "license": "apache-2.0", "size": 20912 }
[ "com.jcabi.http.Request", "com.jcabi.http.request.ApacheRequest", "io.apiman.test.common.resttest.RestTest", "java.io.IOException", "java.net.ProtocolException", "java.net.URISyntaxException", "java.util.Map", "org.apache.commons.lang3.StringUtils" ]
import com.jcabi.http.Request; import com.jcabi.http.request.ApacheRequest; import io.apiman.test.common.resttest.RestTest; import java.io.IOException; import java.net.ProtocolException; import java.net.URISyntaxException; import java.util.Map; import org.apache.commons.lang3.StringUtils;
import com.jcabi.http.*; import com.jcabi.http.request.*; import io.apiman.test.common.resttest.*; import java.io.*; import java.net.*; import java.util.*; import org.apache.commons.lang3.*;
[ "com.jcabi.http", "io.apiman.test", "java.io", "java.net", "java.util", "org.apache.commons" ]
com.jcabi.http; io.apiman.test; java.io; java.net; java.util; org.apache.commons;
1,995,491
public void setWorkTask(WorkTask newWorkTask) { if (newWorkTask != workTask) { NotificationChain msgs = null; if (workTask != null) msgs = ((InternalEObject)workTask).eInverseRemove(this, InfWorkPackage.WORK_TASK__WORK_COST_DETAILS, WorkTask.class, msgs); if (newWorkTask != null) msgs = ((InternalEObject)newWorkTask).eInverseAdd(this, InfWorkPackage.WORK_TASK__WORK_COST_DETAILS, WorkTask.class, msgs); msgs = basicSetWorkTask(newWorkTask, msgs); if (msgs != null) msgs.dispatch(); } }
void function(WorkTask newWorkTask) { if (newWorkTask != workTask) { NotificationChain msgs = null; if (workTask != null) msgs = ((InternalEObject)workTask).eInverseRemove(this, InfWorkPackage.WORK_TASK__WORK_COST_DETAILS, WorkTask.class, msgs); if (newWorkTask != null) msgs = ((InternalEObject)newWorkTask).eInverseAdd(this, InfWorkPackage.WORK_TASK__WORK_COST_DETAILS, WorkTask.class, msgs); msgs = basicSetWorkTask(newWorkTask, msgs); if (msgs != null) msgs.dispatch(); } }
/** * Sets the value of the '{@link CIM15.IEC61970.Informative.InfWork.WorkCostDetail#getWorkTask <em>Work Task</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Work Task</em>' reference. * @see #getWorkTask() * @generated */
Sets the value of the '<code>CIM15.IEC61970.Informative.InfWork.WorkCostDetail#getWorkTask Work Task</code>' reference.
setWorkTask
{ "repo_name": "SES-fortiss/SmartGridCoSimulation", "path": "core/cim15/src/CIM15/IEC61970/Informative/InfWork/WorkCostDetail.java", "license": "apache-2.0", "size": 49803 }
[ "org.eclipse.emf.common.notify.NotificationChain", "org.eclipse.emf.ecore.InternalEObject" ]
import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.common.notify.*; import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
108,153
protected Transition buildTransition(Element element) throws WorkflowException { String id = element.getAttribute("id"); String source = element.getAttribute("from"); String destination = element.getAttribute("to"); TransitionImpl transition = new TransitionImpl(id, source, destination); NodeList conditionElements = element.getElementsByTagNameNS(Workflow.NAMESPACE, "condition"); Condition[] conditions = new Condition[conditionElements.getLength()]; for (int i = 0; i < conditionElements.getLength(); i++) { conditions[i] = buildCondition((Element) conditionElements.item(i)); } transition.setConditions(conditions); NodeList actionElements = element.getElementsByTagNameNS(Workflow.NAMESPACE, "action"); Action[] actions = new Action[actionElements.getLength()]; for (int i = 0; i < actionElements.getLength(); i++) { actions[i] = buildAction((Element) actionElements.item(i)); } transition.setActions(actions); NodeList descriptionElements = element.getElementsByTagNameNS(Workflow.NAMESPACE, "description"); for (int i = 0; i < descriptionElements.getLength(); i++) { Element desc = (Element)descriptionElements.item(i); String language = desc.getAttribute("xml:lang"); String description = desc.getFirstChild().getNodeValue(); transition.addDescription(description, language); } return transition; }
Transition function(Element element) throws WorkflowException { String id = element.getAttribute("id"); String source = element.getAttribute("from"); String destination = element.getAttribute("to"); TransitionImpl transition = new TransitionImpl(id, source, destination); NodeList conditionElements = element.getElementsByTagNameNS(Workflow.NAMESPACE, STR); Condition[] conditions = new Condition[conditionElements.getLength()]; for (int i = 0; i < conditionElements.getLength(); i++) { conditions[i] = buildCondition((Element) conditionElements.item(i)); } transition.setConditions(conditions); NodeList actionElements = element.getElementsByTagNameNS(Workflow.NAMESPACE, STR); Action[] actions = new Action[actionElements.getLength()]; for (int i = 0; i < actionElements.getLength(); i++) { actions[i] = buildAction((Element) actionElements.item(i)); } transition.setActions(actions); NodeList descriptionElements = element.getElementsByTagNameNS(Workflow.NAMESPACE, STR); for (int i = 0; i < descriptionElements.getLength(); i++) { Element desc = (Element)descriptionElements.item(i); String language = desc.getAttribute(STR); String description = desc.getFirstChild().getNodeValue(); transition.addDescription(description, language); } return transition; }
/** * Builds a transition from an XML element. * @param element An XML element. * @return A transition. * @throws WorkflowException when something went wrong. */
Builds a transition from an XML element
buildTransition
{ "repo_name": "baszero/yanel", "path": "src/core/java/org/wyona/yanel/core/workflow/WorkflowBuilder.java", "license": "apache-2.0", "size": 7971 }
[ "org.w3c.dom.Element", "org.w3c.dom.NodeList", "org.wyona.yanel.core.workflow.impl.TransitionImpl" ]
import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.wyona.yanel.core.workflow.impl.TransitionImpl;
import org.w3c.dom.*; import org.wyona.yanel.core.workflow.impl.*;
[ "org.w3c.dom", "org.wyona.yanel" ]
org.w3c.dom; org.wyona.yanel;
1,761,290
public Document read(InputStream in) throws DocumentException, IOException, XmlPullParserException { return read(createReader(in)); }
Document function(InputStream in) throws DocumentException, IOException, XmlPullParserException { return read(createReader(in)); }
/** * <p> * Reads a Document from the given stream * </p> * * @param in * <code>InputStream</code> to read from. * * @return the newly created Document instance * * @throws DocumentException * if an error occurs during parsing. * @throws IOException * DOCUMENT ME! * @throws XmlPullParserException * DOCUMENT ME! */
Reads a Document from the given stream
read
{ "repo_name": "AndreasMaring/text2epc", "path": "dom4j-1.6.1/src/java/org/dom4j/io/XPP3Reader.java", "license": "gpl-3.0", "size": 17646 }
[ "java.io.IOException", "java.io.InputStream", "org.dom4j.Document", "org.dom4j.DocumentException", "org.xmlpull.v1.XmlPullParserException" ]
import java.io.IOException; import java.io.InputStream; import org.dom4j.Document; import org.dom4j.DocumentException; import org.xmlpull.v1.XmlPullParserException;
import java.io.*; import org.dom4j.*; import org.xmlpull.v1.*;
[ "java.io", "org.dom4j", "org.xmlpull.v1" ]
java.io; org.dom4j; org.xmlpull.v1;
2,598,385
@Test public void testCountMatches() throws Exception { Assert.assertEquals(0, (int) run("COUNT_MATCHES(null, '*')", new HashedMap())); Assert.assertEquals(2, (int) run("COUNT_MATCHES('apachemetron', 'e')", new HashedMap())); Assert.assertEquals(2, (int) run("COUNT_MATCHES('anand', 'an')", new HashedMap())); Assert.assertEquals(0, (int) run("COUNT_MATCHES('abcd', null)", new HashedMap())); // No input boolean thrown = false; try { run("COUNT_MATCHES()", Collections.emptyMap()); } catch (ParseException pe) { thrown = true; Assert.assertTrue(pe.getMessage().contains("incorrect arguments")); } Assert.assertTrue(thrown); thrown = false; // Incorrect number of arguments - 1 try { run("COUNT_MATCHES('abc')", Collections.emptyMap()); } catch (ParseException pe) { thrown = true; Assert.assertTrue(pe.getMessage().contains("incorrect arguments")); } Assert.assertTrue(thrown); thrown = false; // Integer input try { run("COUNT_MATCHES(123, 456)", Collections.emptyMap()); } catch (ParseException pe) { thrown = true; Assert.assertTrue(pe.getMessage().contains("cannot be cast")); } Assert.assertTrue(thrown); } // Input strings to be used @Multiline private String string1; @Multiline private String string2; @Multiline private String string3; @Multiline private String string4; @Multiline private String string5;
void function() throws Exception { Assert.assertEquals(0, (int) run(STR, new HashedMap())); Assert.assertEquals(2, (int) run(STR, new HashedMap())); Assert.assertEquals(2, (int) run(STR, new HashedMap())); Assert.assertEquals(0, (int) run(STR, new HashedMap())); boolean thrown = false; try { run(STR, Collections.emptyMap()); } catch (ParseException pe) { thrown = true; Assert.assertTrue(pe.getMessage().contains(STR)); } Assert.assertTrue(thrown); thrown = false; try { run(STR, Collections.emptyMap()); } catch (ParseException pe) { thrown = true; Assert.assertTrue(pe.getMessage().contains(STR)); } Assert.assertTrue(thrown); thrown = false; try { run(STR, Collections.emptyMap()); } catch (ParseException pe) { thrown = true; Assert.assertTrue(pe.getMessage().contains(STR)); } Assert.assertTrue(thrown); } private String string1; private String string2; private String string3; private String string4; private String string5;
/** * COUNT_MATCHES StringFunction */
COUNT_MATCHES StringFunction
testCountMatches
{ "repo_name": "dlyle65535/metron", "path": "metron-stellar/stellar-common/src/test/java/org/apache/metron/stellar/dsl/functions/StringFunctionsTest.java", "license": "apache-2.0", "size": 24584 }
[ "java.util.Collections", "org.apache.commons.collections4.map.HashedMap", "org.apache.metron.stellar.common.utils.StellarProcessorUtils", "org.apache.metron.stellar.dsl.ParseException", "org.junit.Assert" ]
import java.util.Collections; import org.apache.commons.collections4.map.HashedMap; import org.apache.metron.stellar.common.utils.StellarProcessorUtils; import org.apache.metron.stellar.dsl.ParseException; import org.junit.Assert;
import java.util.*; import org.apache.commons.collections4.map.*; import org.apache.metron.stellar.common.utils.*; import org.apache.metron.stellar.dsl.*; import org.junit.*;
[ "java.util", "org.apache.commons", "org.apache.metron", "org.junit" ]
java.util; org.apache.commons; org.apache.metron; org.junit;
406,956
public static JapaneseDate now(Clock clock) { return new JapaneseDate(LocalDate.now(clock)); }
static JapaneseDate function(Clock clock) { return new JapaneseDate(LocalDate.now(clock)); }
/** * Obtains the current {@code JapaneseDate} from the specified clock. * <p> * This will query the specified clock to obtain the current date - today. * Using this method allows the use of an alternate clock for testing. * The alternate clock may be introduced using {@linkplain Clock dependency injection}. * * @param clock the clock to use, not null * @return the current date, not null * @throws DateTimeException if the current date cannot be obtained */
Obtains the current JapaneseDate from the specified clock. This will query the specified clock to obtain the current date - today. Using this method allows the use of an alternate clock for testing. The alternate clock may be introduced using Clock dependency injection
now
{ "repo_name": "FauxFaux/jdk9-jdk", "path": "src/java.base/share/classes/java/time/chrono/JapaneseDate.java", "license": "gpl-2.0", "size": 30060 }
[ "java.time.Clock", "java.time.LocalDate" ]
import java.time.Clock; import java.time.LocalDate;
import java.time.*;
[ "java.time" ]
java.time;
1,838,977
private static void writeMarshalArgument(IndentingWriter p, String streamName, Type type, String name) throws IOException { int typeCode = type.getTypeCode(); switch (typeCode) { case TC_BOOLEAN: p.p(streamName + ".writeBoolean(" + name + ")"); break; case TC_BYTE: p.p(streamName + ".writeByte(" + name + ")"); break; case TC_CHAR: p.p(streamName + ".writeChar(" + name + ")"); break; case TC_SHORT: p.p(streamName + ".writeShort(" + name + ")"); break; case TC_INT: p.p(streamName + ".writeInt(" + name + ")"); break; case TC_LONG: p.p(streamName + ".writeLong(" + name + ")"); break; case TC_FLOAT: p.p(streamName + ".writeFloat(" + name + ")"); break; case TC_DOUBLE: p.p(streamName + ".writeDouble(" + name + ")"); break; case TC_ARRAY: case TC_CLASS: p.p(streamName + ".writeObject(" + name + ")"); break; default: throw new Error("unexpected type code: " + typeCode); } }
static void function(IndentingWriter p, String streamName, Type type, String name) throws IOException { int typeCode = type.getTypeCode(); switch (typeCode) { case TC_BOOLEAN: p.p(streamName + STR + name + ")"); break; case TC_BYTE: p.p(streamName + STR + name + ")"); break; case TC_CHAR: p.p(streamName + STR + name + ")"); break; case TC_SHORT: p.p(streamName + STR + name + ")"); break; case TC_INT: p.p(streamName + STR + name + ")"); break; case TC_LONG: p.p(streamName + STR + name + ")"); break; case TC_FLOAT: p.p(streamName + STR + name + ")"); break; case TC_DOUBLE: p.p(streamName + STR + name + ")"); break; case TC_ARRAY: case TC_CLASS: p.p(streamName + STR + name + ")"); break; default: throw new Error(STR + typeCode); } }
/** * Write a snippet of Java code to marshal a value named "name" of * type "type" to the java.io.ObjectOutput stream named "stream". * * Primitive types are marshalled with their corresponding methods * in the java.io.DataOutput interface, and objects (including arrays) * are marshalled using the writeObject method. */
Write a snippet of Java code to marshal a value named "name" of type "type" to the java.io.ObjectOutput stream named "stream". Primitive types are marshalled with their corresponding methods in the java.io.DataOutput interface, and objects (including arrays) are marshalled using the writeObject method
writeMarshalArgument
{ "repo_name": "rokn/Count_Words_2015", "path": "testing/openjdk/jdk/src/share/classes/sun/rmi/rmic/RMIGenerator.java", "license": "mit", "size": 49125 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
712,665
public BlockUCState getBlockUCState() { return blockUCState; }
BlockUCState function() { return blockUCState; }
/** * Return the state of the block under construction. * @see BlockUCState */
Return the state of the block under construction
getBlockUCState
{ "repo_name": "NJUJYB/disYarn", "path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockUnderConstructionFeature.java", "license": "apache-2.0", "size": 10861 }
[ "org.apache.hadoop.hdfs.server.common.HdfsServerConstants" ]
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
import org.apache.hadoop.hdfs.server.common.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
2,556,570
List<Ca> getCaList() { return caList; }
List<Ca> getCaList() { return caList; }
/** * Retorna a lista de CA's associada. * @return Lista de CA's. */
Retorna a lista de CA's associada
getCaList
{ "repo_name": "robsonsmartins/fiap-mba-java-projects", "path": "source/tcc.fiap.jboss7/ICPAdmin/src/icp/web/controller/CaConverter.java", "license": "gpl-3.0", "size": 1356 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
121,242
private void ensureFragmentsAreInitialized(SparseArray<Fragment> lastInFragments) { final int count = lastInFragments.size(); for (int i = 0; i < count; i++) { final Fragment fragment = lastInFragments.valueAt(i); if (fragment.mState < Fragment.CREATED) { mManager.makeActive(fragment); mManager.moveToState(fragment, Fragment.CREATED, 0, 0, false); } } }
void function(SparseArray<Fragment> lastInFragments) { final int count = lastInFragments.size(); for (int i = 0; i < count; i++) { final Fragment fragment = lastInFragments.valueAt(i); if (fragment.mState < Fragment.CREATED) { mManager.makeActive(fragment); mManager.moveToState(fragment, Fragment.CREATED, 0, 0, false); } } }
/** * Ensure that fragments that are entering are at least at the CREATED state * so that they may load Transitions using TransitionInflater. */
Ensure that fragments that are entering are at least at the CREATED state so that they may load Transitions using TransitionInflater
ensureFragmentsAreInitialized
{ "repo_name": "madhavanks26/com.vliesaputra.deviceinformation", "path": "src/com/vliesaputra/cordova/plugins/android/support/v4/src/java/android/support/v4/app/BackStackRecord.java", "license": "mit", "size": 59752 }
[ "android.util.SparseArray" ]
import android.util.SparseArray;
import android.util.*;
[ "android.util" ]
android.util;
995,071
private void indexZip(IndexWriter writer, File zipFile, TextParser textParser) { ZipEntry ze; try (FileInputStream fis = new FileInputStream(zipFile); ZipInputStream zis = new ZipInputStream(fis)) { //Iterate over every file inside zip. while ( (ze = zis.getNextEntry()) != null ) { // Index file read. // Create a new empty document. Document doc = new Document(); // Add the path of the file as a field named "docID". Use a // field that is indexed (i.e. searchable), but don't tokenize // the field into separate words and don't index term frequency // or positional information: Field idField = new Field("docID", zipFile.getPath()+"/"+ze.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS); idField.setIndexOptions(IndexOptions.DOCS_ONLY); doc.add(idField); // Do the same with the name Field nameField = new Field("name", zipFile.getPath()+"/"+ze.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS); nameField.setIndexOptions(IndexOptions.DOCS_ONLY); doc.add(nameField); // read file byte[] byteContent = new byte[2048]; int justRead; String s = ""; while ((justRead = zis.read(byteContent)) > 0) { s += new String(byteContent, 0, justRead); } // Add the contents of the file to a field named "contents". doc.add(new Field("contents", textParser.parse(s), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES)); // New index, so we just add the document (no old document can be there) writer.addDocument(doc); } } catch (IOException ex) { System.err.println("Exception caught while performing an I/O operation: " + ex.getClass().getSimpleName()); System.err.println(ex.getMessage()); } }
void function(IndexWriter writer, File zipFile, TextParser textParser) { ZipEntry ze; try (FileInputStream fis = new FileInputStream(zipFile); ZipInputStream zis = new ZipInputStream(fis)) { while ( (ze = zis.getNextEntry()) != null ) { Document doc = new Document(); Field idField = new Field("docID", zipFile.getPath()+"/"+ze.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS); idField.setIndexOptions(IndexOptions.DOCS_ONLY); doc.add(idField); Field nameField = new Field("name", zipFile.getPath()+"/"+ze.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS); nameField.setIndexOptions(IndexOptions.DOCS_ONLY); doc.add(nameField); byte[] byteContent = new byte[2048]; int justRead; String s = STRcontentsSTRException caught while performing an I/O operation: " + ex.getClass().getSimpleName()); System.err.println(ex.getMessage()); } }
/** * Indexes every file inside zip file passed. * Behavior undefined for zip files containing folders. * * @param writer Writer to the path where the index will be stored. * @param zipfile Zip file reading. * @param zis ZipInputStream to index * @param textParser the parser used to process documents. * @throws IOException If the file or directory cannot be indexed. */
Indexes every file inside zip file passed. Behavior undefined for zip files containing folders
indexZip
{ "repo_name": "guillermoruizalv/DataMining", "path": "bmi-p1-03/src/es/uam/eps/bmi/search/indexing/LuceneIndex.java", "license": "gpl-3.0", "size": 17712 }
[ "es.uam.eps.bmi.search.parsing.TextParser", "java.io.File", "java.io.FileInputStream", "java.util.zip.ZipEntry", "java.util.zip.ZipInputStream", "org.apache.lucene.document.Document", "org.apache.lucene.document.Field", "org.apache.lucene.index.FieldInfo", "org.apache.lucene.index.IndexWriter" ]
import es.uam.eps.bmi.search.parsing.TextParser; import java.io.File; import java.io.FileInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.IndexWriter;
import es.uam.eps.bmi.search.parsing.*; import java.io.*; import java.util.zip.*; import org.apache.lucene.document.*; import org.apache.lucene.index.*;
[ "es.uam.eps", "java.io", "java.util", "org.apache.lucene" ]
es.uam.eps; java.io; java.util; org.apache.lucene;
2,638,027
@Override public void setParent(PassiveScanThread parent) { this.parent = parent; }
void function(PassiveScanThread parent) { this.parent = parent; }
/** * sets the parent * @param parent */
sets the parent
setParent
{ "repo_name": "0xkasun/security-tools", "path": "src/org/zaproxy/zap/extension/pscanrulesAlpha/DirectoryBrowsingScanner.java", "license": "apache-2.0", "size": 5158 }
[ "org.zaproxy.zap.extension.pscan.PassiveScanThread" ]
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.*;
[ "org.zaproxy.zap" ]
org.zaproxy.zap;
2,738,837
EList<ModelCheckerInstance> getModelCheckers();
EList<ModelCheckerInstance> getModelCheckers();
/** * Returns the value of the '<em><b>Model Checkers</b></em>' reference list. * The list contents are of type {@link org.bimserver.models.store.ModelCheckerInstance}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Model Checkers</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>Model Checkers</em>' reference list. * @see org.bimserver.models.store.StorePackage#getService_ModelCheckers() * @model * @generated */
Returns the value of the 'Model Checkers' reference list. The list contents are of type <code>org.bimserver.models.store.ModelCheckerInstance</code>. If the meaning of the 'Model Checkers' reference list isn't clear, there really should be more of a description here...
getModelCheckers
{ "repo_name": "opensourceBIM/BIMserver", "path": "PluginBase/generated/org/bimserver/models/store/Service.java", "license": "agpl-3.0", "size": 23230 }
[ "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,149,776
@Test void testGetModuleDoc() { assertNotNull(API1.doc()); assertNotNull(API2.doc()); assertNotNull(API3.doc()); }
void testGetModuleDoc() { assertNotNull(API1.doc()); assertNotNull(API2.doc()); assertNotNull(API3.doc()); }
/** * Test for {@link JiffyBoxApi#doc()}. */
Test for <code>JiffyBoxApi#doc()</code>
testGetModuleDoc
{ "repo_name": "jschlichtholz/jiffybox", "path": "src/test/java/eu/df/jiffybox/JiffyBoxApiTest.java", "license": "mit", "size": 2639 }
[ "org.junit.jupiter.api.Assertions" ]
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.*;
[ "org.junit.jupiter" ]
org.junit.jupiter;
1,112,713
private TimeSeries createSeries() { RegularTimePeriod t = new Day(); TimeSeries series = new TimeSeries("Test"); series.add(t, 1.0); t = t.next(); series.add(t, 2.0); t = t.next(); series.add(t, null); t = t.next(); series.add(t, 4.0); return series; }
TimeSeries function() { RegularTimePeriod t = new Day(); TimeSeries series = new TimeSeries("Test"); series.add(t, 1.0); t = t.next(); series.add(t, 2.0); t = t.next(); series.add(t, null); t = t.next(); series.add(t, 4.0); return series; }
/** * Creates a time series for testing. * * @return A time series. */
Creates a time series for testing
createSeries
{ "repo_name": "SpoonLabs/astor", "path": "examples/chart_11/tests/org/jfree/data/time/junit/TimeSeriesCollectionTests.java", "license": "gpl-2.0", "size": 9849 }
[ "junit.framework.Test", "org.jfree.data.time.Day", "org.jfree.data.time.RegularTimePeriod", "org.jfree.data.time.TimeSeries" ]
import junit.framework.Test; import org.jfree.data.time.Day; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries;
import junit.framework.*; import org.jfree.data.time.*;
[ "junit.framework", "org.jfree.data" ]
junit.framework; org.jfree.data;
158,418
Optional<WebDriver> createDriver(Capabilities capabilities) throws SessionNotCreatedException;
Optional<WebDriver> createDriver(Capabilities capabilities) throws SessionNotCreatedException;
/** * Creates a new instance of the {@link WebDriver} implementation. The instance must be killed by * sending the "quit" command. If the instance cannot be created because {@link #isAvailable()} is * {@code false}, then {@link Optional#empty()} is returned. Otherwise, an attempt to start the * session is made and the result returned. */
Creates a new instance of the <code>WebDriver</code> implementation. The instance must be killed by sending the "quit" command. If the instance cannot be created because <code>#isAvailable()</code> is false, then <code>Optional#empty()</code> is returned. Otherwise, an attempt to start the session is made and the result returned
createDriver
{ "repo_name": "5hawnknight/selenium", "path": "java/client/src/org/openqa/selenium/WebDriverInfo.java", "license": "apache-2.0", "size": 3454 }
[ "java.util.Optional" ]
import java.util.Optional;
import java.util.*;
[ "java.util" ]
java.util;
1,277,248
public static Map<String, Integer> getEnumValues(String attributeName) { if (sEnumValueMap != null) { return sEnumValueMap.get(attributeName); } return null; }
static Map<String, Integer> function(String attributeName) { if (sEnumValueMap != null) { return sEnumValueMap.get(attributeName); } return null; }
/** * Returns the list of possible enums for a given attribute name. */
Returns the list of possible enums for a given attribute name
getEnumValues
{ "repo_name": "JSDemos/android-sdk-20", "path": "src/com/android/layoutlib/bridge/Bridge.java", "license": "apache-2.0", "size": 23530 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,305,545
public BigDecimal getUnsettleWeight() { return this.unsettleWeight; }
BigDecimal function() { return this.unsettleWeight; }
/** * get the unsettleWeight * @return the unsettleWeight */
get the unsettleWeight
getUnsettleWeight
{ "repo_name": "stserp/erp1", "path": "source/src/com/baosight/sts/st/rp/domain/STRP0221.java", "license": "apache-2.0", "size": 20337 }
[ "java.math.BigDecimal" ]
import java.math.BigDecimal;
import java.math.*;
[ "java.math" ]
java.math;
604,592
@VisibleForTesting static Charset getCharSet(File file) { long bufferSize = file.length() < 9999 ? file.length() : 9999; byte[] buffer = new byte[(int) bufferSize]; try (InputStream initialStream = new FileInputStream(file)) { int bytesRead = initialStream.read(buffer); if (bytesRead < bufferSize) { throw new IOException("Was not able to read expected number of bytes"); } } catch (IOException e) { throw new IllegalStateException(e); } return getCharSet(buffer); }
static Charset getCharSet(File file) { long bufferSize = file.length() < 9999 ? file.length() : 9999; byte[] buffer = new byte[(int) bufferSize]; try (InputStream initialStream = new FileInputStream(file)) { int bytesRead = initialStream.read(buffer); if (bytesRead < bufferSize) { throw new IOException(STR); } } catch (IOException e) { throw new IllegalStateException(e); } return getCharSet(buffer); }
/** * Returns the likely charset for the given file, if it can be determined. A confidence score is * calculated. If the score is less than 60 (on a 1 to 100 interval) the system default charset is * returned instead. * * @param file The file to be evaluated * @return The likely charset, or the system default charset */
Returns the likely charset for the given file, if it can be determined. A confidence score is calculated. If the score is less than 60 (on a 1 to 100 interval) the system default charset is returned instead
getCharSet
{ "repo_name": "axkr/symja_android_library", "path": "symja_android_library/matheclipse-io/src/main/java/tech/tablesaw/io/Source.java", "license": "gpl-3.0", "size": 4442 }
[ "java.io.File", "java.io.FileInputStream", "java.io.IOException", "java.io.InputStream", "java.nio.charset.Charset" ]
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset;
import java.io.*; import java.nio.charset.*;
[ "java.io", "java.nio" ]
java.io; java.nio;
754,539
public void blockOptimize(BlockOptimization job, List newBody) { switch(job) { case DEADCODE_ELIMINATE: newBody.add(this); break; default: //It's potentially dangerous if we perform an optimization and only some parts of our system implement it. //Catch that. throw new RuntimeException("Optimization not implemented: "+job); } }
void function(BlockOptimization job, List newBody) { switch(job) { case DEADCODE_ELIMINATE: newBody.add(this); break; default: throw new RuntimeException(STR+job); } }
/** * Optimizes the InputStatement - phase II */
Optimizes the InputStatement - phase II
blockOptimize
{ "repo_name": "srinathtv/pepper", "path": "compiler/frontend/src/SFE/Compiler/InputStatement.java", "license": "bsd-3-clause", "size": 5204 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,158,462
@Test(expectedExceptions = XL4JRuntimeException.class) public void testNullArgumentNames() { FunctionEntry.of(FUNCTION_NAME, null, ARGUMENT_TYPES, RETURN_TYPE, ARGUMENTS_HELP, DESCRIPTION, FUNCTION_ATTRIBUTES, METHOD); }
@Test(expectedExceptions = XL4JRuntimeException.class) void function() { FunctionEntry.of(FUNCTION_NAME, null, ARGUMENT_TYPES, RETURN_TYPE, ARGUMENTS_HELP, DESCRIPTION, FUNCTION_ATTRIBUTES, METHOD); }
/** * Tests that the argument names cannot be null. */
Tests that the argument names cannot be null
testNullArgumentNames
{ "repo_name": "McLeodMoores/xl4j", "path": "xll-core/src/test/java/com/mcleodmoores/xl4j/v1/simulator/FunctionEntryTest.java", "license": "gpl-3.0", "size": 5064 }
[ "com.mcleodmoores.xl4j.v1.util.XL4JRuntimeException", "org.testng.annotations.Test" ]
import com.mcleodmoores.xl4j.v1.util.XL4JRuntimeException; import org.testng.annotations.Test;
import com.mcleodmoores.xl4j.v1.util.*; import org.testng.annotations.*;
[ "com.mcleodmoores.xl4j", "org.testng.annotations" ]
com.mcleodmoores.xl4j; org.testng.annotations;
2,785,317
public void onStruckByLightning(EntityLightningBolt lightningBolt) { this.attackEntityFrom(DamageSource.lightningBolt, 5.0F); ++this.fire; if (this.fire == 0) { this.setFire(8); } }
void function(EntityLightningBolt lightningBolt) { this.attackEntityFrom(DamageSource.lightningBolt, 5.0F); ++this.fire; if (this.fire == 0) { this.setFire(8); } }
/** * Called when a lightning bolt hits the entity. */
Called when a lightning bolt hits the entity
onStruckByLightning
{ "repo_name": "SkidJava/BaseClient", "path": "new_1.8.8/net/minecraft/entity/Entity.java", "license": "gpl-2.0", "size": 87662 }
[ "net.minecraft.entity.effect.EntityLightningBolt", "net.minecraft.util.DamageSource" ]
import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.util.DamageSource;
import net.minecraft.entity.effect.*; import net.minecraft.util.*;
[ "net.minecraft.entity", "net.minecraft.util" ]
net.minecraft.entity; net.minecraft.util;
1,785,065
@Test public void testGetJobsByCommandName() { final List<Job> jobs = this.service.getJobs( null, null, null, null, null, null, null, "pig_13_prod", null, -1, 0, true, null ); Assert.assertEquals(1, jobs.size()); Assert.assertEquals(JOB_1_ID, jobs.get(0).getId()); }
void function() { final List<Job> jobs = this.service.getJobs( null, null, null, null, null, null, null, STR, null, -1, 0, true, null ); Assert.assertEquals(1, jobs.size()); Assert.assertEquals(JOB_1_ID, jobs.get(0).getId()); }
/** * Test the get jobs function. */
Test the get jobs function
testGetJobsByCommandName
{ "repo_name": "sensaid/genie", "path": "genie-core/src/integration-test/java/com/netflix/genie/core/services/impl/jpa/IntTestJobServiceJPAImpl.java", "license": "apache-2.0", "size": 29071 }
[ "com.netflix.genie.common.model.Job", "java.util.List", "org.junit.Assert" ]
import com.netflix.genie.common.model.Job; import java.util.List; import org.junit.Assert;
import com.netflix.genie.common.model.*; import java.util.*; import org.junit.*;
[ "com.netflix.genie", "java.util", "org.junit" ]
com.netflix.genie; java.util; org.junit;
1,871,720
public Option<Resource> getCurrentResource() { return getResourceForIndex(position); }
Option<Resource> function() { return getResourceForIndex(position); }
/** * Returns the current resource, or null * if there is none. * * @return */
Returns the current resource, or null if there is none
getCurrentResource
{ "repo_name": "eurekapp/biblioreader", "path": "src/org/eurekapp/pageturner/epub/PageTurnerSpine.java", "license": "gpl-3.0", "size": 11684 }
[ "nl.siegmann.epublib.domain.Resource" ]
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.*;
[ "nl.siegmann.epublib" ]
nl.siegmann.epublib;
1,928,946
public void comparisonEvaluation(Parameters p, QuerySetJudgments judgments, PrintStream output) throws IOException { Parameters eval = comparisonEvaluation(p, judgments, limitQueryIdentifiers); String formatString = "%1$-32s%2$-20s%3$10.4f\n"; List<String> metrics = eval.getList("_metrics", String.class); List<String> comparisons = eval.getList("_comparisons", String.class); for (String metric : metrics) { for (String comparison : comparisons) { output.format(formatString, metric, comparison, eval.getMap(metric).getDouble(comparison)); } } }
void function(Parameters p, QuerySetJudgments judgments, PrintStream output) throws IOException { Parameters eval = comparisonEvaluation(p, judgments, limitQueryIdentifiers); String formatString = STR; List<String> metrics = eval.getList(STR, String.class); List<String> comparisons = eval.getList(STR, String.class); for (String metric : metrics) { for (String comparison : comparisons) { output.format(formatString, metric, comparison, eval.getMap(metric).getDouble(comparison)); } } }
/** * When run as a standalone application, this returns comparison output */
When run as a standalone application, this returns comparison output
comparisonEvaluation
{ "repo_name": "jjfiv/galago-git", "path": "eval/src/main/java/org/lemurproject/galago/core/eval/Eval.java", "license": "bsd-3-clause", "size": 27978 }
[ "java.io.IOException", "java.io.PrintStream", "java.util.List", "org.lemurproject.galago.utility.Parameters" ]
import java.io.IOException; import java.io.PrintStream; import java.util.List; import org.lemurproject.galago.utility.Parameters;
import java.io.*; import java.util.*; import org.lemurproject.galago.utility.*;
[ "java.io", "java.util", "org.lemurproject.galago" ]
java.io; java.util; org.lemurproject.galago;
2,128,005
public boolean isDataFlavorSupported(DataFlavor df) { return getDropTargetContext().isDataFlavorSupported(df); } public int getSourceActions() { return actions; }
boolean function(DataFlavor df) { return getDropTargetContext().isDataFlavorSupported(df); } public int getSourceActions() { return actions; }
/** * This method returns a <code>boolean</code> indicating if the * specified <code>DataFlavor</code> is available * from the source. * <P> * @param df the <code>DataFlavor</code> to test * <P> * @return if the DataFlavor specified is available from the source */
This method returns a <code>boolean</code> indicating if the specified <code>DataFlavor</code> is available from the source.
isDataFlavorSupported
{ "repo_name": "jgaltidor/VarJ", "path": "analyzed_libs/jdk1.6.0_06_src/java/awt/dnd/DropTargetDropEvent.java", "license": "mit", "size": 9173 }
[ "java.awt.datatransfer.DataFlavor" ]
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.*;
[ "java.awt" ]
java.awt;
2,368,177
public V getValueFromCache(K key) { Cache<K, V> cache = getEntitlementCache(); if (cache != null) { if (cache.containsKey(key)) { if (log.isDebugEnabled()) { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); log.debug("Cache : " + Entitlement_CACHE_NAME + " is HIT " + "in tenant domain : " + tenantDomain); } return cache.get(key); } } if (log.isDebugEnabled()) { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); log.debug("Cache : " + Entitlement_CACHE_NAME + " is MISSED " + "in tenant domain : " + tenantDomain); } return null; }
V function(K key) { Cache<K, V> cache = getEntitlementCache(); if (cache != null) { if (cache.containsKey(key)) { if (log.isDebugEnabled()) { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); log.debug(STR + Entitlement_CACHE_NAME + STR + STR + tenantDomain); } return cache.get(key); } } if (log.isDebugEnabled()) { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); log.debug(STR + Entitlement_CACHE_NAME + STR + STR + tenantDomain); } return null; }
/** * Retrieves a cache entry. * * @param key CacheKey * @return Cached entry. */
Retrieves a cache entry
getValueFromCache
{ "repo_name": "wso2/carbon-identity-framework", "path": "components/entitlement/org.wso2.carbon.identity.entitlement/src/main/java/org/wso2/carbon/identity/entitlement/cache/EntitlementBaseCache.java", "license": "apache-2.0", "size": 8874 }
[ "javax.cache.Cache", "org.wso2.carbon.context.CarbonContext" ]
import javax.cache.Cache; import org.wso2.carbon.context.CarbonContext;
import javax.cache.*; import org.wso2.carbon.context.*;
[ "javax.cache", "org.wso2.carbon" ]
javax.cache; org.wso2.carbon;
2,832,677
@FIXVersion(introduced="4.3") @TagNumRef(tagNum=TagNum.SecondaryClOrdID) public void setSecondaryClOrdID(String secondaryClOrdID) { this.secondaryClOrdID = secondaryClOrdID; }
@FIXVersion(introduced="4.3") @TagNumRef(tagNum=TagNum.SecondaryClOrdID) void function(String secondaryClOrdID) { this.secondaryClOrdID = secondaryClOrdID; }
/** * Message field setter. * @param secondaryClOrdID field value */
Message field setter
setSecondaryClOrdID
{ "repo_name": "marvisan/HadesFIX", "path": "Model/src/main/java/net/hades/fix/message/OrderStatusRequestMsg.java", "license": "gpl-3.0", "size": 41851 }
[ "net.hades.fix.message.anno.FIXVersion", "net.hades.fix.message.anno.TagNumRef", "net.hades.fix.message.type.TagNum" ]
import net.hades.fix.message.anno.FIXVersion; import net.hades.fix.message.anno.TagNumRef; import net.hades.fix.message.type.TagNum;
import net.hades.fix.message.anno.*; import net.hades.fix.message.type.*;
[ "net.hades.fix" ]
net.hades.fix;
1,292,816
@ApiModelProperty(example = "null", value = "") public String getMessage() { return message; }
@ApiModelProperty(example = "null", value = "") String function() { return message; }
/** * Get message * @return message **/
Get message
getMessage
{ "repo_name": "Metatavu/kunta-api-spec", "path": "java-client-generated/src/main/java/fi/metatavu/kuntaapi/client/model/BadRequest.java", "license": "agpl-3.0", "size": 3025 }
[ "io.swagger.annotations.ApiModelProperty" ]
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.*;
[ "io.swagger.annotations" ]
io.swagger.annotations;
1,463,147
final Iterable<Region> regions = regionService.getRegions(); return ok(encodeArray(Region.class, "regions", regions)).build(); }
final Iterable<Region> regions = regionService.getRegions(); return ok(encodeArray(Region.class, STR, regions)).build(); }
/** * Returns set of all regions. * * @return 200 OK * @onos.rsModel Regions */
Returns set of all regions
getRegions
{ "repo_name": "sonu283304/onos", "path": "web/api/src/main/java/org/onosproject/rest/resources/RegionsWebResource.java", "license": "apache-2.0", "size": 9049 }
[ "org.onosproject.net.region.Region" ]
import org.onosproject.net.region.Region;
import org.onosproject.net.region.*;
[ "org.onosproject.net" ]
org.onosproject.net;
2,738,842
public int stackCuboidRegion(Region region, BlockVector3 dir, int count, boolean copyAir) throws MaxChangedBlocksException { return stackCuboidRegion(region, dir, count, true, false, copyAir ? null : new ExistingBlockMask(this)); }
int function(Region region, BlockVector3 dir, int count, boolean copyAir) throws MaxChangedBlocksException { return stackCuboidRegion(region, dir, count, true, false, copyAir ? null : new ExistingBlockMask(this)); }
/** * Stack a cuboid region. For compatibility, entities are copied by biomes are not. * Use {@link #stackCuboidRegion(Region, BlockVector3, int, boolean, boolean, Mask)} to fine tune. * * @param region the region to stack * @param dir the direction to stack * @param count the number of times to stack * @param copyAir true to also copy air blocks * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */
Stack a cuboid region. For compatibility, entities are copied by biomes are not. Use <code>#stackCuboidRegion(Region, BlockVector3, int, boolean, boolean, Mask)</code> to fine tune
stackCuboidRegion
{ "repo_name": "HolodeckOne-Minecraft/WorldEdit", "path": "worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java", "license": "gpl-3.0", "size": 107454 }
[ "com.sk89q.worldedit.function.mask.ExistingBlockMask", "com.sk89q.worldedit.math.BlockVector3", "com.sk89q.worldedit.regions.Region" ]
import com.sk89q.worldedit.function.mask.ExistingBlockMask; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.function.mask.*; import com.sk89q.worldedit.math.*; import com.sk89q.worldedit.regions.*;
[ "com.sk89q.worldedit" ]
com.sk89q.worldedit;
1,306,288
public void test_fill$CC() { // Test for method void java.util.Arrays.fill(char [], char) char d[] = new char[1000]; Arrays.fill(d, 'V'); for (int i = 0; i < d.length; i++) assertEquals("Failed to fill char array correctly", 'V', d[i]); }
public void test_fill$CC() { char d[] = new char[1000]; Arrays.fill(d, 'V'); for (int i = 0; i < d.length; i++) assertEquals(STR, 'V', d[i]); }
/** * java.util.Arrays#fill(char[], char) */
java.util.Arrays#fill(char[], char)
test_fill$CC
{ "repo_name": "AdmireTheDistance/android_libcore", "path": "harmony-tests/src/test/java/org/apache/harmony/tests/java/util/ArraysTest.java", "license": "gpl-2.0", "size": 156287 }
[ "java.util.Arrays" ]
import java.util.Arrays;
import java.util.*;
[ "java.util" ]
java.util;
1,836,665
public VersionManager getVersionManager();
VersionManager function();
/** * Returns the <code>VersionManager</code> object. * * @return an <code>VersionManager</code> object. * @throws UnsupportedRepositoryOperationException * if the implementation does not support versioning. * @throws RepositoryException if an error occurs. * @since JCR 2.0 */
Returns the <code>VersionManager</code> object
getVersionManager
{ "repo_name": "kbachl/brix-cms-backup", "path": "brix-wrapper/src/main/java/org/brixcms/jcr/api/JcrWorkspace.java", "license": "apache-2.0", "size": 6731 }
[ "javax.jcr.version.VersionManager" ]
import javax.jcr.version.VersionManager;
import javax.jcr.version.*;
[ "javax.jcr" ]
javax.jcr;
1,146,410
public String[] getArchiveTimestamps() { return DistributedCache.getArchiveTimestamps(conf); }
String[] function() { return DistributedCache.getArchiveTimestamps(conf); }
/** * Get the timestamps of the archives. Used by internal * DistributedCache and MapReduce code. * @return a string array of timestamps * @throws IOException */
Get the timestamps of the archives. Used by internal DistributedCache and MapReduce code
getArchiveTimestamps
{ "repo_name": "moreus/hadoop", "path": "hadoop-0.23.10/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/JobContextImpl.java", "license": "apache-2.0", "size": 12427 }
[ "org.apache.hadoop.mapreduce.filecache.DistributedCache" ]
import org.apache.hadoop.mapreduce.filecache.DistributedCache;
import org.apache.hadoop.mapreduce.filecache.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
1,570,118
public static void writeToEMF(JComponent panel, File fileName) throws IOException { // print the panel to pdf int width = panel.getWidth(); int height = panel.getWidth(); logger.info( () -> MessageFormat.format("Exporting panel to EMF file (width x height; {0} x {1}): {2}", width, height, fileName.getAbsolutePath())); VectorGraphics g = new EMFGraphics2D(fileName, new Dimension(width, height)); g.startExport(); panel.print(g); g.endExport(); }
static void function(JComponent panel, File fileName) throws IOException { int width = panel.getWidth(); int height = panel.getWidth(); logger.info( () -> MessageFormat.format(STR, width, height, fileName.getAbsolutePath())); VectorGraphics g = new EMFGraphics2D(fileName, new Dimension(width, height)); g.startExport(); panel.print(g); g.endExport(); }
/** * Writes swing to EMF * * @param panel * @param fileName * @throws Exception */
Writes swing to EMF
writeToEMF
{ "repo_name": "mzmine/mzmine3", "path": "src/main/java/io/github/mzmine/util/swing/SwingExportUtil.java", "license": "gpl-2.0", "size": 8028 }
[ "java.awt.Dimension", "java.io.File", "java.io.IOException", "java.text.MessageFormat", "javax.swing.JComponent", "org.freehep.graphics2d.VectorGraphics", "org.freehep.graphicsio.emf.EMFGraphics2D" ]
import java.awt.Dimension; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import javax.swing.JComponent; import org.freehep.graphics2d.VectorGraphics; import org.freehep.graphicsio.emf.EMFGraphics2D;
import java.awt.*; import java.io.*; import java.text.*; import javax.swing.*; import org.freehep.graphics2d.*; import org.freehep.graphicsio.emf.*;
[ "java.awt", "java.io", "java.text", "javax.swing", "org.freehep.graphics2d", "org.freehep.graphicsio" ]
java.awt; java.io; java.text; javax.swing; org.freehep.graphics2d; org.freehep.graphicsio;
1,651,895
private boolean objectHasField(Unit unit) { // Здесь мы берем количество параметров юнита. Если оно больше 3, то предположительно // 4-ый параметр всегда "damage" (пускай в этой игре будет так). Как выяснить, есть ли // поле у конкретного subclass я не знаю, названия полей теряются после компиляции. // Технически этот метод здесь и не нужен по ТЗ, т.к. орков атаковать мы не будем все равно // (только у орков есть юнит без damage), но теоретически такой юнит в игре может появиться. boolean result = false; Constructor[] constructors = unit.getClass().getConstructors(); for (int i = 0; i != constructors.length; i++) { Constructor constructor = constructors[i]; Parameter[] parameters = constructor.getParameters(); if (parameters.length > 3) { result = true; } } return result; }
boolean function(Unit unit) { boolean result = false; Constructor[] constructors = unit.getClass().getConstructors(); for (int i = 0; i != constructors.length; i++) { Constructor constructor = constructors[i]; Parameter[] parameters = constructor.getParameters(); if (parameters.length > 3) { result = true; } } return result; }
/** * Finds number of fields of a subclass. * * @param unit - some unit. * @return boolean. */
Finds number of fields of a subclass
objectHasField
{ "repo_name": "alittlemind/junior", "path": "strategyprototype/src/main/java/game/units/undead/Necromancer.java", "license": "apache-2.0", "size": 3799 }
[ "java.lang.reflect.Constructor", "java.lang.reflect.Parameter" ]
import java.lang.reflect.Constructor; import java.lang.reflect.Parameter;
import java.lang.reflect.*;
[ "java.lang" ]
java.lang;
2,405,722
public ArrayList<Asignatura> getOptativasGenerales(){ ArrayList<Asignatura> optativas = new ArrayList<>(); try { PreparedStatement ps = this.c.getConexion().prepareStatement("SELECT DISTINCT * FROM db WHERE curso = 0 ORDER BY asignatura;"); ResultSet rs = ps.executeQuery(); while(rs.next()){ optativas.add(build(rs)); } } catch(Exception e) { e.printStackTrace(); } return optativas; }
ArrayList<Asignatura> function(){ ArrayList<Asignatura> optativas = new ArrayList<>(); try { PreparedStatement ps = this.c.getConexion().prepareStatement(STR); ResultSet rs = ps.executeQuery(); while(rs.next()){ optativas.add(build(rs)); } } catch(Exception e) { e.printStackTrace(); } return optativas; }
/** * Devuelve todas las optativas generales * @return Lista de optativas generales */
Devuelve todas las optativas generales
getOptativasGenerales
{ "repo_name": "daster1324/enroll", "path": "src/modelo/Consultor.java", "license": "gpl-2.0", "size": 5721 }
[ "java.sql.PreparedStatement", "java.sql.ResultSet", "java.util.ArrayList" ]
import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList;
import java.sql.*; import java.util.*;
[ "java.sql", "java.util" ]
java.sql; java.util;
206,359
public synchronized void setupReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws ProtocolException { if ( ! req.containsHeader(HEADER_TRANSPORT)){ throw new ProtocolException("No Transport header"); } final Deque<String> requestOptions = new java.util.LinkedList<String>(Arrays.asList(req.getHeader(HEADER_TRANSPORT).split(";"))); final List<String> responseOptions = new java.util.LinkedList<String>(); final String requestProtocol = requestOptions.removeFirst(); if ( ! "RTP/AVP/UDP".equals(requestProtocol)){ throw new ProtocolException("Transport protocol must be RTP/AVP/UDP, but was " + requestProtocol); } responseOptions.add(requestProtocol); for(final String requestOption: requestOptions) { final Matcher transportOption = PATTERN_TRANSPORT_OPTION.matcher(requestOption); if ( ! transportOption.matches() ){ throw new ProtocolException("Cannot parse Transport option " + requestOption); } final String key = transportOption.group(1); final String value = transportOption.group(3); if ("interleaved".equals(key)) { if ( ! "0-1".equals(value)){ throw new ProtocolException("Unsupported Transport option, interleaved must be 0-1 but was " + value); } responseOptions.add("interleaved=0-1"); } else if ("mode".equals(key)) { if ( ! "record".equals(value)){ throw new ProtocolException("Unsupported Transport option, mode must be record but was " + value); } responseOptions.add("mode=record"); } else if ("control_port".equals(key)) { final int clientControlPort = Integer.valueOf(value); controlChannel = createRtpChannel( substitutePort((InetSocketAddress)ctx.getChannel().getLocalAddress(), 53670), substitutePort((InetSocketAddress)ctx.getChannel().getRemoteAddress(), clientControlPort), RaopRtpChannelType.Control ); LogManager.w("Launched RTP control service on " + controlChannel.getLocalAddress()); responseOptions.add("control_port=" + ((InetSocketAddress)controlChannel.getLocalAddress()).getPort()); } else if ("timing_port".equals(key)) { final int clientTimingPort = Integer.valueOf(value); timingChannel = createRtpChannel( substitutePort((InetSocketAddress)ctx.getChannel().getLocalAddress(), 53669), substitutePort((InetSocketAddress)ctx.getChannel().getRemoteAddress(), clientTimingPort), RaopRtpChannelType.Timing ); LogManager.w("Launched RTP timing service on " + timingChannel.getLocalAddress()); responseOptions.add("timing_port=" + ((InetSocketAddress)timingChannel.getLocalAddress()).getPort()); } else { responseOptions.add(requestOption); } } audioChannel = createRtpChannel( substitutePort((InetSocketAddress)ctx.getChannel().getLocalAddress(), 53671), null, RaopRtpChannelType.Audio ); LogManager.w("Launched RTP audio service on " + audioChannel.getLocalAddress()); responseOptions.add("server_port=" + ((InetSocketAddress)audioChannel.getLocalAddress()).getPort()); final StringBuilder transportResponseBuilder = new StringBuilder(); for(final String responseOption: responseOptions) { if (transportResponseBuilder.length() > 0){ transportResponseBuilder.append(";"); } transportResponseBuilder.append(responseOption); } final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); response.addHeader(HEADER_TRANSPORT, transportResponseBuilder.toString()); response.addHeader(HEADER_SESSION, "DEADBEEEF"); ctx.getChannel().write(response); }
synchronized void function(final ChannelHandlerContext ctx, final HttpRequest req) throws ProtocolException { if ( ! req.containsHeader(HEADER_TRANSPORT)){ throw new ProtocolException(STR); } final Deque<String> requestOptions = new java.util.LinkedList<String>(Arrays.asList(req.getHeader(HEADER_TRANSPORT).split(";"))); final List<String> responseOptions = new java.util.LinkedList<String>(); final String requestProtocol = requestOptions.removeFirst(); if ( ! STR.equals(requestProtocol)){ throw new ProtocolException(STR + requestProtocol); } responseOptions.add(requestProtocol); for(final String requestOption: requestOptions) { final Matcher transportOption = PATTERN_TRANSPORT_OPTION.matcher(requestOption); if ( ! transportOption.matches() ){ throw new ProtocolException(STR + requestOption); } final String key = transportOption.group(1); final String value = transportOption.group(3); if (STR.equals(key)) { if ( ! "0-1".equals(value)){ throw new ProtocolException(STR + value); } responseOptions.add(STR); } else if ("mode".equals(key)) { if ( ! STR.equals(value)){ throw new ProtocolException(STR + value); } responseOptions.add(STR); } else if (STR.equals(key)) { final int clientControlPort = Integer.valueOf(value); controlChannel = createRtpChannel( substitutePort((InetSocketAddress)ctx.getChannel().getLocalAddress(), 53670), substitutePort((InetSocketAddress)ctx.getChannel().getRemoteAddress(), clientControlPort), RaopRtpChannelType.Control ); LogManager.w(STR + controlChannel.getLocalAddress()); responseOptions.add(STR + ((InetSocketAddress)controlChannel.getLocalAddress()).getPort()); } else if (STR.equals(key)) { final int clientTimingPort = Integer.valueOf(value); timingChannel = createRtpChannel( substitutePort((InetSocketAddress)ctx.getChannel().getLocalAddress(), 53669), substitutePort((InetSocketAddress)ctx.getChannel().getRemoteAddress(), clientTimingPort), RaopRtpChannelType.Timing ); LogManager.w(STR + timingChannel.getLocalAddress()); responseOptions.add(STR + ((InetSocketAddress)timingChannel.getLocalAddress()).getPort()); } else { responseOptions.add(requestOption); } } audioChannel = createRtpChannel( substitutePort((InetSocketAddress)ctx.getChannel().getLocalAddress(), 53671), null, RaopRtpChannelType.Audio ); LogManager.w(STR + audioChannel.getLocalAddress()); responseOptions.add(STR + ((InetSocketAddress)audioChannel.getLocalAddress()).getPort()); final StringBuilder transportResponseBuilder = new StringBuilder(); for(final String responseOption: responseOptions) { if (transportResponseBuilder.length() > 0){ transportResponseBuilder.append(";"); } transportResponseBuilder.append(responseOption); } final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); response.addHeader(HEADER_TRANSPORT, transportResponseBuilder.toString()); response.addHeader(HEADER_SESSION, STR); ctx.getChannel().write(response); }
/** * Handles SETUP requests and creates the audio, control and timing RTP channels */
Handles SETUP requests and creates the audio, control and timing RTP channels
setupReceived
{ "repo_name": "lukeqsun/AirSpeakerMobile", "path": "app/src/main/java/nz/co/iswe/android/airplay/audio/RaopAudioHandler.java", "license": "mit", "size": 32707 }
[ "com.fenggit.util.LogManager", "java.net.InetSocketAddress", "java.util.Arrays", "java.util.Deque", "java.util.List", "java.util.regex.Matcher", "org.jboss.netty.channel.ChannelHandlerContext", "org.jboss.netty.handler.codec.http.DefaultHttpResponse", "org.jboss.netty.handler.codec.http.HttpRequest", "org.jboss.netty.handler.codec.http.HttpResponse", "org.jboss.netty.handler.codec.rtsp.RtspResponseStatuses", "org.jboss.netty.handler.codec.rtsp.RtspVersions", "org.phlo.airreceiver.ProtocolException" ]
import com.fenggit.util.LogManager; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Deque; import java.util.List; import java.util.regex.Matcher; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.rtsp.RtspResponseStatuses; import org.jboss.netty.handler.codec.rtsp.RtspVersions; import org.phlo.airreceiver.ProtocolException;
import com.fenggit.util.*; import java.net.*; import java.util.*; import java.util.regex.*; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.http.*; import org.jboss.netty.handler.codec.rtsp.*; import org.phlo.airreceiver.*;
[ "com.fenggit.util", "java.net", "java.util", "org.jboss.netty", "org.phlo.airreceiver" ]
com.fenggit.util; java.net; java.util; org.jboss.netty; org.phlo.airreceiver;
453,732
@Override public String getPreDisbursementCustomerProfileSubUnit() { final String subUnit = getParameterService().getParameterValueAsString(DisbursementVoucherDocument.class, KFSParameterKeyConstants.PdpExtractBatchParameters.PDP_SBUNT_CODE); return subUnit; }
String function() { final String subUnit = getParameterService().getParameterValueAsString(DisbursementVoucherDocument.class, KFSParameterKeyConstants.PdpExtractBatchParameters.PDP_SBUNT_CODE); return subUnit; }
/** * Uses the value in the KFS-FP / DisbursementVoucher / PRE_DISBURSEMENT_EXTRACT_SUB_UNIT * @see org.kuali.kfs.sys.document.PaymentSource#getPreDisbursementCustomerProfileSubUnit() */
Uses the value in the KFS-FP / DisbursementVoucher / PRE_DISBURSEMENT_EXTRACT_SUB_UNIT
getPreDisbursementCustomerProfileSubUnit
{ "repo_name": "ua-eas/ua-kfs-5.3", "path": "work/src/org/kuali/kfs/fp/document/service/impl/DisbursementVoucherExtractionHelperServiceImpl.java", "license": "agpl-3.0", "size": 37018 }
[ "org.kuali.kfs.fp.document.DisbursementVoucherDocument", "org.kuali.kfs.sys.KFSParameterKeyConstants" ]
import org.kuali.kfs.fp.document.DisbursementVoucherDocument; import org.kuali.kfs.sys.KFSParameterKeyConstants;
import org.kuali.kfs.fp.document.*; import org.kuali.kfs.sys.*;
[ "org.kuali.kfs" ]
org.kuali.kfs;
925,875
public ConditionalExpr withCondition(Mutation<Expr> mutation) { return location.safeTraversalMutate(SConditionalExpr.CONDITION, mutation); }
ConditionalExpr function(Mutation<Expr> mutation) { return location.safeTraversalMutate(SConditionalExpr.CONDITION, mutation); }
/** * Mutates the condition of this conditional expression. * * @param mutation the mutation to apply to the condition of this conditional expression. * @return the resulting mutated conditional expression. */
Mutates the condition of this conditional expression
withCondition
{ "repo_name": "ptitjes/jlato", "path": "src/main/java/org/jlato/internal/td/expr/TDConditionalExpr.java", "license": "lgpl-3.0", "size": 5004 }
[ "org.jlato.internal.bu.expr.SConditionalExpr", "org.jlato.tree.expr.ConditionalExpr", "org.jlato.tree.expr.Expr", "org.jlato.util.Mutation" ]
import org.jlato.internal.bu.expr.SConditionalExpr; import org.jlato.tree.expr.ConditionalExpr; import org.jlato.tree.expr.Expr; import org.jlato.util.Mutation;
import org.jlato.internal.bu.expr.*; import org.jlato.tree.expr.*; import org.jlato.util.*;
[ "org.jlato.internal", "org.jlato.tree", "org.jlato.util" ]
org.jlato.internal; org.jlato.tree; org.jlato.util;
2,462,265
void hmSet(String key, Map<String, Serializable> values) throws Exception;
void hmSet(String key, Map<String, Serializable> values) throws Exception;
/** * hash multiple set * * @param key * @param values * @throws Exception */
hash multiple set
hmSet
{ "repo_name": "Kuohong/commons-parent", "path": "commons-jredis/src/main/java/org/power/commons/redis/RedisOperation.java", "license": "apache-2.0", "size": 6043 }
[ "java.io.Serializable", "java.util.Map" ]
import java.io.Serializable; import java.util.Map;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
2,224,535
public List<Query> getEntries(final String key, final boolean breakOnFirst) { Query root = getRoot(this); final List<Query> queries = new ArrayList<>(); try { visitInternal(root, new AbstractQueryVistor() {
List<Query> function(final String key, final boolean breakOnFirst) { Query root = getRoot(this); final List<Query> queries = new ArrayList<>(); try { visitInternal(root, new AbstractQueryVistor() {
/** * Gets the entries. * * @param key * the key * @param breakOnFirst * the break on first * @return the entries */
Gets the entries
getEntries
{ "repo_name": "SirmaITT/conservation-space-1.7.0", "path": "docker/sirma-platform/platform/seip-parent/platform/domain-model/domain-model-api/src/main/java/com/sirma/itt/seip/domain/search/Query.java", "license": "lgpl-3.0", "size": 18805 }
[ "java.util.ArrayList", "java.util.List" ]
import java.util.ArrayList; import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
866,389
private boolean loadLOBDataFromFileSystem(){ if("".equals(m_attachmentPathRoot)){ log.severe("no attachmentPath defined"); return false; } // Reset m_items = new ArrayList<MAttachmentEntry>(); // byte[] data = getBinaryData(); if (data == null) return true; log.fine("TextFileSize=" + data.length); if (data.length == 0) return true; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(new ByteArrayInputStream(data)); final NodeList entries = document.getElementsByTagName("entry"); for (int i = 0; i < entries.getLength(); i++) { final Node entryNode = entries.item(i); final NamedNodeMap attributes = entryNode.getAttributes(); final Node fileNode = attributes.getNamedItem("file"); final Node nameNode = attributes.getNamedItem("name"); if(fileNode==null || nameNode==null){ log.severe("no filename for entry " + i); m_items = null; return false; } log.fine("name: " + nameNode.getNodeValue()); String filePath = fileNode.getNodeValue(); log.fine("filePath: " + filePath); if(filePath!=null){ filePath = filePath.replaceFirst(ATTACHMENT_FOLDER_PLACEHOLDER, m_attachmentPathRoot.replaceAll("\\\\","\\\\\\\\")); //just to be shure... String replaceSeparator = File.separator; if(!replaceSeparator.equals("/")){ replaceSeparator = "\\\\"; } filePath = filePath.replaceAll("/", replaceSeparator); filePath = filePath.replaceAll("\\\\", replaceSeparator); } log.fine("filePath: " + filePath); final File file = new File(filePath); if (file.exists()) { // read files into byte[] final byte[] dataEntry = new byte[(int) file.length()]; try { final FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.read(dataEntry); fileInputStream.close(); } catch (FileNotFoundException e) { log.severe("File Not Found."); e.printStackTrace(); } catch (IOException e1) { log.severe("Error Reading The File."); e1.printStackTrace(); } final MAttachmentEntry entry = new MAttachmentEntry(filePath, dataEntry, m_items.size() + 1); m_items.add(entry); } else { log.severe("file not found: " + file.getAbsolutePath()); } } } catch (SAXException sxe) { // Error generated during parsing) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); log.severe(x.getMessage()); } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); log.severe(pce.getMessage()); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); log.severe(ioe.getMessage()); } return true; }
boolean function(){ if(STRno attachmentPath definedSTRTextFileSize=STRentrySTRfileSTRnameSTRno filename for entry STRname: STRfilePath: STR\\\\","\\\\\\\\STR/STR\\\\STR/STR\\\\STRfilePath: STRFile Not Found.STRError Reading The File.STRfile not found: " + file.getAbsolutePath()); } } } catch (SAXException sxe) { Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); log.severe(x.getMessage()); } catch (ParserConfigurationException pce) { pce.printStackTrace(); log.severe(pce.getMessage()); } catch (IOException ioe) { ioe.printStackTrace(); log.severe(ioe.getMessage()); } return true; }
/** * Load Data from file system * @return true if success */
Load Data from file system
loadLOBDataFromFileSystem
{ "repo_name": "neuroidss/adempiere", "path": "base/src/org/compiere/model/MAttachment.java", "license": "gpl-2.0", "size": 28068 }
[ "java.io.File", "java.io.IOException", "javax.xml.parsers.ParserConfigurationException", "org.xml.sax.SAXException" ]
import java.io.File; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException;
import java.io.*; import javax.xml.parsers.*; import org.xml.sax.*;
[ "java.io", "javax.xml", "org.xml.sax" ]
java.io; javax.xml; org.xml.sax;
999,670
@Test public void testBlockIdCK() throws Exception { final short REPL_FACTOR = 2; short NUM_DN = 2; final long blockSize = 512; String [] racks = {"/rack1", "/rack2"}; String [] hosts = {"host1", "host2"}; Configuration conf = new Configuration(); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize); conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2); MiniDFSCluster cluster = null; DistributedFileSystem dfs = null; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts) .racks(racks).build(); assertNotNull("Failed Cluster Creation", cluster); cluster.waitClusterUp(); dfs = cluster.getFileSystem(); assertNotNull("Failed to get FileSystem", dfs); DFSTestUtil util = new DFSTestUtil.Builder(). setName(getClass().getSimpleName()).setNumFiles(1).build(); //create files final String pathString = new String("/testfile"); final Path path = new Path(pathString); util.createFile(dfs, path, 1024, REPL_FACTOR , 1000L); util.waitReplication(dfs, path, REPL_FACTOR); StringBuilder sb = new StringBuilder(); for (LocatedBlock lb: util.getAllBlocks(dfs, path)){ sb.append(lb.getBlock().getLocalBlock().getBlockName()+" "); } String[] bIds = sb.toString().split(" "); //run fsck try { //illegal input test String runFsckResult = runFsck(conf, 0, true, "/", "-blockId", "not_a_block_id"); assertTrue(runFsckResult.contains("Incorrect blockId format:")); //general test runFsckResult = runFsck(conf, 0, true, "/", "-blockId", sb.toString()); assertTrue(runFsckResult.contains(bIds[0])); assertTrue(runFsckResult.contains(bIds[1])); assertTrue(runFsckResult.contains( "Block replica on datanode/rack: host1/rack1 is HEALTHY")); assertTrue(runFsckResult.contains( "Block replica on datanode/rack: host2/rack2 is HEALTHY")); } finally { cluster.shutdown(); } }
void function() throws Exception { final short REPL_FACTOR = 2; short NUM_DN = 2; final long blockSize = 512; String [] racks = {STR, STR}; String [] hosts = {"host1", "host2"}; Configuration conf = new Configuration(); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize); conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 2); MiniDFSCluster cluster = null; DistributedFileSystem dfs = null; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DN).hosts(hosts) .racks(racks).build(); assertNotNull(STR, cluster); cluster.waitClusterUp(); dfs = cluster.getFileSystem(); assertNotNull(STR, dfs); DFSTestUtil util = new DFSTestUtil.Builder(). setName(getClass().getSimpleName()).setNumFiles(1).build(); final String pathString = new String(STR); final Path path = new Path(pathString); util.createFile(dfs, path, 1024, REPL_FACTOR , 1000L); util.waitReplication(dfs, path, REPL_FACTOR); StringBuilder sb = new StringBuilder(); for (LocatedBlock lb: util.getAllBlocks(dfs, path)){ sb.append(lb.getBlock().getLocalBlock().getBlockName()+" "); } String[] bIds = sb.toString().split(" "); try { String runFsckResult = runFsck(conf, 0, true, "/", STR, STR); assertTrue(runFsckResult.contains(STR)); runFsckResult = runFsck(conf, 0, true, "/", STR, sb.toString()); assertTrue(runFsckResult.contains(bIds[0])); assertTrue(runFsckResult.contains(bIds[1])); assertTrue(runFsckResult.contains( STR)); assertTrue(runFsckResult.contains( STR)); } finally { cluster.shutdown(); } }
/** * Test for blockIdCK */
Test for blockIdCK
testBlockIdCK
{ "repo_name": "gilv/hadoop", "path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java", "license": "apache-2.0", "size": 62445 }
[ "org.apache.hadoop.conf.Configuration", "org.apache.hadoop.fs.Path", "org.apache.hadoop.hdfs.DFSConfigKeys", "org.apache.hadoop.hdfs.DFSTestUtil", "org.apache.hadoop.hdfs.DistributedFileSystem", "org.apache.hadoop.hdfs.MiniDFSCluster", "org.apache.hadoop.hdfs.protocol.LocatedBlock", "org.junit.Assert" ]
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.junit.Assert;
import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.hdfs.*; import org.apache.hadoop.hdfs.protocol.*; import org.junit.*;
[ "org.apache.hadoop", "org.junit" ]
org.apache.hadoop; org.junit;
1,922,740