auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static ClassLoader load(final List<URL> urls) throws IOException { final ClassLoader parentClassLoader = ExtensionClassLoader.class.getClassLoader(); ClassLoader extensionClassLoader = java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<ExtensionClassLoader>() { @Override public ExtensionClassLoader run() { return new ExtensionClassLoader(urls.toArray(new URL[urls.size()]), parentClassLoader); } } ); <START> LOG.info("Created a new ExtensionClassLoader with parent = using classpath = {}", <END> parentClassLoader.toString(), Arrays.toString(urls.toArray())); return extensionClassLoader; }</code><technical_language>Nit: printing additional paths suffice, information get drowned</technical_language>

Target:
public static ClassLoader load(final List<URL> urls) throws IOException { final ClassLoader parentClassLoader = ExtensionClassLoader.class.getClassLoader(); ClassLoader extensionClassLoader = java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<ExtensionClassLoader>() { @Override public ExtensionClassLoader run() { return new ExtensionClassLoader(urls.toArray(new URL[urls.size()]), parentClassLoader); } } ); LOG.info("Created a new ExtensionClassLoader using classpath = {}", Arrays.toString(urls.toArray())); return extensionClassLoader; }
Source:
<code>public String summary() { return null; <START> } <END></code><technical_language>@NaitYoussef , @qasmi add this function post get summay , i useful</technical_language>

Target:
public String summary() { return this.postContent.getSummary(); }
Source:
<code>public void send(DatastreamTask task, DatastreamEventRecord record) { if (_shutdownRequested) { throw new IllegalStateException("send() is not allowed on a shutdown producer"); } validateAndNormalizeEventRecord(record); try { _sendFlushLock.readLock().lock(); <START> _partitionLocks.get(record.getPartition()).lock(); <END> _transportProvider.send(task.getDatastreamDestination().getConnectionString(), record); _latestCheckpoints.get(task).put(record.getPartition(), record.getCheckpoint()); _pendingCheckpoint = true; } catch (TransportException e) { LOG.info(String.format("Failed send the event %s exception %s", record, e)); throw new RuntimeException("Failed to send: " + record, e); } finally { _partitionLocks.get(record.getPartition()).unlock(); _sendFlushLock.readLock().unlock(); } }</code><technical_language>Do need a partition lock, Do assume underlying transport provider is thread safe</technical_language>

Target:
public void send(DatastreamTask task, DatastreamEventRecord record) { if (_shutdownRequested) { throw new IllegalStateException("send() is not allowed on a shutdown producer"); } validateAndNormalizeEventRecord(record); try { _sendFlushLock.readLock().lock(); _transportProvider.send(task.getDatastreamDestination().getConnectionString(), record); _latestCheckpoints.get(task).put(record.getPartition(), record.getCheckpoint()); _pendingCheckpoint = true; } catch (TransportException e) { LOG.info(String.format("Failed send the event %s exception %s", record, e)); throw new RuntimeException("Failed to send: " + record, e); } finally { _sendFlushLock.readLock().unlock(); } }
Source:
<code>public void testNormalIndexAndFullTextSearchIndex() { SessionFactoryBuilder config = SessionFactoryBuilder.entities( NormalIndexAndFullTextSearchIndexEntity.class ); try ( SessionFactory ignored = config.build() ) { <START> fail( "Expected exception at Hibernate factory creation time was not raised!" ); <END> } catch (Exception e) { assertThat( e ) .isExactlyInstanceOf( HibernateException.class ) .hasMessage( "OGM001231: Unable to create index normal on collection MyDoc" ); assertThat( e.getCause() ).isExactlyInstanceOf( MongoCommandException.class ); assertThat( e.getCause().getMessage() ).contains( "already exists with different options" ); } }</code><technical_language>change message to: fail defined indexes conflicting configurations field UniqueConstraintAndNotUniqueIndexEntity#email reason expect a failure</technical_language>

Target:
public void testNormalIndexAndFullTextSearchIndex() { SessionFactoryBuilder config = SessionFactoryBuilder.entities( NormalIndexAndFullTextSearchIndexEntity.class ); this.entity = null; try ( SessionFactory ignored = config.build() ) { fail( "Should fail because we defined two indexes with conflicting configurations on field `NormalIndexAndFullTextSearchIndexEntity#email`" ); } catch (Exception e) { assertThat( e ) .isExactlyInstanceOf( HibernateException.class ) .hasMessage( "OGM001231: Unable to create index normal on collection MyDoc" ); assertThat( e.getCause() ).isExactlyInstanceOf( MongoCommandException.class ); assertThat( e.getCause().getMessage() ).contains( "already exists with different options" ); } }
Source:
<code>void onException(SQLException e, OperationType operationType) { if (e instanceof SQLTransientConnectionException) { reset(); } <START> if (!(e instanceof SQLIntegrityConstraintViolationException || isCredentialError(e))) { <END> if (operationType == OperationType.Write) { metrics.writeFailureCount.inc(); } else { metrics.readFailureCount.inc(); } } }</code><technical_language>suffice check if e instanceof SQLTransientConnectionException above. cases handle</technical_language>

Target:
void onException(SQLException e, OperationType operationType) { if (e instanceof SQLTransientConnectionException) { if (operationType == OperationType.Write) { metrics.writeFailureCount.inc(); } else { metrics.readFailureCount.inc(); } reset(); } }
Source:
<code>public Object get(Object obj) { <START> return super.get(StringUtils.toLowerCase((String) obj)); <END> }</code><technical_language>This breaks contract of HashMap allows key null. StringUtils.toLowerCase(null) throw NPE</technical_language>

