auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void resetProfile() { this.profile = new Profile(); this.profile.setBirthday(LocalDate.parse("2000-01-01")); }

Target:
public void resetProfile() { this.profile = new Profile(); this.profile.setBirthday(LocalDate.now()); }
Source:
public void tearDown() { try { Case.closeCurrentCase(); try { Thread.sleep(2000); } catch (InterruptedException ex) { } FileUtils.deleteDirectory(CASE_DIR); } catch (CaseActionException | IOException ex) { Exceptions.printStackTrace(ex); } assertFalse(CASE_DIR.exists()); }

Target:
public void tearDown() { try { Case.closeCurrentCase(); } catch (CaseActionException ex) { Exceptions.printStackTrace(ex); } }
Source:
public void aggregate() { long time = timeSelector.getLong(); if (time < firstTime) { firstTime = time; Object value = valueSelector.getObject(); if (value instanceof String) { firstValue = (String) value; } else if (value instanceof SerializablePairLongString) { firstValue = ((SerializablePairLongString) value).rhs; } else if (value != null) { throw new IllegalStateException( "Try to aggregate unsuported class type [" + value.getClass().getName() + "]. Supported class types: String or SerializablePairLongString" ); } if (firstValue != null && firstValue.length() > maxStringBytes) { firstValue = firstValue.substring(0, maxStringBytes); } } }

Target:
public void aggregate() { long time = timeSelector.getLong(); if (time < firstTime) { firstTime = time; Object value = valueSelector.getObject(); if (value != null) { if (value instanceof String) { firstValue = (String) value; } else if (value instanceof SerializablePairLongString) { firstValue = ((SerializablePairLongString) value).rhs; } else { throw new ISE( "Try to aggregate unsuported class type [%s].Supported class types: String or SerializablePairLongString", value.getClass().getCanonicalName() ); } if (firstValue != null && firstValue.length() > maxStringBytes) { firstValue = firstValue.substring(0, maxStringBytes); } } else { firstValue = null; } } }
Source:
public void cancelTransference(OCFile file) { Account account = mFileActivity.getAccount(); FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder(); FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder(); if (downloaderBinder != null) { if (downloaderBinder.isDownloading(account, file)) { if (file.keepInSync()) { OCFile parent = mFileActivity.getStorageManager().getFileById(file.getParentId()); parent.setEtag(""); mFileActivity.getStorageManager().saveFile(parent); } downloaderBinder.cancel(account, file); } else { Log_OC.d(TAG, "Download for " + file + " not in progress. Cannot cancel " + file); } } if (uploaderBinder != null) { if (uploaderBinder.isUploading(account, file)) { uploaderBinder.cancel(account, file); } else { Log_OC.d(TAG, "Upload for " + file + " not in progress. Cannot cancel."); } } if(downloaderBinder == null && uploaderBinder == null) { Log_OC.w(TAG, "Neither downloaderBinder nor uploaderBinder set. Cannot cancel."); } }

Target:
public void cancelTransference(OCFile file) { Account account = mFileActivity.getAccount(); if (file.isFolder()) { OperationsService.OperationsServiceBinder opsBinder = mFileActivity.getOperationsServiceBinder(); if (opsBinder != null) { opsBinder.cancel(account, file); } } FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder(); FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder(); if (downloaderBinder != null) { if (downloaderBinder.isDownloading(account, file)) { if (file.isFavorite()) { OCFile parent = mFileActivity.getStorageManager().getFileById(file.getParentId()); parent.setEtag(""); mFileActivity.getStorageManager().saveFile(parent); } downloaderBinder.cancel(account, file); } else { Log_OC.d(TAG, "Download for " + file + " not in progress. Cannot cancel " + file); } } if (uploaderBinder != null) { if (uploaderBinder.isUploading(account, file)) { uploaderBinder.cancel(account, file); } else { Log_OC.d(TAG, "Upload for " + file + " not in progress. Cannot cancel."); } } if(downloaderBinder == null && uploaderBinder == null) { Log_OC.w(TAG, "Neither downloaderBinder nor uploaderBinder set. Cannot cancel."); } }
Source:
private void persistCleanupToken() throws IOException, StoreException { if (endToken == null || ((StoreFindToken) endToken).isUninitialized()) { return; } final Timer.Context context = metrics.cleanupTokenFlushTime.time(); File tempFile = new File(dataDir, Cleanup_Token_Filename + ".tmp"); File actual = new File(dataDir, Cleanup_Token_Filename); FileOutputStream fileStream = new FileOutputStream(tempFile); CrcOutputStream crc = new CrcOutputStream(fileStream); DataOutputStream writer = new DataOutputStream(crc); try { writer.writeShort(version); writer.write(startTokenSafeToPersist.toBytes()); writer.write(endToken.toBytes()); writer.write(hardDeleteRecoveryRange.toBytes()); long crcValue = crc.getValue(); writer.writeLong(crcValue); fileStream.getChannel().force(true); tempFile.renameTo(actual); } catch (IOException e) { throw new StoreException("IO error while persisting cleanup tokens to disk " + tempFile.getAbsoluteFile(), StoreErrorCodes.IOError); } finally { writer.close(); context.stop(); } logger.debug("Completed writing cleanup tokens to file {}", actual.getAbsolutePath()); }

Target:
private void persistCleanupToken() throws IOException, StoreException { if (endToken == null || ((StoreFindToken) endToken).isUninitialized()) { return; } final Timer.Context context = metrics.cleanupTokenFlushTime.time(); File tempFile = new File(dataDir, Cleanup_Token_Filename + ".tmp"); File actual = new File(dataDir, Cleanup_Token_Filename); FileOutputStream fileStream = new FileOutputStream(tempFile); CrcOutputStream crc = new CrcOutputStream(fileStream); DataOutputStream writer = new DataOutputStream(crc); try { writer.writeShort(Cleanup_Token_Version_V1); writer.write(startTokenSafeToPersist.toBytes()); writer.write(endToken.toBytes()); writer.write(hardDeleteRecoveryRange.toBytes()); long crcValue = crc.getValue(); writer.writeLong(crcValue); fileStream.getChannel().force(true); tempFile.renameTo(actual); } catch (IOException e) { throw new StoreException("IO error while persisting cleanup tokens to disk " + tempFile.getAbsoluteFile(), StoreErrorCodes.IOError); } finally { writer.close(); context.stop(); } logger.debug("Completed writing cleanup tokens to file {}", actual.getAbsolutePath()); }
Source:
private void checkExtendedAttributesSupport() { if (isMacOSX()) { throw new SkipException("filesystem does not support extended attributes on Mac OSX"); } }

