auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<ActionEventRequest> buildActionsForConfig(Config config) { List<ActionEventRequest> actions = new ArrayList<>(); for (CommcareApplicationJson application : schemaService.retrieveApplications(config.getName())) { for (CommcareModuleJson module : application.getModules()) { for (FormSchemaJson form : module.getFormSchemas()) { SortedSet<ActionParameterRequest> parameters = buildActionParameters(form); String displayName = DisplayNameHelper.buildDisplayName(DisplayNames.SUBMIT_FORM, form.getFormName(), application.getApplicationName(), config.getName()); <START> String appId = application.getCommcareAppId(); <END> if (appId == null) { appId = ""; } ActionEventRequestBuilder actionBuilder = new ActionEventRequestBuilder() .setDisplayName(displayName) .setSubject(EventSubjects.SUBMIT_FORM + "." + form.getXmlns() + appId + "." + config.getName()) .setActionParameters(parameters); actions.add(actionBuilder.createActionEventRequest()); } } } return actions; }</code><technical_language>this done in line</technical_language>

Target:
private List<ActionEventRequest> buildActionsForConfig(Config config) { List<ActionEventRequest> actions = new ArrayList<>(); for (CommcareApplicationJson application : schemaService.retrieveApplications(config.getName())) { for (CommcareModuleJson module : application.getModules()) { for (FormSchemaJson form : module.getFormSchemas()) { SortedSet<ActionParameterRequest> parameters = buildActionParameters(form); String displayName = DisplayNameHelper.buildDisplayName(DisplayNames.SUBMIT_FORM, form.getFormName(), application.getApplicationName(), config.getName()); String appId = (application.getCommcareAppId() == null) ? "" : application.getCommcareAppId(); ActionEventRequestBuilder actionBuilder = new ActionEventRequestBuilder() .setDisplayName(displayName) .setSubject(EventSubjects.SUBMIT_FORM + "." + form.getXmlns() + appId + "." + config.getName()) .setActionParameters(parameters); actions.add(actionBuilder.createActionEventRequest()); } } } return actions; }
Source:
<code>public void setUp() throws IOException { <START> if (extractor == null) { <END> doorHtmlExport = folder.newFile("sample_DOORS_export.htm"); copyResource("sample_DOORS_export.htm", doorHtmlExport); copyResource(THIS_IS_A_JPEG_IMAGE_JPG, folder.newFile(THIS_IS_A_JPEG_IMAGE_JPG)); copyResource(THIS_IS_A_PNG_IMAGE_PNG, folder.newFile(THIS_IS_A_PNG_IMAGE_PNG)); } extractor = new DoorsArtifactExtractor(); collector = new RoughArtifactCollector(null); }</code><technical_language>this once? if so, @BeforeClass</technical_language>

Target:
public void setUp() { extractor = new DoorsArtifactExtractor(); collector = new RoughArtifactCollector(null); }
Source:
<code><START> public List<ManufacturerDto> getManufacturers() { <END> return Manufacturer.createDto(manufacturerDao.getAll()); }</code><technical_language>REST, send a Response object. control HTTP status send</technical_language>

Target:
public Response getManufacturers() { List<ManufacturerDto> manufacturerDtos = Manufacturer.createDto(manufacturerDao.getAll()); return Response.ok(manufacturerDtos).build(); }
Source:
<code>private void testAddingMixedTypes(Version version, boolean addingMixedTypesShouldSucceed) { storagePool.setcompatibility_version(version); <START> when(storagePoolDAO.getStorageTypesInPool(storagePool.getId())).thenReturn(Arrays.asList(StorageType.NFS)); <END> StorageDomain domainToAttach = createValidStorageDomain(); domainToAttach.setStorageFormat(cmd.getSupportedStorageFormatSet(version).iterator().next()); initCommand(); assertTrue("Attaching an NFS domain to a pool with NFS domain with no mixed type allowed failed, version: " + version, cmd.checkDomainCanBeAttached(domainToAttach)); domainToAttach.setStorageType(StorageType.ISCSI); initCommand(); if (addingMixedTypesShouldSucceed) { assertTrue("Attaching an ISCSI domain to a pool with NFS domain with with mixed type allowed failed, version: " + version, cmd.checkDomainCanBeAttached(domainToAttach)); } else { assertFalse("Attaching an ISCSI domain to a pool with NFS domain with no mixed type allowed succeeded, version: " + version, cmd.checkDomainCanBeAttached(domainToAttach)); CanDoActionTestUtils.assertCanDoActionMessages("Attaching an ISCSI domain to a pool with NFS domain with no mixed type failed with the wrong message", cmd, VdcBllMessages.ACTION_TYPE_FAILED_MIXED_STORAGE_TYPES_NOT_ALLOWED); } }</code><technical_language>Please Collections.singletonList</technical_language>

Target:
private void testAddingMixedTypes(Version version, boolean addingMixedTypesShouldSucceed) { storagePool.setcompatibility_version(version); StorageDomain existingStorageDomain = createValidStorageDomain(); existingStorageDomain.setStorageType(StorageType.NFS); addDomainToPool(existingStorageDomain); StorageDomain domainToAttach = createValidStorageDomain(); domainToAttach.setStorageFormat(cmd.getSupportedStorageFormatSet(version).iterator().next()); existingStorageDomain.setStorageType(StorageType.NFS); initCommand(); assertTrue("Attaching an NFS domain to a pool with NFS domain with no mixed type allowed failed, version: " + version, cmd.checkDomainCanBeAttached(domainToAttach)); domainToAttach.setStorageType(StorageType.ISCSI); initCommand(); if (addingMixedTypesShouldSucceed) { assertTrue("Attaching an ISCSI domain to a pool with NFS domain with with mixed type allowed failed, version: " + version, cmd.checkDomainCanBeAttached(domainToAttach)); } else { assertFalse("Attaching an ISCSI domain to a pool with NFS domain with no mixed type allowed succeeded, version: " + version, cmd.checkDomainCanBeAttached(domainToAttach)); CanDoActionTestUtils.assertCanDoActionMessages("Attaching an ISCSI domain to a pool with NFS domain with no mixed type failed with the wrong message", cmd, VdcBllMessages.ACTION_TYPE_FAILED_MIXED_STORAGE_TYPES_NOT_ALLOWED); } }
Source:
<code>public INDArray params(boolean backwardOnly) { if(backwardOnly) return params(); List<INDArray> params = new ArrayList<>(); for (Layer layer: getLayers()){ INDArray layerParams; if(layer instanceof BasePretrainNetwork) <START> layerParams = ((BasePretrainNetwork) layer).paramsBackprop(); <END> else layerParams = layer.params(); if(layerParams != null) params.add(layerParams); } return Nd4j.toFlattened('f', params); }</code><technical_language>reason noted training. This is for backwardOnly</technical_language>

