method
stringlengths 13
441k
| clean_method
stringlengths 7
313k
| doc
stringlengths 17
17.3k
| comment
stringlengths 3
1.42k
| method_name
stringlengths 1
273
| extra
dict | imports
sequence | imports_info
stringlengths 19
34.8k
| cluster_imports_info
stringlengths 15
3.66k
| libraries
sequence | libraries_info
stringlengths 6
661
| id
int64 0
2.92M
|
---|---|---|---|---|---|---|---|---|---|---|---|
@Override
public List<ConceptRelationship> getOldInferredRelationships() {
throw new UnsupportedOperationException();
} | List<ConceptRelationship> function() { throw new UnsupportedOperationException(); } | /**
* Returns the old inferred relationships.
*
* @return the old inferred relationships
*/ | Returns the old inferred relationships | getOldInferredRelationships | {
"repo_name": "WestCoastInformatics/UMLS-Terminology-Server",
"path": "jpa-services/src/main/java/com/wci/umls/server/jpa/algo/OwlApiClassifier.java",
"license": "apache-2.0",
"size": 24890
} | [
"com.wci.umls.server.model.content.ConceptRelationship",
"java.util.List"
] | import com.wci.umls.server.model.content.ConceptRelationship; import java.util.List; | import com.wci.umls.server.model.content.*; import java.util.*; | [
"com.wci.umls",
"java.util"
] | com.wci.umls; java.util; | 1,529,629 |
public PopFuture<PopCommandResponse> disconnect() throws PopException {
final State state = stateRef.get();
if (state != State.CONNECTED) {
throw new PopException(PopException.Type.INVALID_STATE);
}
if (stateRef.compareAndSet(state, State.NULL)) {
Future f = sessionChannel.disconnect();
PopFuture<PopCommandResponse> disconnectFuture = new PopFuture<PopCommandResponse>(f);
sessionChannel = null;
return disconnectFuture;
}
throw new PopException(PopException.Type.INVALID_STATE);
} | PopFuture<PopCommandResponse> function() throws PopException { final State state = stateRef.get(); if (state != State.CONNECTED) { throw new PopException(PopException.Type.INVALID_STATE); } if (stateRef.compareAndSet(state, State.NULL)) { Future f = sessionChannel.disconnect(); PopFuture<PopCommandResponse> disconnectFuture = new PopFuture<PopCommandResponse>(f); sessionChannel = null; return disconnectFuture; } throw new PopException(PopException.Type.INVALID_STATE); } | /**
* Disconnect the session, close session and cleanup.
*
* @return the future object for disconnect
* @throws PopException on failure
*/ | Disconnect the session, close session and cleanup | disconnect | {
"repo_name": "lafaspot/pop3sclient",
"path": "src/main/java/com/lafaspot/pop/session/PopSession.java",
"license": "mit",
"size": 14039
} | [
"com.lafaspot.pop.command.PopCommandResponse",
"com.lafaspot.pop.exception.PopException",
"io.netty.util.concurrent.Future"
] | import com.lafaspot.pop.command.PopCommandResponse; import com.lafaspot.pop.exception.PopException; import io.netty.util.concurrent.Future; | import com.lafaspot.pop.command.*; import com.lafaspot.pop.exception.*; import io.netty.util.concurrent.*; | [
"com.lafaspot.pop",
"io.netty.util"
] | com.lafaspot.pop; io.netty.util; | 955,449 |
public Collection<CollisionFormula> getFormulas()
{
return formulas;
}
| Collection<CollisionFormula> function() { return formulas; } | /**
* Get collision formulas reference as read only..
*
* @return The collision formulas reference.
*/ | Get collision formulas reference as read only. | getFormulas | {
"repo_name": "b3dgs/lionengine",
"path": "lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/CollisionGroup.java",
"license": "gpl-3.0",
"size": 4021
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 2,353,952 |
private void initializeDialog() {
dialog = new JDialog();
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setModal(true);
dialog.setTitle(TITLE);
label = new JLabel();
label.setBorder(new EmptyBorder(PADDING, PADDING, PADDING, PADDING));
buttons = new JPanel(new FlowLayout());
content = new JPanel(new BorderLayout());
} | void function() { dialog = new JDialog(); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); dialog.setModal(true); dialog.setTitle(TITLE); label = new JLabel(); label.setBorder(new EmptyBorder(PADDING, PADDING, PADDING, PADDING)); buttons = new JPanel(new FlowLayout()); content = new JPanel(new BorderLayout()); } | /**
* This method initializes the dialog box.
*/ | This method initializes the dialog box | initializeDialog | {
"repo_name": "aturri/sheepland-aturri-asalmoiraghi",
"path": "cg_1/src/main/java/it/polimi/sheepland/client/Selection.java",
"license": "gpl-2.0",
"size": 2605
} | [
"java.awt.BorderLayout",
"java.awt.FlowLayout",
"javax.swing.JDialog",
"javax.swing.JLabel",
"javax.swing.JPanel",
"javax.swing.border.EmptyBorder"
] | import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; | import java.awt.*; import javax.swing.*; import javax.swing.border.*; | [
"java.awt",
"javax.swing"
] | java.awt; javax.swing; | 1,490,127 |
public void formatFooter( PrintStream out, ResultSetMetaData metaData ) throws Exception {
} | void function( PrintStream out, ResultSetMetaData metaData ) throws Exception { } | /**
* Outputs a footer for a query. This method isn't used in the NullFormatter.
*
* @param out the PrintStream to output data to.
* @param metaData the ResultSetMetaData for the output.
*
*/ | Outputs a footer for a query. This method isn't used in the NullFormatter | formatFooter | {
"repo_name": "stdunbar/jisql",
"path": "src/main/java/com/xigole/util/sql/outputformatter/NullFormatter.java",
"license": "apache-2.0",
"size": 2850
} | [
"java.io.PrintStream",
"java.sql.ResultSetMetaData"
] | import java.io.PrintStream; import java.sql.ResultSetMetaData; | import java.io.*; import java.sql.*; | [
"java.io",
"java.sql"
] | java.io; java.sql; | 604,379 |
public void render(Writer writer, String encoding) {
PrintWriter pw = new PrintWriter(writer);
render(pw, encoding);
pw.flush();
}
| void function(Writer writer, String encoding) { PrintWriter pw = new PrintWriter(writer); render(pw, encoding); pw.flush(); } | /**
* Render this channel as XML conforming to the RSS 0.91 specification,
* to the specified writer, indicating the specified character encoding.
*
* @param writer The writer to render output to
* @param encoding The character encoding to declare, or <code>null</code>
* for no declaration
*/ | Render this channel as XML conforming to the RSS 0.91 specification, to the specified writer, indicating the specified character encoding | render | {
"repo_name": "hudson3-plugins/commons-jelly",
"path": "jelly-tags/betwixt/src/test/org/apache/commons/digester/rss/Channel.java",
"license": "apache-2.0",
"size": 15144
} | [
"java.io.PrintWriter",
"java.io.Writer"
] | import java.io.PrintWriter; import java.io.Writer; | import java.io.*; | [
"java.io"
] | java.io; | 2,272,051 |
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<VirtualWanInner>, VirtualWanInner> beginCreateOrUpdate(
String resourceGroupName, String virtualWanName, VirtualWanInner wanParameters); | @ServiceMethod(returns = ReturnType.SINGLE) SyncPoller<PollResult<VirtualWanInner>, VirtualWanInner> beginCreateOrUpdate( String resourceGroupName, String virtualWanName, VirtualWanInner wanParameters); | /**
* Creates a VirtualWAN resource if it doesn't exist else updates the existing VirtualWAN.
*
* @param resourceGroupName The resource group name of the VirtualWan.
* @param virtualWanName The name of the VirtualWAN being created or updated.
* @param wanParameters VirtualWAN Resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @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 virtualWAN Resource.
*/ | Creates a VirtualWAN resource if it doesn't exist else updates the existing VirtualWAN | beginCreateOrUpdate | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/VirtualWansClient.java",
"license": "mit",
"size": 22453
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.management.polling.PollResult",
"com.azure.core.util.polling.SyncPoller",
"com.azure.resourcemanager.network.fluent.models.VirtualWanInner"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.management.polling.PollResult; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.network.fluent.models.VirtualWanInner; | import com.azure.core.annotation.*; import com.azure.core.management.polling.*; import com.azure.core.util.polling.*; import com.azure.resourcemanager.network.fluent.models.*; | [
"com.azure.core",
"com.azure.resourcemanager"
] | com.azure.core; com.azure.resourcemanager; | 2,284,556 |
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
// many of the zoom methods need a screen location - all we have is
// the zoomPoint, but it might be null. Here we grab the x and y
// coordinates, or use defaults...
double screenX = -1.0;
double screenY = -1.0;
if (this.zoomPoint != null) {
screenX = this.zoomPoint.getX();
screenY = this.zoomPoint.getY();
}
if (command.equals(PROPERTIES_COMMAND)) {
doEditChartProperties();
}
else if (command.equals(SAVE_COMMAND)) {
try {
doSaveAs();
}
catch (IOException e) {
e.printStackTrace();
}
}
else if (command.equals(PRINT_COMMAND)) {
createChartPrintJob();
}
else if (command.equals(ZOOM_IN_BOTH_COMMAND)) {
zoomInBoth(screenX, screenY);
}
else if (command.equals(ZOOM_IN_DOMAIN_COMMAND)) {
zoomInDomain(screenX, screenY);
}
else if (command.equals(ZOOM_IN_RANGE_COMMAND)) {
zoomInRange(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_BOTH_COMMAND)) {
zoomOutBoth(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_DOMAIN_COMMAND)) {
zoomOutDomain(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_RANGE_COMMAND)) {
zoomOutRange(screenX, screenY);
}
else if (command.equals(ZOOM_RESET_BOTH_COMMAND)) {
restoreAutoBounds();
}
else if (command.equals(ZOOM_RESET_DOMAIN_COMMAND)) {
restoreAutoDomainBounds();
}
else if (command.equals(ZOOM_RESET_RANGE_COMMAND)) {
restoreAutoRangeBounds();
}
} | void function(ActionEvent event) { String command = event.getActionCommand(); double screenX = -1.0; double screenY = -1.0; if (this.zoomPoint != null) { screenX = this.zoomPoint.getX(); screenY = this.zoomPoint.getY(); } if (command.equals(PROPERTIES_COMMAND)) { doEditChartProperties(); } else if (command.equals(SAVE_COMMAND)) { try { doSaveAs(); } catch (IOException e) { e.printStackTrace(); } } else if (command.equals(PRINT_COMMAND)) { createChartPrintJob(); } else if (command.equals(ZOOM_IN_BOTH_COMMAND)) { zoomInBoth(screenX, screenY); } else if (command.equals(ZOOM_IN_DOMAIN_COMMAND)) { zoomInDomain(screenX, screenY); } else if (command.equals(ZOOM_IN_RANGE_COMMAND)) { zoomInRange(screenX, screenY); } else if (command.equals(ZOOM_OUT_BOTH_COMMAND)) { zoomOutBoth(screenX, screenY); } else if (command.equals(ZOOM_OUT_DOMAIN_COMMAND)) { zoomOutDomain(screenX, screenY); } else if (command.equals(ZOOM_OUT_RANGE_COMMAND)) { zoomOutRange(screenX, screenY); } else if (command.equals(ZOOM_RESET_BOTH_COMMAND)) { restoreAutoBounds(); } else if (command.equals(ZOOM_RESET_DOMAIN_COMMAND)) { restoreAutoDomainBounds(); } else if (command.equals(ZOOM_RESET_RANGE_COMMAND)) { restoreAutoRangeBounds(); } } | /**
* Handles action events generated by the popup menu.
*
* @param event the event.
*/ | Handles action events generated by the popup menu | actionPerformed | {
"repo_name": "ibestvina/multithread-centiscape",
"path": "CentiScaPe2.1/src/main/java/org/jfree/chart/ChartPanel.java",
"license": "mit",
"size": 88952
} | [
"java.awt.event.ActionEvent",
"java.io.IOException"
] | import java.awt.event.ActionEvent; import java.io.IOException; | import java.awt.event.*; import java.io.*; | [
"java.awt",
"java.io"
] | java.awt; java.io; | 485,933 |
public static Bitmap combineTimeAndFilter(final BaseIndexFactory factory,
final Bitmap timeBitmap, final IBitmapResult filter) {
if (timeBitmap == null) {
return factory.createBitmap();
} else if (filter == null || filter.getBitmap() == null) {
return timeBitmap;
} else {
return filter.getBitmap().and(timeBitmap);
}
} | static Bitmap function(final BaseIndexFactory factory, final Bitmap timeBitmap, final IBitmapResult filter) { if (timeBitmap == null) { return factory.createBitmap(); } else if (filter == null filter.getBitmap() == null) { return timeBitmap; } else { return filter.getBitmap().and(timeBitmap); } } | /**
* Combines the two bitmaps with each-other using an and-operation. A
* {@code null} as {@code timeBitmap} is handled as empty bitmap, whereby a
* {@code null} bitmap for the filter is handled as a full-bitmap, e.g. all
* values are set to one.
*
* @param factory
* the {@code IndexFactory} used if a new {@code Bitmap} has to
* be created
* @param timeBitmap
* the bitmap, specifying the selected values within the
* time-dimension, {@code null} is handled as empty bitmap
* @param filter
* specifying the filtered values, {@code null} is handled as
* full bitmap
*
*
* @return the result of the combination
*/ | Combines the two bitmaps with each-other using an and-operation. A null as timeBitmap is handled as empty bitmap, whereby a null bitmap for the filter is handled as a full-bitmap, e.g. all values are set to one | combineTimeAndFilter | {
"repo_name": "pmeisen/dis-timeintervaldataanalyzer",
"path": "src/net/meisen/dissertation/model/indexes/datarecord/slices/Bitmap.java",
"license": "bsd-3-clause",
"size": 14126
} | [
"net.meisen.dissertation.impl.parser.query.select.evaluator.IBitmapResult",
"net.meisen.dissertation.model.indexes.BaseIndexFactory"
] | import net.meisen.dissertation.impl.parser.query.select.evaluator.IBitmapResult; import net.meisen.dissertation.model.indexes.BaseIndexFactory; | import net.meisen.dissertation.impl.parser.query.select.evaluator.*; import net.meisen.dissertation.model.indexes.*; | [
"net.meisen.dissertation"
] | net.meisen.dissertation; | 984,451 |
public Date getXingshizhengFazhengriqi() {
return xingshizhengFazhengriqi;
} | Date function() { return xingshizhengFazhengriqi; } | /**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column surveyinfo.xingshizheng_fazhengriqi
*
* @return the value of surveyinfo.xingshizheng_fazhengriqi
*
* @mbggenerated
*/ | This method was generated by MyBatis Generator. This method returns the value of the database column surveyinfo.xingshizheng_fazhengriqi | getXingshizhengFazhengriqi | {
"repo_name": "ThomasYangLin/DbToJson",
"path": "src/main/java/com/yanglin/model/SurveyInfo.java",
"license": "apache-2.0",
"size": 27819
} | [
"java.util.Date"
] | import java.util.Date; | import java.util.*; | [
"java.util"
] | java.util; | 2,682,175 |
final DataTypeDescriptor getType()
{
return type;
}
public void setType( DataTypeDescriptor dts ) { type = dts; } | final DataTypeDescriptor getType() { return type; } public void setType( DataTypeDescriptor dts ) { type = dts; } | /**
* Returns the data type of the column being defined.
*
* @return the data type of the column
*/ | Returns the data type of the column being defined | getType | {
"repo_name": "apache/derby",
"path": "java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/ColumnDefinitionNode.java",
"license": "apache-2.0",
"size": 29183
} | [
"org.apache.derby.iapi.types.DataTypeDescriptor"
] | import org.apache.derby.iapi.types.DataTypeDescriptor; | import org.apache.derby.iapi.types.*; | [
"org.apache.derby"
] | org.apache.derby; | 435,787 |
public synchronized void clearSSLConfigMap() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "clearSSLConfigMap");
sslConfigMap.clear();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "clearSSLConfigMap");
} | synchronized void function() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, STR); sslConfigMap.clear(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, STR); } | /***
* This method adds an SSL config to the SSLConfigManager map and list.
*
* @param alias
* @param sslConfig
* @throws Exception
***/ | This method adds an SSL config to the SSLConfigManager map and list | clearSSLConfigMap | {
"repo_name": "OpenLiberty/open-liberty",
"path": "dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/config/SSLConfigManager.java",
"license": "epl-1.0",
"size": 62575
} | [
"com.ibm.websphere.ras.Tr",
"com.ibm.websphere.ras.TraceComponent"
] | import com.ibm.websphere.ras.Tr; import com.ibm.websphere.ras.TraceComponent; | import com.ibm.websphere.ras.*; | [
"com.ibm.websphere"
] | com.ibm.websphere; | 1,100,411 |
static IndexCondition create(
List<String> fieldNames,
String indexName,
List<String> indexColumnNames,
List<RexNode> pushDownConditions,
List<RexNode> remainderConditions) {
return new IndexCondition(fieldNames, indexName, indexColumnNames, null,
pushDownConditions, remainderConditions, null, null,
ComparisonOperator.NOP, ComparisonOperator.NOP, ImmutableList.of(),
ImmutableList.of());
} | static IndexCondition create( List<String> fieldNames, String indexName, List<String> indexColumnNames, List<RexNode> pushDownConditions, List<RexNode> remainderConditions) { return new IndexCondition(fieldNames, indexName, indexColumnNames, null, pushDownConditions, remainderConditions, null, null, ComparisonOperator.NOP, ComparisonOperator.NOP, ImmutableList.of(), ImmutableList.of()); } | /**
* Creates a new instance for {@link InnodbFilterTranslator} to build
* index condition which can be pushed down.
*/ | Creates a new instance for <code>InnodbFilterTranslator</code> to build index condition which can be pushed down | create | {
"repo_name": "datametica/calcite",
"path": "innodb/src/main/java/org/apache/calcite/adapter/innodb/IndexCondition.java",
"license": "apache-2.0",
"size": 13320
} | [
"com.alibaba.innodb.java.reader.comparator.ComparisonOperator",
"com.google.common.collect.ImmutableList",
"java.util.List",
"org.apache.calcite.rex.RexNode"
] | import com.alibaba.innodb.java.reader.comparator.ComparisonOperator; import com.google.common.collect.ImmutableList; import java.util.List; import org.apache.calcite.rex.RexNode; | import com.alibaba.innodb.java.reader.comparator.*; import com.google.common.collect.*; import java.util.*; import org.apache.calcite.rex.*; | [
"com.alibaba.innodb",
"com.google.common",
"java.util",
"org.apache.calcite"
] | com.alibaba.innodb; com.google.common; java.util; org.apache.calcite; | 2,688,986 |
public static void setStatusBarColor(@NonNull Activity activity, @ColorRes int colorResId) {
//noinspection ConstantConditions
if (activity == null) {
return;
}
final int backgroundColor = ContextCompat.getColor(activity, colorResId);
activity.getWindow().setStatusBarColor(backgroundColor);
} | static void function(@NonNull Activity activity, @ColorRes int colorResId) { if (activity == null) { return; } final int backgroundColor = ContextCompat.getColor(activity, colorResId); activity.getWindow().setStatusBarColor(backgroundColor); } | /**
* Set the status bar color of an activity to a specified value.
*
* @param activity The activity to set the colorResId for.
* @param colorResId The value to use.
*/ | Set the status bar color of an activity to a specified value | setStatusBarColor | {
"repo_name": "android/animation-samples",
"path": "OurStreets/app/src/main/java/com/google/samples/apps/ourstreets/view/ViewUtils.java",
"license": "apache-2.0",
"size": 12024
} | [
"android.app.Activity",
"androidx.annotation.ColorRes",
"androidx.annotation.NonNull",
"androidx.core.content.ContextCompat"
] | import android.app.Activity; import androidx.annotation.ColorRes; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; | import android.app.*; import androidx.annotation.*; import androidx.core.content.*; | [
"android.app",
"androidx.annotation",
"androidx.core"
] | android.app; androidx.annotation; androidx.core; | 1,593,440 |
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(0, 0, 0));
frame.setBackground(new Color(0, 0, 0));
frame.setBounds(100, 100, 350, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new MigLayout("", "[grow,fill]", "[5px][][75px:75px:100px,fill][grow,fill]"));
inputStorage = new JLabel("");
inputStorage.setHorizontalAlignment(SwingConstants.LEFT);
inputStorage.setVerticalAlignment(SwingConstants.TOP);
inputStorage.setForeground(Color.WHITE);
frame.getContentPane().add(inputStorage, "cell 0 1");
inputField = new JTextField();
inputField.setBackground(new Color(0, 0, 0));
inputField.setForeground(new Color(255, 255, 255));
inputField.setFont(new Font("Monospaced", Font.PLAIN, 28));
inputField.setHorizontalAlignment(SwingConstants.RIGHT);
frame.getContentPane().add(inputField, "cell 0 2,grow");
inputField.setColumns(10);
// Remove old and make new invisible inner border
inputField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
inputField.setCaretColor(new Color(255, 255, 255));
JPanel panelMain = new JPanel();
panelMain.setBackground(Color.BLACK);
frame.getContentPane().add(panelMain, "cell 0 3");
panelMain.setLayout(new MigLayout("", "[250px,grow,fill][150px,grow,fill]", "[grow,fill][grow,fill]"));
JPanel panelLeft = new JPanel();
panelMain.add(panelLeft, "cell 0 0 1 2,growy");
panelLeft.setBackground(new Color(0, 0, 0));
panelLeft.setLayout(new GridLayout(4, 3, 5, 5));
JPanel panelRight = new JPanel();
panelRight.setBackground(Color.BLACK);
panelMain.add(panelRight, "cell 1 0 1 2,grow");
panelRight.setLayout(new GridLayout(5, 1, 5, 5));
Object[] tmpArray= new Object[leftPanelButtons.length];
// List<JButton> buttons = new ArrayList<JButton>();
Map<String, JButton> Buttons = new HashMap<>();
for (int i = 0; i < leftPanelButtons.length; i++) {
JButton tmpBtn = new JButton(leftPanelButtons[i]);
tmpBtn.setForeground(Color.WHITE);
tmpBtn.setFont(new Font("Monospaced", Font.PLAIN, 20));
tmpBtn.setBackground(Color.BLACK);
tmpBtn.setBorder(javax.swing.BorderFactory.createEmptyBorder());
Buttons.put(leftPanelButtons[i], tmpBtn);
| void function() { frame = new JFrame(); frame.getContentPane().setBackground(new Color(0, 0, 0)); frame.setBackground(new Color(0, 0, 0)); frame.setBounds(100, 100, 350, 450); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new MigLayout(STR[grow,fill]STR[5px][][75px:75px:100px,fill][grow,fill]STRSTRcell 0 1STRMonospacedSTRcell 0 2,growSTRcell 0 3"); panelMain.setLayout(new MigLayout(STR[250px,grow,fill][150px,grow,fill]STR[grow,fill][grow,fill]STRcell 0 0 1 2,growySTRcell 1 0 1 2,growSTRMonospaced", Font.PLAIN, 20)); tmpBtn.setBackground(Color.BLACK); tmpBtn.setBorder(javax.swing.BorderFactory.createEmptyBorder()); Buttons.put(leftPanelButtons[i], tmpBtn); | /**
* Initialize the contents of the frame.
*/ | Initialize the contents of the frame | initialize | {
"repo_name": "bearhagen/edu-hio-java",
"path": "src/oblig3/calculator/Main.java",
"license": "gpl-3.0",
"size": 10449
} | [
"java.awt.Color",
"java.awt.Font",
"javax.swing.JFrame",
"net.miginfocom.swing.MigLayout"
] | import java.awt.Color; import java.awt.Font; import javax.swing.JFrame; import net.miginfocom.swing.MigLayout; | import java.awt.*; import javax.swing.*; import net.miginfocom.swing.*; | [
"java.awt",
"javax.swing",
"net.miginfocom.swing"
] | java.awt; javax.swing; net.miginfocom.swing; | 270,392 |
public boolean hasPermission(String permission, ModuleEntity module)
{
boolean hasPermission = false;
try
{
hasPermission = ((ScarabUser)data.getUser())
.hasPermission(permission, module);
}
catch (Exception e)
{
hasPermission = false;
Log.error("Permission check failed on:" + permission, e);
}
return hasPermission;
}
// ****************** Recyclable implementation ************************ | boolean function(String permission, ModuleEntity module) { boolean hasPermission = false; try { hasPermission = ((ScarabUser)data.getUser()) .hasPermission(permission, module); } catch (Exception e) { hasPermission = false; Log.error(STR + permission, e); } return hasPermission; } | /**
* Determine if the user currently interacting with the scarab
* application has a permission within a module.
*
* @param permission a <code>String</code> permission value, which should
* be a constant in this interface.
* @param module a <code>ModuleEntity</code> value
* @return true if the permission exists for the user within the
* given module, false otherwise
*/ | Determine if the user currently interacting with the scarab application has a permission within a module | hasPermission | {
"repo_name": "SpoonLabs/gumtree-spoon-ast-diff",
"path": "src/test/resources/examples/t_226145/left_ScarabRequestTool_1.90.java",
"license": "apache-2.0",
"size": 35338
} | [
"org.apache.turbine.Log",
"org.tigris.scarab.om.ScarabUser",
"org.tigris.scarab.services.module.ModuleEntity"
] | import org.apache.turbine.Log; import org.tigris.scarab.om.ScarabUser; import org.tigris.scarab.services.module.ModuleEntity; | import org.apache.turbine.*; import org.tigris.scarab.om.*; import org.tigris.scarab.services.module.*; | [
"org.apache.turbine",
"org.tigris.scarab"
] | org.apache.turbine; org.tigris.scarab; | 2,890,660 |
public static void setBlockAt(World world, int x, int y, int z, IBlockState block) {
setBlockAt(world, new BlockPos(x, y, z), block);
}
| static void function(World world, int x, int y, int z, IBlockState block) { setBlockAt(world, new BlockPos(x, y, z), block); } | /**
* Sets the block at a specified location. And triggers a block update
*
* @param world The world to change the block in.
* @param x The X-coordinate to change.
* @param y The Y-coordinate to change.
* @param z The Z-coordinate to change.
* @param block the block to set.
*/ | Sets the block at a specified location. And triggers a block update | setBlockAt | {
"repo_name": "BlazeLoader/BlazeLoader",
"path": "src/main/com/blazeloader/api/world/ApiWorld.java",
"license": "bsd-2-clause",
"size": 16835
} | [
"net.minecraft.block.state.IBlockState",
"net.minecraft.util.math.BlockPos",
"net.minecraft.world.World"
] | import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; | import net.minecraft.block.state.*; import net.minecraft.util.math.*; import net.minecraft.world.*; | [
"net.minecraft.block",
"net.minecraft.util",
"net.minecraft.world"
] | net.minecraft.block; net.minecraft.util; net.minecraft.world; | 2,522,052 |
private static ByteString readChunk(InputStream in, final int chunkSize)
throws IOException {
final byte[] buf = new byte[chunkSize];
int bytesRead = 0;
while (bytesRead < chunkSize) {
final int count = in.read(buf, bytesRead, chunkSize - bytesRead);
if (count == -1) {
break;
}
bytesRead += count;
}
if (bytesRead == 0) {
return null;
}
// Always make a copy since InputStream could steal a reference to buf.
return ByteString.copyFrom(buf, 0, bytesRead);
}
// =================================================================
// Multiple ByteStrings -> One ByteString | static ByteString function(InputStream in, final int chunkSize) throws IOException { final byte[] buf = new byte[chunkSize]; int bytesRead = 0; while (bytesRead < chunkSize) { final int count = in.read(buf, bytesRead, chunkSize - bytesRead); if (count == -1) { break; } bytesRead += count; } if (bytesRead == 0) { return null; } return ByteString.copyFrom(buf, 0, bytesRead); } | /**
* Blocks until a chunk of the given size can be made from the
* stream, or EOF is reached. Calls read() repeatedly in case the
* given stream implementation doesn't completely fill the given
* buffer in one read() call.
*
* @return A chunk of the desired size, or else a chunk as large as
* was available when end of stream was reached. Returns null if the
* given stream had no more data in it.
*/ | Blocks until a chunk of the given size can be made from the stream, or EOF is reached. Calls read() repeatedly in case the given stream implementation doesn't completely fill the given buffer in one read() call | readChunk | {
"repo_name": "android/games-samples",
"path": "agdk/third_party/protobuf-3.0.0/java/core/src/main/java/com/google/protobuf/ByteString.java",
"license": "apache-2.0",
"size": 53958
} | [
"java.io.IOException",
"java.io.InputStream"
] | import java.io.IOException; import java.io.InputStream; | import java.io.*; | [
"java.io"
] | java.io; | 1,673,915 |
@Function(name = "formatToParts", arity = 1)
public static Object formatToParts(ExecutionContext cx, Object thisValue, Object x) {
NumberFormatObject numberFormat = thisNumberFormatObject(cx, thisValue,
"Intl.NumberFormat.prototype.formatToParts");
return FormatNumberToParts(cx, numberFormat, ToNumber(cx, x));
} | @Function(name = STR, arity = 1) static Object function(ExecutionContext cx, Object thisValue, Object x) { NumberFormatObject numberFormat = thisNumberFormatObject(cx, thisValue, STR); return FormatNumberToParts(cx, numberFormat, ToNumber(cx, x)); } | /**
* Intl.NumberFormat.prototype.formatToParts (x)
*
* @param cx
* the execution context
* @param thisValue
* the function this-value
* @param x
* the number argument
* @return the format object
*/ | Intl.NumberFormat.prototype.formatToParts (x) | formatToParts | {
"repo_name": "anba/es6draft",
"path": "src/main/java/com/github/anba/es6draft/runtime/objects/intl/NumberFormatPrototype.java",
"license": "mit",
"size": 7614
} | [
"com.github.anba.es6draft.runtime.AbstractOperations",
"com.github.anba.es6draft.runtime.ExecutionContext",
"com.github.anba.es6draft.runtime.internal.Properties",
"com.github.anba.es6draft.runtime.objects.intl.NumberFormatConstructor"
] | import com.github.anba.es6draft.runtime.AbstractOperations; import com.github.anba.es6draft.runtime.ExecutionContext; import com.github.anba.es6draft.runtime.internal.Properties; import com.github.anba.es6draft.runtime.objects.intl.NumberFormatConstructor; | import com.github.anba.es6draft.runtime.*; import com.github.anba.es6draft.runtime.internal.*; import com.github.anba.es6draft.runtime.objects.intl.*; | [
"com.github.anba"
] | com.github.anba; | 2,392,070 |
interface WithSourceApplicationSecurityGroups {
WithCreate withSourceApplicationSecurityGroups(List<ApplicationSecurityGroupInner> sourceApplicationSecurityGroups);
} | interface WithSourceApplicationSecurityGroups { WithCreate withSourceApplicationSecurityGroups(List<ApplicationSecurityGroupInner> sourceApplicationSecurityGroups); } | /**
* Specifies sourceApplicationSecurityGroups.
* @param sourceApplicationSecurityGroups The application security group specified as source
* @return the next definition stage
*/ | Specifies sourceApplicationSecurityGroups | withSourceApplicationSecurityGroups | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/network/mgmt-v2019_11_01/src/main/java/com/microsoft/azure/management/network/v2019_11_01/NetworkSecurityGroupSecurityRule.java",
"license": "mit",
"size": 22310
} | [
"com.microsoft.azure.management.network.v2019_11_01.implementation.ApplicationSecurityGroupInner",
"java.util.List"
] | import com.microsoft.azure.management.network.v2019_11_01.implementation.ApplicationSecurityGroupInner; import java.util.List; | import com.microsoft.azure.management.network.v2019_11_01.implementation.*; import java.util.*; | [
"com.microsoft.azure",
"java.util"
] | com.microsoft.azure; java.util; | 2,382,662 |
@Override
public PooledConnection getPooledConnection(String username, String pass)
throws SQLException {
getConnectionCalled = true;
PooledConnectionImpl pci = null;
// Workaround for buggy WebLogic 5.1 classloader - ignore the
// exception upon first invocation.
try {
if (connectionProperties != null) {
connectionProperties.put("user", username);
connectionProperties.put("password", pass);
pci = new PooledConnectionImpl(DriverManager.getConnection(
getUrl(), connectionProperties));
} else {
pci = new PooledConnectionImpl(DriverManager.getConnection(
getUrl(), username, pass));
}
pci.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
}
catch (ClassCircularityError e)
{
if (connectionProperties != null) {
pci = new PooledConnectionImpl(DriverManager.getConnection(
getUrl(), connectionProperties));
} else {
pci = new PooledConnectionImpl(DriverManager.getConnection(
getUrl(), username, pass));
}
pci.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
}
KeyedObjectPool<PStmtKeyCPDS, PoolablePreparedStatement<PStmtKeyCPDS>> stmtPool = null;
if (isPoolPreparedStatements()) {
GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
config.setMaxTotalPerKey(Integer.MAX_VALUE);
config.setBlockWhenExhausted(false);
config.setMaxWaitMillis(0);
config.setMaxIdlePerKey(getMaxIdle());
if (getMaxPreparedStatements() <= 0)
{
// since there is no limit, create a prepared statement pool with an eviction thread
// evictor settings are the same as the connection pool settings.
config.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis());
config.setNumTestsPerEvictionRun(getNumTestsPerEvictionRun());
config.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis());
}
else
{
// since there is limit, create a prepared statement pool without an eviction thread
// pool has LRU functionality so when the limit is reached, 15% of the pool is cleared.
// see org.apache.commons.pool2.impl.GenericKeyedObjectPool.clearOldest method
config.setMaxTotal(getMaxPreparedStatements());
config.setTimeBetweenEvictionRunsMillis(-1);
config.setNumTestsPerEvictionRun(0);
config.setMinEvictableIdleTimeMillis(0);
}
stmtPool = new GenericKeyedObjectPool<>(pci, config);
pci.setStatementPool(stmtPool);
}
return pci;
} | PooledConnection function(String username, String pass) throws SQLException { getConnectionCalled = true; PooledConnectionImpl pci = null; try { if (connectionProperties != null) { connectionProperties.put("user", username); connectionProperties.put(STR, pass); pci = new PooledConnectionImpl(DriverManager.getConnection( getUrl(), connectionProperties)); } else { pci = new PooledConnectionImpl(DriverManager.getConnection( getUrl(), username, pass)); } pci.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); } catch (ClassCircularityError e) { if (connectionProperties != null) { pci = new PooledConnectionImpl(DriverManager.getConnection( getUrl(), connectionProperties)); } else { pci = new PooledConnectionImpl(DriverManager.getConnection( getUrl(), username, pass)); } pci.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); } KeyedObjectPool<PStmtKeyCPDS, PoolablePreparedStatement<PStmtKeyCPDS>> stmtPool = null; if (isPoolPreparedStatements()) { GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig(); config.setMaxTotalPerKey(Integer.MAX_VALUE); config.setBlockWhenExhausted(false); config.setMaxWaitMillis(0); config.setMaxIdlePerKey(getMaxIdle()); if (getMaxPreparedStatements() <= 0) { config.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis()); config.setNumTestsPerEvictionRun(getNumTestsPerEvictionRun()); config.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis()); } else { config.setMaxTotal(getMaxPreparedStatements()); config.setTimeBetweenEvictionRunsMillis(-1); config.setNumTestsPerEvictionRun(0); config.setMinEvictableIdleTimeMillis(0); } stmtPool = new GenericKeyedObjectPool<>(pci, config); pci.setStatementPool(stmtPool); } return pci; } | /**
* Attempt to establish a database connection.
* @param username name to be used for the connection
* @param pass password to be used fur the connection
*/ | Attempt to establish a database connection | getPooledConnection | {
"repo_name": "kmiku7/apache-commons-dbcp-annotated",
"path": "src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java",
"license": "apache-2.0",
"size": 26088
} | [
"java.sql.DriverManager",
"java.sql.SQLException",
"javax.sql.PooledConnection",
"org.apache.commons.dbcp2.PoolablePreparedStatement",
"org.apache.commons.pool2.KeyedObjectPool",
"org.apache.commons.pool2.impl.GenericKeyedObjectPool",
"org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig"
] | import java.sql.DriverManager; import java.sql.SQLException; import javax.sql.PooledConnection; import org.apache.commons.dbcp2.PoolablePreparedStatement; import org.apache.commons.pool2.KeyedObjectPool; import org.apache.commons.pool2.impl.GenericKeyedObjectPool; import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig; | import java.sql.*; import javax.sql.*; import org.apache.commons.dbcp2.*; import org.apache.commons.pool2.*; import org.apache.commons.pool2.impl.*; | [
"java.sql",
"javax.sql",
"org.apache.commons"
] | java.sql; javax.sql; org.apache.commons; | 1,450,179 |
public Stroke getAdvanceLineStroke() {
return this.advanceLineStroke;
}
| Stroke function() { return this.advanceLineStroke; } | /**
* The advance line is the line drawn at the limit of the current cycle,
* when erasing the previous cycle.
*
* @return The stroke (never <code>null</code>).
*/ | The advance line is the line drawn at the limit of the current cycle, when erasing the previous cycle | getAdvanceLineStroke | {
"repo_name": "sternze/CurrentTopics_JFreeChart",
"path": "source/org/jfree/chart/axis/CyclicNumberAxis.java",
"license": "lgpl-2.1",
"size": 42129
} | [
"java.awt.Stroke"
] | import java.awt.Stroke; | import java.awt.*; | [
"java.awt"
] | java.awt; | 2,056,159 |
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<ConfluentAgreementResourceInner> list() {
return new PagedIterable<>(listAsync());
} | @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<ConfluentAgreementResourceInner> function() { return new PagedIterable<>(listAsync()); } | /**
* List Confluent marketplace agreements in the subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response of a list operation.
*/ | List Confluent marketplace agreements in the subscription | list | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/confluent/azure-resourcemanager-confluent/src/main/java/com/azure/resourcemanager/confluent/implementation/MarketplaceAgreementsClientImpl.java",
"license": "mit",
"size": 20730
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.http.rest.PagedIterable",
"com.azure.resourcemanager.confluent.fluent.models.ConfluentAgreementResourceInner"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.resourcemanager.confluent.fluent.models.ConfluentAgreementResourceInner; | import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.resourcemanager.confluent.fluent.models.*; | [
"com.azure.core",
"com.azure.resourcemanager"
] | com.azure.core; com.azure.resourcemanager; | 2,856,125 |
IResult findOrCreateBookmark(String url, String title, String details, String language, String userId, JSONObject tagLabels, ITicket credentials);
| IResult findOrCreateBookmark(String url, String title, String details, String language, String userId, JSONObject tagLabels, ITicket credentials); | /**
* Find bookmark node for <code>url</code> or otherwise make it and pivot to <code>userId</code>
* @param url
* @param title
* @param details TODO
* @param language
* @param userId
* @param tagLabels can be <code>null</code>
* @param credentials
* @return
*/ | Find bookmark node for <code>url</code> or otherwise make it and pivot to <code>userId</code> | findOrCreateBookmark | {
"repo_name": "wenzowski/backside-servlet-ks",
"path": "src/main/java/org/topicquests/backside/servlet/apps/tm/api/ITopicMapModel.java",
"license": "apache-2.0",
"size": 7447
} | [
"net.minidev.json.JSONObject",
"org.topicquests.ks.api.ITicket",
"org.topicquests.support.api.IResult"
] | import net.minidev.json.JSONObject; import org.topicquests.ks.api.ITicket; import org.topicquests.support.api.IResult; | import net.minidev.json.*; import org.topicquests.ks.api.*; import org.topicquests.support.api.*; | [
"net.minidev.json",
"org.topicquests.ks",
"org.topicquests.support"
] | net.minidev.json; org.topicquests.ks; org.topicquests.support; | 2,260,409 |
public static ClosableIterator<Class> getAllRange(Model model, org.ontoware.rdf2go.model.node.Resource instanceResource) {
return Base.getAll(model, instanceResource, RANGE, Class.class);
}
| static ClosableIterator<Class> function(Model model, org.ontoware.rdf2go.model.node.Resource instanceResource) { return Base.getAll(model, instanceResource, RANGE, Class.class); } | /**
* Get all values of property Range * @param model an RDF2Go model
* @param resource an RDF2Go resource
* @return a ClosableIterator of $type
*
* [Generated from RDFReactor template rule #get11static]
*/ | Get all values of property Range | getAllRange | {
"repo_name": "josectoledo/semweb4j",
"path": "org.semweb4j.rdfreactor.runtime/src/main/java/org/ontoware/rdfreactor/schema/rdfs/Property.java",
"license": "bsd-2-clause",
"size": 36485
} | [
"org.ontoware.aifbcommons.collection.ClosableIterator",
"org.ontoware.rdf2go.model.Model",
"org.ontoware.rdfreactor.runtime.Base"
] | import org.ontoware.aifbcommons.collection.ClosableIterator; import org.ontoware.rdf2go.model.Model; import org.ontoware.rdfreactor.runtime.Base; | import org.ontoware.aifbcommons.collection.*; import org.ontoware.rdf2go.model.*; import org.ontoware.rdfreactor.runtime.*; | [
"org.ontoware.aifbcommons",
"org.ontoware.rdf2go",
"org.ontoware.rdfreactor"
] | org.ontoware.aifbcommons; org.ontoware.rdf2go; org.ontoware.rdfreactor; | 2,326,347 |
public String retrieveCreatedUserOfRequest(String uuid) throws InternalWorkflowException {
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
String query = SQLConstants.GET_WORKFLOW_REQUEST_QUERY;
try {
prepStmt = connection.prepareStatement(query);
prepStmt.setString(1, uuid);
resultSet = prepStmt.executeQuery();
if (resultSet.next()) {
return resultSet.getString(SQLConstants.CREATED_BY_COLUMN);
}
} catch (SQLException e) {
throw new InternalWorkflowException("Error when executing the sql query:" + query, e);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
return "";
} | String function(String uuid) throws InternalWorkflowException { Connection connection = IdentityDatabaseUtil.getDBConnection(); PreparedStatement prepStmt = null; ResultSet resultSet = null; String query = SQLConstants.GET_WORKFLOW_REQUEST_QUERY; try { prepStmt = connection.prepareStatement(query); prepStmt.setString(1, uuid); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { return resultSet.getString(SQLConstants.CREATED_BY_COLUMN); } } catch (SQLException e) { throw new InternalWorkflowException(STR + query, e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt); } return ""; } | /**
* Get user who created the request.
*
* @param uuid
* @return
* @throws InternalWorkflowException
*/ | Get user who created the request | retrieveCreatedUserOfRequest | {
"repo_name": "bastiaanb/carbon-identity",
"path": "components/workflow-mgt/org.wso2.carbon.identity.workflow.mgt/src/main/java/org/wso2/carbon/identity/workflow/mgt/dao/WorkflowRequestDAO.java",
"license": "apache-2.0",
"size": 20172
} | [
"java.sql.Connection",
"java.sql.PreparedStatement",
"java.sql.ResultSet",
"java.sql.SQLException",
"org.wso2.carbon.identity.core.util.IdentityDatabaseUtil",
"org.wso2.carbon.identity.workflow.mgt.exception.InternalWorkflowException"
] | import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.workflow.mgt.exception.InternalWorkflowException; | import java.sql.*; import org.wso2.carbon.identity.core.util.*; import org.wso2.carbon.identity.workflow.mgt.exception.*; | [
"java.sql",
"org.wso2.carbon"
] | java.sql; org.wso2.carbon; | 2,012,708 |
Matrix getTransform(); | Matrix getTransform(); | /**
* Gets the current transform.
*
* @return the transform
*/ | Gets the current transform | getTransform | {
"repo_name": "mrkcsc/android-mg-bootstrap",
"path": "mg-bootstrap/lib/src/main/java/com/miguelgaeta/bootstrap/mg_images/samples/zoomable/ZoomableController.java",
"license": "apache-2.0",
"size": 2585
} | [
"android.graphics.Matrix"
] | import android.graphics.Matrix; | import android.graphics.*; | [
"android.graphics"
] | android.graphics; | 1,527,429 |
@Override
public void onTagDiscovered(Tag tag)
{
Transceiver.Response response;
logger.clear();
logger.info(TAG, "Card Detected on Reader: " + StringUtil.join(tag.getTechList(), ", "));
Transceiver transceiver = Transceiver.create(logger, tag);
if (null == transceiver)
{
logger.alert(CARD_COMM_ERROR, ERROR_TITLE);
return;
}
// Select the PIV Card Application:
response = transceiver.transceive("SELECT PIV AID", Opacity.SELECT_PIV);
if (null == response)
{
logger.alert(CARD_COMM_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
// Open an Opacity secure tunnel, receiving the session keys:
OpacitySecureTunnel opacityTunnel = new OpacitySecureTunnel(logger);
HashMap<String, byte[]> sessionKeys;
try
{
sessionKeys = opacityTunnel.openTunnel(transceiver);
if (sessionKeys == null)
{
logger.error(TAG, "Unable to generate Opacity session keys");
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
} catch (GeneralSecurityException e)
{
logger.error(TAG, "Unable to establish Opacity Secure Tunnel", e);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
logger.newLine();
logger.info(TAG, "*** Begin secure messaging using AES-128 ***");
logger.newLine();
// Get the discovery object in the clear for later
// comparison with that retrieved through a secure channel.
response = transceiver.transceive("Get Discovery object in clear", GET_DISCOVERY_OBJECT);
if (null == response)
{
logger.alert(CARD_COMM_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
byte[] discoveryObject = response.data;
// Secure messaging using AES-128
// NIST SP800-73-4 says this should start at 1 (Part 2, Page 32)
int encCount = 1;
AesParameters encryptionParameters;
try
{
encryptionParameters = new AesParameters(encCount, ByteUtil.hexStringToByteArray(MCV), ByteUtil.hexStringToByteArray(RMCV), sessionKeys);
} catch (GeneralSecurityException e)
{
logger.error(TAG, "Unable to create AES Cipher", e);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
byte[][] encryptedApdu;
byte[] decryptedResponse;
String transaction;
// Check for need for pairing code:
if ((0xf & discoveryObject[discoveryObject.length - 2]) == 0x8)
{
logger.newLine();
transaction = "Verify Pairing Code";
logger.info(TAG, transaction);
GetNumericInputDialogFragment fragment = GetNumericInputDialogFragment.create("Enter Pairing Code (data encrypted in transit)");
String input = fragment.showDialog(activity);
fragment.dismiss();
if (null == input)
{
logger.error(TAG, "Unable to get Pairing Code from user");
logger.alert("Unable to get Pairing Code from user: try again.", ERROR_TITLE);
transceiver.close();
return;
}
logger.info(TAG, "Pairing code: " + input);
byte[] pairingCode = input.getBytes();
if (pairingCode.length != 8)
{
logger.error(TAG, "Pairing Code is too short or too long");
logger.alert("Pairing code is too short or too long: try again", ERROR_TITLE);
transceiver.close();
return;
}
try
{
encryptedApdu = Opacity.encryptApdu(
encryptionParameters,
new byte[]{(byte) 0x20},
new byte[1],
new byte[]{(byte) 0x98},
pairingCode,
null);
} catch (GeneralSecurityException e)
{
logger.error(TAG, "Unable to encrypt Pairing Code APDU", e);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
response = transceiver.transceive(transaction, encryptedApdu);
if (null == response)
{
logger.alert(CARD_COMM_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
if (!Opacity.confirmRmac(encryptionParameters, response.data))
{
logger.error(TAG, "Check of Pairing Code response CMAC failed");
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
if (!response.isWrappedStatusSuccess())
{
logger.error(TAG, "Pairing Code verification failed");
logger.alert("Pairing code verification failed.", ERROR_TITLE);
transceiver.close();
return;
}
encryptionParameters.count++;
}
// Get the X.509 certificate for PIV authentication:
logger.newLine();
transaction = "Get X.509 Cert. for PIV Auth.";
logger.info(TAG, transaction);
X509Certificate pivCert = null;
X509Certificate dodCaCert = new DODCACert().getDODCert();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "PIV_Auth_Cert_"+ByteUtil.toHexString(opacityTunnel.cardSignature.id)+".der");
FileOutputStream fos = null;
if(file.exists())
{
try
{
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream fis;
try
{
fis = new FileInputStream(file);
} catch (FileNotFoundException e)
{
e.printStackTrace();
return;
}
pivCert = (X509Certificate) cf.generateCertificate(fis);
try
{
pivCert.checkValidity();
pivCert.verify(dodCaCert.getPublicKey());
//Should do Cert CRL check here, will implement at a later date.
}catch(Exception ex)
{
logger.error(ERROR_TITLE,"PIV Auth. Certificate Invalid! "+ex.toString());
logger.alert(AUTH_ERROR,ERROR_TITLE);
transceiver.close();
return;
}
logger.info(TAG, "Stored PIV Auth. Cert:\n" + pivCert.toString());
} catch (GeneralSecurityException e)
{
logger.error(TAG, "Unable to decrypt response", e);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
}
else
{
try
{
encryptedApdu = Opacity.encryptApdu(
encryptionParameters,
ByteUtil.hexStringToByteArray("CB"),
ByteUtil.hexStringToByteArray("3F"),
ByteUtil.hexStringToByteArray("FF"),
ByteUtil.hexStringToByteArray("5C 03 5F C1 05"),
null);
} catch (Exception ex)
{
logger.error(TAG, "Unable to encrypt APDU", ex);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
response = transceiver.transceive(transaction, encryptedApdu);
if (null == response)
{
logger.alert(CARD_COMM_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
if (!Opacity.confirmRmac(encryptionParameters, response.data))
{
logger.error(TAG, "Check of Response CMAC failed");
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
try
{
decryptedResponse = Opacity.getDecryptedResponse(encryptionParameters, response.data);
if (null != decryptedResponse)
{
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bis = new ByteArrayInputStream(Arrays.copyOfRange(decryptedResponse, 8, 8 + (((decryptedResponse[6] & 0xFF) << 8) | (decryptedResponse[7] & 0xFF))));
pivCert = (X509Certificate) cf.generateCertificate(bis);
try
{
pivCert.checkValidity();
pivCert.verify(dodCaCert.getPublicKey());
//Should do Cert CRL check here, will implement at a later date.
} catch (Exception ex)
{
logger.error(ERROR_TITLE, "PIV Auth. Certificate Invalid! " + ex.toString());
logger.alert(AUTH_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
logger.info(TAG, "Decrypted response:\n" + pivCert.toString());
}
} catch (GeneralSecurityException e)
{
logger.error(TAG, "Unable to decrypt response", e);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
try
{
fos = new FileOutputStream(file);
// Writes bytes from the specified byte array to this file output stream
try
{
fos.write(pivCert.getEncoded());
} catch (CertificateEncodingException e)
{
e.printStackTrace();
}
}catch (FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch (IOException ioe)
{
System.out.println("Exception while writing file " + ioe);
}
finally
{
// Make sure the stream is closed:
try
{
if (fos != null)
{
fos.close();
}
}
catch (IOException ioe)
{
System.out.println("Error while closing stream: " + ioe);
}
}
logger.info(TAG, "PIV Auth. Cert. Path: " + file.getPath());
encryptionParameters.count++;
}
// Get the PIN from the user and verify it:
logger.newLine();
transaction = "Verify PIN";
logger.info(TAG, transaction);
GetNumericInputDialogFragment fragment = GetNumericInputDialogFragment.create("Enter PIN (data encrypted in transit)");
String input = fragment.showDialog(activity);
fragment.dismiss();
if (null == input)
{
logger.error(TAG, "Unable to get PIN from user");
logger.alert("Unable to get PIN from user: try again.", ERROR_TITLE);
transceiver.close();
return;
}
logger.info(TAG, "PIN: " + input);
byte[] pin = input.getBytes();
if (pin.length < 6 || pin.length > 8)
{
logger.error(TAG, "PIN is too short or too long");
logger.alert("PIN is too short or too long: try again.", ERROR_TITLE);
transceiver.close();
return;
} else if (pin.length < 8)
{
byte[] pad = new byte[8 - pin.length];
Arrays.fill(pad, (byte) 0xff);
pin = ByteUtil.concatenate(pin, pad);
}
try
{
encryptedApdu = Opacity.encryptApdu(
encryptionParameters,
new byte[]{(byte) 0x20},
new byte[1],
new byte[]{(byte) 0x80},
pin,
null);
} catch (GeneralSecurityException e)
{
logger.error(TAG, "Unable to encrypt PIN APDU", e);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
response = transceiver.transceive(transaction, encryptedApdu);
if (null == response)
{
logger.alert(CARD_COMM_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
if (!Opacity.confirmRmac(encryptionParameters, response.data))
{
logger.error(TAG, "Check of PIN response CMAC failed");
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
if (!response.isWrappedStatusSuccess())
{
logger.error(TAG, "PIN verification failed");
logger.alert("PIN verification failed: try again.", ERROR_TITLE);
transceiver.close();
return;
} else
{
logger.info(TAG,"Virtual Contact Interface Open\n\n" + "OPACITY Secure Tunnel\nestablished in: " + opacityTunnel.getCreationTime().toString() + " ms\n\n(secure messaging using AES-128)\n");
}
encryptionParameters.count++;
logger.newLine();
transaction = "PIV Auth. Challenge with 192-Byte Nonce";
logger.info(TAG, transaction);
long sigStartTime = System.currentTimeMillis();
byte[] nonce=new byte[192];
SecureRandom rand=new SecureRandom();
rand.nextBytes(nonce);
byte[] payload = ByteUtil.hexStringToByteArray("7C" + "820106" + "8200" + "81820100");
payload = ByteUtil.concatenate(payload, Opacity.pkcs1v15Pad("01", nonce));
try
{
encryptedApdu = Opacity.encryptApdu(
encryptionParameters,
ByteUtil.hexStringToByteArray("87"),
ByteUtil.hexStringToByteArray("07"),
ByteUtil.hexStringToByteArray("9A"),
payload,
new byte[]{(byte) 0x00});
} catch (Exception ex)
{
logger.error(TAG, "Unable to encrypt APDU", ex);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
response = transceiver.transceive(transaction, encryptedApdu);
if (null == response)
{
logger.alert(CARD_COMM_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
if (!Opacity.confirmRmac(encryptionParameters, response.data))
{
logger.error(TAG, "Check of Response CMAC failed");
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
try
{
decryptedResponse = Opacity.getDecryptedResponse(encryptionParameters, response.data);
if (null != decryptedResponse)
{
logger.info(TAG, "Decrypted response: " + ByteUtil.toHexString(decryptedResponse, " "));
}
} catch (GeneralSecurityException e)
{
logger.error(TAG, "Unable to decrypt response", e);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
encryptionParameters.count++;
Signature sig = null;
try
{
sig = Signature.getInstance("NONEwithRSA");
} catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
if(null!=sig)
{
try
{
sig.initVerify(pivCert);
} catch (InvalidKeyException e)
{
e.printStackTrace();
}
try
{
sig.update(nonce);
} catch (SignatureException e)
{
e.printStackTrace();
}
try
{
if (sig.verify(decryptedResponse, 8, 256))
{
logger.info(TAG, "PIV Challenge Valid");
logger.alert("Contactless PIV Authentication\nFIPS 201 Level 4 Assurance\n\nRSA Challenge Time: " + (System.currentTimeMillis() - sigStartTime) + " ms\n\n" + "OPACITY Secure Tunnel\nestablished in: " + opacityTunnel.getCreationTime().toString() + " ms\n\n(secure messaging using AES-128)\n", SUCCESS_TITLE);
} else
{
logger.info(TAG, "PIV Challenge Invalid");
logger.alert(AUTH_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
} catch (SignatureException e)
{
e.printStackTrace();
}
}
// Get the discovery object through a secure messaging tunnel:
logger.newLine();
transaction = "Get Discovery Object through secure messaging tunnel";
logger.info(TAG, transaction);
try
{
encryptedApdu = Opacity.encryptApdu(
encryptionParameters,
ByteUtil.hexStringToByteArray("CB"),
ByteUtil.hexStringToByteArray("3F"),
ByteUtil.hexStringToByteArray("FF"),
ByteUtil.hexStringToByteArray("5C 01 7E"),
new byte[1]);
}
catch (Exception ex)
{
logger.error(TAG, "Unable to encrypt APDU", ex);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
response = transceiver.transceive(transaction, encryptedApdu);
if (null == response)
{
logger.alert(CARD_COMM_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
if (!Opacity.confirmRmac(encryptionParameters, response.data))
{
logger.error(TAG, "Check of Response CMAC failed");
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
try
{
decryptedResponse = Opacity.getDecryptedResponse(encryptionParameters, response.data);
if (null != decryptedResponse)
{
logger.info(TAG, "Decrypted response: " + ByteUtil.toHexString(decryptedResponse, " "));
}
else
{
logger.error(TAG, "There is no response to decrypt");
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
}
catch (GeneralSecurityException e)
{
logger.error(TAG, "Unable to decrypt response", e);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
logger.newLine();
logger.info(TAG, "Check Discovery Object decryption:");
logger.info(TAG, " " + ByteUtil.toHexString(discoveryObject, " "));
logger.info(TAG, " " + ByteUtil.toHexString(decryptedResponse, " "));
if (Arrays.equals(discoveryObject, Arrays.copyOfRange(decryptedResponse, 0, discoveryObject.length)))
{
logger.info(TAG,"Decrypted Discovery Object matches that received in the clear.");
}
else
{
logger.info(TAG,"Decrypted Discovery Object does not match that received in the clear: check log for details");
}
encryptionParameters.count++;
// Get and display the cardholder facial image from the card:
logger.newLine();
transaction = "Get Cardholder Facial Image";
logger.info(TAG, transaction);
try
{
encryptedApdu = Opacity.encryptApdu(
encryptionParameters,
ByteUtil.hexStringToByteArray("CB"),
ByteUtil.hexStringToByteArray("3F"),
ByteUtil.hexStringToByteArray("FF"),
ByteUtil.hexStringToByteArray("5C 03 5F C1 08"),
null);
}
catch (Exception ex)
{
logger.error(TAG, "Unable to encrypt APDU", ex);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
response = transceiver.transceive(transaction, encryptedApdu);
if (null == response)
{
logger.alert(CARD_COMM_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
if (!Opacity.confirmRmac(encryptionParameters, response.data))
{
logger.error(TAG, "Check of Response CMAC failed");
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
try
{
decryptedResponse = Opacity.getDecryptedResponse(encryptionParameters, response.data);
if (null != decryptedResponse)
{
logger.info(TAG, "Decrypted response: " + ByteUtil.toHexString(Arrays.copyOfRange(decryptedResponse,0,100)," ")+" ... response truncated ... ");
}
else
{
logger.warn(TAG, "No decrypted facial image to store");
transceiver.close();
return;
}
}
catch (GeneralSecurityException e)
{
logger.error(TAG, "Unable to decrypt response", e);
logger.alert(CRYPTO_ERROR, ERROR_TITLE);
transceiver.close();
return;
}
encryptionParameters.count++;
transceiver.close();
String decryptedResponseHexString = ByteUtil.toHexString(decryptedResponse);
int headerStartIndex = decryptedResponseHexString.indexOf("4641430030313000") / 2;
int imageStartIndex = decryptedResponseHexString.indexOf("FF4FFF51") / 2;
int imageLength = 0;
logger.info(TAG, "Header start index: " + headerStartIndex);
logger.info(TAG, "Image start index: " + imageStartIndex);
if (0 != headerStartIndex)
{
imageLength = Integer.parseInt(decryptedResponseHexString.substring(headerStartIndex * 2 + 16, headerStartIndex * 2 + 24), 16) - 46;
logger.info(TAG, "Image length: " + imageLength);
logger.info(TAG, String.format("Received %d-byte facial image from card!", imageLength));
}
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "face_image.jp2");
fos = null;
logger.info(TAG, "Image Path: " + file.getPath());
boolean success = false;
try
{
fos = new FileOutputStream(file);
// Writes bytes from the specified byte array to this file output stream
fos.write(Arrays.copyOfRange(decryptedResponse, imageStartIndex, imageStartIndex + imageLength));
success = true;
}
catch (FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch (IOException ioe)
{
System.out.println("Exception while writing file " + ioe);
}
finally
{
// Make sure the stream is closed:
try
{
if (fos != null)
{
fos.close();
}
}
catch (IOException ioe)
{
System.out.println("Error while closing stream: " + ioe);
}
}
if (success)
{
// Launch an activity to view the facial image, which is in JPEG 2000 format.
// The Android app "Image Converter" seems to work pretty well.
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW);
sendIntent.setData(Uri.fromFile(file));
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (sendIntent.resolveActivity(activity.getPackageManager()) != null)
{
activity.startActivity(sendIntent);
}
}
} | void function(Tag tag) { Transceiver.Response response; logger.clear(); logger.info(TAG, STR + StringUtil.join(tag.getTechList(), STR)); Transceiver transceiver = Transceiver.create(logger, tag); if (null == transceiver) { logger.alert(CARD_COMM_ERROR, ERROR_TITLE); return; } response = transceiver.transceive(STR, Opacity.SELECT_PIV); if (null == response) { logger.alert(CARD_COMM_ERROR, ERROR_TITLE); transceiver.close(); return; } OpacitySecureTunnel opacityTunnel = new OpacitySecureTunnel(logger); HashMap<String, byte[]> sessionKeys; try { sessionKeys = opacityTunnel.openTunnel(transceiver); if (sessionKeys == null) { logger.error(TAG, STR); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } } catch (GeneralSecurityException e) { logger.error(TAG, STR, e); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } logger.newLine(); logger.info(TAG, STR); logger.newLine(); response = transceiver.transceive(STR, GET_DISCOVERY_OBJECT); if (null == response) { logger.alert(CARD_COMM_ERROR, ERROR_TITLE); transceiver.close(); return; } byte[] discoveryObject = response.data; int encCount = 1; AesParameters encryptionParameters; try { encryptionParameters = new AesParameters(encCount, ByteUtil.hexStringToByteArray(MCV), ByteUtil.hexStringToByteArray(RMCV), sessionKeys); } catch (GeneralSecurityException e) { logger.error(TAG, STR, e); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } byte[][] encryptedApdu; byte[] decryptedResponse; String transaction; if ((0xf & discoveryObject[discoveryObject.length - 2]) == 0x8) { logger.newLine(); transaction = STR; logger.info(TAG, transaction); GetNumericInputDialogFragment fragment = GetNumericInputDialogFragment.create(STR); String input = fragment.showDialog(activity); fragment.dismiss(); if (null == input) { logger.error(TAG, STR); logger.alert(STR, ERROR_TITLE); transceiver.close(); return; } logger.info(TAG, STR + input); byte[] pairingCode = input.getBytes(); if (pairingCode.length != 8) { logger.error(TAG, STR); logger.alert(STR, ERROR_TITLE); transceiver.close(); return; } try { encryptedApdu = Opacity.encryptApdu( encryptionParameters, new byte[]{(byte) 0x20}, new byte[1], new byte[]{(byte) 0x98}, pairingCode, null); } catch (GeneralSecurityException e) { logger.error(TAG, STR, e); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } response = transceiver.transceive(transaction, encryptedApdu); if (null == response) { logger.alert(CARD_COMM_ERROR, ERROR_TITLE); transceiver.close(); return; } if (!Opacity.confirmRmac(encryptionParameters, response.data)) { logger.error(TAG, STR); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } if (!response.isWrappedStatusSuccess()) { logger.error(TAG, STR); logger.alert(STR, ERROR_TITLE); transceiver.close(); return; } encryptionParameters.count++; } logger.newLine(); transaction = STR; logger.info(TAG, transaction); X509Certificate pivCert = null; X509Certificate dodCaCert = new DODCACert().getDODCert(); File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), STR+ByteUtil.toHexString(opacityTunnel.cardSignature.id)+".der"); FileOutputStream fos = null; if(file.exists()) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); FileInputStream fis; try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); return; } pivCert = (X509Certificate) cf.generateCertificate(fis); try { pivCert.checkValidity(); pivCert.verify(dodCaCert.getPublicKey()); }catch(Exception ex) { logger.error(ERROR_TITLE,STR+ex.toString()); logger.alert(AUTH_ERROR,ERROR_TITLE); transceiver.close(); return; } logger.info(TAG, STR + pivCert.toString()); } catch (GeneralSecurityException e) { logger.error(TAG, STR, e); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } } else { try { encryptedApdu = Opacity.encryptApdu( encryptionParameters, ByteUtil.hexStringToByteArray("CB"), ByteUtil.hexStringToByteArray("3F"), ByteUtil.hexStringToByteArray("FF"), ByteUtil.hexStringToByteArray(STR), null); } catch (Exception ex) { logger.error(TAG, STR, ex); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } response = transceiver.transceive(transaction, encryptedApdu); if (null == response) { logger.alert(CARD_COMM_ERROR, ERROR_TITLE); transceiver.close(); return; } if (!Opacity.confirmRmac(encryptionParameters, response.data)) { logger.error(TAG, STR); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } try { decryptedResponse = Opacity.getDecryptedResponse(encryptionParameters, response.data); if (null != decryptedResponse) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bis = new ByteArrayInputStream(Arrays.copyOfRange(decryptedResponse, 8, 8 + (((decryptedResponse[6] & 0xFF) << 8) (decryptedResponse[7] & 0xFF)))); pivCert = (X509Certificate) cf.generateCertificate(bis); try { pivCert.checkValidity(); pivCert.verify(dodCaCert.getPublicKey()); } catch (Exception ex) { logger.error(ERROR_TITLE, STR + ex.toString()); logger.alert(AUTH_ERROR, ERROR_TITLE); transceiver.close(); return; } logger.info(TAG, STR + pivCert.toString()); } } catch (GeneralSecurityException e) { logger.error(TAG, STR, e); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } try { fos = new FileOutputStream(file); try { fos.write(pivCert.getEncoded()); } catch (CertificateEncodingException e) { e.printStackTrace(); } }catch (FileNotFoundException e) { System.out.println(STR + e); } catch (IOException ioe) { System.out.println(STR + ioe); } finally { try { if (fos != null) { fos.close(); } } catch (IOException ioe) { System.out.println(STR + ioe); } } logger.info(TAG, STR + file.getPath()); encryptionParameters.count++; } logger.newLine(); transaction = STR; logger.info(TAG, transaction); GetNumericInputDialogFragment fragment = GetNumericInputDialogFragment.create(STR); String input = fragment.showDialog(activity); fragment.dismiss(); if (null == input) { logger.error(TAG, STR); logger.alert(STR, ERROR_TITLE); transceiver.close(); return; } logger.info(TAG, STR + input); byte[] pin = input.getBytes(); if (pin.length < 6 pin.length > 8) { logger.error(TAG, STR); logger.alert(STR, ERROR_TITLE); transceiver.close(); return; } else if (pin.length < 8) { byte[] pad = new byte[8 - pin.length]; Arrays.fill(pad, (byte) 0xff); pin = ByteUtil.concatenate(pin, pad); } try { encryptedApdu = Opacity.encryptApdu( encryptionParameters, new byte[]{(byte) 0x20}, new byte[1], new byte[]{(byte) 0x80}, pin, null); } catch (GeneralSecurityException e) { logger.error(TAG, STR, e); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } response = transceiver.transceive(transaction, encryptedApdu); if (null == response) { logger.alert(CARD_COMM_ERROR, ERROR_TITLE); transceiver.close(); return; } if (!Opacity.confirmRmac(encryptionParameters, response.data)) { logger.error(TAG, STR); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } if (!response.isWrappedStatusSuccess()) { logger.error(TAG, STR); logger.alert(STR, ERROR_TITLE); transceiver.close(); return; } else { logger.info(TAG,STR + STR + opacityTunnel.getCreationTime().toString() + STR); } encryptionParameters.count++; logger.newLine(); transaction = STR; logger.info(TAG, transaction); long sigStartTime = System.currentTimeMillis(); byte[] nonce=new byte[192]; SecureRandom rand=new SecureRandom(); rand.nextBytes(nonce); byte[] payload = ByteUtil.hexStringToByteArray("7C" + STR + "8200" + STR); payload = ByteUtil.concatenate(payload, Opacity.pkcs1v15Pad("01", nonce)); try { encryptedApdu = Opacity.encryptApdu( encryptionParameters, ByteUtil.hexStringToByteArray("87"), ByteUtil.hexStringToByteArray("07"), ByteUtil.hexStringToByteArray("9A"), payload, new byte[]{(byte) 0x00}); } catch (Exception ex) { logger.error(TAG, STR, ex); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } response = transceiver.transceive(transaction, encryptedApdu); if (null == response) { logger.alert(CARD_COMM_ERROR, ERROR_TITLE); transceiver.close(); return; } if (!Opacity.confirmRmac(encryptionParameters, response.data)) { logger.error(TAG, STR); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } try { decryptedResponse = Opacity.getDecryptedResponse(encryptionParameters, response.data); if (null != decryptedResponse) { logger.info(TAG, STR + ByteUtil.toHexString(decryptedResponse, " ")); } } catch (GeneralSecurityException e) { logger.error(TAG, STR, e); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } encryptionParameters.count++; Signature sig = null; try { sig = Signature.getInstance(STR); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } if(null!=sig) { try { sig.initVerify(pivCert); } catch (InvalidKeyException e) { e.printStackTrace(); } try { sig.update(nonce); } catch (SignatureException e) { e.printStackTrace(); } try { if (sig.verify(decryptedResponse, 8, 256)) { logger.info(TAG, STR); logger.alert(STR + (System.currentTimeMillis() - sigStartTime) + STR + STR + opacityTunnel.getCreationTime().toString() + STR, SUCCESS_TITLE); } else { logger.info(TAG, STR); logger.alert(AUTH_ERROR, ERROR_TITLE); transceiver.close(); return; } } catch (SignatureException e) { e.printStackTrace(); } } logger.newLine(); transaction = STR; logger.info(TAG, transaction); try { encryptedApdu = Opacity.encryptApdu( encryptionParameters, ByteUtil.hexStringToByteArray("CB"), ByteUtil.hexStringToByteArray("3F"), ByteUtil.hexStringToByteArray("FF"), ByteUtil.hexStringToByteArray(STR), new byte[1]); } catch (Exception ex) { logger.error(TAG, STR, ex); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } response = transceiver.transceive(transaction, encryptedApdu); if (null == response) { logger.alert(CARD_COMM_ERROR, ERROR_TITLE); transceiver.close(); return; } if (!Opacity.confirmRmac(encryptionParameters, response.data)) { logger.error(TAG, STR); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } try { decryptedResponse = Opacity.getDecryptedResponse(encryptionParameters, response.data); if (null != decryptedResponse) { logger.info(TAG, STR + ByteUtil.toHexString(decryptedResponse, " ")); } else { logger.error(TAG, STR); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } } catch (GeneralSecurityException e) { logger.error(TAG, STR, e); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } logger.newLine(); logger.info(TAG, STR); logger.info(TAG, " " + ByteUtil.toHexString(discoveryObject, " ")); logger.info(TAG, " " + ByteUtil.toHexString(decryptedResponse, " ")); if (Arrays.equals(discoveryObject, Arrays.copyOfRange(decryptedResponse, 0, discoveryObject.length))) { logger.info(TAG,STR); } else { logger.info(TAG,STR); } encryptionParameters.count++; logger.newLine(); transaction = STR; logger.info(TAG, transaction); try { encryptedApdu = Opacity.encryptApdu( encryptionParameters, ByteUtil.hexStringToByteArray("CB"), ByteUtil.hexStringToByteArray("3F"), ByteUtil.hexStringToByteArray("FF"), ByteUtil.hexStringToByteArray(STR), null); } catch (Exception ex) { logger.error(TAG, STR, ex); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } response = transceiver.transceive(transaction, encryptedApdu); if (null == response) { logger.alert(CARD_COMM_ERROR, ERROR_TITLE); transceiver.close(); return; } if (!Opacity.confirmRmac(encryptionParameters, response.data)) { logger.error(TAG, STR); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } try { decryptedResponse = Opacity.getDecryptedResponse(encryptionParameters, response.data); if (null != decryptedResponse) { logger.info(TAG, STR + ByteUtil.toHexString(Arrays.copyOfRange(decryptedResponse,0,100)," ")+STR); } else { logger.warn(TAG, STR); transceiver.close(); return; } } catch (GeneralSecurityException e) { logger.error(TAG, STR, e); logger.alert(CRYPTO_ERROR, ERROR_TITLE); transceiver.close(); return; } encryptionParameters.count++; transceiver.close(); String decryptedResponseHexString = ByteUtil.toHexString(decryptedResponse); int headerStartIndex = decryptedResponseHexString.indexOf(STR) / 2; int imageStartIndex = decryptedResponseHexString.indexOf(STR) / 2; int imageLength = 0; logger.info(TAG, STR + headerStartIndex); logger.info(TAG, STR + imageStartIndex); if (0 != headerStartIndex) { imageLength = Integer.parseInt(decryptedResponseHexString.substring(headerStartIndex * 2 + 16, headerStartIndex * 2 + 24), 16) - 46; logger.info(TAG, STR + imageLength); logger.info(TAG, String.format(STR, imageLength)); } file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), STR); fos = null; logger.info(TAG, STR + file.getPath()); boolean success = false; try { fos = new FileOutputStream(file); fos.write(Arrays.copyOfRange(decryptedResponse, imageStartIndex, imageStartIndex + imageLength)); success = true; } catch (FileNotFoundException e) { System.out.println(STR + e); } catch (IOException ioe) { System.out.println(STR + ioe); } finally { try { if (fos != null) { fos.close(); } } catch (IOException ioe) { System.out.println(STR + ioe); } } if (success) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_VIEW); sendIntent.setData(Uri.fromFile(file)); sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (sendIntent.resolveActivity(activity.getPackageManager()) != null) { activity.startActivity(sendIntent); } } } | /**
* Called when the NFS system finds a tag.
* @param tag the discovered NFC tag
*/ | Called when the NFS system finds a tag | onTagDiscovered | {
"repo_name": "PIVopacity/PIVOpacityDemo-android",
"path": "app/src/main/java/com/exponent/androidopacitydemo/CacReader.java",
"license": "mit",
"size": 28596
} | [
"android.content.Intent",
"android.net.Uri",
"android.nfc.Tag",
"android.os.Environment",
"com.exponent.CA",
"com.exponent.opacity.AesParameters",
"com.exponent.opacity.Opacity",
"com.exponent.opacity.OpacitySecureTunnel",
"java.io.ByteArrayInputStream",
"java.io.File",
"java.io.FileInputStream",
"java.io.FileNotFoundException",
"java.io.FileOutputStream",
"java.io.IOException",
"java.security.GeneralSecurityException",
"java.security.InvalidKeyException",
"java.security.NoSuchAlgorithmException",
"java.security.SecureRandom",
"java.security.Signature",
"java.security.SignatureException",
"java.security.cert.CertificateEncodingException",
"java.security.cert.CertificateFactory",
"java.security.cert.X509Certificate",
"java.util.Arrays",
"java.util.HashMap"
] | import android.content.Intent; import android.net.Uri; import android.nfc.Tag; import android.os.Environment; import com.exponent.CA; import com.exponent.opacity.AesParameters; import com.exponent.opacity.Opacity; import com.exponent.opacity.OpacitySecureTunnel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.HashMap; | import android.content.*; import android.net.*; import android.nfc.*; import android.os.*; import com.exponent.*; import com.exponent.opacity.*; import java.io.*; import java.security.*; import java.security.cert.*; import java.util.*; | [
"android.content",
"android.net",
"android.nfc",
"android.os",
"com.exponent",
"com.exponent.opacity",
"java.io",
"java.security",
"java.util"
] | android.content; android.net; android.nfc; android.os; com.exponent; com.exponent.opacity; java.io; java.security; java.util; | 1,385,625 |
@Test public void testAggregateRemove5() {
final HepProgram program = new HepProgramBuilder()
.addRuleInstance(AggregateRemoveRule.INSTANCE)
.addRuleInstance(ProjectMergeRule.INSTANCE)
.build();
final String sql = "select empno, deptno, sum(sal) "
+ "from sales.emp group by cube(empno, deptno)\n";
sql(sql).with(program)
.checkUnchanged();
} | @Test void function() { final HepProgram program = new HepProgramBuilder() .addRuleInstance(AggregateRemoveRule.INSTANCE) .addRuleInstance(ProjectMergeRule.INSTANCE) .build(); final String sql = STR + STR; sql(sql).with(program) .checkUnchanged(); } | /**
* Negative test case for AggregateRemoveRule, should not
* remove non-simple aggregates.
*/ | Negative test case for AggregateRemoveRule, should not remove non-simple aggregates | testAggregateRemove5 | {
"repo_name": "xhoong/incubator-calcite",
"path": "core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java",
"license": "apache-2.0",
"size": 255036
} | [
"org.apache.calcite.plan.hep.HepProgram",
"org.apache.calcite.plan.hep.HepProgramBuilder",
"org.apache.calcite.rel.rules.AggregateRemoveRule",
"org.apache.calcite.rel.rules.ProjectMergeRule",
"org.junit.Test"
] | import org.apache.calcite.plan.hep.HepProgram; import org.apache.calcite.plan.hep.HepProgramBuilder; import org.apache.calcite.rel.rules.AggregateRemoveRule; import org.apache.calcite.rel.rules.ProjectMergeRule; import org.junit.Test; | import org.apache.calcite.plan.hep.*; import org.apache.calcite.rel.rules.*; import org.junit.*; | [
"org.apache.calcite",
"org.junit"
] | org.apache.calcite; org.junit; | 2,617,473 |
protected synchronized void setActiveMessages(List<Message> messages) {
this.messages = new CopyOnWriteArrayList<>(messages);
this.fetchTime = System.currentTimeMillis();
// Enforce the provider attribute of the messages
this.messages.forEach(msg -> msg.setProvider(getProviderId()));
getCache().clear();
} | synchronized void function(List<Message> messages) { this.messages = new CopyOnWriteArrayList<>(messages); this.fetchTime = System.currentTimeMillis(); this.messages.forEach(msg -> msg.setProvider(getProviderId())); getCache().clear(); } | /**
* Updates the full list of active MSI messages
* @param messages the new full list of active MSI messages
*/ | Updates the full list of active MSI messages | setActiveMessages | {
"repo_name": "dma-dk/MsiProxy",
"path": "msiproxy-common/src/main/java/dk/dma/msiproxy/common/provider/AbstractProviderService.java",
"license": "apache-2.0",
"size": 14664
} | [
"dk.dma.msiproxy.model.msi.Message",
"java.util.List",
"java.util.concurrent.CopyOnWriteArrayList"
] | import dk.dma.msiproxy.model.msi.Message; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; | import dk.dma.msiproxy.model.msi.*; import java.util.*; import java.util.concurrent.*; | [
"dk.dma.msiproxy",
"java.util"
] | dk.dma.msiproxy; java.util; | 246,417 |
@Override
public void close() throws JMSException {
if (ActiveMQRASession.trace) {
ActiveMQRALogger.LOGGER.trace("close()");
}
sf.closeSession(this);
closeSession();
} | void function() throws JMSException { if (ActiveMQRASession.trace) { ActiveMQRALogger.LOGGER.trace(STR); } sf.closeSession(this); closeSession(); } | /**
* Closes the session. Sends a ConnectionEvent.CONNECTION_CLOSED to the
* managed connection.
*
* @throws JMSException Failed to close session.
*/ | Closes the session. Sends a ConnectionEvent.CONNECTION_CLOSED to the managed connection | close | {
"repo_name": "mnovak1/activemq-artemis",
"path": "artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQRASession.java",
"license": "apache-2.0",
"size": 48497
} | [
"javax.jms.JMSException"
] | import javax.jms.JMSException; | import javax.jms.*; | [
"javax.jms"
] | javax.jms; | 918,685 |
@CheckReturnValue
RelationType getRelationType(String label); | RelationType getRelationType(String label); | /**
* Get the Relation Type with the label provided, if it exists.
*
* @param label A unique label which identifies the Relation Type in the graph.
* @return The Relation Type with the provided label or null if no such Relation Type exists.
*
* @throws GraphOperationException if the graph is closed
*/ | Get the Relation Type with the label provided, if it exists | getRelationType | {
"repo_name": "alexandraorth/mindmapsdb",
"path": "grakn-core/src/main/java/ai/grakn/GraknGraph.java",
"license": "gpl-3.0",
"size": 15216
} | [
"ai.grakn.concept.RelationType"
] | import ai.grakn.concept.RelationType; | import ai.grakn.concept.*; | [
"ai.grakn.concept"
] | ai.grakn.concept; | 583,971 |
public NetworkInfo getOtherNetworkInfo() {
return mOtherNetworkInfo;
} | NetworkInfo function() { return mOtherNetworkInfo; } | /**
* If the most recent connectivity event was a DISCONNECT, return any information supplied in the broadcast about an alternate network that might be available. If this returns a non-null value, then another broadcast should follow shortly indicating whether connection to the other network succeeded.
*
* @return NetworkInfo
*/ | If the most recent connectivity event was a DISCONNECT, return any information supplied in the broadcast about an alternate network that might be available. If this returns a non-null value, then another broadcast should follow shortly indicating whether connection to the other network succeeded | getOtherNetworkInfo | {
"repo_name": "apkdemo/cube-sdk",
"path": "core/src/in/srain/cube/util/NetworkStatusManager.java",
"license": "apache-2.0",
"size": 7071
} | [
"android.net.NetworkInfo"
] | import android.net.NetworkInfo; | import android.net.*; | [
"android.net"
] | android.net; | 716,696 |
public Intent getNextStartedService() {
return ShadowApplication.getInstance().getNextStartedService();
} | Intent function() { return ShadowApplication.getInstance().getNextStartedService(); } | /**
* Delegates to the application to consume and return the next {@code Intent} on the
* started services stack.
*
* @return the next started {@code Intent} for a service
*/ | Delegates to the application to consume and return the next Intent on the started services stack | getNextStartedService | {
"repo_name": "ChengCorp/robolectric",
"path": "shadows/framework/src/main/java/org/robolectric/shadows/ShadowContextWrapper.java",
"license": "mit",
"size": 2394
} | [
"android.content.Intent"
] | import android.content.Intent; | import android.content.*; | [
"android.content"
] | android.content; | 310,967 |
static Object find(String factoryId, String fallbackClassName)
throws ConfigurationError
{
dPrint("find factoryId =" + factoryId);
// Use the system property first
try {
String systemProp = ss.getSystemProperty(factoryId);
if (systemProp != null) {
dPrint("found system property, value=" + systemProp);
return newInstance(systemProp, null, true, false, true);
}
}
catch (SecurityException se) {
if (debug) se.printStackTrace();
}
// try to read from $java.home/lib/jaxp.properties
try {
String factoryClassName = null;
if (firstTime) {
synchronized (cacheProps) {
if (firstTime) {
String configFile = ss.getSystemProperty("java.home") + File.separator +
"lib" + File.separator + "jaxp.properties";
File f = new File(configFile);
firstTime = false;
if (ss.doesFileExist(f)) {
dPrint("Read properties file "+f);
cacheProps.load(ss.getFileInputStream(f));
}
}
}
}
factoryClassName = cacheProps.getProperty(factoryId);
if (factoryClassName != null) {
dPrint("found in $java.home/jaxp.properties, value=" + factoryClassName);
return newInstance(factoryClassName, null, true, false, true);
}
}
catch (Exception ex) {
if (debug) ex.printStackTrace();
}
// Try Jar Service Provider Mechanism
Object provider = findJarServiceProvider(factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
dPrint("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, null, true, false, true);
} | static Object find(String factoryId, String fallbackClassName) throws ConfigurationError { dPrint(STR + factoryId); try { String systemProp = ss.getSystemProperty(factoryId); if (systemProp != null) { dPrint(STR + systemProp); return newInstance(systemProp, null, true, false, true); } } catch (SecurityException se) { if (debug) se.printStackTrace(); } try { String factoryClassName = null; if (firstTime) { synchronized (cacheProps) { if (firstTime) { String configFile = ss.getSystemProperty(STR) + File.separator + "lib" + File.separator + STR; File f = new File(configFile); firstTime = false; if (ss.doesFileExist(f)) { dPrint(STR+f); cacheProps.load(ss.getFileInputStream(f)); } } } } factoryClassName = cacheProps.getProperty(factoryId); if (factoryClassName != null) { dPrint(STR + factoryClassName); return newInstance(factoryClassName, null, true, false, true); } } catch (Exception ex) { if (debug) ex.printStackTrace(); } Object provider = findJarServiceProvider(factoryId); if (provider != null) { return provider; } if (fallbackClassName == null) { throw new ConfigurationError( STR + factoryId + STR, null); } dPrint(STR + fallbackClassName); return newInstance(fallbackClassName, null, true, false, true); } | /**
* Finds the implementation Class object in the specified order. Main
* entry point.
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* Package private so this code can be shared.
*/ | Finds the implementation Class object in the specified order. Main entry point | find | {
"repo_name": "axDev-JDK/jaxp",
"path": "src/javax/xml/transform/FactoryFinder.java",
"license": "gpl-2.0",
"size": 14167
} | [
"java.io.File"
] | import java.io.File; | import java.io.*; | [
"java.io"
] | java.io; | 1,603,394 |
List<ValidationRule> getValidationRulesWithNotificationTemplates(); | List<ValidationRule> getValidationRulesWithNotificationTemplates(); | /**
* Returns all ValidationRules which have associated
* ValidationNotificationTemplates.
*
* @return a List of ValidationRules.
*/ | Returns all ValidationRules which have associated ValidationNotificationTemplates | getValidationRulesWithNotificationTemplates | {
"repo_name": "dhis2/dhis2-core",
"path": "dhis-2/dhis-api/src/main/java/org/hisp/dhis/validation/ValidationRuleStore.java",
"license": "bsd-3-clause",
"size": 2317
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,161,981 |
@Override
public String getInitParameter(final String name) {
// Special handling for XML settings as the context setting must
// always override anything that might have been set by an application.
if (Globals.JASPER_XML_VALIDATION_TLD_INIT_PARAM.equals(name) &&
context.getTldValidation()) {
return "true";
}
if (Globals.JASPER_XML_VALIDATION_INIT_PARAM.equals(name) &&
context.getXmlValidation()) {
return "true";
}
if (Globals.JASPER_XML_BLOCK_EXTERNAL_INIT_PARAM.equals(name)) {
if (!context.getXmlBlockExternal()) {
// System admin has explicitly changed the default
return "false";
}
}
return parameters.get(name);
} | String function(final String name) { if (Globals.JASPER_XML_VALIDATION_TLD_INIT_PARAM.equals(name) && context.getTldValidation()) { return "true"; } if (Globals.JASPER_XML_VALIDATION_INIT_PARAM.equals(name) && context.getXmlValidation()) { return "true"; } if (Globals.JASPER_XML_BLOCK_EXTERNAL_INIT_PARAM.equals(name)) { if (!context.getXmlBlockExternal()) { return "false"; } } return parameters.get(name); } | /**
* Return the value of the specified initialization parameter, or
* <code>null</code> if this parameter does not exist.
*
* @param name Name of the initialization parameter to retrieve
*/ | Return the value of the specified initialization parameter, or <code>null</code> if this parameter does not exist | getInitParameter | {
"repo_name": "thanple/tomcatsrc",
"path": "java/org/apache/catalina/core/ApplicationContext.java",
"license": "apache-2.0",
"size": 57473
} | [
"org.apache.catalina.Globals"
] | import org.apache.catalina.Globals; | import org.apache.catalina.*; | [
"org.apache.catalina"
] | org.apache.catalina; | 965,181 |
void setLocalBranches(@Nonnull List<String> branches); | void setLocalBranches(@Nonnull List<String> branches); | /**
* Set local branches into view.
*
* @param branches
* local branches
*/ | Set local branches into view | setLocalBranches | {
"repo_name": "Panthro/che-plugins",
"path": "plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/fetch/FetchView.java",
"license": "epl-1.0",
"size": 4530
} | [
"java.util.List",
"javax.annotation.Nonnull"
] | import java.util.List; import javax.annotation.Nonnull; | import java.util.*; import javax.annotation.*; | [
"java.util",
"javax.annotation"
] | java.util; javax.annotation; | 2,500,281 |
protected void setButtonCGridLayoutData( Button button )
{
int widthHint = convertHorizontalDLUsToPixels( IDialogConstants.BUTTON_WIDTH );
Point minSize = button.computeSize( SWT.DEFAULT, SWT.DEFAULT, true );
button.setLayoutData( GridDataFactory.swtDefaults( )
.hint( Math.max( widthHint, minSize.x ), SWT.DEFAULT )
.create( ) );
}
private Composite valuesComposite;
private CCombo groupGroupLevel;
private CCombo measureGroupLevel;
private Button detailBtn;
private CrosstabFilterExpressionProvider provider;
private Label valuesLabel;
private Button updateAggrButton; | void function( Button button ) { int widthHint = convertHorizontalDLUsToPixels( IDialogConstants.BUTTON_WIDTH ); Point minSize = button.computeSize( SWT.DEFAULT, SWT.DEFAULT, true ); button.setLayoutData( GridDataFactory.swtDefaults( ) .hint( Math.max( widthHint, minSize.x ), SWT.DEFAULT ) .create( ) ); } private Composite valuesComposite; private CCombo groupGroupLevel; private CCombo measureGroupLevel; private Button detailBtn; private CrosstabFilterExpressionProvider provider; private Label valuesLabel; private Button updateAggrButton; | /**
* Set the layout data of the button to a GridData with appropriate heights
* and widths.
*
* @param button
*/ | Set the layout data of the button to a GridData with appropriate heights and widths | setButtonCGridLayoutData | {
"repo_name": "Charling-Huang/birt",
"path": "xtab/org.eclipse.birt.report.item.crosstab.ui/src/org/eclipse/birt/report/item/crosstab/ui/views/dialogs/CrosstabFilterConditionBuilder.java",
"license": "epl-1.0",
"size": 96434
} | [
"org.eclipse.birt.report.item.crosstab.internal.ui.dialogs.CrosstabFilterExpressionProvider",
"org.eclipse.jface.dialogs.IDialogConstants",
"org.eclipse.jface.layout.GridDataFactory",
"org.eclipse.swt.custom.CCombo",
"org.eclipse.swt.graphics.Point",
"org.eclipse.swt.widgets.Button",
"org.eclipse.swt.widgets.Composite",
"org.eclipse.swt.widgets.Label"
] | import org.eclipse.birt.report.item.crosstab.internal.ui.dialogs.CrosstabFilterExpressionProvider; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; | import org.eclipse.birt.report.item.crosstab.internal.ui.dialogs.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.layout.*; import org.eclipse.swt.custom.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; | [
"org.eclipse.birt",
"org.eclipse.jface",
"org.eclipse.swt"
] | org.eclipse.birt; org.eclipse.jface; org.eclipse.swt; | 1,103,972 |
private Purchase insertPurchase(Income income) {
Purchase purchase = new Purchase();
purchase.setSupplier(income.getSupplier());
purchase.setStatus(PurchaseStatus.CLOSED);
purchase.setSeries(income.getSeries());
purchase.setNumber(SeriesNumberUtil.obtainNumber(income.getSeries(), "Purchase"));
purchase.setPayMethod(null);
purchase.setIssueDate(income.getIssueTime());
IManagerBean purchaseBean;
try {
purchaseBean = BeanManager.getManagerBean(Purchase.class);
purchase = (Purchase)purchaseBean.insert(purchase);
return purchase;
} catch (ManagerBeanException e) {
LOGGER.log(Level.SEVERE,"Error inserting purchase for income with id: " + income.getId());
}
return null;
}
| Purchase function(Income income) { Purchase purchase = new Purchase(); purchase.setSupplier(income.getSupplier()); purchase.setStatus(PurchaseStatus.CLOSED); purchase.setSeries(income.getSeries()); purchase.setNumber(SeriesNumberUtil.obtainNumber(income.getSeries(), STR)); purchase.setPayMethod(null); purchase.setIssueDate(income.getIssueTime()); IManagerBean purchaseBean; try { purchaseBean = BeanManager.getManagerBean(Purchase.class); purchase = (Purchase)purchaseBean.insert(purchase); return purchase; } catch (ManagerBeanException e) { LOGGER.log(Level.SEVERE,STR + income.getId()); } return null; } | /**
* Inserts a purchase with this income
*
* @param income the related income
* @return the purchase inserted
*/ | Inserts a purchase with this income | insertPurchase | {
"repo_name": "Esleelkartea/aonGTA",
"path": "aongta_v1.0.0_src/Fuentes y JavaDoc/aon-ui-warehouse/src/com/code/aon/ui/warehouse/event/IncomeDetailControllerListener.java",
"license": "gpl-2.0",
"size": 7212
} | [
"com.code.aon.common.BeanManager",
"com.code.aon.common.IManagerBean",
"com.code.aon.common.ManagerBeanException",
"com.code.aon.common.temp.SeriesNumberUtil",
"com.code.aon.purchase.Purchase",
"com.code.aon.purchase.enumeration.PurchaseStatus",
"com.code.aon.warehouse.Income",
"java.util.logging.Level"
] | import com.code.aon.common.BeanManager; import com.code.aon.common.IManagerBean; import com.code.aon.common.ManagerBeanException; import com.code.aon.common.temp.SeriesNumberUtil; import com.code.aon.purchase.Purchase; import com.code.aon.purchase.enumeration.PurchaseStatus; import com.code.aon.warehouse.Income; import java.util.logging.Level; | import com.code.aon.common.*; import com.code.aon.common.temp.*; import com.code.aon.purchase.*; import com.code.aon.purchase.enumeration.*; import com.code.aon.warehouse.*; import java.util.logging.*; | [
"com.code.aon",
"java.util"
] | com.code.aon; java.util; | 232,048 |
@ZeppelinApi List<Revision> revisionHistory(String noteId,
String notePath,
AuthenticationInfo subject) throws IOException; | @ZeppelinApi List<Revision> revisionHistory(String noteId, String notePath, AuthenticationInfo subject) throws IOException; | /**
* List of revisions of the given Notebook.
*
* @param noteId id of the note
* @param notePath path of the note
* @param subject
* @return list of revisions
*/ | List of revisions of the given Notebook | revisionHistory | {
"repo_name": "sergeymazin/zeppelin",
"path": "zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/NotebookRepoWithVersionControl.java",
"license": "apache-2.0",
"size": 3459
} | [
"java.io.IOException",
"java.util.List",
"org.apache.zeppelin.annotation.ZeppelinApi",
"org.apache.zeppelin.user.AuthenticationInfo"
] | import java.io.IOException; import java.util.List; import org.apache.zeppelin.annotation.ZeppelinApi; import org.apache.zeppelin.user.AuthenticationInfo; | import java.io.*; import java.util.*; import org.apache.zeppelin.annotation.*; import org.apache.zeppelin.user.*; | [
"java.io",
"java.util",
"org.apache.zeppelin"
] | java.io; java.util; org.apache.zeppelin; | 1,993,819 |
public void setColor(final int color, final boolean callback) {
final int alpha = Color.alpha(color);
final float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
if (mShowAlphaPanel) {
mAlpha = alpha;
} else {
mAlpha = 0xff;
}
mHue = hsv[0];
mSat = hsv[1];
mVal = hsv[2];
if (callback) {
if (mOnColorChangedListener != null) {
mOnColorChangedListener.onColorChanged(color);
}
}
invalidate();
} | void function(final int color, final boolean callback) { final int alpha = Color.alpha(color); final float[] hsv = new float[3]; Color.colorToHSV(color, hsv); if (mShowAlphaPanel) { mAlpha = alpha; } else { mAlpha = 0xff; } mHue = hsv[0]; mSat = hsv[1]; mVal = hsv[2]; if (callback) { if (mOnColorChangedListener != null) { mOnColorChangedListener.onColorChanged(color); } } invalidate(); } | /**
* Set the color this view should show.
*
* @param color The color that should be selected.
* @param callback If you want to get a callback to your
* OnColorChangedListener.
*/ | Set the color this view should show | setColor | {
"repo_name": "0359xiaodong/twidere",
"path": "src/org/mariotaku/twidere/view/ColorPickerView.java",
"license": "gpl-3.0",
"size": 23424
} | [
"android.graphics.Color"
] | import android.graphics.Color; | import android.graphics.*; | [
"android.graphics"
] | android.graphics; | 1,596,066 |
// PRIVATE ============================================================================
private void pvSearchList() throws DBSIOException{
if (getEditingMode() == EditingMode.UPDATING){
ignoreEditing();
}
//Dispara evento para atualizar os dados
if (pvFireEventBeforeRefresh()){
//Apaga itens selecionados, se houver.
wSelectedRowsIndexes.clear();
pvFireEventAfterRefresh();
}
}
| void function() throws DBSIOException{ if (getEditingMode() == EditingMode.UPDATING){ ignoreEditing(); } if (pvFireEventBeforeRefresh()){ wSelectedRowsIndexes.clear(); pvFireEventAfterRefresh(); } } | /**
* Atualiza dados da lista e dispara os eventos beforeRefresh e afterRefresh.<br/>
* @throws DBSIOException
*/ | Atualiza dados da lista e dispara os eventos beforeRefresh e afterRefresh | pvSearchList | {
"repo_name": "dbsoftcombr/dbsfaces",
"path": "src/main/java/br/com/dbsoft/ui/bean/crud/DBSCrudOldBean.java",
"license": "mit",
"size": 120397
} | [
"br.com.dbsoft.error.DBSIOException"
] | import br.com.dbsoft.error.DBSIOException; | import br.com.dbsoft.error.*; | [
"br.com.dbsoft"
] | br.com.dbsoft; | 1,635,576 |
@Test
public void successZoom7() {
Vector2[] vertices = this.load(EarClippingTest.class.getResourceAsStream("/org/dyn4j/data/zoom7.dat"));
// decompose the poly
List<? extends Convex> result = this.algo.decompose(vertices);
// the result should have n - 2 triangles shapes
TestCase.assertTrue(result.size() <= vertices.length - 2);
}
| void function() { Vector2[] vertices = this.load(EarClippingTest.class.getResourceAsStream(STR)); List<? extends Convex> result = this.algo.decompose(vertices); TestCase.assertTrue(result.size() <= vertices.length - 2); } | /**
* Tests the implementation against the zoom7 data file.
* @since 3.1.9
*/ | Tests the implementation against the zoom7 data file | successZoom7 | {
"repo_name": "dmitrykolesnikovich/dyn4j",
"path": "junit/org/dyn4j/geometry/EarClippingTest.java",
"license": "bsd-3-clause",
"size": 21225
} | [
"java.util.List",
"junit.framework.TestCase"
] | import java.util.List; import junit.framework.TestCase; | import java.util.*; import junit.framework.*; | [
"java.util",
"junit.framework"
] | java.util; junit.framework; | 2,896,654 |
public TypeElement getEnclosingClass(); | TypeElement function(); | /**
* Returns the innermost type element containing the position of this scope
*/ | Returns the innermost type element containing the position of this scope | getEnclosingClass | {
"repo_name": "karianna/jdk8_tl",
"path": "langtools/src/share/classes/com/sun/source/tree/Scope.java",
"license": "gpl-2.0",
"size": 2780
} | [
"javax.lang.model.element.TypeElement"
] | import javax.lang.model.element.TypeElement; | import javax.lang.model.element.*; | [
"javax.lang"
] | javax.lang; | 1,174,157 |
public static void SerializeFloat32(ByteBuffer block, int offset, double value) {
SerializeFloat32(block, offset, value, IS_LITTLE_ENDIAN);
} | static void function(ByteBuffer block, int offset, double value) { SerializeFloat32(block, offset, value, IS_LITTLE_ENDIAN); } | /**
* SerializeFloat32( block, offset, value, isLittleEndian )
*
* @param block
* the data block
* @param offset
* the data block offset
* @param value
* the number value
*/ | SerializeFloat32( block, offset, value, isLittleEndian ) | SerializeFloat32 | {
"repo_name": "jugglinmike/es6draft",
"path": "src/main/java/com/github/anba/es6draft/runtime/objects/simd/SIMDType.java",
"license": "mit",
"size": 24396
} | [
"java.nio.ByteBuffer"
] | import java.nio.ByteBuffer; | import java.nio.*; | [
"java.nio"
] | java.nio; | 222,585 |
public Future<Path> createTmpFile(String name, DistributedCacheEntry entry, JobID jobID, ExecutionAttemptID executionId) throws Exception {
synchronized (lock) {
Map<String, Future<Path>> jobEntries = entries.computeIfAbsent(jobID, k -> new HashMap<>());
// register reference holder
final Set<ExecutionAttemptID> refHolders = jobRefHolders.computeIfAbsent(jobID, id -> new HashSet<>());
refHolders.add(executionId);
Future<Path> fileEntry = jobEntries.get(name);
if (fileEntry != null) {
// file is already in the cache. return a future that
// immediately returns the file
return fileEntry;
} else {
// need to copy the file
// create the target path
File tempDirToUse = new File(storageDirectories[nextDirectory++], jobID.toString());
if (nextDirectory >= storageDirectories.length) {
nextDirectory = 0;
}
// kick off the copying
Callable<Path> cp;
if (entry.blobKey != null) {
cp = new CopyFromBlobProcess(entry, jobID, blobService, new Path(tempDirToUse.getAbsolutePath()));
} else {
cp = new CopyFromDFSProcess(entry, new Path(tempDirToUse.getAbsolutePath()));
}
FutureTask<Path> copyTask = new FutureTask<>(cp);
executorService.submit(copyTask);
// store our entry
jobEntries.put(name, copyTask);
return copyTask;
}
}
} | Future<Path> function(String name, DistributedCacheEntry entry, JobID jobID, ExecutionAttemptID executionId) throws Exception { synchronized (lock) { Map<String, Future<Path>> jobEntries = entries.computeIfAbsent(jobID, k -> new HashMap<>()); final Set<ExecutionAttemptID> refHolders = jobRefHolders.computeIfAbsent(jobID, id -> new HashSet<>()); refHolders.add(executionId); Future<Path> fileEntry = jobEntries.get(name); if (fileEntry != null) { return fileEntry; } else { File tempDirToUse = new File(storageDirectories[nextDirectory++], jobID.toString()); if (nextDirectory >= storageDirectories.length) { nextDirectory = 0; } Callable<Path> cp; if (entry.blobKey != null) { cp = new CopyFromBlobProcess(entry, jobID, blobService, new Path(tempDirToUse.getAbsolutePath())); } else { cp = new CopyFromDFSProcess(entry, new Path(tempDirToUse.getAbsolutePath())); } FutureTask<Path> copyTask = new FutureTask<>(cp); executorService.submit(copyTask); jobEntries.put(name, copyTask); return copyTask; } } } | /**
* If the file doesn't exists locally, retrieve the file from the blob-service.
*
* @param entry The cache entry descriptor (path, executable flag)
* @param jobID The ID of the job for which the file is copied.
* @return The handle to the task that copies the file.
*/ | If the file doesn't exists locally, retrieve the file from the blob-service | createTmpFile | {
"repo_name": "ueshin/apache-flink",
"path": "flink-runtime/src/main/java/org/apache/flink/runtime/filecache/FileCache.java",
"license": "apache-2.0",
"size": 11259
} | [
"java.io.File",
"java.util.HashMap",
"java.util.HashSet",
"java.util.Map",
"java.util.Set",
"java.util.concurrent.Callable",
"java.util.concurrent.Future",
"java.util.concurrent.FutureTask",
"org.apache.flink.api.common.JobID",
"org.apache.flink.api.common.cache.DistributedCache",
"org.apache.flink.core.fs.Path",
"org.apache.flink.runtime.executiongraph.ExecutionAttemptID"
] | import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import org.apache.flink.api.common.JobID; import org.apache.flink.api.common.cache.DistributedCache; import org.apache.flink.core.fs.Path; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; | import java.io.*; import java.util.*; import java.util.concurrent.*; import org.apache.flink.api.common.*; import org.apache.flink.api.common.cache.*; import org.apache.flink.core.fs.*; import org.apache.flink.runtime.executiongraph.*; | [
"java.io",
"java.util",
"org.apache.flink"
] | java.io; java.util; org.apache.flink; | 427,397 |
public void setSubtitles(List subtitles) {
if (subtitles == null) {
throw new NullPointerException("Null 'subtitles' argument.");
}
this.subtitles = subtitles;
fireChartChanged();
} | void function(List subtitles) { if (subtitles == null) { throw new NullPointerException(STR); } this.subtitles = subtitles; fireChartChanged(); } | /**
* Sets the title list for the chart (completely replaces any existing
* titles).
*
* @param subtitles the new list of subtitles (<code>null</code> not
* permitted).
*
* @see #getSubtitles()
*/ | Sets the title list for the chart (completely replaces any existing titles) | setSubtitles | {
"repo_name": "simeshev/parabuild-ci",
"path": "3rdparty/jfreechart-1.0.5/source/org/jfree/chart/JFreeChart.java",
"license": "lgpl-3.0",
"size": 64355
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,510,123 |
public List<Integer> convert (List<int[]> list){
List<Integer> result = new ArrayList<Integer>();
for (int[] a : list) {
for (int i : a) {
result.add(i);
}
}
return result;
} | List<Integer> function (List<int[]> list){ List<Integer> result = new ArrayList<Integer>(); for (int[] a : list) { for (int i : a) { result.add(i); } } return result; } | /**
* Method convert List<int[]> to List<Integer>.
* @param list
* @return
*/ | Method convert List to List | convert | {
"repo_name": "revdaalex/learn_java",
"path": "chapter5/arrayConversion/src/main/java/ru/revdaalex/arrayConversion/ConvertList.java",
"license": "apache-2.0",
"size": 2029
} | [
"java.util.ArrayList",
"java.util.List"
] | import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,168,214 |
public String[] getText() {
if (!textSet) {
throw new IllegalStateException(PropertyUtil.getString("PNGEncodeParam20"));
}
return text;
} | String[] function() { if (!textSet) { throw new IllegalStateException(PropertyUtil.getString(STR)); } return text; } | /**
* Returns the text strings to be stored in uncompressed form with this
* image as an array of <code>String</code>s.
*
* <p> If the text strings have not previously been set, or have been
* unset, an <code>IllegalStateException</code> will be thrown.
*
* @throws IllegalStateException if the text strings are not set.
*/ | Returns the text strings to be stored in uncompressed form with this image as an array of <code>String</code>s. If the text strings have not previously been set, or have been unset, an <code>IllegalStateException</code> will be thrown | getText | {
"repo_name": "sflyphotobooks/crp-batik",
"path": "sources/org/apache/batik/ext/awt/image/codec/png/PNGEncodeParam.java",
"license": "apache-2.0",
"size": 48179
} | [
"org.apache.batik.ext.awt.image.codec.util.PropertyUtil"
] | import org.apache.batik.ext.awt.image.codec.util.PropertyUtil; | import org.apache.batik.ext.awt.image.codec.util.*; | [
"org.apache.batik"
] | org.apache.batik; | 2,495,562 |
private ArchiveStoreItem addStoreElement(ArchiveStoreContext ctx, FreenetURI key, String name, Bucket temp, MutableBoolean gotElement, String callbackName, ArchiveExtractCallback callback, ObjectContainer container, ClientContext context) throws ArchiveFailureException {
RealArchiveStoreItem element = new RealArchiveStoreItem(ctx, key, name, temp);
if(logMINOR) Logger.minor(this, "Adding store element: "+element+" ( "+key+ ' ' +name+" size "+element.spaceUsed()+" )");
ArchiveStoreItem oldItem;
// Let it throw, if it does something is drastically wrong
Bucket matchBucket = null;
if((!gotElement.value) && name.equals(callbackName)) {
matchBucket = element.getReaderBucket();
}
synchronized (this) {
oldItem = storedData.get(element.key);
storedData.push(element.key, element);
cachedData += element.spaceUsed();
if(oldItem != null) {
cachedData -= oldItem.spaceUsed();
if(logMINOR) Logger.minor(this, "Dropping old store element from archive cache: "+oldItem);
oldItem.close();
}
}
if(matchBucket != null) {
callback.gotBucket(matchBucket, container, context);
gotElement.value = true;
}
return element;
} | ArchiveStoreItem function(ArchiveStoreContext ctx, FreenetURI key, String name, Bucket temp, MutableBoolean gotElement, String callbackName, ArchiveExtractCallback callback, ObjectContainer container, ClientContext context) throws ArchiveFailureException { RealArchiveStoreItem element = new RealArchiveStoreItem(ctx, key, name, temp); if(logMINOR) Logger.minor(this, STR+element+STR+key+ ' ' +name+STR+element.spaceUsed()+STR); ArchiveStoreItem oldItem; Bucket matchBucket = null; if((!gotElement.value) && name.equals(callbackName)) { matchBucket = element.getReaderBucket(); } synchronized (this) { oldItem = storedData.get(element.key); storedData.push(element.key, element); cachedData += element.spaceUsed(); if(oldItem != null) { cachedData -= oldItem.spaceUsed(); if(logMINOR) Logger.minor(this, STR+oldItem); oldItem.close(); } } if(matchBucket != null) { callback.gotBucket(matchBucket, container, context); gotElement.value = true; } return element; } | /**
* Add a store element.
* @param callbackName If set, the name of the file for which we must call the callback if this file happens to
* match.
* @param gotElement Flag indicating whether we've already found the file for the callback. If so we must not call
* it again.
* @param callback Callback to be called if we do find it. We must getReaderBucket() before adding the data to the
* LRU, otherwise it may be deleted before it reaches the client.
* @throws ArchiveFailureException If a failure occurred resulting in the data not being readable. Only happens if
* callback != null.
*/ | Add a store element | addStoreElement | {
"repo_name": "wnoisephx/fred-official",
"path": "src/freenet/client/ArchiveManager.java",
"license": "gpl-2.0",
"size": 28387
} | [
"com.db4o.ObjectContainer"
] | import com.db4o.ObjectContainer; | import com.db4o.*; | [
"com.db4o"
] | com.db4o; | 1,986,414 |
@Override
public void setActiveEditor(IEditorPart part) {
super.setActiveEditor(part);
activeEditorPart = part;
// Switch to the new selection provider.
//
if (selectionProvider != null) {
selectionProvider.removeSelectionChangedListener(this);
}
if (part == null) {
selectionProvider = null;
}
else {
selectionProvider = part.getSite().getSelectionProvider();
selectionProvider.addSelectionChangedListener(this);
// Fake a selection changed event to update the menus.
//
if (selectionProvider.getSelection() != null) {
selectionChanged(new SelectionChangedEvent(selectionProvider, selectionProvider.getSelection()));
}
}
}
| void function(IEditorPart part) { super.setActiveEditor(part); activeEditorPart = part; if (selectionProvider != null) { selectionProvider.removeSelectionChangedListener(this); } if (part == null) { selectionProvider = null; } else { selectionProvider = part.getSite().getSelectionProvider(); selectionProvider.addSelectionChangedListener(this); if (selectionProvider.getSelection() != null) { selectionChanged(new SelectionChangedEvent(selectionProvider, selectionProvider.getSelection())); } } } | /**
* When the active editor changes, this remembers the change and registers with it as a selection provider.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | When the active editor changes, this remembers the change and registers with it as a selection provider. | setActiveEditor | {
"repo_name": "uppaal-emf/uppaal",
"path": "metamodel/org.muml.uppaal.editor/src/org/muml/uppaal/statements/presentation/StatementsActionBarContributor.java",
"license": "epl-1.0",
"size": 14459
} | [
"org.eclipse.jface.viewers.SelectionChangedEvent",
"org.eclipse.ui.IEditorPart"
] | import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.ui.IEditorPart; | import org.eclipse.jface.viewers.*; import org.eclipse.ui.*; | [
"org.eclipse.jface",
"org.eclipse.ui"
] | org.eclipse.jface; org.eclipse.ui; | 1,714,889 |
String bbox = "";
ImageWmsLayerDataSource source = (ImageWmsLayerDataSource) layer.getSource();
String name = source.getLayerNames();
if (name.contains(":")) {
name = name.split(":")[1];
}
// only handle layers that are available in our geoserver
if (!source.getUrl().toLowerCase().contains("geoserver.action")) {
return "";
}
RESTLayer restLayer = this.getLayer(workspace, name);
if (restLayer == null) {
throw new Exception("Could not find the RESTLayer for name " + name);
}
RESTBoundingBox restBbox;
Type type = restLayer.getType();
if (type.equals(Type.VECTOR)) {
RESTFeatureType restFeatureType = this.getFeatureType(restLayer);
if (restFeatureType == null) {
throw new Exception("Could not find the RESTFeatureType for layer " + name);
}
restBbox = restFeatureType.getNativeBoundingBox();
} else if (type.equals(Type.RASTER)){
RESTCoverage restCoverage = this.getCoverage(restLayer);
if (restCoverage == null) {
throw new Exception("Could not find the RESTCoverage for layer " + name);
}
restBbox = restCoverage.getNativeBoundingBox();
} else {
throw new Exception("Could not determine the layertype for layer " + name);
}
if (restBbox.getCRS() != "EPSG:3857") {
CoordinateReferenceSystem sourceCRS;
// for geographic projections, we need to switch axes
if (restBbox.getCRS().equalsIgnoreCase("EPSG:4326")) {
sourceCRS = CRS.decode(restBbox.getCRS(), true);
} else {
sourceCRS = CRS.decode(restBbox.getCRS());
}
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:3857");
MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
Coordinate ll = new Coordinate(restBbox.getMinX(), restBbox.getMinY());
Coordinate ur = new Coordinate(restBbox.getMaxX(), restBbox.getMaxY());
Coordinate transformedLl = JTS.transform(ll, null, transform);
Coordinate transformedUr = JTS.transform(ur, null, transform);
bbox =
String.valueOf(transformedLl.x) + ", " +
String.valueOf(transformedLl.y) + ", " +
String.valueOf(transformedUr.x) + ", " +
String.valueOf(transformedUr.y);
} else {
bbox =
String.valueOf(restBbox.getMinX()) + ", " +
String.valueOf(restBbox.getMinY()) + ", " +
String.valueOf(restBbox.getMaxX()) + ", " +
String.valueOf(restBbox.getMaxY());
}
return bbox;
} | String bbox = STR:STR:STRgeoserver.actionSTRSTRCould not find the RESTLayer for name STRCould not find the RESTFeatureType for layer STRCould not find the RESTCoverage for layer STRCould not determine the layertype for layer STREPSG:3857STREPSG:4326STREPSG:3857STR, STR, STR, STR, STR, STR, " + String.valueOf(restBbox.getMaxY()); } return bbox; } | /**
* Get the data extent for the given layer
*
* @param layer
* @return
* @throws Exception
*/ | Get the data extent for the given layer | getLayerExtent | {
"repo_name": "buehner/momo3-backend",
"path": "src/main/java/de/terrestris/momo/dao/GeoserverReaderDao.java",
"license": "gpl-3.0",
"size": 5549
} | [
"it.geosolutions.geoserver.rest.decoder.RESTCoverage",
"it.geosolutions.geoserver.rest.decoder.RESTFeatureType",
"it.geosolutions.geoserver.rest.decoder.RESTLayer"
] | import it.geosolutions.geoserver.rest.decoder.RESTCoverage; import it.geosolutions.geoserver.rest.decoder.RESTFeatureType; import it.geosolutions.geoserver.rest.decoder.RESTLayer; | import it.geosolutions.geoserver.rest.decoder.*; | [
"it.geosolutions.geoserver"
] | it.geosolutions.geoserver; | 2,322,053 |
static void register(final Object value) {
synchronized (HashCodeBuilder.class) {
if (getRegistry() == null) {
REGISTRY.set(new HashSet<IDKey>());
}
}
getRegistry().add(new IDKey(value));
} | static void register(final Object value) { synchronized (HashCodeBuilder.class) { if (getRegistry() == null) { REGISTRY.set(new HashSet<IDKey>()); } } getRegistry().add(new IDKey(value)); } | /**
* <p>
* Registers the given object. Used by the reflection methods to avoid infinite loops.
* </p>
*
* @param value
* The object to register.
*/ | Registers the given object. Used by the reflection methods to avoid infinite loops. | register | {
"repo_name": "nhchanh/apache-commons-lang3-3.2",
"path": "src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java",
"license": "apache-2.0",
"size": 31923
} | [
"java.util.HashSet"
] | import java.util.HashSet; | import java.util.*; | [
"java.util"
] | java.util; | 1,177,748 |
protected void checkPermission(final IQuery query)
throws PermissionException {
final DefinedPermission[][] permSets = query.getNeededPermissions();
if (!DefinedPermission.checkPermission(authManager, permSets)) {
exceptionRegistry.throwRuntimeException(PermissionException.class,
1000, DefinedPermission.toString(permSets));
}
} | void function(final IQuery query) throws PermissionException { final DefinedPermission[][] permSets = query.getNeededPermissions(); if (!DefinedPermission.checkPermission(authManager, permSets)) { exceptionRegistry.throwRuntimeException(PermissionException.class, 1000, DefinedPermission.toString(permSets)); } } | /**
* Checks if the current user has the permission to process the specified
* {@code query}.
*
* @param query
* the query to be checked
*
* @throws PermissionException
* if the permission is not available
*/ | Checks if the current user has the permission to process the specified query | checkPermission | {
"repo_name": "pmeisen/dis-timeintervaldataanalyzer",
"path": "src/net/meisen/dissertation/impl/parser/query/QueryFactory.java",
"license": "bsd-3-clause",
"size": 7128
} | [
"net.meisen.dissertation.exceptions.PermissionException",
"net.meisen.dissertation.model.auth.permissions.DefinedPermission",
"net.meisen.dissertation.model.parser.query.IQuery"
] | import net.meisen.dissertation.exceptions.PermissionException; import net.meisen.dissertation.model.auth.permissions.DefinedPermission; import net.meisen.dissertation.model.parser.query.IQuery; | import net.meisen.dissertation.exceptions.*; import net.meisen.dissertation.model.auth.permissions.*; import net.meisen.dissertation.model.parser.query.*; | [
"net.meisen.dissertation"
] | net.meisen.dissertation; | 2,067,379 |
Date value = (Date) getValue();
return value != null ? new LocalDateTime(value).toString(formatter) : "";
} | Date value = (Date) getValue(); return value != null ? new LocalDateTime(value).toString(formatter) : ""; } | /**
* Format the YearMonthDay as String, using the specified format.
*
* @return DateTime formatted string
*/ | Format the YearMonthDay as String, using the specified format | getAsText | {
"repo_name": "brunoquadrotti/menuber",
"path": "src/main/java/br/com/menuber/web/propertyeditors/LocaleDateTimeEditor.java",
"license": "mit",
"size": 2020
} | [
"java.util.Date",
"org.joda.time.LocalDateTime"
] | import java.util.Date; import org.joda.time.LocalDateTime; | import java.util.*; import org.joda.time.*; | [
"java.util",
"org.joda.time"
] | java.util; org.joda.time; | 59,561 |
private final void invalidateNode(Object node, boolean forceRebuild)
{
if (dirtyAll == false)
{
// get item for this node
TreeItem item = nodeToItemMap.get(node);
if (item != null)
{
boolean createDOM = false;
if (forceRebuild)
{
// recreate the item
int level = item.getLevel();
List<TreeItem> children = item.getChildren();
String id = item.getId();
// store the parent of old item
TreeItem parent = item.getParentItem();
// if the old item has a parent, store it's index
int index = parent != null ? parent.getChildren().indexOf(item) : -1;
createDOM = dirtyItemsCreateDOM.contains(item);
dirtyItems.remove(item);
dirtyItemsCreateDOM.remove(item);
item.remove();
item = newTreeItem(parent, node, level, id);
itemContainer.add(item);
item.setChildren(children);
// was the item an root item?
if (parent == null)
{
rootItem = item;
}
else
{
parent.getChildren().set(index, item);
}
}
if (!dirtyItems.contains(item))
dirtyItems.add(item);
if (createDOM && !dirtyItemsCreateDOM.contains(item))
{
dirtyItemsCreateDOM.add(item);
}
}
}
} | final void function(Object node, boolean forceRebuild) { if (dirtyAll == false) { TreeItem item = nodeToItemMap.get(node); if (item != null) { boolean createDOM = false; if (forceRebuild) { int level = item.getLevel(); List<TreeItem> children = item.getChildren(); String id = item.getId(); TreeItem parent = item.getParentItem(); int index = parent != null ? parent.getChildren().indexOf(item) : -1; createDOM = dirtyItemsCreateDOM.contains(item); dirtyItems.remove(item); dirtyItemsCreateDOM.remove(item); item.remove(); item = newTreeItem(parent, node, level, id); itemContainer.add(item); item.setChildren(children); if (parent == null) { rootItem = item; } else { parent.getChildren().set(index, item); } } if (!dirtyItems.contains(item)) dirtyItems.add(item); if (createDOM && !dirtyItemsCreateDOM.contains(item)) { dirtyItemsCreateDOM.add(item); } } } } | /**
* Invalidates single node (without children). On the next render, this node will be updated.
* Node will not be rebuilt, unless forceRebuild is true.
*
* @param node
* The node to invalidate
* @param forceRebuild
*/ | Invalidates single node (without children). On the next render, this node will be updated. Node will not be rebuilt, unless forceRebuild is true | invalidateNode | {
"repo_name": "astubbs/wicket.get-portals2",
"path": "wicket/src/main/java/org/apache/wicket/markup/html/tree/AbstractTree.java",
"license": "apache-2.0",
"size": 38944
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,988,197 |
void putString(StringWrapper complexBody) throws ServiceException; | void putString(StringWrapper complexBody) throws ServiceException; | /**
* Put complex types with string properties
*
* @param complexBody Please put 'goodrequest', '', and null
* @throws ServiceException the exception wrapped in ServiceException if failed.
*/ | Put complex types with string properties | putString | {
"repo_name": "BretJohnson/autorest",
"path": "AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/Primitive.java",
"license": "mit",
"size": 17621
} | [
"com.microsoft.rest.ServiceException"
] | import com.microsoft.rest.ServiceException; | import com.microsoft.rest.*; | [
"com.microsoft.rest"
] | com.microsoft.rest; | 1,167,167 |
public static java.util.Set extractHandlingMovementDetailSet(ims.domain.ILightweightDomainFactory domainFactory, ims.nursing.vo.HandlingMovementDetailVoCollection voCollection)
{
return extractHandlingMovementDetailSet(domainFactory, voCollection, null, new HashMap());
}
| static java.util.Set function(ims.domain.ILightweightDomainFactory domainFactory, ims.nursing.vo.HandlingMovementDetailVoCollection voCollection) { return extractHandlingMovementDetailSet(domainFactory, voCollection, null, new HashMap()); } | /**
* Create the ims.nursing.domain.objects.HandlingMovementDetail set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/ | Create the ims.nursing.domain.objects.HandlingMovementDetail set from the value object collection | extractHandlingMovementDetailSet | {
"repo_name": "open-health-hub/openmaxims-linux",
"path": "openmaxims_workspace/ValueObjects/src/ims/nursing/vo/domain/HandlingMovementDetailVoAssembler.java",
"license": "agpl-3.0",
"size": 22987
} | [
"java.util.HashMap"
] | import java.util.HashMap; | import java.util.*; | [
"java.util"
] | java.util; | 2,339,000 |
public byte getByte() throws StandardException
{
throw dataTypeConversion("byte");
} | byte function() throws StandardException { throw dataTypeConversion("byte"); } | /**
* Gets the value in the data value descriptor as a byte.
* Throws an exception if the data value is not receivable as a byte.
*
* @return The data value as a byte.
*
* @exception StandardException Thrown on error
*/ | Gets the value in the data value descriptor as a byte. Throws an exception if the data value is not receivable as a byte | getByte | {
"repo_name": "lpxz/grail-derby104",
"path": "java/engine/org/apache/derby/iapi/types/DataType.java",
"license": "apache-2.0",
"size": 34458
} | [
"org.apache.derby.iapi.error.StandardException"
] | import org.apache.derby.iapi.error.StandardException; | import org.apache.derby.iapi.error.*; | [
"org.apache.derby"
] | org.apache.derby; | 339,383 |
void checkDeleteHistoricProcessInstance(HistoricProcessInstance instance); | void checkDeleteHistoricProcessInstance(HistoricProcessInstance instance); | /**
* Checks if it is allowed to delete the given historic process instance.
*/ | Checks if it is allowed to delete the given historic process instance | checkDeleteHistoricProcessInstance | {
"repo_name": "Diaskhan/jetbpm",
"path": "camunda-bpm-platform-master/engine/src/main/java/org/camunda/bpm/engine/impl/cfg/CommandChecker.java",
"license": "apache-2.0",
"size": 9500
} | [
"org.camunda.bpm.engine.history.HistoricProcessInstance"
] | import org.camunda.bpm.engine.history.HistoricProcessInstance; | import org.camunda.bpm.engine.history.*; | [
"org.camunda.bpm"
] | org.camunda.bpm; | 983,860 |
@Override
public void onItemSelected(int id) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putInt(AnimationDetailFragment.ARG_ITEM_ID, id);
AnimationDetailFragment fragment = new AnimationDetailFragment();
fragment.setArguments(arguments);
getFragmentManager().beginTransaction()
.replace(R.id.animation_detail_container, fragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this,
AnimationDetailActivity.class);
detailIntent.putExtra(AnimationDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
} | void function(int id) { if (mTwoPane) { Bundle arguments = new Bundle(); arguments.putInt(AnimationDetailFragment.ARG_ITEM_ID, id); AnimationDetailFragment fragment = new AnimationDetailFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .replace(R.id.animation_detail_container, fragment) .commit(); } else { Intent detailIntent = new Intent(this, AnimationDetailActivity.class); detailIntent.putExtra(AnimationDetailFragment.ARG_ITEM_ID, id); startActivity(detailIntent); } } | /**
* Callback method from {@link AnimationListFragment.Callbacks} indicating
* that the item with the given ID was selected.
*/ | Callback method from <code>AnimationListFragment.Callbacks</code> indicating that the item with the given ID was selected | onItemSelected | {
"repo_name": "nguyendinhduc/SampleEasyAnimation",
"path": "Animation_demo/src/com/easyandroidanimations/demo/AnimationListActivity.java",
"license": "apache-2.0",
"size": 2812
} | [
"android.content.Intent",
"android.os.Bundle"
] | import android.content.Intent; import android.os.Bundle; | import android.content.*; import android.os.*; | [
"android.content",
"android.os"
] | android.content; android.os; | 519,907 |
void shutdown(String reason) {
LOG.info("Shutting down");
if (isShutdown) {
return;
}
LOG.info("Shutdown called",
new Exception("shutdown Leader! reason: " + reason));
if (cnxAcceptor != null) {
cnxAcceptor.halt();
}
// NIO should not accept conenctions
self.setZooKeeperServer(null);
self.adminServer.setZooKeeperServer(null);
try {
ss.close();
} catch (IOException e) {
LOG.warn("Ignoring unexpected exception during close",e);
}
self.closeAllConnections();
// shutdown the previous zk
if (zk != null) {
zk.shutdown();
}
synchronized (learners) {
for (Iterator<LearnerHandler> it = learners.iterator(); it
.hasNext();) {
LearnerHandler f = it.next();
it.remove();
f.shutdown();
}
}
isShutdown = true;
}
| void shutdown(String reason) { LOG.info(STR); if (isShutdown) { return; } LOG.info(STR, new Exception(STR + reason)); if (cnxAcceptor != null) { cnxAcceptor.halt(); } self.setZooKeeperServer(null); self.adminServer.setZooKeeperServer(null); try { ss.close(); } catch (IOException e) { LOG.warn(STR,e); } self.closeAllConnections(); if (zk != null) { zk.shutdown(); } synchronized (learners) { for (Iterator<LearnerHandler> it = learners.iterator(); it .hasNext();) { LearnerHandler f = it.next(); it.remove(); f.shutdown(); } } isShutdown = true; } | /**
* Close down all the LearnerHandlers
*/ | Close down all the LearnerHandlers | shutdown | {
"repo_name": "pedrohrf/ZookeeperQuasarFibers",
"path": "src/java/main/org/apache/zookeeper/server/quorum/Leader.java",
"license": "apache-2.0",
"size": 52879
} | [
"java.io.IOException",
"java.util.Iterator"
] | import java.io.IOException; import java.util.Iterator; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 1,158,165 |
public static Object convertNumberToWrapper(Number num, Class<?> wrapper) {
//XXX Paul: Using valueOf will reduce object creation
if (wrapper.equals(String.class)) {
return num.toString();
} else if (wrapper.equals(Boolean.class)) {
return Boolean.valueOf(num.intValue() == 1);
} else if (wrapper.equals(Double.class)) {
return Double.valueOf(num.doubleValue());
} else if (wrapper.equals(Long.class)) {
return Long.valueOf(num.longValue());
} else if (wrapper.equals(Float.class)) {
return Float.valueOf(num.floatValue());
} else if (wrapper.equals(Integer.class)) {
return Integer.valueOf(num.intValue());
} else if (wrapper.equals(Short.class)) {
return Short.valueOf(num.shortValue());
} else if (wrapper.equals(Byte.class)) {
return Byte.valueOf(num.byteValue());
}
throw new ConversionException(String.format("Unable to convert number to: %s", wrapper));
}
| static Object function(Number num, Class<?> wrapper) { if (wrapper.equals(String.class)) { return num.toString(); } else if (wrapper.equals(Boolean.class)) { return Boolean.valueOf(num.intValue() == 1); } else if (wrapper.equals(Double.class)) { return Double.valueOf(num.doubleValue()); } else if (wrapper.equals(Long.class)) { return Long.valueOf(num.longValue()); } else if (wrapper.equals(Float.class)) { return Float.valueOf(num.floatValue()); } else if (wrapper.equals(Integer.class)) { return Integer.valueOf(num.intValue()); } else if (wrapper.equals(Short.class)) { return Short.valueOf(num.shortValue()); } else if (wrapper.equals(Byte.class)) { return Byte.valueOf(num.byteValue()); } throw new ConversionException(String.format(STR, wrapper)); } | /**
* Convert number to primitive wrapper like Boolean or Float
* @param num Number to conver
* @param wrapper Primitive wrapper type
* @return Converted object
*/ | Convert number to primitive wrapper like Boolean or Float | convertNumberToWrapper | {
"repo_name": "cwpenhale/red5-mobileconsole",
"path": "red5_server/src/main/java/org/red5/server/util/ConversionUtils.java",
"license": "apache-2.0",
"size": 15903
} | [
"org.apache.commons.beanutils.ConversionException"
] | import org.apache.commons.beanutils.ConversionException; | import org.apache.commons.beanutils.*; | [
"org.apache.commons"
] | org.apache.commons; | 1,790,737 |
private void runOneTask() throws Exception {
if (chunk.length != 1)
throw new AssertionError();
final IBindingSet bindingSet = chunk[0];
// constrain the predicate to the given bindings.
IPredicate<E> asBound = predicate.asBound(bindingSet);
if (asBound == null) {
return;
}
if (partitionId != -1) {
asBound = asBound.setPartitionId(partitionId);
}
new JoinTask.AccessPathTask(asBound, Arrays.asList(chunk))
.call();
}
| void function() throws Exception { if (chunk.length != 1) throw new AssertionError(); final IBindingSet bindingSet = chunk[0]; IPredicate<E> asBound = predicate.asBound(bindingSet); if (asBound == null) { return; } if (partitionId != -1) { asBound = asBound.setPartitionId(partitionId); } new JoinTask.AccessPathTask(asBound, Arrays.asList(chunk)) .call(); } | /**
* There is exactly one {@link IBindingSet} in the chunk, so run
* exactly one {@link AccessPathTask}.
*
* @throws Exception
*/ | There is exactly one <code>IBindingSet</code> in the chunk, so run exactly one <code>AccessPathTask</code> | runOneTask | {
"repo_name": "rac021/blazegraph_1_5_3_cluster_2_nodes",
"path": "bigdata/src/java/com/bigdata/bop/join/PipelineJoin.java",
"license": "gpl-2.0",
"size": 74690
} | [
"com.bigdata.bop.IBindingSet",
"com.bigdata.bop.IPredicate",
"java.util.Arrays"
] | import com.bigdata.bop.IBindingSet; import com.bigdata.bop.IPredicate; import java.util.Arrays; | import com.bigdata.bop.*; import java.util.*; | [
"com.bigdata.bop",
"java.util"
] | com.bigdata.bop; java.util; | 568,919 |
Configuration conf = new Configuration();
MiniJournalCluster cluster = new MiniJournalCluster.Builder(conf).build();
cluster.waitActive();
QuorumJournalManager qjm = null;
long ret;
try {
qjm = createInjectableQJM(cluster);
qjm.format(FAKE_NSINFO, false);
doWorkload(cluster, qjm);
SortedSet<Integer> ipcCounts = Sets.newTreeSet();
for (AsyncLogger l : qjm.getLoggerSetForTests().getLoggersForTests()) {
InvocationCountingChannel ch = (InvocationCountingChannel)l;
ch.waitForAllPendingCalls();
ipcCounts.add(ch.getRpcCount());
}
// All of the loggers should have sent the same number of RPCs, since there
// were no failures.
assertEquals(1, ipcCounts.size());
ret = ipcCounts.first();
LOG.info("Max IPC count = " + ret);
} finally {
IOUtils.closeStream(qjm);
cluster.shutdown();
}
return ret;
}
@Rule
public ExpectedException expectedException = ExpectedException.none(); | Configuration conf = new Configuration(); MiniJournalCluster cluster = new MiniJournalCluster.Builder(conf).build(); cluster.waitActive(); QuorumJournalManager qjm = null; long ret; try { qjm = createInjectableQJM(cluster); qjm.format(FAKE_NSINFO, false); doWorkload(cluster, qjm); SortedSet<Integer> ipcCounts = Sets.newTreeSet(); for (AsyncLogger l : qjm.getLoggerSetForTests().getLoggersForTests()) { InvocationCountingChannel ch = (InvocationCountingChannel)l; ch.waitForAllPendingCalls(); ipcCounts.add(ch.getRpcCount()); } assertEquals(1, ipcCounts.size()); ret = ipcCounts.first(); LOG.info(STR + ret); } finally { IOUtils.closeStream(qjm); cluster.shutdown(); } return ret; } public ExpectedException expectedException = ExpectedException.none(); | /**
* Run through the creation of a log without any faults injected,
* and count how many RPCs are made to each node. This sets the
* bounds for the other test cases, so they can exhaustively explore
* the space of potential failures.
*/ | Run through the creation of a log without any faults injected, and count how many RPCs are made to each node. This sets the bounds for the other test cases, so they can exhaustively explore the space of potential failures | determineMaxIpcNumber | {
"repo_name": "lukmajercak/hadoop",
"path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/qjournal/client/TestQJMWithFaults.java",
"license": "apache-2.0",
"size": 18986
} | [
"com.google.common.collect.Sets",
"java.util.SortedSet",
"org.apache.hadoop.conf.Configuration",
"org.apache.hadoop.hdfs.qjournal.MiniJournalCluster",
"org.apache.hadoop.io.IOUtils",
"org.junit.Assert",
"org.junit.rules.ExpectedException"
] | import com.google.common.collect.Sets; import java.util.SortedSet; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.qjournal.MiniJournalCluster; import org.apache.hadoop.io.IOUtils; import org.junit.Assert; import org.junit.rules.ExpectedException; | import com.google.common.collect.*; import java.util.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.hdfs.qjournal.*; import org.apache.hadoop.io.*; import org.junit.*; import org.junit.rules.*; | [
"com.google.common",
"java.util",
"org.apache.hadoop",
"org.junit",
"org.junit.rules"
] | com.google.common; java.util; org.apache.hadoop; org.junit; org.junit.rules; | 2,562,920 |
@Override
public void enter()
{
super.enter();
// In Scene TimeLine.
Timeline inTimeline = Timeline.createSequence()
.beginSequence()
.push(Tween.to(getInSceneRoot(), GroupAccessor.POSITION_XY, 0).target(getInScene().getWidth(), 0).ease(getEaseEquation()))
.push(Tween.to(getInSceneRoot(), GroupAccessor.POSITION_XY, getDurationMillis()).target(0, 0).ease(getEaseEquation()))
.end()
.start();
// In Scene TimeLine Action.
TimelineAction inTimelineAction = TimelineAction.$(inTimeline);
getInSceneRoot().addAction(inTimelineAction);
// Out Scene TimeLine.
Timeline outTimeline = Timeline.createSequence()
.beginSequence()
.push(Tween.to(getOutSceneRoot(), GroupAccessor.POSITION_XY, 0).target(0, 0).ease(getEaseEquation()))
.push(Tween.to(getOutSceneRoot(), GroupAccessor.POSITION_XY, getDurationMillis()).target(-getOutScene().getWidth(), 0).ease(getEaseEquation()))
.setCallbackTriggers(TweenCallback.COMPLETE)
.setCallback(this)
.end()
.start();
// Out Scene TimeLine Action.
TimelineAction outTimelineAction = TimelineAction.$(outTimeline);
getOutSceneRoot().addAction(outTimelineAction);
}
| void function() { super.enter(); Timeline inTimeline = Timeline.createSequence() .beginSequence() .push(Tween.to(getInSceneRoot(), GroupAccessor.POSITION_XY, 0).target(getInScene().getWidth(), 0).ease(getEaseEquation())) .push(Tween.to(getInSceneRoot(), GroupAccessor.POSITION_XY, getDurationMillis()).target(0, 0).ease(getEaseEquation())) .end() .start(); TimelineAction inTimelineAction = TimelineAction.$(inTimeline); getInSceneRoot().addAction(inTimelineAction); Timeline outTimeline = Timeline.createSequence() .beginSequence() .push(Tween.to(getOutSceneRoot(), GroupAccessor.POSITION_XY, 0).target(0, 0).ease(getEaseEquation())) .push(Tween.to(getOutSceneRoot(), GroupAccessor.POSITION_XY, getDurationMillis()).target(-getOutScene().getWidth(), 0).ease(getEaseEquation())) .setCallbackTriggers(TweenCallback.COMPLETE) .setCallback(this) .end() .start(); TimelineAction outTimelineAction = TimelineAction.$(outTimeline); getOutSceneRoot().addAction(outTimelineAction); } | /**
* On entry build easing TimeLines.
*
*/ | On entry build easing TimeLines | enter | {
"repo_name": "exilef/libgx-wip",
"path": "netthreads-libgdx/src/main/java/com/netthreads/libgdx/scene/transition/MoveInRTransitionScene.java",
"license": "apache-2.0",
"size": 3825
} | [
"com.netthreads.libgdx.action.TimelineAction",
"com.netthreads.libgdx.tween.GroupAccessor"
] | import com.netthreads.libgdx.action.TimelineAction; import com.netthreads.libgdx.tween.GroupAccessor; | import com.netthreads.libgdx.action.*; import com.netthreads.libgdx.tween.*; | [
"com.netthreads.libgdx"
] | com.netthreads.libgdx; | 771,780 |
EReference getDocumentRoot_Artifact(); | EReference getDocumentRoot_Artifact(); | /**
* Returns the meta object for the containment reference '{@link org.eclipse.bpmn2.DocumentRoot#getArtifact <em>Artifact</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Artifact</em>'.
* @see org.eclipse.bpmn2.DocumentRoot#getArtifact()
* @see #getDocumentRoot()
* @generated
*/ | Returns the meta object for the containment reference '<code>org.eclipse.bpmn2.DocumentRoot#getArtifact Artifact</code>'. | getDocumentRoot_Artifact | {
"repo_name": "Rikkola/kie-wb-common",
"path": "kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-emf/src/main/java/org/eclipse/bpmn2/Bpmn2Package.java",
"license": "apache-2.0",
"size": 929298
} | [
"org.eclipse.emf.ecore.EReference"
] | import org.eclipse.emf.ecore.EReference; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,123,931 |
private static GemFireTransaction startCommonTransaction(ContextManager cm,
GemFireTransaction parentTran, GfxdLockSet compatibilitySpace,
String contextId, String transName, boolean skipLocks, boolean abortAll,
long connectionID, boolean isTxExecute) throws StandardException {
final boolean logTran = GemFireXDUtils.TraceTran
|| GemFireXDUtils.TraceQuery || SanityManager.isFineEnabled
|| GemFireXDUtils.TraceNCJ;
if (logTran) {
SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_TRAN,
"GemFireTransaction: starting a new TX");
}
if (SanityManager.DEBUG) {
if (logTran) {
final ContextService contextFactory = ContextService.getFactory();
SanityManager.ASSERT(cm == contextFactory.getCurrentContextManager());
}
}
final GemFireTransaction tran = new GemFireTransaction(transName,
parentTran, skipLocks, compatibilitySpace, connectionID, isTxExecute);
pushTransactionContext(cm, contextId, tran, abortAll);
tran.setActiveState();
if (logTran) {
SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_TRAN,
"GemFireTransaction: created new TX " + tran.toString());
}
return tran;
} | static GemFireTransaction function(ContextManager cm, GemFireTransaction parentTran, GfxdLockSet compatibilitySpace, String contextId, String transName, boolean skipLocks, boolean abortAll, long connectionID, boolean isTxExecute) throws StandardException { final boolean logTran = GemFireXDUtils.TraceTran GemFireXDUtils.TraceQuery SanityManager.isFineEnabled GemFireXDUtils.TraceNCJ; if (logTran) { SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_TRAN, STR); } if (SanityManager.DEBUG) { if (logTran) { final ContextService contextFactory = ContextService.getFactory(); SanityManager.ASSERT(cm == contextFactory.getCurrentContextManager()); } } final GemFireTransaction tran = new GemFireTransaction(transName, parentTran, skipLocks, compatibilitySpace, connectionID, isTxExecute); pushTransactionContext(cm, contextId, tran, abortAll); tran.setActiveState(); if (logTran) { SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_TRAN, STR + tran.toString()); } return tran; } | /**
* Common work done to create local transactions.
*
* @param cm
* the current context manager to associate the Transaction with
* @param parentTran
* parent Transaction, if any, of the new Transaction
* @param compatibilitySpace
* if null, use the transaction being created, else if non-null use
* this compatibilitySpace.
* @param contextId
* the context ID to use for the new Transaction
* @param skipLocks
* set to true to skip acquiring any locks in the new Transaction
* @param abortAll
* if true, then any error will abort the whole transaction.
* Otherwise, let Context.cleanupOnError decide what to do
* @param connectionID
* The id of EmbedConnection with which the transaction is associated
* with.
*
* @exception StandardException
* Standard exception policy.
*/ | Common work done to create local transactions | startCommonTransaction | {
"repo_name": "papicella/snappy-store",
"path": "gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/engine/access/GemFireTransaction.java",
"license": "apache-2.0",
"size": 148971
} | [
"com.pivotal.gemfirexd.internal.engine.GfxdConstants",
"com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils",
"com.pivotal.gemfirexd.internal.engine.locks.GfxdLockSet",
"com.pivotal.gemfirexd.internal.iapi.error.StandardException",
"com.pivotal.gemfirexd.internal.iapi.services.context.ContextManager",
"com.pivotal.gemfirexd.internal.iapi.services.context.ContextService",
"com.pivotal.gemfirexd.internal.shared.common.sanity.SanityManager"
] | import com.pivotal.gemfirexd.internal.engine.GfxdConstants; import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils; import com.pivotal.gemfirexd.internal.engine.locks.GfxdLockSet; import com.pivotal.gemfirexd.internal.iapi.error.StandardException; import com.pivotal.gemfirexd.internal.iapi.services.context.ContextManager; import com.pivotal.gemfirexd.internal.iapi.services.context.ContextService; import com.pivotal.gemfirexd.internal.shared.common.sanity.SanityManager; | import com.pivotal.gemfirexd.internal.engine.*; import com.pivotal.gemfirexd.internal.engine.distributed.utils.*; import com.pivotal.gemfirexd.internal.engine.locks.*; import com.pivotal.gemfirexd.internal.iapi.error.*; import com.pivotal.gemfirexd.internal.iapi.services.context.*; import com.pivotal.gemfirexd.internal.shared.common.sanity.*; | [
"com.pivotal.gemfirexd"
] | com.pivotal.gemfirexd; | 472,049 |
Set<WorkspaceDir> getSetWorkspaceDir(Class<? extends WorkspaceDir> workspaceDirClass); | Set<WorkspaceDir> getSetWorkspaceDir(Class<? extends WorkspaceDir> workspaceDirClass); | /**
* Returns the Set of all {@link WorkspaceDir}'s of a given WorkspaceDir
* subclass.
*
* @param workspaceDirClass WorkspaceDir subclass. Can be null to return all
* WorkspaceDir.
* @return See description.
*/ | Returns the Set of all <code>WorkspaceDir</code>'s of a given WorkspaceDir subclass | getSetWorkspaceDir | {
"repo_name": "azyva/dragom-api",
"path": "src/main/java/org/azyva/dragom/execcontext/plugin/WorkspacePlugin.java",
"license": "agpl-3.0",
"size": 12345
} | [
"java.util.Set"
] | import java.util.Set; | import java.util.*; | [
"java.util"
] | java.util; | 2,066,457 |
public void handleStatus(SVNStatus status) throws SVNException {
try {
sendToHandler(status);
} catch (SAXException th) {
getDebugLog().logSevere(SVNLogType.DEFAULT, th);
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.XML_MALFORMED, th.getLocalizedMessage());
SVNErrorManager.error(err, th, SVNLogType.DEFAULT);
}
} | void function(SVNStatus status) throws SVNException { try { sendToHandler(status); } catch (SAXException th) { getDebugLog().logSevere(SVNLogType.DEFAULT, th); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.XML_MALFORMED, th.getLocalizedMessage()); SVNErrorManager.error(err, th, SVNLogType.DEFAULT); } } | /**
* Handles a next <code>status</code> object producing corresponding xml.
*
* @param status
* @throws SVNException
*/ | Handles a next <code>status</code> object producing corresponding xml | handleStatus | {
"repo_name": "shabanovd/exist",
"path": "extensions/svn/src/org/exist/versioning/svn/wc/xml/SVNXMLStatusHandler.java",
"license": "lgpl-2.1",
"size": 10435
} | [
"org.tmatesoft.svn.core.SVNErrorCode",
"org.tmatesoft.svn.core.SVNErrorMessage",
"org.tmatesoft.svn.core.SVNException",
"org.tmatesoft.svn.core.internal.wc.SVNErrorManager",
"org.tmatesoft.svn.core.wc.SVNStatus",
"org.tmatesoft.svn.util.SVNLogType",
"org.xml.sax.SAXException"
] | import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.util.SVNLogType; import org.xml.sax.SAXException; | import org.tmatesoft.svn.core.*; import org.tmatesoft.svn.core.internal.wc.*; import org.tmatesoft.svn.core.wc.*; import org.tmatesoft.svn.util.*; import org.xml.sax.*; | [
"org.tmatesoft.svn",
"org.xml.sax"
] | org.tmatesoft.svn; org.xml.sax; | 1,926,202 |
@Override
public void setCurrency(Currency currency) {
ndf.setCurrency(Currency.getInstance(currency.getCurrencyCode()));
symbols.setCurrency(currency);
} | void function(Currency currency) { ndf.setCurrency(Currency.getInstance(currency.getCurrencyCode())); symbols.setCurrency(currency); } | /**
* Sets the currency used by this decimal format. The min and max fraction
* digits remain the same.
*
* @param currency
* the currency this {@code DecimalFormat} should use.
* @see DecimalFormatSymbols#setCurrency(Currency)
*/ | Sets the currency used by this decimal format. The min and max fraction digits remain the same | setCurrency | {
"repo_name": "rex-xxx/mt6572_x201",
"path": "libcore/luni/src/main/java/java/text/DecimalFormat.java",
"license": "gpl-2.0",
"size": 51654
} | [
"java.util.Currency"
] | import java.util.Currency; | import java.util.*; | [
"java.util"
] | java.util; | 1,045,826 |
public Size size()
{
return mySize;
} | Size function() { return mySize; } | /**
* Returns this drawing's display region's size. This includes the border if
* any. If the return value is equal to <TT>Drawing.AUTOMATIC_SIZE</TT>
* (0,0), it signifies that the drawing's display region's size should be
* determined automatically based on the drawing items in the drawing.
*
* @return Display region size.
*/ | Returns this drawing's display region's size. This includes the border if any. If the return value is equal to Drawing.AUTOMATIC_SIZE (0,0), it signifies that the drawing's display region's size should be determined automatically based on the drawing items in the drawing | size | {
"repo_name": "JimiHFord/pj2",
"path": "lib/edu/rit/draw/Drawing.java",
"license": "lgpl-3.0",
"size": 21725
} | [
"edu.rit.draw.item.Size"
] | import edu.rit.draw.item.Size; | import edu.rit.draw.item.*; | [
"edu.rit.draw"
] | edu.rit.draw; | 807,481 |
public static void fireSREChanged(PropertyChangeEvent event) {
for (final Object listener : SRE_LISTENERS.getListeners()) {
((ISREInstallChangedListener) listener).sreChanged(event);
}
} | static void function(PropertyChangeEvent event) { for (final Object listener : SRE_LISTENERS.getListeners()) { ((ISREInstallChangedListener) listener).sreChanged(event); } } | /**
* Notifies all SRE install changed listeners of the given property change.
*
* @param event - event describing the change.
*/ | Notifies all SRE install changed listeners of the given property change | fireSREChanged | {
"repo_name": "jgfoster/sarl",
"path": "main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/runtime/SARLRuntime.java",
"license": "apache-2.0",
"size": 31834
} | [
"org.eclipse.jdt.launching.PropertyChangeEvent"
] | import org.eclipse.jdt.launching.PropertyChangeEvent; | import org.eclipse.jdt.launching.*; | [
"org.eclipse.jdt"
] | org.eclipse.jdt; | 756,236 |
private static byte[] ntlmv2Hash(final String domain, final String user, final byte[] ntlmHash)
throws NTLMEngineException {
try {
final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash);
// Upper case username, mixed case target!!
hmacMD5.update(user.toUpperCase(Locale.ENGLISH).getBytes("UnicodeLittleUnmarked"));
if (domain != null) {
hmacMD5.update(domain.getBytes("UnicodeLittleUnmarked"));
}
return hmacMD5.getOutput();
} catch (final UnsupportedEncodingException e) {
throw new NTLMEngineException("Unicode not supported! " + e.getMessage(), e);
}
} | static byte[] function(final String domain, final String user, final byte[] ntlmHash) throws NTLMEngineException { try { final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash); hmacMD5.update(user.toUpperCase(Locale.ENGLISH).getBytes(STR)); if (domain != null) { hmacMD5.update(domain.getBytes(STR)); } return hmacMD5.getOutput(); } catch (final UnsupportedEncodingException e) { throw new NTLMEngineException(STR + e.getMessage(), e); } } | /**
* Creates the NTLMv2 Hash of the user's password.
*
* @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2
* Responses.
*/ | Creates the NTLMv2 Hash of the user's password | ntlmv2Hash | {
"repo_name": "SxdsF/Visit",
"path": "src/org/apache/http/impl/auth/NTLMEngineImpl.java",
"license": "apache-2.0",
"size": 66695
} | [
"java.io.UnsupportedEncodingException",
"java.util.Locale"
] | import java.io.UnsupportedEncodingException; import java.util.Locale; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 287,709 |
private ImmutableSet<String> getSecondaryTailSet(
ProguardTranslatorFactory translatorFactory)
throws IOException {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
if (secondaryDexTailClassesFile.isPresent()) {
Iterable<String> classes = FluentIterable
.from(filesystem.readLines(secondaryDexTailClassesFile.get()))
.transform(STRING_TRIM)
.filter(IS_NEITHER_EMPTY_NOR_COMMENT)
.transform(translatorFactory.createObfuscationFunction());
builder.addAll(classes);
}
return ImmutableSet.copyOf(builder.build());
} | ImmutableSet<String> function( ProguardTranslatorFactory translatorFactory) throws IOException { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); if (secondaryDexTailClassesFile.isPresent()) { Iterable<String> classes = FluentIterable .from(filesystem.readLines(secondaryDexTailClassesFile.get())) .transform(STRING_TRIM) .filter(IS_NEITHER_EMPTY_NOR_COMMENT) .transform(translatorFactory.createObfuscationFunction()); builder.addAll(classes); } return ImmutableSet.copyOf(builder.build()); } | /**
* Construct a {@link Set} of internal class names that must go into the beginning of
* the secondary dexes.
* <p/>
* @return ImmutableSet of class internal names.
*/ | Construct a <code>Set</code> of internal class names that must go into the beginning of the secondary dexes. | getSecondaryTailSet | {
"repo_name": "tgummerer/buck",
"path": "src/com/facebook/buck/android/SplitZipStep.java",
"license": "apache-2.0",
"size": 17616
} | [
"com.google.common.collect.FluentIterable",
"com.google.common.collect.ImmutableSet",
"java.io.IOException"
] | import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import java.io.IOException; | import com.google.common.collect.*; import java.io.*; | [
"com.google.common",
"java.io"
] | com.google.common; java.io; | 2,128,766 |
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<StampCapacityInner> listCapacities(String resourceGroupName, String name) {
return new PagedIterable<>(listCapacitiesAsync(resourceGroupName, name));
} | @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<StampCapacityInner> function(String resourceGroupName, String name) { return new PagedIterable<>(listCapacitiesAsync(resourceGroupName, name)); } | /**
* Get the used, available, and total worker capacity an App Service Environment.
*
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param name Name of the App Service Environment.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws DefaultErrorResponseErrorException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the used, available, and total worker capacity an App Service Environment.
*/ | Get the used, available, and total worker capacity an App Service Environment | listCapacities | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/AppServiceEnvironmentsClientImpl.java",
"license": "mit",
"size": 563770
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.http.rest.PagedIterable",
"com.azure.resourcemanager.appservice.fluent.models.StampCapacityInner"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.resourcemanager.appservice.fluent.models.StampCapacityInner; | import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.resourcemanager.appservice.fluent.models.*; | [
"com.azure.core",
"com.azure.resourcemanager"
] | com.azure.core; com.azure.resourcemanager; | 2,642,857 |
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.COGSAccountRef.class;
} | @Override() java.lang.Class function( ) { return org.chocolate_milk.model.COGSAccountRef.class; } | /**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/ | Method getJavaClass | getJavaClass | {
"repo_name": "galleon1/chocolate-milk",
"path": "src/org/chocolate_milk/model/descriptors/COGSAccountRefDescriptor.java",
"license": "lgpl-3.0",
"size": 5621
} | [
"org.chocolate_milk.model.COGSAccountRef"
] | import org.chocolate_milk.model.COGSAccountRef; | import org.chocolate_milk.model.*; | [
"org.chocolate_milk.model"
] | org.chocolate_milk.model; | 912,936 |
private JCheckBox getChkParseRobotsTxt() {
if (parseRobotsTxt == null) {
parseRobotsTxt = new JCheckBox();
parseRobotsTxt.setText(Constant.messages.getString("spider.options.label.robotstxt"));
}
return parseRobotsTxt;
}
| JCheckBox function() { if (parseRobotsTxt == null) { parseRobotsTxt = new JCheckBox(); parseRobotsTxt.setText(Constant.messages.getString(STR)); } return parseRobotsTxt; } | /**
* This method initializes the Parse robots.txt checkbox.
*
* @return javax.swing.JCheckBox
*/ | This method initializes the Parse robots.txt checkbox | getChkParseRobotsTxt | {
"repo_name": "Harinus/zaproxy",
"path": "src/org/zaproxy/zap/extension/spider/OptionsSpiderPanel.java",
"license": "apache-2.0",
"size": 20110
} | [
"javax.swing.JCheckBox",
"org.parosproxy.paros.Constant"
] | import javax.swing.JCheckBox; import org.parosproxy.paros.Constant; | import javax.swing.*; import org.parosproxy.paros.*; | [
"javax.swing",
"org.parosproxy.paros"
] | javax.swing; org.parosproxy.paros; | 216,296 |
public void addExtensions(Map<String,String> map) {
for (Map.Entry mapEntry : map.entrySet()) {
String key = (String) mapEntry.getKey();
String value = (String) mapEntry.getValue();
extendedMap.put(key, value);
}
} | void function(Map<String,String> map) { for (Map.Entry mapEntry : map.entrySet()) { String key = (String) mapEntry.getKey(); String value = (String) mapEntry.getValue(); extendedMap.put(key, value); } } | /**
* Add the extension map to the internal extensions map.
*
* @param map Map<String, String> of name value pairs
*/ | Add the extension map to the internal extensions map | addExtensions | {
"repo_name": "shanghaiscott/joid",
"path": "src/com/swdouglass/joid/AuthenticationRequest.java",
"license": "agpl-3.0",
"size": 15154
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 152,667 |
public Observable<ServiceResponse<VpnGatewayInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String gatewayName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
} | Observable<ServiceResponse<VpnGatewayInner>> function(String resourceGroupName, String gatewayName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException(STR); } if (resourceGroupName == null) { throw new IllegalArgumentException(STR); } if (gatewayName == null) { throw new IllegalArgumentException(STR); } | /**
* Retrieves the details of a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/ | Retrieves the details of a virtual wan vpn gateway | getByResourceGroupWithServiceResponseAsync | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/implementation/VpnGatewaysInner.java",
"license": "mit",
"size": 120434
} | [
"com.microsoft.rest.ServiceResponse"
] | import com.microsoft.rest.ServiceResponse; | import com.microsoft.rest.*; | [
"com.microsoft.rest"
] | com.microsoft.rest; | 2,533,461 |
public String toString()
{
String result = "size: " + size + ", blockSize: " + blockSize;
// Render only the blocks that are currently filled in.
List<Integer> blocks = new ArrayList<Integer>(blockMap.keySet());
Collections.sort(blocks);
for (int block : blocks)
{
List<T> list = blockMap.get(block);
result += ", [from: " + (block * blockSize);
result += ", to: " + ((block * blockSize) + list.size() - 1);
result += ", " + list + "]";
}
return result;
} | String function() { String result = STR + size + STR + blockSize; List<Integer> blocks = new ArrayList<Integer>(blockMap.keySet()); Collections.sort(blocks); for (int block : blocks) { List<T> list = blockMap.get(block); result += STR + (block * blockSize); result += STR + ((block * blockSize) + list.size() - 1); result += STR + list + "]"; } return result; } | /**
* Renders as a string for debugging purposes.
*
* @return A string for debugging purposes.
*/ | Renders as a string for debugging purposes | toString | {
"repo_name": "rupertlssmith/lojix",
"path": "base/common/src/main/com/thesett/common/util/LazyPagingList.java",
"license": "apache-2.0",
"size": 5800
} | [
"java.util.ArrayList",
"java.util.Collections",
"java.util.List"
] | import java.util.ArrayList; import java.util.Collections; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,356,356 |
protected void performCloseProcessing(ScenarioType scenario)
{
// just check if we're doing the end of run processing
if (doEndOfRunWrite())
{
try
{
// ok. get ready to output our status information
FileWriter _myWriter = createOutputFileWriter(scenario);
// write the asset header info
writeHeaderInfo(_myWriter);
// and output our results
writeMyResults(_myWriter);
// and close the writer
_myWriter.close();
// and reset my data
resetData();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
| void function(ScenarioType scenario) { if (doEndOfRunWrite()) { try { FileWriter _myWriter = createOutputFileWriter(scenario); writeHeaderInfo(_myWriter); writeMyResults(_myWriter); _myWriter.close(); resetData(); } catch (IOException e) { e.printStackTrace(); } } } | /**
* right, the scenario is about to close. We haven't removed the listeners
* or forgotten the scenario (yet).
*
* @param scenario the scenario we're closing from
*/ | right, the scenario is about to close. We haven't removed the listeners or forgotten the scenario (yet) | performCloseProcessing | {
"repo_name": "theanuradha/debrief",
"path": "org.mwc.asset.legacy/src/ASSET/Scenario/Observers/EndOfRunRecordToFileObserver.java",
"license": "epl-1.0",
"size": 3813
} | [
"java.io.FileWriter",
"java.io.IOException"
] | import java.io.FileWriter; import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,127,385 |
protected final void logDebugMessage(String message, Object... params) {
Logger.debug(decorateLogMessage(message), params);
} | final void function(String message, Object... params) { Logger.debug(decorateLogMessage(message), params); } | /**
* Print a DEBUG log message.
*
* @param message
* @param params
*/ | Print a DEBUG log message | logDebugMessage | {
"repo_name": "dubex/concourse",
"path": "concourse-server/src/main/java/com/cinchapi/concourse/server/upgrade/UpgradeTask.java",
"license": "apache-2.0",
"size": 6839
} | [
"com.cinchapi.concourse.util.Logger"
] | import com.cinchapi.concourse.util.Logger; | import com.cinchapi.concourse.util.*; | [
"com.cinchapi.concourse"
] | com.cinchapi.concourse; | 2,700,392 |
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
HttpURLConnection connection = createConnection(url);
int timeoutMs = request.getTimeoutMs();
connection.setConnectTimeout(timeoutMs);
connection.setReadTimeout(timeoutMs);
connection.setUseCaches(false);
connection.setDoInput(true);
// use caller-provided custom SslSocketFactory, if any, for HTTPS
if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
}
return connection;
} | HttpURLConnection function(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory); } return connection; } | /**
* Opens an {@link HttpURLConnection} with parameters.
* @param url
* @return an open connection
* @throws IOException
*/ | Opens an <code>HttpURLConnection</code> with parameters | openConnection | {
"repo_name": "jun0813/Telegram-plusplus",
"path": "TMessagesProj/src/main/java/org/telegramsecureplus/android/volley/toolbox/HurlStack.java",
"license": "gpl-2.0",
"size": 9761
} | [
"java.io.IOException",
"java.net.HttpURLConnection",
"javax.net.ssl.HttpsURLConnection",
"org.telegramsecureplus.android.volley.Request"
] | import java.io.IOException; import java.net.HttpURLConnection; import javax.net.ssl.HttpsURLConnection; import org.telegramsecureplus.android.volley.Request; | import java.io.*; import java.net.*; import javax.net.ssl.*; import org.telegramsecureplus.android.volley.*; | [
"java.io",
"java.net",
"javax.net",
"org.telegramsecureplus.android"
] | java.io; java.net; javax.net; org.telegramsecureplus.android; | 1,422,072 |
public void setProperties(Properties properties) {
if (properties == null) {
throw new IllegalArgumentException("invalid (null) Properties object");
}
for (Iterator i = properties.entrySet().iterator(); i.hasNext();) {
Entry e = (Entry) i.next();
setProperty((String) e.getKey(), (String) e.getValue());
}
} | void function(Properties properties) { if (properties == null) { throw new IllegalArgumentException(STR); } for (Iterator i = properties.entrySet().iterator(); i.hasNext();) { Entry e = (Entry) i.next(); setProperty((String) e.getKey(), (String) e.getValue()); } } | /**
* Inserts all properties from the given Properties instance into this PropertyTree.
*
* @param properties
* @throws IllegalArgumentException if the Properties object is null
* @throws IllegalArgumentException if a property's key is null
* @throws IllegalArgumentException if a property's value is null
*/ | Inserts all properties from the given Properties instance into this PropertyTree | setProperties | {
"repo_name": "geothomasp/kualico-rice-kc",
"path": "rice-middleware/core/api/src/main/java/org/kuali/rice/core/api/util/collect/PropertiesMap.java",
"license": "apache-2.0",
"size": 20116
} | [
"java.util.Iterator",
"java.util.Properties"
] | import java.util.Iterator; import java.util.Properties; | import java.util.*; | [
"java.util"
] | java.util; | 1,110,131 |
public void load() {
long t1 = System.nanoTime();
initDirs();
// Before digester - it may be needed
initNaming();
// Create and execute our Digester
Digester digester = createStartDigester();
InputSource inputSource = null;
InputStream inputStream = null;
File file = null;
try {
file = configFile();
inputStream = new FileInputStream(file);
inputSource = new InputSource(file.toURI().toURL().toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("catalina.configFail", file), e);
}
}
if (inputStream == null) {
try {
inputStream = getClass().getClassLoader()
.getResourceAsStream(getConfigFile());
inputSource = new InputSource
(getClass().getClassLoader()
.getResource(getConfigFile()).toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("catalina.configFail",
getConfigFile()), e);
}
}
}
// This should be included in catalina.jar
// Alternative: don't bother with xml, just create it manually.
if( inputStream==null ) {
try {
inputStream = getClass().getClassLoader()
.getResourceAsStream("server-embed.xml");
inputSource = new InputSource
(getClass().getClassLoader()
.getResource("server-embed.xml").toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("catalina.configFail",
"server-embed.xml"), e);
}
}
}
if (inputStream == null || inputSource == null) {
if (file == null) {
log.warn(sm.getString("catalina.configFail",
getConfigFile() + "] or [server-embed.xml]"));
} else {
log.warn(sm.getString("catalina.configFail",
file.getAbsolutePath()));
if (file.exists() && !file.canRead()) {
log.warn("Permissions incorrect, read permission is not allowed on the file.");
}
}
return;
}
try {
inputSource.setByteStream(inputStream);
digester.push(this);
digester.parse(inputSource);
} catch (SAXParseException spe) {
log.warn("Catalina.start using " + getConfigFile() + ": " +
spe.getMessage());
return;
} catch (Exception e) {
log.warn("Catalina.start using " + getConfigFile() + ": " , e);
return;
} finally {
try {
inputStream.close();
} catch (IOException e) {
// Ignore
}
}
getServer().setCatalina(this);
// Stream redirection
initStreams();
// Start the new server
try {
getServer().init();
} catch (LifecycleException e) {
if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) {
throw new java.lang.Error(e);
} else {
log.error("Catalina.start", e);
}
}
long t2 = System.nanoTime();
if(log.isInfoEnabled()) {
log.info("Initialization processed in " + ((t2 - t1) / 1000000) + " ms");
}
} | void function() { long t1 = System.nanoTime(); initDirs(); initNaming(); Digester digester = createStartDigester(); InputSource inputSource = null; InputStream inputStream = null; File file = null; try { file = configFile(); inputStream = new FileInputStream(file); inputSource = new InputSource(file.toURI().toURL().toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString(STR, file), e); } } if (inputStream == null) { try { inputStream = getClass().getClassLoader() .getResourceAsStream(getConfigFile()); inputSource = new InputSource (getClass().getClassLoader() .getResource(getConfigFile()).toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString(STR, getConfigFile()), e); } } } if( inputStream==null ) { try { inputStream = getClass().getClassLoader() .getResourceAsStream(STR); inputSource = new InputSource (getClass().getClassLoader() .getResource(STR).toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString(STR, STR), e); } } } if (inputStream == null inputSource == null) { if (file == null) { log.warn(sm.getString(STR, getConfigFile() + STR)); } else { log.warn(sm.getString(STR, file.getAbsolutePath())); if (file.exists() && !file.canRead()) { log.warn(STR); } } return; } try { inputSource.setByteStream(inputStream); digester.push(this); digester.parse(inputSource); } catch (SAXParseException spe) { log.warn(STR + getConfigFile() + STR + spe.getMessage()); return; } catch (Exception e) { log.warn(STR + getConfigFile() + STR , e); return; } finally { try { inputStream.close(); } catch (IOException e) { } } getServer().setCatalina(this); initStreams(); try { getServer().init(); } catch (LifecycleException e) { if (Boolean.getBoolean(STR)) { throw new java.lang.Error(e); } else { log.error(STR, e); } } long t2 = System.nanoTime(); if(log.isInfoEnabled()) { log.info(STR + ((t2 - t1) / 1000000) + STR); } } | /**
* Start a new server instance.
*/ | Start a new server instance | load | {
"repo_name": "EdwardLee03/tomcat-sr",
"path": "src/main/java/org/apache/catalina/startup/Catalina.java",
"license": "apache-2.0",
"size": 30652
} | [
"java.io.File",
"java.io.FileInputStream",
"java.io.IOException",
"java.io.InputStream",
"org.apache.catalina.LifecycleException",
"org.apache.tomcat.util.digester.Digester",
"org.xml.sax.InputSource",
"org.xml.sax.SAXParseException"
] | import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.catalina.LifecycleException; import org.apache.tomcat.util.digester.Digester; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; | import java.io.*; import org.apache.catalina.*; import org.apache.tomcat.util.digester.*; import org.xml.sax.*; | [
"java.io",
"org.apache.catalina",
"org.apache.tomcat",
"org.xml.sax"
] | java.io; org.apache.catalina; org.apache.tomcat; org.xml.sax; | 1,641,134 |
private void checkPushedDownDistinct(List<AbstractPlanNode> pn, boolean isMultiPart) {
assertTrue(pn.size() > 0);
AbstractPlanNode p = pn.get(0).getChild(0).getChild(0);
assertTrue(p instanceof DistinctPlanNode);
assertTrue(p.toJSONString().contains("\"DISTINCT\""));
if (isMultiPart) {
assertTrue(pn.size() == 2);
p = pn.get(1).getChild(0);
assertTrue(p instanceof DistinctPlanNode);
assertTrue(p.toJSONString().contains("\"DISTINCT\""));
}
} | void function(List<AbstractPlanNode> pn, boolean isMultiPart) { assertTrue(pn.size() > 0); AbstractPlanNode p = pn.get(0).getChild(0).getChild(0); assertTrue(p instanceof DistinctPlanNode); assertTrue(p.toJSONString().contains("\"DISTINCT\STR\STR")); } } | /**
* Check if the distinct node is pushed-down in the given plan.
*
* @param np
* The generated plan
* @param isMultiPart
* Whether or not the plan is distributed
*/ | Check if the distinct node is pushed-down in the given plan | checkPushedDownDistinct | {
"repo_name": "kobronson/cs-voltdb",
"path": "tests/frontend/org/voltdb/planner/TestPushDownAggregates.java",
"license": "agpl-3.0",
"size": 12834
} | [
"java.util.List",
"org.voltdb.plannodes.AbstractPlanNode",
"org.voltdb.plannodes.DistinctPlanNode"
] | import java.util.List; import org.voltdb.plannodes.AbstractPlanNode; import org.voltdb.plannodes.DistinctPlanNode; | import java.util.*; import org.voltdb.plannodes.*; | [
"java.util",
"org.voltdb.plannodes"
] | java.util; org.voltdb.plannodes; | 2,478,093 |
@Deprecated public static <T> UnmodifiableIterator<T> unmodifiableIterator(
UnmodifiableIterator<T> iterator) {
return checkNotNull(iterator);
} | @Deprecated static <T> UnmodifiableIterator<T> function( UnmodifiableIterator<T> iterator) { return checkNotNull(iterator); } | /**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/ | Simply returns its argument | unmodifiableIterator | {
"repo_name": "UBERMALLOW/external_guava",
"path": "guava/src/com/google/common/collect/Iterators.java",
"license": "apache-2.0",
"size": 45571
} | [
"com.google.common.base.Preconditions"
] | import com.google.common.base.Preconditions; | import com.google.common.base.*; | [
"com.google.common"
] | com.google.common; | 9,107 |
public static StyledParagraph insertChar(AttributedCharacterIterator aci,
char[] chars,
int insertPos,
StyledParagraph oldParagraph) {
// If the styles at insertPos match those at insertPos-1,
// oldParagraph will be reused. Otherwise we create a new
// paragraph.
char ch = aci.setIndex(insertPos);
int relativePos = Math.max(insertPos - aci.getBeginIndex() - 1, 0);
Map<? extends Attribute, ?> attributes =
addInputMethodAttrs(aci.getAttributes());
Decoration d = Decoration.getDecoration(attributes);
if (!oldParagraph.getDecorationAt(relativePos).equals(d)) {
return new StyledParagraph(aci, chars);
}
Object f = getGraphicOrFont(attributes);
if (f == null) {
FontResolver resolver = FontResolver.getInstance();
int fontIndex = resolver.getFontIndex(ch);
f = resolver.getFont(fontIndex, attributes);
}
if (!oldParagraph.getFontOrGraphicAt(relativePos).equals(f)) {
return new StyledParagraph(aci, chars);
}
// insert into existing paragraph
oldParagraph.length += 1;
if (oldParagraph.decorations != null) {
insertInto(relativePos,
oldParagraph.decorationStarts,
oldParagraph.decorations.size());
}
if (oldParagraph.fonts != null) {
insertInto(relativePos,
oldParagraph.fontStarts,
oldParagraph.fonts.size());
}
return oldParagraph;
} | static StyledParagraph function(AttributedCharacterIterator aci, char[] chars, int insertPos, StyledParagraph oldParagraph) { char ch = aci.setIndex(insertPos); int relativePos = Math.max(insertPos - aci.getBeginIndex() - 1, 0); Map<? extends Attribute, ?> attributes = addInputMethodAttrs(aci.getAttributes()); Decoration d = Decoration.getDecoration(attributes); if (!oldParagraph.getDecorationAt(relativePos).equals(d)) { return new StyledParagraph(aci, chars); } Object f = getGraphicOrFont(attributes); if (f == null) { FontResolver resolver = FontResolver.getInstance(); int fontIndex = resolver.getFontIndex(ch); f = resolver.getFont(fontIndex, attributes); } if (!oldParagraph.getFontOrGraphicAt(relativePos).equals(f)) { return new StyledParagraph(aci, chars); } oldParagraph.length += 1; if (oldParagraph.decorations != null) { insertInto(relativePos, oldParagraph.decorationStarts, oldParagraph.decorations.size()); } if (oldParagraph.fonts != null) { insertInto(relativePos, oldParagraph.fontStarts, oldParagraph.fonts.size()); } return oldParagraph; } | /**
* Return a StyledParagraph reflecting the insertion of a single character
* into the text. This method will attempt to reuse the given paragraph,
* but may create a new paragraph.
* @param aci an iterator over the text. The text should be the same as the
* text used to create (or most recently update) oldParagraph, with
* the exception of inserting a single character at insertPos.
* @param chars the characters in aci
* @param insertPos the index of the new character in aci
* @param oldParagraph a StyledParagraph for the text in aci before the
* insertion
*/ | Return a StyledParagraph reflecting the insertion of a single character into the text. This method will attempt to reuse the given paragraph, but may create a new paragraph | insertChar | {
"repo_name": "isaacl/openjdk-jdk",
"path": "src/share/classes/java/awt/font/StyledParagraph.java",
"license": "gpl-2.0",
"size": 17617
} | [
"java.text.AttributedCharacterIterator",
"java.util.Map"
] | import java.text.AttributedCharacterIterator; import java.util.Map; | import java.text.*; import java.util.*; | [
"java.text",
"java.util"
] | java.text; java.util; | 2,864,887 |
public static Properties loadDatabaseConfig()
{
Properties prop = new Properties();
try
{
//LOGGER.trace("config folder: " + AbstractConfig.getConfigurationFolder());
prop.load(new FileReader(AbstractConfig.getConfigurationFolder() + "database.properties"));
}
catch(IOException exception)
{
LOGGER.warn("Unable to read database properties reason: {}", exception.getMessage());
}
return prop;
} | static Properties function() { Properties prop = new Properties(); try { prop.load(new FileReader(AbstractConfig.getConfigurationFolder() + STR)); } catch(IOException exception) { LOGGER.warn(STR, exception.getMessage()); } return prop; } | /**
* loads the database.properties file from the configuration folder of the usef party
* */ | loads the database.properties file from the configuration folder of the usef party | loadDatabaseConfig | {
"repo_name": "USEF-Foundation/ri.usef.energy",
"path": "usef-build/usef-hoogdalem/usef-workflow-hd/usef-hd-agr1/src/main/java/nl/energieprojecthoogdalem/configurationservice/AgrConfiguration.java",
"license": "apache-2.0",
"size": 9373
} | [
"info.usef.core.config.AbstractConfig",
"java.io.FileReader",
"java.io.IOException",
"java.util.Properties"
] | import info.usef.core.config.AbstractConfig; import java.io.FileReader; import java.io.IOException; import java.util.Properties; | import info.usef.core.config.*; import java.io.*; import java.util.*; | [
"info.usef.core",
"java.io",
"java.util"
] | info.usef.core; java.io; java.util; | 1,241,533 |
public static int getConstantPreLayoutWidth(View view) {
// We haven't been layed out yet, so get the size from the LayoutParams
final ViewGroup.LayoutParams p = view.getLayoutParams();
if (p.width < 0) {
throw new IllegalStateException("Expecting view's width to be a constant rather " +
"than a result of the layout pass");
}
return p.width;
} | static int function(View view) { final ViewGroup.LayoutParams p = view.getLayoutParams(); if (p.width < 0) { throw new IllegalStateException(STR + STR); } return p.width; } | /**
* Returns the width as specified in the LayoutParams
* @throws IllegalStateException Thrown if the view's width is unknown before a layout pass
* s
*/ | Returns the width as specified in the LayoutParams | getConstantPreLayoutWidth | {
"repo_name": "s20121035/rk3288_android5.1_repo",
"path": "packages/apps/ContactsCommon/src/com/android/contacts/common/util/ViewUtil.java",
"license": "gpl-3.0",
"size": 4026
} | [
"android.view.View",
"android.view.ViewGroup"
] | import android.view.View; import android.view.ViewGroup; | import android.view.*; | [
"android.view"
] | android.view; | 1,093,584 |
@SuppressWarnings("unchecked")
public Object getProperty(String path) {
if (!path.contains(seperator)) {
Object val = root.get(path);
if (val == null) {
return null;
}
return val;
}
String[] parts = path.split(seperator);
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
if (o == null) {
return null;
}
if (i == parts.length - 1) {
return o;
}
try {
node = (Map<String, Object>) o;
} catch (ClassCastException e) {
return null;
}
}
return null;
} | @SuppressWarnings(STR) Object function(String path) { if (!path.contains(seperator)) { Object val = root.get(path); if (val == null) { return null; } return val; } String[] parts = path.split(seperator); Map<String, Object> node = root; for (int i = 0; i < parts.length; i++) { Object o = node.get(parts[i]); if (o == null) { return null; } if (i == parts.length - 1) { return o; } try { node = (Map<String, Object>) o; } catch (ClassCastException e) { return null; } } return null; } | /**
* Gets a property at a location. This will either return an Object
* or null, with null meaning that no configuration value exists at
* that location. This could potentially return a default value (not yet
* implemented) as defined by a plugin, if this is a plugin-tied
* configuration.
*
* @param path path to node (dot notation)
* @return object or null
*/ | Gets a property at a location. This will either return an Object or null, with null meaning that no configuration value exists at that location. This could potentially return a default value (not yet implemented) as defined by a plugin, if this is a plugin-tied configuration | getProperty | {
"repo_name": "Engelier/XcraftChat",
"path": "src/de/xcraft/engelier/utils/config/ConfigurationNode.java",
"license": "gpl-3.0",
"size": 17491
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 361,862 |
public boolean shouldSyncForCrashedMember(InternalDistributedMember id) {
return advisee instanceof DistributedRegion
&& ((InternalRegion) advisee).shouldSyncForCrashedMember(id);
} | boolean function(InternalDistributedMember id) { return advisee instanceof DistributedRegion && ((InternalRegion) advisee).shouldSyncForCrashedMember(id); } | /**
* determine whether a delta-gii synchronization should be performed for this lost member
*
* @return true if a delta-gii should be performed
*/ | determine whether a delta-gii synchronization should be performed for this lost member | shouldSyncForCrashedMember | {
"repo_name": "davinash/geode",
"path": "geode-core/src/main/java/org/apache/geode/distributed/internal/DistributionAdvisor.java",
"license": "apache-2.0",
"size": 62763
} | [
"org.apache.geode.distributed.internal.membership.InternalDistributedMember",
"org.apache.geode.internal.cache.DistributedRegion",
"org.apache.geode.internal.cache.InternalRegion"
] | import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.cache.DistributedRegion; import org.apache.geode.internal.cache.InternalRegion; | import org.apache.geode.distributed.internal.membership.*; import org.apache.geode.internal.cache.*; | [
"org.apache.geode"
] | org.apache.geode; | 2,903,370 |
public static Double createMFI(java.util.List<Double> highs,
java.util.List<Double> lows,
java.util.List<Double> closes,
// TODO: CRITICAL LONG BUG REVISED NEEDED.
java.util.List<Long> volumes, int period) {
if (period <= 0) {
throw new java.lang.IllegalArgumentException("period must be greater than 0");
}
if (highs.size() != lows.size() || highs.size() != closes.size() || highs.size() != volumes.size()) {
throw new java.lang.IllegalArgumentException("input list must be same size");
}
final int size = highs.size();
final Core core = new Core();
final int allocationSize = size - core.mfiLookback(period);
if (allocationSize <= 0) {
return null;
}
final double[] output = new double[allocationSize];
final MInteger outBegIdx = new MInteger();
final MInteger outNbElement = new MInteger();
double[] _highs = ArrayUtils.toPrimitive(highs.toArray(new Double[0]));
double[] _lows = ArrayUtils.toPrimitive(lows.toArray(new Double[0]));
double[] _closes = ArrayUtils.toPrimitive(closes.toArray(new Double[0]));
long[] _volumes = ArrayUtils.toPrimitive(volumes.toArray(new Long[0]));
double[] dv = new double[_volumes.length];
// Do not use System.arraycopy.
// It will cause java.lang.ArrayStoreException, due to type mismatch.
for (int i = 0; i < dv.length; i++) {
dv[i] = _volumes[i];
}
core.mfi(0, _highs.length - 1, _highs, _lows, _closes, dv, period, outBegIdx, outNbElement, output);
return output[outNbElement.value - 1];
} | static Double function(java.util.List<Double> highs, java.util.List<Double> lows, java.util.List<Double> closes, java.util.List<Long> volumes, int period) { if (period <= 0) { throw new java.lang.IllegalArgumentException(STR); } if (highs.size() != lows.size() highs.size() != closes.size() highs.size() != volumes.size()) { throw new java.lang.IllegalArgumentException(STR); } final int size = highs.size(); final Core core = new Core(); final int allocationSize = size - core.mfiLookback(period); if (allocationSize <= 0) { return null; } final double[] output = new double[allocationSize]; final MInteger outBegIdx = new MInteger(); final MInteger outNbElement = new MInteger(); double[] _highs = ArrayUtils.toPrimitive(highs.toArray(new Double[0])); double[] _lows = ArrayUtils.toPrimitive(lows.toArray(new Double[0])); double[] _closes = ArrayUtils.toPrimitive(closes.toArray(new Double[0])); long[] _volumes = ArrayUtils.toPrimitive(volumes.toArray(new Long[0])); double[] dv = new double[_volumes.length]; for (int i = 0; i < dv.length; i++) { dv[i] = _volumes[i]; } core.mfi(0, _highs.length - 1, _highs, _lows, _closes, dv, period, outBegIdx, outNbElement, output); return output[outNbElement.value - 1]; } | /**
* Returns the latest MFI.
*
* @param highs list of high price
* @param lows list of low price
* @param closes list of close price
* @param volumes list of volume
* @param period the duration period
* @return the latest MFI
*/ | Returns the latest MFI | createMFI | {
"repo_name": "oehm-smith/JStockMvn",
"path": "src/main/java/org/yccheok/jstock/charting/TechnicalAnalysis.java",
"license": "gpl-2.0",
"size": 16111
} | [
"com.tictactec.ta.lib.Core",
"com.tictactec.ta.lib.MInteger",
"java.util.List",
"org.apache.commons.lang.ArrayUtils"
] | import com.tictactec.ta.lib.Core; import com.tictactec.ta.lib.MInteger; import java.util.List; import org.apache.commons.lang.ArrayUtils; | import com.tictactec.ta.lib.*; import java.util.*; import org.apache.commons.lang.*; | [
"com.tictactec.ta",
"java.util",
"org.apache.commons"
] | com.tictactec.ta; java.util; org.apache.commons; | 1,522,694 |
public void shutdown(int id, int containers)
{
pendingRequests.incrementAndGet();
try
{
// simply shutdown
manager.shutdown(id, containers);
}
catch (BadParametersException bpe)
{
BadParametersException hbpe = new BadParametersException(bpe.getMessage(), bpe);
reportException(hbpe);
// rethrow CORBA specific
throw new BAD_PARAM(bpe.getMessage());
}
catch (NoResourcesException nre)
{
NoResourcesException hnre = new NoResourcesException(nre.getMessage(), nre);
reportException(hnre);
// rethrow CORBA specific
throw new NO_RESOURCES(nre.getMessage());
}
catch (AcsJNoPermissionEx npe)
{
//reportException(npe);
// rethrow CORBA specific
//throw npe.toNoPermissionEx();
throw new NO_PERMISSION(npe.getMessage());
}
catch (Throwable ex)
{
CoreException hce = new CoreException(ex.getMessage(), ex);
reportException(hce);
// rethrow CORBA specific
throw new UNKNOWN(ex.getMessage());
}
finally
{
pendingRequests.decrementAndGet();
}
} | void function(int id, int containers) { pendingRequests.incrementAndGet(); try { manager.shutdown(id, containers); } catch (BadParametersException bpe) { BadParametersException hbpe = new BadParametersException(bpe.getMessage(), bpe); reportException(hbpe); throw new BAD_PARAM(bpe.getMessage()); } catch (NoResourcesException nre) { NoResourcesException hnre = new NoResourcesException(nre.getMessage(), nre); reportException(hnre); throw new NO_RESOURCES(nre.getMessage()); } catch (AcsJNoPermissionEx npe) { throw new NO_PERMISSION(npe.getMessage()); } catch (Throwable ex) { CoreException hce = new CoreException(ex.getMessage(), ex); reportException(hce); throw new UNKNOWN(ex.getMessage()); } finally { pendingRequests.decrementAndGet(); } } | /**
* Shutdown the Manager.
* <B>Warning:</B> This call will also deactivate all components active in the system, including startup and immortal components.
*
* @param id Identification of the caller. The caller must have the SHUTDOWN_SYSTEM access right.
* @param containers The code to send to shutdown methods of all Containers. If 0, the Container's shutdown methods are not called.
*/ | Shutdown the Manager. Warning: This call will also deactivate all components active in the system, including startup and immortal components | shutdown | {
"repo_name": "csrg-utfsm/acscb",
"path": "LGPL/CommonSoftware/jmanager/src/com/cosylab/acs/maci/plug/ManagerProxyImpl.java",
"license": "mit",
"size": 63719
} | [
"com.cosylab.acs.maci.BadParametersException",
"com.cosylab.acs.maci.CoreException",
"com.cosylab.acs.maci.NoResourcesException"
] | import com.cosylab.acs.maci.BadParametersException; import com.cosylab.acs.maci.CoreException; import com.cosylab.acs.maci.NoResourcesException; | import com.cosylab.acs.maci.*; | [
"com.cosylab.acs"
] | com.cosylab.acs; | 1,107,581 |
private void writeJsonArrayStart(String fieldName)
throws JsonGenerationException, IOException {
generator.writeArrayFieldStart(fieldName);
} | void function(String fieldName) throws JsonGenerationException, IOException { generator.writeArrayFieldStart(fieldName); } | /**
* Writes the Start of Array String to the JSONGenerator along with Array
* Name.
*
* @param fieldName
* name of the JSON array
*/ | Writes the Start of Array String to the JSONGenerator along with Array Name | writeJsonArrayStart | {
"repo_name": "xuzha/aws-sdk-java",
"path": "aws-java-sdk-core/src/main/java/com/amazonaws/auth/policy/internal/JsonPolicyWriter.java",
"license": "apache-2.0",
"size": 13689
} | [
"com.fasterxml.jackson.core.JsonGenerationException",
"java.io.IOException"
] | import com.fasterxml.jackson.core.JsonGenerationException; import java.io.IOException; | import com.fasterxml.jackson.core.*; import java.io.*; | [
"com.fasterxml.jackson",
"java.io"
] | com.fasterxml.jackson; java.io; | 2,687,727 |
@Command
@NotifyChange("moduleDirectory")
public void loadSelectedModel() {
if (getSelectedModel() == null)
return;
// get module info
ModuleInfo moduleInfo = sessionState.getModuleInfo();
if (moduleInfo == null)
return;
// get module directory
File moduleDirectory = moduleInfo.getDirectory();
if (moduleDirectory == null)
return;
if (!moduleDirectory.exists())
return;
if (!moduleDirectory.isDirectory())
return;
// get model directory
File modelDirectory = new File(moduleDirectory, "models");
if (!modelDirectory.exists())
return;
if (!modelDirectory.isDirectory())
return;
// get model file
String modelFileName = getSelectedModel().getEnvironment() + ".xml";
File modelFile = new File(modelDirectory, modelFileName);
if (!modelFile.exists())
return;
if (!modelFile.isFile())
return;
try {
// load model
String model = FileUtils.readFileToString(modelFile, "UTF-8");
// escape model for transport to client
String escapedModel = escapeModelForTransport(model);
// invoke java script to create editor with document
StringBuilder script = new StringBuilder().append(CLIENTSIDE_JS_CREATEDOC).append("(\'")
.append(escapedModel).append("\')");
Clients.evalJavaScript(script.toString());
} catch (Exception e) {
Object[] args = { StackTraceHelper.getStrackTrace(e) };
String msg = webMessageProvider.getMessage("mp.load_model_failed", args);
logger.error(msg);
return;
}
}
| @NotifyChange(STR) void function() { if (getSelectedModel() == null) return; ModuleInfo moduleInfo = sessionState.getModuleInfo(); if (moduleInfo == null) return; File moduleDirectory = moduleInfo.getDirectory(); if (moduleDirectory == null) return; if (!moduleDirectory.exists()) return; if (!moduleDirectory.isDirectory()) return; File modelDirectory = new File(moduleDirectory, STR); if (!modelDirectory.exists()) return; if (!modelDirectory.isDirectory()) return; String modelFileName = getSelectedModel().getEnvironment() + ".xml"; File modelFile = new File(modelDirectory, modelFileName); if (!modelFile.exists()) return; if (!modelFile.isFile()) return; try { String model = FileUtils.readFileToString(modelFile, "UTF-8"); String escapedModel = escapeModelForTransport(model); StringBuilder script = new StringBuilder().append(CLIENTSIDE_JS_CREATEDOC).append("(\'") .append(escapedModel).append("\')"); Clients.evalJavaScript(script.toString()); } catch (Exception e) { Object[] args = { StackTraceHelper.getStrackTrace(e) }; String msg = webMessageProvider.getMessage(STR, args); logger.error(msg); return; } } | /**
* Event handler for selection of model in list box.
*
* Will load the model, escapes the model and invokes a client side java script
* which creates a editor instance with the document.
*/ | Event handler for selection of model in list box. Will load the model, escapes the model and invokes a client side java script which creates a editor instance with the document | loadSelectedModel | {
"repo_name": "athrane/pineapple",
"path": "applications/pineapple-web-application/pineapple-web-application-war/src/main/java/com/alpha/pineapple/web/zk/viewmodel/ModulePanel.java",
"license": "gpl-3.0",
"size": 21279
} | [
"com.alpha.javautils.StackTraceHelper",
"com.alpha.pineapple.module.ModuleInfo",
"java.io.File",
"org.apache.commons.io.FileUtils",
"org.zkoss.bind.annotation.NotifyChange",
"org.zkoss.zk.ui.util.Clients"
] | import com.alpha.javautils.StackTraceHelper; import com.alpha.pineapple.module.ModuleInfo; import java.io.File; import org.apache.commons.io.FileUtils; import org.zkoss.bind.annotation.NotifyChange; import org.zkoss.zk.ui.util.Clients; | import com.alpha.javautils.*; import com.alpha.pineapple.module.*; import java.io.*; import org.apache.commons.io.*; import org.zkoss.bind.annotation.*; import org.zkoss.zk.ui.util.*; | [
"com.alpha.javautils",
"com.alpha.pineapple",
"java.io",
"org.apache.commons",
"org.zkoss.bind",
"org.zkoss.zk"
] | com.alpha.javautils; com.alpha.pineapple; java.io; org.apache.commons; org.zkoss.bind; org.zkoss.zk; | 259,562 |
public static byte[] decode(char[] chars)
{
return Base64Coder.decode(chars);
} | static byte[] function(char[] chars) { return Base64Coder.decode(chars); } | /**
* Decode this base64 string to a regular string.
* @param string
* @return
*/ | Decode this base64 string to a regular string | decode | {
"repo_name": "jbundle/jbundle",
"path": "thin/base/util/base64/src/main/java/org/jbundle/thin/base/util/base64/Base64.java",
"license": "gpl-3.0",
"size": 10251
} | [
"biz.source_code.base64Coder.Base64Coder"
] | import biz.source_code.base64Coder.Base64Coder; | import biz.source_code.*; | [
"biz.source_code"
] | biz.source_code; | 2,448,488 |
public int convertFieldToBin(byte[] buffer, int offset, String value) throws ConversionException
{
logger.debug("Convert FieldToBin start");
logger.debug("Output buffer content is now: " + BinaryUtils.dumpByteArrayAsInts(buffer));
// Obtain, from the string value, an equivalent byte array
// with the GVDTE internal byte ordering (high byte first)
byte[] fieldBuffer = null;
try {
fieldBuffer = decode(value);
logger.debug("FieldBuffer content is now: "
+ BinaryUtils.dumpByteArrayAsInts(fieldBuffer));
// Get current binary field max lenght
int fieldMaxLen = fieldLen;
logger.debug("fieldMaxLen: " + fieldMaxLen);
// Must handle complementation and byte ordering
logger.debug("encoding: " + encoding);
logger.debug("byteOrder: " + byteOrder);
// Handle encoding
// TODO handle encoding
// Handle byte ordering
if (encoding.equals(BYTEORDER_LITTLE)) {
// Little endian means that the first byte is
// the least significant: is the inverse of the
// internal byte ordering of GVDTE Engine, so
// the byte array fieldBuffer must be inverted
// before copying it into the binary buffer
for (int i = 0; i < fieldBuffer.length; i++) {
tempLE[fieldBuffer.length - 1 - i] = fieldBuffer[i];
}
if (tempLE.length > fieldMaxLen) {
logger.error("Numeric value '" + value
+ "' is longer than its destination field into output binary buffer (" + fieldMaxLen + ")");
throw new ConversionException("GVDTE_ENCODING_ERROR", new String[][]{{
"msg",
"Numeric value '" + value
+ "' is longer than its destination field into output binary buffer ("
+ fieldMaxLen + ")"}});
}
System.arraycopy(tempLE, 0, buffer, offset, tempLE.length);
logger.debug("Output buffer content is now: "
+ BinaryUtils.dumpByteArrayAsInts(buffer));
}
else {
// Big endian means that the first byte is
// the most significant: is the same of the
// internal byte ordering of GVDTE Engine, so
// the byte array can be directly copied
// into the binary buffer
if (fieldBuffer.length > fieldMaxLen) {
logger.error("Numeric value '" + value
+ "' is longer than its destination field into output binary buffer (" + fieldMaxLen + ")");
throw new ConversionException("GVDTE_ENCODING_ERROR", new String[][]{{
"msg",
"Numeric value '" + value
+ "' is longer than its destination field into output binary buffer ("
+ fieldMaxLen + ")"}});
}
System.arraycopy(fieldBuffer, 0, buffer, offset, fieldBuffer.length);
logger.debug("Output buffer content is now: "
+ BinaryUtils.dumpByteArrayAsInts(buffer));
}
logger.debug("Convert FieldToBin stop");
return (offset + fieldBuffer.length);
}
catch (IOException exc) {
logger.error("Error while decoding string value", exc);
throw new ConversionException("GVDTE_ENCODING_ERROR", new String[][]{{"msg", "string value "}}, exc);
}
catch (Throwable exc) {
logger.error("Unexpected error while copying fieldBuffer into binary buffer", exc);
throw new ConversionException("GVDTE_GENERIC_ERROR", new String[][]{{"msg",
"Unexpected error while copying fieldBuffer into binary buffer."}}, exc);
}
} | int function(byte[] buffer, int offset, String value) throws ConversionException { logger.debug(STR); logger.debug(STR + BinaryUtils.dumpByteArrayAsInts(buffer)); byte[] fieldBuffer = null; try { fieldBuffer = decode(value); logger.debug(STR + BinaryUtils.dumpByteArrayAsInts(fieldBuffer)); int fieldMaxLen = fieldLen; logger.debug(STR + fieldMaxLen); logger.debug(STR + encoding); logger.debug(STR + byteOrder); if (encoding.equals(BYTEORDER_LITTLE)) { for (int i = 0; i < fieldBuffer.length; i++) { tempLE[fieldBuffer.length - 1 - i] = fieldBuffer[i]; } if (tempLE.length > fieldMaxLen) { logger.error(STR + value + STR + fieldMaxLen + ")"); throw new ConversionException(STR, new String[][]{{ "msg", STR + value + STR + fieldMaxLen + ")"}}); } System.arraycopy(tempLE, 0, buffer, offset, tempLE.length); logger.debug(STR + BinaryUtils.dumpByteArrayAsInts(buffer)); } else { if (fieldBuffer.length > fieldMaxLen) { logger.error(STR + value + STR + fieldMaxLen + ")"); throw new ConversionException(STR, new String[][]{{ "msg", STR + value + STR + fieldMaxLen + ")"}}); } System.arraycopy(fieldBuffer, 0, buffer, offset, fieldBuffer.length); logger.debug(STR + BinaryUtils.dumpByteArrayAsInts(buffer)); } logger.debug(STR); return (offset + fieldBuffer.length); } catch (IOException exc) { logger.error(STR, exc); throw new ConversionException(STR, new String[][]{{"msg", STR}}, exc); } catch (Throwable exc) { logger.error(STR, exc); throw new ConversionException(STR, new String[][]{{"msg", STR}}, exc); } } | /**
* Calls the <tt>decode</tt> method on the string <tt>value</tt> and copies the
* content of the resulting byte array (after performing byte-ordering inversion
* if needed) in the output binary buffer.
*
* @param buffer
* the byte array in which the binary field, containing converted
* data, will be inserted;
* @param offset
* the start position, within <code>buffer</code>, of the field
* containing the converted value;
* @param value
* the string value, contained within the XML element (or attribute)
* to be converted.
* @return the offset, within <code>buffer</code>, of the next binary field
* within the buffer.
* @throws ConversionException
* if any error occurs during conversion.
*/ | Calls the decode method on the string value and copies the content of the resulting byte array (after performing byte-ordering inversion if needed) in the output binary buffer | convertFieldToBin | {
"repo_name": "green-vulcano/gv-engine",
"path": "gvengine/gvdte/src/main/java/it/greenvulcano/gvesb/gvdte/transformers/bin/converters/NumConversion.java",
"license": "lgpl-3.0",
"size": 12567
} | [
"it.greenvulcano.util.bin.BinaryUtils",
"java.io.IOException"
] | import it.greenvulcano.util.bin.BinaryUtils; import java.io.IOException; | import it.greenvulcano.util.bin.*; import java.io.*; | [
"it.greenvulcano.util",
"java.io"
] | it.greenvulcano.util; java.io; | 539,659 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.