auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void getResourceClasses(final IDMContext dmc, final DataRequestMonitor<IResourceClass[]> rm) { <START> getExecutor().submit(new DsfRunnable() { <END> @Override public void run() { IGDBControl control = getServicesTracker().getService(IGDBControl.class); control.queueCommand(new MIInfoOs(dmc), new DataRequestMonitor<MIInfoOsInfo>(getExecutor(), rm) { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleCompleted() { rm.setData(getData().getResourceClasses()); super.handleCompleted(); } }); } }); }</code><technical_language>This class is a DSF service called DSF executor. run code submitting executor</technical_language>

Target:
public void getResourceClasses(final IDMContext dmc, final DataRequestMonitor<IResourceClass[]> rm) { IGDBControl control = getServicesTracker().getService(IGDBControl.class); if (control == null) { rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_STATE, "Service not available", null)); return; } control.queueCommand(new MIInfoOs(dmc), new DataRequestMonitor<MIInfoOsInfo>(getExecutor(), rm) { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleSuccess() { rm.setData(getData().getResourceClasses()); rm.done(); } }); }
Source:
<code>private boolean updateTemplates() { for (VmTemplate template : templatesLockedForUpdate) { template.setClusterCompatibilityVersion(getCluster().getCompatibilityVersion()); UpdateVmTemplateParameters parameters = new UpdateVmTemplateParameters(template); parameters.setLockProperties(LockProperties.create(LockProperties.Scope.None)); parameters.setClusterLevelChangeFromVersion(oldCluster.getCompatibilityVersion()); updateRngDeviceIfNecessary(template.getId(), template.getCustomCompatibilityVersion(), parameters); if (!parameters.isUpdateRngDevice()) { continue; } final VdcReturnValueBase result = runInternalAction( VdcActionType.UpdateVmTemplate, parameters, cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { List<String> params = new ArrayList<>(); params.add("$action Update"); params.add("$type Template"); params.add(parseErrorMessage(result.getValidationMessages())); List<String> messages = Backend.getInstance().getErrorsTranslator().translateErrorText(params); <START> failedUpgradeVms.put(template.getName(), <END> messages.get(0)); } } return true; }</code><technical_language>rename failedUpgradeEntities? more generic is templates vms, vms</technical_language>

Target:
private boolean updateTemplates() { for (VmTemplate template : templatesLockedForUpdate) { template.setClusterCompatibilityVersion(getCluster().getCompatibilityVersion()); UpdateVmTemplateParameters parameters = new UpdateVmTemplateParameters(template); parameters.setLockProperties(LockProperties.create(LockProperties.Scope.None)); parameters.setClusterLevelChangeFromVersion(oldCluster.getCompatibilityVersion()); updateRngDeviceIfNecessary(template.getId(), template.getCustomCompatibilityVersion(), parameters); if (!parameters.isUpdateRngDevice()) { continue; } final VdcReturnValueBase result = runInternalAction( VdcActionType.UpdateVmTemplate, parameters, cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { List<String> params = new ArrayList<>(); params.add("$action Update"); params.add("$type Template"); params.add(parseErrorMessage(result.getValidationMessages())); List<String> messages = Backend.getInstance().getErrorsTranslator().translateErrorText(params); failedUpgradeEntities.put(template.getName(), getFailedMessage(messages)); } } return true; }
Source:
<code>public void close() { try { LOG.info("Shutting down supervisor {}", getId()); <START> metricsReporters.close(); <END> this.active = false; heartbeatTimer.close(); workerHeartbeatTimer.close(); eventTimer.close(); if (eventManager != null) { eventManager.close(); } if (readState != null) { readState.close(); } asyncLocalizer.close(); getStormClusterState().disconnect(); if (thriftServer != null) { this.thriftServer.stop(); } } catch (Exception e) { LOG.error("Error Shutting down", e); } }</code><technical_language>Nit: This a null check, metricsReporters guaranteed non-null</technical_language>

Target:
public void close() { try { LOG.info("Shutting down supervisor {}", getId()); if (metricsReporters != null) { metricsReporters.close(); } this.active = false; heartbeatTimer.close(); workerHeartbeatTimer.close(); eventTimer.close(); if (eventManager != null) { eventManager.close(); } if (readState != null) { readState.close(); } asyncLocalizer.close(); getStormClusterState().disconnect(); if (thriftServer != null) { this.thriftServer.stop(); } } catch (Exception e) { LOG.error("Error Shutting down", e); } }
Source:
<code>protected void runInContext() { Connect conn = null; try { conn = LibvirtConnection.getConnection(); diskStatusMap.clear(); File[] iscsiVolumes = new File(ISCSI_PATH_PREFIX).listFiles(); if (iscsiVolumes == null || iscsiVolumes.length == 0) { s_logger.debug("No iscsi sessions found for cleanup"); return; } for( File v : iscsiVolumes) { if (isIscsiDisk(v.getAbsolutePath())) { s_logger.debug("found iscsi disk by cleanup thread, marking inactive:" + v.getAbsolutePath()); diskStatusMap.put(v.getAbsolutePath(), false); } } int[] domains = conn.listDomains(); s_logger.debug(String.format("found %d domains", domains.length)); for (int domId : domains) { Domain dm = conn.domainLookupByID(domId); final String domXml = dm.getXMLDesc(0); final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); parser.parseDomainXML(domXml); List<LibvirtVMDef.DiskDef> disks = parser.getDisks(); for (final LibvirtVMDef.DiskDef disk : disks) { if (diskStatusMap.containsKey(disk.getDiskPath())) { diskStatusMap.put(disk.getDiskPath(), true); <START> s_logger.debug("active disk found by cleanup thread" + disk.getDiskPath()); <END> } } } for (String diskPath : diskStatusMap.keySet()) { if (!diskStatusMap.get(diskPath)) { if (Files.exists(Paths.get(diskPath))) { try { s_logger.info("Cleaning up disk " + diskPath); iscsiStorageAdaptor.disconnectPhysicalDiskByPath(diskPath); } catch (Exception e) { s_logger.warn("[ignored] Error cleaning up " + diskPath, e); } } } } } catch (LibvirtException e) { s_logger.warn("[ignored] Error trying to cleanup ", e); } }</code><technical_language>space needed in log message path</technical_language>

Target:
protected void runInContext() { Connect conn = null; try { conn = LibvirtConnection.getConnection(); File[] iscsiVolumes = new File(ISCSI_PATH_PREFIX).listFiles(); if (iscsiVolumes == null || iscsiVolumes.length == 0) { s_logger.debug("No iscsi sessions found for cleanup"); return; } initializeDiskStatusMap(iscsiVolumes); updateDiskStatusMapWithInactiveIscsiSessions(conn); disconnectInactiveSessions(); } catch (LibvirtException e) { s_logger.warn("[ignored] Error trying to cleanup ", e); } }
Source:
<code>protected SimpleKeyManagerFactory(String name) { super(CURRENT_SPI.get(), PROVIDER, name); CURRENT_SPI.get().init(this); CURRENT_SPI.remove(); if (name == null) { throw new NullPointerException("name"); <START> } <END> }</code><technical_language>remove this check part of calling super. (see above)</technical_language>

Target:
protected SimpleKeyManagerFactory(String name) { super(CURRENT_SPI.get(), PROVIDER, ObjectUtil.checkNotNull(name, "name")); CURRENT_SPI.get().init(this); CURRENT_SPI.remove(); }
Source:
<code>@Override public boolean contains(Object o) { if (o == null) <START> throw new UnsupportedOperationException("Null values are not supported!"); <END> return contains((int)o); }</code><technical_language>I get it, return "false"</technical_language>

Target:
@Override public boolean contains(Object o) { if (o == null) throw new NullPointerException("Null values are not supported!"); return contains((int)o); }
Source:
<code><START> public static String callProcOverJSONRaw(String varString, final int expectedCode) throws Exception { <END> URI jsonAPIURI = URI.create("http://localhost:8095/api/1.0/"); try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpPost post = new HttpPost(jsonAPIURI); RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build(); post.setProtocolVersion(HttpVersion.HTTP_1_1); post.setConfig(rc); post.setEntity(new StringEntity(varString, ContentType.APPLICATION_FORM_URLENCODED)); ResponseHandler<String> rh = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); assertEquals(expectedCode, status); if ((status >= 200 && status < 300) || status == 400) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } return null; } }; return httpclient.execute(post,rh); } }</code><technical_language>behavior 1.0 1.1 build test works in versions? repeat this protocol version</technical_language>