Target:
public INDArray params(boolean backwardOnly) { if(backwardOnly) return params(); List<INDArray> params = new ArrayList<>(); for (Layer layer: getLayers()){ INDArray layerParams = layer.params(); if(layerParams != null) params.add(layerParams); } return Nd4j.toFlattened('f', params); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(new ThemeUtils(this).getSettingsTheme()); setTitle(R.string.general_preferences); if (savedInstanceState == null) { boolean adminMode = getIntent().getBooleanExtra(INTENT_KEY_ADMIN_MODE, false); <START> boolean openMapsPrefs = getIntent().getBooleanExtra("openMapsPrefs", false); <END> Fragment fragment = openMapsPrefs ? MapsPreferences.newInstance(adminMode) : GeneralPreferencesFragment.newInstance(adminMode); getFragmentManager() .beginTransaction() .add(android.R.id.content, fragment, TAG) .commit(); } }</code><technical_language>this extra for version maps preference screen opened widgets, chance? (and removed?)</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(new ThemeUtils(this).getSettingsTheme()); setTitle(R.string.general_preferences); if (savedInstanceState == null) { boolean adminMode = getIntent().getBooleanExtra(INTENT_KEY_ADMIN_MODE, false); Fragment fragment = GeneralPreferencesFragment.newInstance(adminMode); getFragmentManager() .beginTransaction() .add(android.R.id.content, fragment, TAG) .commit(); } }
Source:
<code><START> public void setCurrentContainer(FormsContainer container) { <END> this.container = container; }</code><technical_language>this method public, sense arguments for flush(ClientSession, String) method, session (editor) a FormsContainer instance, set in setCurrentContainer... please change package protected access (so access modifier set)? work/make sense for you</technical_language>

Target:
void setCurrentContainer(FormsContainer container) { this.container = container; }
Source:
<code>protected void handleRemoteBrowseSelected() { IHost currentConnectionSelected = getCurrentConnection(); SystemRemoteFileDialog dlg = new SystemRemoteFileDialog(getControl() .getShell(), Messages.RemoteCMainTab_Remote_Path_Browse_Button_Title, currentConnectionSelected); dlg.setBlockOnOpen(true); if (dlg.open() == Window.OK) { Object retObj = dlg.getSelectedObject(); if (retObj instanceof IRemoteFile) { IRemoteFile selectedFile = (IRemoteFile) retObj; String absPath = selectedFile.getAbsolutePath(); if (selectedFile.isDirectory()) { IPath appPath = new Path(fProgText.getText()); <START> IPath remotePath = new Path(selectedFile.getAbsolutePath()).append(appPath.lastSegment()); <END> absPath = remotePath.toPortableString(); } remoteProgText.setText(absPath); } } }</code><technical_language>I appPath empty string lastSegment() return null, NPE. try this leaving program text box empty</technical_language>

Target:
protected void handleRemoteBrowseSelected() { IHost currentConnectionSelected = getCurrentConnection(); SystemRemoteFileDialog dlg = new SystemRemoteFileDialog(getControl() .getShell(), Messages.RemoteCMainTab_Remote_Path_Browse_Button_Title, currentConnectionSelected); dlg.setBlockOnOpen(true); if (dlg.open() == Window.OK) { Object retObj = dlg.getSelectedObject(); if (retObj instanceof IRemoteFile) { IRemoteFile selectedFile = (IRemoteFile) retObj; String absPath = selectedFile.getAbsolutePath(); if (selectedFile.isDirectory()) { IPath appPath = new Path(fProgText.getText().trim()); String lastSegment = appPath.lastSegment(); if (lastSegment != null && lastSegment.trim().length() > 0) { IPath remotePath = new Path(selectedFile.getAbsolutePath()).append(lastSegment.trim()); absPath = remotePath.toOSString(); } } remoteProgText.setText(absPath); } } }
Source:
<code>private void updateMenuItemVisibility() { if (mMenuAdd == null || mMenuEdit == null || mMenuSearch == null) { return; } if (getAdapter().getIsInSearchMode()) { mMenuEdit.setVisible(false); mMenuAdd.setVisible(false); } else { mMenuEdit.setVisible(mSiteStore.getSitesAccessedViaWPComRestCount() > 1); mMenuAdd.setVisible(true); } mMenuSearch.setVisible(mSiteStore.getSitesCount() > 1); <START> invalidateOptionsMenu(); <END> }</code><technical_language>Adding invalidateOptionsMenu() menu refreshed multiple times. Calling invalidateOptionsMenu() in updateMenuItemVisibility() onPrepareOptionsMenu(Menu menu) triggered, calls updateMenuItemVisibility() invalidateOptionsMenu() again. refreshing menu multiple times fixes bug, mask root cause. remove this invalidateOptionsMenu() call in order address underlying issue</technical_language>

