auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testErrorMessageOnInvalidLambdaBody() { assertInvalidFunction("reduce(ARRAY [1, 2], 0, (s, x) -> concat(s, x), s -> s)", FUNCTION_NOT_FOUND); }

Target:
public void testErrorMessageOnInvalidLambdaBody() { assertInvalidFunction("reduce(ARRAY [1, 2], 0, (s, x) -> concat(s, x), s -> s)", FUNCTION_NOT_FOUND, "Unexpected parameters (integer, integer) for function concat. Expected: concat(array(E), E) for type(s): E or concat(E, array(E)) for type(s): E or concat(array(E)) for type(s): E (wrong number of arguments: expected 1 got 2) or concat(varchar) for type(s): (wrong number of arguments: expected 1 got 2) or concat(varbinary) for type(s): (wrong number of arguments: expected 1 got 2)"); }
Source:
public TenderFilter(Double minPrice, Double maxPrice, List<Integer> categories, List<Integer> locations, List<Integer> items, List<Integer> statuses, Date minDate, Date maxDate) { this.minPrice = (minPrice!=null)?minPrice:0; this.maxPrice = (maxPrice!=null)?maxPrice:999999999.99; if (categories==null) { setCategoryFlag(1); }else { this.categories =categories; setCategoryFlag(0); } if (locations==null){ setLocationFlag(1); }else { this.locations = locations; setLocationFlag(0); } if (items==null){ setItemFlag(1); }else { this.items = items; setItemFlag(0); } if (statuses==null) { List<Integer> list = new ArrayList<>(); list.add(OPEN_TENDER_STATUS); list.add(IN_PROGRESS_TENDER_STATUS); setStatuses(list); }else { this.statuses = statuses; } this.minDate = (minDate!=null)?minDate:new Date(); this.maxDate = (maxDate!=null)?maxDate:new Date((new Date().getTime())+2419200000l); }

Target:
public TenderFilter(Double minPrice, Double maxPrice, List<Integer> categories, List<Integer> locations, List<Integer> items, List<Integer> statuses, Date minDate, Date maxDate) { this.minPrice = (minPrice!=null)?minPrice:0; this.maxPrice = (maxPrice!=null)?maxPrice:999999999.99; if (categories==null) { setCategoryFlag(1); }else { this.categories =categories; setCategoryFlag(0); } if (locations==null){ setLocationFlag(1); }else { this.locations = locations; setLocationFlag(0); } if (items==null){ setItemFlag(1); }else { this.items = items; setItemFlag(0); } if (statuses==null) { List<Integer> list = new ArrayList<>(); list.add(OPEN_TENDER_STATUS); list.add(IN_PROGRESS_TENDER_STATUS); setStatuses(list); }else { this.statuses = statuses; } this.minDate = (minDate!=null)?minDate:new Date((new Date().getTime())-604800000l); this.maxDate = (maxDate!=null)?maxDate:new Date(); }
Source:
protected File doInBackground(Void... voids) { mAppMorph.morphApp(mLabel, mIcon); return null; }

Target:
protected Void doInBackground(Void... voids) { mAppMorph.morphApp(mLabel, mIcon); return null; }
Source:
protected VDS selectBestProxy(FenceProxySourceType fenceProxySource, Guid excludedHostId) { return getDbFacade().getVdsDao().getAll().stream() .filter(vds -> !vds.getId().equals(fencedHost.getId()) && !isHostExcluded(vds, excludedHostId) && isHostFromSelectedSource(vds, fenceProxySource) && areAgentsVersionCompatible(vds) && isFencingPolicySupported(vds, getMinSupportedVersionForFencingPolicy()) && !isHostNetworkUnreachable(vds)) .sorted((x, y) -> (x.getStatus() == VDSStatus.Up ? -1 : y.getStatus() == VDSStatus.Up ? 1 : 0)) .findFirst() .orElse(null); }

Target:
protected VDS selectBestProxy(FenceProxySourceType fenceProxySource, Guid excludedHostId) { return getDbFacade().getVdsDao().getAll().stream() .peek(vds -> log.debug("Evaluating host '{}'", vds.getHostName())) .filter(vds -> !Objects.equals(vds.getId(), fencedHost.getId())) .filter(vds -> !isHostExcluded(vds, excludedHostId)) .filter(vds -> isHostFromSelectedSource(vds, fenceProxySource)) .filter(this::areAgentsVersionCompatible) .filter(vds -> isFencingPolicySupported(vds, getMinSupportedVersionForFencingPolicy())) .filter(vds -> !isHostNetworkUnreachable(vds)) .sorted(Comparator.comparingInt(vds -> vds.getStatus() == VDSStatus.Up ? -1 : 1)) .findFirst() .orElse(null); }
Source:
public void illegalStateExceptionThrownWhenConstraintMatchNotEnabled() { ScoreHolder scoreHolder = buildScoreHolder(false); thrown.expect(IllegalStateException.class); thrown.expectMessage("constraintMatchEnabled"); scoreHolder.getConstraintMatchTotals().clear(); }

Target:
public void illegalStateExceptionThrownWhenConstraintMatchNotEnabled() { ScoreHolder scoreHolder = buildScoreHolder(false); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("constraintMatchEnabled"); scoreHolder.getConstraintMatchTotals().clear(); }
Source:
public PositionedCryptoInputStream(Properties props, InputStream in, byte[] key, byte[] iv, long streamOffset) throws IOException { this(in, Utils.getCipherInstance(props), Utils.getBufferSize(props), key, iv, streamOffset); }