Target:
protected void checkExtendedAttributesSupport() { if (isMacOSX()) { throw new SkipException("filesystem does not support extended attributes in Mac OSX"); } }
Source:
public void connect(IDocument doc) { document = doc; document.setDocumentPartitioner(this); lld = document.getLegalLineDelimiters(); partitions.clear(); pendingPartitions.clear(); inputPartitions = new ArrayList<>(); queueJob = new QueueProcessingJob(); queueJob.setSystem(true); queueJob.setPriority(Job.INTERACTIVE); queueJob.setRule(console.getSchedulingRule()); }

Target:
public void connect(IDocument doc) { if (doc == document) { return; } synchronized (partitions) { disconnect(); if (doc != null) { inputPartitions = new ArrayList<>(); document = doc; lld = document.getLegalLineDelimiters(); if (lld == null) { lld = new String[0]; } } } }
Source:
public void notifyTableChanged(String dbName, String tableName, long updateTime) { LOG.debug("Table changed: {}.{}, at {}", dbName, tableName, updateTime); List<CacheEntry> entriesToInvalidate = null; rwLock.writeLock().lock(); try { String key = TableName.getDbTable(dbName, tableName).toLowerCase(); Set<CacheEntry> entriesForTable = tableToEntryMap.get(key); if (entriesForTable != null) { entriesToInvalidate = new ArrayList<>(entriesForTable); } if (entriesToInvalidate != null) { for (CacheEntry entry : entriesToInvalidate) { if (entry.getQueryInfo().getQueryTime() <= updateTime) { removeEntry(entry); } } } } finally { rwLock.writeLock().unlock(); } }

Target:
public void notifyTableChanged(String dbName, String tableName, long updateTime) { LOG.debug("Table changed: {}.{}, at {}", dbName, tableName, updateTime); List<CacheEntry> entriesToInvalidate = null; rwLock.writeLock().lock(); try { String key = (dbName.toLowerCase() + "." + tableName.toLowerCase()); Set<CacheEntry> entriesForTable = tableToEntryMap.get(key); if (entriesForTable != null) { entriesToInvalidate = new ArrayList<>(entriesForTable); } if (entriesToInvalidate != null) { for (CacheEntry entry : entriesToInvalidate) { if (entry.getQueryInfo().getQueryTime() <= updateTime) { removeEntry(entry); } } } } finally { rwLock.writeLock().unlock(); } }
Source:
private String deployVlan(final String networkDomainId, final String vlanName, final DimensionDataCloudControlTemplateOptions templateOptions) { logger.debug("Creating a vlan %s in network domain '%s' ...", vlanName, networkDomainId); String defaultPrivateIPv4BaseAddress = firstNonNull(templateOptions.getDefaultPrivateIPv4BaseAddress(), DEFAULT_PRIVATE_IPV4_BASE_ADDRESS); Integer defaultPrivateIPv4PrefixSize = firstNonNull(templateOptions.getDefaultPrivateIPv4PrefixSize(), DEFAULT_PRIVATE_IPV4_PREFIX_SIZE); String vlanId = api.getNetworkApi() .deployVlan(networkDomainId, vlanName, "vlan created by jclouds", defaultPrivateIPv4BaseAddress, defaultPrivateIPv4PrefixSize); boolean isVlanReady = retry(new VlanState(api.getNetworkApi(), State.NORMAL), timeouts.nodeRunning).apply(vlanId); if (!isVlanReady) { String message = format("vlan(%s) is not ready within %d ms.", vlanId, timeouts.nodeRunning); throw new IllegalStateException(message); } return vlanId; }