Target:
public Object get(Object obj) { return super.get(obj == null ? null : StringUtils.toLowerCase((String) obj)); }
Source:
<code>public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = new ArrayList<PermissionSubject>(); permissionList.add(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups, getActionType().getActionGroup())); permissionList.add(new PermissionSubject(getVmTemplateId(), VdcObjectType.VmTemplate, getActionType().getActionGroup())); if (getVmTemplate() != null && !getVmTemplate().getDiskList().isEmpty()) { for (DiskImage disk : getParameters().getDiskInfoDestinationMap().values()) { if (disk.getStorageIds() != null && !disk.getStorageIds().isEmpty()) { permissionList.add(new PermissionSubject(GuidUtils.getGuidValue(getStorageDomainId()), <START> VdcObjectType.Storage, ActionGroup.CREATE_DISK)); <END> } } } addPermissionSubjectForAdminLevelProperties(permissionList); return permissionList; }</code><technical_language>multiple storage domains</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = new ArrayList<PermissionSubject>(); permissionList.add(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups, getActionType().getActionGroup())); permissionList.add(new PermissionSubject(getVmTemplateId(), VdcObjectType.VmTemplate, getActionType().getActionGroup())); if (getVmTemplate() != null && !getVmTemplate().getDiskList().isEmpty()) { for (DiskImage disk : getParameters().getDiskInfoDestinationMap().values()) { if (disk.getStorageIds() != null && !disk.getStorageIds().isEmpty()) { permissionList.add(new PermissionSubject(GuidUtils.getGuidValue(disk.getStorageIds().get(0)), VdcObjectType.Storage, ActionGroup.CREATE_DISK)); } } } addPermissionSubjectForAdminLevelProperties(permissionList); return permissionList; }
Source:
<code>private void processSetting(Map<String, Object> map, String prefix, String setting, Object value, Set<String> maskedSettings) { int prefixLength = setting.indexOf('.'); if (prefixLength == -1) { @SuppressWarnings("unchecked") Map<String, Object> innerMap = (Map<String, Object>) map.get(prefix + setting); if (innerMap != null) { for (Map.Entry<String, Object> entry : innerMap.entrySet()) { map.put(prefix + setting + "." + entry.getKey(), entry.getValue()); } } String settingKey = prefix + setting; <START> Object settingValue = (maskedSettings.contains(settingKey)) ? MASKED_VALUE : value; <END> map.put(settingKey, settingValue); } else { String key = setting.substring(0, prefixLength); String rest = setting.substring(prefixLength + 1); Object existingValue = map.get(prefix + key); if (existingValue == null) { Map<String, Object> newMap = new HashMap<>(2); processSetting(newMap, "", rest, value, maskedSettings); map.put(key, newMap); } else { if (existingValue instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> innerMap = (Map<String, Object>) existingValue; processSetting(innerMap, "", rest, value, maskedSettings); map.put(key, innerMap); } else { processSetting(map, prefix + key + ".", rest, value, maskedSettings); } } } }</code><technical_language>suggestion Object settingValue = maskedSettings.contains(settingKey) ? MASKED_VALUE : value;</technical_language>

Target:
private void processSetting(Map<String, Object> map, String prefix, String setting, Object value, Set<String> maskedSettings) { int prefixLength = setting.indexOf('.'); if (prefixLength == -1) { @SuppressWarnings("unchecked") Map<String, Object> innerMap = (Map<String, Object>) map.get(prefix + setting); if (innerMap != null) { for (Map.Entry<String, Object> entry : innerMap.entrySet()) { map.put(prefix + setting + "." + entry.getKey(), entry.getValue()); } } String settingKey = prefix + setting; Object settingValue = maskedSettings.contains(settingKey) ? MASKED_VALUE : value; map.put(settingKey, settingValue); } else { String key = setting.substring(0, prefixLength); String rest = setting.substring(prefixLength + 1); Object existingValue = map.get(prefix + key); if (existingValue == null) { Map<String, Object> newMap = new HashMap<>(2); processSetting(newMap, "", rest, value, maskedSettings); map.put(key, newMap); } else { if (existingValue instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> innerMap = (Map<String, Object>) existingValue; processSetting(innerMap, "", rest, value, maskedSettings); map.put(key, innerMap); } else { processSetting(map, prefix + key + ".", rest, value, maskedSettings); } } } }
Source:
<code>public void UpdateUserActionGroups(Object targetObject, ArrayList<Guid> roleIdList) { ArrayList<VdcQueryParametersBase> queryParamsList = new ArrayList<VdcQueryParametersBase>(); ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>(); for (Guid roleId : roleIdList) { queryTypeList.add(VdcQueryType.GetRoleActionGroupsByRoleId); queryParamsList.add(new MultilevelAdministrationByRoleIdParameters(roleId)); <START> Frontend.RunMultipleQueries(queryTypeList, queryParamsList, new IFrontendMultipleQueryAsyncCallback() { <END> @Override public void Executed(FrontendMultipleQueryAsyncResult result) { for (int i = 0; i < result.getReturnValues().size(); i++) { VdcQueryReturnValue retVal = result.getReturnValues().get(i); ArrayList<ActionGroup> roleActionGroupList = (ArrayList<ActionGroup>) retVal.getReturnValue(); for (ActionGroup actionGroup : roleActionGroupList) { if (!UserPortalLoginModel.this.getLoggedUserActionGroupList().contains(actionGroup)) { UserPortalLoginModel.this.getLoggedUserActionGroupList().add(actionGroup); } } UserPortalLoginModel.this.setRolesCounter(UserPortalLoginModel.this.getRolesCounter() - 1); if (UserPortalLoginModel.this.getRolesCounter() == 0) { CheckIsENGINEUser(UserPortalLoginModel.this); } } } }); } }</code><technical_language>multipleQuery in for loop</technical_language>