Target:
private void updateMenuItemVisibility() { if (mMenuAdd == null || mMenuEdit == null || mMenuSearch == null) { return; } if (getAdapter().getIsInSearchMode()) { mMenuEdit.setVisible(false); mMenuAdd.setVisible(false); } else { mMenuEdit.setVisible(mSiteStore.getSitesAccessedViaWPComRestCount() > 1); mMenuAdd.setVisible(true); } mMenuSearch.setVisible(mSiteStore.getSitesCount() > 1); }
Source:
<code>public static ShipConfig load(HullConfigManager hullConfigs, JSONObject rootNode, ItemManager itemManager) { if (rootNode == null) { return null; } String hullName = rootNode.getString("hull"); HullConfig hull = hullConfigs.getConfig(hullName); ShipConfig guard; if (rootNode.has("guard")) { <START> guard = load(hullConfigs, rootNode.has("guard") ? rootNode.getJSONObject("guard") : null, itemManager); <END> } else { guard = null; } String items = rootNode.getString("items"); int money = rootNode.optInt("money", 0); float density = (float) rootNode.optDouble("density", -1); return new ShipConfig(hull, items, money, density, guard, itemManager); }</code><technical_language>I understand this. rootNode.has("guard") *never* false, verified is true in line 119</technical_language>

Target:
public static ShipConfig load(HullConfigManager hullConfigs, JSONObject rootNode, ItemManager itemManager) { if (rootNode == null) { return null; } String hullName = rootNode.getString("hull"); HullConfig hull = hullConfigs.getConfig(hullName); ShipConfig guard; if (rootNode.has("guard")) { guard = load(hullConfigs, rootNode.getJSONObject("guard"), itemManager); } else { guard = null; } String items = rootNode.getString("items"); int money = rootNode.optInt("money", 0); float density = (float) rootNode.optDouble("density", -1); return new ShipConfig(hull, items, money, density, guard, itemManager); }
Source:
<code>public void configureOSPF(OSPFService ospfService) throws CapabilityException { IAction action = createActionAndCheckParams(OSPFActionSet.OSPF_CONFIGURE, ospfService); <START> ospfService.setEnabledState(EnabledState.DISABLED); END> queueAction(action); }</code><technical_language>preferrable changed state setting a parameter in action check parameters. some actions store a live reference parameter, others not, resulting in undesired behaviour. Furthermore, aware some actions checkParams set behaviour</technical_language>

Target:
public void configureOSPF(OSPFService ospfService) throws CapabilityException { ospfService.setEnabledState(EnabledState.DISABLED); IAction action = createActionAndCheckParams(OSPFActionSet.OSPF_CONFIGURE, ospfService); queueAction(action); }
Source:
<code>public synchronized void start() { if (store != null) { store.start(); } else { <START> LOG.warn("Store not initialized, so not starting the service"); <END> } super.start(); }</code><technical_language>log store is initialized</technical_language>

Target:
public synchronized void start() { if (store != null) { store.start((com.inmobi.grill.server.api.events.GrillEventService) GrillServices.get().getService(EventServiceImpl.NAME)); } else { LOG.warn("Unable to start the LogStore."); } super.start(); }
Source:
<code>private void traceContainers(String action, long start) { Long delta = Long.valueOf(System.currentTimeMillis() - start); <START> Long length = Long.valueOf(getContainersFile().length()); <END> String pattern = "{0} {1} bytes in containers.dat in {2}ms"; String message = NLS.bind(pattern, new Object[] { action, length, delta }); System.out.println(message); }</code><technical_language>I suggest "long" type autoboxing work</technical_language>

Target:
private void traceContainers(String action, long start) { Long delta = System.currentTimeMillis() - start; Long length = getContainersFile().length(); String pattern = "{0} {1} bytes in containers.dat in {2}ms"; String message = NLS.bind(pattern, new Object[] { action, length, delta }); System.out.println(message); }
Source:
<code>public HandleJobsWithGroupNamePermission(Map<String, String> genericInformations) { super(DESCRIPTION); if (genericInformations.containsKey(GROUP)) { <START> String bucketName = genericInformations.get(GROUP); <END> this.allowedGroups = Collections.singleton(bucketName); } else { this.allowedGroups = Collections.EMPTY_SET; } }</code><technical_language>groupName</technical_language>

Target:
public HandleJobsWithGroupNamePermission(Map<String, String> genericInformations) { super(DESCRIPTION); if (genericInformations.containsKey(GROUP)) { String groupName = genericInformations.get(GROUP); this.allowedGroups = Collections.singleton(groupName); } else { this.allowedGroups = Collections.EMPTY_SET; } }
Source:
<code>public static String getExtension(final String filename) { if (filename == null) { throw new IllegalArgumentException("filename cannot be null"); <START> } <END> int lastDotIdx = filename.lastIndexOf("."); return lastDotIdx >= 0 ? filename.substring(lastDotIdx) : ""; }</code><technical_language>This is perfectly fine, ICYMI for future reference, Java 7 do this built-in java.util.Objects class: Objects.requireNotNull(filename,"filename null"); is methods return parameter, in constructors method params easily check assign a one-liner</technical_language>

Target:
public static String getExtension(final String filename) { Objects.requireNonNull(filename, "filename cannot be null"); int lastDotIdx = filename.lastIndexOf("."); return lastDotIdx >= 0 ? filename.substring(lastDotIdx) : ""; }
Source:
<code>default boolean isHealthy() { if (getContainerId() == null) { return false; } try { InspectContainerResponse inspectContainerResponse = getCurrentContainerInfo(); HealthState health = inspectContainerResponse.getState().getHealth(); if (health == null) { <START> throw new RuntimeException("Healthchecks not configured for this container"); <END> } return STATE_HEALTHY.equals(health.getStatus()); } catch (DockerException e) { return false; } }</code><technical_language>I good give user a more of a hint wrong/what do. Perhaps: suggestion throw new RuntimeException("This container's image a healthcheck declared, health determined. amend image another approach determine containers healthy.");</technical_language>

Target:
default boolean isHealthy() { if (getContainerId() == null) { return false; } try { InspectContainerResponse inspectContainerResponse = getCurrentContainerInfo(); HealthState health = inspectContainerResponse.getState().getHealth(); if (health == null) { throw new RuntimeException("This container's image does not have a healthcheck declared, so health cannot be determined. Either amend the image or use another approach to determine whether containers are healthy."); } return STATE_HEALTHY.equals(health.getStatus()); } catch (DockerException e) { return false; } }
Source:
<code>private byte[] parseLine(String line) throws OpenEnergyMonitorException { logger.trace("Received line: {}", line); String[] bytes = line.toString().split(" "); ByteBuffer bytebuf = ByteBuffer.allocate(bytes.length); try { for (int j = 0; j < bytes.length; j++) { if (!bytes[j].isEmpty()) { byte b = (byte) Integer.parseInt(bytes[j]); bytebuf.put(b); } } } catch (NumberFormatException e) { <START> throw new OpenEnergyMonitorException("Error occured while receiving data", e); <END> } return bytebuf.array(); }</code><technical_language>"occurred"</technical_language>