Target:
public static String callProcOverJSONRaw(String varString, final int expectedCode) throws Exception { URI jsonAPIURI = URI.create("http://localhost:8095/api/1.0/"); try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpPost post = new HttpPost(jsonAPIURI); RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build(); post.setProtocolVersion(HttpVersion.HTTP_1_1); post.setConfig(rc); post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded)); ResponseHandler<String> rh = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); assertEquals(expectedCode, status); if ((status >= 200 && status < 300) || status == 400) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } return null; } }; return httpclient.execute(post,rh); } }
Source:
<code>private int findUnusedPort() { synchronized (processLock) { int port = config.getStartPort(); int maxPortSoFar = -1; for (ProcessHolder processHolder : processes) { if (processHolder.port > maxPortSoFar) { maxPortSoFar = processHolder.port; } if (processHolder.port == port) { port = maxPortSoFar + 1; <START> } <END> } return port; } }</code><technical_language>I verify port is unused, hoping incrementing give unused port</technical_language>

Target:
private int findUnusedPort() { synchronized (tasks) { int port = config.getStartPort(); int maxPortSoFar = -1; for (TaskInfo taskInfo : tasks.values()) { if (taskInfo.processHolder != null) { if (taskInfo.processHolder.port > maxPortSoFar) { maxPortSoFar = taskInfo.processHolder.port; } if (taskInfo.processHolder.port == port) { port = maxPortSoFar + 1; } } } return port; } }
Source:
<code>public static <T> T newInstance(Class<T> theClass, Configuration conf, <START> Class<?>[] argTypes, Object ... values) { <END> T result; try { Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass); if (meth == null) { meth = theClass.getDeclaredConstructor(argTypes); meth.setAccessible(true); CONSTRUCTOR_CACHE.put(theClass, meth); } result = meth.newInstance(values); } catch (Exception e) { throw new RuntimeException(e); } setConf(result, conf); return result; }</code><technical_language>more do is checking argTypes.length == values.length, throw IllegalArgumentException like: "1 parameters required 0 arguments provided". This more informative default exception message</technical_language>

Target:
public static <T> T newInstance(Class<T> theClass, Configuration conf, Class<?>[] argTypes, Object ... values) { T result; if (argTypes.length != values.length) { throw new IllegalArgumentException(argTypes.length + " parameters are required but " + values.length + " arguments are provided"); } try { Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass); if (meth == null) { meth = theClass.getDeclaredConstructor(argTypes); meth.setAccessible(true); CONSTRUCTOR_CACHE.put(theClass, meth); } result = meth.newInstance(values); } catch (Exception e) { throw new RuntimeException(e); } setConf(result, conf); return result; }
Source:
<code>public String getColumnText(Object element, int columnIndex) { if (element instanceof TimeGraphEntry) { TimeGraphEntry entry = (TimeGraphEntry) element; ITimeGraphState function = fFunctions.get(entry.getModel().getId()); <START> if (columnIndex == 0 && function != null) { <END> return function.getLabel(); } else if (columnIndex == 0 && ((CallStackEntryModel) entry.getModel()).getStackLevel() <= 0) { return entry.getName(); } else if (columnIndex == 1 && function != null) { return Integer.toString(((CallStackEntryModel) entry.getModel()).getStackLevel()); } else if (columnIndex == 2 && function != null) { return TmfTimestampFormat.getDefaulTimeFormat().format(function.getStartTime()); } else if (columnIndex == 3 && function != null) { return TmfTimestampFormat.getDefaulTimeFormat().format(function.getStartTime() + function.getDuration()); } else if (columnIndex == 4 && function != null) { return TmfTimestampFormat.getDefaulIntervalFormat().format(function.getDuration()); } } return ""; }</code><technical_language>return if function == null</technical_language>