Target:
private String deployVlan(final String networkDomainId, final String vlanName, final DimensionDataCloudControlTemplateOptions templateOptions) { logger.debug("Creating a vlan %s in network domain '%s' ...", vlanName, networkDomainId); String defaultPrivateIPv4BaseAddress = firstNonNull(templateOptions.getDefaultPrivateIPv4BaseAddress(), DimensionDataCloudControlTemplateOptions.DEFAULT_PRIVATE_IPV4_BASE_ADDRESS); Integer defaultPrivateIPv4PrefixSize = firstNonNull(templateOptions.getDefaultPrivateIPv4PrefixSize(), DimensionDataCloudControlTemplateOptions.DEFAULT_PRIVATE_IPV4_PREFIX_SIZE); String vlanId = api.getNetworkApi() .deployVlan(networkDomainId, vlanName, "vlan created by jclouds", defaultPrivateIPv4BaseAddress, defaultPrivateIPv4PrefixSize); if (!vlanNormalPredicate.apply(vlanId)) { String message = format("vlan(%s) is not ready within %d ms.", vlanId, timeouts.nodeRunning); throw new IllegalStateException(message); } return vlanId; }
Source:
public void delete(E plugin) { ApplicationService<Application, ApplicationDao<Application>> appService = this.applicationService; if (appService == null) { LOG.error("Plugin cannot be deleted, failed to autowire application service"); return; } List<Application> apps = appService.findAll(); Integer pluginId = plugin.getId(); for (Application app : apps) { List<Plugin> plugins = app.getPlugins(); if (plugins != null && plugins.contains(plugin)) { if (LOG.isDebugEnabled()) { String msg = String.format( "Remove plugin (id=%s) from application (id=%s)", pluginId, app.getId() ); LOG.debug(msg); } plugins.remove(plugin); appService.saveOrUpdate(app); } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Delete plugin (id=%s)", pluginId)); } super.delete(plugin); }

Target:
public void delete(E plugin) { if (applicationService == null) { LOG.error("Plugin cannot be deleted, failed to autowire application service"); return; } List<Application> apps = applicationService.findAll(); Integer pluginId = plugin.getId(); for (Application app : apps) { List<Plugin> plugins = app.getPlugins(); if (plugins != null && plugins.contains(plugin)) { String msg = String.format( "Remove plugin (id=%s) from application (id=%s)", pluginId, app.getId() ); LOG.debug(msg); plugins.remove(plugin); applicationService.saveOrUpdate(app); } } LOG.debug(String.format("Delete plugin (id=%s)", pluginId)); super.delete(plugin); }
Source:
private Host getHostFromSession(final HttpServletRequest request, final User user, final PageMode mode) throws DotSecurityException, DotDataException { final Object hostId = request.getSession().getAttribute(WebKeys.CMS_SELECTED_HOST_ID); if(mode.isAdmin && hostId !=null) { return this.hostAPI.find(hostId.toString(), user, mode.respectAnonPerms); } else { return null; } }

Target:
private Optional<Host> getHostFromSession(final HttpServletRequest request, final User user, final PageMode mode) throws DotSecurityException, DotDataException { final Object hostId = request.getSession().getAttribute(WebKeys.CMS_SELECTED_HOST_ID); if(mode.isAdmin && hostId !=null) { final Host host = this.hostAPI.find(hostId.toString(), user, mode.respectAnonPerms); return Optional.ofNullable(host); } else { return Optional.empty(); } }
Source:
public void evenTheSecundaryNameIsTaken() { doReturn(mock(Repository.class)).when(repositoryService).getRepositoryFromSpace(any(Space.class), eq("module1")); doReturn(mock(Repository.class)).when(repositoryService).getRepositoryFromSpace(any(Space.class), eq("module1-1")); String module = "module1"; String module_1 = "module1 [1]"; String module_2 = "module1 [2]"; doReturn(module_2).when(projectService).createProjectName(any(), eq(module)); WorkspaceProject project1 = mock(WorkspaceProject.class); doReturn(module).when(project1).getName(); List<WorkspaceProject> projects1 = new ArrayList<>(); projects1.add(project1); projects1.add(project1); doReturn(projects1).when(projectService).getAllWorkspaceProjectsByName(any(), eq("module1")); WorkspaceProject project2 = mock(WorkspaceProject.class); doReturn(module_1).when(project2).getName(); List<WorkspaceProject> projects2 = new ArrayList<>(); projects2.add(project2); doReturn(projects2).when(projectService).getAllWorkspaceProjectsByName(any(), eq(module_1)); service.setupExamples(exampleOrganizationalUnit, exampleProjects); verify(projectScreenService).save(any(), modelCapture.capture(), any()); final ProjectScreenModel model = modelCapture.getValue(); assertEquals(module_2, model.getPOM().getName()); }

Target:
public void evenTheSecundaryNameIsTaken() { String module = "module1"; String module_1 = "module1 [1]"; String module_2 = "module1 [2]"; doReturn(mock(Repository.class)).when(repositoryService).getRepositoryFromSpace(any(Space.class), eq(module)); doReturn(mock(Repository.class)).when(repositoryService).getRepositoryFromSpace(any(Space.class), eq(module_1)); doReturn(module_2).when(projectService).createFreshProjectName(any(), eq(module)); WorkspaceProject project1 = mock(WorkspaceProject.class); doReturn(module).when(project1).getName(); List<WorkspaceProject> projects1 = new ArrayList<>(); projects1.add(project1); projects1.add(project1); doReturn(projects1).when(projectService).getAllWorkspaceProjectsByName(any(), eq(module)); WorkspaceProject project2 = mock(WorkspaceProject.class); doReturn(module_1).when(project2).getName(); List<WorkspaceProject> projects2 = new ArrayList<>(); projects2.add(project2); doReturn(projects2).when(projectService).getAllWorkspaceProjectsByName(any(), eq(module_1)); service.setupExamples(exampleOrganizationalUnit, exampleProjects); verify(projectScreenService).save(any(), modelCapture.capture(), any()); final ProjectScreenModel model = modelCapture.getValue(); assertEquals(module_2, model.getPOM().getName()); }
Source:
public void open() { session.getUiElements().getMenu().openMenu(MainMenu.PERUN_ADMIN); session.getUiElements().getBreadcrumbs().setLocation(0, "edit_keys", getUrlWithParameters()); }

Target:
public void open() { session.getUiElements().getMenu().openMenu(MainMenu.PERUN_ADMIN); session.getUiElements().getBreadcrumbs().setLocation(0, "Entityless attributes setting", getUrlWithParameters()); }
Source:
public void register(String name, HealthCheck healthCheck) { HealthCheck registered = null; synchronized (lock) { if (!healthChecks.containsKey(name)) { registered = healthCheck; if (healthCheck.getClass().isAnnotationPresent(Async.class)) { registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); } healthChecks.put(name, registered); } } if (registered == null) { throw new IllegalArgumentException("A health check named " + name + " already exists"); } else { onHealthCheckAdded(name, registered); } }

Target:
public void register(String name, HealthCheck healthCheck) { HealthCheck registered; synchronized (lock) { if (healthChecks.containsKey(name)) { throw new IllegalArgumentException("A health check named " + name + " already exists"); } registered = healthCheck; if (healthCheck.getClass().isAnnotationPresent(Async.class)) { registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); } healthChecks.put(name, registered); } onHealthCheckAdded(name, registered); }
Source:
public static void displayWarningMsg(Throwable exception) { final String warningMsg = exception.getMessage(); Display.getDefault().asyncExec(() -> { final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); Activator.getDefault().logWarning(warningMsg, exception); MessageDialog.openError(shell, exception.getClass().getSimpleName(), warningMsg); }); }

