auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static byte[] inflate(byte[] bytes, int expectedSize) { try { Inflater decompressor = new Inflater(); decompressor.setInput(bytes, 0, bytes.length); byte[] result = new byte[expectedSize]; <START> decompressor.inflate(result); <END> decompressor.end(); return result; } catch (Exception e) { throw new RuntimeException("Unable to inflate binary data", e); } }</code><technical_language>Inflate tricky. If done yet, need call again. fully populate output buffer verify zlib crc trailer corrupt data inflated. this: for (int dstoff = 0;;) { int n = inf.inflate(dstbuf, dstoff, dstbuf.length - dstoff); dstoff += n; if (inf.finished()) { return dstbuf; } else if (inf.needsInput()) { position += inf.setInput(bytes, position, bytes.length - position); } else if (n == 0) { throw new DataFormatException(); } }</technical_language>

Target:
public static byte[] inflate(byte[] bytes, int expectedSize) throws DataFormatException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(expectedSize); InflaterOutputStream ios = new InflaterOutputStream(baos); ios.write(bytes, 0, bytes.length); return baos.toByteArray(); } catch (Exception e) { throw new DataFormatException(); } }
Source:
<code>public void startWebSocketServer(String hostname, int webSocketPort) throws IOException { if(webSocketTestServer == null){ webSocketTestServer = new NanoWebSocketTestServer(hostname,webSocketPort); } <START> webSocketTestServer.start(); <END> }</code><technical_language>allow configure timeout, tests want ping/pong connection alive (I'd expect them, "noise")</technical_language>

Target:
public void startWebSocketServer(String hostname, int webSocketPort) throws IOException { startWebSocketServer(hostname,webSocketPort,5000); }
Source:
<code>Buffer marshallCall(ReplicableCommand command) { try { <START> return new Buffer(ispnMarshaller.objectToByteBuffer(command)); <END> } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Failure to marshal argument(s)", e); } }</code><technical_language>marshaller.objectToBuffer() instead? objectToByteBuffer() trim byte[] objectToBuffer() save some allocations. wdyt</technical_language>

Target:
Buffer marshallCall(ReplicableCommand command) { try { ByteBuffer bytes = ispnMarshaller.objectToBuffer(command); return new Buffer(bytes.getBuf(), bytes.getOffset(), bytes.getLength()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Failure to marshal argument(s)", e); } }
Source:
<code>public Map<String, Long> getPartitionTimeLag(Map<String, String> currentOffsets) { <START> return partitionResources.entrySet() <END> .stream() .collect( Collectors.toMap(k -> k.getKey().getPartitionId(), k -> k.getValue().getPartitionTimeLag(currentOffsets.get(k.getKey().getPartitionId()))) ); }</code><technical_language>number of partitions order of hundreds, sense avoid streams for performance (I remember issues in stream perf)</technical_language>

Target:
public Map<String, Long> getPartitionTimeLag(Map<String, String> currentOffsets) { Map<String, Long> partitionLag = Maps.newHashMapWithExpectedSize(currentOffsets.size()); for (Map.Entry<StreamPartition<String>, PartitionResource> partition : partitionResources.entrySet()) { final String partitionId = partition.getKey().getPartitionId(); partitionLag.put(partitionId, partition.getValue().getPartitionTimeLag(currentOffsets.get(partitionId))); } return partitionLag; }
Source:
<code>public DynamicSSLContextImpl(AuthenticationContext authenticationContext) throws GeneralSecurityException { this.authenticationContext = authenticationContext; this.configuredSSLContexts = AUTH_CONTEXT_CLIENT.getConfiguredSSLContexts(authenticationContext); this.configuredDefaultSSLContext = AUTH_CONTEXT_CLIENT.getDefaultSSLContext(authenticationContext); <START> } <END></code><technical_language>good assert authenticationContext null here</technical_language>

Target:
public DynamicSSLContextImpl(AuthenticationContext authenticationContext) throws GeneralSecurityException { Assert.assertNotNull("authenticationContext"); this.authenticationContext = authenticationContext; this.configuredSSLContexts = AUTH_CONTEXT_CLIENT.getConfiguredSSLContexts(authenticationContext); this.configuredDefaultSSLContext = AUTH_CONTEXT_CLIENT.getDefaultSSLContext(authenticationContext); }
Source:
<code>public GetUserCallback(final GetUserResponse getUserResponse) { this.getUserResponse = getUserResponse; callback = new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { SocialMember socialMember; try { JSONObject userObj = response.getJSONObject(); if (userObj == null) { logger.warn("Unable to get user json object from facebook graph api."); return; } socialMember = jsonToUser(userObj); <START> } catch (Exception e) { <END> logger.warn("Some exception occurred in fetching user data from facebook graph api."); return; } GetUserCallback.this.getUserResponse.onCompleted(socialMember); } }; }</code><technical_language>catch exception is thrown instead of Exception base class</technical_language>

Target:
public GetUserCallback(final GetUserResponse getUserResponse) { this.getUserResponse = getUserResponse; callback = new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { SocialMember socialMember; try { JSONObject userObj = response.getJSONObject(); if (userObj == null) { logger.warn("Unable to get user json object from facebook graph api."); return; } socialMember = jsonToUser(userObj); } catch (JSONException e) { logger.error(e); return; } GetUserCallback.this.getUserResponse.onCompleted(socialMember); } }; }
Source:
<code>protected ReusableSubprocessTaskExecutionSet createReusableSubprocessTaskExecutionSet(CallActivity activity, CallActivityPropertyReader p) { return new ReusableSubprocessTaskExecutionSet(new CalledElement(activity.getCalledElement()), new IsCase(p.isCase()), new Independent(p.isIndependent()), new WaitForCompletion(p.isWaitForCompletion()), new IsAsync(p.isAsync()), <START> new SLADueDate(p.getSlaDueDate()), <END> new AdHocAutostart(p.isAdHocAutostart()), new IsMultipleInstance(p.isMultipleInstance()), new MultipleInstanceExecutionMode(p.isSequential()), new MultipleInstanceCollectionInput(p.getCollectionInput()), new MultipleInstanceDataInput(p.getDataInput()), new MultipleInstanceCollectionOutput(p.getCollectionOutput()), new MultipleInstanceDataOutput(p.getDataOutput()), new MultipleInstanceCompletionCondition(p.getCompletionCondition()), new OnEntryAction(p.getOnEntryAction()), new OnExitAction(p.getOnExitAction())); }</code><technical_language>please update CallActivityConverterTest</technical_language>

Target:
protected ReusableSubprocessTaskExecutionSet createReusableSubprocessTaskExecutionSet(CallActivity activity, CallActivityPropertyReader p) { return new ReusableSubprocessTaskExecutionSet(new CalledElement(activity.getCalledElement()), new IsCase(p.isCase()), new Independent(p.isIndependent()), new AbortParent(p.isAbortParent()), new WaitForCompletion(p.isWaitForCompletion()), new IsAsync(p.isAsync()), new AdHocAutostart(p.isAdHocAutostart()), new IsMultipleInstance(p.isMultipleInstance()), new MultipleInstanceExecutionMode(p.isSequential()), new MultipleInstanceCollectionInput(p.getCollectionInput()), new MultipleInstanceDataInput(p.getDataInput()), new MultipleInstanceCollectionOutput(p.getCollectionOutput()), new MultipleInstanceDataOutput(p.getDataOutput()), new MultipleInstanceCompletionCondition(p.getCompletionCondition()), new OnEntryAction(p.getOnEntryAction()), new OnExitAction(p.getOnExitAction()), new SLADueDate(p.getSlaDueDate())); }
Source:
<code>private ImmutableList<String> createCommand() { ImmutableList.Builder<String> command = ImmutableList.builder(); command.addAll(groovyc.getCommandPrefix(resolver)); String classpath = Joiner.on(File.pathSeparator).join(transform(declaredClasspathEntries, Object::toString)); command .add("-cp") .add(classpath.isEmpty() ? "''" : classpath) .add("-d") .add(outputDirectory.toString()); addCrossCompilationOptions(command); command.addAll(extraArguments.orElse(ImmutableList.of())); command.add("@" + pathToSrcsList); ImmutableList<String> built = command.build(); <START> built.forEach(System.out::println); <END> return command.build(); }</code><technical_language>Remove</technical_language>

Target:
private ImmutableList<String> createCommand() { ImmutableList.Builder<String> command = ImmutableList.builder(); command.addAll(groovyc.getCommandPrefix(resolver)); String classpath = Joiner.on(File.pathSeparator).join(transform(declaredClasspathEntries, Object::toString)); command .add("-cp") .add(classpath.isEmpty() ? "''" : classpath) .add("-d") .add(outputDirectory.toString()); addCrossCompilationOptions(command); command.addAll(extraArguments.orElse(ImmutableList.of())); command.add("@" + pathToSrcsList); return command.build(); }
Source:
<code>public void clickViewActionsButtonOfFirstEntry(){ WebElement table = browser.driver.findElement(By.id("logsTable")); WebElement tableRow; try { tableRow = table.findElements(By.tagName("tr")).get(1); } catch (IndexOutOfBoundsException onlyoneentry) { tableRow = table.findElements(By.tagName("tr")).get(0); <START> } <END> WebElement element = tableRow.findElement(By.tagName("button")); element.click(); }</code><technical_language>Try exceptions control normal workflow. check result size first</technical_language>

Target:
public void clickViewActionsButtonOfFirstEntry(){ WebElement table = browser.driver.findElement(By.id("logsTable")); WebElement tableRow = table.findElements(By.tagName("tr")).get(1); WebElement element = tableRow.findElement(By.tagName("button")); element.click(); }
Source:
<code>public int compare(TaskExecution firstTaskExecution, TaskExecution secondTaskExecution) { if (firstTaskExecution.getStartTime().equals(secondTaskExecution.getStartTime())) { <START> return Long.valueOf(firstTaskExecution.getExecutionId()).compareTo(Long.valueOf(secondTaskExecution.getExecutionId())); <END> } else { return secondTaskExecution.getStartTime().compareTo(firstTaskExecution.getStartTime()); } }</code><technical_language>Long.valueOf? values longs anyways..</technical_language>

Target:
public int compare(TaskExecution firstTaskExecution, TaskExecution secondTaskExecution) { if (firstTaskExecution.getStartTime().equals(secondTaskExecution.getStartTime())) { return Long.compare(firstTaskExecution.getExecutionId(), secondTaskExecution.getExecutionId()); } else { return secondTaskExecution.getStartTime().compareTo(firstTaskExecution.getStartTime()); } }
Source:
<code>public Resource getTotalUsedResources() { return getInstances().stream() .map(PackingPlan.InstancePlan::getResource) <START> .reduce(Resource::plus) <END> .orElse(Resource.EMPTY_RESOURCE) .plus(getPadding()); }</code><technical_language>is a reduce EMPTY_SOURCE initial value? cleaner way</technical_language>

Target:
public Resource getTotalUsedResources() { return getInstances().stream() .map(PackingPlan.InstancePlan::getResource) .reduce(Resource.EMPTY_RESOURCE, Resource::plus) .plus(getPadding()); }
Source:
<code><START> private final void excludeLinesIfTrue(boolean shouldExclude, Tree tree, Class<? extends JavaCheck> rule) { <END> if (shouldExclude) { excludeLines(tree, rule); } else { acceptLines(tree, rule); } }</code><technical_language>final sense for private method, a rule for</technical_language>

Target:
private void excludeLinesIfTrue(boolean shouldExclude, Tree tree, Class<? extends JavaCheck> rule) { if (shouldExclude) { excludeLines(tree, rule); } else { acceptLines(tree, rule); } }
Source:
<code>protected Object[] fetchChildren(Object o, IProgressMonitor monitor) throws TeamException { if (tag.getType() == CVSTag.BRANCH) { monitor = Policy.monitorFor(monitor); monitor.beginTask(NLS.bind( <START> CVSUIMessages.RemoteFolderElement_fetchingRemoteChildren, <END> new String[] { root.toString() }), 100); try { ICVSRemoteResource[] children = CVSUIPlugin .getPlugin() .getRepositoryManager() .getFoldersForTag(root, tag, Policy.subMonitorFor(monitor, 50)); if (getWorkingSet() != null) children = CVSUIPlugin.getPlugin().getRepositoryManager() .filterResources(getWorkingSet(), children); return getTopLevelFoldersForChildren(children, Policy.subMonitorFor(monitor, 50)); } finally { monitor.done(); } } ICVSRemoteResource[] children = CVSUIPlugin.getPlugin().getRepositoryManager().getFoldersForTag(root, tag, monitor); if (getWorkingSet() != null) children = CVSUIPlugin.getPlugin().getRepositoryManager().filterResources(getWorkingSet(), children); return children; }</code><technical_language>agreed hard add a more specific message here</technical_language>

Target:
protected Object[] fetchChildren(Object o, IProgressMonitor monitor) throws TeamException { if (tag.getType() == CVSTag.BRANCH) { monitor = Policy.monitorFor(monitor); monitor.beginTask(NLS.bind( CVSUIMessages.RemoteFolderElement_fetchingRemoteChildren, new String[] { root.toString() }), 100); try { ICVSRemoteResource[] children = CVSUIPlugin .getPlugin() .getRepositoryManager() .getFoldersForTag(root, tag, Policy.subMonitorFor(monitor, 50)); if (getWorkingSet() != null) children = CVSUIPlugin.getPlugin().getRepositoryManager() .filterResources(getWorkingSet(), children); return getTopLevelRemoteFolders(children, Policy.subMonitorFor(monitor, 50)); } finally { monitor.done(); } } ICVSRemoteResource[] children = CVSUIPlugin.getPlugin().getRepositoryManager().getFoldersForTag(root, tag, monitor); if (getWorkingSet() != null) children = CVSUIPlugin.getPlugin().getRepositoryManager().filterResources(getWorkingSet(), children); return children; }
Source:
<code>public String render(final GetTapesWithFullDetailsResult obj) throws JsonProcessingException { final NamedDetailedTapeList result = obj.getTapesWithDetails(); <START> if ((result == null) || (null == result.getNamedDetailedTapes()) || (result.getNamedDetailedTapes().size() == 0 ) ){ <END> return "You do not have any tapes"; } return ASCIITable.getInstance().getTable(getHeaders(), formatTapeList(result)); }</code><technical_language>null == in middle condition sets OCD (backwards comparison) - I change this... I written I prefer constant left in comparisons PHB put kibosh</technical_language>

Target:
public String render(final GetTapesWithFullDetailsResult obj) throws JsonProcessingException { final NamedDetailedTapeList result = obj.getTapesWithDetails(); if ((result == null) || (Guard.isNullOrEmpty(result.getNamedDetailedTapes())) ){ return "You do not have any tapes"; } return ASCIITable.getInstance().getTable(getHeaders(), formatTapeList(result)); }
Source:
<code>protected boolean isVersionSupportedForShareable() { return Config.<Boolean> GetValue(ConfigValues.ShareableDiskEnabled, <START> getStoragePool().getcompatibility_version().getValue()); <END> }</code><technical_language>for storage pool null? (LUN disk, floating..)</technical_language>

Target:
protected boolean isVersionSupportedForShareable() { return getStoragePool() != null ?Config.<Boolean> GetValue(ConfigValues.ShareableDiskEnabled, getStoragePool().getcompatibility_version().getValue()) : true; }
Source:
<code>private static IStatus openTraceFromFolder(TmfTraceFolder destinationFolder, String traceName) { final List<ITmfProjectModelElement> elements = destinationFolder.getChildren(); TmfTraceElement traceElement = null; for (ITmfProjectModelElement element : elements) { if (element instanceof TmfTraceElement && element.getName().equals(traceName)) { traceElement = (TmfTraceElement) element; } } if (traceElement == null) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, NLS.bind(Messages.TmfOpenTraceHelper_TraceNotFound, traceName)); } <START> IStatus status = openFromElement(traceElement); return status; <END> }</code><technical_language>return</technical_language>

Target:
private static IStatus openTraceFromFolder(TmfTraceFolder destinationFolder, String traceName) { final List<ITmfProjectModelElement> elements = destinationFolder.getChildren(); TmfTraceElement traceElement = null; for (ITmfProjectModelElement element : elements) { if (element instanceof TmfTraceElement && element.getName().equals(traceName)) { traceElement = (TmfTraceElement) element; } } if (traceElement == null) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, NLS.bind(Messages.TmfOpenTraceHelper_TraceNotFound, traceName)); } IStatus status = openFromElement(traceElement); if (!status.isOK()) { Activator.getDefault().logError("Error opening trace from folder: " + status.getMessage()); } return status; }
Source:
<code>public void onProduct(final Product product) throws Exception { ProductId id = product.getId(); try { productStorage.storeProduct(product); } catch (ProductAlreadyInStorageException e) { } Date expirationDate = new Date(new Date().getTime() + productStorageMaxAge); URLNotification notification = new URLNotification(id, expirationDate, product.getTrackerURL(), productStorage.getProductURL(id)); Iterator<Notification> existing = getNotificationIndex() .findNotifications(id).iterator(); while (existing.hasNext()) { getNotificationIndex().removeNotification(existing.next()); } <START> getNotificationIndex().addNotification(notification); <END> sendNotification(notification); new ProductTracker(notification.getTrackerURL()).notificationSent( this.getName(), notification); }</code><technical_language>sendNotification fail, adding a notification index occur calling sendNotification - retry in future a restart</technical_language>