Target:
public void UpdateUserActionGroups(Object targetObject, ArrayList<Guid> roleIdList) { ArrayList<VdcQueryParametersBase> queryParamsList = new ArrayList<VdcQueryParametersBase>(); ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>(); for (Guid roleId : roleIdList) { queryTypeList.add(VdcQueryType.GetRoleActionGroupsByRoleId); queryParamsList.add(new MultilevelAdministrationByRoleIdParameters(roleId)); } Frontend.RunMultipleQueries(queryTypeList, queryParamsList, new IFrontendMultipleQueryAsyncCallback() { @Override public void Executed(FrontendMultipleQueryAsyncResult result) { for (int i = 0; i < result.getReturnValues().size(); i++) { VdcQueryReturnValue retVal = result.getReturnValues().get(i); ArrayList<ActionGroup> roleActionGroupList = (ArrayList<ActionGroup>) retVal.getReturnValue(); for (ActionGroup actionGroup : roleActionGroupList) { if (!UserPortalLoginModel.this.getLoggedUserActionGroupList().contains(actionGroup)) { UserPortalLoginModel.this.getLoggedUserActionGroupList().add(actionGroup); } } UserPortalLoginModel.this.setRolesCounter(UserPortalLoginModel.this.getRolesCounter() - 1); if (UserPortalLoginModel.this.getRolesCounter() == 0) { CheckIsENGINEUser(UserPortalLoginModel.this); } } } }); }
Source:
<code>public IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull, Node endNodeOrNull ) { KernelTransaction ktx = txBridge.get(); try ( Statement ignore = ktx.acquireStatement() ) { RelationshipExplicitIndexCursor cursor = ktx.cursors().allocateRelationshipExplicitIndexCursor(); <START> long source = startNodeOrNull == null ? -1L : startNodeOrNull.getId(); <END> long target = endNodeOrNull == null ? -1L : endNodeOrNull.getId(); ktx.indexRead().relationshipExplicitIndexLookup( cursor, name, key, valueOrNull, source, target ); return new CursorWrappingRelationshipIndexHits( cursor, getGraphDatabase(), ktx, name ); } catch ( ExplicitIndexNotFoundKernelException e ) { throw new NotFoundException( type + " index '" + name + "' doesn't exist" ); } }</code><technical_language>Magic -1's</technical_language>

Target:
public IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull, Node endNodeOrNull ) { KernelTransaction ktx = txBridge.get(); try ( Statement ignore = ktx.acquireStatement() ) { RelationshipExplicitIndexCursor cursor = ktx.cursors().allocateRelationshipExplicitIndexCursor(); long source = startNodeOrNull == null ? NO_SUCH_NODE : startNodeOrNull.getId(); long target = endNodeOrNull == null ? NO_SUCH_NODE : endNodeOrNull.getId(); ktx.indexRead().relationshipExplicitIndexLookup( cursor, name, key, valueOrNull, source, target ); return new CursorWrappingRelationshipIndexHits( cursor, getGraphDatabase(), ktx, name ); } catch ( ExplicitIndexNotFoundKernelException e ) { throw new NotFoundException( type + " index '" + name + "' doesn't exist" ); } }
Source:
<code>void processFile(AbstractFile f, DrawableDB.DrawableTransaction tr) throws TskCoreException { final boolean known = f.getKnown() == TskData.FileKnown.KNOWN; if (known) { taskDB.removeFile(f.getId(), tr); } else { try { if (FileTypeUtils.hasDrawableMIMEType(f)) { taskDB.updateFile(DrawableFile.create(f, true, false), tr); } else { if (null == f.getMIMEType()) { this.setTaskCompletionStatus(false); <START> } <END> taskDB.removeFile(f.getId(), tr); } } catch (FileTypeDetector.FileTypeDetectorInitException ex) { throw new TskCoreException("Failed to initialize FileTypeDetector.", ex); } } }</code><technical_language>AbstractFile.getMIMEType return null a call FileTypeUtils.hasDrawableMIMEType, call setTaskCompletionStatus executed do need taskCompletionStatus stuff. @bcarrier, apparently this idea, is behavior create</technical_language>

Target:
void processFile(AbstractFile f, DrawableDB.DrawableTransaction tr) throws TskCoreException { final boolean known = f.getKnown() == TskData.FileKnown.KNOWN; if (known) { taskDB.removeFile(f.getId(), tr); } else { try { if ( null != f.getMIMEType() && FileTypeUtils.hasDrawableMIMEType(f)) { taskDB.updateFile(DrawableFile.create(f, true, false), tr); } else { if (null == f.getMIMEType()) { this.setTaskCompletionStatus(false); } taskDB.removeFile(f.getId(), tr); } } catch (FileTypeDetector.FileTypeDetectorInitException ex) { throw new TskCoreException("Failed to initialize FileTypeDetector.", ex); } } }
Source:
<code>public boolean error(final Message message, final Throwable throwable) { if (isInvalidBusContentException(throwable)) { <START> final YesNoCancelPopup result = YesNoCancelPopup.newYesNoCancelPopup("Session timeout", <END> DefaultWorkbenchConstants.INSTANCE.InvalidBusResponseProbablySessionTimeout(), Window.Location::reload, () -> {}, () -> {}); result.clearScrollHeight(); result.show(); return false; } else if (isKieServerForbiddenException(throwable)) { ErrorPopup.showMessage(DefaultWorkbenchConstants.INSTANCE.KieServerError403()); return false; } else if (isKieServerUnauthorizedException(throwable)) { ErrorPopup.showMessage(DefaultWorkbenchConstants.INSTANCE.KieServerError401()); return false; } else if (throwable instanceof KieServicesHttpException) { KieServicesHttpException ex = (KieServicesHttpException) throwable; ErrorPopup.showMessage(CommonConstants.INSTANCE.ExceptionGeneric0(ex.getExceptionMessage())); return false; } else { return super.error(message, throwable); } }</code><technical_language>i18n please</technical_language>

Target:
public boolean error(final Message message, final Throwable throwable) { if (isInvalidBusContentException(throwable)) { final YesNoCancelPopup result = YesNoCancelPopup.newYesNoCancelPopup(DefaultWorkbenchConstants.INSTANCE.SessionTimeout(), DefaultWorkbenchConstants.INSTANCE.InvalidBusResponseProbablySessionTimeout(), Window.Location::reload, null, () -> {}); result.clearScrollHeight(); result.show(); return false; } else if (isKieServerForbiddenException(throwable)) { ErrorPopup.showMessage(DefaultWorkbenchConstants.INSTANCE.KieServerError403()); return false; } else if (isKieServerUnauthorizedException(throwable)) { ErrorPopup.showMessage(DefaultWorkbenchConstants.INSTANCE.KieServerError401()); return false; } else if (throwable instanceof KieServicesHttpException) { KieServicesHttpException ex = (KieServicesHttpException) throwable; ErrorPopup.showMessage(CommonConstants.INSTANCE.ExceptionGeneric0(ex.getExceptionMessage())); return false; } else { return super.error(message, throwable); } }
Source:
<code>private void cleanUpStreams() { <START> System.setOut(null); <END> }</code><technical_language>I this is a clear reset values default - I think, like: System.setOut(System.out);</technical_language>