Target:
public PositionedCryptoInputStream(Properties props, InputStream in, byte[] key, byte[] iv, long streamOffset) throws IOException { this(in, CipherFactory.getInstance(props), Utils.getBufferSize(props), key, iv, streamOffset); }
Source:
protected Map<String, Object> removeSection(ParameterParser params, SessionState state) { String message; String errorMessage = null; Map<String, Object> results = new HashMap<String, Object>(); try { int locationId = params.getInt("locationId"); CitationCollection collection = getCitationCollection(state, false); errorMessage = getCitationValidator().getRemoveSectionErrorMessage(collection, locationId); if (errorMessage==null){ getCitationService().removeLocation(collection.getId(), locationId); message = rb.getString("resource.updated"); results.put("sectionToRemove", "#sectionInlineEditor" + locationId); logger.info("Reading list successfully updated."); } else { message = errorMessage; logger.warn("Invalid citation list in removeSection(). " + errorMessage); } state.setAttribute(STATE_CITATION_COLLECTION, null); } catch (Exception e){ message = e.getMessage(); logger.warn("Exception in removeSection() " + e); } if(errorMessage==null && message != null && ! message.trim().equals("")) { results.put("message", message); } else { results.put("Error: ", new String[]{errorMessage}); } return results; }

Target:
protected Map<String, Object> removeSection(ParameterParser params, SessionState state) { String message; String errorMessage = null; Map<String, Object> results = new HashMap<String, Object>(); try { int locationId = params.getInt("locationId"); CitationCollection collection = getCitationCollection(state, false); errorMessage = getCitationValidator().getRemoveSectionErrorMessage(collection, locationId); if (errorMessage==null){ getCitationService().removeLocation(collection.getId(), locationId); message = rb.getString("resource.updated"); results.put("sectionToRemove", "#sectionInlineEditor" + locationId); logger.debug("Reading list with collection id: " + collection.getId() + " successfully updated. Section removed at location: " + locationId); } else { message = errorMessage; logger.warn("Invalid citation list with collection id: " + collection.getId() + " in removeSection(). " + errorMessage); } state.setAttribute(STATE_CITATION_COLLECTION, null); } catch (Exception e){ message = e.getMessage(); logger.warn("Exception in removeSection() " + e); } if(errorMessage==null && message != null && ! message.trim().equals("")) { results.put("message", message); } else { results.put("Error: ", new String[]{errorMessage}); } return results; }
Source:
public QueryInterruptedException(Throwable cause) { super(cause); host = null; causeMessage = null; }

Target:
public QueryInterruptedException(Throwable cause) { this(cause, null); }
Source:
protected SafeHtml getImageSafeHtml(IconType iconType) { return SafeHtmlUtils.fromTrustedString("<i class='fa "+ iconType.getCssName() + "' style='font-size:16px;color:orange'></i>"); }

Target:
protected SafeHtml getImageSafeHtml(IconType iconType) { return AssetProvider.getTemplates().iconTypeAlertTemplate(iconType.getCssName()); }
Source:
public void postProcess(BeanDefinitionBuilder builder, RepositoryConfigurationSource source) { String transactionManagerRef = source.getAttribute("transactionManagerRef"); builder.addPropertyValue("transactionManager", transactionManagerRef == null ? DEFAULT_TRANSACTION_MANAGER_BEAN_NAME : transactionManagerRef); String entityManagerFactoryRef = getEntityManagerFactoryRef(source); if (entityManagerFactoryRef != null) { builder.addPropertyValue("entityManager", getEntityManagerBeanDefinitionFor(entityManagerFactoryRef, source)); } builder.addPropertyReference("mappingContext", JPA_MAPPING_CONTEXT_BEAN_NAME); String expressionEvaluationContextProviderRef = source.getAttribute("expressionEvaluationContextProviderRef"); if (StringUtils.hasText(expressionEvaluationContextProviderRef)) { builder.addPropertyReference(DEFAULT_EXPRESSION_EVALUATION_CONTEXT_PROVIDER, expressionEvaluationContextProviderRef); } }

Target:
public void postProcess(BeanDefinitionBuilder builder, RepositoryConfigurationSource source) { String transactionManagerRef = source.getAttribute("transactionManagerRef"); builder.addPropertyValue("transactionManager", transactionManagerRef == null ? DEFAULT_TRANSACTION_MANAGER_BEAN_NAME : transactionManagerRef); String entityManagerFactoryRef = getEntityManagerFactoryRef(source); if (entityManagerFactoryRef != null) { builder.addPropertyValue("entityManager", getEntityManagerBeanDefinitionFor(entityManagerFactoryRef, source)); } builder.addPropertyReference("mappingContext", JPA_MAPPING_CONTEXT_BEAN_NAME); }
Source:
protected void handleGenerateMementoException(Exception e, String context) { Exceptions.propagateIfFatal(e); if (isActive()) { LOG.warn("Problem generating memento for "+context, e); } else { Exceptions.propagateIfFatal(e); LOG.debug("Problem generating memento for "+context+", but no longer active (ignoring)", e); } }

Target:
protected void handleGenerateMementoException(Exception e, String context) { Exceptions.propagateIfFatal(e); if (isActive()) { LOG.warn("Problem generating memento for "+context, e); } else { LOG.debug("Problem generating memento for "+context+", but no longer active (ignoring)", e); } }
Source:
public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { super.placeBlock(player, state, face, holding, clickedLoc); final MaterialData data = state.getData(); if (!(data instanceof Button)) { GlowServer.logger.warning("Placing " + getMaterial().name() + ": MaterialData was of wrong type (" + data.getClass().getName() + ")"); return; } final Button button = (Button) data; setAttachedFace(button, face.getOppositeFace()); }