Target:
public void onProduct(final Product product) throws Exception { ProductId id = product.getId(); try { productStorage.storeProduct(product); } catch (ProductAlreadyInStorageException e) { } Date expirationDate = new Date(new Date().getTime() + productStorageMaxAge); URLNotification notification = new URLNotification(id, expirationDate, product.getTrackerURL(), productStorage.getProductURL(id)); Iterator<Notification> existing = getNotificationIndex() .findNotifications(id).iterator(); while (existing.hasNext()) { getNotificationIndex().removeNotification(existing.next()); } try { sendNotification(notification); } catch (Exception e) { productStorage.removeProduct(id); throw e; } getNotificationIndex().addNotification(notification); new ProductTracker(notification.getTrackerURL()).notificationSent( this.getName(), notification); }
Source:
<code><START> public static TaskType fromToken(String token) { <END> return TaskType.valueOf(token.trim().toUpperCase()); }</code><technical_language>do need this serialization logic? @twdsilva @kadirozde I copied LinkType other Enum's defined above</technical_language>

Target:
public static IndexType fromToken(String token) { return IndexType.valueOf(token.trim().toUpperCase()); }
Source:
<code>public void run(String[] args) { boolean validCommand = false; if (args.length >= 2) { boolean flag = false; if ("enable".equals(args[1])) { flag = true; validCommand = true; } else if ("disable".equals(args[1])) { flag = false; validCommand = true; } if (validCommand) { IWifiManager wifiMgr = IWifiManager.Stub.asInterface(ServiceManager.getService(Context.WIFI_SERVICE)); try { <START> if (wifiMgr == null) { System.err.println("Wi-Fi service is not ready"); return; } <END> wifiMgr.setWifiEnabled("com.android.shell", flag); } catch (RemoteException e) { System.err.println("Wi-Fi operation failed: " + e); } return; } } System.err.println(longHelp()); }</code><technical_language>Do a reason put this try block</technical_language>