Target:
private void cleanUpStreams() { System.setOut(System.out); }
Source:
<code>private void activate() { for (ExtensionEntry entry : loadedEntries.values()) { if (entry.enabled) { try { Extension extension = <START> lookupExtension(entry, loadModule(entry.getConfig().getProperty(MODULE))).newInstance(); <END> extension.setContext(entry.context); extension.init(); entry.setExtension(extension); activatedEntries.put(entry.getName(), entry); MultiValueMapUtils.addToMap(entry.getProvides(), entry, providesEntries); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException ex ) { log.error(String.format("Error in activating extension %1$s. Exception message is " + entry.getName()), ex.getMessage()); if (log.isDebugEnabled()) { log.error("", ex); } } } } }</code><technical_language>is change, pushed</technical_language>

Target:
private void activate() { for (ExtensionEntry entry : loadedEntries.values()) { if (entry.enabled) { try { Extension extension = (Extension) lookupService( Extension.class, entry.getConfig().getProperty(CLASS), loadModule(entry.getConfig().getProperty(MODULE)) ).newInstance(); extension.setContext(entry.context); extension.init(); entry.setExtension(extension); activatedEntries.put(entry.getName(), entry); MultiValueMapUtils.addToMap(entry.getProvides(), entry, providesEntries); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException ex ) { log.error(String.format("Error in activating extension %1$s. Exception message is " + entry.getName()), ex.getMessage()); if (log.isDebugEnabled()) { log.error("", ex); } } } } }
Source:
<code><START> public void testSetAsync() { <END> String slaDueDate = "12/25/1983"; tested.setSlaDueDate(new SLADueDate(slaDueDate)); assertTrue(CustomElement.slaDueDate.of(tested.getFlowElement()).get().contains(slaDueDate)); }</code><technical_language>test method is testing isAsync property. is pasted accident, test is right below</technical_language>

Target:
public void testSetAsync() { tested.setAsync(true); assertTrue(CustomElement.async.of(tested.getFlowElement()).get()); }
Source:
<code>protected void ExecuteVmCommand() { <START> lockVmWithCompensationIfNeeded(); <END> if (!isInternalExecution()) { freeLock(); } restoreSnapshotAndRemoveObsoleteSnapshots(); boolean succeeded = true; boolean hasAsyncTasks = false; if (!getImagesList().isEmpty()) { for (DiskImage image : getImagesList()) { if (image.getimageStatus() != ImageStatus.ILLEGAL) { ImagesContainterParametersBase params = new RestoreFromSnapshotParameters(image.getImageId(), getVmId(), targetSnapshot, removedSnapshotId); VdcReturnValueBase returnValue = runAsyncTask(VdcActionType.RestoreFromSnapshot, params); if (succeeded && !returnValue.getSucceeded()) { succeeded = false; getReturnValue().setFault(returnValue.getFault()); } } } hasAsyncTasks = !getTaskIdList().isEmpty(); } removeSnapshotsFromDB(); if (hasAsyncTasks) { deleteOrphanedImages(); } else { endActionOnVmConfiguration(); } setSucceeded(succeeded); }</code><technical_language>Fron patch set 3: Allon: want removing (a VDSM command), while in middle of snapshoting, IMHO. Answer: If VM disks lock in memory enough. User able remove VM. freelock() removing snapshots DB, simply remove call endActionOnVmConfiguration() call UpdateVmInSpm(getVm().getstorage_pool_id(), Arrays.asList(getVm()));</technical_language>

Target:
protected void ExecuteVmCommand() { if (!getImagesList().isEmpty()) { lockVmWithCompensationIfNeeded(); } if (!isInternalExecution()) { freeLock(); } restoreSnapshotAndRemoveObsoleteSnapshots(); boolean succeeded = true; boolean hasAsyncTasks = false; if (!getImagesList().isEmpty()) { for (DiskImage image : getImagesList()) { if (image.getimageStatus() != ImageStatus.ILLEGAL) { ImagesContainterParametersBase params = new RestoreFromSnapshotParameters(image.getImageId(), getVmId(), targetSnapshot, removedSnapshotId); VdcReturnValueBase returnValue = runAsyncTask(VdcActionType.RestoreFromSnapshot, params); if (succeeded && !returnValue.getSucceeded()) { succeeded = false; getReturnValue().setFault(returnValue.getFault()); } } } hasAsyncTasks = !getTaskIdList().isEmpty(); } removeSnapshotsFromDB(); if (hasAsyncTasks) { deleteOrphanedImages(); } else { endActionOnVmConfiguration(); } setSucceeded(succeeded); }
Source:
<code>private void populateFileCountBySizeDB() { for (int i = 0; i < upperBoundCount.length; i++) { <START> long fileSizeUpperBound = (long) Math.pow(2, (10 + i)); <END> FileCountBySize fileCountRecord = fileCountBySizeDao.findById(fileSizeUpperBound); FileCountBySize newRecord = new FileCountBySize(fileSizeUpperBound, upperBoundCount[i]); if(fileCountRecord == null){ fileCountBySizeDao.insert(newRecord); } else{ fileCountBySizeDao.update(newRecord); } } }</code><technical_language>changed log2, computation accurate is plan show files < 1 MB query? more computation done in UI. user point of view, 1KB, 2KB, 4KB is noise in UI. 10s of bytes more readable</technical_language>