Target:
private byte[] parseLine(String line) throws OpenEnergyMonitorException { logger.trace("Received line: {}", line); String[] bytes = line.toString().split(" "); ByteBuffer bytebuf = ByteBuffer.allocate(bytes.length); try { for (int j = 0; j < bytes.length; j++) { if (!bytes[j].isEmpty()) { byte b = (byte) Integer.parseInt(bytes[j]); bytebuf.put(b); } } } catch (NumberFormatException e) { throw new OpenEnergyMonitorException("Error occurred while receiving data. ", e); } return bytebuf.array(); }
Source:
<code>protected void onHandleIntent(@NonNull Intent intent) { List<ReadingListPageDiskRow> queue = new ArrayList<>(); Collection<ReadingListPageDiskRow> rows = dao.startDiskTransaction(); L.i("Syncing saved rlp pages with saved pages service"); for (final ReadingListPageDiskRow row : rows) { L.v("Found pending tx with status: " + row.status().name()); switch (row.status()) { case UNSAVED: <START> case DELETED: <END> String filename = row.filename(); if (filename != null) { FileUtil.delete(new File(filename), true); L.v("Deleted" + filename); continue; } L.e("Found row with null filename; skipping"); continue; case OUTDATED: queue.add(row); continue; case ONLINE: case SAVED: continue; default: throw new UnsupportedOperationException("Invalid disk row status: " + row.status().name()); } } saveNewEntries(queue); }</code><technical_language>need complete transaction for cases</technical_language>

Target:
protected void onHandleIntent(@NonNull Intent intent) { List<ReadingListPageDiskRow> queue = new ArrayList<>(); Collection<ReadingListPageDiskRow> rows = dao.startDiskTransaction(); L.i("Syncing saved rlp pages with saved pages service"); for (final ReadingListPageDiskRow row : rows) { L.v("Found pending tx with status: " + row.status().name()); switch (row.status()) { case UNSAVED: case DELETED: String filename = row.filename(); if (filename != null) { FileUtil.delete(new File(filename), true); dao.completeDiskTransaction(row); L.v("Deleted" + filename); continue; } L.e("Found row with null filename; skipping"); continue; case OUTDATED: queue.add(row); continue; case ONLINE: case SAVED: L.w("Received row with unexpected status " + row.status() + ": " + row.toString()); continue; default: throw new UnsupportedOperationException("Invalid disk row status: " + row.status().name()); } } saveNewEntries(queue); }
Source:
<code>public double isApplicable(VElement vElement, ViewModelContext viewModelContext) { if (classType == null) { return NOT_APPLICABLE; } if (selectSubclasses && !classType.isSuperTypeOf(vElement.eClass())) { return NOT_APPLICABLE; } else if (!selectSubclasses && !classType.equals(vElement.eClass())) { return NOT_APPLICABLE; } if (attribute != null) { final Object attrValue = vElement.eGet(attribute); if (attrValue == null) { return NOT_APPLICABLE; } if (!attrValue.equals(attributeValue)) { return NOT_APPLICABLE; } } if (attribute != null) { <START> return 6; <END> } return 5; }</code><technical_language>why</technical_language>

Target:
public double isApplicable(VElement vElement, ViewModelContext viewModelContext) { if (classType == null) { return NOT_APPLICABLE; } if (selectSubclasses && !classType.isSuperTypeOf(vElement.eClass())) { return NOT_APPLICABLE; } else if (!selectSubclasses && !classType.equals(vElement.eClass())) { return NOT_APPLICABLE; } if (attribute != null) { final Object attrValue = vElement.eGet(attribute); if (attrValue == null) { return NOT_APPLICABLE; } if (!attrValue.equals(attributeValue)) { return NOT_APPLICABLE; } return 6; } return 5; }
Source:
<code>public void testPostConent() throws Exception { ITask task = harness.createTask("GetContent"); File file = File.createTempFile("attachment", null); file.deleteOnExit(); <START> try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { <END> out.write("Mylar".getBytes()); } attachmentHandler.postContent(repository, task, new FileTaskAttachmentSource(file), "comment", null, null); ITracClient client = connector.getClientManager().getTracClient(repository); try (InputStream in = client.getAttachmentData(Integer.parseInt(task.getTaskId()), file.getName(), null)) { byte[] result = new byte[5]; in.read(result); assertEquals("Mylar", new String(result)); } }</code><technical_language>BufferedOutputStream is overkill write 5 bytes once, is OK here. Please try-with resource, though</technical_language>

Target:
public void testPostConent() throws Exception { ITask task = harness.createTask("GetContent"); File file = File.createTempFile("attachment", null); file.deleteOnExit(); try (OutputStream out = new FileOutputStream(file)) { out.write("Mylar".getBytes()); } attachmentHandler.postContent(repository, task, new FileTaskAttachmentSource(file), "comment", null, null); ITracClient client = connector.getClientManager().getTracClient(repository); try (InputStream in = client.getAttachmentData(Integer.parseInt(task.getTaskId()), file.getName(), null)) { byte[] result = new byte[5]; in.read(result); assertEquals("Mylar", new String(result)); } }
Source:
<code>public static String rangeParser(List<String> values) { if <START> (values == <END> null) { return "0"; } return String.valueOf(ThreadLocalRandom.current().nextInt(Integer.valueOf(values.get(0)), Integer.valueOf(values.get(1))) ); }</code><technical_language>do values strings parsable int</technical_language>