Target:
public void run(String[] args) { boolean validCommand = false; if (args.length >= 2) { boolean flag = false; if ("enable".equals(args[1])) { flag = true; validCommand = true; } else if ("disable".equals(args[1])) { flag = false; validCommand = true; } if (validCommand) { IWifiManager wifiMgr = IWifiManager.Stub.asInterface(ServiceManager.getService(Context.WIFI_SERVICE)); if (wifiMgr == null) { System.err.println("Wi-Fi service is not ready"); return; } try { wifiMgr.setWifiEnabled("com.android.shell", flag); } catch (RemoteException e) { System.err.println("Wi-Fi operation failed: " + e); } return; } } System.err.println(longHelp()); }
Source:
<code>protected boolean canDoAction() { if (!isVmExist()) { return false; } if (!acquireLockInternal()) { return false; } VM vm = getVm(); if (vm != null) { <START> updateDisksFromDb(); <END> if (!isDiskCanBeAddedToVm(getParameters().getDiskInfo()) || !isDiskPassPciAndIdeLimit(getParameters().getDiskInfo())) { return false; } } if (DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfImageDiskCanBeAdded(vm); } if (DiskStorageType.LUN == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfLunDiskCanBeAdded(); } return true; }</code><technical_language>I some doubts placing here. is related canDoAction is - info brought this method populates, for canDoAction validation. place call executeCommand</technical_language>