Target:
public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { super.placeBlock(player, state, face, holding, clickedLoc); MaterialData data = state.getData(); if (!(data instanceof Button)) { warnMaterialData(Button.class, data); return; } setAttachedFace(state, face.getOppositeFace()); }
Source:
public static VM buildVmsDataFromExternalProvider(Map<String, Object> xmlRpcStruct) { VmStatic vmStatic = buildVmStaticDataFromExternalProvider(xmlRpcStruct); if (vmStatic == null) { return null; } VmDynamic vmDynamic = buildVMDynamicDataFromList(xmlRpcStruct); VM vm = new VM(vmStatic, vmDynamic, new VmStatistics()); for (DiskImage image : vm.getImages()) { vm.getDiskMap().put(Guid.newGuid(), image); } try { vm.setClusterArch(parseArchitecture(xmlRpcStruct)); } catch (IllegalArgumentException ex) { log.error("Illegal architecture type, error: %s", ex.getMessage()); vm.setClusterArch(ArchitectureType.x86_64); } return vm; }

Target:
public static VM buildVmsDataFromExternalProvider(Map<String, Object> xmlRpcStruct) { VmStatic vmStatic = buildVmStaticDataFromExternalProvider(xmlRpcStruct); if (vmStatic == null) { return null; } VmDynamic vmDynamic = buildVMDynamicDataFromList(xmlRpcStruct); VM vm = new VM(vmStatic, vmDynamic, new VmStatistics()); for (DiskImage image : vm.getImages()) { vm.getDiskMap().put(Guid.newGuid(), image); } try { vm.setClusterArch(parseArchitecture(xmlRpcStruct)); } catch (IllegalArgumentException ex) { log.error("Illegal architecture type while trying to read %s, error: %s", VdsProperties.vm_arch, ex.getMessage()); vm.setClusterArch(ArchitectureType.x86_64); } return vm; }
Source:
private Object getDhisResponseForHttpResponse(String json, String uri, CloseableHttpResponse response, Class responseType) { Object status; try (InputStream content = getContentForResponse(response)) { String contentString = IOUtils.toString(content); LOGGER.debug(String.format("Received response to create resource: %s, request: %s", contentString, json)); status = new ObjectMapper().readValue(contentString, responseType); if (status.toString().contains("ERROR")) { String msg = String.format("Error in DHIS2 status response, error details: %s", contentString); throw new DhisWebException(msg); } } catch (IOException e) { String msg = String.format("Error parsing response from uri: %s, exception: %s", uri, e.toString()); statusMessageService.warn(msg, MODULE_NAME); throw new DhisWebException(msg, e); } finally { closeResponse(response); } return status; }

Target:
private DhisResponse getDhisResponseForHttpResponse(String json, String uri, CloseableHttpResponse response, Class responseType) { DhisResponse status; try (InputStream content = getContentForResponse(response)) { String contentString = IOUtils.toString(content); LOGGER.debug(String.format("Received response to create resource: %s, request: %s", contentString, json)); if(responseType == DhisStatusResponse.class) { status = new ObjectMapper().readValue(contentString, DhisStatusResponse.class); } else { status = new ObjectMapper().readValue(contentString, DhisDataValueStatusResponse.class); } if (status.getStatus() == DhisStatus.ERROR) { String msg = String.format("Error in DHIS2 status response, error details: %s", contentString); throw new DhisWebException(msg); } } catch (IOException e) { String msg = String.format("Error parsing response from uri: %s, exception: %s", uri, e.toString()); statusMessageService.warn(msg, MODULE_NAME); throw new DhisWebException(msg, e); } finally { closeResponse(response); } return status; }
Source:
IndexValue(String logSegmentName, ByteBuffer value, short version) { this.version = version; switch (version) { case PersistentIndex.VERSION_0: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V0) { throw new IllegalArgumentException("Invalid buffer size for version 0"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); expiresAtMs = value.getLong(); relatedMessageOffset = value.getLong(); operationTimeInMs = (int) Utils.Infinite_Time; accountId = UNKNOWN_ACCOUNT_ID; containerId = UNKNOWN_CONTAINER_ID; break; case PersistentIndex.VERSION_1: case PersistentIndex.VERSION_2: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V1) { throw new IllegalArgumentException("Invalid buffer size for version 1"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); long expiresAt = value.getInt(); expiresAtMs = expiresAtMs != Utils.Infinite_Time && expiresAt >= 0 ? TimeUnit.SECONDS.toMillis(expiresAt) : Utils.Infinite_Time; relatedMessageOffset = value.getLong(); long operationTimeInSecs = value.getInt(); operationTimeInMs = operationTimeInSecs != Utils.Infinite_Time ? TimeUnit.SECONDS.toMillis(operationTimeInSecs) : Utils.Infinite_Time; accountId = value.getShort(); containerId = value.getShort(); break; default: throw new IllegalArgumentException("Unsupported version " + version + " passed in for IndexValue "); } }

Target:
IndexValue(String logSegmentName, ByteBuffer value, short version) { this.version = version; switch (version) { case PersistentIndex.VERSION_0: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V0) { throw new IllegalArgumentException("Invalid buffer size for version 0"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); expiresAtMs = value.getLong(); originalMessageOffset = value.getLong(); operationTimeInMs = (int) Utils.Infinite_Time; accountId = UNKNOWN_ACCOUNT_ID; containerId = UNKNOWN_CONTAINER_ID; break; case PersistentIndex.VERSION_1: case PersistentIndex.VERSION_2: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V1) { throw new IllegalArgumentException("Invalid buffer size for version 1"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); long expiresAt = value.getInt(); expiresAtMs = expiresAt != Utils.Infinite_Time && expiresAt >= 0 ? TimeUnit.SECONDS.toMillis(expiresAt) : Utils.Infinite_Time; originalMessageOffset = value.getLong(); long operationTimeInSecs = value.getInt(); operationTimeInMs = operationTimeInSecs != Utils.Infinite_Time ? TimeUnit.SECONDS.toMillis(operationTimeInSecs) : Utils.Infinite_Time; accountId = value.getShort(); containerId = value.getShort(); break; default: throw new IllegalArgumentException("Unsupported version " + version + " passed in for IndexValue "); } }
Source:
protected void clearData()