Target:
public static String rangeParser(List<String> values) { String warnMessage = "skip and parse 0, please review applicaion.conf"; try { return String.valueOf(ThreadLocalRandom.current().nextInt(Integer.valueOf(values.get(0)), Integer.valueOf(values.get(1)))); } catch (NullPointerException e) { log.warn("range values must be set", warnMessage); return "0"; } catch (IllegalArgumentException e) { log.warn("bad range values were found {}", warnMessage); return "0"; } }
Source:
<code>protected void testExecute_nonExistingEmail() { ______TS("Typical case: non-existing email address"); String[] nonExistingParam = new String[] { Const.ParamsNames.SESSION_LINKS_RECOVERY_EMAIL, "non-existent email address", }; SessionLinksRecoveryAction a = getAction(nonExistingParam); JsonResult result = getJsonResult(a); SessionLinksRecoveryResponseData output = (SessionLinksRecoveryResponseData) result.getOutput(); assertEquals("The recovery links for your feedback sessions have been sent to " + "the specified email address: non-existent email address", output.getMessage()); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); <START> verifyNumberOfEmailsSent(a, 1); <END> EmailWrapper emailSent = a.getEmailSender().getEmailsSent().get(0); assertEquals(EmailType.SESSION_LINKS_RECOVERY.getSubject(), emailSent.getSubject()); assertEquals("non-existent email address", emailSent.getRecipient()); assertEquals(Templates.populateTemplate( Templates.EmailTemplates.SESSION_LINKS_RECOVERY_EMAIL_NOT_FOUND, "${userEmail}", SanitizationHelper.sanitizeForHtml("non-existent email address"), "${supportEmail}", Config.SUPPORT_EMAIL, "${teammateHomePageLink}", Config.APP_URL), emailSent.getContent()); }</code><technical_language>doesnt sense this is a random string, a valid email address. check param input is a valid email address</technical_language>

Target:
protected void testExecute_nonExistingEmail() { ______TS("Typical case: non-existent email address"); String[] nonExistingParam = new String[] { Const.ParamsNames.SESSION_LINKS_RECOVERY_EMAIL, "non-existent@abc.com", }; SessionLinksRecoveryAction a = getAction(nonExistingParam); JsonResult result = getJsonResult(a); SessionLinksRecoveryResponseData output = (SessionLinksRecoveryResponseData) result.getOutput(); assertEquals("The recovery links for your feedback sessions have been sent to " + "the specified email address: non-existent@abc.com", output.getMessage()); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); verifyNumberOfEmailsSent(a, 1); EmailWrapper emailSent = a.getEmailSender().getEmailsSent().get(0); assertEquals(EmailType.SESSION_LINKS_RECOVERY.getSubject(), emailSent.getSubject()); assertEquals("non-existent@abc.com", emailSent.getRecipient()); }
Source:
<code>protected String reformat( String message ) { if ( channel == null ) { return message; } <START> String localChannelId = getLocalChannelId(); <END> String dbConnectionId = getDbConnectionId(); if ( localChannelId != null && dbConnectionId != null ) { return format( "[0x%s][%s] %s", localChannelId, dbConnectionId, message ); } return format( "[0x%s][] %s", localChannelId, message ); }</code><technical_language>assign localChannelId constructor directly</technical_language>

Target:
protected String reformat( String message ) { if ( channel == null ) { return message; } String dbConnectionId = getDbConnectionId(); if ( localChannelId != null && dbConnectionId != null ) { return format( "[0x%s][%s] %s", localChannelId, dbConnectionId, message ); } return format( "[0x%s][] %s", localChannelId, message ); }
Source:
<code>public static void runPigJob(String[] args) throws Exception { PigStats stats = PigUtil.runPigJob(args, props); PigUtil.dumpHadoopCounters(stats, props); if (stats.isSuccessful()) { return; } if (pigLogFile != null) { handleError(pigLogFile); } <START> if (isTuningError && jobTryCount <= maxJobRetry) { <END> throw new RuntimeException("Pig job failed."); } PigUtil.selfKill(); }</code><technical_language>I of a static isTuningError here. I cleaner handleError runPigJob return boolean values indicating a tuning error, create a new exception type TuningException is thrown tuning-specific errors</technical_language>

Target:
public static void runPigJob(String[] args) throws Exception { PigStats stats = PigUtil.runPigJob(args, props); PigUtil.dumpHadoopCounters(stats, props); if (stats.isSuccessful()) { return; } if (pigLogFile != null) { handleError(pigLogFile); } PigUtil.selfKill(); }
Source:
<code>public CompositeDisposable(@NonNull Disposable... disposables) { <START> ObjectHelper.requireNonNull(disposables, "Disposables are null"); <END> this.resources = new OpenHashSet<Disposable>(disposables.length + 1); for (Disposable d : disposables) { ObjectHelper.requireNonNull(d, "Disposable item in Disposables is null"); this.resources.add(d); } }</code><technical_language>Please lowercase refers argument: disposables is null</technical_language>

Target:
public CompositeDisposable(@NonNull Disposable... disposables) { ObjectHelper.requireNonNull(disposables, "disposables is null"); this.resources = new OpenHashSet<Disposable>(disposables.length + 1); for (Disposable d : disposables) { ObjectHelper.requireNonNull(d, "A Disposable in the disposables array is null"); this.resources.add(d); } }
Source:
<code>private boolean canEvict(final int refCount, boolean writer) { if (refCount == 0 && storage != null) { if (backPressureEnabled) { if (!writer) { boolean evict = true; int blocks = 0; for (Block temp = this.prev; (blocks < (MAX_COUNT_OF_INMEM_BLOCKS - 1)) && (temp != null); temp = temp.prev, ++blocks) { if (temp.refCount.get() != 0) { evict = false; break; } } logger.debug("Block evict {}", this, evict); return evict; } else { return false; } } else { return true; } } else { if (storage != null) { logger.debug("Holding in memory due to references.", this, refCount); } else { <START> logger.debug("Holding in memory as spooling is disabled"); <END> } return false; } }</code><technical_language>logged once, for block (spooling is enabled disabled)</technical_language>