Target:
public String getColumnText(Object element, int columnIndex) { if (element instanceof TimeGraphEntry) { TimeGraphEntry entry = (TimeGraphEntry) element; ITimeGraphEntryModel model = entry.getModel(); ITimeGraphState function = fFunctions.get(model.getId()); if (columnIndex == 0 && function != null) { return function.getLabel(); } else if (columnIndex == 0 && (!(model instanceof CallStackEntryModel) || (model instanceof CallStackEntryModel && ((CallStackEntryModel) model).getStackLevel() <= 0))) { return entry.getName(); } else if (columnIndex == 1 && function != null && model instanceof CallStackEntryModel) { return Integer.toString(((CallStackEntryModel) model).getStackLevel()); } else if (columnIndex == 2 && function != null) { return TmfTimestampFormat.getDefaulTimeFormat().format(function.getStartTime()); } else if (columnIndex == 3 && function != null) { return TmfTimestampFormat.getDefaulTimeFormat().format(function.getStartTime() + function.getDuration()); } else if (columnIndex == 4 && function != null) { return TmfTimestampFormat.getDefaulIntervalFormat().format(function.getDuration()); } } return ""; }
Source:
<code>private void logMissingTranslation(String filePath, String fileName) { log(0, MSG_KEY_MISSING_TRANSLATION_FILE, fileName); fireErrors(filePath); <START> } <END></code><technical_language>Issue is #5057</technical_language>

Target:
private void logMissingTranslation(String filePath, String fileName) { log(0, MSG_KEY_MISSING_TRANSLATION_FILE, fileName); fireErrors(filePath); getMessageDispatcher().fireFileFinished(filePath); }
Source:
<code>private Set<ObjectId> listRefLogObjects(Ref ref, long minTime) throws IOException { ReflogReader reflogReader = repo.getReflogReader(ref.getName()); <START> if (reflogReader == null) { <END> throw new IOException(); } List<ReflogEntry> rlEntries = reflogReader .getReverseEntries(); if (rlEntries == null || rlEntries.isEmpty()) return Collections.<ObjectId> emptySet(); Set<ObjectId> ret = new HashSet<ObjectId>(); for (ReflogEntry e : rlEntries) { if (e.getWho().getWhen().getTime() < minTime) break; ObjectId newId = e.getNewId(); if (newId != null && !ObjectId.zeroId().equals(newId)) ret.add(newId); ObjectId oldId = e.getOldId(); if (oldId != null && !ObjectId.zeroId().equals(oldId)) ret.add(oldId); } return ret; }</code><technical_language>This happen if ref disappeared caller resolved it. I is return Collections.emptySet() in case</technical_language>

Target:
private Set<ObjectId> listRefLogObjects(Ref ref, long minTime) throws IOException { ReflogReader reflogReader = repo.getReflogReader(ref.getName()); if (reflogReader == null) { return Collections.emptySet(); } List<ReflogEntry> rlEntries = reflogReader .getReverseEntries(); if (rlEntries == null || rlEntries.isEmpty()) return Collections.<ObjectId> emptySet(); Set<ObjectId> ret = new HashSet<ObjectId>(); for (ReflogEntry e : rlEntries) { if (e.getWho().getWhen().getTime() < minTime) break; ObjectId newId = e.getNewId(); if (newId != null && !ObjectId.zeroId().equals(newId)) ret.add(newId); ObjectId oldId = e.getOldId(); if (oldId != null && !ObjectId.zeroId().equals(oldId)) ret.add(oldId); } return ret; }
Source:
<code>protected final void configure() { if (alreadyBound) { if (!boundType.equals(getClass())) { throw new RuntimeException("You are trying to use more than one DispatchAsync implementation. " + boundType.getName() + " was already installed."); } } else { alreadyBound = true; boundType = getClass(); bind(ClientActionHandlerRegistry.class).to(builder.clientActionHandlerRegistryType).asEagerSingleton(); bind(ExceptionHandler.class).to(builder.exceptionHandlerType); bind(SecurityCookieAccessor.class).to(builder.sessionAccessorType); <START> bind(DispatchHooks.class).to(builder.getDispatchHooks()).in(Singleton.class); <END> configureDispatch(); } }</code><technical_language>getDispatchHooks method removed direct access private member : builder.dispatchHooks used, for consistency</technical_language>

Target:
protected final void configure() { if (alreadyBound) { if (!boundType.equals(getClass())) { throw new RuntimeException("You are trying to use more than one DispatchAsync implementation. " + boundType.getName() + " was already installed."); } } else { alreadyBound = true; boundType = getClass(); bind(ClientActionHandlerRegistry.class).to(builder.clientActionHandlerRegistryType).asEagerSingleton(); bind(ExceptionHandler.class).to(builder.exceptionHandlerType); bind(SecurityCookieAccessor.class).to(builder.sessionAccessorType); bind(DispatchHooks.class).to(builder.dispatchHooks).in(Singleton.class); configureDispatch(); } }
Source:
<code><START> public void copyPreviousWalFiles(List<PreviousWALDetails> parentWals, Set<PreviousWALDetails> alreadyCopiedWals) <END> { try { PreviousWALDetails parentWal = parentWals.iterator().next(); for (long i = parentWal.getStartPosition().fileId; i <= parentWal.getEndPosition().fileId; i++) { DataInputStream in = bfs.getInputStream(parentWal.getWalKey(), WAL_FILE_PREFIX + i); DataOutputStream out = bfs.getOutputStream(walKey, WAL_FILE_PREFIX + i); IOUtils.copyLarge(in, out); in.close(); out.close(); } alreadyCopiedWals.add(parentWal); parentWals.clear(); } catch (IOException e) { DTThrowable.wrapIfChecked(e); } }</code><technical_language>need public</technical_language>