Target:
protected void clearData() { getSnapshots().clear(); mObjectCache.clear(); }
Source:
public static SourceFile fromZipEntry( String originalZipPath, String absoluteZipPath, String entryPath, Charset inputCharset) throws MalformedURLException { String zipEntryPath = JAR_URL_PREFIX + absoluteZipPath + BANG_SLASH + entryPath.replace(File.pathSeparatorChar, '/'); URL zipEntryUrl = new URL(zipEntryPath); return builder() .withCharset(inputCharset) .withOriginalPath(originalZipPath + BANG_SLASH + entryPath) .buildFromUrl(zipEntryUrl); }

Target:
public static SourceFile fromZipEntry( String originalZipPath, String absoluteZipPath, String entryPath, Charset inputCharset) throws MalformedURLException { String zipEntryPath = JAR_URL_PREFIX + absoluteZipPath + BANG_SLASH + entryPath.replace(File.separator, "/"); URL zipEntryUrl = new URL(zipEntryPath); return builder() .withCharset(inputCharset) .withOriginalPath(originalZipPath + BANG_SLASH + entryPath) .buildFromUrl(zipEntryUrl); }
Source:
public QueryBuilder doRewrite(QueryRewriteContext context) throws IOException { OsStats.Cpu cpu = osService.stats().getCpu(); return super.doRewrite(condition -> condition.test(cpu)); }

Target:
public QueryBuilder doRewrite(QueryRewriteContext context) throws IOException { context.nowInMillis(); OsStats.Cpu cpu = osService.stats().getCpu(); return super.doRewrite(condition -> condition.test(cpu)); }
Source:
private static Integer runCommandAndWait( String command, String workingDir, String extraPath ) throws Exception { String path = System.getenv( "PATH" ); if (extraPath != null) { path = extraPath + File.pathSeparator + path; } Process proc = Runtime.getRuntime().exec(command, new String[] {"M2_HOME=" + MVN_LOCATION, "PATH=" + path}, new File(workingDir)); File buildlog = new File(workingDir, "build.log"); try ( BufferedReader stdout = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); BufferedReader stderr = new BufferedReader( new InputStreamReader( proc.getErrorStream() ) ); PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( buildlog, true ) ) ) ) { String line; String errline = null; while ( ( line = stdout.readLine() ) != null || ( errline = stderr.readLine() ) != null ) { if ( line != null ) { out.println( line ); } if ( errline != null ) { out.println( errline ); } } return proc.waitFor(); } }

Target:
private static Integer runCommandAndWait( String command, String workingDir, String extraPath ) throws Exception { String path = System.getenv( "PATH" ); if (extraPath != null) { path = extraPath + File.pathSeparator + path; } Process proc = Runtime.getRuntime().exec(command, new String[] {"PATH=" + path}, new File(workingDir)); File buildlog = new File(workingDir, "build.log"); try ( BufferedReader stdout = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); BufferedReader stderr = new BufferedReader( new InputStreamReader( proc.getErrorStream() ) ); PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( buildlog, true ) ) ) ) { String line; String errline = null; while ( ( line = stdout.readLine() ) != null || ( errline = stderr.readLine() ) != null ) { if ( line != null ) { out.println( line ); } if ( errline != null ) { out.println( errline ); } } return proc.waitFor(); } }
Source:
public void connect() { if (countRetry == 0) { return; } if (!connected) { terminalHolder .getInitializerPromise() .then( aVoid -> { ServerImpl terminalServer = machine .getServerByName(SERVER_TERMINAL_REFERENCE) .orElseThrow( () -> new OperationException( "Machine " + machine.getName() + " doesn't provide terminal server.")); connectToTerminal(wsAgentURLModifier.modify(terminalServer.getUrl())); }) .catchError( arg -> { notificationManager.notify( locale.failedToConnectTheTerminal(), locale.terminalCanNotLoadScript(), FAIL, NOT_EMERGE_MODE); reconnect(); }); } }

Target:
public void connect() { if (countRetry == 0) { return; } if (!connected) { terminalHolder .getInitializerPromise() .then( aVoid -> { ServerImpl terminalServer = machine .getServerByName(SERVER_TERMINAL_REFERENCE) .orElseThrow( () -> new OperationException( "Machine " + machine.getName() + " doesn't provide terminal server.")); connectToTerminal(agentURLModifier.modify(terminalServer.getUrl())); }) .catchError( arg -> { notificationManager.notify( locale.failedToConnectTheTerminal(), locale.terminalCanNotLoadScript(), FAIL, NOT_EMERGE_MODE); reconnect(); }); } }
Source:
private void createPreparedStatements() { Select.Where select = QueryBuilder .select() .all() .from( CassandraModel.CF_METRICS_LOCATOR_NAME ) .where( eq ( "key", bindMarker() )); getValue = DatastaxIO.getSession().prepare( select ); Insert insert = QueryBuilder.insertInto(CassandraModel.QUOTED_KEYSPACE, CassandraModel.CF_METRICS_LOCATOR_NAME) .using(ttl(TenantTtlProvider.LOCATOR_TTL)) .value(KEY, bindMarker()) .value(COLUMN1, bindMarker()) .value(VALUE, bindMarker()); putValue = DatastaxIO.getSession() .prepare(insert) .setConsistencyLevel( ConsistencyLevel.ONE); }