Target:
public static void displayWarningMsg(Throwable exception) { final String warningMsg = exception.getMessage(); Display.getDefault().asyncExec(() -> { final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); Activator.getDefault().logWarning(warningMsg, exception); MessageDialog.openWarning(shell, exception.getClass().getSimpleName(), warningMsg); }); }
Source:
public void test(TestHarness th) { try { String dirPath = System.getProperty("fileconn.dir.private").substring(2); FileConnection dir = (FileConnection)Connector.open(dirPath); th.check(dir.isOpen(), "Directory opened"); th.check(dir.exists(), "Directory exists"); th.check(dir.isDirectory(), "Directory is a directory"); Enumeration files = dir.list(); th.check(!files.hasMoreElements(), "Directory is empty"); FileConnection file = (FileConnection)Connector.open(dirPath + "prova"); th.check(file.isOpen(), "File opened"); th.check(!file.exists(), "File doesn't exist"); th.check(!file.isDirectory(), "File isn't a directory"); file.create(); th.check(file.exists(), "File created"); th.check(!file.isDirectory(), "Check is directory"); th.check(file.fileSize(), 0, "Check file size"); OutputStream out = file.openOutputStream(); out.write(new byte[]{ 5, 4, 3, 2, 1 }); out.close(); th.check(file.fileSize(), 5); InputStream in = file.openInputStream(); th.check(in.read(), 5); th.check(in.read(), 4); th.check(in.read(), 3); th.check(in.read(), 2); th.check(in.read(), 1); th.check(in.read(), -1); in.close(); file.close(); th.check(!file.isOpen()); files = dir.list(); th.check(files.hasMoreElements(), "Directory has one file"); th.check(files.nextElement(), "/prova"); th.check(!files.hasMoreElements(), "Directory has just one file"); dir.close(); th.check(!dir.isOpen()); } catch (Exception e) { th.fail("Unexpected exception"); e.printStackTrace(); } }

Target:
public void test(TestHarness th) { try { String dirPath = System.getProperty("fileconn.dir.private").substring(2); FileConnection dir = (FileConnection)Connector.open(dirPath); th.check(dir.isOpen(), "Directory opened"); th.check(dir.exists(), "Directory exists"); th.check(dir.isDirectory(), "Directory is a directory"); Enumeration files = dir.list(); th.check(!files.hasMoreElements(), "Directory is empty"); FileConnection file = (FileConnection)Connector.open(dirPath + "prova"); th.check(file.isOpen(), "File opened"); th.check(!file.exists(), "File doesn't exist"); th.check(!file.isDirectory(), "File isn't a directory"); file.create(); th.check(file.exists(), "File created"); th.check(!file.isDirectory(), "Check is directory"); th.check(file.fileSize(), 0, "Check file size"); OutputStream out = file.openOutputStream(); out.write(new byte[]{ 5, 4, 3, 2, 1 }); out.close(); th.check(file.fileSize(), 5); InputStream in = file.openInputStream(); th.check(in.read(), 5); th.check(in.read(), 4); th.check(in.read(), 3); th.check(in.read(), 2); th.check(in.read(), 1); th.check(in.read(), -1); in.close(); file.close(); th.check(!file.isOpen()); files = dir.list(); th.check(files.hasMoreElements(), "Directory has one file"); th.check(files.nextElement(), "/prova"); th.check(!files.hasMoreElements(), "Directory has just one file"); dir.close(); th.check(!dir.isOpen()); } catch (Exception e) { th.fail("Unexpected exception: " + e); e.printStackTrace(); } }
Source:
public CharSeq leftPadTo(int length, Character element) { if (length <= back.length()) { return this; } final StringBuilder sb = new StringBuilder(padding(element, length - back.length())).append(back); return new CharSeq(sb.toString()); }

Target:
public CharSeq leftPadTo(int length, Character element) { final int actualLength = back.length(); if (length <= actualLength) { return this; } else { final StringBuilder sb = padding(element, length - actualLength).append(back); return new CharSeq(sb.toString()); } }
Source:
public void updateEndpoints(List<WebServiceEndpoint> endpoints) { dataProvider.setList(endpoints); sortHandler.setList(dataProvider.getList()); ColumnSortEvent.fire(table, table.getColumnSortList()); table.selectDefaultEntity(); SingleSelectionModel<WebServiceEndpoint> selectionModel = (SingleSelectionModel<WebServiceEndpoint>) table.getSelectionModel(); WebServiceEndpoint selection = selectionModel.getSelectedObject(); sampler.addSample( new Metric( selection.getRequestCount(), selection.getResponseCount(), selection.getFaultCount() )); }

Target:
public void updateEndpoints(List<WebServiceEndpoint> endpoints) { dataProvider.setList(endpoints); sortHandler.setList(dataProvider.getList()); ColumnSortEvent.fire(table, table.getColumnSortList()); table.selectDefaultEntity(); WebServiceEndpoint selection = selectionModel.getSelectedObject(); addSample(selection); }
Source:
private void assertBaseline(String content, int baselineSz, int srvsSz) throws IOException { assertNotNull(content); assertFalse(content.isEmpty()); JsonNode node = JSON_MAPPER.readTree(content); assertEquals(STATUS_SUCCESS, node.get("successStatus").asInt()); assertTrue(node.get("error").isNull()); assertNotSame(securityEnabled(), node.get("sessionToken").isNull()); JsonNode res = node.get("response"); assertFalse(res.isNull()); GridBaselineCommandResponse baseline = JSON_MAPPER.treeToValue(res, GridBaselineCommandResponse.class); assertTrue(baseline.isActive()); assertEquals(grid(0).cluster().topologyVersion(), baseline.getTopologyVersion()); assertEquals(baselineSz, baseline.getBaseline().size()); assertEqualsCollections(consistentIdMapper(grid(0).cluster().currentBaselineTopology()), new HashSet<>(baseline.getBaseline())); assertEquals(srvsSz, baseline.getServers().size()); assertEqualsCollections(consistentIdMapper(grid(0).cluster().nodes()), new HashSet<>(baseline.getServers())); }