Target:
private boolean canEvict(final int refCount, boolean writer) { if (refCount == 0) { if (backPressureEnabled) { if (!writer) { boolean evict = true; synchronized (this) { for (Block temp = this.prev; temp != null; temp = temp.prev) { if (temp.refCount.get() != 0) { evict = false; break; } } } logger.debug("Block evict {}", this, evict); return evict; } else { return false; } } else { return true; } } logger.debug("Not evicting due to references.", this, refCount); return false; }
Source:
<code>public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; GetObjectRequest that = (GetObjectRequest) object; if (isRequesterPays() != that.isRequesterPays()) return false; if (!s3ObjectIdBuilder.equals(that.s3ObjectIdBuilder)) return false; if (!java.util.Arrays.equals(getRange(), that.getRange())) return false; <START> if (!getMatchingETagConstraints().equals(that.getMatchingETagConstraints())) return false; <END> if (!nonmatchingEtagConstraints.equals(that.nonmatchingEtagConstraints)) return false; if (getUnmodifiedSinceConstraint() != null ? !getUnmodifiedSinceConstraint().equals(that.getUnmodifiedSinceConstraint()) : that.getUnmodifiedSinceConstraint() != null) return false; if (getModifiedSinceConstraint() != null ? !getModifiedSinceConstraint().equals(that.getModifiedSinceConstraint()) : that.getModifiedSinceConstraint() != null) return false; if (getResponseHeaders() != null ? !getResponseHeaders().equals(that.getResponseHeaders()) : that.getResponseHeaders() != null) return false; if (sseCustomerKey != null ? !sseCustomerKey.equals(that.sseCustomerKey) : that.sseCustomerKey != null) return false; if (getPartNumber() != null ? !getPartNumber().equals(that.getPartNumber()) : that.getPartNumber() != null) return false; return true; }</code><technical_language>need a null check for getMatchingETagConstraints</technical_language>

Target:
public boolean equals(Object object) { if (this == object) return true; if (object == null || object instanceof GetObjectRequest == false) return false; if (!super.equals(object)) return false; GetObjectRequest that = (GetObjectRequest) object; if (isRequesterPays() != that.isRequesterPays()) return false; if (!s3ObjectIdBuilder.equals(that.s3ObjectIdBuilder)) return false; if (!java.util.Arrays.equals(getRange(), that.getRange())) return false; if (getMatchingETagConstraints() != null ? !getMatchingETagConstraints().equals(that.getMatchingETagConstraints()) : that.getMatchingETagConstraints() != null) return false; if (getNonmatchingETagConstraints() != null ? !getNonmatchingETagConstraints().equals(that.getNonmatchingETagConstraints()) : that.getNonmatchingETagConstraints() != null) return false; if (getUnmodifiedSinceConstraint() != null ? !getUnmodifiedSinceConstraint().equals(that.getUnmodifiedSinceConstraint()) : that.getUnmodifiedSinceConstraint() != null) return false; if (getModifiedSinceConstraint() != null ? !getModifiedSinceConstraint().equals(that.getModifiedSinceConstraint()) : that.getModifiedSinceConstraint() != null) return false; if (getResponseHeaders() != null ? !getResponseHeaders().equals(that.getResponseHeaders()) : that.getResponseHeaders() != null) return false; if (getSSECustomerKey() != null ? !getSSECustomerKey().equals(that.getSSECustomerKey()) : that.getSSECustomerKey() != null) return false; if (getPartNumber() != null ? !getPartNumber().equals(that.getPartNumber()) : that.getPartNumber() != null) return false; return true; }
Source:
<code>private void showPantsMakeTaskMessage(String message, ConsoleViewContentType type, Project project) { ConsoleView executionConsole = PantsConsoleManager.getOrMakeNewConsole(project); Filter filter = new Filter() { @Nullable @Override public Result applyFilter(String line, int entireLength) { Optional<ParseResult> result = ParseResult.parseErrorLocation(line, ERROR_TAG); if (result.isPresent()) { OpenFileHyperlinkInfo linkInfo = new OpenFileHyperlinkInfo( project, result.get().getFile(), <START> result.get().lineNumber - 1, END> result.get().columnNumber - 1 ); int startHyperlink = entireLength - line.length() + line.indexOf(ERROR_TAG); return new Result( startHyperlink, entireLength, linkInfo, null ); } return null; } }; ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { executionConsole.addMessageFilter(filter); executionConsole.print(message, type); } }, ModalityState.NON_MODAL); }</code><technical_language>getLineNumber getColumnNumber</technical_language>

Target:
private void showPantsMakeTaskMessage(String message, ConsoleViewContentType type, Project project) { ConsoleView executionConsole = PantsConsoleManager.getOrMakeNewConsole(project); Filter filter = new Filter() { @Nullable @Override public Result applyFilter(String line, int entireLength) { Optional<ParseResult> result = ParseResult.parseErrorLocation(line, ERROR_TAG); if (result.isPresent()) { OpenFileHyperlinkInfo linkInfo = new OpenFileHyperlinkInfo( project, result.get().getFile(), result.get().getLineNumber() - 1, result.get().getColumnNumber() - 1 ); int startHyperlink = entireLength - line.length() + line.indexOf(ERROR_TAG); return new Result( startHyperlink, entireLength, linkInfo, null ); } return null; } }; ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { executionConsole.addMessageFilter(filter); executionConsole.print(message, type); } }, ModalityState.NON_MODAL); }
Source:
<code>public void startHistoryWithPrice(String symbol, Double newPrice) throws StockMarketExpection { if (!marketHistory.containsKey(symbol)) { List<Double> <START> priceList = <END> new ArrayList<Double>(); priceList.add(newPrice); marketHistory.put(symbol, priceList); } }</code><technical_language>variable name type</technical_language>