Target:
public void copyPreviousWalFiles(List<PreviousWALDetails> parentWals, Set<PreviousWALDetails> alreadyCopiedWals) { try { PreviousWALDetails parentWal = parentWals.iterator().next(); for (long i = parentWal.getStartPosition().fileId; i <= parentWal.getEndPosition().fileId; i++) { DataInputStream in = bfs.getInputStream(parentWal.getWalKey(), WAL_FILE_PREFIX + i); DataOutputStream out = bfs.getOutputStream(walKey, WAL_FILE_PREFIX + i); IOUtils.copyLarge(in, out); in.close(); out.close(); } } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
<code>public void bridgeDeleteVxLanPort(UUID bridgeId, IPv4Addr mgmtIp) throws SerializationException, StateAccessException { Bridge b = bridgesGet(bridgeId); if (b == null || b.getVxLanPortIds() == null) { return; } for (UUID portId : b.getVxLanPortIds()) { VxLanPort p = (VxLanPort)portsGet(portId); <START> if (p.getMgmtIpAddr().equals(mgmtIp)) { <END> bridgeDeleteVxLanPort(p); return; } } }</code><technical_language>Check p is null</technical_language>

Target:
public void bridgeDeleteVxLanPort(UUID bridgeId, IPv4Addr mgmtIp) throws SerializationException, StateAccessException { Bridge b = bridgesGet(bridgeId); if (b == null) { return; } for (UUID portId : b.getVxLanPortIds()) { VxLanPort p = (VxLanPort)portsGet(portId); if (p.getMgmtIpAddr().equals(mgmtIp)) { bridgeDeleteVxLanPort(p); return; } } }
Source:
<code><START> protected File getFolder(final String folderPath) { <END> return getFolder(new File(folderPath)); }</code><technical_language>Is a reason protected</technical_language>

Target:
private File getFolder(final String folderPath) { return getFolder(new File(folderPath)); }
Source:
<code>public void execute(IProgressMonitor monitor) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor actMonitor) throws CoreException { if (commitAll) commitAll(); else if (amending || commitFileList != null && commitFileList.size() > 0 || commitIndex) { <START> SubMonitor progress = SubMonitor.convert(actMonitor, <END> CoreText.CommitOperation_PerformingCommit, 1); addUntracked(); commit(); progress.worked(1); } else if (commitWorkingDirChanges) { } else { } } }; ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor); }</code><technical_language>one-argument version of "convert" call setTaskName. monitors (including SubMonitor) ignore string argument convert(...) beginTask(...) default. setTaskName is treated differently is shown user. is need allocate consume ticks this monitor entire is consumed parent. Remove local variable change to: SubMonitor.convert(actMonitor).setTaskName(CoreText.CommitOperation_PerformingCommit);</technical_language>

Target:
public void execute(IProgressMonitor monitor) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor actMonitor) throws CoreException { if (commitAll) commitAll(); else if (amending || commitFileList != null && commitFileList.size() > 0 || commitIndex) { SubMonitor progress = SubMonitor.convert(actMonitor); progress.setTaskName( CoreText.CommitOperation_PerformingCommit); addUntracked(); commit(); } else if (commitWorkingDirChanges) { } else { } } }; ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor); }
Source:
<code>public void marshal(ITypeMarshalBuffer buffer) throws CoreException { short firstBytes = ITypeMarshalBuffer.FUNCTION_TYPE; int len= parameters.length & 0xffff; int codedLen= len * ITypeMarshalBuffer.FLAG1; <START> if (codedLen < ITypeMarshalBuffer.FLAG4) { <END> firstBytes |= codedLen; buffer.putShort(firstBytes); } else { firstBytes |= ITypeMarshalBuffer.FLAG4; buffer.putShort(firstBytes); buffer.putInt(len); } buffer.marshalType(returnType); for (int i = 0; i < len; i++) { buffer.marshalType(parameters[i]); } }</code><technical_language>This check stringent is more room is in firstBytes</technical_language>

Target:
public void marshal(ITypeMarshalBuffer buffer) throws CoreException { short firstBytes = ITypeMarshalBuffer.FUNCTION_TYPE; int len= parameters.length & 0xffff; int codedLen= len * ITypeMarshalBuffer.FIRST_FLAG; if (codedLen < ITypeMarshalBuffer.LAST_FLAG) { firstBytes |= codedLen; buffer.putShort(firstBytes); } else { firstBytes |= ITypeMarshalBuffer.LAST_FLAG; buffer.putShort(firstBytes); buffer.putInt(len); } buffer.marshalType(returnType); for (int i = 0; i < len; i++) { buffer.marshalType(parameters[i]); } }
Source:
<code>public void runServer() throws Exception { <START> TraceUtil.enableServerTraces(getHostname(), applicationName, context.getConfiguration()); <END> final AtomicReference<Throwable> err = new AtomicReference<>(); Thread service = new Thread(this, applicationName); service.setUncaughtExceptionHandler((thread, exception) -> { err.set(exception); }); service.start(); service.join(); Throwable thrown = err.get(); if (thrown != null) { if (thrown instanceof Error) { throw (Error) thrown; } if (thrown instanceof Exception) { throw (Exception) thrown; } throw new RuntimeException("Weird throwable type thrown", thrown); } }</code><technical_language>fine... long remaining body of constructor try trace anything. Also, instead of moving this, try setting of hostname more standardized moving AbstractServer constructor itself</technical_language>