Target:
private void assertBaseline(String content, int baselineSz, int srvsSz) throws IOException { assertNotNull(content); assertFalse(content.isEmpty()); JsonNode node = JSON_MAPPER.readTree(content); assertEquals(STATUS_SUCCESS, node.get("successStatus").asInt()); assertTrue(node.get("error").isNull()); assertNotSame(securityEnabled(), node.get("sessionToken").isNull()); JsonNode res = node.get("response"); assertFalse(res.isNull()); GridBaselineCommandResponse baseline = JSON_MAPPER.treeToValue(res, GridBaselineCommandResponse.class); assertTrue(baseline.isActive()); assertEquals(grid(0).cluster().topologyVersion(), baseline.getTopologyVersion()); assertEquals(baselineSz, baseline.getBaseline().size()); assertEqualsCollections(nodeConsistentIds(grid(0).cluster().currentBaselineTopology()), baseline.getBaseline()); assertEquals(srvsSz, baseline.getServers().size()); assertEqualsCollections(nodeConsistentIds(grid(0).cluster().nodes()), baseline.getServers()); }
Source:
public void testSaveOrUpdateExisting() { int sizeBeforeSave = dao.getAll().size(); existingUser.setFirstName("changedname"); existingUser.setLastName("changedsurname"); int sizeAfterSave = dao.getAll().size(); dao.saveOrUpdate(existingUser); DbUser result = dao.get(existingUser.getId()); assertEquals(existingUser, result); assertEquals(0, sizeAfterSave - sizeBeforeSave); }

Target:
public void testSaveOrUpdateExisting() { int sizeBeforeSave = dao.getAll().size(); existingUser.setFirstName("changedname"); existingUser.setLastName("changedsurname"); dao.saveOrUpdate(existingUser); int sizeAfterSave = dao.getAll().size(); DbUser result = dao.get(existingUser.getId()); assertEquals(existingUser, result); assertEquals(0, sizeAfterSave - sizeBeforeSave); }
Source:
private String generateNewAnonID() { String uuid = UUID.randomUUID().toString(); String[] uuidSplitted = uuid.split("-"); StringBuilder builder = new StringBuilder(); for (String currentPart : uuidSplitted) { builder.append(currentPart); } uuid = builder.toString(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); final SharedPreferences.Editor editor = preferences.edit(); editor.putString(TRACKS_ANON_ID, uuid); editor.apply(); mAnonID = uuid; return uuid; }

Target:
private String generateNewAnonID() { String uuid = UUID.randomUUID().toString(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); final SharedPreferences.Editor editor = preferences.edit(); editor.putString(TRACKS_ANON_ID, uuid); editor.apply(); mAnonID = uuid; return uuid; }
Source:
MMappedIndexRowIterable( Iterable<Rowboat> index, List<String> convertedDims, Map<String, IntBuffer> converters, int indexNumber ) { this.index = index; this.convertedDims = convertedDims; this.converters = converters; this.indexNumber = indexNumber; this.converterArray = new IntBuffer[convertedDims.size()]; for(int i = 0; i < convertedDims.size(); ++i){ this.converterArray[i] = converters.get(convertedDims.get(i)); } }

Target:
MMappedIndexRowIterable( Iterable<Rowboat> index, List<String> convertedDims, Map<String, IntBuffer> converters, int indexNumber ) { this.index = index; this.convertedDims = convertedDims; this.converters = converters; this.indexNumber = indexNumber; }
Source:
private String getDstRef(Repository repo, boolean launchFetch) { if (launchFetch) { String realName = getRealBranchName(repo); String name = BRANCH_NAME_PATTERN.matcher(realName).replaceAll(""); String remote = repo.getConfig().getString(CONFIG_BRANCH_SECTION, name, CONFIG_KEY_REMOTE); String merge = repo.getConfig().getString(CONFIG_BRANCH_SECTION, name, CONFIG_KEY_MERGE); String mergeBranchName = merge.substring( merge.lastIndexOf("/"), merge.length()); return R_REMOTES + remote + mergeBranchName; } else return HEAD; }

Target:
private String getDstRef(Repository repo, boolean launchFetch) { if (launchFetch) { String realName = getRealBranchName(repo); String name = BRANCH_NAME_PATTERN.matcher(realName).replaceAll(""); StoredConfig config = repo.getConfig(); String remote = config.getString(CONFIG_BRANCH_SECTION, name, CONFIG_KEY_REMOTE); String merge = config.getString(CONFIG_BRANCH_SECTION, name, CONFIG_KEY_MERGE); if (remote == null || merge == null) return HEAD; String mergeBranchName = merge.substring( merge.lastIndexOf("/"), merge.length()); return R_REMOTES + remote + mergeBranchName; } else return HEAD; }
Source:
private void doUpdate(Exchange exchange) { final Message msg = exchange.getIn(); final String id = msg.getHeader(CinderConstants.ID, msg.getHeader(CinderConstants.VOLUME_ID, String.class), String.class); final Volume vol = messageToVolume(msg); ; ObjectHelper.notEmpty(id, "Cinder Volume ID"); ObjectHelper.notEmpty(vol.getDescription(), "Cinder Volume Description"); ObjectHelper.notEmpty(vol.getName(), "Cinder Volume Name"); final ActionResponse out = os.blockStorage().volumes().update(id, vol.getName(), vol.getDescription()); checkFailure(out, msg, "Update volume " + id); }