Target:
public void startHistoryWithPrice(String symbol, Double newPrice) throws StockMarketExpection { if (!marketHistory.containsKey(symbol)) { List<Double> price = new ArrayList<Double>(); priceList.add(newPrice); marketHistory.put(symbol, price); } }
Source:
<code>public static EventService getAnalyticsRest(@NonNull StreamConfig streamConfig) { DestinationEventService destinationEventService = streamConfig.getDestinationEventService(); if (destinationEventService == null) { destinationEventService = DestinationEventService.ANALYTICS; } EventService s; if (ANALYTICS_REST_SERVICE_CACHE.get(destinationEventService.getId()) != null) { s = ANALYTICS_REST_SERVICE_CACHE.get(destinationEventService.getId()); if (s != null) { return s; } } String intakeBaseUriOverride = getEventPlatformIntakeUriOverride(); <START> Retrofit r = createRetrofit(WikiSite.forLanguageCode(WikipediaApp.getInstance().getAppOrSystemLanguageCode()), <END> intakeBaseUriOverride != null ? intakeBaseUriOverride : destinationEventService.getBaseUri()); s = r.create(EventService.class); ANALYTICS_REST_SERVICE_CACHE.put(destinationEventService.getId(), s); return s; }</code><technical_language>a WikiSite wiki parameter wiki create a Retrofit instance? e.g. getAnalyticsRest(@NonNull WikiSite wiki, @NonNull StreamConfig streamConfig)</technical_language>

Target:
public static EventService getAnalyticsRest(@NonNull StreamConfig streamConfig) { DestinationEventService destinationEventService = streamConfig.getDestinationEventService(); if (destinationEventService == null) { destinationEventService = DestinationEventService.ANALYTICS; } EventService s; if (ANALYTICS_REST_SERVICE_CACHE.get(destinationEventService.getId()) != null) { s = ANALYTICS_REST_SERVICE_CACHE.get(destinationEventService.getId()); if (s != null) { return s; } } String intakeBaseUriOverride = getEventPlatformIntakeUriOverride(); Retrofit r = createRetrofit(null, StringUtils.defaultString(intakeBaseUriOverride, destinationEventService.getBaseUri())); s = r.create(EventService.class); ANALYTICS_REST_SERVICE_CACHE.put(destinationEventService.getId(), s); return s; }
Source:
<code>public static String keyWithResourceNameAndSuffix(String resourceName, String suffix) { <START> return String.format("%s.%s.%s", EXTERNAL_RESOURCE_PREFIX, resourceName, suffix); <END> }</code><technical_language>add checkNotNull for arguments</technical_language>

Target:
private static String keyWithResourceNameAndSuffix(String resourceName, String suffix) { return String.format("%s.%s.%s", EXTERNAL_RESOURCE_PREFIX, Preconditions.checkNotNull(resourceName), Preconditions.checkNotNull(suffix)); }
Source:
<code>public static Takes make(final Base base) throws IOException { final Takes fork = new TsFork( new FkParams( PsByFlag.class.getSimpleName(), Pattern.compile(".+"), new TkRedirect() ), new FkRegex( "/xsl/.*", new TsWithType(new TsClasspath(), "text/xsl") ), new FkRegex( "/css/.*", new TsWithType( new TsFork( new FkHitRefresh( new File("./src/main/scss"), new Runnable() { @Override public void run() { new VerboseProcess( new ProcessBuilder( "mvn", "sass:update-stylesheets", "minify:minify" ) ).stdout(); } }, new TsFiles("./target/classes") ), new FkFixed(new TsClasspath()) ), "text/css" ) ), <START> new FkRegex("/images/.*", new TsClasspath()), <END> new FkRegex("/robots.txt", ""), new FkRegex( "/", new TsFork( new FkAuthenticated( new Target<Request>() { @Override public Take route(final Request req) throws IOException { return new TkDocs( base.user( new RqAuth(req).identity().urn() ), req ); } } ), new FkAnonymous( new Target<Request>() { @Override public Take route(final Request req) { return new TkIndex(req); } } ) ) ), new FkRegex( "/doc/.*", new TsSecure(new TsGreedy(new TsDoc(base))) ) ); return TsApp.fallback( new TsVerbose(new TsFlash(TsApp.auth(fork))) ); }</code><technical_language>image is returned Content-Type set. some browsers complain. wrap this TsWithType</technical_language>