Target:
public void runServer() throws Exception { final AtomicReference<Throwable> err = new AtomicReference<>(); Thread service = new Thread(this, applicationName); service.setUncaughtExceptionHandler((thread, exception) -> { err.set(exception); }); service.start(); service.join(); Throwable thrown = err.get(); if (thrown != null) { if (thrown instanceof Error) { throw (Error) thrown; } if (thrown instanceof Exception) { throw (Exception) thrown; } throw new RuntimeException("Weird throwable type thrown", thrown); } }
Source:
<code>MigrationZipFile newZipFileFor(Path exportDirectory) { Validate.notNull(exportDirectory, "invalid null export file"); try { List<Path> exportFilePaths = Files.find( exportDirectory, 1, <START> (path, basicFileAttributes) -> <END> path.toFile() .getName() .matches( productBranding + "-.*" + ConfigurationMigrationManager.EXPORT_EXTENSION)) .collect(Collectors.toList()); switch (exportFilePaths.size()) { case 1: return new MigrationZipFile(exportFilePaths.get(0)); case 0: throw new MigrationException(Messages.IMPORT_FILE_MISSING_ERROR, exportDirectory, ""); default: throw new MigrationException(Messages.IMPORT_FILE_MULTIPLE_ERROR, exportDirectory); } } catch (FileNotFoundException e) { throw new MigrationException(Messages.IMPORT_FILE_MISSING_ERROR, exportDirectory, e); } catch (SecurityException | IOException e) { throw new MigrationException(Messages.IMPORT_FILE_OPEN_ERROR, exportDirectory, e); } }</code><technical_language>moved a private method find() more readable</technical_language>