Target:
void populateFileCountBySizeDB() { for (int i = 0; i < upperBoundCount.length; i++) { long fileSizeUpperBound = (i == upperBoundCount.length - 1) ? Long.MAX_VALUE : (long) Math.pow(2, (10 + i)); FileCountBySize fileCountRecord = fileCountBySizeDao.findById(fileSizeUpperBound); FileCountBySize newRecord = new FileCountBySize(fileSizeUpperBound, upperBoundCount[i]); if (fileCountRecord == null) { fileCountBySizeDao.insert(newRecord); } else { fileCountBySizeDao.update(newRecord); } } }
Source:
<code>private static @Nullable String getCommonTraceType(TmfExperiment experiment) { String commonTraceType = null; try { for (final ITmfTrace trace : experiment.getTraces()) { <START> final IResource resource = trace.getResource(); if (resource == null) { return null; } final String traceType = resource.getPersistentProperty(TmfCommonConstants.TRACETYPE); if ((commonTraceType != null) && !commonTraceType.equals(traceType)) { return null; } <END> commonTraceType = traceType; } } catch (CoreException e) { return null; } return commonTraceType; }</code><technical_language>is this tracetype id else? if consider trace.getTraceTypeId()</technical_language>

Target:
private static @Nullable String getCommonTraceType(TmfExperiment experiment) { String commonTraceType = null; for (final ITmfTrace trace : experiment.getTraces()) { String traceType = trace.getTraceTypeId(); if ((commonTraceType != null) && !commonTraceType.equals(traceType)) { return null; } commonTraceType = traceType; } return commonTraceType; }
Source:
<code>private T processInternal(ParametersWrapper parameters) throws Exception { HandlerMethod candidate = this.findHandlerMethodForParameters(parameters); Assert.notNull(candidate, "No candidate methods found for messages."); Expression expression = candidate.getExpression(); Class<?> expectedType = this.expectedType != null ? this.expectedType : candidate.method.getReturnType(); try { @SuppressWarnings("unchecked") T result = (T) this.evaluateExpression(expression, parameters, expectedType); if (this.requiresReply) { Assert.notNull(result, "Expression evaluation result was null, but this processor requires a reply."); } return result; } catch (Exception e) { Throwable evaluationException = e; if ((e instanceof EvaluationException || e instanceof MessageHandlingException) && e.getCause() != null) { evaluationException = e.getCause(); } if (evaluationException instanceof Exception) { throw (Exception) evaluationException; } else if (evaluationException instanceof Error) { <START> throw (Error) evaluationException; <END> } else { throw new IllegalStateException("Cannot process message", evaluationException); } } }</code><technical_language>Original code, I know, I remove this clause - evaluationException Error</technical_language>

Target:
private T processInternal(ParametersWrapper parameters) throws Exception { HandlerMethod candidate = this.findHandlerMethodForParameters(parameters); Assert.notNull(candidate, "No candidate methods found for messages."); Expression expression = candidate.getExpression(); Class<?> expectedType = this.expectedType != null ? this.expectedType : candidate.method.getReturnType(); try { @SuppressWarnings("unchecked") T result = (T) this.evaluateExpression(expression, parameters, expectedType); if (this.requiresReply) { Assert.notNull(result, "Expression evaluation result was null, but this processor requires a reply."); } return result; } catch (Exception e) { Throwable evaluationException = e; if ((e instanceof EvaluationException || e instanceof MessageHandlingException) && e.getCause() != null) { evaluationException = e.getCause(); } if (evaluationException instanceof Exception) { throw (Exception) evaluationException; } else { throw new IllegalStateException("Cannot process message", evaluationException); } } }
Source:
<code>private String metadataPath(String containerId, String moduleId) { <START> return Paths.build(Paths.MODULE_DEPLOYMENTS, Paths.ALLOCATED, containerId, moduleId, "metadata"); <END> }</code><technical_language>I this part of this PR, I "metadata" string declared a constant Paths</technical_language>

Target:
private String metadataPath(String containerId, String moduleId) { return Paths.build(Paths.MODULE_DEPLOYMENTS, Paths.ALLOCATED, containerId, moduleId, Paths.METADATA); }
Source:
<code>public boolean canEquip(EquipmentType type) { <START> if (this.self.isOnline()) { <END> return this.self.getPlayer().get().canEquip(type); } else { throw new UnsupportedOperationException(); } }</code><technical_language>This work, cleaner: this.self.getPlayer().orElseThrow(() -> new UnsupportedOperationException("User is offline, offline inventory API implemented")).canEquip(type)</technical_language>

Target:
public boolean canEquip(EquipmentType type) { return getUserIfOnlineForInventory().canEquip(type); }
Source:
<code>public List<String> extractWithJsonPath(String jsonString, String jsonPath) throws ParseException { JsonPath jsonPathParser = getJsonPath(jsonPath); <START> Object values = jsonPathParser.<List<?>> read(jsonString); <END> List<String> jsonExtraction = new ArrayList<String>(); if (values instanceof String) { jsonExtraction.add((String) values); } else if (values instanceof List<?>) { List<?> asList = (List<?>) values; for (Object object : asList) { if(object instanceof String) { jsonExtraction.add((String)object); } else { jsonExtraction.add(object.toString()); } } } return jsonExtraction; }</code><technical_language>do <List<?>> assign result Object</technical_language>

Target:
public List<String> extractWithJsonPath(String jsonString, String jsonPath) throws ParseException { JsonPath jsonPathParser = getJsonPath(jsonPath); return jsonPathParser.read(jsonString); }
Source:
<code><START> public void setProperties(List<String> properties) { <END> this.properties = properties; }</code><technical_language>@VisibleForTesting annotation. public removed</technical_language>

Target:
void setProperties(List<String> properties) { this.properties = properties; }
Source:
<code>private static void closeSecureStorage() { <START> for (int i = 0; i < 5; i++) { <END> if (new ShellWithTextIsAvailable("Secure Storage").test()) { new DefaultShell("Secure Storage"); new LabeledText("Password:").setText("admin"); new PushButton("OK").click(); break; } AbstractWait.sleep(TimePeriod.SHORT); } AbstractWait.sleep(TimePeriod.SHORT); new DefaultShell("New Server"); }</code><technical_language>this is a nice example for a wait condition ;-)</technical_language>