Target:
public static Takes make(final Base base) throws IOException { final Takes fork = new TsFork( new FkParams( PsByFlag.class.getSimpleName(), Pattern.compile(".+"), new TkRedirect() ), new FkRegex( "/xsl/.*", new TsWithType(new TsClasspath(), "text/xsl") ), new FkRegex( "/css/.*", new TsWithType( new TsFork( new FkHitRefresh( new File("./src/main/scss"), new Runnable() { @Override public void run() { new VerboseProcess( new ProcessBuilder( "mvn", "sass:update-stylesheets", "minify:minify" ) ).stdout(); } }, new TsFiles("./target/classes") ), new FkFixed(new TsClasspath()) ), "text/css" ) ), new FkRegex( "/images/.*\\.png", new TsWithType(new TsClasspath(), MediaType.PNG.toString()) ), new FkRegex("/robots.txt", ""), new FkRegex( "/", new TsFork( new FkAuthenticated( new Target<Request>() { @Override public Take route(final Request req) throws IOException { return new TkDocs( base.user( new RqAuth(req).identity().urn() ), req ); } } ), new FkAnonymous( new Target<Request>() { @Override public Take route(final Request req) { return new TkIndex(req); } } ) ) ), new FkRegex( "/doc/.*", new TsSecure(new TsGreedy(new TsDoc(base))) ) ); return TsApp.fallback( new TsVerbose(new TsFlash(TsApp.auth(fork))) ); }
Source:
<code>public void testNoTaskJobLauncher() { String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true", "--spring.cloud.task.batch.failOnJobFailurePollInterval=500", "--spring.batch.job.enabled=false" }; this.applicationContext = SpringApplication.run(new Class[] { TaskJobLauncherCommandLineRunnerTests.JobWithFailureConfiguration.class }, enabledArgs); <START> } <END></code><technical_language>this verify? assertions</technical_language>

Target:
public void testNoTaskJobLauncher() { String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true", "--spring.cloud.task.batch.failOnJobFailurePollInterval=500", "--spring.batch.job.enabled=false" }; this.applicationContext = SpringApplication.run(new Class[] { TaskJobLauncherCommandLineRunnerTests.JobWithFailureConfiguration.class }, enabledArgs); JobExplorer jobExplorer = this.applicationContext.getBean(JobExplorer.class); assertThat(jobExplorer.getJobNames().size()).isEqualTo(0); }
Source:
<code>public WikiBasePageObject(WebDriver driver) { super(driver); <START> this.globalNav = new GlobalNavPageObject(driver); <END> }</code><technical_language>create instance of this object requested in constructor</technical_language>

Target:
public WikiBasePageObject(WebDriver driver) { super(driver); PageFactory.initElements(driver, this); }
Source:
<code>void addChild(ObjectId repoId, ObjectId cacheId, String path) throws IOException { <START> String[] entrys = path.split("/"); END> String pathKey = entrys[0]; IPath fullPath = getLocation().append(pathKey); if (entrys.length > 1) { GitModelCacheTree cacheEntry = (GitModelCacheTree) cacheTreeMap .get(pathKey); if (cacheEntry == null) { cacheEntry = new GitModelCacheTree(this, baseCommit, repoId, cacheId, fullPath, factory); cacheTreeMap.put(pathKey, cacheEntry); } cacheEntry.addChild(repoId, cacheId, path.substring(path.indexOf('/') + 1)); } else cacheTreeMap.put(pathKey, factory.createFileModel(this, baseCommit, repoId, cacheId, fullPath)); }</code><technical_language>argument in file: interested in location of slash ... I guess indexOf+substring faster</technical_language>

Target:
void addChild(ObjectId repoId, ObjectId cacheId, String path) throws IOException { String pathKey; int firstSlash = path.indexOf("/"); if (firstSlash > -1) pathKey = path.substring(0, firstSlash); else pathKey = path; IPath fullPath = getLocation().append(pathKey); if (path.contains("/")) { GitModelCacheTree cacheEntry = (GitModelCacheTree) cacheTreeMap .get(pathKey); if (cacheEntry == null) { cacheEntry = new GitModelCacheTree(this, baseCommit, repoId, cacheId, fullPath, factory); cacheTreeMap.put(pathKey, cacheEntry); } cacheEntry.addChild(repoId, cacheId, path.substring(firstSlash + 1)); } else cacheTreeMap.put(pathKey, factory.createFileModel(this, baseCommit, repoId, cacheId, fullPath)); }
Source:
<code>public void testFindDistinctChromosomesByStudyId() { List<String> chromosomeList = variantEntityRepository.findDistinctChromosomes(); List<String> expectedChromosomeList = new ArrayList<>(); expectedChromosomeList.add("11"); <START> assertEquals(expectedChromosomeList, chromosomeList); <END> }</code><technical_language>expectedChromsomeList declared Collections.singletonList("11"), assertEquals (or if prefer for readibility). This is small method is necessary here, in bigger test methods reducing number of lines improves readibility</technical_language>

Target:
public void testFindDistinctChromosomesByStudyId() { List<String> chromosomeList = variantEntityRepository.findDistinctChromosomes(); List<String> expectedChromosomeList = new ArrayList<>(); expectedChromosomeList.add("11"); expectedChromosomeList.add("9"); expectedChromosomeList.add("2"); assertEquals(expectedChromosomeList, chromosomeList); }
Source:
<code>public ObjectStat statObject(String bucketName, String objectName, ServerSideEncryption sse) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException { <START> if ((sse.getType().toString().equals("SSE_S3")) <END> || (sse.getType().toString().equals("SSE_KMS"))) { throw new InvalidArgumentException("Encryption type is not supported for this operation."); } else if ((sse.getType().toString().equals("SSE_C")) && (!this.baseUrl.isHttps())) { throw new InvalidArgumentException("SSE_C provided keys must be made over a secure connection."); } else { Map<String, String> headers = new HashMap<>(); sse.marshal(headers); HttpResponse response = executeHead(bucketName, objectName, headers); ResponseHeader header = response.header(); Map<String,List<String>> httpHeaders = response.httpHeaders(); ObjectStat objectStat = new ObjectStat(bucketName, objectName, header, httpHeaders); return objectStat; } }</code><technical_language>sse.getType() == ServerSideEnccryption.SSE_S3 enum. need string conversion</technical_language>

Target:
public ObjectStat statObject(String bucketName, String objectName, ServerSideEncryption sse) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException { if ((sse.getType() == ServerSideEncryption.Type.SSE_S3) || (sse.getType() == ServerSideEncryption.Type.SSE_KMS)) { throw new InvalidArgumentException("StatObject doesn't support encryption type " + sse.getType()); } else if ((sse.getType() == ServerSideEncryption.Type.SSE_C) && (!this.baseUrl.isHttps())) { throw new InvalidArgumentException("SSE_C operations must be performed over a secure connection."); } Map<String, String> headers = new HashMap<>(); sse.marshal(headers); HttpResponse response = executeHead(bucketName, objectName, headers); ResponseHeader header = response.header(); Map<String,List<String>> httpHeaders = response.httpHeaders(); ObjectStat objectStat = new ObjectStat(bucketName, objectName, header, httpHeaders); return objectStat; }
Source:
<code>public void addMetacardType(MetacardType metacardType) { <START> <END> metacardType .getAttributeDescriptors() .forEach( attribute -> { countedFieldsCache .computeIfAbsent(attribute.getName(), key -> new AtomicInteger(0)) .incrementAndGet(); addToFieldsCache(attribute); }); metacardType .getAttributeDescriptors() .stream() .filter(descriptor -> BasicTypes.STRING_TYPE.equals(descriptor.getType())) .map(stringDescriptor -> stringDescriptor.getName() + SchemaFields.TEXT_SUFFIX) .forEach(fieldName -> anyTextFieldsCache.add(fieldName)); }</code><technical_language>Space</technical_language>

Target:
public void addMetacardType(MetacardType metacardType) { metacardType.getAttributeDescriptors().forEach(this::addToFieldsCache); metacardType .getAttributeDescriptors() .stream() .filter(descriptor -> BasicTypes.STRING_TYPE.equals(descriptor.getType())) .map(stringDescriptor -> stringDescriptor.getName() + SchemaFields.TEXT_SUFFIX) .forEach(fieldName -> anyTextFieldsCache.add(fieldName)); }