Target:
MigrationZipFile newZipFileFor(Path exportDirectory) { Validate.notNull(exportDirectory, "invalid null export file"); try { List<Path> exportFilePaths = Files.find(exportDirectory, 1, this::exportFileWithBrandingName) .collect(Collectors.toList()); switch (exportFilePaths.size()) { case 1: return new MigrationZipFile(exportFilePaths.get(0)); case 0: throw new MigrationException(Messages.IMPORT_FILE_MISSING_ERROR, exportDirectory, ""); default: throw new MigrationException(Messages.IMPORT_FILE_MULTIPLE_ERROR, exportDirectory); } } catch (FileNotFoundException e) { throw new MigrationException(Messages.IMPORT_FILE_MISSING_ERROR, exportDirectory, e); } catch (SecurityException | IOException e) { throw new MigrationException(Messages.IMPORT_FILE_OPEN_ERROR, exportDirectory, e); } }
Source:
<code>public static CharSequence getDescription(AccessibilityNodeInfoCompat node, View view) { CharSequence contentDescription = node.getContentDescription(); CharSequence nodeText = node.getText(); boolean hasNodeText = !TextUtils.isEmpty(nodeText); boolean isEditText = view instanceof EditText; if (!TextUtils.isEmpty(contentDescription) && (!isEditText || !hasNodeText)) { return contentDescription; } if (hasNodeText) { return nodeText; } if (view instanceof ViewGroup) { <START> String concatChildDescription = ""; <END> String separator = ", "; ViewGroup viewGroup = (ViewGroup) view; for (int i = 0, count = viewGroup.getChildCount(); i < count; i++) { final View child = viewGroup.getChildAt(i); AccessibilityNodeInfoCompat childNodeInfo = AccessibilityNodeInfoCompat.obtain(); ViewCompat.onInitializeAccessibilityNodeInfo(child, childNodeInfo); CharSequence childNodeDescription = null; if (AccessibilityUtil.isSpeakingNode(childNodeInfo, child)) { childNodeDescription = getDescription(childNodeInfo, child); } if (!TextUtils.isEmpty(childNodeDescription)) { if (!TextUtils.isEmpty(concatChildDescription)) { concatChildDescription += separator; } concatChildDescription += childNodeDescription; } childNodeInfo.recycle(); } return !TextUtils.isEmpty(concatChildDescription) ? concatChildDescription : null; } return null; }</code><technical_language>a StringBuilder here. += a String in a loop is a classic performance anti-pattern for a language/runtime immutable strings (like Java, C#/VB, etc.)</technical_language>

Target:
public static CharSequence getDescription(AccessibilityNodeInfoCompat node, View view) { CharSequence contentDescription = node.getContentDescription(); CharSequence nodeText = node.getText(); boolean hasNodeText = !TextUtils.isEmpty(nodeText); boolean isEditText = view instanceof EditText; if (!TextUtils.isEmpty(contentDescription) && (!isEditText || !hasNodeText)) { return contentDescription; } if (hasNodeText) { return nodeText; } if (view instanceof ViewGroup) { final StringBuilder concatChildDescription = new StringBuilder(); final String separator = ", "; ViewGroup viewGroup = (ViewGroup) view; for (int i = 0, count = viewGroup.getChildCount(); i < count; i++) { final View child = viewGroup.getChildAt(i); AccessibilityNodeInfoCompat childNodeInfo = AccessibilityNodeInfoCompat.obtain(); ViewCompat.onInitializeAccessibilityNodeInfo(child, childNodeInfo); CharSequence childNodeDescription = null; if (AccessibilityUtil.isSpeakingNode(childNodeInfo, child)) { childNodeDescription = getDescription(childNodeInfo, child); } if (!TextUtils.isEmpty(childNodeDescription)) { if (concatChildDescription.length() > 0) { concatChildDescription.append(separator); } concatChildDescription.append(childNodeDescription); } childNodeInfo.recycle(); } return concatChildDescription.length() > 0 ? concatChildDescription.toString() : null; } return null; }
Source:
<code>public void testMsgNotifHeartbeat_requestModel_nonRoot() throws Exception { TestApplication app = new TestApplication(); app.setDirectory( this.folder.newFolder()); ManagedApplication ma = new ManagedApplication( app ); this.managerWrapper.getNameToManagedApplication().put( app.getName(), ma ); <START> String targetId = this.manager.targetsMngr().createTarget( "id: tid2\nhandler: h" ); <END> this.manager.targetsMngr().associateTargetWith( targetId, app, null ); File dir = new File( this.manager.configurationMngr().getWorkingDirectory(), ConfigurationUtils.TARGETS + "/" + targetId ); Utils.createDirectory( dir ); Utils.writeStringInto( "#!/bin/bash\necho Bonjour le monde cruel > toto.txt", new File( dir, Constants.TARGET_SCRIPT_FILE_NAME )); Assert.assertNotNull( this.manager.targetsMngr().findScriptResources(targetId) ); this.msgClient.allSentMessages.clear(); Assert.assertEquals( 0, this.msgClient.allSentMessages.size()); MsgNotifHeartbeat msg = new MsgNotifHeartbeat( app.getName(), app.getWar(), "192.168.1.45" ); msg.setModelRequired( true ); this.managerWrapper.getMessagingClient().getMessageProcessor().storeMessage( msg ); Thread.sleep( 100 ); Assert.assertEquals( 0, this.msgClient.allSentMessages.size()); app.getWar().getComponent().installerName( Constants.TARGET_INSTALLER ); this.managerWrapper.getMessagingClient().getMessageProcessor().storeMessage( msg ); Thread.sleep( 100 ); Assert.assertEquals( 1, this.msgClient.allSentMessages.size()); Message sentMessage = this.msgClient.allSentMessages.get( 0 ); Assert.assertEquals( MsgCmdSetScopedInstance.class, sentMessage.getClass()); Assert.assertNotNull(((MsgCmdSetScopedInstance) sentMessage).getScopedInstance()); }</code><technical_language>A HUGE no. Do modify this test. Write a new one. This test prevents regressions</technical_language>

Target:
public void testMsgNotifHeartbeat_requestModel_nonRoot() throws Exception { TestApplication app = new TestApplication(); app.setDirectory( this.folder.newFolder()); ManagedApplication ma = new ManagedApplication( app ); this.managerWrapper.getNameToManagedApplication().put( app.getName(), ma ); this.msgClient.allSentMessages.clear(); Assert.assertEquals( 0, this.msgClient.allSentMessages.size()); MsgNotifHeartbeat msg = new MsgNotifHeartbeat( app.getName(), app.getWar(), "192.168.1.45" ); msg.setModelRequired( true ); this.managerWrapper.getMessagingClient().getMessageProcessor().storeMessage( msg ); Thread.sleep( 100 ); Assert.assertEquals( 0, this.msgClient.allSentMessages.size()); app.getWar().getComponent().installerName( Constants.TARGET_INSTALLER ); this.managerWrapper.getMessagingClient().getMessageProcessor().storeMessage( msg ); Thread.sleep( 100 ); Assert.assertEquals( 1, this.msgClient.allSentMessages.size()); Message sentMessage = this.msgClient.allSentMessages.get( 0 ); Assert.assertEquals( MsgCmdSetScopedInstance.class, sentMessage.getClass()); Assert.assertNotNull(((MsgCmdSetScopedInstance) sentMessage).getScopedInstance()); }
Source:
<code><START> protected void prepareOnAffectedNodes(TxInvocationContext<?> ctx, PrepareCommand command, Collection<Address> recipients, boolean ignored) { <END> try { Map<Address, Response> resps = rpcManager.invokeRemotely(recipients, command, rpcManager.getDefaultRpcOptions(true, DeliverOrder.NONE)); CacheTransaction ct = ctx.getCacheTransaction(); for (Response r : resps.values()) readVersionsFromResponse(r, ct); } finally { transactionRemotelyPrepared(ctx); } }</code><technical_language>users of TxInvocationContext ignore type parameter, ignore too. TBH context a type parameter, I removed I need add cast compile</technical_language>

Target:
protected void prepareOnAffectedNodes(TxInvocationContext<?> ctx, PrepareCommand command, Collection<Address> recipients, boolean ignored) { try { Map<Address, Response> resps = rpcManager.invokeRemotely(recipients, command, rpcManager.getDefaultRpcOptions(true, DeliverOrder.NONE)); checkTxCommandResponses(resps); CacheTransaction ct = ctx.getCacheTransaction(); for (Response r : resps.values()) readVersionsFromResponse(r, ct); } finally { transactionRemotelyPrepared(ctx); } }
Source:
<code>public Entry[] list(File directory, FileModeStrategy fileModeStrategy) { List<Entry> result = new ArrayList<>(); FS fs = this; try { Files.walkFileTree(directory.toPath(), EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { File f = file.toFile(); FS.Attributes attributes = new FS.Attributes(fs, f, true, attrs.isDirectory(), <START> fs.supportsExecute() ? <END> f.canExecute() : false, attrs.isSymbolicLink(), attrs.isRegularFile(), attrs.creationTime().toMillis(), attrs.lastModifiedTime().toMillis(), attrs.size()); result.add(new FileEntry(f, fs, attributes, fileModeStrategy)); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); } catch (IOException e) { } if (result.isEmpty()) { return NO_ENTRIES; } return result.toArray(new Entry[result.size()]); }</code><technical_language>This is constant, set loop</technical_language>

Target:
public Entry[] list(File directory, FileModeStrategy fileModeStrategy) { List<Entry> result = new ArrayList<>(); FS fs = this; boolean checkExecutable = fs.supportsExecute(); try { Files.walkFileTree(directory.toPath(), EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { File f = file.toFile(); FS.Attributes attributes = new FS.Attributes(fs, f, true, attrs.isDirectory(), checkExecutable && f.canExecute(), attrs.isSymbolicLink(), attrs.isRegularFile(), attrs.creationTime().toMillis(), attrs.lastModifiedTime().toMillis(), attrs.size()); result.add(new FileEntry(f, fs, attributes, fileModeStrategy)); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); } catch (IOException e) { } if (result.isEmpty()) { return NO_ENTRIES; } return result.toArray(new Entry[result.size()]); }
Source:
<code>private void doGetHeadDeleteTest(int contentSize, boolean multipartPost) throws Exception { ByteBuffer content = ByteBuffer.wrap(TestUtils.getRandomBytes(contentSize)); String serviceId = "getHeadDeleteServiceID"; String contentType = "application/octet-stream"; String ownerId = "getHeadDeleteOwnerID"; HttpHeaders headers = new DefaultHttpHeaders(); setAmbryHeadersForPut(headers, 7200, false, serviceId, contentType, ownerId); <START> headers.set(HttpHeaderNames.CONTENT_LENGTH, content.capacity()); <END> String blobId; byte[] usermetadata = null; if (multipartPost) { usermetadata = UtilsTest.getRandomString(32).getBytes(); } else { headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key1", "value1"); headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key2", "value2"); } blobId = putBlob(headers, content, usermetadata); headers.add(RestUtils.Headers.BLOB_SIZE, (long) content.capacity()); getBlobAndVerify(blobId, null, headers, content); getNotModifiedBlobAndVerify(blobId, null, false); getUserMetadataAndVerify(blobId, null, headers, usermetadata); getBlobInfoAndVerify(blobId, null, headers, usermetadata); getHeadAndVerify(blobId, null, headers); deleteBlobAndVerify(blobId); verifyOperationsAfterDelete(blobId, headers, content, usermetadata); }</code><technical_language>remember content length is set this want remove</technical_language>

Target:
private void doGetHeadDeleteTest(int contentSize, boolean multipartPost) throws Exception { ByteBuffer content = ByteBuffer.wrap(TestUtils.getRandomBytes(contentSize)); String serviceId = "getHeadDeleteServiceID"; String contentType = "application/octet-stream"; String ownerId = "getHeadDeleteOwnerID"; HttpHeaders headers = new DefaultHttpHeaders(); setAmbryHeadersForPut(headers, 7200, false, serviceId, contentType, ownerId); String blobId; byte[] usermetadata = null; if (multipartPost) { usermetadata = UtilsTest.getRandomString(32).getBytes(); } else { headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key1", "value1"); headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key2", "value2"); } blobId = putBlob(headers, content, usermetadata); headers.add(RestUtils.Headers.BLOB_SIZE, (long) content.capacity()); getBlobAndVerify(blobId, null, headers, content); getNotModifiedBlobAndVerify(blobId, null, false); getUserMetadataAndVerify(blobId, null, headers, usermetadata); getBlobInfoAndVerify(blobId, null, headers, usermetadata); getHeadAndVerify(blobId, null, headers); deleteBlobAndVerify(blobId); verifyOperationsAfterDelete(blobId, headers, content, usermetadata); }
Source:
<code>public void showDialogueBox(Allergy allergy) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext()); <START> alertDialogBuilder.setTitle(R.string.delete_allergy_title); <END> alertDialogBuilder .setMessage(R.string.delete_allergy_description) .setCancelable(false) .setPositiveButton(R.string.mark_patient_deceased_proceed, (dialog, id) -> { dialog.cancel(); ((PatientDashboardAllergyPresenter) mPresenter).deleteAllergy(allergy.getUuid()); }) .setNegativeButton(R.string.dialog_button_cancel, (dialog, id) -> { alertDialog.cancel(); }); alertDialog = alertDialogBuilder.create(); alertDialog.show(); }</code><technical_language>title show allergen. E.g. "Delete 'ACE Inhibitors'?"</technical_language>