Target:
protected boolean canDoAction() { if (!isVmExist() || !acquireLockInternal()) { return false; } VM vm = getVm(); if (vm != null) { updateDisksFromDb(); if (!isDiskCanBeAddedToVm(getParameters().getDiskInfo()) || !isDiskPassPciAndIdeLimit(getParameters().getDiskInfo())) { return false; } } if (DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfImageDiskCanBeAdded(vm); } if (DiskStorageType.LUN == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfLunDiskCanBeAdded(); } return true; }
Source:
<code>public void configure(Type type, Properties params, Dialect dialect) throws MappingException { <START> params.setProperty( SEGMENT_VALUE_PARAM, params.getProperty( IDENTITY_NAME ) ); <END> tableGenerator.configure( type, params, dialect ); }</code><technical_language>modify input, create a copy Properties newParams = new Properties( params);</technical_language>

Target:
public void configure(Type type, Properties params, Dialect dialect) throws MappingException { Properties newParams = new Properties( params ); for ( Map.Entry<Object, Object> param : params.entrySet() ) { newParams.put( param.getKey(), param.getValue() ); } newParams.setProperty( OgmTableGenerator.SEGMENT_VALUE_PARAM, newParams.getProperty( PersistentIdentifierGenerator.TABLE ) ); tableGenerator.configure( type, newParams, dialect ); }
Source:
<code>public void testLogcatOutput_ShouldPrintIfTrayAuthorityIsNotDefault() throws Exception { final MockContext stuff = new MockContext() { @Override public Resources getResources() { final Resources mockResources = mock(Resources.class); <START> when(mockResources.getString(anyInt())).thenReturn(eq("notDefaultTrayAuthority")); <END> return mockResources; } }; TrayContract.generateInternalContentUri(stuff); assertTrue(true); }</code><technical_language>define mockResources of MockContext verify called</technical_language>

Target:
public void testLogcatOutput_ShouldPrintIfTrayAuthorityIsNotDefault() throws Exception { final List<ProviderInfo> mockProviders = new ArrayList<>(); ProviderInfo info = new ProviderInfo(); info.authority = "my.custom.authority"; info.name = TrayContentProvider.class.getName(); mockProviders.add(info); getProviderMockContext().setProviderInfos(mockProviders); final Resources mockResources = mock(Resources.class); when(mockResources.getString(R.string.tray__authority)) .thenReturn("NOTlegacyTrayAuthority"); getProviderMockContext().setResources(mockResources); TrayContract.generateInternalContentUri(getProviderMockContext()); verify(mockResources).getString(R.string.tray__authority); }
Source:
<code>public static void checkConfiguration() { Job job = new Job(UIText.ConfigurationChecker_checkConfiguration) { @Override protected IStatus run(IProgressMonitor monitor) { if (PlatformUI.isWorkbenchRunning()) PlatformUI.getWorkbench().getDisplay() .asyncExec(new Runnable() { public void run() { check(); } }); else <START> schedule(1000L); <END> return Status.OK_STATUS; } }; job.schedule(); }</code><technical_language>add braces for if else? omit braces in simple statements</technical_language>