Target:
private void createPreparedStatements() { Select.Where select = QueryBuilder .select() .all() .from( CassandraModel.CF_METRICS_LOCATOR_NAME ) .where( eq ( KEY, bindMarker() )); getValue = DatastaxIO.getSession().prepare( select ); Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_LOCATOR_NAME) .using(ttl(TenantTtlProvider.LOCATOR_TTL)) .value(KEY, bindMarker()) .value(COLUMN1, bindMarker()) .value(VALUE, bindMarker()); putValue = DatastaxIO.getSession() .prepare(insert) .setConsistencyLevel( ConsistencyLevel.ONE); }
Source:
public ImportApplicationViewImpl(OpenshiftLocalizationConstant locale, CoreLocalizationConstant constants, org.eclipse.che.ide.Resources resources, OpenshiftResources openshiftResources) { this.locale = locale; this.openshiftResources = openshiftResources; openshiftResources.css().ensureInjected(); ensureDebugId("importApplication"); setTitle(locale.importApplicationViewTitle()); setWidget(uiBinder.createAndBindUi(this)); importButton = createPrimaryButton(locale.importApplicationImportButton(), "importApplication-import-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onImportApplicationClicked(); } }); addButtonToFooter(importButton); cancelButton = createButton(constants.cancel(), "importApplication-cancel-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onCancelClicked(); } }); addButtonToFooter(cancelButton); buildConfigList = new CategoriesList(resources); categoriesPanel.add(buildConfigList); getWidget().getElement().getStyle().setPadding(0, Style.Unit.PX); }

Target:
public ImportApplicationViewImpl(OpenshiftLocalizationConstant locale, CoreLocalizationConstant constants, org.eclipse.che.ide.Resources resources, OpenshiftResources openshiftResources) { this.locale = locale; this.openshiftResources = openshiftResources; ensureDebugId("importApplication"); setTitle(locale.importApplicationViewTitle()); setWidget(uiBinder.createAndBindUi(this)); importButton = createPrimaryButton(locale.importApplicationImportButton(), "importApplication-import-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onImportApplicationClicked(); } }); addButtonToFooter(importButton); cancelButton = createButton(constants.cancel(), "importApplication-cancel-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onCancelClicked(); } }); addButtonToFooter(cancelButton); buildConfigList = new CategoriesList(resources); categoriesPanel.add(buildConfigList); getWidget().getElement().getStyle().setPadding(0, Style.Unit.PX); }
Source:
public void multiple_callbacks_should_be_invoked_realmresults_sync() { final int NUMBER_OF_LISTENERS = 7; final Realm realm = looperThread.realm; realm.addChangeListener(new RealmChangeListener<Realm>() { @Override public void onChange(Realm object) { looperThread.postRunnable(new Runnable() { @Override public void run() { assertEquals(NUMBER_OF_LISTENERS, typebasedCommitInvocations.get()); looperThread.testComplete(); } }); } }); realm.beginTransaction(); Dog akamaru = realm.createObject(Dog.class); realm.commitTransaction(); looperThread.keepStrongReference.add(akamaru); RealmResults<Dog> dogs = realm.where(Dog.class).findAll(); looperThread.keepStrongReference.add(dogs); for (int i = 0; i < NUMBER_OF_LISTENERS; i++) { dogs.addChangeListener(new RealmChangeListener<RealmResults<Dog>>() { @Override public void onChange(RealmResults<Dog> object) { typebasedCommitInvocations.incrementAndGet(); } }); } realm.beginTransaction(); akamaru.setAge(17); realm.commitTransaction(); }

Target:
public void multiple_callbacks_should_be_invoked_realmresults_sync() { final int NUMBER_OF_LISTENERS = 7; final Realm realm = looperThread.realm; realm.addChangeListener(new RealmChangeListener<Realm>() { @Override public void onChange(Realm object) { looperThread.postRunnable(new Runnable() { @Override public void run() { assertEquals(NUMBER_OF_LISTENERS, typebasedCommitInvocations.get()); looperThread.testComplete(); } }); } }); realm.beginTransaction(); Dog akamaru = realm.createObject(Dog.class); realm.commitTransaction(); RealmResults<Dog> dogs = realm.where(Dog.class).findAll(); looperThread.keepStrongReference.add(dogs); for (int i = 0; i < NUMBER_OF_LISTENERS; i++) { dogs.addChangeListener(new RealmChangeListener<RealmResults<Dog>>() { @Override public void onChange(RealmResults<Dog> object) { typebasedCommitInvocations.incrementAndGet(); } }); } realm.beginTransaction(); akamaru.setAge(17); realm.commitTransaction(); }
Source:
public static MixpanelAPI getInstance(Context context, String token) { if (null == token || null == context) { return null; } synchronized (sInstanceMap) { final Context appContext = context.getApplicationContext(); if (null == sReferrerPrefs) { sReferrerPrefs = sPrefsLoader.loadPreferences(context, MPConfig.REFERRER_PREFS_NAME, null); } Map <Context, MixpanelAPI> instances = sInstanceMap.get(token); if (null == instances) { instances = new HashMap<Context, MixpanelAPI>(); sInstanceMap.put(token, instances); } MixpanelAPI instance = instances.get(appContext); if (null == instance) { instance = new MixpanelAPI(appContext, sReferrerPrefs, token); instances.put(appContext, instance); } if (context instanceof Activity) { try { Class<?> clazz = Class.forName("bolts.AppLinks"); Intent intent = ((Activity) context).getIntent(); Method getTargetUrlFromInboundIntent = clazz.getMethod("getTargetUrlFromInboundIntent", Context.class, Intent.class); getTargetUrlFromInboundIntent.invoke(null, context, intent); } catch (Exception e) { Log.d(LOGTAG, "Unable to detect inbound App Links.", e); } } else { Log.d(LOGTAG, "Context is not an instance of Activity. To detect inbound App Links, pass an instance of an Activity to getInstance."); } return instance; } }