Target:
public void showDialogueBox(Allergy allergy) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext()); alertDialogBuilder.setTitle(getString(R.string.delete_allergy_title, allergy.getAllergen().getCodedAllergen().getDisplay())); alertDialogBuilder .setMessage(R.string.delete_allergy_description) .setCancelable(false) .setPositiveButton(R.string.mark_patient_deceased_proceed, (dialog, id) -> { dialog.cancel(); ((PatientDashboardAllergyPresenter) mPresenter).deleteAllergy(allergy.getUuid()); }) .setNegativeButton(R.string.dialog_button_cancel, (dialog, id) -> { alertDialog.cancel(); }); alertDialog = alertDialogBuilder.create(); alertDialog.show(); }
Source:
<code>protected void executeQueryCommand() { Map<KeyValuePairCompat<ConfigurationValues, String>, Object> configValuesMap = new HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object>(); <START> createConfigValuesSet(); <END> for (ConfigurationValues configValue : ConfigurationValues.values()) { if (!shouldReturnValue(configValue) || !configValuesSet.contains(configValue.toString())) { continue; } List<String> versions = new ArrayList<String>(); versions.add(Config.DefaultConfigurationVersion); for (Version version : Version.ALL) { versions.add(version.toString()); } for (String version : versions) { KeyValuePairCompat<ConfigurationValues, String> key = new KeyValuePairCompat<ConfigurationValues, String>(configValue, version); Object value = Config.<Object> GetValue(ConfigValues.valueOf(configValue.toString()), version); configValuesMap.put(key, value); } } getQueryReturnValue().setReturnValue(configValuesMap); }</code><technical_language>this done in a static block - a waste do time</technical_language>