Target:
public static void checkConfiguration() { Job job = new Job(UIText.ConfigurationChecker_checkConfiguration) { @Override protected IStatus run(IProgressMonitor monitor) { if (PlatformUI.isWorkbenchRunning()) { PlatformUI.getWorkbench().getDisplay() .asyncExec(new Runnable() { public void run() { check(); } }); } else { schedule(1000L); } return Status.OK_STATUS; } }; job.schedule(); }
Source:
<code>private void casePropertiesChange(Object oldValue, Object newValue) { if (oldValue instanceof String[] && newValue instanceof Property) { Property property = (Property) newValue; if (property.getItem() instanceof ProcessItem) { ITestContainerProviderService service = getTestContainerProviderService(); boolean isTestCase = false; if (service != null) { isTestCase = service.isTestContainerItem(property.getItem()); } if (isTestCase) { } else { String[] oldFields = (String[]) oldValue; if (oldFields.length == 0) { return; } String oldName = oldFields[0]; String oldVersion = oldFields[1]; if (!oldName.equals(property.getLabel())) { TalendJavaProjectManager.deleteAllVersionTalendJobProject(property.getId(), oldName, true); TalendJavaProjectManager.createAllVersionTalendJobProject(property.getId()); } else if (!oldVersion.equals(property.getVersion())) { <START> TalendJavaProjectManager.generatePom((ProcessItem) property.getItem(), 0x8); <END> } } } } }</code><technical_language>constants !!!! read this code later</technical_language>

Target:
private void casePropertiesChange(Object oldValue, Object newValue) { if (oldValue instanceof String[] && newValue instanceof Property) { Property property = (Property) newValue; if (property.getItem() instanceof ProcessItem) { ITestContainerProviderService service = getTestContainerProviderService(); boolean isTestCase = false; if (service != null) { isTestCase = service.isTestContainerItem(property.getItem()); } if (isTestCase) { } else { String[] oldFields = (String[]) oldValue; if (oldFields.length == 0) { return; } String oldName = oldFields[0]; String oldVersion = oldFields[1]; if (!oldName.equals(property.getLabel())) { TalendJavaProjectManager.deleteAllVersionTalendJobProject(property.getId(), oldName, true); TalendJavaProjectManager.createAllVersionTalendJobProject(property.getId()); } else if (!oldVersion.equals(property.getVersion())) { TalendJavaProjectManager.generatePom((ProcessItem) property.getItem(), TalendJavaProjectConstants.GEN_PROPERTIES_CHANGED); } } } } }
Source:
<code>public void run() { Logger.info(this, "Trying to reindex all the content"); try{ conAPI.reindex(); Logger.info(this, "Reindexation is in progress"); }catch (Exception e) { Logger.info(this, "Unable to reindex. Probably because another reindexation is in progress"); }finally{ try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { <START> Logger.error(ContentReindexerThread.class, e.getMessage(), e); <END> } } }</code><technical_language>Remove entire wrapper finally block</technical_language>

Target:
public void run() { Logger.info(this, "Trying to reindex all the content"); try{ conAPI.reindex(); Logger.info(this, "Reindexation is in progress"); }catch (Exception e) { Logger.info(this, "Unable to reindex. Probably because another reindexation is in progress"); } }
Source:
<code>public void exportRowEnd(final OutputStream outputStream, final int rowPosition) throws IOException { <START> this.currentRow.append("\n"); <END> outputStream.write(this.currentRow.toString().getBytes(this.usedCharset)); }</code><technical_language>I \n is sufficient thinking other operating systems. this System.getProperty("line.separator") related charset, working that</technical_language>

Target:
public void exportRowEnd(final OutputStream outputStream, final int rowPosition) throws IOException { this.currentRow.append(System.getProperty("line.separator")); outputStream.write(this.currentRow.toString().getBytes(this.usedCharset)); }
Source:
<code>public static DocumentPath from(List<String> elements) { List<String> copy = new ArrayList<>(); <START> copy.add(""); <END> copy.addAll(elements); return new DocumentPath(copy); }</code><technical_language>empty string for</technical_language>

Target:
public static DocumentPath from(List<String> elements) { List<String> copy = new ArrayList<>(); copy.add(ROOT_ELEMENT); copy.addAll(elements); return new DocumentPath(copy); }
Source:
<code>protected void setParentNode(GoloElement parent) { <START> if (!(parent instanceof Union) || parent == null) { <END> throw new IllegalArgumentException("UnionValue can only be defined in a Union"); } super.setParentNode(parent); }</code><technical_language>Findbugs "redundant nullcheck", parent instanceof Union is false if parent is null</technical_language>

Target:
protected void setParentNode(GoloElement parent) { if (!(parent instanceof Union)) { throw new IllegalArgumentException("UnionValue can only be defined in a Union"); } super.setParentNode(parent); }
Source:
<code>public void setComplete() { this.complete = true; ExchangeObserver obs = this.observer; <START> if (null != obs) { <END> obs.completed(this); } }</code><technical_language>@boaks, prefer this pattern of putting *constant* compare in place. Personally, I find this harder read. So, a strong opinion this change comparisons instead stick approach rest of code. discuss mailing list a vote want adopt this pattern in general</technical_language>

Target:
public void setComplete() { this.complete = true; ExchangeObserver obs = this.observer; if (obs != null) { obs.completed(this); } }
Source:
<code>public void update(Observable arg0, Object argN) { final String arg1 = OoyalaNotification.getNameOrUnknown(argN); if (arg1 == OoyalaPlayer.TIME_CHANGED_NOTIFICATION_NAME) { return; } if (arg1 == OoyalaPlayer.ERROR_NOTIFICATION_NAME) { final String msg = "Error Event Received"; if (player != null && player.getError() != null) { Log.e(TAG, msg, player.getError()); } else { Log.e(TAG, msg); } return; } if (arg1 == OoyalaSkinLayoutController.FULLSCREEN_CHANGED_NOTIFICATION_NAME) { Log.d(TAG, "Fullscreen Notification received : " + arg1 + " - fullScreen: " + ((OoyalaNotification)argN).getData()); } String text="Notification Received: " + arg1 + " - state: " + player.getState(); log.writeToSdcardLog(text); <START> Log.d(TAG, "Notification Received: " + arg1 + " - state: " + player.getState()); <END> }</code><technical_language>reuse text variable exact string literal</technical_language>