Target:
public static MixpanelAPI getInstance(Context context, String token) { if (null == token || null == context) { return null; } synchronized (sInstanceMap) { final Context appContext = context.getApplicationContext(); if (null == sReferrerPrefs) { sReferrerPrefs = sPrefsLoader.loadPreferences(context, MPConfig.REFERRER_PREFS_NAME, null); } Map <Context, MixpanelAPI> instances = sInstanceMap.get(token); if (null == instances) { instances = new HashMap<Context, MixpanelAPI>(); sInstanceMap.put(token, instances); } MixpanelAPI instance = instances.get(appContext); if (null == instance) { instance = new MixpanelAPI(appContext, sReferrerPrefs, token); registerAppLinksListeners(context, instance); instances.put(appContext, instance); } checkIntentForInboundAppLink(context); return instance; } }
Source:
public String validateUserCredentials(String url, String username, char[] password) { try (CloseableHttpClient httpClient = new CommonHttpClientBuilder().allowAnyCertificate(true).build()) { HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(USER_KEY, username)); params.add(new BasicNameValuePair(SECRET_KEY, String.valueOf(password))); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); if ((httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) || (null == httpResponse.getEntity())) throw new IAMException("Failed to validate credentials of user '" + username, new HTTPException(httpResponse.getStatusLine().getStatusCode())); return EntityUtils.toString(httpResponse.getEntity()); } catch (Exception e) { throw new IAMException("Error occurred while validating credentials of user [" + username + "]", e); } }

Target:
public String validateUserCredentials(String url, String username, char[] password) { try (CloseableHttpClient httpClient = new CommonHttpClientBuilder().allowAnyCertificate(true).build()) { HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(USER_KEY, username)); params.add(new BasicNameValuePair(SECRET_KEY, String.valueOf(password))); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); if ((httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) || (null == httpResponse.getEntity())) { throw new IAMException("Failed to validate credentials of user '" + username, new HTTPException(httpResponse.getStatusLine().getStatusCode())); } return EntityUtils.toString(httpResponse.getEntity()); } catch (Exception e) { throw new IAMException("Error occurred while validating credentials of user [" + username + "]", e); } }
Source:
public static int discoverPartitions(Path basePath) { try (Stream<Path> paths = Files.list(basePath)) { int ret = (int) paths.filter( path -> (path.toFile().isDirectory() && path.getFileName().toString().startsWith(PARTITION_PREFIX))) .count(); if (ret == 0) { throw new IOException("No chronicles queues file found"); } return ret; } catch (IOException e) { throw new IllegalArgumentException("Invalid basePath for queue: " + basePath, e); } }

Target:
public static int discoverPartitions(Path basePath) { try (Stream<Path> paths = Files.list(basePath)) { int ret = (int) paths.filter(ChronicleLogAppender::isPartitionDirectory).count(); if (ret == 0) { throw new IOException("No chronicles queues file found"); } return ret; } catch (IOException e) { throw new IllegalArgumentException("Invalid basePath for queue: " + basePath, e); } }
Source:
public Storage update(Storage connection) { validateParameters(connection, "address", "type", "host"); validateEnums(Storage.class, connection); return performUpdate(connection, new QueryIdResolver<String>(VdcQueryType.GetStorageServerConnectionById, StorageServerConnectionQueryParametersBase.class), VdcActionType.UpdateStorageServerConnection, new UpdateParametersProvider()); }

Target:
public Storage update(Storage connection) { validateParameters(connection, "host.id|name"); validateEnums(Storage.class, connection); return performUpdate(connection, new QueryIdResolver<String>(VdcQueryType.GetStorageServerConnectionById, StorageServerConnectionQueryParametersBase.class), VdcActionType.UpdateStorageServerConnection, new UpdateParametersProvider()); }
Source:
public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isAvailable(); if(isConnected && !NetworkUtil.isOnZeroRatedNetwork(context)) { logger.debug("Have reconnected, testing download speed."); Intent speedTestIntent = new Intent(context, DownloadSpeedService.class); String downloadEndpoint = context.getString(R.string.speed_test_url); speedTestIntent.putExtra(DownloadSpeedService.EXTRA_FILE_DESC, new DownloadDescriptor(downloadEndpoint, !isFirstStart)); context.startService(speedTestIntent); isFirstStart = true; } if (NetworkUtil.isConnectedMobile(context)){ ISegment segIO = SegmentFactory.getInstance(); TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); String carrierName = manager.getNetworkOperatorName(); segIO.trackUserCellConnection(carrierName, NetworkUtil.isOnZeroRatedNetwork(context)); } }

Target:
public void onReceive(Context context, Intent intent) { if(Config.getInstance().isSpeedTestEnabled()) { ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isAvailable(); if (isConnected) { logger.debug("Have reconnected, testing download speed."); Intent speedTestIntent = new Intent(context, DownloadSpeedService.class); String downloadEndpoint = context.getString(R.string.speed_test_url); speedTestIntent.putExtra(DownloadSpeedService.EXTRA_FILE_DESC, new DownloadDescriptor(downloadEndpoint, !isFirstStart)); context.startService(speedTestIntent); isFirstStart = true; } } if (NetworkUtil.isConnectedMobile(context)){ ISegment segIO = SegmentFactory.getInstance(); TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); String carrierName = manager.getNetworkOperatorName(); segIO.trackUserCellConnection(carrierName, NetworkUtil.isOnZeroRatedNetwork(context)); } }
Source:
public boolean isTotalOrderCache(String cacheName) { if (!running) { if (log.isDebugEnabled()) { log.debugf("isTotalOrderCache(%s) returning false because the local cache manager is not running", cacheName); } return false; } LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { if (log.isDebugEnabled()) { log.debugf("isTotalOrderCache(%s) returning false because the cache doesn't exist locally", cacheName); } return false; } boolean totalOrder = cacheStatus.getJoinInfo().isTotalOrder(); if (log.isDebugEnabled()) { log.debugf("isTotalOrderCache(%s) returning %s", cacheName, totalOrder); } return totalOrder; }