Target:
private static void closeSecureStorage() { try { new WaitUntil(new ShellWithTextIsAvailable("Secure Storage"), TimePeriod.getCustom(5)); } catch (RuntimeException ex) { return; } new DefaultShell("Secure Storage"); new LabeledText("Password:").setText("admin"); new PushButton("OK").click(); AbstractWait.sleep(TimePeriod.SHORT); new DefaultShell("New Server"); }
Source:
<code>private String readLineSimple() throws IOException { StringBuilder buff = new StringBuilder(); if (skipLF) { skipLF = false; int i = readCharacter(); if (i == -1 || i == '\r') { return buff.toString(); } else if (i == '\n') { } else { buff.append((char) i); } } while (true) { int i = readCharacter(); if (i == -1 && buff.length() == 0) { return null; } if (i == -1 || i == '\n') { break; } else if (i == '\r') { skipLF = true; break; } else { buff.append((char) i); } } String str = buff.toString(); if (str.length() > 0) { if (mask == null && isHistoryEnabled()) { history.add(str); } else { mask = null; } } history.moveToEnd(); return str; <START> <END> }</code><technical_language>reason calling return finishBuffer() instead</technical_language>

Target:
private String readLineSimple() throws IOException { if (skipLF) { skipLF = false; int i = readCharacter(); if (i == -1 || i == '\r') { return finishBuffer(); } else if (i == '\n') { } else { buf.buffer.append((char) i); } } while (true) { int i = readCharacter(); if (i == -1 && buf.buffer.length() == 0) { return null; } else if (i == -1 || i == '\n') { return finishBuffer(); } else if (i == '\r') { skipLF = true; return finishBuffer(); } else { buf.buffer.append((char) i); } } }
Source:
<code>public ExitShellRequest quitShell() { <START> return ExitShellRequest.NORMAL_EXIT; <END> }</code><technical_language>remove this. for graceful close</technical_language>

Target:
public ExitShellRequest quitShell() { closeClientConnection(); return ExitShellRequest.NORMAL_EXIT; }
Source:
<code>private StudentProfileAttributes loadStudentProfile(StudentAttributes student, InstructorAttributes currentInstructor) { StudentProfileAttributes studentProfile = null; boolean hasExistingStatus = !statusToUser.isEmpty() || session.getAttribute(Const.ParamsNames.STATUS_MESSAGES_LIST) != null; boolean isInstructorAllowedToViewStudent = currentInstructor.isAllowedForPrivilege(student.section, Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTIONS); boolean isStudentWithProfile = !student.googleId.isEmpty(); if (isInstructorAllowedToViewStudent && isStudentWithProfile) { studentProfile = logic.getStudentProfile(student.googleId); Assumption.assertNotNull(studentProfile); return studentProfile; <START> } else { <END> if (!isStudentWithProfile) { if (!hasExistingStatus) { statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_NOT_JOINED_YET_FOR_RECORDS, StatusMessageColor.WARNING)); } } if (!isInstructorAllowedToViewStudent) { if (!hasExistingStatus) { statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_PROFILE_UNACCESSIBLE_TO_INSTRUCTOR, StatusMessageColor.WARNING)); } } return null; } }</code><technical_language>remove else</technical_language>

Target:
private StudentProfileAttributes loadStudentProfile(StudentAttributes student, InstructorAttributes currentInstructor) { StudentProfileAttributes studentProfile = null; boolean isInstructorAllowedToViewStudent = currentInstructor.isAllowedForPrivilege(student.section, Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTIONS); boolean isStudentWithProfile = !student.googleId.isEmpty(); if (isInstructorAllowedToViewStudent && isStudentWithProfile) { studentProfile = logic.getStudentProfile(student.googleId); Assumption.assertNotNull(studentProfile); return studentProfile; } boolean hasExistingStatus = !statusToUser.isEmpty() || session.getAttribute(Const.ParamsNames.STATUS_MESSAGES_LIST) != null; if (!isStudentWithProfile && !hasExistingStatus) { statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_NOT_JOINED_YET_FOR_RECORDS, StatusMessageColor.WARNING)); } if (!isInstructorAllowedToViewStudent && !hasExistingStatus) { statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_PROFILE_UNACCESSIBLE_TO_INSTRUCTOR, StatusMessageColor.WARNING)); } return null; }
Source:
<code>private static Function<Method, Optional<String>> hasParam(Class<? extends Annotation> annotation, Class<?> type) { return method -> { int count = 0; for (Parameter parameter : method.getParameters()) { if (parameter.isAnnotationPresent(annotation) && type.equals(parameter.getType())) { count++; } } String errorMessageCommon = " method parameter with @" + annotation.getSimpleName() + " annotation and type " + type.getSimpleName(); <START> if (count == 0) { return Optional.of(invalid(method, "Misssing" + errorMessageCommon)); } else if (count > 1) { return Optional.of(invalid(method, "Multiple" + errorMessageCommon)); } else { return Optional.empty(); } <END> }; }</code><technical_language>I this code block appears in class, please extract</technical_language>

Target:
private static Function<Method, Optional<String>> hasParam(Class<? extends Annotation> annotation, Class<?> type) { return method -> { long count = Arrays.stream(method.getParameters()) .filter(parameter -> parameter.isAnnotationPresent(annotation) && type.equals(parameter.getType())) .count(); String errorMessageCommon = " method parameter with @" + annotation.getSimpleName() + " annotation and type " + type.getSimpleName(); return evaluateResult(method, count, errorMessageCommon); }; }
Source:
<code>public void getShop(final Callback<Shop> callback) { <START> retrofitService.getShop().observeOn(AndroidSchedulers.mainThread()).subscribe(new InternalCallback<Shop>() { <END> @Override public void success(Shop body, Response response) { callback.success(body, response); } @Override public void failure(RetrofitError error) { callback.failure(error); } }); }</code><technical_language>Hey @yervantk lets extract AndroidSchedulers.mainThread() local field in future configure thread/scheduler client want for call backs</technical_language>

