method stringlengths 13 441k | clean_method stringlengths 7 313k | doc stringlengths 17 17.3k | comment stringlengths 3 1.42k | method_name stringlengths 1 273 | extra dict | imports list | imports_info stringlengths 19 34.8k | cluster_imports_info stringlengths 15 3.66k | libraries list | libraries_info stringlengths 6 661 | id int64 0 2.92M |
|---|---|---|---|---|---|---|---|---|---|---|---|
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String ID_req = request.getParameter("accountID");
int ID_req_int = Integer.parseInt(ID_req);
BankAccount bankAccount = accountDAO.getAccountByID_asSingleAccount(ID_req_int);
request.setAttribute("bankAccount", bankAccount);
request.getRequestDispatcher("/simpleuser/account_info.jsp").forward(request, response);
}
| void function(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ID_req = request.getParameter(STR); int ID_req_int = Integer.parseInt(ID_req); BankAccount bankAccount = accountDAO.getAccountByID_asSingleAccount(ID_req_int); request.setAttribute(STR, bankAccount); request.getRequestDispatcher(STR).forward(request, response); } | /**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/ | Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods | processRequest | {
"repo_name": "Evegen55/WebTask",
"path": "Payments_v_1_1/src/java/controller/GetAccount.java",
"license": "apache-2.0",
"size": 3357
} | [
"java.io.IOException",
"javax.servlet.ServletException",
"javax.servlet.http.HttpServletRequest",
"javax.servlet.http.HttpServletResponse"
] | import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; | import java.io.*; import javax.servlet.*; import javax.servlet.http.*; | [
"java.io",
"javax.servlet"
] | java.io; javax.servlet; | 2,421,887 |
public int getColumnIndexByHeader(final String label) {
if (table.hasHeader()) {
int idx = 0;
for (String header : getHeaders()) {
if (header.equalsIgnoreCase(label)) {
return idx;
}
++idx;
}
return Row.COLUMN_NOT_FOUND;
} else {
return Row.COLUMN_NOT_FOUND;
}
} | int function(final String label) { if (table.hasHeader()) { int idx = 0; for (String header : getHeaders()) { if (header.equalsIgnoreCase(label)) { return idx; } ++idx; } return Row.COLUMN_NOT_FOUND; } else { return Row.COLUMN_NOT_FOUND; } } | /**
* Return the value of the header for the given index or return null if this document does not have a header
*/ | Return the value of the header for the given index or return null if this document does not have a header | getColumnIndexByHeader | {
"repo_name": "eXparity/exparity-data",
"path": "src/main/java/org/exparity/data/CSV.java",
"license": "apache-2.0",
"size": 12048
} | [
"org.exparity.data.types.Row"
] | import org.exparity.data.types.Row; | import org.exparity.data.types.*; | [
"org.exparity.data"
] | org.exparity.data; | 829,289 |
@Nonnull
public AuthenticationMethodTargetCollectionRequest filter(@Nonnull final String value) {
addFilterOption(value);
return this;
} | AuthenticationMethodTargetCollectionRequest function(@Nonnull final String value) { addFilterOption(value); return this; } | /**
* Sets the filter clause for the request
*
* @param value the filter clause
* @return the updated request
*/ | Sets the filter clause for the request | filter | {
"repo_name": "microsoftgraph/msgraph-sdk-java",
"path": "src/main/java/com/microsoft/graph/requests/AuthenticationMethodTargetCollectionRequest.java",
"license": "mit",
"size": 6328
} | [
"com.microsoft.graph.requests.AuthenticationMethodTargetCollectionRequest",
"javax.annotation.Nonnull"
] | import com.microsoft.graph.requests.AuthenticationMethodTargetCollectionRequest; import javax.annotation.Nonnull; | import com.microsoft.graph.requests.*; import javax.annotation.*; | [
"com.microsoft.graph",
"javax.annotation"
] | com.microsoft.graph; javax.annotation; | 1,055,382 |
public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {
} | void function(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) { } | /**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/ | Sets the raw JSON object | setRawObject | {
"repo_name": "microsoftgraph/msgraph-sdk-java",
"path": "src/main/java/com/microsoft/graph/models/CommsNotification.java",
"license": "mit",
"size": 2128
} | [
"com.google.gson.JsonObject",
"com.microsoft.graph.serializer.ISerializer",
"javax.annotation.Nonnull"
] | import com.google.gson.JsonObject; import com.microsoft.graph.serializer.ISerializer; import javax.annotation.Nonnull; | import com.google.gson.*; import com.microsoft.graph.serializer.*; import javax.annotation.*; | [
"com.google.gson",
"com.microsoft.graph",
"javax.annotation"
] | com.google.gson; com.microsoft.graph; javax.annotation; | 1,590,067 |
public static int convertWidthInCharsToPixels(FontMetrics fontMetrics,
int chars) {
return fontMetrics.getAverageCharWidth() * chars;
} | static int function(FontMetrics fontMetrics, int chars) { return fontMetrics.getAverageCharWidth() * chars; } | /**
* Returns the number of pixels corresponding to the width of the given
* number of characters.
* <p>
* The required <code>FontMetrics</code> parameter may be created in the
* following way: <code>
* GC gc = new GC(control);
* gc.setFont(control.getFont());
* fontMetrics = gc.getFontMetrics();
* gc.dispose();
* </code>
* </p>
*
* @param fontMetrics
* used in performing the conversion
* @param chars
* the number of characters
* @return the number of pixels
* @since 2.0
*/ | Returns the number of pixels corresponding to the width of the given number of characters. The required <code>FontMetrics</code> parameter may be created in the following way: <code> GC gc = new GC(control); gc.setFont(control.getFont()); fontMetrics = gc.getFontMetrics(); gc.dispose(); </code> | convertWidthInCharsToPixels | {
"repo_name": "ghillairet/gef-gwt",
"path": "src/main/java/org/eclipse/jface/dialogs/Dialog.java",
"license": "epl-1.0",
"size": 41103
} | [
"org.eclipse.swt.graphics.FontMetrics"
] | import org.eclipse.swt.graphics.FontMetrics; | import org.eclipse.swt.graphics.*; | [
"org.eclipse.swt"
] | org.eclipse.swt; | 1,040,721 |
StructureRotation getRotationType(); | StructureRotation getRotationType(); | /**
* Gets the target rotation type.
* Default StructureRotation.NONE.
*
* @return {@link StructureRotation}.
*/ | Gets the target rotation type. Default StructureRotation.NONE | getRotationType | {
"repo_name": "Shynixn/StructureBlockLib",
"path": "structureblocklib-api/src/main/java/com/github/shynixn/structureblocklib/api/entity/StructurePlaceMeta.java",
"license": "mit",
"size": 1444
} | [
"com.github.shynixn.structureblocklib.api.enumeration.StructureRotation"
] | import com.github.shynixn.structureblocklib.api.enumeration.StructureRotation; | import com.github.shynixn.structureblocklib.api.enumeration.*; | [
"com.github.shynixn"
] | com.github.shynixn; | 301,363 |
private void performZoom(MotionEvent event) {
if (event.getPointerCount() >= 2) {
OnChartGestureListener l = mChart.getOnChartGestureListener();
// get the distance between the pointers of the touch
// event
float totalDist = spacing(event);
if (totalDist > 10f) {
// get the translation
PointF t = getTrans(mTouchPointCenter.x, mTouchPointCenter.y);
// take actions depending on the activated touch
// mode
if (mTouchMode == PINCH_ZOOM) {
mLastGesture = ChartGesture.PINCH_ZOOM;
float scale = totalDist / mSavedDist; // total scale
boolean isZoomingOut = (scale < 1);
boolean canZoomMoreX = isZoomingOut ?
mChart.getViewPortHandler().canZoomOutMoreX() :
mChart.getViewPortHandler().canZoomInMoreX();
float scaleX = (mChart.isScaleXEnabled()) ? scale : 1f;
float scaleY = (mChart.isScaleYEnabled()) ? scale : 1f;
if (mChart.isScaleYEnabled() || canZoomMoreX) {
mMatrix.set(mSavedMatrix);
mMatrix.postScale(scaleX, scaleY, t.x, t.y);
if (l != null)
l.onChartScale(event, scaleX, scaleY);
}
} else if (mTouchMode == X_ZOOM && mChart.isScaleXEnabled()) {
mLastGesture = ChartGesture.X_ZOOM;
float xDist = getXDist(event);
float scaleX = xDist / mSavedXDist; // x-axis scale
boolean isZoomingOut = (scaleX < 1);
boolean canZoomMoreX = isZoomingOut ?
mChart.getViewPortHandler().canZoomOutMoreX() :
mChart.getViewPortHandler().canZoomInMoreX();
if (canZoomMoreX) {
mMatrix.set(mSavedMatrix);
mMatrix.postScale(scaleX, 1f, t.x, t.y);
if (l != null)
l.onChartScale(event, scaleX, 1f);
}
} else if (mTouchMode == Y_ZOOM && mChart.isScaleYEnabled()) {
mLastGesture = ChartGesture.Y_ZOOM;
float yDist = getYDist(event);
float scaleY = yDist / mSavedYDist; // y-axis scale
mMatrix.set(mSavedMatrix);
// y-axis comes from top to bottom, revert y
mMatrix.postScale(1f, scaleY, t.x, t.y);
if (l != null)
l.onChartScale(event, 1f, scaleY);
}
}
}
} | void function(MotionEvent event) { if (event.getPointerCount() >= 2) { OnChartGestureListener l = mChart.getOnChartGestureListener(); float totalDist = spacing(event); if (totalDist > 10f) { PointF t = getTrans(mTouchPointCenter.x, mTouchPointCenter.y); if (mTouchMode == PINCH_ZOOM) { mLastGesture = ChartGesture.PINCH_ZOOM; float scale = totalDist / mSavedDist; boolean isZoomingOut = (scale < 1); boolean canZoomMoreX = isZoomingOut ? mChart.getViewPortHandler().canZoomOutMoreX() : mChart.getViewPortHandler().canZoomInMoreX(); float scaleX = (mChart.isScaleXEnabled()) ? scale : 1f; float scaleY = (mChart.isScaleYEnabled()) ? scale : 1f; if (mChart.isScaleYEnabled() canZoomMoreX) { mMatrix.set(mSavedMatrix); mMatrix.postScale(scaleX, scaleY, t.x, t.y); if (l != null) l.onChartScale(event, scaleX, scaleY); } } else if (mTouchMode == X_ZOOM && mChart.isScaleXEnabled()) { mLastGesture = ChartGesture.X_ZOOM; float xDist = getXDist(event); float scaleX = xDist / mSavedXDist; boolean isZoomingOut = (scaleX < 1); boolean canZoomMoreX = isZoomingOut ? mChart.getViewPortHandler().canZoomOutMoreX() : mChart.getViewPortHandler().canZoomInMoreX(); if (canZoomMoreX) { mMatrix.set(mSavedMatrix); mMatrix.postScale(scaleX, 1f, t.x, t.y); if (l != null) l.onChartScale(event, scaleX, 1f); } } else if (mTouchMode == Y_ZOOM && mChart.isScaleYEnabled()) { mLastGesture = ChartGesture.Y_ZOOM; float yDist = getYDist(event); float scaleY = yDist / mSavedYDist; mMatrix.set(mSavedMatrix); mMatrix.postScale(1f, scaleY, t.x, t.y); if (l != null) l.onChartScale(event, 1f, scaleY); } } } } | /**
* Performs the all operations necessary for pinch and axis zoom.
*
* @param event
*/ | Performs the all operations necessary for pinch and axis zoom | performZoom | {
"repo_name": "jokeog/ProjectCalendae",
"path": "library/src/main/java/com/mikephil/charting/listener/BarLineChartTouchListener.java",
"license": "apache-2.0",
"size": 19762
} | [
"android.graphics.PointF",
"android.view.MotionEvent"
] | import android.graphics.PointF; import android.view.MotionEvent; | import android.graphics.*; import android.view.*; | [
"android.graphics",
"android.view"
] | android.graphics; android.view; | 389,144 |
protected void addSuspendInitialDurationPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_AbstractEndPoint_suspendInitialDuration_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_AbstractEndPoint_suspendInitialDuration_feature", "_UI_AbstractEndPoint_type"),
EsbPackage.Literals.ABSTRACT_END_POINT__SUSPEND_INITIAL_DURATION,
true,
false,
false,
ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE,
"Endpoint Suspend State",
null));
} | void function(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString(STR), getString(STR, STR, STR), EsbPackage.Literals.ABSTRACT_END_POINT__SUSPEND_INITIAL_DURATION, true, false, false, ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE, STR, null)); } | /**
* This adds a property descriptor for the Suspend Initial Duration feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/ | This adds a property descriptor for the Suspend Initial Duration feature. | addSuspendInitialDurationPropertyDescriptor | {
"repo_name": "chanakaudaya/developer-studio",
"path": "esb/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/AbstractEndPointItemProvider.java",
"license": "apache-2.0",
"size": 23207
} | [
"org.eclipse.emf.edit.provider.ComposeableAdapterFactory",
"org.eclipse.emf.edit.provider.ItemPropertyDescriptor",
"org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage"
] | import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage; | import org.eclipse.emf.edit.provider.*; import org.wso2.developerstudio.eclipse.gmf.esb.*; | [
"org.eclipse.emf",
"org.wso2.developerstudio"
] | org.eclipse.emf; org.wso2.developerstudio; | 2,500,964 |
private DLNode addDLNode(ArrayList<DLNode> allNodes, String identifier, String label) {
for (DLNode node:allNodes) {
if (node.getIdentifier().equalsIgnoreCase(identifier)) {
node.setLabel(label);
return node;
}
}
DLNode newNode = new DLNode(identifier,label);
allNodes.add(newNode);
return newNode;
}
| DLNode function(ArrayList<DLNode> allNodes, String identifier, String label) { for (DLNode node:allNodes) { if (node.getIdentifier().equalsIgnoreCase(identifier)) { node.setLabel(label); return node; } } DLNode newNode = new DLNode(identifier,label); allNodes.add(newNode); return newNode; } | /**
* If existing node matches to this identifier, update that node with the label info; if not, create a new node and add to the list.
* @param allNodes
* @param identifier
* @param label
* @return the node updated/created
*/ | If existing node matches to this identifier, update that node with the label info; if not, create a new node and add to the list | addDLNode | {
"repo_name": "ModelWriter/Deliverables",
"path": "WP2/D2.5.2_Generation/Jeni/src/synalp/parsing/ParseResult.java",
"license": "epl-1.0",
"size": 12853
} | [
"java.util.ArrayList"
] | import java.util.ArrayList; | import java.util.*; | [
"java.util"
] | java.util; | 596,494 |
public MetadataProperty getMetadataProperty(String propertyName) throws IllegalArgumentException
{
String value = getMetadataPropertyValue(propertyName);
return value == null ? null : new MetadataProperty(propertyName, value);
}
| MetadataProperty function(String propertyName) throws IllegalArgumentException { String value = getMetadataPropertyValue(propertyName); return value == null ? null : new MetadataProperty(propertyName, value); } | /**
* Returns the metadata property with the given name, or null if this property does not exist.
* @param propertyName The name of the metadata property.
* @return Metadata property with given name, or null.
* @throws IllegalArgumentException Thrown if propertyName is null or empty.
*/ | Returns the metadata property with the given name, or null if this property does not exist | getMetadataProperty | {
"repo_name": "langmo/youscope",
"path": "core/api/src/main/java/org/youscope/common/measurement/MeasurementConfiguration.java",
"license": "gpl-2.0",
"size": 10944
} | [
"org.youscope.common.MetadataProperty"
] | import org.youscope.common.MetadataProperty; | import org.youscope.common.*; | [
"org.youscope.common"
] | org.youscope.common; | 1,483,491 |
void removeJoinColumns(ResultColumnList joinColumns)
{
int jcSize = joinColumns.size();
for (int index = 0; index < jcSize; index++)
{
ResultColumn joinRC = (ResultColumn) joinColumns.elementAt(index);
String columnName = joinRC.getName();
// columnName should always be non-null
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(columnName != null,
"columnName should be non-null");
}
ResultColumn rightRC = getResultColumn(columnName);
// Remove the RC from this list.
if (rightRC != null)
{
removeElement(rightRC);
}
}
} | void removeJoinColumns(ResultColumnList joinColumns) { int jcSize = joinColumns.size(); for (int index = 0; index < jcSize; index++) { ResultColumn joinRC = (ResultColumn) joinColumns.elementAt(index); String columnName = joinRC.getName(); if (SanityManager.DEBUG) { SanityManager.ASSERT(columnName != null, STR); } ResultColumn rightRC = getResultColumn(columnName); if (rightRC != null) { removeElement(rightRC); } } } | /**
* Remove the columns which are join columns (in the
* joinColumns RCL) from this list. This is useful
* for a JOIN with a USING clause.
*
* @param joinColumns The list of join columns
*/ | Remove the columns which are join columns (in the joinColumns RCL) from this list. This is useful for a JOIN with a USING clause | removeJoinColumns | {
"repo_name": "papicella/snappy-store",
"path": "gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/sql/compile/ResultColumnList.java",
"license": "apache-2.0",
"size": 134730
} | [
"com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager"
] | import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager; | import com.pivotal.gemfirexd.internal.iapi.services.sanity.*; | [
"com.pivotal.gemfirexd"
] | com.pivotal.gemfirexd; | 2,384,560 |
@Test
@SmallTest
@UiThreadTest
public void testOneSmallControlTakesFullWidth() {
InfoBarControlLayout layout = new InfoBarControlLayout(mContext);
layout.setLayoutParams(
new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
View smallSwitch = layout.addSwitch(0, 0, "A", SWITCH_ID_1, false);
// Trigger the measurement algorithm.
int parentWidthSpec = MeasureSpec.makeMeasureSpec(INFOBAR_WIDTH, MeasureSpec.AT_MOST);
int parentHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
layout.measure(parentWidthSpec, parentHeightSpec);
// Small control takes the full width of the layout because it's put on its own line.
ControlLayoutParams params = InfoBarControlLayout.getControlLayoutParams(smallSwitch);
Assert.assertEquals(0, params.top);
Assert.assertEquals(0, params.start);
Assert.assertEquals(2, params.columnsRequired);
Assert.assertEquals(INFOBAR_WIDTH, smallSwitch.getMeasuredWidth());
} | void function() { InfoBarControlLayout layout = new InfoBarControlLayout(mContext); layout.setLayoutParams( new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); View smallSwitch = layout.addSwitch(0, 0, "A", SWITCH_ID_1, false); int parentWidthSpec = MeasureSpec.makeMeasureSpec(INFOBAR_WIDTH, MeasureSpec.AT_MOST); int parentHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); layout.measure(parentWidthSpec, parentHeightSpec); ControlLayoutParams params = InfoBarControlLayout.getControlLayoutParams(smallSwitch); Assert.assertEquals(0, params.top); Assert.assertEquals(0, params.start); Assert.assertEquals(2, params.columnsRequired); Assert.assertEquals(INFOBAR_WIDTH, smallSwitch.getMeasuredWidth()); } | /**
* A small control on the last line takes up the full width.
*/ | A small control on the last line takes up the full width | testOneSmallControlTakesFullWidth | {
"repo_name": "endlessm/chromium-browser",
"path": "chrome/browser/ui/messages/android/java/src/org/chromium/chrome/browser/ui/messages/infobar/InfoBarControlLayoutTest.java",
"license": "bsd-3-clause",
"size": 8452
} | [
"android.view.View",
"android.view.ViewGroup",
"org.chromium.chrome.browser.ui.messages.infobar.InfoBarControlLayout",
"org.junit.Assert"
] | import android.view.View; import android.view.ViewGroup; import org.chromium.chrome.browser.ui.messages.infobar.InfoBarControlLayout; import org.junit.Assert; | import android.view.*; import org.chromium.chrome.browser.ui.messages.infobar.*; import org.junit.*; | [
"android.view",
"org.chromium.chrome",
"org.junit"
] | android.view; org.chromium.chrome; org.junit; | 577,134 |
public PublicKey getPublicKey() {
return publicKey;
} | PublicKey function() { return publicKey; } | /**
* Get the configured public key for use with Raw Public Key.
*/ | Get the configured public key for use with Raw Public Key | getPublicKey | {
"repo_name": "nikhilvibhav/camel",
"path": "components/camel-coap/src/main/java/org/apache/camel/coap/CoAPEndpoint.java",
"license": "apache-2.0",
"size": 16216
} | [
"java.security.PublicKey"
] | import java.security.PublicKey; | import java.security.*; | [
"java.security"
] | java.security; | 610,131 |
@Exported(name="property",inline=true)
public List<ViewProperty> getAllProperties() {
return getProperties().toList();
} | @Exported(name=STR,inline=true) List<ViewProperty> function() { return getProperties().toList(); } | /**
* List of all {@link ViewProperty}s exposed primarily for the remoting API.
* @since 1.406
*/ | List of all <code>ViewProperty</code>s exposed primarily for the remoting API | getAllProperties | {
"repo_name": "damianszczepanik/jenkins",
"path": "core/src/main/java/hudson/model/View.java",
"license": "mit",
"size": 51759
} | [
"java.util.List",
"org.kohsuke.stapler.export.Exported"
] | import java.util.List; import org.kohsuke.stapler.export.Exported; | import java.util.*; import org.kohsuke.stapler.export.*; | [
"java.util",
"org.kohsuke.stapler"
] | java.util; org.kohsuke.stapler; | 885,275 |
void blockServiceOnFacility(PerunSession perunSession, Service service, Facility facility) throws ServiceAlreadyBannedException, PrivilegeException; | void blockServiceOnFacility(PerunSession perunSession, Service service, Facility facility) throws ServiceAlreadyBannedException, PrivilegeException; | /**
* Bans Service on facility.
* It wouldn't be possible to execute the given Service on the whole facility nor on any of its destinations.
*
* @param perunSession
* @param service The Service to be banned on the facility
* @param facility The facility on which we want to ban the Service
* @throws InternalErrorException
* @throws ServiceAlreadyBannedException
*/ | Bans Service on facility. It wouldn't be possible to execute the given Service on the whole facility nor on any of its destinations | blockServiceOnFacility | {
"repo_name": "martin-kuba/perun",
"path": "perun-core/src/main/java/cz/metacentrum/perun/core/api/ServicesManager.java",
"license": "bsd-2-clause",
"size": 46186
} | [
"cz.metacentrum.perun.core.api.exceptions.PrivilegeException",
"cz.metacentrum.perun.core.api.exceptions.ServiceAlreadyBannedException"
] | import cz.metacentrum.perun.core.api.exceptions.PrivilegeException; import cz.metacentrum.perun.core.api.exceptions.ServiceAlreadyBannedException; | import cz.metacentrum.perun.core.api.exceptions.*; | [
"cz.metacentrum.perun"
] | cz.metacentrum.perun; | 1,327,155 |
RectF getDisplayRect(); | RectF getDisplayRect(); | /**
* Gets the Display Rectangle of the currently displayed Drawable. The Rectangle is relative to
* this View and includes all scaling and translations.
*
* @return - RectF of Displayed Drawable
*/ | Gets the Display Rectangle of the currently displayed Drawable. The Rectangle is relative to this View and includes all scaling and translations | getDisplayRect | {
"repo_name": "Joy-Whale/ImageSelector",
"path": "imageselector/src/main/java/cn/joy/imageselector/crop/IPhotoView.java",
"license": "apache-2.0",
"size": 10322
} | [
"android.graphics.RectF"
] | import android.graphics.RectF; | import android.graphics.*; | [
"android.graphics"
] | android.graphics; | 1,498,815 |
private void createCameraPreviewSession() {
Log.d(TAG, "createCameraPreviewSession: ");
try {
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
// We configure the size of default buffer to be the size of camera preview we want.
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
// This is the output Surface we need to start preview.
Surface surface = new Surface(texture);
// We set up a CaptureRequest.Builder with the output Surface.
mPreviewRequestBuilder
= mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);
// Here, we create a CameraCaptureSession for camera preview.
mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
new CameraCaptureSession.StateCallback() { | void function() { Log.d(TAG, STR); try { SurfaceTexture texture = mTextureView.getSurfaceTexture(); assert texture != null; texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); Surface surface = new Surface(texture); mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); mPreviewRequestBuilder.addTarget(surface); mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()), new CameraCaptureSession.StateCallback() { | /**
* Creates a new {@link CameraCaptureSession} for camera preview.
*/ | Creates a new <code>CameraCaptureSession</code> for camera preview | createCameraPreviewSession | {
"repo_name": "MaTriXy/io2015-codelabs",
"path": "voice-interaction-api/voice-interaction-start/Application/src/main/java/com/example/android/voicecamera/CameraFragment.java",
"license": "apache-2.0",
"size": 37429
} | [
"android.graphics.SurfaceTexture",
"android.hardware.camera2.CameraCaptureSession",
"android.hardware.camera2.CameraDevice",
"android.util.Log",
"android.view.Surface",
"java.util.Arrays"
] | import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraDevice; import android.util.Log; import android.view.Surface; import java.util.Arrays; | import android.graphics.*; import android.hardware.camera2.*; import android.util.*; import android.view.*; import java.util.*; | [
"android.graphics",
"android.hardware",
"android.util",
"android.view",
"java.util"
] | android.graphics; android.hardware; android.util; android.view; java.util; | 1,299,111 |
public void setErrorHandler (ErrorHandler handler)
{
xmlReader.setErrorHandler(handler);
} | void function (ErrorHandler handler) { xmlReader.setErrorHandler(handler); } | /**
* Register the error event handler.
*
* @param handler The new error event handler.
* @see org.xml.sax.Parser#setErrorHandler
*/ | Register the error event handler | setErrorHandler | {
"repo_name": "mirego/j2objc",
"path": "jre_emul/android/platform/libcore/luni/src/main/java/org/xml/sax/helpers/XMLReaderAdapter.java",
"license": "apache-2.0",
"size": 14577
} | [
"org.xml.sax.ErrorHandler"
] | import org.xml.sax.ErrorHandler; | import org.xml.sax.*; | [
"org.xml.sax"
] | org.xml.sax; | 111,490 |
@SuppressWarnings("unchecked")
public void mousePressed(MouseEvent e) {
if(checkModifiers(e)) {
final VisualizationViewer<String,String> vv =
(VisualizationViewer<String,String>)e.getSource();
final Point2D p = e.getPoint();
GraphElementAccessor<String,String> pickSupport = vv.getPickSupport();
if(pickSupport != null) {
final String vertex = pickSupport.getVertex(vv.getModel().getGraphLayout(), p.getX(), p.getY());
if(vertex != null) { // get ready to make an edge
startVertex = vertex;
down = e.getPoint();
transformEdgeShape(down, down);
vv.addPostRenderPaintable(edgePaintable);
transformArrowShape(down, e.getPoint());
vv.addPostRenderPaintable(arrowPaintable);
}
}
vv.repaint();
}
} | @SuppressWarnings(STR) void function(MouseEvent e) { if(checkModifiers(e)) { final VisualizationViewer<String,String> vv = (VisualizationViewer<String,String>)e.getSource(); final Point2D p = e.getPoint(); GraphElementAccessor<String,String> pickSupport = vv.getPickSupport(); if(pickSupport != null) { final String vertex = pickSupport.getVertex(vv.getModel().getGraphLayout(), p.getX(), p.getY()); if(vertex != null) { startVertex = vertex; down = e.getPoint(); transformEdgeShape(down, down); vv.addPostRenderPaintable(edgePaintable); transformArrowShape(down, e.getPoint()); vv.addPostRenderPaintable(arrowPaintable); } } vv.repaint(); } } | /**
* If the mouse is pressed in an empty area, create a new vertex there.
* If the mouse is pressed on an existing vertex, prepare to create
* an edge from that vertex to another
*/ | If the mouse is pressed in an empty area, create a new vertex there. If the mouse is pressed on an existing vertex, prepare to create an edge from that vertex to another | mousePressed | {
"repo_name": "iig-uni-freiburg/SEWOL",
"path": "src/de/uni/freiburg/iig/telematik/sewol/accesscontrol/rbac/lattice/graphic/RoleGraphEditingPlugin.java",
"license": "bsd-3-clause",
"size": 7935
} | [
"edu.uci.ics.jung.algorithms.layout.GraphElementAccessor",
"edu.uci.ics.jung.visualization.VisualizationViewer",
"java.awt.event.MouseEvent",
"java.awt.geom.Point2D"
] | import edu.uci.ics.jung.algorithms.layout.GraphElementAccessor; import edu.uci.ics.jung.visualization.VisualizationViewer; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; | import edu.uci.ics.jung.algorithms.layout.*; import edu.uci.ics.jung.visualization.*; import java.awt.event.*; import java.awt.geom.*; | [
"edu.uci.ics",
"java.awt"
] | edu.uci.ics; java.awt; | 1,602,591 |
public ConfigMap properties(NodeList properties, String sourceFileName)
{
int length = properties.getLength();
ConfigMap map = new ConfigMap(length);
for (int p = 0; p < length; p++)
{
Node prop = properties.item(p);
String propName = prop.getNodeName();
if (propName != null)
{
propName = propName.trim();
if (prop.getNodeType() == Node.ELEMENT_NODE)
{
NodeList attributes = selectNodeList(prop, "@*");
NodeList children = selectNodeList(prop, "*");
if (children.getLength() > 0 || attributes.getLength() > 0)
{
ConfigMap childMap = new ConfigMap();
if (children.getLength() > 0)
childMap.addProperties(properties(children, sourceFileName));
if (attributes.getLength() > 0)
childMap.addProperties(properties(attributes, sourceFileName));
map.addProperty(propName, childMap);
}
else
{
// replace tokens before setting property
tokenReplacer.replaceToken(prop, sourceFileName);
String propValue = evaluateExpression(prop, ".").toString();
map.addProperty(propName, propValue);
}
}
else
{
// replace tokens before setting property
tokenReplacer.replaceToken(prop, sourceFileName);
map.addProperty(propName, prop.getNodeValue());
}
}
}
return map;
} | ConfigMap function(NodeList properties, String sourceFileName) { int length = properties.getLength(); ConfigMap map = new ConfigMap(length); for (int p = 0; p < length; p++) { Node prop = properties.item(p); String propName = prop.getNodeName(); if (propName != null) { propName = propName.trim(); if (prop.getNodeType() == Node.ELEMENT_NODE) { NodeList attributes = selectNodeList(prop, "@*"); NodeList children = selectNodeList(prop, "*"); if (children.getLength() > 0 attributes.getLength() > 0) { ConfigMap childMap = new ConfigMap(); if (children.getLength() > 0) childMap.addProperties(properties(children, sourceFileName)); if (attributes.getLength() > 0) childMap.addProperties(properties(attributes, sourceFileName)); map.addProperty(propName, childMap); } else { tokenReplacer.replaceToken(prop, sourceFileName); String propValue = evaluateExpression(prop, ".").toString(); map.addProperty(propName, propValue); } } else { tokenReplacer.replaceToken(prop, sourceFileName); map.addProperty(propName, prop.getNodeValue()); } } } return map; } | /**
* Recursively processes all child elements for each of the properties in the provided
* node list.
*
* @param properties the NodeList object
* @param sourceFileName the source file name
* @return ConfigMap the ConfigMap object
*/ | Recursively processes all child elements for each of the properties in the provided node list | properties | {
"repo_name": "apache/flex-blazeds",
"path": "common/src/main/java/flex/messaging/config/AbstractConfigurationParser.java",
"license": "apache-2.0",
"size": 19021
} | [
"org.w3c.dom.Node",
"org.w3c.dom.NodeList"
] | import org.w3c.dom.Node; import org.w3c.dom.NodeList; | import org.w3c.dom.*; | [
"org.w3c.dom"
] | org.w3c.dom; | 2,606,020 |
protected KnowledgeBase getKnowledgeBase() {
return knowledgeAgent.getKnowledgeBase();
} | KnowledgeBase function() { return knowledgeAgent.getKnowledgeBase(); } | /**
* <p>
* Gets the KnowledgeBase cached in KnowledgeAgent.
* </p>
*
* @return the KnowledgeBase cached in KnowledgeAgent
*/ | Gets the KnowledgeBase cached in KnowledgeAgent. | getKnowledgeBase | {
"repo_name": "NASA-Tournament-Lab/CoECI-OPM-Service-Credit-Redeposit-Deposit-Application",
"path": "Code/SCRD_BRE/src/java/ejb/gov/opm/scrd/services/impl/DroolsRuleService.java",
"license": "apache-2.0",
"size": 4481
} | [
"org.drools.KnowledgeBase"
] | import org.drools.KnowledgeBase; | import org.drools.*; | [
"org.drools"
] | org.drools; | 648,316 |
List<TBasketBean> loadMainBaskets();
| List<TBasketBean> loadMainBaskets(); | /**
* Loads the main baskets
* @return
*/ | Loads the main baskets | loadMainBaskets | {
"repo_name": "trackplus/Genji",
"path": "src/main/java/com/aurel/track/dao/BasketDAO.java",
"license": "gpl-3.0",
"size": 2487
} | [
"com.aurel.track.beans.TBasketBean",
"java.util.List"
] | import com.aurel.track.beans.TBasketBean; import java.util.List; | import com.aurel.track.beans.*; import java.util.*; | [
"com.aurel.track",
"java.util"
] | com.aurel.track; java.util; | 2,780,484 |
public void readPacketData(PacketBuffer buf) throws IOException
{
this.blockPos = buf.readBlockPos();
this.lines = new IChatComponent[4];
for (int i = 0; i < 4; ++i)
{
this.lines[i] = buf.readChatComponent();
}
} | void function(PacketBuffer buf) throws IOException { this.blockPos = buf.readBlockPos(); this.lines = new IChatComponent[4]; for (int i = 0; i < 4; ++i) { this.lines[i] = buf.readChatComponent(); } } | /**
* Reads the raw packet data from the data stream.
*/ | Reads the raw packet data from the data stream | readPacketData | {
"repo_name": "dogjaw2233/tiu-s-mod",
"path": "build/tmp/recompileMc/sources/net/minecraft/network/play/server/S33PacketUpdateSign.java",
"license": "lgpl-2.1",
"size": 1949
} | [
"java.io.IOException",
"net.minecraft.network.PacketBuffer",
"net.minecraft.util.IChatComponent"
] | import java.io.IOException; import net.minecraft.network.PacketBuffer; import net.minecraft.util.IChatComponent; | import java.io.*; import net.minecraft.network.*; import net.minecraft.util.*; | [
"java.io",
"net.minecraft.network",
"net.minecraft.util"
] | java.io; net.minecraft.network; net.minecraft.util; | 718,864 |
protected void traverseClassTraits (Traits traits)
{
for (Trait t : traits)
{
switch (t.getKind())
{
case TRAIT_Const:
traverseClassConstTrait(t);
break;
case TRAIT_Var:
traverseClassSlotTrait(t);
break;
case TRAIT_Method:
traverseClassMethodTrait(t);
break;
case TRAIT_Getter:
traverseClassGetterTrait(t);
break;
case TRAIT_Setter:
traverseClassSetterTrait(t);
break;
case TRAIT_Function:
traverseClassFunctionTrait(t);
break;
}
}
} | void function (Traits traits) { for (Trait t : traits) { switch (t.getKind()) { case TRAIT_Const: traverseClassConstTrait(t); break; case TRAIT_Var: traverseClassSlotTrait(t); break; case TRAIT_Method: traverseClassMethodTrait(t); break; case TRAIT_Getter: traverseClassGetterTrait(t); break; case TRAIT_Setter: traverseClassSetterTrait(t); break; case TRAIT_Function: traverseClassFunctionTrait(t); break; } } } | /**
* Traverse the traits of a Class Info
*/ | Traverse the traits of a Class Info | traverseClassTraits | {
"repo_name": "adufilie/flex-falcon",
"path": "compiler/src/org/apache/flex/abc/print/ABCDumpVisitor.java",
"license": "apache-2.0",
"size": 36770
} | [
"org.apache.flex.abc.semantics.Trait",
"org.apache.flex.abc.semantics.Traits"
] | import org.apache.flex.abc.semantics.Trait; import org.apache.flex.abc.semantics.Traits; | import org.apache.flex.abc.semantics.*; | [
"org.apache.flex"
] | org.apache.flex; | 1,897,384 |
@Override
public void selectionChanged(JavaTextSelection selection) {
try {
setEnabled(RefactoringAvailabilityTester.isPushDownAvailable(selection));
} catch (JavaModelException e) {
setEnabled(false);
}
} | void function(JavaTextSelection selection) { try { setEnabled(RefactoringAvailabilityTester.isPushDownAvailable(selection)); } catch (JavaModelException e) { setEnabled(false); } } | /**
* Note: This method is for internal use only. Clients should not call this method.
*
* @param selection the Java text selection
* @noreference This method is not intended to be referenced by clients.
*/ | Note: This method is for internal use only. Clients should not call this method | selectionChanged | {
"repo_name": "elucash/eclipse-oxygen",
"path": "org.eclipse.jdt.ui/src/org/eclipse/jdt/ui/actions/PushDownAction.java",
"license": "epl-1.0",
"size": 6277
} | [
"org.eclipse.jdt.core.JavaModelException",
"org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester",
"org.eclipse.jdt.internal.ui.javaeditor.JavaTextSelection"
] | import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; import org.eclipse.jdt.internal.ui.javaeditor.JavaTextSelection; | import org.eclipse.jdt.core.*; import org.eclipse.jdt.internal.corext.refactoring.*; import org.eclipse.jdt.internal.ui.javaeditor.*; | [
"org.eclipse.jdt"
] | org.eclipse.jdt; | 2,600,290 |
default void onRoleRenamed (@Nonnull @Nonempty final String sRoleID)
{} | default void onRoleRenamed (@Nonnull @Nonempty final String sRoleID) {} | /**
* Called after a role was renamed.
*
* @param sRoleID
* The modified role ID. Never <code>null</code>.
*/ | Called after a role was renamed | onRoleRenamed | {
"repo_name": "phax/ph-oton",
"path": "ph-oton-security/src/main/java/com/helger/photon/security/role/IRoleModificationCallback.java",
"license": "apache-2.0",
"size": 2002
} | [
"com.helger.commons.annotation.Nonempty",
"javax.annotation.Nonnull"
] | import com.helger.commons.annotation.Nonempty; import javax.annotation.Nonnull; | import com.helger.commons.annotation.*; import javax.annotation.*; | [
"com.helger.commons",
"javax.annotation"
] | com.helger.commons; javax.annotation; | 2,863,355 |
protected void updateProblemIndication() {
if (updateProblemIndication) {
BasicDiagnostic diagnostic =
new BasicDiagnostic
(Diagnostic.OK,
"insa.expArithm.editor",
0,
null,
new Object [] { editingDomain.getResourceSet() });
for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) {
if (childDiagnostic.getSeverity() != Diagnostic.OK) {
diagnostic.add(childDiagnostic);
}
}
int lastEditorPage = getPageCount() - 1;
if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) {
((ProblemEditorPart)getEditor(lastEditorPage)).setDiagnostic(diagnostic);
if (diagnostic.getSeverity() != Diagnostic.OK) {
setActivePage(lastEditorPage);
}
}
else if (diagnostic.getSeverity() != Diagnostic.OK) {
ProblemEditorPart problemEditorPart = new ProblemEditorPart();
problemEditorPart.setDiagnostic(diagnostic);
problemEditorPart.setMarkerHelper(markerHelper);
try {
addPage(++lastEditorPage, problemEditorPart, getEditorInput());
setPageText(lastEditorPage, problemEditorPart.getPartName());
setActivePage(lastEditorPage);
showTabs();
}
catch (PartInitException exception) {
ExpArithmEditorPlugin.INSTANCE.log(exception);
}
}
if (markerHelper.hasMarkers(editingDomain.getResourceSet())) {
markerHelper.deleteMarkers(editingDomain.getResourceSet());
if (diagnostic.getSeverity() != Diagnostic.OK) {
try {
markerHelper.createMarkers(diagnostic);
}
catch (CoreException exception) {
ExpArithmEditorPlugin.INSTANCE.log(exception);
}
}
}
}
} | void function() { if (updateProblemIndication) { BasicDiagnostic diagnostic = new BasicDiagnostic (Diagnostic.OK, STR, 0, null, new Object [] { editingDomain.getResourceSet() }); for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) { if (childDiagnostic.getSeverity() != Diagnostic.OK) { diagnostic.add(childDiagnostic); } } int lastEditorPage = getPageCount() - 1; if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) { ((ProblemEditorPart)getEditor(lastEditorPage)).setDiagnostic(diagnostic); if (diagnostic.getSeverity() != Diagnostic.OK) { setActivePage(lastEditorPage); } } else if (diagnostic.getSeverity() != Diagnostic.OK) { ProblemEditorPart problemEditorPart = new ProblemEditorPart(); problemEditorPart.setDiagnostic(diagnostic); problemEditorPart.setMarkerHelper(markerHelper); try { addPage(++lastEditorPage, problemEditorPart, getEditorInput()); setPageText(lastEditorPage, problemEditorPart.getPartName()); setActivePage(lastEditorPage); showTabs(); } catch (PartInitException exception) { ExpArithmEditorPlugin.INSTANCE.log(exception); } } if (markerHelper.hasMarkers(editingDomain.getResourceSet())) { markerHelper.deleteMarkers(editingDomain.getResourceSet()); if (diagnostic.getSeverity() != Diagnostic.OK) { try { markerHelper.createMarkers(diagnostic); } catch (CoreException exception) { ExpArithmEditorPlugin.INSTANCE.log(exception); } } } } } | /**
* Updates the problems indication with the information described in the specified diagnostic.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | Updates the problems indication with the information described in the specified diagnostic. | updateProblemIndication | {
"repo_name": "diverse-project/k3",
"path": "k3-sample/expArithm/insa.expArithm.editor/src/expArithm/presentation/ExpArithmEditor.java",
"license": "epl-1.0",
"size": 54035
} | [
"org.eclipse.core.runtime.CoreException",
"org.eclipse.emf.common.ui.editor.ProblemEditorPart",
"org.eclipse.emf.common.util.BasicDiagnostic",
"org.eclipse.emf.common.util.Diagnostic",
"org.eclipse.ui.PartInitException"
] | import org.eclipse.core.runtime.CoreException; import org.eclipse.emf.common.ui.editor.ProblemEditorPart; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.ui.PartInitException; | import org.eclipse.core.runtime.*; import org.eclipse.emf.common.ui.editor.*; import org.eclipse.emf.common.util.*; import org.eclipse.ui.*; | [
"org.eclipse.core",
"org.eclipse.emf",
"org.eclipse.ui"
] | org.eclipse.core; org.eclipse.emf; org.eclipse.ui; | 2,007,770 |
@SuppressWarnings("unchecked")
@Test
public void testRunningContainerReturnsRunningIsTrue() throws Exception {
// create container
containerInstanceInfo = dockerHelper.createContainer(session, randomId, defaultImageInfo);
containerInfo = containerInstanceInfo.getContainerInfo();
// start container
dockerHelper.startContainer(session, containerInfo);
// setup context
context.put(EXECUTIONRESULT_KEY, executionResult);
context.put(SESSION_KEY, session);
context.put(CONTAINER_INFO_KEY, containerInfo);
// execute command
inspectContainerCommand.execute(context);
// test
assertCommandWasSuccessfulWithDefinedInspectionState();
ContainerJson info = (ContainerJson) context.get(InspectContainerCommand.INSPECTED_CONTAINER_KEY);
assertEquals(true, info.getState().isRunning());
}
| @SuppressWarnings(STR) void function() throws Exception { containerInstanceInfo = dockerHelper.createContainer(session, randomId, defaultImageInfo); containerInfo = containerInstanceInfo.getContainerInfo(); dockerHelper.startContainer(session, containerInfo); context.put(EXECUTIONRESULT_KEY, executionResult); context.put(SESSION_KEY, session); context.put(CONTAINER_INFO_KEY, containerInfo); inspectContainerCommand.execute(context); assertCommandWasSuccessfulWithDefinedInspectionState(); ContainerJson info = (ContainerJson) context.get(InspectContainerCommand.INSPECTED_CONTAINER_KEY); assertEquals(true, info.getState().isRunning()); } | /**
* Test that running container returns running state to be true.
*/ | Test that running container returns running state to be true | testRunningContainerReturnsRunningIsTrue | {
"repo_name": "athrane/pineapple",
"path": "support/pineapple-docker-support/src/test/java/com/alpha/pineapple/docker/command/InspectContainerCommandSystemTest.java",
"license": "gpl-3.0",
"size": 10961
} | [
"com.alpha.pineapple.docker.model.rest.ContainerJson",
"org.junit.Assert"
] | import com.alpha.pineapple.docker.model.rest.ContainerJson; import org.junit.Assert; | import com.alpha.pineapple.docker.model.rest.*; import org.junit.*; | [
"com.alpha.pineapple",
"org.junit"
] | com.alpha.pineapple; org.junit; | 530,181 |
public BooleanWrapper nodeIsAvailable(String nodeUrl) {
final RMNode node = this.allNodes.get(nodeUrl);
return new BooleanWrapper(node != null && !node.isDown());
}
/**
* This method is called periodically by ProActive Nodes to inform the
* Resource Manager of a possible reconnection. The method is also used by
* ProActive Nodes to know if they are still known by the Resource Manager.
* For instance a Node which has been removed by a user from the
* Resource Manager is no longer known.
* <p>
* The method is defined as Immediate Service. This way it is executed in
* a dedicated Thread. It is essential in order to allow other methods to
* be executed immediately even if incoming connection to the Nodes is stopped
* or filtered while a timeout occurs when this method tries to send back a reply.
* <p>
* The {@code allNodes} data-structure is written by a single Thread only
* but read by multiple Threads. The data-structure is marked as volatile
* to ensure visibility.
* <p>
* Parallel executions of this method must involves different {@code nodeUrl}s.
* <p>
* The underlying calls to {@code setBusyNode} and {@code internalSetFree} | BooleanWrapper function(String nodeUrl) { final RMNode node = this.allNodes.get(nodeUrl); return new BooleanWrapper(node != null && !node.isDown()); } /** * This method is called periodically by ProActive Nodes to inform the * Resource Manager of a possible reconnection. The method is also used by * ProActive Nodes to know if they are still known by the Resource Manager. * For instance a Node which has been removed by a user from the * Resource Manager is no longer known. * <p> * The method is defined as Immediate Service. This way it is executed in * a dedicated Thread. It is essential in order to allow other methods to * be executed immediately even if incoming connection to the Nodes is stopped * or filtered while a timeout occurs when this method tries to send back a reply. * <p> * The {@code allNodes} data-structure is written by a single Thread only * but read by multiple Threads. The data-structure is marked as volatile * to ensure visibility. * <p> * Parallel executions of this method must involves different {@code nodeUrl}s. * <p> * The underlying calls to {@code setBusyNode} and {@code internalSetFree} | /**
* Returns true if the node nodeUrl is registered (i.e. known by the RM). Note that
* true is returned even if the node is down.
*
* @param nodeUrl the tested node.
* @return true if the node nodeUrl is registered.
*/ | Returns true if the node nodeUrl is registered (i.e. known by the RM). Note that true is returned even if the node is down | nodeIsAvailable | {
"repo_name": "yinan-liu/scheduling",
"path": "rm/rm-server/src/main/java/org/ow2/proactive/resourcemanager/core/RMCore.java",
"license": "agpl-3.0",
"size": 87108
} | [
"org.objectweb.proactive.Service",
"org.objectweb.proactive.core.node.Node",
"org.objectweb.proactive.core.util.wrapper.BooleanWrapper",
"org.ow2.proactive.resourcemanager.rmnode.RMNode"
] | import org.objectweb.proactive.Service; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.util.wrapper.BooleanWrapper; import org.ow2.proactive.resourcemanager.rmnode.RMNode; | import org.objectweb.proactive.*; import org.objectweb.proactive.core.node.*; import org.objectweb.proactive.core.util.wrapper.*; import org.ow2.proactive.resourcemanager.rmnode.*; | [
"org.objectweb.proactive",
"org.ow2.proactive"
] | org.objectweb.proactive; org.ow2.proactive; | 1,463,122 |
//-----------------------------------------------------------------------
public Set<Calendar> getPaymentCalendars() {
return _paymentCalendars;
} | Set<Calendar> function() { return _paymentCalendars; } | /**
* Gets the paymentCalendars.
* @return the value of the property
*/ | Gets the paymentCalendars | getPaymentCalendars | {
"repo_name": "McLeodMoores/starling",
"path": "projects/integration/src/main/java/com/opengamma/integration/tool/portfolio/xml/v1_0/jaxb/FxForwardTrade.java",
"license": "apache-2.0",
"size": 17443
} | [
"java.util.Set"
] | import java.util.Set; | import java.util.*; | [
"java.util"
] | java.util; | 1,556,049 |
protected Rectangle forwardMapRect(Rectangle sourceRect,
int sourceIndex) {
if ( sourceRect == null ) {
throw new IllegalArgumentException(JaiI18N.getString("Generic0"));
}
if (sourceIndex != 0) {
throw new IllegalArgumentException(JaiI18N.getString("Generic1"));
}
// Get the source dimensions
int dx0 = sourceRect.x / blockX;
int dy0 = sourceRect.y / blockY;
int dx1 = (sourceRect.x + sourceRect.width -1) / blockX;
int dy1 = (sourceRect.y + sourceRect.height-1) / blockY;
return new Rectangle(dx0, dy0, dx1-dx0+1, dy1-dy0+1);
}
| Rectangle function(Rectangle sourceRect, int sourceIndex) { if ( sourceRect == null ) { throw new IllegalArgumentException(JaiI18N.getString(STR)); } if (sourceIndex != 0) { throw new IllegalArgumentException(JaiI18N.getString(STR)); } int dx0 = sourceRect.x / blockX; int dy0 = sourceRect.y / blockY; int dx1 = (sourceRect.x + sourceRect.width -1) / blockX; int dy1 = (sourceRect.y + sourceRect.height-1) / blockY; return new Rectangle(dx0, dy0, dx1-dx0+1, dy1-dy0+1); } | /**
* Returns the minimum bounding box of the region of the destination
* to which a particular <code>Rectangle</code> of the specified source
* will be mapped.
*
* @param sourceRect the <code>Rectangle</code> in source coordinates.
* @param sourceIndex the index of the source image.
*
* @return a <code>Rectangle</code> indicating the destination
* bounding box, or <code>null</code> if the bounding box
* is unknown.
*
* @throws IllegalArgumentException if <code>sourceIndex</code> is
* negative or greater than the index of the last source.
* @throws IllegalArgumentException if <code>sourceRect</code> is
* <code>null</code>.
*/ | Returns the minimum bounding box of the region of the destination to which a particular <code>Rectangle</code> of the specified source will be mapped | forwardMapRect | {
"repo_name": "RoProducts/rastertheque",
"path": "JAILibrary/src/com/sun/media/jai/opimage/SubsampleBinaryToGray2x2OpImage.java",
"license": "gpl-2.0",
"size": 18387
} | [
"java.awt.Rectangle"
] | import java.awt.Rectangle; | import java.awt.*; | [
"java.awt"
] | java.awt; | 2,214,835 |
Collection<String> collection = wordsNearest(lookupTable.vector(label), n);
if (collection.contains(label))
collection.remove(label);
return collection;
} | Collection<String> collection = wordsNearest(lookupTable.vector(label), n); if (collection.contains(label)) collection.remove(label); return collection; } | /**
* This method does full scan against whole vocabulary, building descending list of similar words
* @param label
* @param n
* @return
*/ | This method does full scan against whole vocabulary, building descending list of similar words | wordsNearest | {
"repo_name": "kinbod/deeplearning4j",
"path": "deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/reader/impl/FlatModelUtils.java",
"license": "apache-2.0",
"size": 1976
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 1,461,735 |
public boolean intersects(Rectangle2D r) {
if (r == null || r.isEmpty()) {
return false;
}
for(int i = 1; i < rect[0]; i+= 4) {
if (r.intersects(rect[i], rect[i+1], rect[i + 2]-rect[i]+1, rect[i + 3]-rect[i + 1]+1)) {
return true;
}
}
return false;
} | boolean function(Rectangle2D r) { if (r == null r.isEmpty()) { return false; } for(int i = 1; i < rect[0]; i+= 4) { if (r.intersects(rect[i], rect[i+1], rect[i + 2]-rect[i]+1, rect[i + 3]-rect[i + 1]+1)) { return true; } } return false; } | /**
* Tests does Rectangle2D intersect MultiRectArea object
*/ | Tests does Rectangle2D intersect MultiRectArea object | intersects | {
"repo_name": "freeVM/freeVM",
"path": "enhanced/java/classlib/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/MultiRectArea.java",
"license": "apache-2.0",
"size": 23352
} | [
"java.awt.geom.Rectangle2D"
] | import java.awt.geom.Rectangle2D; | import java.awt.geom.*; | [
"java.awt"
] | java.awt; | 66,035 |
private ArrayList<IntArrayList> getIntegerSequence(Sequence sequence) {
ArrayList<IntArrayList> intSeq = new ArrayList<IntArrayList>();
ArrayList<String> seq = null;
String s = null;
// TODO use reflection to access the field, based on sequence.label
switch (sequence) {
case DELAY_TREND: s = delayTREND;
break;
case MA_WIN_LS: s = mawinLS;
break;
case R_PERIOD_LS: s = returnPeriodLS;
break;
default:
Assertion.assertStrict(false, Assertion.Level.ERR, "Unkown sequence type passed into 'getIntegerSequence'");
}
seq = parseParamSequence(s);
if (s.indexOf("[") == -1) { // a sequence of numbers, not intervals
for (int i = 0; i < seq.size(); i++) {
IntArrayList value = new IntArrayList(new int [] {0}); // forces the array to be initialised, otherwise 'set' won't work
Assertion.assertStrict(isInteger(seq.get(i)), Assertion.Level.ERR, "The values in " + s + " = " + seq + " have to be integers");
value.set(0, Integer.valueOf(seq.get(i)));
intSeq.add(value);
}
}
else { // is it a sequence of intervals?
String [] item;
for (int i = 0; i < seq.size(); i++) {
IntArrayList interval = new IntArrayList(new int [] {0,0}); // forces the array to be initialised, otherwise 'set' won't work
item = seq.get(i).replace("[", "").split("[\\[\\],]");
Assertion.assertStrict(isInteger(item[0]) && isInteger(item[1]), Assertion.Level.ERR, "The values in " + s + " = " + seq + " have to be integers");
interval.set(0, Integer.valueOf(item[0]));
interval.set(1, Integer.valueOf(item[1]));
intSeq.add(interval);
}
}
if ((intSeq.size() == 1) && (sequence.length(this) > 1)) // one item of the sequence is provided, copy if more are required
expandIntegerSequence(intSeq, sequence);
Assertion.assertStrict((intSeq.size() == sequence.length(this)) && (sequence.length(this) != 0), Assertion.Level.ERR, intSeq.size() + " items in the sequence '" + sequence.label +
"', different to the " + sequence.length(this) + " required");
return intSeq;
}
| ArrayList<IntArrayList> function(Sequence sequence) { ArrayList<IntArrayList> intSeq = new ArrayList<IntArrayList>(); ArrayList<String> seq = null; String s = null; switch (sequence) { case DELAY_TREND: s = delayTREND; break; case MA_WIN_LS: s = mawinLS; break; case R_PERIOD_LS: s = returnPeriodLS; break; default: Assertion.assertStrict(false, Assertion.Level.ERR, STR); } seq = parseParamSequence(s); if (s.indexOf("[") == -1) { for (int i = 0; i < seq.size(); i++) { IntArrayList value = new IntArrayList(new int [] {0}); Assertion.assertStrict(isInteger(seq.get(i)), Assertion.Level.ERR, STR + s + STR + seq + STR); value.set(0, Integer.valueOf(seq.get(i))); intSeq.add(value); } } else { String [] item; for (int i = 0; i < seq.size(); i++) { IntArrayList interval = new IntArrayList(new int [] {0,0}); item = seq.get(i).replace("[", STR[\\[\\],]"); Assertion.assertStrict(isInteger(item[0]) && isInteger(item[1]), Assertion.Level.ERR, STR + s + STR + seq + STR); interval.set(0, Integer.valueOf(item[0])); interval.set(1, Integer.valueOf(item[1])); intSeq.add(interval); } } if ((intSeq.size() == 1) && (sequence.length(this) > 1)) expandIntegerSequence(intSeq, sequence); Assertion.assertStrict((intSeq.size() == sequence.length(this)) && (sequence.length(this) != 0), Assertion.Level.ERR, intSeq.size() + " items in the sequence 'STR', different to the STR required"); return intSeq; } | /**
* Transforms a sequence of strings into integers or intervals of integers. Checks whether the sequence
* contains integers rather than doubles
*
* Returns a sequence of single numbers or of intervals
*/ | Transforms a sequence of strings into integers or intervals of integers. Checks whether the sequence contains integers rather than doubles Returns a sequence of single numbers or of intervals | getIntegerSequence | {
"repo_name": "gitwitcho/var-agent-model",
"path": "agentsimulator/src/info/financialecology/finance/abm/simulation/LPLSEqnParams.java",
"license": "apache-2.0",
"size": 42872
} | [
"info.financialecology.finance.utilities.Assertion",
"java.util.ArrayList"
] | import info.financialecology.finance.utilities.Assertion; import java.util.ArrayList; | import info.financialecology.finance.utilities.*; import java.util.*; | [
"info.financialecology.finance",
"java.util"
] | info.financialecology.finance; java.util; | 2,695,905 |
@Override
public int showOpenDialog(Component parent) {
throw new IllegalStateException("Cannot load images!");
} | int function(Component parent) { throw new IllegalStateException(STR); } | /**
* Throws an exception.
*
* @param parent the parent of this file chooser
* @return throws an exception
*/ | Throws an exception | showOpenDialog | {
"repo_name": "waikato-datamining/adams-base",
"path": "adams-core/src/main/java/adams/gui/print/JComponentWriterFileChooser.java",
"license": "gpl-3.0",
"size": 11943
} | [
"java.awt.Component"
] | import java.awt.Component; | import java.awt.*; | [
"java.awt"
] | java.awt; | 960,098 |
RectF getDisplayRect(); | RectF getDisplayRect(); | /**
* Gets the Display Rectangle of the currently displayed Drawable. The
* Rectangle is relative to this View and includes all scaling and
* translations.
*
* @return - RectF of Displayed Drawable
*/ | Gets the Display Rectangle of the currently displayed Drawable. The Rectangle is relative to this View and includes all scaling and translations | getDisplayRect | {
"repo_name": "do-android/do_Easemob",
"path": "doExt_do_Easemob/src/doext/easemob/ui/photoview/IPhotoView.java",
"license": "gpl-3.0",
"size": 5491
} | [
"android.graphics.RectF"
] | import android.graphics.RectF; | import android.graphics.*; | [
"android.graphics"
] | android.graphics; | 2,885,145 |
private double getEnrollment(Lecture lecture, Map<Long, Double> limits) {
Double enrollment = limits.get(lecture.getClassId());
return enrollment == null ? 0.0 : enrollment.doubleValue();
} | double function(Lecture lecture, Map<Long, Double> limits) { Double enrollment = limits.get(lecture.getClassId()); return enrollment == null ? 0.0 : enrollment.doubleValue(); } | /**
* Enrollment of the given class
*/ | Enrollment of the given class | getEnrollment | {
"repo_name": "UniTime/cpsolver",
"path": "src/org/cpsolver/coursett/sectioning/SctModel.java",
"license": "lgpl-3.0",
"size": 33093
} | [
"java.util.Map",
"org.cpsolver.coursett.model.Lecture"
] | import java.util.Map; import org.cpsolver.coursett.model.Lecture; | import java.util.*; import org.cpsolver.coursett.model.*; | [
"java.util",
"org.cpsolver.coursett"
] | java.util; org.cpsolver.coursett; | 2,081,098 |
@Test
public void testDiscardReadBytes2() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i ++) {
buffer.writeByte((byte) i);
}
ByteBuf copy = copiedBuffer(buffer);
// Discard the first (CAPACITY / 2 - 1) bytes.
buffer.setIndex(CAPACITY / 2 - 1, CAPACITY - 1);
buffer.discardReadBytes();
assertEquals(0, buffer.readerIndex());
assertEquals(CAPACITY / 2, buffer.writerIndex());
for (int i = 0; i < CAPACITY / 2; i ++) {
assertEquals(copy.slice(CAPACITY / 2 - 1 + i, CAPACITY / 2 - i), buffer.slice(i, CAPACITY / 2 - i));
}
copy.release();
} | void function() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i ++) { buffer.writeByte((byte) i); } ByteBuf copy = copiedBuffer(buffer); buffer.setIndex(CAPACITY / 2 - 1, CAPACITY - 1); buffer.discardReadBytes(); assertEquals(0, buffer.readerIndex()); assertEquals(CAPACITY / 2, buffer.writerIndex()); for (int i = 0; i < CAPACITY / 2; i ++) { assertEquals(copy.slice(CAPACITY / 2 - 1 + i, CAPACITY / 2 - i), buffer.slice(i, CAPACITY / 2 - i)); } copy.release(); } | /**
* The similar test case with {@link #testDiscardReadBytes()} but this one
* discards a large chunk at once.
*/ | The similar test case with <code>#testDiscardReadBytes()</code> but this one discards a large chunk at once | testDiscardReadBytes2 | {
"repo_name": "zer0se7en/netty",
"path": "buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java",
"license": "apache-2.0",
"size": 174561
} | [
"io.netty.buffer.Unpooled",
"org.junit.Assert"
] | import io.netty.buffer.Unpooled; import org.junit.Assert; | import io.netty.buffer.*; import org.junit.*; | [
"io.netty.buffer",
"org.junit"
] | io.netty.buffer; org.junit; | 187,216 |
private void unicast(SwimMember member, ImmutableMember update) {
bootstrapService.getUnicastService().unicast(
member.address(),
MEMBERSHIP_GOSSIP,
SERIALIZER.encode(Lists.newArrayList(update)));
} | void function(SwimMember member, ImmutableMember update) { bootstrapService.getUnicastService().unicast( member.address(), MEMBERSHIP_GOSSIP, SERIALIZER.encode(Lists.newArrayList(update))); } | /**
* Unicasts the given update to the given member.
*
* @param member the member to which to unicast the update
* @param update the update to unicast
*/ | Unicasts the given update to the given member | unicast | {
"repo_name": "kuujo/copycat",
"path": "cluster/src/main/java/io/atomix/cluster/protocol/SwimMembershipProtocol.java",
"license": "apache-2.0",
"size": 37184
} | [
"com.google.common.collect.Lists"
] | import com.google.common.collect.Lists; | import com.google.common.collect.*; | [
"com.google.common"
] | com.google.common; | 2,176,934 |
@Deployment(resources = { "org/flowable/engine/test/api/event/CancelUserTaskEventsTest.bpmn20.xml" })
public void testUserTaskCancelledByMessageBoundaryEvent() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("cancelUserTaskEvents");
assertNotNull(processInstance);
Execution task1Execution = runtimeService.createExecutionQuery().activityId("task1").singleResult();
Execution task2Execution = runtimeService.createExecutionQuery().activityId("task2").singleResult();
Execution boundaryExecution = runtimeService.createExecutionQuery().activityId("cancelBoundaryEvent1").singleResult();
int idx = 0;
FlowableEvent flowableEvent = testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.PROCESS_STARTED, flowableEvent.getType());
ExecutionEntity executionEntity = (ExecutionEntity) ((FlowableProcessStartedEvent) flowableEvent).getEntity();
assertEquals(processInstance.getId(), executionEntity.getProcessInstanceId());
FlowableActivityEvent activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.ACTIVITY_STARTED, activityEvent.getType());
assertEquals("startEvent", activityEvent.getActivityType());
activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.ACTIVITY_COMPLETED, activityEvent.getType());
assertEquals("startEvent", activityEvent.getActivityType());
activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.ACTIVITY_STARTED, activityEvent.getType());
assertEquals("task1", activityEvent.getActivityId());
FlowableEntityEvent entityEvent = (FlowableEntityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.TASK_CREATED, entityEvent.getType());
TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity();
assertEquals("User Task1", taskEntity.getName());
activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.ACTIVITY_STARTED, activityEvent.getType());
assertEquals("task2", activityEvent.getActivityId());
entityEvent = (FlowableEntityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.TASK_CREATED, entityEvent.getType());
taskEntity = (TaskEntity) entityEvent.getEntity();
assertEquals("User Task2", taskEntity.getName());
Execution cancelMessageExecution = runtimeService.createExecutionQuery().messageEventSubscriptionName("cancel")
.singleResult();
assertNotNull(cancelMessageExecution);
assertEquals("cancelBoundaryEvent1", cancelMessageExecution.getActivityId());
// cancel the user task (task2)
runtimeService.messageEventReceived("cancel", cancelMessageExecution.getId());
activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.ACTIVITY_CANCELLED, activityEvent.getType());
FlowableActivityCancelledEvent cancelledEvent = (FlowableActivityCancelledEvent) activityEvent;
assertEquals("task2", cancelledEvent.getActivityId());
assertEquals("userTask", cancelledEvent.getActivityType());
assertEquals("User Task2", cancelledEvent.getActivityName());
assertEquals(task2Execution.getId(), cancelledEvent.getExecutionId());
activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.ACTIVITY_COMPLETED, activityEvent.getType());
assertEquals("cancelBoundaryEvent1", activityEvent.getActivityId());
assertEquals("boundaryEvent", activityEvent.getActivityType());
assertEquals(boundaryExecution.getId(), activityEvent.getExecutionId());
activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.ACTIVITY_STARTED, activityEvent.getType());
assertEquals("endEvent1", activityEvent.getActivityId());
activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.ACTIVITY_CANCELLED, activityEvent.getType());
assertEquals("task1", activityEvent.getActivityId());
assertEquals(task1Execution.getId(), activityEvent.getExecutionId());
entityEvent = (FlowableEntityEvent) testListener.getEventsReceived().get(idx++);
assertEquals(FlowableEngineEventType.PROCESS_COMPLETED_WITH_TERMINATE_END_EVENT, entityEvent.getType());
assertEquals(12, idx);
assertEquals(12, testListener.getEventsReceived().size());
}
class UserActivityEventListener extends AbstractFlowableEngineEventListener {
private List<FlowableEvent> eventsReceived;
public UserActivityEventListener() {
super(new HashSet<>(Arrays.asList(
FlowableEngineEventType.ACTIVITY_STARTED,
FlowableEngineEventType.ACTIVITY_COMPLETED,
FlowableEngineEventType.ACTIVITY_CANCELLED,
FlowableEngineEventType.TASK_CREATED,
FlowableEngineEventType.TASK_COMPLETED,
FlowableEngineEventType.PROCESS_STARTED,
FlowableEngineEventType.PROCESS_COMPLETED,
FlowableEngineEventType.PROCESS_CANCELLED,
FlowableEngineEventType.PROCESS_COMPLETED_WITH_TERMINATE_END_EVENT
)));
eventsReceived = new ArrayList<>();
} | @Deployment(resources = { STR }) void function() throws Exception { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(STR); assertNotNull(processInstance); Execution task1Execution = runtimeService.createExecutionQuery().activityId("task1").singleResult(); Execution task2Execution = runtimeService.createExecutionQuery().activityId("task2").singleResult(); Execution boundaryExecution = runtimeService.createExecutionQuery().activityId(STR).singleResult(); int idx = 0; FlowableEvent flowableEvent = testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.PROCESS_STARTED, flowableEvent.getType()); ExecutionEntity executionEntity = (ExecutionEntity) ((FlowableProcessStartedEvent) flowableEvent).getEntity(); assertEquals(processInstance.getId(), executionEntity.getProcessInstanceId()); FlowableActivityEvent activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.ACTIVITY_STARTED, activityEvent.getType()); assertEquals(STR, activityEvent.getActivityType()); activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.ACTIVITY_COMPLETED, activityEvent.getType()); assertEquals(STR, activityEvent.getActivityType()); activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.ACTIVITY_STARTED, activityEvent.getType()); assertEquals("task1", activityEvent.getActivityId()); FlowableEntityEvent entityEvent = (FlowableEntityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.TASK_CREATED, entityEvent.getType()); TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity(); assertEquals(STR, taskEntity.getName()); activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.ACTIVITY_STARTED, activityEvent.getType()); assertEquals("task2", activityEvent.getActivityId()); entityEvent = (FlowableEntityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.TASK_CREATED, entityEvent.getType()); taskEntity = (TaskEntity) entityEvent.getEntity(); assertEquals(STR, taskEntity.getName()); Execution cancelMessageExecution = runtimeService.createExecutionQuery().messageEventSubscriptionName(STR) .singleResult(); assertNotNull(cancelMessageExecution); assertEquals(STR, cancelMessageExecution.getActivityId()); runtimeService.messageEventReceived(STR, cancelMessageExecution.getId()); activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.ACTIVITY_CANCELLED, activityEvent.getType()); FlowableActivityCancelledEvent cancelledEvent = (FlowableActivityCancelledEvent) activityEvent; assertEquals("task2", cancelledEvent.getActivityId()); assertEquals(STR, cancelledEvent.getActivityType()); assertEquals(STR, cancelledEvent.getActivityName()); assertEquals(task2Execution.getId(), cancelledEvent.getExecutionId()); activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.ACTIVITY_COMPLETED, activityEvent.getType()); assertEquals(STR, activityEvent.getActivityId()); assertEquals(STR, activityEvent.getActivityType()); assertEquals(boundaryExecution.getId(), activityEvent.getExecutionId()); activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.ACTIVITY_STARTED, activityEvent.getType()); assertEquals(STR, activityEvent.getActivityId()); activityEvent = (FlowableActivityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.ACTIVITY_CANCELLED, activityEvent.getType()); assertEquals("task1", activityEvent.getActivityId()); assertEquals(task1Execution.getId(), activityEvent.getExecutionId()); entityEvent = (FlowableEntityEvent) testListener.getEventsReceived().get(idx++); assertEquals(FlowableEngineEventType.PROCESS_COMPLETED_WITH_TERMINATE_END_EVENT, entityEvent.getType()); assertEquals(12, idx); assertEquals(12, testListener.getEventsReceived().size()); } class UserActivityEventListener extends AbstractFlowableEngineEventListener { private List<FlowableEvent> eventsReceived; public UserActivityEventListener() { super(new HashSet<>(Arrays.asList( FlowableEngineEventType.ACTIVITY_STARTED, FlowableEngineEventType.ACTIVITY_COMPLETED, FlowableEngineEventType.ACTIVITY_CANCELLED, FlowableEngineEventType.TASK_CREATED, FlowableEngineEventType.TASK_COMPLETED, FlowableEngineEventType.PROCESS_STARTED, FlowableEngineEventType.PROCESS_COMPLETED, FlowableEngineEventType.PROCESS_CANCELLED, FlowableEngineEventType.PROCESS_COMPLETED_WITH_TERMINATE_END_EVENT ))); eventsReceived = new ArrayList<>(); } | /**
* User task cancelled by message boundary event.
*/ | User task cancelled by message boundary event | testUserTaskCancelledByMessageBoundaryEvent | {
"repo_name": "zwets/flowable-engine",
"path": "modules/flowable-engine/src/test/java/org/flowable/engine/test/api/event/CancelUserTaskTest.java",
"license": "apache-2.0",
"size": 15715
} | [
"java.util.ArrayList",
"java.util.Arrays",
"java.util.HashSet",
"java.util.List",
"org.flowable.engine.common.api.delegate.event.FlowableEngineEventType",
"org.flowable.engine.common.api.delegate.event.FlowableEntityEvent",
"org.flowable.engine.common.api.delegate.event.FlowableEvent",
"org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener",
"org.flowable.engine.delegate.event.FlowableActivityCancelledEvent",
"org.flowable.engine.delegate.event.FlowableActivityEvent",
"org.flowable.engine.delegate.event.FlowableProcessStartedEvent",
"org.flowable.engine.impl.persistence.entity.ExecutionEntity",
"org.flowable.engine.runtime.Execution",
"org.flowable.engine.runtime.ProcessInstance",
"org.flowable.engine.test.Deployment",
"org.flowable.task.service.impl.persistence.entity.TaskEntity"
] | import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.flowable.engine.common.api.delegate.event.FlowableEngineEventType; import org.flowable.engine.common.api.delegate.event.FlowableEntityEvent; import org.flowable.engine.common.api.delegate.event.FlowableEvent; import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener; import org.flowable.engine.delegate.event.FlowableActivityCancelledEvent; import org.flowable.engine.delegate.event.FlowableActivityEvent; import org.flowable.engine.delegate.event.FlowableProcessStartedEvent; import org.flowable.engine.impl.persistence.entity.ExecutionEntity; import org.flowable.engine.runtime.Execution; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.test.Deployment; import org.flowable.task.service.impl.persistence.entity.TaskEntity; | import java.util.*; import org.flowable.engine.common.api.delegate.event.*; import org.flowable.engine.delegate.event.*; import org.flowable.engine.impl.persistence.entity.*; import org.flowable.engine.runtime.*; import org.flowable.engine.test.*; import org.flowable.task.service.impl.persistence.entity.*; | [
"java.util",
"org.flowable.engine",
"org.flowable.task"
] | java.util; org.flowable.engine; org.flowable.task; | 2,177,157 |
@Nonnull
public static <T, U> Observable<U> selectManyIterable(
@Nonnull final Observable<? extends T> source,
@Nonnull final Func1<? super T, ? extends Iterable<? extends U>> selector) {
return selectManyIterable(source, selector, Functions.<T, U>identitySecond());
} | static <T, U> Observable<U> function( @Nonnull final Observable<? extends T> source, @Nonnull final Func1<? super T, ? extends Iterable<? extends U>> selector) { return selectManyIterable(source, selector, Functions.<T, U>identitySecond()); } | /**
* Transform the given source of Ts into Us in a way that the selector might return zero to multiple elements of Us for a single T.
* The iterable is flattened and submitted to the output
* @param <T> the input element type
* @param <U> the output element type
* @param source the source of Ts
* @param selector the selector to return an Iterable of Us
* @return the observable of Us
*/ | Transform the given source of Ts into Us in a way that the selector might return zero to multiple elements of Us for a single T. The iterable is flattened and submitted to the output | selectManyIterable | {
"repo_name": "akarnokd/reactive4java",
"path": "src/main/java/hu/akarnokd/reactive4java/reactive/Reactive.java",
"license": "apache-2.0",
"size": 367224
} | [
"hu.akarnokd.reactive4java.base.Func1",
"hu.akarnokd.reactive4java.base.Observable",
"hu.akarnokd.reactive4java.util.Functions",
"javax.annotation.Nonnull"
] | import hu.akarnokd.reactive4java.base.Func1; import hu.akarnokd.reactive4java.base.Observable; import hu.akarnokd.reactive4java.util.Functions; import javax.annotation.Nonnull; | import hu.akarnokd.reactive4java.base.*; import hu.akarnokd.reactive4java.util.*; import javax.annotation.*; | [
"hu.akarnokd.reactive4java",
"javax.annotation"
] | hu.akarnokd.reactive4java; javax.annotation; | 1,803,480 |
@Override
public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) {
Object childFeature = feature;
Object childObject = child;
boolean qualify =
childFeature == CorePackage.Literals.INTERACTION_FLOW_ELEMENT__PARAMETERS ||
childFeature == CorePackage.Literals.VIEW_COMPONENT__VIEW_COMPONENT_PARTS;
if (qualify) {
return getString
("_UI_CreateChild_text2",
new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) });
}
return super.getCreateChildText(owner, feature, child, selection);
} | String function(Object owner, Object feature, Object child, Collection<?> selection) { Object childFeature = feature; Object childObject = child; boolean qualify = childFeature == CorePackage.Literals.INTERACTION_FLOW_ELEMENT__PARAMETERS childFeature == CorePackage.Literals.VIEW_COMPONENT__VIEW_COMPONENT_PARTS; if (qualify) { return getString (STR, new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) }); } return super.getCreateChildText(owner, feature, child, selection); } | /**
* This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This returns the label text for <code>org.eclipse.emf.edit.command.CreateChildCommand</code>. | getCreateChildText | {
"repo_name": "ifml/ifml-editor",
"path": "plugins/IFMLEditor.edit/src/IFML/Extensions/provider/DetailsItemProvider.java",
"license": "mit",
"size": 4219
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 2,275,080 |
public static void sendHELO(Client client, int serverProtocolVersion)
throws IOException
{
ByteBuffer rawBuf = allocBuffer(4);
JdwpPacket packet = new JdwpPacket(rawBuf);
ByteBuffer buf = getChunkDataBuf(rawBuf);
buf.putInt(serverProtocolVersion);
finishChunkPacket(packet, CHUNK_HELO, buf.position());
Log.d("ddm-hello", "Sending " + name(CHUNK_HELO)
+ " ID=0x" + Integer.toHexString(packet.getId()));
client.sendAndConsume(packet, mInst);
} | static void function(Client client, int serverProtocolVersion) throws IOException { ByteBuffer rawBuf = allocBuffer(4); JdwpPacket packet = new JdwpPacket(rawBuf); ByteBuffer buf = getChunkDataBuf(rawBuf); buf.putInt(serverProtocolVersion); finishChunkPacket(packet, CHUNK_HELO, buf.position()); Log.d(STR, STR + name(CHUNK_HELO) + STR + Integer.toHexString(packet.getId())); client.sendAndConsume(packet, mInst); } | /**
* Send a HELO request to the client.
*/ | Send a HELO request to the client | sendHELO | {
"repo_name": "consulo/consulo-android",
"path": "tools-base/ddmlib/src/main/java/com/android/ddmlib/HandleHello.java",
"license": "apache-2.0",
"size": 7134
} | [
"java.io.IOException",
"java.nio.ByteBuffer"
] | import java.io.IOException; import java.nio.ByteBuffer; | import java.io.*; import java.nio.*; | [
"java.io",
"java.nio"
] | java.io; java.nio; | 1,893,222 |
public KualiDecimal getTotalDollarAmount(boolean includeInactive, boolean includeBelowTheLine) {
KualiDecimal total = new KualiDecimal(BigDecimal.ZERO);
for (PurApItem item : (List<PurApItem>) getItems()) {
if (item.getPurapDocument() == null) {
item.setPurapDocument(this);
}
ItemType it = item.getItemType();
if ((includeBelowTheLine || it.isLineItemIndicator()) && (includeInactive || PurApItemUtils.checkItemActive(item))) {
KualiDecimal totalAmount = item.getTotalAmount();
KualiDecimal itemTotal = (totalAmount != null) ? totalAmount : KualiDecimal.ZERO;
total = total.add(itemTotal);
}
}
return total;
}
| KualiDecimal function(boolean includeInactive, boolean includeBelowTheLine) { KualiDecimal total = new KualiDecimal(BigDecimal.ZERO); for (PurApItem item : (List<PurApItem>) getItems()) { if (item.getPurapDocument() == null) { item.setPurapDocument(this); } ItemType it = item.getItemType(); if ((includeBelowTheLine it.isLineItemIndicator()) && (includeInactive PurApItemUtils.checkItemActive(item))) { KualiDecimal totalAmount = item.getTotalAmount(); KualiDecimal itemTotal = (totalAmount != null) ? totalAmount : KualiDecimal.ZERO; total = total.add(itemTotal); } } return total; } | /**
* Gets the total dollar amount for this Purchase Order.
*
* @param includeInactive indicates whether inactive items shall be included.
* @param includeBelowTheLine indicates whether below the line items shall be included.
* @return the total dollar amount for this Purchase Order.
*/ | Gets the total dollar amount for this Purchase Order | getTotalDollarAmount | {
"repo_name": "ua-eas/ua-kfs-5.3",
"path": "work/src/org/kuali/kfs/module/purap/document/PurchaseOrderDocument.java",
"license": "agpl-3.0",
"size": 85131
} | [
"java.math.BigDecimal",
"java.util.List",
"org.kuali.kfs.module.purap.businessobject.ItemType",
"org.kuali.kfs.module.purap.businessobject.PurApItem",
"org.kuali.kfs.module.purap.util.PurApItemUtils",
"org.kuali.rice.core.api.util.type.KualiDecimal"
] | import java.math.BigDecimal; import java.util.List; import org.kuali.kfs.module.purap.businessobject.ItemType; import org.kuali.kfs.module.purap.businessobject.PurApItem; import org.kuali.kfs.module.purap.util.PurApItemUtils; import org.kuali.rice.core.api.util.type.KualiDecimal; | import java.math.*; import java.util.*; import org.kuali.kfs.module.purap.businessobject.*; import org.kuali.kfs.module.purap.util.*; import org.kuali.rice.core.api.util.type.*; | [
"java.math",
"java.util",
"org.kuali.kfs",
"org.kuali.rice"
] | java.math; java.util; org.kuali.kfs; org.kuali.rice; | 183,895 |
public BigDecimal getHours();
| BigDecimal function(); | /**
* The hours associated with the TimeBlock
*
* <p>
* hours of a TimeBlock
* <p>
*
* @return hours for TimeBlock
*/ | The hours associated with the TimeBlock hours of a TimeBlock | getHours | {
"repo_name": "kuali/kpme",
"path": "tk-lm/api/src/main/java/org/kuali/kpme/tklm/api/time/timeblock/TimeBlockContract.java",
"license": "apache-2.0",
"size": 11355
} | [
"java.math.BigDecimal"
] | import java.math.BigDecimal; | import java.math.*; | [
"java.math"
] | java.math; | 2,805,914 |
public void flushAndClose() throws IOException {
if (isClosed.get() == false) {
logger.trace("flushAndClose now acquire writeLock");
try (ReleasableLock lock = writeLock.acquire()) {
logger.trace("flushAndClose now acquired writeLock");
try {
logger.debug("flushing shard on close - this might take some time to sync files to disk");
try {
flush(); // TODO we might force a flush in the future since we have the write lock already even though recoveries are running.
} catch (FlushNotAllowedEngineException ex) {
logger.debug("flush not allowed during flushAndClose - skipping");
} catch (EngineClosedException ex) {
logger.debug("engine already closed - skipping flushAndClose");
}
} finally {
close(); // double close is not a problem
}
}
}
} | void function() throws IOException { if (isClosed.get() == false) { logger.trace(STR); try (ReleasableLock lock = writeLock.acquire()) { logger.trace(STR); try { logger.debug(STR); try { flush(); } catch (FlushNotAllowedEngineException ex) { logger.debug(STR); } catch (EngineClosedException ex) { logger.debug(STR); } } finally { close(); } } } } | /**
* Flush the engine (committing segments to disk and truncating the
* translog) and close it.
*/ | Flush the engine (committing segments to disk and truncating the translog) and close it | flushAndClose | {
"repo_name": "zhiqinghuang/elasticsearch",
"path": "core/src/main/java/org/elasticsearch/index/engine/Engine.java",
"license": "apache-2.0",
"size": 41811
} | [
"java.io.IOException",
"org.elasticsearch.common.util.concurrent.ReleasableLock"
] | import java.io.IOException; import org.elasticsearch.common.util.concurrent.ReleasableLock; | import java.io.*; import org.elasticsearch.common.util.concurrent.*; | [
"java.io",
"org.elasticsearch.common"
] | java.io; org.elasticsearch.common; | 580,176 |
public void setUpController(ControllerMap controller) {
controller.clearButtons();
controller.getButton(collector_IN)
.whenPressed(new SetCollectorPower(RobotMap.Collector.inPower))
.whenReleased(new SetCollectorPower());
controller.getButton(collector_OUT)
.whenPressed(new SetCollectorPower(RobotMap.Collector.outPower))
.whenReleased(new SetCollectorPower());
controller.getButton(collectorAngler_UP)
.whenPressed(new SetStateUp());
controller.getButton(collectorAngler_DOWN)
.whenPressed(new SetStateDown());
controller.getButton(shooter_START)
.whenPressed(new PreFire(72.7));
controller.getButton(shooter_START_ALT)
.whenPressed(new PreFire(69));
controller.getButton(shooter_STOP)
.whenPressed(new SetShooterPower());
controller.getButton(shooter_FIRE)
.whenPressed(Fire.getInstance())
.whenReleased(new StopFire());
controller.getButton(shooter_EMERGENCY_RELEASE)
.whenPressed(new EmergencyRelease())
.whenReleased(new EndEmergencyRelease());
if (controller == driver) {
controller.getButton(drive_DIRECTION_TOGGLE)
.whenPressed(new ToggleDriveDirection());
}
controller.getButton(vision_SINGLE_ALIGN)
.whenPressed(new RotateUsingVision(4));
controller.getButton(vision_CONT_ALIGN)
.whenPressed(new ToggleAlignVision(true))
.whenReleased(new ToggleAlignVision(false));
controller.getButton(flashlight_TOGGLE)
.whenPressed(new SetFlashlight());
if (controller == operator) {
controller.getMultiButton(ControllerMap.Key.BACK, ControllerMap.Key.START)
.whenPressed(new SetEndGame(true));
}
} | void function(ControllerMap controller) { controller.clearButtons(); controller.getButton(collector_IN) .whenPressed(new SetCollectorPower(RobotMap.Collector.inPower)) .whenReleased(new SetCollectorPower()); controller.getButton(collector_OUT) .whenPressed(new SetCollectorPower(RobotMap.Collector.outPower)) .whenReleased(new SetCollectorPower()); controller.getButton(collectorAngler_UP) .whenPressed(new SetStateUp()); controller.getButton(collectorAngler_DOWN) .whenPressed(new SetStateDown()); controller.getButton(shooter_START) .whenPressed(new PreFire(72.7)); controller.getButton(shooter_START_ALT) .whenPressed(new PreFire(69)); controller.getButton(shooter_STOP) .whenPressed(new SetShooterPower()); controller.getButton(shooter_FIRE) .whenPressed(Fire.getInstance()) .whenReleased(new StopFire()); controller.getButton(shooter_EMERGENCY_RELEASE) .whenPressed(new EmergencyRelease()) .whenReleased(new EndEmergencyRelease()); if (controller == driver) { controller.getButton(drive_DIRECTION_TOGGLE) .whenPressed(new ToggleDriveDirection()); } controller.getButton(vision_SINGLE_ALIGN) .whenPressed(new RotateUsingVision(4)); controller.getButton(vision_CONT_ALIGN) .whenPressed(new ToggleAlignVision(true)) .whenReleased(new ToggleAlignVision(false)); controller.getButton(flashlight_TOGGLE) .whenPressed(new SetFlashlight()); if (controller == operator) { controller.getMultiButton(ControllerMap.Key.BACK, ControllerMap.Key.START) .whenPressed(new SetEndGame(true)); } } | /**
* Setup Single Controller Control
*/ | Setup Single Controller Control | setUpController | {
"repo_name": "frc868/2016-Vizzini",
"path": "src/com/techhounds/OI.java",
"license": "mit",
"size": 10352
} | [
"com.techhounds.commands.EmergencyRelease",
"com.techhounds.commands.EndEmergencyRelease",
"com.techhounds.commands.SetEndGame",
"com.techhounds.commands.SetFlashlight",
"com.techhounds.commands.angler.SetStateDown",
"com.techhounds.commands.angler.SetStateUp",
"com.techhounds.commands.auton.RotateUsingVision",
"com.techhounds.commands.collector.SetCollectorPower",
"com.techhounds.commands.drive.ToggleDriveDirection",
"com.techhounds.commands.shooter.Fire",
"com.techhounds.commands.shooter.PreFire",
"com.techhounds.commands.shooter.SetShooterPower",
"com.techhounds.commands.shooter.StopFire",
"com.techhounds.commands.shooter.ToggleAlignVision",
"com.techhounds.lib.hid.ControllerMap"
] | import com.techhounds.commands.EmergencyRelease; import com.techhounds.commands.EndEmergencyRelease; import com.techhounds.commands.SetEndGame; import com.techhounds.commands.SetFlashlight; import com.techhounds.commands.angler.SetStateDown; import com.techhounds.commands.angler.SetStateUp; import com.techhounds.commands.auton.RotateUsingVision; import com.techhounds.commands.collector.SetCollectorPower; import com.techhounds.commands.drive.ToggleDriveDirection; import com.techhounds.commands.shooter.Fire; import com.techhounds.commands.shooter.PreFire; import com.techhounds.commands.shooter.SetShooterPower; import com.techhounds.commands.shooter.StopFire; import com.techhounds.commands.shooter.ToggleAlignVision; import com.techhounds.lib.hid.ControllerMap; | import com.techhounds.commands.*; import com.techhounds.commands.angler.*; import com.techhounds.commands.auton.*; import com.techhounds.commands.collector.*; import com.techhounds.commands.drive.*; import com.techhounds.commands.shooter.*; import com.techhounds.lib.hid.*; | [
"com.techhounds.commands",
"com.techhounds.lib"
] | com.techhounds.commands; com.techhounds.lib; | 2,327,046 |
static boolean isSimpleOperatorType(int type) {
switch (type) {
case Token.ADD:
case Token.BITAND:
case Token.BITNOT:
case Token.BITOR:
case Token.BITXOR:
case Token.COMMA:
case Token.DIV:
case Token.EQ:
case Token.GE:
case Token.GETELEM:
case Token.GETPROP:
case Token.GT:
case Token.INSTANCEOF:
case Token.LE:
case Token.LSH:
case Token.LT:
case Token.MOD:
case Token.MUL:
case Token.NE:
case Token.NOT:
case Token.RSH:
case Token.SHEQ:
case Token.SHNE:
case Token.SUB:
case Token.TYPEOF:
case Token.VOID:
case Token.POS:
case Token.NEG:
case Token.URSH:
return true;
default:
return false;
}
} | static boolean isSimpleOperatorType(int type) { switch (type) { case Token.ADD: case Token.BITAND: case Token.BITNOT: case Token.BITOR: case Token.BITXOR: case Token.COMMA: case Token.DIV: case Token.EQ: case Token.GE: case Token.GETELEM: case Token.GETPROP: case Token.GT: case Token.INSTANCEOF: case Token.LE: case Token.LSH: case Token.LT: case Token.MOD: case Token.MUL: case Token.NE: case Token.NOT: case Token.RSH: case Token.SHEQ: case Token.SHNE: case Token.SUB: case Token.TYPEOF: case Token.VOID: case Token.POS: case Token.NEG: case Token.URSH: return true; default: return false; } } | /**
* A "simple" operator is one whose children are expressions,
* has no direct side-effects (unlike '+='), and has no
* conditional aspects (unlike '||').
*/ | A "simple" operator is one whose children are expressions, has no direct side-effects (unlike '+='), and has no conditional aspects (unlike '||') | isSimpleOperatorType | {
"repo_name": "nuxleus/closure-compiler",
"path": "src/com/google/javascript/jscomp/NodeUtil.java",
"license": "apache-2.0",
"size": 89782
} | [
"com.google.javascript.rhino.Token"
] | import com.google.javascript.rhino.Token; | import com.google.javascript.rhino.*; | [
"com.google.javascript"
] | com.google.javascript; | 193,502 |
public static byte[] getCFFData(FontFileReader fontFile) throws IOException {
byte[] cff = fontFile.getAllBytes();
CFFDataInput input = new CFFDataInput(fontFile.getAllBytes());
input.readBytes(4); //OTTO
short numTables = input.readShort();
input.readShort(); //searchRange
input.readShort(); //entrySelector
input.readShort(); //rangeShift
for (int q = 0; q < numTables; q++) {
String tagName = new String(input.readBytes(4));
readLong(input); //Checksum
long offset = readLong(input);
long length = readLong(input);
if (tagName.equals("CFF ")) {
cff = new byte[(int)length];
System.arraycopy(fontFile.getAllBytes(), (int)offset, cff, 0, cff.length);
break;
}
}
return cff;
} | static byte[] function(FontFileReader fontFile) throws IOException { byte[] cff = fontFile.getAllBytes(); CFFDataInput input = new CFFDataInput(fontFile.getAllBytes()); input.readBytes(4); short numTables = input.readShort(); input.readShort(); input.readShort(); input.readShort(); for (int q = 0; q < numTables; q++) { String tagName = new String(input.readBytes(4)); readLong(input); long offset = readLong(input); long length = readLong(input); if (tagName.equals(STR)) { cff = new byte[(int)length]; System.arraycopy(fontFile.getAllBytes(), (int)offset, cff, 0, cff.length); break; } } return cff; } | /**
* Reads the CFFData from a given font file
* @param fontFile The font file being read
* @return The byte data found in the CFF table
*/ | Reads the CFFData from a given font file | getCFFData | {
"repo_name": "StrategyObject/fop",
"path": "src/java/org/apache/fop/fonts/truetype/OTFFile.java",
"license": "apache-2.0",
"size": 5800
} | [
"java.io.IOException",
"org.apache.fontbox.cff.CFFDataInput"
] | import java.io.IOException; import org.apache.fontbox.cff.CFFDataInput; | import java.io.*; import org.apache.fontbox.cff.*; | [
"java.io",
"org.apache.fontbox"
] | java.io; org.apache.fontbox; | 489,990 |
@SuppressWarnings("deprecation")
public static Concept searchConcept(String name) {
Concept concept = Context.getConceptService().getConcept(name);
if (concept != null) {
return concept;
} else {
List<ConceptWord> cws = Context.getConceptService().findConcepts(
name, new Locale("en"), false);
if (!cws.isEmpty())
return cws.get(0).getConcept();
}
return null;
} | @SuppressWarnings(STR) static Concept function(String name) { Concept concept = Context.getConceptService().getConcept(name); if (concept != null) { return concept; } else { List<ConceptWord> cws = Context.getConceptService().findConcepts( name, new Locale("en"), false); if (!cws.isEmpty()) return cws.get(0).getConcept(); } return null; } | /**
* Search for concept using name
*
* @param name
* @return
*/ | Search for concept using name | searchConcept | {
"repo_name": "kenyaehrs/laboratory",
"path": "omod/src/main/java/org/openmrs/module/laboratory/web/util/LaboratoryUtil.java",
"license": "gpl-2.0",
"size": 16878
} | [
"java.util.List",
"java.util.Locale",
"org.openmrs.Concept",
"org.openmrs.ConceptWord",
"org.openmrs.api.context.Context"
] | import java.util.List; import java.util.Locale; import org.openmrs.Concept; import org.openmrs.ConceptWord; import org.openmrs.api.context.Context; | import java.util.*; import org.openmrs.*; import org.openmrs.api.context.*; | [
"java.util",
"org.openmrs",
"org.openmrs.api"
] | java.util; org.openmrs; org.openmrs.api; | 299,632 |
public void setDeclaration(BodyDeclaration declaration) {
fDeclaration = declaration;
} | void function(BodyDeclaration declaration) { fDeclaration = declaration; } | /**
* Sets the old member declaration. Must always be called prior to prepareDelegate().
*
* @param declaration the BodyDeclaration
*/ | Sets the old member declaration. Must always be called prior to prepareDelegate() | setDeclaration | {
"repo_name": "sleshchenko/che",
"path": "plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/src/main/java/org/eclipse/jdt/internal/corext/refactoring/delegates/DelegateCreator.java",
"license": "epl-1.0",
"size": 16372
} | [
"org.eclipse.jdt.core.dom.BodyDeclaration"
] | import org.eclipse.jdt.core.dom.BodyDeclaration; | import org.eclipse.jdt.core.dom.*; | [
"org.eclipse.jdt"
] | org.eclipse.jdt; | 576,036 |
public void setValues(String values) {
StringTokenizer st = new StringTokenizer(values);
while (st.hasMoreTokens()) {
String value = st.nextToken();
model.addElement(ResourceManager.getProperty(value));
}
} | void function(String values) { StringTokenizer st = new StringTokenizer(values); while (st.hasMoreTokens()) { String value = st.nextToken(); model.addElement(ResourceManager.getProperty(value)); } } | /**
* DOCUMENT ME!
*
* @param values DOCUMENT ME!
*/ | DOCUMENT ME | setValues | {
"repo_name": "tonivade/tedit",
"path": "src/tk/tomby/tedit/gui/editors/MultiEditor.java",
"license": "gpl-2.0",
"size": 4336
} | [
"java.util.StringTokenizer",
"tk.tomby.tedit.services.ResourceManager"
] | import java.util.StringTokenizer; import tk.tomby.tedit.services.ResourceManager; | import java.util.*; import tk.tomby.tedit.services.*; | [
"java.util",
"tk.tomby.tedit"
] | java.util; tk.tomby.tedit; | 2,881,057 |
public void attachView(View child, int index) {
attachView(child, index, (LayoutParams) child.getLayoutParams());
} | void function(View child, int index) { attachView(child, index, (LayoutParams) child.getLayoutParams()); } | /**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
* @param index Intended child index for child
*/ | Reattach a previously <code>#detachView(android.view.View) detached</code> view. This method should not be used to reattach views that were previously <code>#detachAndScrapView(android.view.View, RecyclerView.Recycler)</code> scrapped} | attachView | {
"repo_name": "rugram/RuGram",
"path": "TMessagesProj/src/main/java/org/telegram/android/support/widget/RecyclerView.java",
"license": "gpl-2.0",
"size": 416898
} | [
"android.view.View"
] | import android.view.View; | import android.view.*; | [
"android.view"
] | android.view; | 434,624 |
void setComponentResolver(ComponentResolver componentResolver); | void setComponentResolver(ComponentResolver componentResolver); | /**
* Sets a custom {@link ComponentResolver} to use.
*/ | Sets a custom <code>ComponentResolver</code> to use | setComponentResolver | {
"repo_name": "mcollovati/camel",
"path": "core/camel-api/src/main/java/org/apache/camel/ExtendedCamelContext.java",
"license": "apache-2.0",
"size": 23401
} | [
"org.apache.camel.spi.ComponentResolver"
] | import org.apache.camel.spi.ComponentResolver; | import org.apache.camel.spi.*; | [
"org.apache.camel"
] | org.apache.camel; | 391,282 |
public static Builder builder(final SamHeader header) {
checkNotNull(header);
final Builder builder = new Builder();
header.getHeaderLineOpt().ifPresent(hl -> builder.withHeaderLine(hl));
return builder
.withSequenceHeaderLines(header.getSequenceHeaderLines())
.withReadGroupHeaderLines(header.getReadGroupHeaderLines())
.withProgramHeaderLines(header.getProgramHeaderLines())
.withCommentHeaderLines(header.getCommentHeaderLines());
}
public static final class Builder {
private SamHeaderLine headerLine;
private List<SamSequenceHeaderLine> sequenceHeaderLines = new ArrayList<SamSequenceHeaderLine>();
private List<SamReadGroupHeaderLine> readGroupHeaderLines = new ArrayList<SamReadGroupHeaderLine>();
private List<SamProgramHeaderLine> programHeaderLines = new ArrayList<SamProgramHeaderLine>();
private List<SamCommentHeaderLine> commentHeaderLines = new ArrayList<SamCommentHeaderLine>();
private Builder() {
// empty
} | static Builder function(final SamHeader header) { checkNotNull(header); final Builder builder = new Builder(); header.getHeaderLineOpt().ifPresent(hl -> builder.withHeaderLine(hl)); return builder .withSequenceHeaderLines(header.getSequenceHeaderLines()) .withReadGroupHeaderLines(header.getReadGroupHeaderLines()) .withProgramHeaderLines(header.getProgramHeaderLines()) .withCommentHeaderLines(header.getCommentHeaderLines()); } public static final class Builder { private SamHeaderLine headerLine; private List<SamSequenceHeaderLine> sequenceHeaderLines = new ArrayList<SamSequenceHeaderLine>(); private List<SamReadGroupHeaderLine> readGroupHeaderLines = new ArrayList<SamReadGroupHeaderLine>(); private List<SamProgramHeaderLine> programHeaderLines = new ArrayList<SamProgramHeaderLine>(); private List<SamCommentHeaderLine> commentHeaderLines = new ArrayList<SamCommentHeaderLine>(); private Builder() { } | /**
* Return a new SAM header builder populated with the fields in the specified SAM header.
*
* @param header SAM header, must not be null
* @return a new SAM header builder populated with the fields in the specified SAM header
*/ | Return a new SAM header builder populated with the fields in the specified SAM header | builder | {
"repo_name": "heuermh/dishevelled-bio",
"path": "alignment/src/main/java/org/dishevelled/bio/alignment/sam/SamHeader.java",
"license": "lgpl-3.0",
"size": 18194
} | [
"com.google.common.base.Preconditions",
"java.util.ArrayList",
"java.util.List"
] | import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.List; | import com.google.common.base.*; import java.util.*; | [
"com.google.common",
"java.util"
] | com.google.common; java.util; | 757,030 |
RaptureExchange xFanout = new RaptureExchange();
xFanout.setName(PipelineConstants.FANOUT_EXCHANGE);
xFanout.setExchangeType(RaptureExchangeType.FANOUT);
xFanout.setDomain(PipelineConstants.DEFAULT_EXCHANGE_DOMAIN);
List<RaptureExchangeQueue> qsFanout = new LinkedList<>();
RaptureExchangeQueue qBroadcast = new RaptureExchangeQueue();
qBroadcast.setName(PipelineConstants.ANONYMOUS_PREFIX + IDGenerator.getUUID());
qBroadcast.setRouteBindings(new ArrayList<String>());
qsFanout.add(qBroadcast);
xFanout.setQueueBindings(qsFanout);
return xFanout;
} | RaptureExchange xFanout = new RaptureExchange(); xFanout.setName(PipelineConstants.FANOUT_EXCHANGE); xFanout.setExchangeType(RaptureExchangeType.FANOUT); xFanout.setDomain(PipelineConstants.DEFAULT_EXCHANGE_DOMAIN); List<RaptureExchangeQueue> qsFanout = new LinkedList<>(); RaptureExchangeQueue qBroadcast = new RaptureExchangeQueue(); qBroadcast.setName(PipelineConstants.ANONYMOUS_PREFIX + IDGenerator.getUUID()); qBroadcast.setRouteBindings(new ArrayList<String>()); qsFanout.add(qBroadcast); xFanout.setQueueBindings(qsFanout); return xFanout; } | /**
* Create the standard fanout exchange configuration, and fill it in so it
* contains an anonymous queue for this server. This will allow a server to
* bind to the fanout exchange and receive broadcast messages
*
* @param category
* @return
*/ | Create the standard fanout exchange configuration, and fill it in so it contains an anonymous queue for this server. This will allow a server to bind to the fanout exchange and receive broadcast messages | createStandardFanout | {
"repo_name": "amkimian/Rapture",
"path": "Libs/RaptureCore/src/main/java/rapture/kernel/pipeline/ExchangeConfigFactory.java",
"license": "mit",
"size": 4283
} | [
"java.util.ArrayList",
"java.util.LinkedList",
"java.util.List"
] | import java.util.ArrayList; import java.util.LinkedList; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,837,069 |
public void flush() throws IOException {
if (debug > 1) {
System.out.println("flush() @ CompressionResponseStream");
}
if (closed) {
throw new IOException("Cannot flush a closed output stream");
}
if (gzipstream != null) {
gzipstream.flush();
}
} | void function() throws IOException { if (debug > 1) { System.out.println(STR); } if (closed) { throw new IOException(STR); } if (gzipstream != null) { gzipstream.flush(); } } | /**
* Flush any buffered data for this output stream, which also causes the
* response to be committed.
*/ | Flush any buffered data for this output stream, which also causes the response to be committed | flush | {
"repo_name": "simeshev/parabuild-ci",
"path": "3rdparty/tomcat4131/webapps/examples/WEB-INF/classes/compressionFilters/CompressionResponseStream.java",
"license": "lgpl-3.0",
"size": 8557
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 899,125 |
//-----------------------------------------------------------------------
public PriceIndexCalculationMethod getIndexCalculationMethod() {
return indexCalculationMethod;
} | PriceIndexCalculationMethod function() { return indexCalculationMethod; } | /**
* Gets reference price index calculation method.
* <p>
* This specifies how the reference index calculation occurs.
* <p>
* This will default to 'Monthly' if not specified.
* @return the value of the property, not null
*/ | Gets reference price index calculation method. This specifies how the reference index calculation occurs. This will default to 'Monthly' if not specified | getIndexCalculationMethod | {
"repo_name": "ChinaQuants/Strata",
"path": "modules/product/src/main/java/com/opengamma/strata/product/swap/type/InflationRateSwapLegConvention.java",
"license": "apache-2.0",
"size": 28364
} | [
"com.opengamma.strata.product.swap.PriceIndexCalculationMethod"
] | import com.opengamma.strata.product.swap.PriceIndexCalculationMethod; | import com.opengamma.strata.product.swap.*; | [
"com.opengamma.strata"
] | com.opengamma.strata; | 80,192 |
public boolean isReopenEnrollmentAuthorized(ProtocolForm protocolForm); | boolean function(ProtocolForm protocolForm); | /**
* This method is to check whether user is authorized to reopen protocol
* Also apply rules if any.
* @param protocolForm
* @return
*/ | This method is to check whether user is authorized to reopen protocol Also apply rules if any | isReopenEnrollmentAuthorized | {
"repo_name": "sanjupolus/kc-coeus-1508.3",
"path": "coeus-impl/src/main/java/org/kuali/kra/irb/actions/IrbProtocolActionRequestService.java",
"license": "agpl-3.0",
"size": 17700
} | [
"org.kuali.kra.irb.ProtocolForm"
] | import org.kuali.kra.irb.ProtocolForm; | import org.kuali.kra.irb.*; | [
"org.kuali.kra"
] | org.kuali.kra; | 2,214,187 |
public Observable<ServiceResponseWithHeaders<StreamingJobInner, StreamingJobsGetHeaders>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String jobName, String expand) {
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 (jobName == null) {
throw new IllegalArgumentException("Parameter jobName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
} | Observable<ServiceResponseWithHeaders<StreamingJobInner, StreamingJobsGetHeaders>> function(String resourceGroupName, String jobName, String expand) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException(STR); } if (resourceGroupName == null) { throw new IllegalArgumentException(STR); } if (jobName == null) { throw new IllegalArgumentException(STR); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException(STR); } | /**
* Gets details about the specified streaming job.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
* @param jobName The name of the streaming job.
* @param expand The $expand OData query parameter. This is a comma-separated list of additional streaming job properties to include in the response, beyond the default set returned when this parameter is absent. The default set is all streaming job properties other than 'inputs', 'transformation', 'outputs', and 'functions'.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the StreamingJobInner object
*/ | Gets details about the specified streaming job | getByResourceGroupWithServiceResponseAsync | {
"repo_name": "hovsepm/azure-sdk-for-java",
"path": "streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/StreamingJobsInner.java",
"license": "mit",
"size": 143599
} | [
"com.microsoft.azure.management.streamanalytics.v2016_03_01.StreamingJobsGetHeaders",
"com.microsoft.rest.ServiceResponseWithHeaders"
] | import com.microsoft.azure.management.streamanalytics.v2016_03_01.StreamingJobsGetHeaders; import com.microsoft.rest.ServiceResponseWithHeaders; | import com.microsoft.azure.management.streamanalytics.v2016_03_01.*; import com.microsoft.rest.*; | [
"com.microsoft.azure",
"com.microsoft.rest"
] | com.microsoft.azure; com.microsoft.rest; | 1,389,115 |
public void setAlign(ElementAlign align) {
getConfiguration().setAlign(align);
} | void function(ElementAlign align) { getConfiguration().setAlign(align); } | /**
* Sets the tick alignment along the axis.
*
* @param align the tick alignment along the axis
*/ | Sets the tick alignment along the axis | setAlign | {
"repo_name": "pepstock-org/Charba",
"path": "src/org/pepstock/charba/client/configuration/CartesianTick.java",
"license": "apache-2.0",
"size": 8345
} | [
"org.pepstock.charba.client.enums.ElementAlign"
] | import org.pepstock.charba.client.enums.ElementAlign; | import org.pepstock.charba.client.enums.*; | [
"org.pepstock.charba"
] | org.pepstock.charba; | 1,477,857 |
private void timedOut() {
Logger.global.finer("timed out");
fCurrentTimeoutState.setTimedOut(true);
fDisplay.wake(); // wake up call!
if (fKeepRunningOnTimeout)
checkedTransition(RUNNING, IDLE);
else
checkedTransition(RUNNING, STOPPED);
} | void function() { Logger.global.finer(STR); fCurrentTimeoutState.setTimedOut(true); fDisplay.wake(); if (fKeepRunningOnTimeout) checkedTransition(RUNNING, IDLE); else checkedTransition(RUNNING, STOPPED); } | /**
* Sets the timed out flag and wakes up the display. Transitions to
* <code>IDLE</code> (if in keep-running mode) or
* <code>STOPPED</code>.
*/ | Sets the timed out flag and wakes up the display. Transitions to <code>IDLE</code> (if in keep-running mode) or <code>STOPPED</code> | timedOut | {
"repo_name": "maxeler/eclipse",
"path": "eclipse.jdt.ui/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/performance/DisplayWaiter.java",
"license": "epl-1.0",
"size": 11566
} | [
"java.util.logging.Logger"
] | import java.util.logging.Logger; | import java.util.logging.*; | [
"java.util"
] | java.util; | 2,721,880 |
@Nullable
@Override
public Result<String> findByPrimaryKey(@NotNull final String id)
{
return findByPrimaryKey(id, getResultList());
} | Result<String> function(@NotNull final String id) { return findByPrimaryKey(id, getResultList()); } | /**
* Retrieves the {@link Result} matching given id.
* @param id the result id.
* @return such result.
*/ | Retrieves the <code>Result</code> matching given id | findByPrimaryKey | {
"repo_name": "rydnr/queryj-rt",
"path": "queryj-test/src/main/java/org/acmsl/queryj/test/sql/CucumberSqlResultDAO.java",
"license": "gpl-2.0",
"size": 5945
} | [
"org.acmsl.queryj.customsql.Result",
"org.jetbrains.annotations.NotNull"
] | import org.acmsl.queryj.customsql.Result; import org.jetbrains.annotations.NotNull; | import org.acmsl.queryj.customsql.*; import org.jetbrains.annotations.*; | [
"org.acmsl.queryj",
"org.jetbrains.annotations"
] | org.acmsl.queryj; org.jetbrains.annotations; | 1,952,919 |
private void updateContactInDb(Contact contact, ContentValues updateVals) {
SQLiteDatabase db = this.databaseHelper.getReadableDatabase();
String selection = DatabaseEntry.COLUMN_NAME_NAME + " LIKE ?";
String[] selectionArgs = { contact.getName() };
new UpdateTask(db, updateVals, selection, selectionArgs).execute();
} | void function(Contact contact, ContentValues updateVals) { SQLiteDatabase db = this.databaseHelper.getReadableDatabase(); String selection = DatabaseEntry.COLUMN_NAME_NAME + STR; String[] selectionArgs = { contact.getName() }; new UpdateTask(db, updateVals, selection, selectionArgs).execute(); } | /**
* update the given contact in the database with given vals. Important note: we select contacts
* in the database on their name rather then phone since if we have multiple numbers for a user
* (i.e. Eric Jaugey -> 5192932939 and 3943932323) we want to star both those numbers.
* @param contact the contact to update in the database
* @param updateVals the vals to update the contact with
*/ | update the given contact in the database with given vals. Important note: we select contacts in the database on their name rather then phone since if we have multiple numbers for a user (i.e. Eric Jaugey -> 5192932939 and 3943932323) we want to star both those numbers | updateContactInDb | {
"repo_name": "steinbachr/spitly-android",
"path": "app/src/main/java/me/iambob/spitly/database/Database.java",
"license": "mit",
"size": 8404
} | [
"android.content.ContentValues",
"android.database.sqlite.SQLiteDatabase",
"me.iambob.spitly.database.DatabaseContract",
"me.iambob.spitly.models.Contact"
] | import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import me.iambob.spitly.database.DatabaseContract; import me.iambob.spitly.models.Contact; | import android.content.*; import android.database.sqlite.*; import me.iambob.spitly.database.*; import me.iambob.spitly.models.*; | [
"android.content",
"android.database",
"me.iambob.spitly"
] | android.content; android.database; me.iambob.spitly; | 693,421 |
private Bitmap loadBitmap(int resource) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeResource(getResources(), resource, options);
} | Bitmap function(int resource) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; return BitmapFactory.decodeResource(getResources(), resource, options); } | /**
* Helper to load Bitmap from resource
*/ | Helper to load Bitmap from resource | loadBitmap | {
"repo_name": "android/renderscript-samples",
"path": "BasicRenderScript/Application/src/main/java/com/example/android/basicrenderscript/MainActivity.java",
"license": "apache-2.0",
"size": 6085
} | [
"android.graphics.Bitmap",
"android.graphics.BitmapFactory"
] | import android.graphics.Bitmap; import android.graphics.BitmapFactory; | import android.graphics.*; | [
"android.graphics"
] | android.graphics; | 716,347 |
@Override
public void delete(final KeyObject inKey, final boolean inCommit) throws SQLException { // NOPMD
// intentionally left empty
}
| void function(final KeyObject inKey, final boolean inCommit) throws SQLException { } | /** No implementation provided.
*
* @see org.hip.kernel.bom.DomainObjectHome#delete(org.hip.kernel.bom.KeyObject, boolean) */ | No implementation provided | delete | {
"repo_name": "aktion-hip/viffw",
"path": "org.hip.viffw/src/org/hip/kernel/bom/directory/LDAPObjectHome.java",
"license": "lgpl-2.1",
"size": 27664
} | [
"java.sql.SQLException",
"org.hip.kernel.bom.KeyObject"
] | import java.sql.SQLException; import org.hip.kernel.bom.KeyObject; | import java.sql.*; import org.hip.kernel.bom.*; | [
"java.sql",
"org.hip.kernel"
] | java.sql; org.hip.kernel; | 2,614,857 |
public void centerMapGlobe(Coordinates targetLocation) {
((NavigatorWindow) getToolWindow(NavigatorWindow.NAME)).updateCoords(targetLocation);
openToolWindow(NavigatorWindow.NAME);
} | void function(Coordinates targetLocation) { ((NavigatorWindow) getToolWindow(NavigatorWindow.NAME)).updateCoords(targetLocation); openToolWindow(NavigatorWindow.NAME); } | /**
* Centers the map and the globe on given coordinates. Also opens the map tool
* if it's closed.
*
* @param targetLocation the new center location
*/ | Centers the map and the globe on given coordinates. Also opens the map tool if it's closed | centerMapGlobe | {
"repo_name": "mars-sim/mars-sim",
"path": "mars-sim-javafx/src/main/java/org/mars_sim/javafx/MainDesktopPane.java",
"license": "gpl-3.0",
"size": 43014
} | [
"org.mars_sim.msp.core.Coordinates",
"org.mars_sim.msp.ui.swing.tool.navigator.NavigatorWindow"
] | import org.mars_sim.msp.core.Coordinates; import org.mars_sim.msp.ui.swing.tool.navigator.NavigatorWindow; | import org.mars_sim.msp.core.*; import org.mars_sim.msp.ui.swing.tool.navigator.*; | [
"org.mars_sim.msp"
] | org.mars_sim.msp; | 2,090,326 |
public static String encodeQueryParam(String queryParam, String encoding) throws UnsupportedEncodingException {
return encode(queryParam, encoding, QUERY_PARAM);
} | static String function(String queryParam, String encoding) throws UnsupportedEncodingException { return encode(queryParam, encoding, QUERY_PARAM); } | /**
* Encodes the given URI query parameter.
*
* @param query the query parameter to be encoded
* @param encoding the character encoding to encode to
* @return the encoded query parameter
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/ | Encodes the given URI query parameter | encodeQueryParam | {
"repo_name": "sosilent/euca",
"path": "clc/modules/www/test-gwt/src/com/eucalyptus/webui/server/UriUtils.java",
"license": "gpl-3.0",
"size": 13496
} | [
"java.io.UnsupportedEncodingException"
] | import java.io.UnsupportedEncodingException; | import java.io.*; | [
"java.io"
] | java.io; | 52,249 |
private void importData(Contact contact,
String prefix, String[] attributes, String data, Object listHandle) {
int attr = parseAttributes(attributes);
int field = VCardSupport.getFieldCode(prefix);
if (field == -1 && prefix.equals(getClassProperty())) {
field = Contact.CLASS;
}
if (!PIMHandler.getInstance().isSupportedField(listHandle, field)) {
return;
}
switch (field) {
case Contact.FORMATTED_NAME:
case Contact.FORMATTED_ADDR:
case Contact.TEL:
case Contact.EMAIL:
case Contact.TITLE:
case Contact.ORG:
case Contact.NICKNAME:
case Contact.NOTE:
case Contact.UID:
case Contact.URL: {
String sdata = FormatSupport.parseString(attributes, data);
contact.addString(field, attr, sdata);
break;
}
case Contact.NAME:
case Contact.ADDR: {
String[] elements =
FormatSupport.parseStringArray(attributes, data);
int elementCount = PIMHandler.getInstance()
.getStringArraySize(listHandle, field);
if (elements.length != elementCount) {
String[] a = new String[elementCount];
System.arraycopy(elements, 0, a, 0,
Math.min(elements.length, elementCount));
elements = a;
}
contact.addStringArray(field, attr, elements);
break;
}
case Contact.BIRTHDAY:
case Contact.REVISION: {
int dateLen = data.length();
// end date is either date in yyyyMMdd format or
// date/time in yyyymmddThhmmss(Z).
long date = (dateLen < 15) ?
PIMHandler.getInstance().parseDate(data) :
PIMHandler.getInstance().parseDateTime(data);
contact.addDate(field, attr, date);
break;
}
case Contact.PHOTO: {
String valueType =
FormatSupport.getAttributeValue(attributes, "VALUE=", null);
if (valueType == null) {
// binary data represented in "B" encoded format
byte[] bData = data.getBytes();
if (bData.length != 0) {
contact.addBinary(Contact.PHOTO, attr, bData, 0,
bData.length);
}
} else if (valueType.equals("URL")) {
String sdata = FormatSupport.parseString(attributes, data);
contact.addString(Contact.PHOTO_URL, attr, sdata);
} else {
// ignore; value type not recognized
}
break;
}
case Contact.PUBLIC_KEY: {
byte[] beeData = data.getBytes();
if (beeData.length != 0) {
contact.addBinary(Contact.PUBLIC_KEY, attr, beeData, 0,
beeData.length);
}
break;
}
case Contact.CLASS: {
int i = VCardSupport.getClassCode(data);
if (i != -1) {
contact.addInt(Contact.CLASS, Contact.ATTR_NONE, i);
}
break;
}
default:
// System.err.println("No match for field prefix '"
// + prefix + "' (REMOVE THIS MESSAGE)");
}
} | void function(Contact contact, String prefix, String[] attributes, String data, Object listHandle) { int attr = parseAttributes(attributes); int field = VCardSupport.getFieldCode(prefix); if (field == -1 && prefix.equals(getClassProperty())) { field = Contact.CLASS; } if (!PIMHandler.getInstance().isSupportedField(listHandle, field)) { return; } switch (field) { case Contact.FORMATTED_NAME: case Contact.FORMATTED_ADDR: case Contact.TEL: case Contact.EMAIL: case Contact.TITLE: case Contact.ORG: case Contact.NICKNAME: case Contact.NOTE: case Contact.UID: case Contact.URL: { String sdata = FormatSupport.parseString(attributes, data); contact.addString(field, attr, sdata); break; } case Contact.NAME: case Contact.ADDR: { String[] elements = FormatSupport.parseStringArray(attributes, data); int elementCount = PIMHandler.getInstance() .getStringArraySize(listHandle, field); if (elements.length != elementCount) { String[] a = new String[elementCount]; System.arraycopy(elements, 0, a, 0, Math.min(elements.length, elementCount)); elements = a; } contact.addStringArray(field, attr, elements); break; } case Contact.BIRTHDAY: case Contact.REVISION: { int dateLen = data.length(); long date = (dateLen < 15) ? PIMHandler.getInstance().parseDate(data) : PIMHandler.getInstance().parseDateTime(data); contact.addDate(field, attr, date); break; } case Contact.PHOTO: { String valueType = FormatSupport.getAttributeValue(attributes, STR, null); if (valueType == null) { byte[] bData = data.getBytes(); if (bData.length != 0) { contact.addBinary(Contact.PHOTO, attr, bData, 0, bData.length); } } else if (valueType.equals("URL")) { String sdata = FormatSupport.parseString(attributes, data); contact.addString(Contact.PHOTO_URL, attr, sdata); } else { } break; } case Contact.PUBLIC_KEY: { byte[] beeData = data.getBytes(); if (beeData.length != 0) { contact.addBinary(Contact.PUBLIC_KEY, attr, beeData, 0, beeData.length); } break; } case Contact.CLASS: { int i = VCardSupport.getClassCode(data); if (i != -1) { contact.addInt(Contact.CLASS, Contact.ATTR_NONE, i); } break; } default: } } | /**
* Parses a single vCard line.
* @param contact element to populate
* @param prefix filter for selecting fields
* @param attributes fields to be processed
* @param data input to be filtered
* @param listHandle handle of the list containing the contact being parsed
*/ | Parses a single vCard line | importData | {
"repo_name": "mykmelez/pluotsorbet",
"path": "java/midp/com/sun/j2me/pim/formats/VCardFormat.java",
"license": "gpl-2.0",
"size": 23410
} | [
"com.sun.j2me.pim.PIMHandler",
"javax.microedition.pim.Contact"
] | import com.sun.j2me.pim.PIMHandler; import javax.microedition.pim.Contact; | import com.sun.j2me.pim.*; import javax.microedition.pim.*; | [
"com.sun.j2me",
"javax.microedition"
] | com.sun.j2me; javax.microedition; | 279,032 |
@ApiModelProperty(
example = "0f8ccf21-7267-4268-9167-a1e2c40c84c8",
value = "Folder relation object's UUID")
public UUID getFolderId() {
return folderId;
} | @ApiModelProperty( example = STR, value = STR) UUID function() { return folderId; } | /**
* Folder relation object's UUID
*
* @return folderId
*/ | Folder relation object's UUID | getFolderId | {
"repo_name": "XeroAPI/Xero-Java",
"path": "src/main/java/com/xero/models/file/FileObject.java",
"license": "mit",
"size": 8012
} | [
"io.swagger.annotations.ApiModelProperty"
] | import io.swagger.annotations.ApiModelProperty; | import io.swagger.annotations.*; | [
"io.swagger.annotations"
] | io.swagger.annotations; | 1,903,387 |
public Object peek(int n) throws EmptyStackException {
int m = (size() - n) - 1;
if (m < 0) {
throw new EmptyStackException();
} else {
return get(m);
}
}
| Object function(int n) throws EmptyStackException { int m = (size() - n) - 1; if (m < 0) { throw new EmptyStackException(); } else { return get(m); } } | /**
* Returns the n'th item down (zero-relative) from the top of this
* stack without removing it.
*
* @param n the number of items down to go
* @return the n'th item on the stack, zero relative
* @throws EmptyStackException if there are not enough items on the
* stack to satisfy this request
*/ | Returns the n'th item down (zero-relative) from the top of this stack without removing it | peek | {
"repo_name": "yuyupapa/OpenSource",
"path": "apache-tomcat-6.0.48/java/org/apache/tomcat/util/digester/ArrayStack.java",
"license": "apache-2.0",
"size": 5809
} | [
"java.util.EmptyStackException"
] | import java.util.EmptyStackException; | import java.util.*; | [
"java.util"
] | java.util; | 193,711 |
public static BinaryMessage correctPDU3(BinaryMessage message)
{
return correctPDU(message, PDU3_CHECKSUMS, 416);
} | static BinaryMessage function(BinaryMessage message) { return correctPDU(message, PDU3_CHECKSUMS, 416); } | /**
* Performs error detection and single-bit error correction against the
* data blocks of a PDU3 message.
*/ | Performs error detection and single-bit error correction against the data blocks of a PDU3 message | correctPDU3 | {
"repo_name": "ImagoTrigger/sdrtrunk",
"path": "src/main/java/io/github/dsheirer/edac/CRCP25.java",
"license": "gpl-3.0",
"size": 21758
} | [
"io.github.dsheirer.bits.BinaryMessage"
] | import io.github.dsheirer.bits.BinaryMessage; | import io.github.dsheirer.bits.*; | [
"io.github.dsheirer"
] | io.github.dsheirer; | 575,052 |
//-----------------------------------------------------------------------
private void writeObject(final ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(map);
} | void function(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } | /**
* Write the map out using a custom routine.
*
* @param out the output stream
* @throws IOException
* @since 3.1
*/ | Write the map out using a custom routine | writeObject | {
"repo_name": "AffogatoLang/Moka",
"path": "lib/Apache_Commons_Collections/src/main/java/org/apache/commons/collections4/map/UnmodifiableSortedMap.java",
"license": "bsd-3-clause",
"size": 5549
} | [
"java.io.IOException",
"java.io.ObjectOutputStream"
] | import java.io.IOException; import java.io.ObjectOutputStream; | import java.io.*; | [
"java.io"
] | java.io; | 61,096 |
public void createFile(String path, String name, InputStream in)
{
createFile(path, name, in, null, null);
}
| void function(String path, String name, InputStream in) { createFile(path, name, in, null, null); } | /**
* Create a file with content specified by the InputStream.
* Guaranteed to be created atomically.
* @param path The path to the containing directory.
* @param name The name to give the file.
* @param in An InputStream containing data for file.
*/ | Create a file with content specified by the InputStream. Guaranteed to be created atomically | createFile | {
"repo_name": "loftuxab/community-edition-old",
"path": "projects/repository/source/java/org/alfresco/repo/avm/AVMServiceImpl.java",
"license": "lgpl-3.0",
"size": 59118
} | [
"java.io.InputStream"
] | import java.io.InputStream; | import java.io.*; | [
"java.io"
] | java.io; | 118,859 |
@Test
public void testUpdateQuota() throws Exception {
setUp();
Quota quotaGeneralToSpecific = dao.getById(FixturesTool.QUOTA_GENERAL);
// Save quotaName and vdsGroup list for future check.
String quotaName = "New Temporary name";
List<QuotaVdsGroup> quotaVdsGroupList =
getQuotaVdsGroup(getSpecificQuotaVdsGroup(quotaGeneralToSpecific.getId()));
Long newStorageLimit = new Long("2345");
// Check before the update, that the fields are not equal.
assertEquals(quotaName.equals(quotaGeneralToSpecific.getQuotaName()), false);
assertEquals(quotaVdsGroupList.size() == quotaGeneralToSpecific.getQuotaVdsGroups().size(), false);
assertEquals(quotaGeneralToSpecific.getStorageSizeGB().equals(newStorageLimit), false);
// Update
quotaGeneralToSpecific.setQuotaName(quotaName);
quotaGeneralToSpecific.setStorageSizeGB(newStorageLimit);
quotaGeneralToSpecific.setQuotaVdsGroups(quotaVdsGroupList);
dao.update(quotaGeneralToSpecific);
quotaGeneralToSpecific = dao.getById(FixturesTool.QUOTA_GENERAL);
// Check after the update, that the fields are equal now.
assertEquals(quotaName.equals(quotaGeneralToSpecific.getQuotaName()), true);
assertEquals(quotaVdsGroupList.size() == quotaGeneralToSpecific.getQuotaVdsGroups().size(), true);
assertEquals(quotaGeneralToSpecific.getStorageSizeGB().equals(newStorageLimit), true);
} | void function() throws Exception { setUp(); Quota quotaGeneralToSpecific = dao.getById(FixturesTool.QUOTA_GENERAL); String quotaName = STR; List<QuotaVdsGroup> quotaVdsGroupList = getQuotaVdsGroup(getSpecificQuotaVdsGroup(quotaGeneralToSpecific.getId())); Long newStorageLimit = new Long("2345"); assertEquals(quotaName.equals(quotaGeneralToSpecific.getQuotaName()), false); assertEquals(quotaVdsGroupList.size() == quotaGeneralToSpecific.getQuotaVdsGroups().size(), false); assertEquals(quotaGeneralToSpecific.getStorageSizeGB().equals(newStorageLimit), false); quotaGeneralToSpecific.setQuotaName(quotaName); quotaGeneralToSpecific.setStorageSizeGB(newStorageLimit); quotaGeneralToSpecific.setQuotaVdsGroups(quotaVdsGroupList); dao.update(quotaGeneralToSpecific); quotaGeneralToSpecific = dao.getById(FixturesTool.QUOTA_GENERAL); assertEquals(quotaName.equals(quotaGeneralToSpecific.getQuotaName()), true); assertEquals(quotaVdsGroupList.size() == quotaGeneralToSpecific.getQuotaVdsGroups().size(), true); assertEquals(quotaGeneralToSpecific.getStorageSizeGB().equals(newStorageLimit), true); } | /**
* Make Quota specific to be the same as Quota general and specific.
*
* @throws Exception
*/ | Make Quota specific to be the same as Quota general and specific | testUpdateQuota | {
"repo_name": "raksha-rao/gluster-ovirt",
"path": "backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/QuotaDAOTest.java",
"license": "apache-2.0",
"size": 16995
} | [
"java.util.List",
"org.junit.Assert",
"org.ovirt.engine.core.common.businessentities.Quota",
"org.ovirt.engine.core.common.businessentities.QuotaVdsGroup"
] | import java.util.List; import org.junit.Assert; import org.ovirt.engine.core.common.businessentities.Quota; import org.ovirt.engine.core.common.businessentities.QuotaVdsGroup; | import java.util.*; import org.junit.*; import org.ovirt.engine.core.common.businessentities.*; | [
"java.util",
"org.junit",
"org.ovirt.engine"
] | java.util; org.junit; org.ovirt.engine; | 1,271,734 |
Observable<ServiceResponse<Map<String, String>>> getStringValidWithServiceResponseAsync(); | Observable<ServiceResponse<Map<String, String>>> getStringValidWithServiceResponseAsync(); | /**
* Get string dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"}.
*
* @return the observable to the Map<String, String> object
*/ | Get string dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"} | getStringValidWithServiceResponseAsync | {
"repo_name": "anudeepsharma/autorest",
"path": "src/generator/AutoRest.Java.Tests/src/main/java/fixtures/bodydictionary/Dictionarys.java",
"license": "mit",
"size": 79030
} | [
"com.microsoft.rest.ServiceResponse",
"java.util.Map"
] | import com.microsoft.rest.ServiceResponse; import java.util.Map; | import com.microsoft.rest.*; import java.util.*; | [
"com.microsoft.rest",
"java.util"
] | com.microsoft.rest; java.util; | 788,782 |
private String listUnsupportedFields() {
String unsupportedFields = "";
if (obj.isIsPacked() != null) {
unsupportedFields += "is_packed "; //NON-NLS
}
if (obj.getDevicePath() != null) {
unsupportedFields += "Device_Path "; //NON-NLS
}
if (obj.getFullPath() != null) {
unsupportedFields += "Full_Path "; //NON-NLS
}
if (obj.getMagicNumber() != null) {
unsupportedFields += "Magic_Number "; //NON-NLS
}
if (obj.getDigitalSignatures() != null) {
unsupportedFields += "Digital_Signatures "; //NON-NLS
}
if (obj.getFileAttributesList() != null) {
unsupportedFields += "File_Attributes_List "; //NON-NLS
}
if (obj.getPermissions() != null) {
unsupportedFields += "Permissions "; //NON-NLS
}
if (obj.getUserOwner() != null) {
unsupportedFields += "User_Owner "; //NON-NLS
}
if (obj.getPackerList() != null) {
unsupportedFields += "Packer_List "; //NON-NLS
}
if (obj.getPeakEntropy() != null) {
unsupportedFields += "Peak_Entropy "; //NON-NLS
}
if (obj.getSymLinks() != null) {
unsupportedFields += "Sym_Links "; //NON-NLS
}
if (obj.getByteRuns() != null) {
unsupportedFields += "Bytes_Runs "; //NON-NLS
}
if (obj.getExtractedFeatures() != null) {
unsupportedFields += "Extracted_Features "; //NON-NLS
}
if (obj.getEncryptionAlgorithm() != null) {
unsupportedFields += "Encryption_Algorithm "; //NON-NLS
}
if (obj.getDecryptionKey() != null) {
unsupportedFields += "Decryption_Key "; //NON-NLS
}
if (obj.getCompressionMethod() != null) {
unsupportedFields += "Compression_Method "; //NON-NLS
}
if (obj.getCompressionVersion() != null) {
unsupportedFields += "Compression_Version "; //NON-NLS
}
if (obj.getCompressionComment() != null) {
unsupportedFields += "Compression_Comment "; //NON-NLS
}
return unsupportedFields;
} | String function() { String unsupportedFields = STRis_packed STRDevice_Path STRFull_Path STRMagic_Number STRDigital_Signatures STRFile_Attributes_List STRPermissions STRUser_Owner STRPacker_List STRPeak_Entropy STRSym_Links STRBytes_Runs STRExtracted_Features STREncryption_Algorithm STRDecryption_Key STRCompression_Method STRCompression_Version STRCompression_Comment "; } return unsupportedFields; } | /**
* List unsupported fields found in the object.
*
* @return List of unsupported fields
*/ | List unsupported fields found in the object | listUnsupportedFields | {
"repo_name": "maxrp/autopsy",
"path": "Core/src/org/sleuthkit/autopsy/modules/stix/EvalFileObj.java",
"license": "apache-2.0",
"size": 30446
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 734,727 |
public void testSpaceCommands() throws Exception {
final Configuration conf = new Configuration();
// set a smaller block size so that we can test with smaller
// diskspace quotas
conf.set("dfs.block.size", "512");
final MiniDFSCluster cluster = new MiniDFSCluster(conf, 2, true, null);
final FileSystem fs = cluster.getFileSystem();
assertTrue("Not a HDFS: "+fs.getUri(),
fs instanceof DistributedFileSystem);
final DistributedFileSystem dfs = (DistributedFileSystem)fs;
try {
int fileLen = 1024;
short replication = 3;
int fileSpace = fileLen * replication;
// create directory /nqdir0/qdir1/qdir20/nqdir30
assertTrue(dfs.mkdirs(new Path("/nqdir0/qdir1/qdir20/nqdir30")));
// set the quota of /nqdir0/qdir1 to 4 * fileSpace
final Path quotaDir1 = new Path("/nqdir0/qdir1");
dfs.setQuota(quotaDir1, FSConstants.QUOTA_DONT_SET, 4 * fileSpace);
ContentSummary c = dfs.getContentSummary(quotaDir1);
assertEquals(c.getSpaceQuota(), 4 * fileSpace);
// set the quota of /nqdir0/qdir1/qdir20 to 6 * fileSpace
final Path quotaDir20 = new Path("/nqdir0/qdir1/qdir20");
dfs.setQuota(quotaDir20, FSConstants.QUOTA_DONT_SET, 6 * fileSpace);
c = dfs.getContentSummary(quotaDir20);
assertEquals(c.getSpaceQuota(), 6 * fileSpace);
// Create /nqdir0/qdir1/qdir21 and set its space quota to 2 * fileSpace
final Path quotaDir21 = new Path("/nqdir0/qdir1/qdir21");
assertTrue(dfs.mkdirs(quotaDir21));
dfs.setQuota(quotaDir21, FSConstants.QUOTA_DONT_SET, 2 * fileSpace);
c = dfs.getContentSummary(quotaDir21);
assertEquals(c.getSpaceQuota(), 2 * fileSpace);
// 5: Create directory /nqdir0/qdir1/qdir21/nqdir32
Path tempPath = new Path(quotaDir21, "nqdir32");
assertTrue(dfs.mkdirs(tempPath));
// create a file under nqdir32/fileDir
DFSTestUtil.createFile(dfs, new Path(tempPath, "fileDir/file1"), fileLen,
replication, 0);
c = dfs.getContentSummary(quotaDir21);
assertEquals(c.getSpaceConsumed(), fileSpace);
// Create a larger file /nqdir0/qdir1/qdir21/nqdir33/
boolean hasException = false;
try {
DFSTestUtil.createFile(dfs, new Path(quotaDir21, "nqdir33/file2"),
2*fileLen, replication, 0);
} catch (QuotaExceededException e) {
hasException = true;
}
assertTrue(hasException);
// delete nqdir33
assertTrue(dfs.delete(new Path(quotaDir21, "nqdir33"), true));
c = dfs.getContentSummary(quotaDir21);
assertEquals(c.getSpaceConsumed(), fileSpace);
assertEquals(c.getSpaceQuota(), 2*fileSpace);
// Verify space before the move:
c = dfs.getContentSummary(quotaDir20);
assertEquals(c.getSpaceConsumed(), 0);
// Move /nqdir0/qdir1/qdir21/nqdir32 /nqdir0/qdir1/qdir20/nqdir30
Path dstPath = new Path(quotaDir20, "nqdir30");
Path srcPath = new Path(quotaDir21, "nqdir32");
assertTrue(dfs.rename(srcPath, dstPath));
// verify space after the move
c = dfs.getContentSummary(quotaDir20);
assertEquals(c.getSpaceConsumed(), fileSpace);
// verify space for its parent
c = dfs.getContentSummary(quotaDir1);
assertEquals(c.getSpaceConsumed(), fileSpace);
// verify space for source for the move
c = dfs.getContentSummary(quotaDir21);
assertEquals(c.getSpaceConsumed(), 0);
final Path file2 = new Path(dstPath, "fileDir/file2");
int file2Len = 2 * fileLen;
// create a larger file under /nqdir0/qdir1/qdir20/nqdir30
DFSTestUtil.createFile(dfs, file2, file2Len, replication, 0);
c = dfs.getContentSummary(quotaDir20);
assertEquals(c.getSpaceConsumed(), 3 * fileSpace);
c = dfs.getContentSummary(quotaDir21);
assertEquals(c.getSpaceConsumed(), 0);
// Reverse: Move /nqdir0/qdir1/qdir20/nqdir30 to /nqdir0/qdir1/qdir21/
hasException = false;
try {
assertFalse(dfs.rename(dstPath, srcPath));
} catch (QuotaExceededException e) {
hasException = true;
}
assertTrue(hasException);
// make sure no intermediate directories left by failed rename
assertFalse(dfs.exists(srcPath));
// directory should exist
assertTrue(dfs.exists(dstPath));
// verify space after the failed move
c = dfs.getContentSummary(quotaDir20);
assertEquals(c.getSpaceConsumed(), 3 * fileSpace);
c = dfs.getContentSummary(quotaDir21);
assertEquals(c.getSpaceConsumed(), 0);
// Test Append :
// verify space quota
c = dfs.getContentSummary(quotaDir1);
assertEquals(c.getSpaceQuota(), 4 * fileSpace);
// verify space before append;
c = dfs.getContentSummary(dstPath);
assertEquals(c.getSpaceConsumed(), 3 * fileSpace);
// reduce quota for quotaDir1 to account for not appending
dfs.setQuota(quotaDir1, FSConstants.QUOTA_DONT_SET, 3 * fileSpace);
// Test set replication :
// first reduce the replication
dfs.setReplication(file2, (short)(replication-1));
// verify that space is reduced by file2Len
c = dfs.getContentSummary(dstPath);
assertEquals(c.getSpaceConsumed(), 3 * fileSpace - file2Len);
// now try to increase the replication and and expect an error.
hasException = false;
try {
dfs.setReplication(file2, (short)(replication+1));
} catch (QuotaExceededException e) {
hasException = true;
}
assertTrue(hasException);
// verify space consumed remains unchanged.
c = dfs.getContentSummary(dstPath);
assertEquals(c.getSpaceConsumed(), 3 * fileSpace - file2Len);
// now increase the quota for quotaDir1 and quotaDir20
dfs.setQuota(quotaDir1, FSConstants.QUOTA_DONT_SET, 10 * fileSpace);
dfs.setQuota(quotaDir20, FSConstants.QUOTA_DONT_SET, 10 * fileSpace);
// then increasing replication should be ok.
dfs.setReplication(file2, (short)(replication+1));
// verify increase in space
c = dfs.getContentSummary(dstPath);
assertEquals(c.getSpaceConsumed(), 3 * fileSpace + file2Len);
} finally {
cluster.shutdown();
}
} | void function() throws Exception { final Configuration conf = new Configuration(); conf.set(STR, "512"); final MiniDFSCluster cluster = new MiniDFSCluster(conf, 2, true, null); final FileSystem fs = cluster.getFileSystem(); assertTrue(STR+fs.getUri(), fs instanceof DistributedFileSystem); final DistributedFileSystem dfs = (DistributedFileSystem)fs; try { int fileLen = 1024; short replication = 3; int fileSpace = fileLen * replication; assertTrue(dfs.mkdirs(new Path(STR))); final Path quotaDir1 = new Path(STR); dfs.setQuota(quotaDir1, FSConstants.QUOTA_DONT_SET, 4 * fileSpace); ContentSummary c = dfs.getContentSummary(quotaDir1); assertEquals(c.getSpaceQuota(), 4 * fileSpace); final Path quotaDir20 = new Path(STR); dfs.setQuota(quotaDir20, FSConstants.QUOTA_DONT_SET, 6 * fileSpace); c = dfs.getContentSummary(quotaDir20); assertEquals(c.getSpaceQuota(), 6 * fileSpace); final Path quotaDir21 = new Path(STR); assertTrue(dfs.mkdirs(quotaDir21)); dfs.setQuota(quotaDir21, FSConstants.QUOTA_DONT_SET, 2 * fileSpace); c = dfs.getContentSummary(quotaDir21); assertEquals(c.getSpaceQuota(), 2 * fileSpace); Path tempPath = new Path(quotaDir21, STR); assertTrue(dfs.mkdirs(tempPath)); DFSTestUtil.createFile(dfs, new Path(tempPath, STR), fileLen, replication, 0); c = dfs.getContentSummary(quotaDir21); assertEquals(c.getSpaceConsumed(), fileSpace); boolean hasException = false; try { DFSTestUtil.createFile(dfs, new Path(quotaDir21, STR), 2*fileLen, replication, 0); } catch (QuotaExceededException e) { hasException = true; } assertTrue(hasException); assertTrue(dfs.delete(new Path(quotaDir21, STR), true)); c = dfs.getContentSummary(quotaDir21); assertEquals(c.getSpaceConsumed(), fileSpace); assertEquals(c.getSpaceQuota(), 2*fileSpace); c = dfs.getContentSummary(quotaDir20); assertEquals(c.getSpaceConsumed(), 0); Path dstPath = new Path(quotaDir20, STR); Path srcPath = new Path(quotaDir21, STR); assertTrue(dfs.rename(srcPath, dstPath)); c = dfs.getContentSummary(quotaDir20); assertEquals(c.getSpaceConsumed(), fileSpace); c = dfs.getContentSummary(quotaDir1); assertEquals(c.getSpaceConsumed(), fileSpace); c = dfs.getContentSummary(quotaDir21); assertEquals(c.getSpaceConsumed(), 0); final Path file2 = new Path(dstPath, STR); int file2Len = 2 * fileLen; DFSTestUtil.createFile(dfs, file2, file2Len, replication, 0); c = dfs.getContentSummary(quotaDir20); assertEquals(c.getSpaceConsumed(), 3 * fileSpace); c = dfs.getContentSummary(quotaDir21); assertEquals(c.getSpaceConsumed(), 0); hasException = false; try { assertFalse(dfs.rename(dstPath, srcPath)); } catch (QuotaExceededException e) { hasException = true; } assertTrue(hasException); assertFalse(dfs.exists(srcPath)); assertTrue(dfs.exists(dstPath)); c = dfs.getContentSummary(quotaDir20); assertEquals(c.getSpaceConsumed(), 3 * fileSpace); c = dfs.getContentSummary(quotaDir21); assertEquals(c.getSpaceConsumed(), 0); c = dfs.getContentSummary(quotaDir1); assertEquals(c.getSpaceQuota(), 4 * fileSpace); c = dfs.getContentSummary(dstPath); assertEquals(c.getSpaceConsumed(), 3 * fileSpace); dfs.setQuota(quotaDir1, FSConstants.QUOTA_DONT_SET, 3 * fileSpace); dfs.setReplication(file2, (short)(replication-1)); c = dfs.getContentSummary(dstPath); assertEquals(c.getSpaceConsumed(), 3 * fileSpace - file2Len); hasException = false; try { dfs.setReplication(file2, (short)(replication+1)); } catch (QuotaExceededException e) { hasException = true; } assertTrue(hasException); c = dfs.getContentSummary(dstPath); assertEquals(c.getSpaceConsumed(), 3 * fileSpace - file2Len); dfs.setQuota(quotaDir1, FSConstants.QUOTA_DONT_SET, 10 * fileSpace); dfs.setQuota(quotaDir20, FSConstants.QUOTA_DONT_SET, 10 * fileSpace); dfs.setReplication(file2, (short)(replication+1)); c = dfs.getContentSummary(dstPath); assertEquals(c.getSpaceConsumed(), 3 * fileSpace + file2Len); } finally { cluster.shutdown(); } } | /**
* Test HDFS operations that change disk space consumed by a directory tree.
* namely create, rename, delete, append, and setReplication.
*
* This is based on testNamespaceCommands() above.
*/ | Test HDFS operations that change disk space consumed by a directory tree. namely create, rename, delete, append, and setReplication. This is based on testNamespaceCommands() above | testSpaceCommands | {
"repo_name": "kohsuke/hadoop",
"path": "src/test/org/apache/hadoop/hdfs/TestQuota.java",
"license": "apache-2.0",
"size": 23919
} | [
"org.apache.hadoop.conf.Configuration",
"org.apache.hadoop.fs.ContentSummary",
"org.apache.hadoop.fs.FileSystem",
"org.apache.hadoop.fs.Path",
"org.apache.hadoop.hdfs.protocol.FSConstants",
"org.apache.hadoop.hdfs.protocol.QuotaExceededException"
] | import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.protocol.FSConstants; import org.apache.hadoop.hdfs.protocol.QuotaExceededException; | import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.hdfs.protocol.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 2,914,499 |
public String getBootloaderType() {
KickstartCommand bootloaderCommand = this.getCommand("bootloader");
if (bootloaderCommand == null || bootloaderCommand.getArguments() == null) {
return "grub";
}
String regEx = ".*--useLilo.*";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(bootloaderCommand.getArguments());
if (matcher.matches()) {
return "lilo";
}
return "grub";
} | String function() { KickstartCommand bootloaderCommand = this.getCommand(STR); if (bootloaderCommand == null bootloaderCommand.getArguments() == null) { return "grub"; } String regEx = STR; Pattern pattern = Pattern.compile(regEx); Matcher matcher = pattern.matcher(bootloaderCommand.getArguments()); if (matcher.matches()) { return "lilo"; } return "grub"; } | /**
* Get the bootloader type
*
* @return String: lilo or grub
*/ | Get the bootloader type | getBootloaderType | {
"repo_name": "renner/spacewalk",
"path": "java/code/src/com/redhat/rhn/domain/kickstart/KickstartData.java",
"license": "gpl-2.0",
"size": 48300
} | [
"java.util.regex.Matcher",
"java.util.regex.Pattern"
] | import java.util.regex.Matcher; import java.util.regex.Pattern; | import java.util.regex.*; | [
"java.util"
] | java.util; | 1,804,515 |
EClass getMLCD20x4Backlight(); | EClass getMLCD20x4Backlight(); | /**
* Returns the meta object for class '{@link org.openhab.binding.tinkerforge.internal.model.MLCD20x4Backlight <em>MLCD2 0x4 Backlight</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>MLCD2 0x4 Backlight</em>'.
* @see org.openhab.binding.tinkerforge.internal.model.MLCD20x4Backlight
* @generated
*/ | Returns the meta object for class '<code>org.openhab.binding.tinkerforge.internal.model.MLCD20x4Backlight MLCD2 0x4 Backlight</code>'. | getMLCD20x4Backlight | {
"repo_name": "gregfinley/openhab",
"path": "bundles/binding/org.openhab.binding.tinkerforge/src/main/java/org/openhab/binding/tinkerforge/internal/model/ModelPackage.java",
"license": "epl-1.0",
"size": 665067
} | [
"org.eclipse.emf.ecore.EClass"
] | import org.eclipse.emf.ecore.EClass; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 64,160 |
@Deprecated
@Override
public void postGet(final ObserverContext<RegionCoprocessorEnvironment> c, final Get get,
final List<KeyValue> result)
throws IOException {
} | void function(final ObserverContext<RegionCoprocessorEnvironment> c, final Get get, final List<KeyValue> result) throws IOException { } | /**
* WARNING: please override postGetOp instead of this method. This is to maintain some
* compatibility and to ease the transition from 0.94 -> 0.96. It is super inefficient!
*/ | compatibility and to ease the transition from 0.94 -> 0.96. It is super inefficient | postGet | {
"repo_name": "Jackygq1982/hbase_src",
"path": "hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/BaseRegionObserver.java",
"license": "apache-2.0",
"size": 19924
} | [
"java.io.IOException",
"java.util.List",
"org.apache.hadoop.hbase.KeyValue",
"org.apache.hadoop.hbase.client.Get"
] | import java.io.IOException; import java.util.List; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Get; | import java.io.*; import java.util.*; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; | [
"java.io",
"java.util",
"org.apache.hadoop"
] | java.io; java.util; org.apache.hadoop; | 1,937,863 |
private void testClientReuse(int maxConnections, boolean concurrent)
throws IOException, InterruptedException {
Map<String, String> configMap = new HashMap<>();
configMap.put("spark.shuffle.io.numConnectionsPerPeer", Integer.toString(maxConnections));
TransportConf conf = new TransportConf("shuffle", new MapConfigProvider(configMap));
RpcHandler rpcHandler = new NoOpRpcHandler();
try (TransportContext context = new TransportContext(conf, rpcHandler)) {
TransportClientFactory factory = context.createClientFactory();
Set<TransportClient> clients = Collections.synchronizedSet(
new HashSet<>());
AtomicInteger failed = new AtomicInteger();
Thread[] attempts = new Thread[maxConnections * 10];
// Launch a bunch of threads to create new clients.
for (int i = 0; i < attempts.length; i++) {
attempts[i] = new Thread(() -> {
try {
TransportClient client =
factory.createClient(TestUtils.getLocalHost(), server1.getPort());
assertTrue(client.isActive());
clients.add(client);
} catch (IOException e) {
failed.incrementAndGet();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
if (concurrent) {
attempts[i].start();
} else {
attempts[i].run();
}
}
// Wait until all the threads complete.
for (Thread attempt : attempts) {
attempt.join();
}
Assert.assertEquals(0, failed.get());
Assert.assertTrue(clients.size() <= maxConnections);
for (TransportClient client : clients) {
client.close();
}
factory.close();
}
} | void function(int maxConnections, boolean concurrent) throws IOException, InterruptedException { Map<String, String> configMap = new HashMap<>(); configMap.put(STR, Integer.toString(maxConnections)); TransportConf conf = new TransportConf(STR, new MapConfigProvider(configMap)); RpcHandler rpcHandler = new NoOpRpcHandler(); try (TransportContext context = new TransportContext(conf, rpcHandler)) { TransportClientFactory factory = context.createClientFactory(); Set<TransportClient> clients = Collections.synchronizedSet( new HashSet<>()); AtomicInteger failed = new AtomicInteger(); Thread[] attempts = new Thread[maxConnections * 10]; for (int i = 0; i < attempts.length; i++) { attempts[i] = new Thread(() -> { try { TransportClient client = factory.createClient(TestUtils.getLocalHost(), server1.getPort()); assertTrue(client.isActive()); clients.add(client); } catch (IOException e) { failed.incrementAndGet(); } catch (InterruptedException e) { throw new RuntimeException(e); } }); if (concurrent) { attempts[i].start(); } else { attempts[i].run(); } } for (Thread attempt : attempts) { attempt.join(); } Assert.assertEquals(0, failed.get()); Assert.assertTrue(clients.size() <= maxConnections); for (TransportClient client : clients) { client.close(); } factory.close(); } } | /**
* Request a bunch of clients to a single server to test
* we create up to maxConnections of clients.
*
* If concurrent is true, create multiple threads to create clients in parallel.
*/ | Request a bunch of clients to a single server to test we create up to maxConnections of clients. If concurrent is true, create multiple threads to create clients in parallel | testClientReuse | {
"repo_name": "goldmedal/spark",
"path": "common/network-common/src/test/java/org/apache/spark/network/TransportClientFactorySuite.java",
"license": "apache-2.0",
"size": 7976
} | [
"java.io.IOException",
"java.util.Collections",
"java.util.HashMap",
"java.util.HashSet",
"java.util.Map",
"java.util.Set",
"java.util.concurrent.atomic.AtomicInteger",
"org.apache.spark.network.client.TransportClient",
"org.apache.spark.network.client.TransportClientFactory",
"org.apache.spark.network.server.NoOpRpcHandler",
"org.apache.spark.network.server.RpcHandler",
"org.apache.spark.network.util.MapConfigProvider",
"org.apache.spark.network.util.TransportConf",
"org.junit.Assert"
] | import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.apache.spark.network.client.TransportClient; import org.apache.spark.network.client.TransportClientFactory; import org.apache.spark.network.server.NoOpRpcHandler; import org.apache.spark.network.server.RpcHandler; import org.apache.spark.network.util.MapConfigProvider; import org.apache.spark.network.util.TransportConf; import org.junit.Assert; | import java.io.*; import java.util.*; import java.util.concurrent.atomic.*; import org.apache.spark.network.client.*; import org.apache.spark.network.server.*; import org.apache.spark.network.util.*; import org.junit.*; | [
"java.io",
"java.util",
"org.apache.spark",
"org.junit"
] | java.io; java.util; org.apache.spark; org.junit; | 863,249 |
public void addElement(GElement e,Point2D mouse){
if(e instanceof GScreen){
this.currentS = (GScreen) e;
this.currentL = null;
this.currentlayers.clear();
for(GElement lay : currentS.getElements()){
this.currentlayers.add((GLayer)lay);
}
this.getGui().addScreen(currentS);
this.getGui().goTo(currentS);
} else if(e instanceof GLayer){
if(this.currentS != null){
this.getGui().addElement(e,this.currentS);
}else
throw new IllegalDropException("No screen!");
GLayer temp =(GLayer) e;
this.currentL=temp;
this.currentlayers.add(temp);
e.getParent().getNiftyElement().layoutElements();
}
else{
if(this.currentlayers.isEmpty()){
throw new IllegalDropException("No layer to drop in");
}
if(currentL.contains(mouse)){
GElement result = findElement(mouse);
this.getGui().addElement(e, result);
String layout= result.getAttribute("childLayout");
if(layout.equals("absolute")){
int parentX = result.getNiftyElement().getX();
int parentY = result.getNiftyElement().getY();
e.addAttribute("x",""+ (int)(mouse.getX()-parentX));
e.addAttribute("y",""+ (int)(mouse.getY()-parentY));
e.refresh();
}
e.getParent().getNiftyElement().layoutElements();
}
}
this.setChanged();
this.notifyObservers(new AddElementEvent(e));
this.selectElement(e);
} | void function(GElement e,Point2D mouse){ if(e instanceof GScreen){ this.currentS = (GScreen) e; this.currentL = null; this.currentlayers.clear(); for(GElement lay : currentS.getElements()){ this.currentlayers.add((GLayer)lay); } this.getGui().addScreen(currentS); this.getGui().goTo(currentS); } else if(e instanceof GLayer){ if(this.currentS != null){ this.getGui().addElement(e,this.currentS); }else throw new IllegalDropException(STR); GLayer temp =(GLayer) e; this.currentL=temp; this.currentlayers.add(temp); e.getParent().getNiftyElement().layoutElements(); } else{ if(this.currentlayers.isEmpty()){ throw new IllegalDropException(STR); } if(currentL.contains(mouse)){ GElement result = findElement(mouse); this.getGui().addElement(e, result); String layout= result.getAttribute(STR); if(layout.equals(STR)){ int parentX = result.getNiftyElement().getX(); int parentY = result.getNiftyElement().getY(); e.addAttribute("x",STRy",""+ (int)(mouse.getY()-parentY)); e.refresh(); } e.getParent().getNiftyElement().layoutElements(); } } this.setChanged(); this.notifyObservers(new AddElementEvent(e)); this.selectElement(e); } | /**
* Add an Element in a specific position
* @param e element to add
* @param mouse mouse position or screen position
*
*/ | Add an Element in a specific position | addElement | {
"repo_name": "relu91/niftyeditor",
"path": "src/jada/ngeditor/controller/GUIEditor.java",
"license": "apache-2.0",
"size": 21859
} | [
"java.awt.geom.Point2D"
] | import java.awt.geom.Point2D; | import java.awt.geom.*; | [
"java.awt"
] | java.awt; | 984,425 |
private void setUpInterfaceService() {
interfaceService.addListener(anyObject(InterfaceListener.class));
expectLastCall().andDelegateTo(new TestInterfaceService());
// Interface with no VLAN
Interface sw1Eth1 = new Interface("intf1", SW1_ETH1,
Collections.singletonList(INTF1), MAC1, VlanId.NONE);
expect(interfaceService.getMatchingInterface(NEXT_HOP1)).andReturn(sw1Eth1);
interfaces.add(sw1Eth1);
// Interface with a VLAN
Interface sw2Eth1 = new Interface("intf2", SW1_ETH2,
Collections.singletonList(INTF2), MAC2, VLAN1);
expect(interfaceService.getMatchingInterface(NEXT_HOP2)).andReturn(sw2Eth1);
interfaces.add(sw2Eth1);
expect(interfaceService.getInterfaces()).andReturn(interfaces);
replay(interfaceService);
} | void function() { interfaceService.addListener(anyObject(InterfaceListener.class)); expectLastCall().andDelegateTo(new TestInterfaceService()); Interface sw1Eth1 = new Interface("intf1", SW1_ETH1, Collections.singletonList(INTF1), MAC1, VlanId.NONE); expect(interfaceService.getMatchingInterface(NEXT_HOP1)).andReturn(sw1Eth1); interfaces.add(sw1Eth1); Interface sw2Eth1 = new Interface("intf2", SW1_ETH2, Collections.singletonList(INTF2), MAC2, VLAN1); expect(interfaceService.getMatchingInterface(NEXT_HOP2)).andReturn(sw2Eth1); interfaces.add(sw2Eth1); expect(interfaceService.getInterfaces()).andReturn(interfaces); replay(interfaceService); } | /**
* Sets up InterfaceService.
*/ | Sets up InterfaceService | setUpInterfaceService | {
"repo_name": "Shashikanth-Huawei/bmp",
"path": "apps/routing/src/test/java/org/onosproject/routing/impl/SingleSwitchFibInstallerTest.java",
"license": "apache-2.0",
"size": 16364
} | [
"java.util.Collections",
"org.easymock.EasyMock",
"org.onlab.packet.VlanId",
"org.onosproject.incubator.net.intf.Interface",
"org.onosproject.incubator.net.intf.InterfaceListener"
] | import java.util.Collections; import org.easymock.EasyMock; import org.onlab.packet.VlanId; import org.onosproject.incubator.net.intf.Interface; import org.onosproject.incubator.net.intf.InterfaceListener; | import java.util.*; import org.easymock.*; import org.onlab.packet.*; import org.onosproject.incubator.net.intf.*; | [
"java.util",
"org.easymock",
"org.onlab.packet",
"org.onosproject.incubator"
] | java.util; org.easymock; org.onlab.packet; org.onosproject.incubator; | 1,062,321 |
@Nullable
protected AbstractTreeNode<?> createChildNode(ItemReference item) {
if ("file".equals(item.getType())) {
return getTreeStructure().newFileNode(this, item);
} else if ("folder".equals(item.getType()) || "project".equals(item.getType())) {
return getTreeStructure().newFolderNode(this, item);
}
return null;
} | AbstractTreeNode<?> function(ItemReference item) { if ("file".equals(item.getType())) { return getTreeStructure().newFileNode(this, item); } else if (STR.equals(item.getType()) STR.equals(item.getType())) { return getTreeStructure().newFolderNode(this, item); } return null; } | /**
* Creates node for the specified item. Method called for every child item in {@link #refreshChildren(AsyncCallback)} method.
* <p/>
* May be overridden in order to provide a way to create a node for the specified by.
*
* @param item
* {@link ItemReference} for which need to create node
* @return new node instance or {@code null} if the specified item is not supported
*/ | Creates node for the specified item. Method called for every child item in <code>#refreshChildren(AsyncCallback)</code> method. May be overridden in order to provide a way to create a node for the specified by | createChildNode | {
"repo_name": "aljiru/che-core",
"path": "ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/project/tree/generic/FolderNode.java",
"license": "epl-1.0",
"size": 5818
} | [
"org.eclipse.che.api.project.shared.dto.ItemReference",
"org.eclipse.che.ide.api.project.tree.AbstractTreeNode"
] | import org.eclipse.che.api.project.shared.dto.ItemReference; import org.eclipse.che.ide.api.project.tree.AbstractTreeNode; | import org.eclipse.che.api.project.shared.dto.*; import org.eclipse.che.ide.api.project.tree.*; | [
"org.eclipse.che"
] | org.eclipse.che; | 2,277,237 |
public static boolean fileEndsWithNewlineChar(File inFile) throws Exception
{
RandomAccessFile raf = new RandomAccessFile(inFile, "r");
try
{
raf.seek(raf.length() - 1);
char c = (char) raf.readByte();
if (c == '\n' || c == '\r')
{
return true;
}
else
{
return false;
}
}
finally
{
raf.close();
}
} | static boolean function(File inFile) throws Exception { RandomAccessFile raf = new RandomAccessFile(inFile, "r"); try { raf.seek(raf.length() - 1); char c = (char) raf.readByte(); if (c == '\n' c == '\r') { return true; } else { return false; } } finally { raf.close(); } } | /**
* Find out if the source file ends with a newline character. Useful in combination with getNumberOfLines().
*
* @param inFile
*
* @return
* @throws Exception
*/ | Find out if the source file ends with a newline character. Useful in combination with getNumberOfLines() | fileEndsWithNewlineChar | {
"repo_name": "DionKoolhaas/molgenis",
"path": "molgenis-core/src/main/java/org/molgenis/util/TextFileUtils.java",
"license": "lgpl-3.0",
"size": 3519
} | [
"java.io.File",
"java.io.RandomAccessFile"
] | import java.io.File; import java.io.RandomAccessFile; | import java.io.*; | [
"java.io"
] | java.io; | 2,863,924 |
public List<Locale> getLocales() {
// Need logic to construct ordered locale list.
// Consider creating a separate ILocaleResolver
// interface to do this work.
final List rslt = new ArrayList();
// Add highest priority locales first
addToLocaleList(rslt, sessionLocales);
addToLocaleList(rslt, userLocales);
// We will ignore browser locales until we know how to
// translate them into proper java.util.Locales
// addToLocaleList(locales, browserLocales);
addToLocaleList(rslt, portalLocales);
return rslt;
} | List<Locale> function() { final List rslt = new ArrayList(); addToLocaleList(rslt, sessionLocales); addToLocaleList(rslt, userLocales); addToLocaleList(rslt, portalLocales); return rslt; } | /**
* Produces a sorted list of locales according to locale preferences obtained from several
* places. The following priority is given: session, user, browser, portal, and jvm.
*
* @return the sorted list of locales
*/ | Produces a sorted list of locales according to locale preferences obtained from several places. The following priority is given: session, user, browser, portal, and jvm | getLocales | {
"repo_name": "GIP-RECIA/esco-portail",
"path": "uPortal-core/src/main/java/org/apereo/portal/i18n/LocaleManager.java",
"license": "apache-2.0",
"size": 5439
} | [
"java.util.ArrayList",
"java.util.List",
"java.util.Locale"
] | import java.util.ArrayList; import java.util.List; import java.util.Locale; | import java.util.*; | [
"java.util"
] | java.util; | 1,019,899 |
@Test
public void productTest() throws ModelQueryException {
Configuration cfg = reasoningTest("Product.ivml", 0);
IDecisionVariable var = cfg.getDecision("i_product1", false);
Assert.assertNotNull(var);
Assert.assertNotNull(var.getValue());
Assert.assertEquals(120, var.getValue().getValue());
var = cfg.getDecision("i_product2", false);
Assert.assertNotNull(var);
Assert.assertNotNull(var.getValue());
Assert.assertEquals(5040, var.getValue().getValue());
} | void function() throws ModelQueryException { Configuration cfg = reasoningTest(STR, 0); IDecisionVariable var = cfg.getDecision(STR, false); Assert.assertNotNull(var); Assert.assertNotNull(var.getValue()); Assert.assertEquals(120, var.getValue().getValue()); var = cfg.getDecision(STR, false); Assert.assertNotNull(var); Assert.assertNotNull(var.getValue()); Assert.assertEquals(5040, var.getValue().getValue()); } | /**
* Product test. [Ke Liu]
*
* @throws ModelQueryException shall not happen
*/ | Product test. [Ke Liu] | productTest | {
"repo_name": "SSEHUB/EASyProducer",
"path": "Plugins/Reasoner/ReasonerCore/ReasonerCore.test/src/test/net/ssehub/easy/reasoning/core/reasoner/IntegerTests.java",
"license": "apache-2.0",
"size": 3062
} | [
"net.ssehub.easy.varModel.confModel.Configuration",
"net.ssehub.easy.varModel.confModel.IDecisionVariable",
"net.ssehub.easy.varModel.model.ModelQueryException",
"org.junit.Assert"
] | import net.ssehub.easy.varModel.confModel.Configuration; import net.ssehub.easy.varModel.confModel.IDecisionVariable; import net.ssehub.easy.varModel.model.ModelQueryException; import org.junit.Assert; | import net.ssehub.easy.*; import org.junit.*; | [
"net.ssehub.easy",
"org.junit"
] | net.ssehub.easy; org.junit; | 986,459 |
protected void extendIterationEndDateIfNeeded(final Iteration iteration,
final Date midnight) {
final boolean automaticallyExtendEndDate = Boolean.valueOf(
this.properties.getProperty(
DataSamplerImpl.AUTOMATICALLY_EXTEND_END_DATE_PROP,
"false")).booleanValue();
if (automaticallyExtendEndDate
&& IterationStatus.ACTIVE.toInt() == iteration.getStatus()
&& iteration.getEndDate().compareTo(midnight) < 0) {
this.LOG.debug("Extend iteration end day to " + midnight);
iteration.setEndDate(midnight);
this.getHibernateOperations().save(iteration);
}
} | void function(final Iteration iteration, final Date midnight) { final boolean automaticallyExtendEndDate = Boolean.valueOf( this.properties.getProperty( DataSamplerImpl.AUTOMATICALLY_EXTEND_END_DATE_PROP, "false")).booleanValue(); if (automaticallyExtendEndDate && IterationStatus.ACTIVE.toInt() == iteration.getStatus() && iteration.getEndDate().compareTo(midnight) < 0) { this.LOG.debug(STR + midnight); iteration.setEndDate(midnight); this.getHibernateOperations().save(iteration); } } | /**
* Extend iteration end date if needed.
*
* @param iteration
* the iteration
* @param midnight
* the midnight
*/ | Extend iteration end date if needed | extendIterationEndDateIfNeeded | {
"repo_name": "alarulrajan/CodeFest",
"path": "src/com/technoetic/xplanner/charts/DataSamplerImpl.java",
"license": "gpl-2.0",
"size": 6933
} | [
"com.technoetic.xplanner.domain.IterationStatus",
"java.util.Date",
"net.sf.xplanner.domain.Iteration"
] | import com.technoetic.xplanner.domain.IterationStatus; import java.util.Date; import net.sf.xplanner.domain.Iteration; | import com.technoetic.xplanner.domain.*; import java.util.*; import net.sf.xplanner.domain.*; | [
"com.technoetic.xplanner",
"java.util",
"net.sf.xplanner"
] | com.technoetic.xplanner; java.util; net.sf.xplanner; | 1,039,377 |
public void testES6RegExpFlags() {
mode = LanguageMode.ECMASCRIPT6;
parse("/a/y");
parse("/a/u");
mode = LanguageMode.ECMASCRIPT5;
parseWarning("/a/y",
"this language feature is only supported in es6 mode: new RegExp flag 'y'");
parseWarning("/a/u",
"this language feature is only supported in es6 mode: new RegExp flag 'u'");
parseWarning("/a/yu",
"this language feature is only supported in es6 mode: new RegExp flag 'y'",
"this language feature is only supported in es6 mode: new RegExp flag 'u'");
} | void function() { mode = LanguageMode.ECMASCRIPT6; parse("/a/y"); parse("/a/u"); mode = LanguageMode.ECMASCRIPT5; parseWarning("/a/y", STR); parseWarning("/a/u", STR); parseWarning("/a/yu", STR, STR); } | /**
* New RegExp flags added in ES6.
*/ | New RegExp flags added in ES6 | testES6RegExpFlags | {
"repo_name": "tsdl2013/closure-compiler",
"path": "test/com/google/javascript/jscomp/parsing/NewParserTest.java",
"license": "apache-2.0",
"size": 89994
} | [
"com.google.javascript.jscomp.parsing.Config"
] | import com.google.javascript.jscomp.parsing.Config; | import com.google.javascript.jscomp.parsing.*; | [
"com.google.javascript"
] | com.google.javascript; | 366,110 |
public NativeInfo getLegacyBinaryInfoProvider() {
return legacyBinaryInfoProvider;
} | NativeInfo function() { return legacyBinaryInfoProvider; } | /**
* Returns a {@link NativeInfo} possessing information about the linked binary. Depending on the
* type of binary, this may be either a {@link AppleExecutableBinaryInfo}, a {@link
* AppleDylibBinaryInfo}, or a {@link AppleLoadableBundleBinaryInfo}.
*/ | Returns a <code>NativeInfo</code> possessing information about the linked binary. Depending on the type of binary, this may be either a <code>AppleExecutableBinaryInfo</code>, a <code>AppleDylibBinaryInfo</code>, or a <code>AppleLoadableBundleBinaryInfo</code> | getLegacyBinaryInfoProvider | {
"repo_name": "meteorcloudy/bazel",
"path": "src/main/java/com/google/devtools/build/lib/rules/objc/AppleLinkingOutputs.java",
"license": "apache-2.0",
"size": 7682
} | [
"com.google.devtools.build.lib.packages.NativeInfo"
] | import com.google.devtools.build.lib.packages.NativeInfo; | import com.google.devtools.build.lib.packages.*; | [
"com.google.devtools"
] | com.google.devtools; | 1,651,120 |
@Override
public void debug(Object message) {
logger.log(Level.FINE, String.valueOf(message));
} | void function(Object message) { logger.log(Level.FINE, String.valueOf(message)); } | /**
* Write messages debug level logs
*
* @param message Message
*/ | Write messages debug level logs | debug | {
"repo_name": "girinoboy/lojacasamento",
"path": "pagseguro-api/src/main/java/br/com/uol/pagseguro/api/utils/logging/SimpleLog.java",
"license": "mit",
"size": 4973
} | [
"java.util.logging.Level"
] | import java.util.logging.Level; | import java.util.logging.*; | [
"java.util"
] | java.util; | 2,047,634 |
public static String decodeHtmlEntities(String input, String encoding) {
Matcher matcher = ENTITIY_PATTERN.matcher(input);
StringBuffer result = new StringBuffer(input.length());
Charset charset = Charset.forName(encoding);
CharsetEncoder encoder = charset.newEncoder();
while (matcher.find()) {
String entity = matcher.group();
String value = entity.substring(2, entity.length() - 1);
int c = Integer.valueOf(value).intValue();
if (c < 128) {
// first 128 chars are contained in almost every charset
entity = new String(new char[] {(char)c});
// this is intended as performance improvement since
// the canEncode() operation appears quite CPU heavy
} else if (encoder.canEncode((char)c)) {
// encoder can encode this char
entity = new String(new char[] {(char)c});
}
matcher.appendReplacement(result, entity);
}
matcher.appendTail(result);
return result.toString();
} | static String function(String input, String encoding) { Matcher matcher = ENTITIY_PATTERN.matcher(input); StringBuffer result = new StringBuffer(input.length()); Charset charset = Charset.forName(encoding); CharsetEncoder encoder = charset.newEncoder(); while (matcher.find()) { String entity = matcher.group(); String value = entity.substring(2, entity.length() - 1); int c = Integer.valueOf(value).intValue(); if (c < 128) { entity = new String(new char[] {(char)c}); } else if (encoder.canEncode((char)c)) { entity = new String(new char[] {(char)c}); } matcher.appendReplacement(result, entity); } matcher.appendTail(result); return result.toString(); } | /**
* Decodes HTML entity references like <code>&#8364;</code> that are contained in the
* String to a regular character, but only if that character is contained in the given
* encodings charset.<p>
*
* @param input the input to decode the HTML entities in
* @param encoding the charset to decode the input for
* @return the input with the decoded HTML entities
*
* @see #encodeHtmlEntities(String, String)
*/ | Decodes HTML entity references like <code>&#8364;</code> that are contained in the String to a regular character, but only if that character is contained in the given encodings charset | decodeHtmlEntities | {
"repo_name": "victos/opencms-core",
"path": "src/org/opencms/i18n/CmsEncoder.java",
"license": "lgpl-2.1",
"size": 28663
} | [
"java.nio.charset.Charset",
"java.nio.charset.CharsetEncoder",
"java.util.regex.Matcher"
] | import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.regex.Matcher; | import java.nio.charset.*; import java.util.regex.*; | [
"java.nio",
"java.util"
] | java.nio; java.util; | 310,245 |
public List<EntityInstance> traceEntities(String tableName, String entityMappingId, int minCSN,int currentCSN,int maxCSN,String userId);
| List<EntityInstance> function(String tableName, String entityMappingId, int minCSN,int currentCSN,int maxCSN,String userId); | /**
* This method traces historical data back
*
* @param tableName the name of the table
* @param entityMappingId the mappingId stored mappingTable related to EntityInstance of baseTable
* @param minCSN the min csn of this entity
* @param currentCSN the csn user want to trace
* @param maxCSN the max csn of this entity
* @param userId the id of current user
* @return returns historical data (a list of EntityInstances include version details) based on given parameters
*/ | This method traces historical data back | traceEntities | {
"repo_name": "unsw-cse-soc/CoreDB",
"path": "src/CoreDB-Relational Pluggin/Library/src/coredb/controller/IEntityControllerTracing.java",
"license": "apache-2.0",
"size": 6495
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,020,807 |
public static File findUserDataDir() {
String xdgDataHome = System.getenv("XDG_DATA_HOME");
if ( xdgDataHome == null )
xdgDataHome = System.getProperty("user.home") +"/.local/share";
File[] candidates = new File[] {
// Windows XP
new File( System.getProperty("user.home") +"/My Documents/My Games/FasterThanLight" ),
// Windows Vista/7
new File( System.getProperty("user.home") +"/Documents/My Games/FasterThanLight" ),
// Linux
new File( xdgDataHome +"/FasterThanLight" ),
// OSX
new File( System.getProperty("user.home") +"/Library/Application Support/FasterThanLight" )
};
File result = null;
for ( File candidate : candidates ) {
if ( candidate.isDirectory() && candidate.exists() ) {
result = candidate;
break;
}
}
return result;
} | static File function() { String xdgDataHome = System.getenv(STR); if ( xdgDataHome == null ) xdgDataHome = System.getProperty(STR) +STR; File[] candidates = new File[] { new File( System.getProperty(STR) +STR ), new File( System.getProperty(STR) +STR ), new File( xdgDataHome +STR ), new File( System.getProperty(STR) +STR ) }; File result = null; for ( File candidate : candidates ) { if ( candidate.isDirectory() && candidate.exists() ) { result = candidate; break; } } return result; } | /**
* Returns the directory for user profiles and saved games, or null.
*/ | Returns the directory for user profiles and saved games, or null | findUserDataDir | {
"repo_name": "eric-stanley/Slipstream-Mod-Manager",
"path": "src/main/java/net/vhati/modmanager/core/FTLUtilities.java",
"license": "gpl-2.0",
"size": 8080
} | [
"java.io.File"
] | import java.io.File; | import java.io.*; | [
"java.io"
] | java.io; | 654,049 |
public synchronized boolean removeLock(Object bookmark, SessionInfo sessionInfo)
{
Utility.getLogger().info("Unlock: " + bookmark + ", Session: " + sessionInfo.m_iSessionID + " success: " + sessionInfo.equals(this.get(bookmark)));
if (!sessionInfo.equals(this.get(bookmark)))
return false; // Not my session - error.
if (this.getWaitlist(bookmark, false) != null)
if (this.getWaitlist(bookmark, false).size() > 0)
{ // Notify this person that the wait is over
SessionInfo sessionInfoToUnlock = this.getWaitlist(bookmark, true).get(0);
if (sessionInfoToUnlock == null)
return false; // Never
synchronized (sessionInfoToUnlock)
{
if (sessionInfoToUnlock != this.popWaitlistSession(bookmark))
return false; // Never since the only remove is this (synchronized line)
boolean bSuccess = sessionInfo.equals(this.remove(bookmark));
if (bSuccess) // Always
sessionInfoToUnlock.notify(); // Tell locked session to continue
return bSuccess;
}
}
return sessionInfo.equals(this.remove(bookmark));
} | synchronized boolean function(Object bookmark, SessionInfo sessionInfo) { Utility.getLogger().info(STR + bookmark + STR + sessionInfo.m_iSessionID + STR + sessionInfo.equals(this.get(bookmark))); if (!sessionInfo.equals(this.get(bookmark))) return false; if (this.getWaitlist(bookmark, false) != null) if (this.getWaitlist(bookmark, false).size() > 0) { SessionInfo sessionInfoToUnlock = this.getWaitlist(bookmark, true).get(0); if (sessionInfoToUnlock == null) return false; synchronized (sessionInfoToUnlock) { if (sessionInfoToUnlock != this.popWaitlistSession(bookmark)) return false; boolean bSuccess = sessionInfo.equals(this.remove(bookmark)); if (bSuccess) sessionInfoToUnlock.notify(); return bSuccess; } } return sessionInfo.equals(this.remove(bookmark)); } | /**
* Remove this bookmark from the lock list.
* @param bookmark The bookmark to lock.
* @param session The session to lock.
* @return true if successful.
*/ | Remove this bookmark from the lock list | removeLock | {
"repo_name": "jbundle/jbundle",
"path": "base/remote/src/main/java/org/jbundle/base/remote/lock/LockTable.java",
"license": "gpl-3.0",
"size": 5199
} | [
"org.jbundle.base.model.Utility"
] | import org.jbundle.base.model.Utility; | import org.jbundle.base.model.*; | [
"org.jbundle.base"
] | org.jbundle.base; | 704,031 |
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase#messagingEntityProvider")
@ParameterizedTest
void transactionScheduleAndCommitTest(MessagingEntityType entityType) {
// Arrange
boolean isSessionEnabled = false;
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final Duration scheduleDuration = Duration.ofSeconds(3);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
// Assert & Act
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(sender.createTransaction())
.assertNext(transactionContext -> {
transaction.set(transactionContext);
assertNotNull(transaction);
})
.verifyComplete();
StepVerifier.create(sender.scheduleMessage(message, OffsetDateTime.now().plusSeconds(5), transaction.get()))
.assertNext(sequenceNumber -> {
assertNotNull(sequenceNumber);
assertTrue(sequenceNumber.intValue() > 0);
})
.verifyComplete();
StepVerifier.create(sender.commitTransaction(transaction.get()))
.verifyComplete();
StepVerifier.create(Mono.delay(scheduleDuration).then(receiver.receiveMessages().next()))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
})
.verifyComplete();
} | @MethodSource(STR) void transactionScheduleAndCommitTest(MessagingEntityType entityType) { boolean isSessionEnabled = false; setSenderAndReceiver(entityType, 0, isSessionEnabled); final Duration scheduleDuration = Duration.ofSeconds(3); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(transactionContext -> { transaction.set(transactionContext); assertNotNull(transaction); }) .verifyComplete(); StepVerifier.create(sender.scheduleMessage(message, OffsetDateTime.now().plusSeconds(5), transaction.get())) .assertNext(sequenceNumber -> { assertNotNull(sequenceNumber); assertTrue(sequenceNumber.intValue() > 0); }) .verifyComplete(); StepVerifier.create(sender.commitTransaction(transaction.get())) .verifyComplete(); StepVerifier.create(Mono.delay(scheduleDuration).then(receiver.receiveMessages().next())) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .verifyComplete(); } | /**
* Verifies that we can create transaction, scheduleMessage and commit.
*/ | Verifies that we can create transaction, scheduleMessage and commit | transactionScheduleAndCommitTest | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSenderAsyncClientIntegrationTest.java",
"license": "mit",
"size": 22853
} | [
"com.azure.messaging.servicebus.implementation.MessagingEntityType",
"java.time.Duration",
"java.time.OffsetDateTime",
"java.util.UUID",
"java.util.concurrent.atomic.AtomicReference",
"org.junit.jupiter.api.Assertions",
"org.junit.jupiter.params.provider.MethodSource"
] | import com.azure.messaging.servicebus.implementation.MessagingEntityType; import java.time.Duration; import java.time.OffsetDateTime; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.provider.MethodSource; | import com.azure.messaging.servicebus.implementation.*; import java.time.*; import java.util.*; import java.util.concurrent.atomic.*; import org.junit.jupiter.api.*; import org.junit.jupiter.params.provider.*; | [
"com.azure.messaging",
"java.time",
"java.util",
"org.junit.jupiter"
] | com.azure.messaging; java.time; java.util; org.junit.jupiter; | 795,469 |
@Override
protected List<SimulationLogEntry> removeIrrelevantEntries(List<SimulationLogEntry> entries, TraceTransformerResult result) {
super.removeIrrelevantEntries(entries, result);
List<SimulationLogEntry> relevantEntries = new ArrayList<SimulationLogEntry>(entries);
for (SimulationLogEntry entry : relevantEntries) {
if (entry.getOriginatorCandidates() == null) {
relevantEntries.remove(entry);
addMessageToResult(getNoticeMessage(String.format(NOTICEF_NO_ORIGINATOR, entry.getActivity())), result);
}
}
return relevantEntries;
} | List<SimulationLogEntry> function(List<SimulationLogEntry> entries, TraceTransformerResult result) { super.removeIrrelevantEntries(entries, result); List<SimulationLogEntry> relevantEntries = new ArrayList<SimulationLogEntry>(entries); for (SimulationLogEntry entry : relevantEntries) { if (entry.getOriginatorCandidates() == null) { relevantEntries.remove(entry); addMessageToResult(getNoticeMessage(String.format(NOTICEF_NO_ORIGINATOR, entry.getActivity())), result); } } return relevantEntries; } | /**
* Removes all entries from the list of affected entries that contain
* <code>null</null> values for the originator field.
*
* @throws ParameterException
*/ | Removes all entries from the list of affected entries that contain <code>null values for the originator field | removeIrrelevantEntries | {
"repo_name": "iig-uni-freiburg/SecSy",
"path": "src/de/uni/freiburg/iig/telematik/secsy/logic/transformation/transformer/trace/abstr/SoDBoDPropertyTransformer.java",
"license": "bsd-3-clause",
"size": 10122
} | [
"de.uni.freiburg.iig.telematik.secsy.logic.generator.log.SimulationLogEntry",
"de.uni.freiburg.iig.telematik.secsy.logic.transformation.TraceTransformerResult",
"java.util.ArrayList",
"java.util.List"
] | import de.uni.freiburg.iig.telematik.secsy.logic.generator.log.SimulationLogEntry; import de.uni.freiburg.iig.telematik.secsy.logic.transformation.TraceTransformerResult; import java.util.ArrayList; import java.util.List; | import de.uni.freiburg.iig.telematik.secsy.logic.generator.log.*; import de.uni.freiburg.iig.telematik.secsy.logic.transformation.*; import java.util.*; | [
"de.uni.freiburg",
"java.util"
] | de.uni.freiburg; java.util; | 410,801 |
public Iterator iterator() {
return list.iterator();
} | Iterator function() { return list.iterator(); } | /**
* Description of the Method
*
* @return Description of the Return Value
*/ | Description of the Method | iterator | {
"repo_name": "medicayun/medicayundicom",
"path": "dcm4che14/tags/DCM4CHE_1_4_2/src/java/org/dcm4cheri/data/DcmObjectImpl.java",
"license": "apache-2.0",
"size": 83021
} | [
"java.util.Iterator"
] | import java.util.Iterator; | import java.util.*; | [
"java.util"
] | java.util; | 1,519,996 |
@Test
public void testMaxTextLength() throws IOException{
Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet();
Cell cell = sheet.createRow(0).createCell(0);
int maxlen = wb instanceof HSSFWorkbook ?
SpreadsheetVersion.EXCEL97.getMaxTextLength()
: SpreadsheetVersion.EXCEL2007.getMaxTextLength();
assertEquals(32767, maxlen);
StringBuffer b = new StringBuffer() ;
// 32767 is okay
for( int i = 0 ; i < maxlen ; i++ )
{
b.append( "X" ) ;
}
cell.setCellValue(b.toString());
b.append("X");
// 32768 produces an invalid XLS file
try {
cell.setCellValue(b.toString());
fail("Expected exception");
} catch (IllegalArgumentException e){
assertEquals("The maximum length of cell contents (text) is 32,767 characters", e.getMessage());
}
wb.close();
} | void function() throws IOException{ Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet(); Cell cell = sheet.createRow(0).createCell(0); int maxlen = wb instanceof HSSFWorkbook ? SpreadsheetVersion.EXCEL97.getMaxTextLength() : SpreadsheetVersion.EXCEL2007.getMaxTextLength(); assertEquals(32767, maxlen); StringBuffer b = new StringBuffer() ; for( int i = 0 ; i < maxlen ; i++ ) { b.append( "X" ) ; } cell.setCellValue(b.toString()); b.append("X"); try { cell.setCellValue(b.toString()); fail(STR); } catch (IllegalArgumentException e){ assertEquals(STR, e.getMessage()); } wb.close(); } | /**
* The maximum length of cell contents (text) is 32,767 characters.
* @throws IOException
*/ | The maximum length of cell contents (text) is 32,767 characters | testMaxTextLength | {
"repo_name": "lvweiwolf/poi-3.16",
"path": "src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java",
"license": "apache-2.0",
"size": 40623
} | [
"java.io.IOException",
"org.apache.poi.hssf.usermodel.HSSFWorkbook",
"org.apache.poi.ss.SpreadsheetVersion",
"org.junit.Assert"
] | import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.SpreadsheetVersion; import org.junit.Assert; | import java.io.*; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.*; import org.junit.*; | [
"java.io",
"org.apache.poi",
"org.junit"
] | java.io; org.apache.poi; org.junit; | 2,708,288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.