Target:
private void doUpdate(Exchange exchange) { final Message msg = exchange.getIn(); final String id = msg.getHeader(CinderConstants.ID, msg.getHeader(CinderConstants.VOLUME_ID, String.class), String.class); final Volume vol = messageToVolume(msg); ObjectHelper.notEmpty(id, "Cinder Volume ID"); ObjectHelper.notEmpty(vol.getDescription(), "Cinder Volume Description"); ObjectHelper.notEmpty(vol.getName(), "Cinder Volume Name"); final ActionResponse out = os.blockStorage().volumes().update(id, vol.getName(), vol.getDescription()); checkFailure(out, msg, "Update volume " + id); }
Source:
public Object getValuePreferringCachedDeserializable() { checkEntryDestroyed(); Object v = this.regionEntry.getValue(null); if (v instanceof CachedDeserializable) { return v; } else { return getRawValue(); } }

Target:
public Object getValuePreferringCachedDeserializable() { checkEntryDestroyed(); Object value = regionEntry.getValue(null); if (value instanceof CachedDeserializable) { return value; } else { return getRawValue(); } }
Source:
private synchronized String requestOAuth2Token() throws ETSdkException { if (clientId == null || clientSecret == null) { return null; } logger.debug("requesting OAuth2 access token..."); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("client_id", clientId); jsonObject.addProperty("client_secret", clientSecret); jsonObject.addProperty("grant_type", "client_credentials"); String requestPayload = gson.toJson(jsonObject); ETRestConnection.Response response = null; response = authConnection.post(PATH_OAUTH2TOKEN, requestPayload); if (response.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new ETSdkException("error obtaining OAuth2 access token " + "(" + response.getResponseCode() + " " + response.getResponseMessage() + ")"); } String responsePayload = response.getResponsePayload(); JsonParser jsonParser = new JsonParser(); jsonObject = jsonParser.parse(responsePayload).getAsJsonObject(); logger.debug("received OAuth2 token:"); this.accessToken = jsonObject.get("access_token").getAsString(); logger.debug(" accessToken: " + this.accessToken); this.expiresIn = jsonObject.get("expires_in").getAsInt(); logger.debug(" expiresIn: " + this.expiresIn); this.endpoint = jsonObject.get("rest_instance_url").getAsString(); this.soapEndpoint = jsonObject.get("soap_instance_url").getAsString() + "service.asmx"; tokenExpirationTime = System.currentTimeMillis() + (expiresIn * 1000); logger.debug("access OAuth2 token expires at " + new Date(tokenExpirationTime)); return accessToken; }

Target:
private synchronized String requestOAuth2Token() throws ETSdkException { if (clientId == null || clientSecret == null) { return null; } JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("client_id", clientId); jsonObject.addProperty("client_secret", clientSecret); jsonObject.addProperty("grant_type", "client_credentials"); if(accountId != null && accountId.length() > 0) { jsonObject.addProperty("account_id", accountId); } if(scope != null && scope.length() > 0) { jsonObject.addProperty("scope", scope); } String requestPayload = gson.toJson(jsonObject); ETRestConnection.Response response = null; response = authConnection.post(PATH_OAUTH2TOKEN, requestPayload); if (response.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new ETSdkException("error obtaining OAuth2 access token " + "(" + response.getResponseCode() + " " + response.getResponseMessage() + ")"); } String responsePayload = response.getResponsePayload(); JsonParser jsonParser = new JsonParser(); jsonObject = jsonParser.parse(responsePayload).getAsJsonObject(); this.accessToken = jsonObject.get("access_token").getAsString(); this.expiresIn = jsonObject.get("expires_in").getAsInt(); this.endpoint = jsonObject.get("rest_instance_url").getAsString(); this.soapEndpoint = jsonObject.get("soap_instance_url").getAsString() + "service.asmx"; tokenExpirationTime = System.currentTimeMillis() + (expiresIn * 1000); return accessToken; }
Source:
private void setDefault(XProcOptionInfo info,Element element ){ String select=info.getSelect(); if (Strings.isNullOrEmpty(select)){ return; } char quote=select.charAt(0); if (quote!='"' && quote!='\''){ return; } if (select.charAt(select.length()-1)!=quote){ return; } String def=select.substring(1,select.length()-1); if (def.length()>0){ element.setAttribute("default",def); } }

Target:
private void setDefault(XProcOptionInfo info,Element element ){ String select=info.getSelect(); if (Strings.isNullOrEmpty(select)){ return; } char quote=select.charAt(0); if (quote!='"' && quote!='\''){ return; } if (select.charAt(select.length()-1)!=quote){ return; } String def=select.substring(1,select.length()-1); element.setAttribute("default",def); }
Source:
public static UNIT getById(final int id) { for (final UNIT e : values()) { if (e.value == id) { return e; } } return MI; }

Target:
public static DistanceUnit getById(final int id) { for (final DistanceUnit e : values()) { if (e.value == id) { return e; } } return MI; }
Source:
protected final IStateHistoryBackend prepareBackend(long startTime, long endTime, List<ITmfStateInterval> intervals) { try { fBackend = getBackendForBuilding(startTime); for (ITmfStateInterval interval : intervals) { fBackend.insertPastState(interval.getStartTime(), interval.getEndTime(), interval.getAttribute(), interval.getStateValue()); } fBackend.finishedBuilding(Math.max(endTime, fBackend.getEndTime())); IStateHistoryBackend backendForBuilding = fBackend; fBackend = null; fBackend = getBackendForQuerying(backendForBuilding); return fBackend; } catch (IOException e) { fail(e.toString()); return null; } }

Target:
protected final IStateHistoryBackend prepareBackend(long startTime, long endTime, List<ITmfStateInterval> intervals) { try { fBackend = getBackendForBuilding(startTime); insertIntervals(fBackend, intervals); fBackend.finishedBuilding(Math.max(endTime, fBackend.getEndTime())); IStateHistoryBackend backendForBuilding = fBackend; fBackend = null; fBackend = getBackendForQuerying(backendForBuilding); return fBackend; } catch (IOException e) { fail(e.toString()); return null; } }
Source:
public void filterTextFieldColor_validFilter_validFilterStyleApplied(){ FilterTextField field = getFirstPanelField(); clearField(); type("is:open"); assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); clearField(); type("-is:open"); assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); clearField(); type("hello"); assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); clearField(); type("is:open & has:assignee"); assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); clearField(); type("(is:closed)"); assertTrue(field.getStyle().contains(VALID_FILTER_STYLE)); }