Target:
public void getShop(final Callback<Shop> callback) { retrofitService.getShop().observeOn(getCallbackScheduler()).subscribe(new InternalCallback<Shop>() { @Override public void success(Shop body, Response response) { callback.success(body, response); } @Override public void failure(RetrofitError error) { callback.failure(error); } }); }
Source:
<code>protected IInteractionContext getContext() { IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IInteractionContext context = null; <START> if (!(activeWorkbenchWindow == null || activeWorkbenchWindow.getActivePage() == null)) { <END> IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage(); IEditorPart activeEditor = activePage.getActiveEditor(); if (activeEditor != null && activePage.getActivePart().equals(activeEditor)) { context = (IInteractionContext) activeEditor.getEditorInput().getAdapter(IInteractionContext.class); } } if (context == null && ContextCorePlugin.getContextManager().isContextActive()) { context = ContextCorePlugin.getContextManager().getActiveContext(); } if (context == null) { throw new IllegalStateException("error determining action context"); } return context; }</code><technical_language>reverse condition? hard parse negated conditions :)</technical_language>

Target:
protected IInteractionContext getContext() { IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IInteractionContext context = null; if (activeWorkbenchWindow != null && activeWorkbenchWindow.getActivePage() != null) { IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage(); IEditorPart activeEditor = activePage.getActiveEditor(); if (activeEditor != null && activePage.getActivePart().equals(activeEditor)) { context = (IInteractionContext) activeEditor.getEditorInput().getAdapter(IInteractionContext.class); } } if (context == null && ContextCorePlugin.getContextManager().isContextActive()) { context = ContextCorePlugin.getContextManager().getActiveContext(); } if (context == null) { throw new IllegalStateException("error determining action context"); } return context; }
Source:
<code>protected void doHandleChanged() { if (getActionOnChange() != null) { final ActionEvent event = new ActionEvent(this, getActionCommand(), getActionObject()); final WComponent currentInput = this; Runnable later = new Runnable() { @Override public void run() { getActionOnChange().execute(event); <START> if (AjaxHelper.isCurrentAjaxTrigger(currentInput) && UIContextHolder.getCurrent().getFocussed() == null) { <END> setFocussed(); } } }; invokeLater(later); } else if (AjaxHelper.isCurrentAjaxTrigger(this) && UIContextHolder.getCurrent().getFocussed() == null) { setFocussed(); } }</code><technical_language>helpful is a new method in AbstractInput check if input is current AJAX trigger. This useful for input components do this check.... /** * * @return true if this input is current AJAX trigger */ public boolean isCurrentAjaxTrigger() { return AjaxHelper.isCurrentAjaxTrigger(this); }</technical_language>

Target:
protected void doHandleChanged() { if (getActionOnChange() != null) { final ActionEvent event = new ActionEvent(this, getActionCommand(), getActionObject()); final boolean isCAT = isCurrentAjaxTrigger(); Runnable later = new Runnable() { @Override public void run() { getActionOnChange().execute(event); if (isCAT && UIContextHolder.getCurrent().getFocussed() == null) { setFocussed(); } } }; invokeLater(later); } else if (AjaxHelper.isCurrentAjaxTrigger(this) && UIContextHolder.getCurrent().getFocussed() == null) { setFocussed(); } }
Source:
<code>public void updateActionBars() { getStatusLineManager().update(false); getMenuManager().update(false); if (toolbarManager != null) { ToolBarManager tbm = <START> (ToolBarManager) toolbarManager; <END> Control tbCtrl = tbm.getControl(); if (tbCtrl == null || tbCtrl.isDisposed()) { if (part.getContext() != null) { } } else { tbm.update(true); if (!tbCtrl.isDisposed()) { Control packParent = getPackParent(tbCtrl); packParent.pack(); if (packParent.getParent() instanceof CTabFolder) packParent.getParent().layout(true); } } MToolBar toolbar = part.getToolbar(); if (toolbar != null) { Object renderer = toolbar.getRenderer(); if (renderer instanceof ToolBarManagerRenderer) { ((ToolBarManagerRenderer) renderer).reconcileManagerToModel(toolbarManager, toolbar); } } } MUIElement parent = getParentModel(); if (parent != null && isOnTop()) { Object renderer = parent.getRenderer(); if (renderer instanceof StackRenderer) { StackRenderer stackRenderer = (StackRenderer) renderer; CTabFolder folder = (CTabFolder) parent.getWidget(); stackRenderer.adjustTopRight(folder); } } super.updateActionBars(); }</code><technical_language>removed if field right type</technical_language>

Target:
public void updateActionBars() { getStatusLineManager().update(false); getMenuManager().update(false); if (toolbarManager != null) { Control tbCtrl = toolbarManager.getControl(); if (tbCtrl == null || tbCtrl.isDisposed()) { if (part.getContext() != null) { } } else { toolbarManager.update(true); if (!tbCtrl.isDisposed()) { Control packParent = getPackParent(tbCtrl); packParent.pack(); if (packParent.getParent() instanceof CTabFolder) packParent.getParent().layout(true); } } MToolBar toolbar = part.getToolbar(); if (toolbar != null) { Object renderer = toolbar.getRenderer(); if (renderer instanceof ToolBarManagerRenderer) { ((ToolBarManagerRenderer) renderer).reconcileManagerToModel(toolbarManager, toolbar); } } } MUIElement parent = getParentModel(); if (parent != null && isOnTop()) { Object renderer = parent.getRenderer(); if (renderer instanceof StackRenderer) { StackRenderer stackRenderer = (StackRenderer) renderer; CTabFolder folder = (CTabFolder) parent.getWidget(); stackRenderer.adjustTopRight(folder); } } super.updateActionBars(); }
Source:
<code>public LdapKeyStore build() { Assert.checkNotNullParam("dirContextSupplier", dirContextSupplier); Assert.checkNotNullParam("searchPath", searchPath); Assert.checkNotNullParam("searchScope", searchScope); Assert.checkNotNullParam("searchTimeLimit", searchTimeLimit); Assert.checkNotNullParam("aliasAttribute", aliasAttribute); Assert.checkNotNullParam("certificateAttribute", certificateAttribute); Assert.checkNotNullParam("certificateType", certificateType); Assert.checkNotNullParam("certificateChainAttribute", certificateChainAttribute); Assert.checkNotNullParam("certificateChainEncoding", certificateChainEncoding); Assert.checkNotNullParam("keyAttribute", keyAttribute); Assert.checkNotNullParam("keyType", keyType); if (filterAlias == null) filterAlias = "(" + aliasAttribute + "={0})"; if (filterCertificate == null) filterCertificate = "(" + certificateAttribute + "={0})"; if (filterIterate == null) filterIterate = "(" + aliasAttribute + "=*)"; LdapKeyStoreSpi spi = new LdapKeyStoreSpi(dirContextSupplier, searchPath, searchScope, searchTimeLimit, filterAlias, filterCertificate, filterIterate, createPath, createRdn, createAttributes, aliasAttribute, certificateAttribute, certificateType, certificateChainAttribute, certificateChainEncoding, keyAttribute, keyType); <START> return new LdapKeyStore(spi, new WildFlyElytronProvider(), "LdapRealm"); <END> }</code><technical_language>I this is right do. instantiate another Elytron provider instance here. need some kind of NullProvider instance</technical_language>