Target:
public void update(Observable arg0, Object argN) { final String arg1 = OoyalaNotification.getNameOrUnknown(argN); if (arg1 == OoyalaPlayer.TIME_CHANGED_NOTIFICATION_NAME) { return; } if (arg1 == OoyalaPlayer.ERROR_NOTIFICATION_NAME) { final String msg = "Error Event Received"; if (null != player && null != player.getError()) { Log.e(TAG, msg, player.getError()); } else { Log.e(TAG, msg); } return; } if (arg1 == OoyalaSkinLayoutController.FULLSCREEN_CHANGED_NOTIFICATION_NAME) { Log.d(TAG, "Fullscreen Notification received : " + arg1 + " - fullScreen: " + ((OoyalaNotification)argN).getData()); } String text = "Notification Received: " + arg1 + " - state: " + player.getState(); log.writeToSdcardLog(text); Log.d(TAG, text); }
Source:
<code>public void setUp() throws Exception { <START> <END> VARIANT.addId("randomID"); VARIANT.setAnnotation(new Annotation(CHROMOSOME, 0, 0, null, null, null, null)); VARIANT.addSourceEntry(new VariantSourceEntryWithSampleNames("fid", "sid", null, null, null, null, null)); List<VariantWithSamplesAndAnnotation> variantEntities = Collections.singletonList(VARIANT); given(variantEntityRepository .findByChromosomeAndStartAndReferenceAndAlternate(eq(CHROMOSOME), anyInt(), any(), any(), any())) .willReturn(variantEntities); }</code><technical_language>suggestion</technical_language>

Target:
public void setUp() throws Exception { VARIANT.addId("randomID"); VARIANT.setAnnotation(new Annotation(CHROMOSOME, 0, 0, null, null, null, null)); VARIANT.addSourceEntry(new VariantSourceEntryWithSampleNames("fid", "sid", null, null, null, null, null)); List<VariantWithSamplesAndAnnotation> variantEntities = Collections.singletonList(VARIANT); given(service.findByChromosomeAndStartAndReferenceAndAlternate(eq(CHROMOSOME), anyInt(), any(), any(), any())) .willReturn(variantEntities); }
Source:
<code>public void outputMatchesExpectedForMissingBackupDir() throws UnsupportedEncodingException { String output = runBackup(); String reason = "Missing argument 'backup-dir'\n\n"; <START> assertEquals( reason + BackupHelpOutput.BACKUP_OUTPUT, output ); <END> }</code><technical_language>brittle. Matchers.containsString sanity check output, breaking whitespace change</technical_language>

Target:
public void outputMatchesExpectedForMissingBackupDir() throws UnsupportedEncodingException { String output = runBackup(); String reason = "Missing argument 'backup-dir'"; assertThat( output, containsString( reason ) ); for ( String line : BackupHelpOutput.BACKUP_OUTPUT_LINES ) { assertThat( output, containsString( line ) ); } }
Source:
<code><START> public boolean containsLockOwner(Object lockOwner) { <END> LockPlaceHolder holder = current; if (holder != null && holder.lockOwner.equals(lockOwner)) { return true; } if (pendingRequest.isEmpty()) { return false; } for (LockPlaceHolder pendingHolder : pendingRequest) { if (pendingHolder.lockOwner.equals(lockOwner)) { return true; } } holder = current; return holder != null && holder.lockOwner.equals(lockOwner); }</code><technical_language>Unused</technical_language>

Target:
public boolean containsLockOwner(Object lockOwner) { return lockOwners.containsKey(lockOwner); }
Source:
<code>public void init() throws IOException { if (fragments == null) { scanIt = new EmptyScanIterator(); } else { Schema projectedFields = getProjectSchema(); initScanner(projectedFields); Schema actualInSchema = scanner.isProjectable() ? projectedFields : inSchema; <START> Target[] realTargets; <END> if (plan.getTargets() == null) { realTargets = PlannerUtil.schemaToTargets(outSchema); } else { realTargets = plan.getTargets(); } if (realTargets.length == inSchema.size()) { for (int i = 0; i < inSchema.size(); i++) { if (realTargets[i].getEvalTree() instanceof FieldEval) { FieldEval f = realTargets[i].getEvalTree(); if(!f.getColumnRef().equals(inSchema.getColumn(i))) { needProjection = true; break; } } else { needProjection = true; break; } } } else { needProjection = true; } if(needProjection) { projector = new Projector(context, actualInSchema, outSchema, plan.getTargets()); } if (plan.hasQual()) { qual.bind(context.getEvalContext(), actualInSchema); } initScanIterator(); } super.init(); }</code><technical_language>if this change is extracted separate method initializeProjector</technical_language>

Target:
public void init() throws IOException { if (fragments == null) { scanIt = new EmptyScanIterator(); } else { Schema projectedFields = getProjectSchema(); initScanner(projectedFields); Schema actualInSchema = scanner.isProjectable() ? projectedFields : inSchema; initializeProjector(actualInSchema); if (plan.hasQual()) { qual.bind(context.getEvalContext(), actualInSchema); } initScanIterator(); } super.init(); }
Source:
<code>private void initKeyStore() throws CertificateManagerException { LOG.debug("SamlCallbackHandler.initKeyStore() -- Begin"); final HashMap<String, String> keyStoreProperties = getKeyStoreSystemProperties(); String storeType = keyStoreProperties.get(KEY_STORE_TYPE_KEY); final String password = keyStoreProperties.get(KEY_STORE_SECRET_KEY); final String storeLoc = keyStoreProperties.get(KEY_STORE_KEY); if (storeType == null) { LOG.warn("javax.net.ssl.keyStoreType is not defined. Switch to use JKS by default"); storeType = JKS_TYPE; } if (password !=null){ if (JKS_TYPE.equals(storeType) && storeLoc == null) { <START> LOG.error("javax.net.ssl.keyStore is not defined"); <END> } else { keyStore = loadKeyStore(storeType, password, storeLoc); } }else{ LOG.error("Please define javax.net.ssl.keyStorePassword"); } LOG.debug("SamlCallbackHandler.initKeyStore() -- End"); }</code><technical_language>Consider KEY_STORE_KEY defined above</technical_language>