Target:
protected void executeQueryCommand() { Map<KeyValuePairCompat<ConfigurationValues, String>, Object> configValuesMap = new HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object>(); for (ConfigurationValues configValue : ConfigurationValues.values()) { if (!shouldReturnValue(configValue)) { continue; } List<String> versions = new ArrayList<String>(); versions.add(Config.DefaultConfigurationVersion); for (Version version : Version.ALL) { versions.add(version.toString()); } for (String version : versions) { KeyValuePairCompat<ConfigurationValues, String> key = new KeyValuePairCompat<ConfigurationValues, String>(configValue, version); Object value = Config.<Object> GetValue(ConfigValues.valueOf(configValue.toString()), version); configValuesMap.put(key, value); } } getQueryReturnValue().setReturnValue(configValuesMap); }
Source:
<code>public void testCompleteXmlToString() { URL resource = XmlConfigurationTest.class.getResource("/configs/ehcache-complete.xml"); Configuration config = new XmlConfiguration(resource); XmlConfiguration xmlConfig = new XmlConfiguration(config); <START> <END> String actualXMLConfigString = xmlConfig.toString(); if(System.getProperty("os.name").toLowerCase().contains("win")) { actualXMLConfigString = actualXMLConfigString.replace('\\', '/'); } assertThat(actualXMLConfigString, isSimilarTo(Input.from(resource)).ignoreComments().ignoreWhitespace().withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText))); }</code><technical_language>This fix is fine. simpler fix change path in test xml file a single directory name path separators</technical_language>

Target:
public void testCompleteXmlToString() { URL resource = XmlConfigurationTest.class.getResource("/configs/ehcache-complete.xml"); Configuration config = new XmlConfiguration(resource); XmlConfiguration xmlConfig = new XmlConfiguration(config); assertThat(xmlConfig.toString(), isSimilarTo(Input.from(resource)).ignoreComments().ignoreWhitespace().withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText))); }
Source:
<code>public void testRefuse() throws Exception { final List<Integer> items = Lists.newArrayList(); <START> Callback<Integer> callback = new Callback<Integer>() { <END> @Override public void call(Integer item) throws Exception { if (item >= 5) { throw new CallbackRefusedException(); } items.add(item); } }; streamer.read(response(200, inputStream(TEST_JSON)), callback, INT_TYPE_REF); assertEquals(ImmutableList.of(1, 2, 3, 4), items); }</code><technical_language>this slightly shorter lambda syntax</technical_language>

Target:
public void testRefuse() throws Exception { final List<Integer> items = Lists.newArrayList(); Callback<Integer> callback = new Callback<Integer>() { @Override public void call(Integer item) throws Exception { if (item >= 5) { throw new CallbackRefusedException(); } items.add(item); } }; streamer.read(response(Status.OK, inputStream(TEST_JSON)), callback, INT_TYPE_REF); assertEquals(ImmutableList.of(1, 2, 3, 4), items); }
Source:
<code><START> public Boolean getDuplicateIndices() { <END> return duplicateIndices; }</code><technical_language>Rename hasDuplicateIndices (unless this breaks serialization, I does)</technical_language>

Target:
public boolean getDuplicateIndices() { return duplicateIndices; }
Source:
<code>void runAction() { synchronized (lock) { throwIfClosed(); <START> action.run(); <END> } }</code><technical_language>automatically call close() release everything? need require developers explicitly call close() CTR CTS</technical_language>

Target:
void runAction() { synchronized (lock) { throwIfClosed(); action.run(); close(); } }
Source:
<code>public void testSingleTaskOccupyingSlotIndefinitely() { final PhysicalSlot physicalSlot = createPhysicalSlot(); allocateSingleLogicalSlotFromPhysicalSlot(physicalSlot, true); assertTrue(physicalSlot.willBeOccupiedIndefinitely()); <START> } <END></code><technical_language>suggestion assertThat(physicalSlot.willBeOccupiedIndefinitely(), is(true)); in other places</technical_language>

Target:
public void testSingleTaskOccupyingSlotIndefinitely() { final PhysicalSlot physicalSlot = createPhysicalSlot(); allocateSingleLogicalSlotFromPhysicalSlot(physicalSlot, true); assertThat(physicalSlot.willBeOccupiedIndefinitely(), is(true)); }
Source:
<code>public void testGetCarbonConfigDirPath() throws ClassNotFoundException, IllegalAccessException, NoSuchFieldException { <START> Map<String, String> newEnv = new HashMap<>(); <END> newEnv.put(CarbonBaseConstants.CARBON_CONFIG_DIR_PATH_ENV, "../wso2am-2.1.0/repository/conf"); try { Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newEnv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField ("theCaseInsensitiveEnvironment"); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newEnv); } catch (NoSuchFieldException e) { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = null; field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newEnv); } } } assertEquals(CarbonBaseUtils.getCarbonConfigDirPath(), "../wso2am-2.1.0/repository/conf", "Must provide the location where carbon.xml resides"); }</code><technical_language>extract setting environment variable logic a separate method class. Example: <LINK_0></technical_language>

Target:
public void testGetCarbonConfigDirPath() throws ClassNotFoundException, IllegalAccessException, NoSuchFieldException { setEnvironmentVariables(CarbonBaseConstants.CARBON_CONFIG_DIR_PATH_ENV, "/wso2am-2.1.0/repository/conf"); assertEquals(CarbonBaseUtils.getCarbonConfigDirPath(), "/wso2am-2.1.0/repository/conf", "Must provide the location where carbon.xml resides"); }
Source:
<code><START> public Result run(String[] args) { <END> Context context = new Context(); JavacFileManager.preRegister(context); return compile(args, context); }</code><technical_language>rename other instance methods named compile? usages in CompilationTestHelper ErrorProneTestCompiler</technical_language>

Target:
public Result run(String[] args) { Context context = new Context(); JavacFileManager.preRegister(context); return run(args, context); }