Target:
public void filterTextFieldColor_validFilter_validFilterStyleApplied(){ testValidFilterStyleApplied("is:open"); testValidFilterStyleApplied("-is:open"); testValidFilterStyleApplied("hello"); testValidFilterStyleApplied("is:open & has:assignee"); testValidFilterStyleApplied("(is:closed)"); }
Source:
private boolean possibleToString(Class classExample) { return (classExample.isPrimitive() || classExample.getName().equals("java.lang.Integer") || classExample.getName().equals("java.lang.Boolean") || classExample.getName().equals("java.lang.String") || classExample.getName().equals("java.lang.Double") || classExample.getName().equals("java.lang.Float") || classExample.getName().equals("java.lang.Byte") || classExample.getName().equals("java.lang.Long") || classExample.getName().equals("java.lang.Short") || classExample.getName().equals("java.lang.Character") || classExample.isEnum()); }

Target:
private boolean possibleToString(Class classExample) { return (classExample.isPrimitive() || classExample.equals(Integer.class) || classExample.equals(Boolean.class) || classExample.equals(String.class) || classExample.equals(Double.class) || classExample.equals(Float.class) || classExample.equals(Byte.class) || classExample.equals(Long.class) || classExample.equals(Short.class) || classExample.equals(Character.class) || classExample.isEnum()); }
Source:
public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongObjectMap<LockResource> localLocks = localShared( resourceType ); for ( long resourceId : resourceIds ) { LockResource resource = localLocks.get( resourceId ); if ( resource.releaseReference() != 0 ) { return; } localLocks.remove( resourceId ); manager.releaseReadLock( new LockResource( resourceType, resourceId ), lockTransaction ); } } finally { stateHolder.decrementActiveClients(); } }

Target:
public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongObjectMap<LockResource> localLocks = localShared( resourceType ); for ( long resourceId : resourceIds ) { LockResource resource = localLocks.get( resourceId ); if ( resource.releaseReference() == 0 ) { localLocks.remove( resourceId ); manager.releaseReadLock( new LockResource( resourceType, resourceId ), lockTransaction ); } } } finally { stateHolder.decrementActiveClients(); } }
Source:
public void testIgnoreError() throws Exception { XMLParser.Config config = new XMLParser.Config("body", "UTF-8", "title:/book/title,author:/book/author," + "year:/book/year", "title:string,author:string,year:int", "Ignore error and continue"); Transform<StructuredRecord, StructuredRecord> transform = new XMLParser(config); transform.initialize(new MockTransformContext()); List<StructuredRecord> input = ImmutableList.of( StructuredRecord.builder(INPUT) .set("offset", 1) .set("body", "<book category=\"COOKING\"><title lang=\"en\">Everyday Italian</title>" + "<author>Giada De Laurentiis</author><year>null</year><price>30.00</price></book>").build(), StructuredRecord.builder(INPUT) .set("offset", 2) .set("body", "<book category=\"children\"><title lang=\"en\">Harry Potter</title>" + "<author>J K. Rowling</author><year>2005</year><price>49.99</price></book>").build()); MockEmitter<StructuredRecord> emitter = new MockEmitter<>(); for (StructuredRecord record : input) { transform.transform(record, emitter); } Assert.assertEquals(1, emitter.getEmitted().size()); Assert.assertEquals(0, emitter.getErrors().size()); StructuredRecord record = emitter.getEmitted().get(0); Assert.assertEquals("Harry Potter", record.get("title")); Assert.assertEquals("J K. Rowling", record.get("author")); Assert.assertEquals(2005, record.get("year")); }

Target:
public void testIgnoreError() throws Exception { XMLParser.Config config = new XMLParser.Config("body", "ISO-8859-1", "title:/book/title,author:/book/author," + "year:/book/year", "title:string,author:string,year:int", "Ignore error and continue"); Transform<StructuredRecord, StructuredRecord> transform = new XMLParser(config); transform.initialize(new MockTransformContext()); List<StructuredRecord> input = ImmutableList.of( StructuredRecord.builder(INPUT) .set("offset", 1) .set("body", "<book category=\"COOKING\"><title lang=\"en\">Everyday Italian</title>" + "<author>Giada De Laurentiis</author><year>null</year><price>30.00</price></book>").build(), StructuredRecord.builder(INPUT) .set("offset", 2) .set("body", "<book category=\"children\"><title lang=\"en\">Harry Potter</title>" + "<author>J K. Rowling</author><year>2005</year><price>49.99</price></book>").build()); MockEmitter<StructuredRecord> emitter = new MockEmitter<>(); for (StructuredRecord record : input) { transform.transform(record, emitter); } Assert.assertEquals(1, emitter.getEmitted().size()); Assert.assertEquals(0, emitter.getErrors().size()); StructuredRecord record = emitter.getEmitted().get(0); Assert.assertEquals("Harry Potter", record.get("title")); Assert.assertEquals("J K. Rowling", record.get("author")); Assert.assertEquals(2005, record.get("year")); }
Source:
public ModulusOffsetCalculator(int numBlocks) { int blocksMinusOne = numBlocks - 1; if (numBlocks <= 0 && (numBlocks & blocksMinusOne) == 0) { throw new IllegalArgumentException("maxOffset " + numBlocks + " must be greater than 0 and a power of 2"); } this.blocksMinusOne = blocksMinusOne; }

Target:
public ModulusOffsetCalculator(int numBlocks) { int blocksMinusOne = numBlocks - 1; if (numBlocks <= 0 || (numBlocks & blocksMinusOne) != 0) { throw new IllegalArgumentException("maxOffset " + numBlocks + " must be greater than 0 and a power of 2"); } this.blocksMinusOne = blocksMinusOne; }
Source:
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); RuntimePermissionUtils.onRequestPermissionsResult(this, requestCode, grantResults); }