Target:
public LdapKeyStore build() { Assert.checkNotNullParam("dirContextSupplier", dirContextSupplier); Assert.checkNotNullParam("searchPath", searchPath); Assert.checkNotNullParam("searchScope", searchScope); Assert.checkNotNullParam("searchTimeLimit", searchTimeLimit); Assert.checkNotNullParam("aliasAttribute", aliasAttribute); Assert.checkNotNullParam("certificateAttribute", certificateAttribute); Assert.checkNotNullParam("certificateType", certificateType); Assert.checkNotNullParam("certificateChainAttribute", certificateChainAttribute); Assert.checkNotNullParam("certificateChainEncoding", certificateChainEncoding); Assert.checkNotNullParam("keyAttribute", keyAttribute); Assert.checkNotNullParam("keyType", keyType); if (filterAlias == null) filterAlias = "(" + aliasAttribute + "={0})"; if (filterCertificate == null) filterCertificate = "(" + certificateAttribute + "={0})"; if (filterIterate == null) filterIterate = "(" + aliasAttribute + "=*)"; LdapKeyStoreSpi spi = new LdapKeyStoreSpi(dirContextSupplier, searchPath, searchScope, searchTimeLimit, filterAlias, filterCertificate, filterIterate, createPath, createRdn, createAttributes, aliasAttribute, certificateAttribute, certificateType, certificateChainAttribute, certificateChainEncoding, keyAttribute, keyType); return new LdapKeyStore(spi, EmptyProvider.getInstance(), "LdapRealm"); }
Source:
<code>private boolean isPortInUse(int port) { try { <START> new Socket("127.0.0.1", port).close(); <END> return true; } catch(IOException e) { } return false; }</code><technical_language>create a ServerSocket 0.0.0.0 attempt bind port, attempting connect it. a lot of reasons connection port fail, block for a bit connect this function hang. Additionally, real guarantee in singularity app bind 127.0.0.1, bind main IP of host miss it, binding 0.0.0.0 ensure listening port address</technical_language>

Target:
private boolean isPortInUse(int port) { try { new ServerSocket(port, 1).close(); return false; } catch(IOException e) { } return true; }
Source:
<code>public ValidationResult(VdcBllMessages message, String... variableReplacements) { if (message == null) { throw new IllegalArgumentException("message must not be null"); } this.message = message; <START> this.variableReplacements = variableReplacements == null ? <END> Collections.<String>emptyList() : Collections.unmodifiableList(Arrays.asList(variableReplacements)); }</code><technical_language>extend condition empty variableReplacements array is more common case of ValidationResult: this.variableReplacements = variableReplacements == null || variableReplacements.length == 0 ? ..</technical_language>

Target:
public ValidationResult(VdcBllMessages message, String... variableReplacements) { if (message == null) { throw new IllegalArgumentException("message must not be null"); } this.message = message; this.variableReplacements = variableReplacements == null || variableReplacements.length == 0 ? Collections.<String>emptyList() : Collections.unmodifiableList(Arrays.asList(variableReplacements)); }
Source:
<code>private void performActionForServicesOfCluster() { List<VDS> servers = getClusterUtils().getAllUpServers(clusterId); <START> final List<GlusterService> serviceList = getServiceList(); <END> List<Callable<Pair<VDS, VDSReturnValue>>> taskList = new ArrayList<Callable<Pair<VDS, VDSReturnValue>>>(); for (final VDS upServer : servers) { final List<String> serviceListStr = new ArrayList<String>(); for (GlusterService srvc : serviceList) { serviceListStr.add(srvc.getServiceName()); } taskList.add(new Callable<Pair<VDS, VDSReturnValue>>() { @Override public Pair<VDS, VDSReturnValue> call() throws Exception { VDSReturnValue returnValue; returnValue = runVdsCommand( VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(upServer.getId(), serviceListStr, actionType)); Pair<VDS, VDSReturnValue> pairRetVal = new Pair<VDS, VDSReturnValue>(upServer, returnValue); if (returnValue.getSucceeded()) updateService(upServer.getId(), serviceList, pairRetVal); return pairRetVal; } }); } setSucceeded(true); if (!taskList.isEmpty()) { List<Pair<VDS, VDSReturnValue>> pairResults = ThreadPoolUtil.invokeAll(taskList); for (Pair<VDS, VDSReturnValue> pairResult : pairResults) { VDSReturnValue retValue = pairResult.getSecond(); if (!retValue.getSucceeded()) { errors.add(retValue.getVdsError().getMessage()); } } } else { setSucceeded(false); } if (errors.size() > 0) { setSucceeded(false); handleVdsErrors(getAuditLogTypeValue(), errors); addCustomValue(GlusterConstants.FAILURE_MESSAGE, StringUtils.join(errors, SystemUtils.LINE_SEPARATOR)); } else { setSucceeded(true); } }</code><technical_language>getServiceList return a List<String> returns service names alone. reuse in performActionForServicesOfServer</technical_language>

Target:
private void performActionForServicesOfCluster() { List<Callable<Pair<VDS, VDSReturnValue>>> taskList = getTaskList(); if (!taskList.isEmpty()) { invokeManageGlusterService(taskList); } else { setSucceeded(false); } }