Target:
public boolean isTotalOrderCache(String cacheName) { if (!running) { if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning false because the local cache manager is not running", cacheName); } return false; } LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning false because the cache doesn't exist locally", cacheName); } return false; } boolean totalOrder = cacheStatus.getJoinInfo().isTotalOrder(); if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning %s", cacheName, totalOrder); } return totalOrder; }
Source:
Optional<User> getUser(final UUID uuid) { this.pollFilesystemWatcher(); if (this.knownUUIDs.contains(uuid)) { return this.getUser((GameProfile) this.server.getPlayerProfileCache().getProfileByUUID(uuid), false); } return Optional.empty(); }

Target:
Optional<User> getUser(final UUID uuid) { return this.getUser((GameProfile) this.server.getPlayerProfileCache().getProfileByUUID(uuid)); }
Source:
public void onSendTagsClicked(View v) { try { OneSignal.setExternalUserId("mikechoch_" + sendTagsCounter, new OneSignal.ExternalUserIdUpdateHandler() { @Override public void onSuccess(String newExternalUserId) { OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, newExternalUserId + " was set SUCCESS"); } @Override public void onFailure(OneSignal.ExternalUserIdError error) { OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Error setting external id: " + error.getMessage() + " with code: " + error.getCode()); } }); OneSignal.sendTags(new JSONObject("{\"counter\" : " + sendTagsCounter + ", \"test_value\" : \"test_key\"}"), new OneSignal.ChangeTagsUpdateHandler() { @Override public void onSuccess(JSONObject tags) { updateTextView("Successfully sent tags: " + tags.toString()); } @Override public void onFailure(OneSignal.SendTagsError error) { updateTextView("Failed to send tags: " + error.toString()); } }); sendTagsCounter++; } catch (JSONException exception) { updateTextView("Failed to serialize tags into JSON: " + exception.getMessage()); } }

Target:
public void onSendTagsClicked(View v) { try { OneSignal.sendTags(new JSONObject("{\"counter\" : " + sendTagsCounter + ", \"test_value\" : \"test_key\"}"), new OneSignal.ChangeTagsUpdateHandler() { @Override public void onSuccess(JSONObject tags) { updateTextView("Successfully sent tags: " + tags.toString()); } @Override public void onFailure(OneSignal.SendTagsError error) { updateTextView("Failed to send tags: " + error.toString()); } }); sendTagsCounter++; } catch (JSONException exception) { updateTextView("Failed to serialize tags into JSON: " + exception.getMessage()); } }
Source:
public Collection<LivingEntity> getEntitiesInRange() { return getWorld().getNearbyEntitiesByType(Player.class, getLocation(), getTier() * 10 + 10, getWorld().getMaxHeight()); }

Target:
public Collection<LivingEntity> getEntitiesInRange() { return getWorld().getNearbyEntitiesByType(Player.class, getLocation(), getTier() * RADIUS_MULTIPLIER, getWorld().getMaxHeight()); }
Source:
public void handle(MotechEvent event) throws TriggerNotFoundException { LOGGER.debug("Handling the motech event with subject: {}", event.getSubject()); Map<String, Object> eventParams = event.getParameters(); TasksEventParser parser = null; if (eventParams != null) { parser = taskService.findCustomParser((String) eventParams.get(TasksEventParser.CUSTOM_PARSER_EVENT_KEY)); } TriggerEvent trigger = taskService.findTrigger(parser == null ? event.getSubject() : parser.parseEventSubject(event.getSubject(), event.getParameters())); Map<String, Object> parameters = parser == null ? event.getParameters() : parser.parseEventParameters(event.getSubject(), event.getParameters()); List<Task> tasks = taskService.findActiveTasksForTrigger(trigger); for (Task task : tasks) { TaskContext taskContext = new TaskContext(task, parameters, activityService); TaskInitializer initializer = new TaskInitializer(taskContext); try { if (initializer.evalConfigSteps(dataProviders)) { for (TaskActionInformation action : task.getActions()) { executor.execute(task, action, taskContext); } handleSuccess(parameters, task); } } catch (TaskHandlerException e) { handleError(parameters, task, e); } catch (Exception e) { handleError(parameters, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e)); } } }

Target:
public void handle(MotechEvent event) throws TriggerNotFoundException { LOGGER.info("Handling the motech event with subject: {}", event.getSubject()); Map<String, Object> eventParams = event.getParameters(); TasksEventParser parser = null; if (eventParams != null) { parser = taskService.findCustomParser((String) eventParams.get(TasksEventParser.CUSTOM_PARSER_EVENT_KEY)); } TriggerEvent trigger = taskService.findTrigger(parser == null ? event.getSubject() : parser.parseEventSubject(event.getSubject(), event.getParameters())); Map<String, Object> parameters = parser == null ? event.getParameters() : parser.parseEventParameters(event.getSubject(), event.getParameters()); List<Task> tasks = taskService.findActiveTasksForTrigger(trigger); for (Task task : tasks) { TaskContext taskContext = new TaskContext(task, parameters, activityService); TaskInitializer initializer = new TaskInitializer(taskContext); try { LOGGER.info("Executing all actions from task: {}", task.getName()); if (initializer.evalConfigSteps(dataProviders)) { for (TaskActionInformation action : task.getActions()) { executor.execute(task, action, taskContext); } handleSuccess(parameters, task); } LOGGER.warn("Actions from task: weren't executed, because config steps didn't pass the evaluation", task.getName()); } catch (TaskHandlerException e) { handleError(parameters, task, e); } catch (Exception e) { handleError(parameters, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e)); } } }
Source:
public int getItemCount() { return contributions==null?0:contributions.size(); }