Target:
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); RuntimePermissionUtils.onRequestPermissionsResult(this, requestCode, grantResults); }
Source:
private static boolean check4matchingAnyID(Logger logger, String idName, int requestID, int responseID) { logger.trace("check4matchingAnyID() called for request{} and response{} {}.", idName, requestID, idName, responseID); if (requestID != responseID) { logger.warn("Gateway response with unexpected as query asked for {}.", idName, requestID, idName, responseID); return false; } else { logger.trace("check4matchingAnyID() returns {}.", true); return true; } }

Target:
private static boolean check4matchingAnyID(Logger logger, String idName, int requestID, int responseID) { logger.trace("check4matchingAnyID() called for request{} and response{} {}.", idName, requestID, idName, responseID); if (requestID != responseID) { logger.warn("Gateway response with unexpected as query asked for {}.", idName, requestID, idName, responseID); return false; } logger.trace("check4matchingAnyID() returns {}.", true); return true; }
Source:
public void testNewImportStringLocations() throws Exception { DispoItemData dispoItem = new DispoItemData(); boolean stoppedParsing = false; String name = "sampleTmoStrings.tmo"; URL resource = getClass().getResource(name); InputStream stream = null; try { stream = new BufferedInputStream(resource.openStream()); stoppedParsing = DiscrepancyParser.buildItemFromFile(dispoItem, name, stream, false, new Date(0)); } finally { Lib.close(stream); } int actualLength = dispoItem.getDiscrepanciesList().size(); Assert.assertEquals(6, actualLength); Assert.assertFalse(stoppedParsing); Map<String, Discrepancy> discrepanciesList = dispoItem.getDiscrepanciesList(); Collection<Discrepancy> values = discrepanciesList.values(); Discrepancy discrepancy13 = null; for (Discrepancy discrepancy : values) { String loc = discrepancy.getLocation(); if (loc.equals("Thirteen")) { discrepancy13 = discrepancy; break; } } String actualText = discrepancy13.getText(); Assert.assertEquals("Failure at Test Point Thirteen. Check Point: Boo_READY5. Expected: WT[1]. Actual: WT [0]. ", actualText); Discrepancy discrepancy12 = null; for (Discrepancy discrepancy : values) { String loc = discrepancy.getLocation(); if (loc.equals("Fourteen")) { discrepancy12 = discrepancy; break; } } actualText = discrepancy12.getText(); Assert.assertEquals( "Failure at Test Point Fourteen. Check Group with Checkpoint Failures: " + "Check Point: pokemon. Expected: charmander. Actual: squirtle. " + "Check Point: superman. Expected: unbeatable. Actual: kryptonite. " + "Check Point: Nicest Guy Ever. Expected: Bob Ross. Actual: Bob Ross. " + "Check Point: Things fail. Expected: sometimes. Actual: A lot. ", actualText); }

Target:
public void testNewImportStringLocations() throws Exception { DispoItemData dispoItem = new DispoItemData(); boolean stoppedParsing = false; String name = "sampleTmoStrings.tmo"; URL resource = getClass().getResource(name); InputStream stream = null; try { stream = new BufferedInputStream(resource.openStream()); stoppedParsing = DiscrepancyParser.buildItemFromFile(dispoItem, name, stream, false, new Date(0)); } finally { Lib.close(stream); } int actualLength = dispoItem.getDiscrepanciesList().size(); Assert.assertEquals(6, actualLength); Assert.assertFalse(stoppedParsing); Map<String, Discrepancy> discrepanciesList = dispoItem.getDiscrepanciesList(); Collection<Discrepancy> values = discrepanciesList.values(); Discrepancy discrepancy13 = null; for (Discrepancy discrepancy : values) { String loc = discrepancy.getLocation(); if (loc.equals("Thirteen")) { discrepancy13 = discrepancy; break; } } String actualText = discrepancy13.getText(); Assert.assertEquals(String.format(thirtneenFailure, "Thirteen"), actualText); Discrepancy discrepancy12 = null; for (Discrepancy discrepancy : values) { String loc = discrepancy.getLocation(); if (loc.equals("Fourteen")) { discrepancy12 = discrepancy; break; } } actualText = discrepancy12.getText(); Assert.assertEquals(String.format(fourteenFailure, "Fourteen"), actualText); }
Source:
public void log(IStatus status) { log(0, status); if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); for (IStatus children1 : children) { log(1, children1); } } }

Target:
public void log(IStatus status) { log(0, status); if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); for (IStatus child : children) { log(1, child); } } }
Source:
public Map<String, String> buildAndVerifyContext(Function<String, Value> parameterProvider, boolean enforceRequiredParameters, Consumer<HandledException> errorConsumer) { Map<String, String> context = new HashMap<>(); for (Parameter<?, ?> parameter : getParameters()) { try { Value contextValue = parameterProvider.apply(parameter.getName()); if (enforceRequiredParameters && !contextValue.isFilled() && parameter.isRequired()) { errorConsumer.accept(Exceptions.createHandled() .withNLSKey("Parameter.required") .set("name", parameter.getLabel()) .handle()); } else { String value = parameter.checkAndTransform(contextValue); context.put(parameter.getName(), value); } } catch (HandledException e) { errorConsumer.accept(e); } } return context; }

Target:
public Map<String, String> buildAndVerifyContext(Function<String, Value> parameterProvider, boolean enforceRequiredParameters, Consumer<HandledException> errorConsumer) { Map<String, String> context = new HashMap<>(); for (Parameter<?, ?> parameter : getParameters()) { try { Value contextValue = parameterProvider.apply(parameter.getName()); if (enforceRequiredParameters && contextValue.isEmptyString() && parameter.isRequired()) { errorConsumer.accept(Exceptions.createHandled() .withNLSKey("Parameter.required") .set("name", parameter.getLabel()) .handle()); } else { String value = parameter.checkAndTransform(contextValue); context.put(parameter.getName(), value); } } catch (HandledException e) { errorConsumer.accept(e); } } return context; }