Target:
private void initKeyStore() throws CertificateManagerException { LOG.debug("SamlCallbackHandler.initKeyStore() -- Begin"); final HashMap<String, String> keyStoreProperties = getKeyStoreSystemProperties(); String storeType = keyStoreProperties.get(KEY_STORE_TYPE_KEY); final String password = keyStoreProperties.get(KEY_STORE_PASSWORD_KEY); final String storeLoc = keyStoreProperties.get(KEY_STORE_KEY); if (storeType == null) { LOG.warn("{} is not defined. Switch to use JKS by default", KEY_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (password !=null){ if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("{} is not defined", KEY_STORE_TYPE_KEY); } else { keyStore = loadKeyStore(storeType, password, storeLoc); } }else{ LOG.error("Please define {}", KEY_STORE_PASSWORD_KEY); } LOG.debug("SamlCallbackHandler.initKeyStore() -- End"); }
Source:
<code>public List<SnmpAgentConfig> getListOfAgentConfigs(DetectRequest request) { List<SnmpAgentConfig> agentConfigList = new ArrayList<>(); Map<String, String> runTimeAttributes = request.getRuntimeAttributes(); if (hasMultipleAgentConfigs(runTimeAttributes)) { runTimeAttributes.remove(HAS_MULTIPLE_AGENT_CONFIGS); <START> runTimeAttributes.forEach((label, configAsString) -> { <END> agentConfigList.add(SnmpAgentConfig.parseProtocolConfigurationString(configAsString)); }); } return agentConfigList; }</code><technical_language>prefix keys in runTimeAttributes map SNMP_AGENT_CONFIG_ derive agent configs keys matching this prefix? This a bit safer assuming else is agent config</technical_language>

Target:
public List<SnmpAgentConfig> getListOfAgentConfigs(DetectRequest request) { List<SnmpAgentConfig> agentConfigList = new ArrayList<>(); Map<String, String> runTimeAttributes = request.getRuntimeAttributes(); if (useSnmpProfiles() && hasMultipleAgentConfigs(runTimeAttributes)) { runTimeAttributes.forEach((label, configAsString) -> { if (label.contains(AGENT_CONFIG_PREFIX)) { agentConfigList.add(SnmpAgentConfig.parseProtocolConfigurationString(configAsString)); } }); } else if (hasMultipleAgentConfigs(runTimeAttributes)) { runTimeAttributes.forEach((label, configAsString) -> { if (label.contains(AGENT_CONFIG_PREFIX) && label.contains(PROFILE_LABEL_FOR_DEFAULT_CONFIG)) { agentConfigList.add(SnmpAgentConfig.parseProtocolConfigurationString(configAsString)); } }); } return agentConfigList; }
Source:
<code>public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { context.acquireControllerLock(); context.readResource(PathAddress.EMPTY_ADDRESS, false); final String group = getServerGroupName(operation); final boolean blocking = operation.get(BLOCKING).asBoolean(false); <START> final int timeout = operation.get(TIMEOUT).asInt(0); <END> context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { context.getServiceRegistry(true); if (group != null) { final Set<String> waitForServers = new HashSet<String>(); final ModelNode model = Resource.Tools.readModel(context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, true)); for (String server : getServersForGroup(model, group)) { serverInventory.stopServer(server, timeout > 0 ? timeout * 1000 : timeout); waitForServers.add(server); } if (blocking) { serverInventory.awaitServersState(waitForServers, false); } } else { serverInventory.stopServers( timeout > 0 ? timeout * 1000 : timeout, blocking); } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }, Stage.RUNTIME); context.stepCompleted(); }</code><technical_language>AD of timeout for creating operation definition do TIMEOUT.resolveModelAttribute(operation).asInt(); this validation handling of default values apply</technical_language>

Target:
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { context.acquireControllerLock(); context.readResource(PathAddress.EMPTY_ADDRESS, false); final String group = getServerGroupName(operation); final boolean blocking = BLOCKING.resolveModelAttribute(context, operation).asBoolean(); final int timeout = TIMEOUT.resolveModelAttribute(context, operation).asInt(); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { context.getServiceRegistry(true); if (group != null) { final Set<String> waitForServers = new HashSet<String>(); final ModelNode model = Resource.Tools.readModel(context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, true)); for (String server : getServersForGroup(model, group)) { serverInventory.stopServer(server, timeout > 0 ? timeout * 1000 : timeout); waitForServers.add(server); } if (blocking) { serverInventory.awaitServersState(waitForServers, false); } } else { serverInventory.stopServers( timeout > 0 ? timeout * 1000 : timeout, blocking); } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }, Stage.RUNTIME); context.stepCompleted(); }
Source:
<code>public static StringBuffer statusToString(IStatus status, int severities, StringBuffer b) { IStatus[] nestedStatus = status.getChildren(); if (b == null) b = new StringBuffer(); if (severities == -1 || (status.getSeverity() & severities) != 0) { if (b.length() > 0) b.append('\n'); b.append(status.getMessage()); } for (IStatus <START> nestedStatu : <END> nestedStatus) { statusToString(nestedStatu, severities, b); } return b; }</code><technical_language>name needed</technical_language>

Target:
public static StringBuffer statusToString(IStatus status, int severities, StringBuffer b) { IStatus[] nestedStatus = status.getChildren(); if (b == null) b = new StringBuffer(); if (severities == -1 || (status.getSeverity() & severities) != 0) { if (b.length() > 0) b.append('\n'); b.append(status.getMessage()); } for (IStatus s : nestedStatus) { statusToString(s, severities, b); } return b; }
Source:
<code>public String load(IResource resource, Connection connection) throws CoreException { IProject project = resource.getProject(); IPod pod = getPod(resource, project, connection); String imageRef = getImageRef(connection, project, pod); int imageDigestIndex = imageRef.indexOf(DOCKER_IMAGE_DIGEST_IDENTIFIER); if (imageDigestIndex > 0) { String imageDigest = imageRef.substring(imageDigestIndex); IResource imageStreamTag = getImageStreamTag(connection, project, imageRef, imageDigest); return getPodPath(imageStreamTag); } else { String imageMetaData = getImageMetaData(imageRef, project); <START> if (imageMetaData != null) { <END> return getPodPath(imageMetaData); } else { return ""; } } }</code><technical_language>this if/else block weird: #getPodPath returns null if imageMetaData is null. this if/else blocks effectively change semantics return "" instead. this isnt consistent: line 62 this isnt transformed. null is potentially returned #getPodPath is returned is. I doubt this if/else is required. I missing something</technical_language>