Target:
public int getItemCount() { return contributions.size(); }
Source:
public void changeAnnouncement(Intent data) { int type = data.getIntExtra(getString(R.string.announcement_type), AnnouncementActivity.ORIGINAL); if (type == AnnouncementActivity.DELETED) { String string = data.getStringExtra(getString(R.string.delete_announcement)); Announcement announcement = NetworkUtils.writeAsObject(getActivity(), string, new TypeReference<Announcement>() {}); for (int i = 0; i < mAnnouncements.size(); i++) { if (mAnnouncements.get(i).getId() == announcement.getId()) { mAnnouncements.remove(i); } } mAdapter.setAnnouncements(mAnnouncements); mAdapter.notifyDataSetChanged(); } else if (type == AnnouncementActivity.EDITED) { String string = data.getStringExtra(getString(R.string.edit_announcement)); Announcement announcement = NetworkUtils.writeAsObject(getActivity(), string, new TypeReference<Announcement>() {}); for (int i = 0; i < mAnnouncements.size(); i++) { if (mAnnouncements.get(i).getId() == announcement.getId()) { mAnnouncements.set(i, announcement); } } mAdapter.setAnnouncements(mAnnouncements); mAdapter.notifyDataSetChanged(); } }

Target:
public void changeAnnouncement(Intent data) { int type = data.getIntExtra(getString(R.string.announcement_type), AnnouncementActivity.ORIGINAL); String string = data.getStringExtra(getString(R.string.change_announcement)); Announcement announcement = NetworkUtils.writeAsObject(getActivity(), string, new TypeReference<Announcement>() {}); if (type == AnnouncementActivity.ORIGINAL) { return; } int index = 0; for (int i = 0; i < mAnnouncements.size(); i++) { if (mAnnouncements.get(i).getId() == announcement.getId()) { index = i; } } switch (type) { case AnnouncementActivity.DELETED: mAnnouncements.remove(index); break; case AnnouncementActivity.EDITED: mAnnouncements.set(index, announcement); break; } mAdapter.setAnnouncements(mAnnouncements); mAdapter.notifyDataSetChanged(); }
Source:
public void testValidateSnapshotVersionWithInvalidVersions() { assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3", "OSGi version 1.2.3 must have .qualifier qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3", "1.2.3.qualifier", "Maven version 1.2.3 must have -SNAPSHOT qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.0.qualifier", "Unqualified OSGi version 1.2.0.qualifier must match unqualified Maven version 1.2.3-SNAPSHOT for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3.qualifier", "1.2.3.qualifier", "Maven version 1.2.3.qualifier must have -SNAPSHOT qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3.SHAPSHOT", "OSGi version 1.2.3.SHAPSHOT must have .qualifier qualifier for SNAPSHOT builds"); }

Target:
public void testValidateSnapshotVersionWithInvalidVersions() { assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3", "OSGi version 1.2.3 must have .qualifier qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3", "1.2.3.qualifier", "Maven version 1.2.3 must have -SNAPSHOT qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.0.qualifier", "Unqualified OSGi version 1.2.0.qualifier must match unqualified Maven version 1.2.3-SNAPSHOT for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3.qualifier", "1.2.3.qualifier", "Maven version 1.2.3.qualifier must have -SNAPSHOT qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3.SNAPSHOT", "OSGi version 1.2.3.SNAPSHOT must have .qualifier qualifier for SNAPSHOT builds"); }
Source:
public AlphaNumericTopNMetricSpec( @JsonProperty("previousStop") String previousStop ) { super((previousStop == null) ? "" : previousStop); this.previousStop = (previousStop == null) ? "" : previousStop; }

Target:
public AlphaNumericTopNMetricSpec( @JsonProperty("previousStop") String previousStop ) { super(previousStop); }
Source:
public API getApiByContextAndVersion(String context, String version) { return null; }

Target:
public API getApiByContextAndVersion(String context, String version) { String key = context + DELEM_PERIOD + version; return apiMap.get(key); }
Source:
public void simplePhenotypeSearchNoFind() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setPhenotype("FooBar"); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response).isNotNull(); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations().size()).isEqualTo(0) ; }

Target:
public void simplePhenotypeSearchNoFind() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setPhenotype(Utils.randomName()); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations()).isEmpty(); }
Source:
public static <E> Collection<E> removeCount(final Collection<E> input, int startIndex, int count) { if (null == input) { throw new IllegalArgumentException("The collection can't be null."); } if (startIndex < 0) { throw new IndexOutOfBoundsException("The start index can't less than 0."); } if (count < 0) { throw new IndexOutOfBoundsException("The count can't less than 0."); } if (input.size() < startIndex + count) { throw new IndexOutOfBoundsException( "The sum of start index and count can't be greater than the size of collection."); } Collection<E> result = new ArrayList<E>(count); Iterator<E> iterator = input.iterator(); while (count > 0) { if (startIndex > 0) { startIndex = startIndex - 1; iterator.next(); continue; } count = count - 1; result.add(iterator.next()); iterator.remove(); } return result; }

Target:
public static <E> Collection<E> removeCount(final Collection<E> input, int startIndex, int count) { if (null == input) { throw new IllegalArgumentException("The collection can't be null."); } if (startIndex < 0) { throw new IndexOutOfBoundsException("The start index can't be less than 0."); } if (count < 0) { throw new IndexOutOfBoundsException("The count can't be less than 0."); } if (input.size() < startIndex + count) { throw new IndexOutOfBoundsException( "The sum of start index and count can't be greater than the size of collection."); } Collection<E> result = new ArrayList<E>(count); Iterator<E> iterator = input.iterator(); while (count > 0) { if (startIndex > 0) { startIndex = startIndex - 1; iterator.next(); continue; } count = count - 1; result.add(iterator.next()); iterator.remove(); } return result; }