Target:
public String load(IResource resource, Connection connection) throws CoreException { IProject project = resource.getProject(); IPod pod = getPod(resource, project, connection); String imageRef = getImageRef(connection, project, pod); int imageDigestIndex = imageRef.indexOf(DOCKER_IMAGE_DIGEST_IDENTIFIER); if (imageDigestIndex > 0) { String imageDigest = imageRef.substring(imageDigestIndex); IResource imageStreamTag = getImageStreamTag(connection, project, imageRef, imageDigest); return getPodPath(imageStreamTag); } else { String imageMetaData = getImageMetaData(imageRef, project); return getPodPath(imageMetaData); } }
Source:
<code>public SerialPortRxTx(String port, SerialPortParameters parameters) { <START> super(port, parameters, DEFAULT_PORT_TIMEOUT); <END> this.logger = LoggerFactory.getLogger(SerialPortRxTx.class); }</code><technical_language>call this(port, parameters, DEFAULT_PORT_TIMEOUT); create logger in constructor</technical_language>

Target:
public SerialPortRxTx(String port, SerialPortParameters parameters) { this(port, parameters, DEFAULT_PORT_TIMEOUT); }
Source:
<code>public void testCleanPayeeACHAccountExtractDetailNoClean() { String bankAccountNumber = "12345"; PayeeACHAccountExtractDetail detail = new PayeeACHAccountExtractDetail(); detail.setBankAccountNumber(bankAccountNumber); payeeACHAccountExtractService.cleanPayeeACHAccountExtractDetail(detail); String expectedBankAccount = bankAccountNumber; <START> assertEquals(expectedBankAccount, detail.getBankAccountNumber()); <END> }</code><technical_language>new unit test methods a lot of duplicated code. I suggest creating a separate helper method do bulk of setup assertion work</technical_language>

Target:
public void testCleanPayeeACHAccountExtractDetailNoClean() { String bankAccountNumber = "12345"; validateCleanPayeeACHAccountExtractDetail(bankAccountNumber, bankAccountNumber); }
Source:
<code>private static List<Field> getAllFields(Class clazz){ List<Field> fields = new ArrayList<>(); fields.addAll(Arrays.asList(clazz.getDeclaredFields())); <START> Class superClass = clazz.getSuperclass(); <END> if (superClass != null) fields.addAll(getAllFields(superClass)); return fields; }</code><technical_language>finals</technical_language>

Target:
private static List<Field> getAllFields(Class clazz){ final List<Field> fields = new ArrayList<>(); fields.addAll(Arrays.asList(clazz.getDeclaredFields())); final Class superClass = clazz.getSuperclass(); if (superClass != null) fields.addAll(getAllFields(superClass)); return fields; }
Source:
<code>public int setTabIndexes(int nextTabIndex) { <START> nextTabIndex++; <END> nameEditor.setTabIndex(nextTabIndex++); cidrEditor.setTabIndex(nextTabIndex++); ipVersionEditor.setTabIndex(nextTabIndex++); gatewayEditor.setTabIndex(nextTabIndex++); return dnsServersEditor.setTabIndexes(nextTabIndex); }</code><technical_language>needed? redundant I91dbedee38d893302f1006c9ce1e58d146ce7cce</technical_language>

Target:
public int setTabIndexes(int nextTabIndex) { nameEditor.setTabIndex(nextTabIndex++); cidrEditor.setTabIndex(nextTabIndex++); ipVersionEditor.setTabIndex(nextTabIndex++); gatewayEditor.setTabIndex(nextTabIndex++); return dnsServersEditor.setTabIndexes(nextTabIndex); }
Source:
<code>Validator createValidator(ConstraintValidatorFactory constraintValidatorFactory, ValueExtractorManager valueExtractorManager, ValidatorFactoryScopedContext validatorFactoryScopedContext, MethodValidationConfiguration methodValidationConfiguration) { ConstraintMetaDataManager constraintMetaDataManager = beanMetaDataManagers.computeIfAbsent( new BeanMetaDataManagerKey( validatorFactoryScopedContext.getParameterNameProvider(), valueExtractorManager, methodValidationConfiguration ), key -> new ConstraintMetaDataManager( constraintHelper, executableHelper, typeResolutionHelper, validatorFactoryScopedContext.getParameterNameProvider(), valueExtractorManager, javaBeanHelper, validationOrderGenerator, methodValidationConfiguration, buildMetaDataProviders(), buildPropertyHolderMetaDataProvider() <START> <END> ) ); return new ValidatorImpl( constraintValidatorFactory, constraintMetaDataManager, valueExtractorManager, constraintValidatorManager, validationOrderGenerator, validatorFactoryScopedContext ); }</code><technical_language>Unnecessary new line</technical_language>

Target:
Validator createValidator(ConstraintValidatorFactory constraintValidatorFactory, ValueExtractorManager valueExtractorManager, ValidatorFactoryScopedContext validatorFactoryScopedContext, MethodValidationConfiguration methodValidationConfiguration) { ConstraintMetaDataManager constraintMetaDataManager = beanMetaDataManagers.computeIfAbsent( new BeanMetaDataManagerKey( validatorFactoryScopedContext.getParameterNameProvider(), valueExtractorManager, methodValidationConfiguration ), key -> new ConstraintMetaDataManager( constraintHelper, executableHelper, typeResolutionHelper, validatorFactoryScopedContext.getParameterNameProvider(), valueExtractorManager, propertyAccessorCreatorProvider, javaBeanHelper, validationOrderGenerator, methodValidationConfiguration, buildMetaDataProviders(), buildPropertyHolderMetaDataProvider() ) ); return new ValidatorImpl( constraintValidatorFactory, constraintMetaDataManager, valueExtractorManager, constraintValidatorManager, validationOrderGenerator, validatorFactoryScopedContext ); }