auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void waitForLinkOpenedInNewTab(WebElement link) { <START> int tabs = driver.getWindowHandles().size(); <END> link.click(); new WebDriverWait(driver, TIMEOUT_PAGE_REGISTRATION) .until((Predicate<WebDriver>) input -> driver.getWindowHandles().size() > tabs); }</code><technical_language>tabs -> initialTabNumber</technical_language>

Target:
private void waitForLinkOpenedInNewTab(WebElement link) { int initialTabsNumber = driver.getWindowHandles().size(); link.click(); new WebDriverWait(driver, TIMEOUT_PAGE_REGISTRATION) .until((Predicate<WebDriver>) input -> getTabsCount() > initialTabsNumber); }
Source:
<code><START> private ActionBarWrapper() { } <END></code><technical_language>nice assert actionBar is displayed. (so if is visible, onActionBar() is called, breaks error bar isnt instead of eg. title doesnt match)</technical_language>

Target:
private ActionBarWrapper() { onView(TITLE_MATCHER) .check(matches(isDisplayed())); onView(NAVIGATE_UP_MATCHER) .check(matches(isDisplayed())); }
Source:
<code>public AsyncResult<Void> waitUntilAvailable(UUID requestId) { log.error("received waitUntilAvailable on a lock believed to be a targeted sweep lock", SafeArg.of("requestId", requestId)); <START> throw new NotSupportedException(); <END> }</code><technical_language>nit: sure. This NotSupportedException() is a 415 a bit of a meaning - suggest throw normal UnsupportedOperationException a 500</technical_language>

Target:
public AsyncResult<Void> waitUntilAvailable(UUID requestId) { log.error("received waitUntilAvailable on a lock believed to be a targeted sweep lock", SafeArg.of("requestId", requestId)); throw new UnsupportedOperationException("received waitUntilAvailable on a lock believed to be a targeted " + "sweep lock."); }
Source:
<code>public void verifyHostnameThrowsSSLPeerUnverifiedExceptionWhenHostDoesNotMatch() throws Exception { System.setProperty("javax.net.ssl.trustStore", this.getClass().getResource("/ssl/trusted/cacerts.jks").getPath()); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); Properties properties = new Properties(); <START> properties.setProperty(GeneralOption.HOST.getKey(), "127.0.0.1"); <END> properties.setProperty(GeneralOption.PORT.getKey(), Integer.toString(trustedService.httpsPort())); properties.setProperty(GeneralOption.USE_HTTPS.getKey(), "true"); properties.setProperty(GeneralOption.VERIFY_SSL.getKey(), "true"); ConnectorDetails connectorDetails = new ConnectorDetails(ConfigurationBuilder.initFromProperties(properties)); HttpHelper httpHelper = new HttpHelper(); HttpHost httpHost = httpHelper.buildHttpHost(connectorDetails); CloseableHttpClient closeableHttpClient = httpHelper.buildClient(httpHost, connectorDetails); when(closeableHttpClient).execute(httpHost, new HttpGet("/hello")); then(caughtException()).isInstanceOf(SSLPeerUnverifiedException.class); }</code><technical_language>[PMD] INFO: Do hard code IP address</technical_language>

Target:
public void verifyHostnameThrowsSSLPeerUnverifiedExceptionWhenHostDoesNotMatch() throws Exception { setSystemTrustStore(); ConnectorDetails connectorDetails = buildConnectorDetails("127.0.0.1", trustedService.httpsPort(), "true", "true"); HttpHelper httpHelper = new HttpHelper(); HttpHost httpHost = httpHelper.buildHttpHost(connectorDetails); CloseableHttpClient closeableHttpClient = httpHelper.buildClient(httpHost, connectorDetails); when(closeableHttpClient).execute(httpHost, new HttpGet("/hello")); then(caughtException()).isInstanceOf(SSLPeerUnverifiedException.class); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { <START> SharedPreferences adminPreferences = this.getSharedPreferences( <END> AdminPreferencesActivity.ADMIN_PREFERENCES, 0); String pw = adminPreferences.getString( AdminKeys.KEY_ADMIN_PW, ""); switch (item.getItemId()) { case R.id.menu_configure_qr_code: if ("".equalsIgnoreCase(pw)) { startActivity(new Intent(this, ScanQRCodeActivity.class)); } else { showDialog(QR_PASSWORD_DIALOG); } return true; case R.id.menu_about: startActivity(new Intent(this, AboutActivity.class)); return true; case R.id.menu_general_preferences: startActivity(new Intent(this, PreferencesActivity.class)); return true; case R.id.menu_admin_preferences: if ("".equalsIgnoreCase(pw)) { startActivity(new Intent(this, AdminPreferencesActivity.class)); } else { showDialog(PASSWORD_DIALOG); } return true; } return super.onOptionsItemSelected(item); }</code><technical_language>This initialized in onCreate onOptionsItemSelected called clicks a menu item. This means adminPreferences a high likelyhood of null if call else. guessing this causing problems in test? some ideas fixing leave test</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_configure_qr_code: analytics.logEvent("ScanQRCode", "MainMenu"); if (adminPasswordProvider.isAdminPasswordSet()) { DialogUtils.showIfNotShowing(AdminPasswordDialog.create(adminPasswordProvider, AdminPasswordDialog.Action.SCAN_QR_CODE), getSupportFragmentManager()); } else { startActivity(new Intent(this, ScanQRCodeActivity.class)); } return true; case R.id.menu_about: startActivity(new Intent(this, AboutActivity.class)); return true; case R.id.menu_general_preferences: startActivity(new Intent(this, PreferencesActivity.class)); return true; case R.id.menu_admin_preferences: if (adminPasswordProvider.isAdminPasswordSet()) { DialogUtils.showIfNotShowing(AdminPasswordDialog.create(adminPasswordProvider, AdminPasswordDialog.Action.ADMIN_SETTINGS), getSupportFragmentManager()); } else { startActivity(new Intent(this, AdminPreferencesActivity.class)); } return true; } return super.onOptionsItemSelected(item); }
Source:
<code>public void createResourceGroup() { <START> String resourceGroupName = Configuration.getGlobalConfiguration().get(AZURE_RESOURCEGROUP_NAME); <END> boolean resourceGroupNameSet = !CoreUtils.isNullOrEmpty(resourceGroupName); if (!resourceGroupNameSet) { resourceGroupName = TEST_RESOURCE_GROUP; } if (resourceGroupNameSet && azure.resourceGroups().checkExistence(resourceGroupName)) { System.out.println("Fetching Resource Group: " + resourceGroupName); resourceGroup = azure.resourceGroups() .getByName(resourceGroupName); } else { System.out.println("Creating Resource Group: " + resourceGroupName); resourceGroup = azure.resourceGroups() .define(resourceGroupName) .withRegion(location) .create(); } }</code><technical_language>is a default hardcoded test resource group get rid of null empty check here. java String resourcegroupname = Configuration.getGlobalConfiguration().get(AZURE_RESOURCEGROUP_NAME, TEST_RESOURCE_GROUP); This is effectively a get default</technical_language>

Target:
public void createResourceGroup() { String resourceGroupName = Configuration.getGlobalConfiguration().get(AZURE_RESOURCEGROUP_NAME, TEST_RESOURCE_GROUP); if (azure.resourceGroups().checkExistence(resourceGroupName)) { System.out.println("Fetching Resource Group: " + resourceGroupName); resourceGroup = azure.resourceGroups() .getByName(resourceGroupName); } else { System.out.println("Creating Resource Group: " + resourceGroupName); resourceGroup = azure.resourceGroups() .define(resourceGroupName) .withRegion(location) .create(); } }
Source:
<code><START> synchronized Currency getDefaultCurrency() { <END> if (this.campaign == null) { return this.backupCurrency; } DateTime date = this.campaign.getDateTime(); if (this.lastChecked == null || this.lastChecked.isBefore(date)) { this.lastChecked = date; this.defaultCurrency = this.backupCurrency; Map<String, Currency> possibleCurrencies = new HashMap<>(); int year = date.getYear(); for (Currency currency : this.currencies) { if ((year >= currency.getStartYear()) && (year <= currency.getEndYear())) { if (currency.getIsDefault()) { return defaultCurrency = currency; } possibleCurrencies.put(currency.getCode(), currency); } } for (Contract contract : this.campaign.getActiveContracts()) { if (contract instanceof AtBContract) { Currency currency = possibleCurrencies.getOrDefault( Faction.getFaction(((AtBContract)contract).getEmployerCode()).getCurrencyCode(), null); if (currency != null) { return defaultCurrency = currency; } } } PlanetarySystem psystem = this.campaign.getCurrentSystem(); if (psystem != null) { Set<Faction> factions = psystem.getFactionSet(date); for (Faction faction : factions) { Currency currency = possibleCurrencies.getOrDefault(faction.getCurrencyCode(), null); if (currency != null) { return defaultCurrency = currency; } } } } return defaultCurrency; }</code><technical_language>Nice idea saving currency for day</technical_language>

Target:
synchronized Currency getDefaultCurrency() { if (this.campaign == null) { return this.backupCurrency; } DateTime date = this.campaign.getDateTime(); PlanetarySystem currentSystem = this.campaign.getCurrentSystem(); if (this.lastChecked == null || this.lastChecked.isBefore(date) || !Objects.equals(this.lastSystem, currentSystem)) { this.lastChecked = date; this.lastSystem = currentSystem; this.defaultCurrency = this.backupCurrency; Map<String, Currency> possibleCurrencies = new HashMap<>(); int year = date.getYear(); for (Currency currency : this.currencies) { if ((year >= currency.getStartYear()) && (year <= currency.getEndYear())) { if (currency.getIsDefault()) { return defaultCurrency = currency; } possibleCurrencies.put(currency.getCode(), currency); } } for (Contract contract : this.campaign.getActiveContracts()) { if (contract instanceof AtBContract) { Currency currency = possibleCurrencies.getOrDefault( Faction.getFaction(((AtBContract)contract).getEmployerCode()).getCurrencyCode(), null); if (currency != null) { return defaultCurrency = currency; } } } if (currentSystem != null) { Set<Faction> factions = currentSystem.getFactionSet(date); for (Faction faction : factions) { Currency currency = possibleCurrencies.getOrDefault(faction.getCurrencyCode(), null); if (currency != null) { return defaultCurrency = currency; } } } } return defaultCurrency; }
Source:
<code>public Response listPersistedReports(UriInfo uriInfo) { final QueryParameters queryParameters = QueryParametersBuilder.buildFrom(uriInfo); final List<ReportCatalogEntry> persistedReports = reportStoreService.getPage(queryParameters.getOffset(), queryParameters.getLimit()); if (persistedReports.isEmpty()) { return Response.noContent().build(); } final Map<String, Object> formatMap = reportStoreService.getFormatMap(); final JSONArray jsonArray = new JSONArray(); for (ReportCatalogEntry eachEntry : persistedReports) { final JSONObject jsonObject = new JSONObject(eachEntry); final List<ReportFormat> formats = (List<ReportFormat>)formatMap.get(eachEntry.getReportId()); if (formats != null && !formats.isEmpty()) { jsonObject.put("formats", new JSONArray(formats)); } else { final String format = eachEntry.getLocation().substring(eachEntry.getLocation().lastIndexOf(".") + 1); <START> jsonObject.put("formats", new JSONArray("[" + format.toUpperCase() +"]")); <END> } jsonArray.put(jsonObject); } return Response.ok() .header("Content-Range", ResponseUtils.getContentRange(jsonArray.length(), queryParameters.getOffset(), reportStoreService.countAll())) .entity(jsonArray.toString()) .type(MediaType.APPLICATION_JSON_TYPE) .build(); }</code><technical_language>Missing space in +"]", ;-)</technical_language>

Target:
public Response listPersistedReports(UriInfo uriInfo) { final QueryParameters queryParameters = QueryParametersBuilder.buildFrom(uriInfo); final List<ReportCatalogEntry> persistedReports = reportStoreService.getPage(queryParameters.getOffset(), queryParameters.getLimit()); if (persistedReports.isEmpty()) { return Response.noContent().build(); } final Map<String, Object> formatMap = reportStoreService.getFormatMap(); final JSONArray jsonArray = new JSONArray(); for (ReportCatalogEntry eachEntry : persistedReports) { final JSONObject jsonObject = new JSONObject(eachEntry); final List<ReportFormat> formats = (List<ReportFormat>)formatMap.get(eachEntry.getReportId()); if (formats != null && !formats.isEmpty()) { jsonObject.put("formats", new JSONArray(formats)); } else { final String format = eachEntry.getLocation().substring(eachEntry.getLocation().lastIndexOf(".") + 1); final JSONArray formatsArray = new JSONArray(); formatsArray.put(format.toUpperCase()); jsonObject.put("formats", formatsArray); } jsonArray.put(jsonObject); } return Response.ok() .header("Content-Range", ResponseUtils.getContentRange(jsonArray.length(), queryParameters.getOffset(), reportStoreService.countAll())) .entity(jsonArray.toString()) .type(MediaType.APPLICATION_JSON_TYPE) .build(); }
Source:
<code>public void process(JSONRequestContext requestContext) { CurriculumDAO curriculumDAO = DAOFactory.getInstance().getCurriculumDAO(); Long curriculumId = requestContext.getLong("curriculumId"); <START> Curriculum curriculum = curriculumDAO.findById(curriculumId); <END> curriculumDAO.archive(curriculum); }</code><technical_language>Check curriculumId curriculum for null</technical_language>

Target:
public void process(JSONRequestContext requestContext) { CurriculumDAO curriculumDAO = DAOFactory.getInstance().getCurriculumDAO(); Long curriculumId = requestContext.getLong("curriculumId"); Curriculum curriculum = curriculumId != null ? curriculumDAO.findById(curriculumId) : null; if (curriculum != null) curriculumDAO.archive(curriculum); else throw new SmvcRuntimeException(StatusCode.UNDEFINED, "Given curriculum was not found."); }
Source:
<code>public String toString() { <START> return StringUtils.nonStrictFormat( <END> "QueryInterruptedException{msg=%s, code=%s, class=%s, host=%s}", getMessage(), errorCode, errorClass, host ); }</code><technical_language>nonStrictFormat() is designed called indirectly, e. g. in a method constructor accepts Object... args itself. In this case I point instead of StringUtils.format()</technical_language>

Target:
public String toString() { return StringUtils.format( "QueryInterruptedException{msg=%s, code=%s, class=%s, host=%s}", getMessage(), errorCode, errorClass, host ); }
Source:
<code><START> public UserDetails myUserDetailsService() { <END> ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> salaboyAuthorities = new ArrayList<>(); salaboyAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_activitiTeam")); extendedInMemoryUserDetailsManager.createUser(new User("salaboy", "password", salaboyAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); List<GrantedAuthority> garthAuthorities = new ArrayList<>(); garthAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); garthAuthorities.add(new SimpleGrantedAuthority("GROUP_doctor")); extendedInMemoryUserDetailsManager.createUser(new User("garth", "password", garthAuthorities)); return (UserDetails) extendedInMemoryUserDetailsManager; }</code><technical_language>@pancudaniel7 this is wrong.. need UserDetailsService cast UserDetails</technical_language>

Target:
public UserDetailsService myUserDetailsService() { ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> salaboyAuthorities = new ArrayList<>(); salaboyAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_activitiTeam")); extendedInMemoryUserDetailsManager.createUser(new User("salaboy", "password", salaboyAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); List<GrantedAuthority> garthAuthorities = new ArrayList<>(); garthAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); garthAuthorities.add(new SimpleGrantedAuthority("GROUP_doctor")); extendedInMemoryUserDetailsManager.createUser(new User("garth", "password", garthAuthorities)); return extendedInMemoryUserDetailsManager; }
Source:
<code>public boolean initializeApplication() { <START> boolean isOk = initializeApplicationHelper(); <END> if (isOk) { if (record.convertedFromOldFormat()) { updateAppRecord(); } } return isOk; }</code><technical_language>isOk is kind of a generic description here. I call this ambiguous "isAppReady"</technical_language>

Target:
public boolean initializeApplication() { boolean appReady = initializeApplicationHelper(); if (appReady) { if (record.wasConvertedByDbUpgrader()) { updateAppRecord(); } } return appReady; }
Source:
<code>boolean checkSchemaAgreement() throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException { Connection connection = connectionRef.get(); if (connection == null || connection.isClosed()) return false; <START> DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS)); <END> DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_LOCAL)); connection.write(peersFuture); connection.write(localFuture); Set<UUID> versions = new HashSet<UUID>(); Row localRow = localFuture.get().one(); if (localRow != null && !localRow.isNull("schema_version")) versions.add(localRow.getUUID("schema_version")); for (Row row : peersFuture.get()) { if (!isValidPeer(row, false)) continue; InetSocketAddress addr = addressToUseForPeerHost(row, connection.address, cluster); if (addr == null || row.isNull("schema_version")) continue; Host peer = cluster.metadata.getHost(addr); if (peer != null && peer.isUp()) versions.add(row.getUUID("schema_version")); } logger.debug("Checking for schema agreement: versions are {}", versions); return versions.size() <= 1; }</code><technical_language>SELECT_PEERS retrieves more columns, notably tokens. a tradeoff payload size (tokens non-negligible virtual nodes), considering bogus entries for schema agreement (which fail). In attachment JAVA-852 lines a non-null rpc_address other null fields, query other a difference..</technical_language>

Target:
boolean checkSchemaAgreement() throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException { Connection connection = connectionRef.get(); if (connection == null || connection.isClosed()) return false; DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_PEERS)); DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_LOCAL)); connection.write(peersFuture); connection.write(localFuture); Set<UUID> versions = new HashSet<UUID>(); Row localRow = localFuture.get().one(); if (localRow != null && !localRow.isNull("schema_version")) versions.add(localRow.getUUID("schema_version")); for (Row row : peersFuture.get()) { InetSocketAddress addr = addressToUseForPeerHost(row, connection.address, cluster); if (addr == null || row.isNull("schema_version")) continue; Host peer = cluster.metadata.getHost(addr); if (peer != null && peer.isUp()) versions.add(row.getUUID("schema_version")); } logger.debug("Checking for schema agreement: versions are {}", versions); return versions.size() <= 1; }
Source:
<code>public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_FACILITY_ATTR_DEF); attr.setFriendlyName("uid-namespace"); attr.setDisplayName("UID namespace"); attr.setType(String.class.getName()); <START> attr.setDescription("UID in namespace perun"); END> return attr; }</code><technical_language>Again, mistake, fix this description if possible. is descrption devel/gui in attributes. delete '//FIXME'. Thank you</technical_language>

Target:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_FACILITY_ATTR_DEF); attr.setFriendlyName("uid-namespace"); attr.setDisplayName("UID namespace"); attr.setType(String.class.getName()); attr.setDescription("Namespace for UIDs which can be used at specific facility."); return attr; }
Source:
<code>public DataSource createDataSource() throws SQLException { final DbInfo db = createNewDatabase(); <START> return createDataSourceFromDBInfo(db); <END> }</code><technical_language>collapse temporary</technical_language>

Target:
public DataSource createDataSource() throws SQLException { return createDataSourceFromConnectionInfo(createNewDatabase()); }
Source:
<code>private void setLimit(final BooleanImageLabel limit, final Boolean enable) { <START> limit.enable(disableIfNull(enable)); <END> }</code><technical_language>suggestion limit.enable(enable); Is done in enable. while rename enable setIsEnabled()</technical_language>

Target:
private void setLimit(final BooleanImageLabel limit, final Boolean enable) { limit.setIsEnabled(enable); }
Source:
<code>public static void assertEquals(int value1, int value2, String message, Object... data) { <START> if (data == null) { checkExpressionFailOnTrue(value1 != value2, message + " - Expected %s; Actual %s", value1, value2); } else { checkExpressionFailOnTrue(value1 != value2, message + " - Expected %s; Actual %s", data, value1, value2); } <END> }</code><technical_language>if do this here, trickle this other asserts too. OseeCoreException.formatMessage a good place handle situations 'data' is null?</technical_language>

Target:
public static void assertEquals(int value1, int value2, String message, Object... data) { if (data == null) { checkExpressionFailOnTrue(value1 != value2, message + " - Expected %s; Actual %s", value1, value2); } else { checkExpressionFailOnTrue(value1 != value2, message + " - Expected %d; Actual %d", data, value1, value2); } }
Source:
<code>public List<EventType> list() { return jdbcTemplate.query( <START> "SELECT et_name, et_event_type_object FROM zn_data.event_type;", <END> new EventTypeMapper()); }</code><technical_language>do need select et_name here</technical_language>

Target:
public List<EventType> list() { return jdbcTemplate.query( "SELECT et_event_type_object FROM zn_data.event_type", new EventTypeMapper()); }
Source:
<code>public Date apply(String retryAfter) { if (retryAfter == null) { return null; } if (retryAfter.matches("^[0-9]+$")) { long deltaMillis = SECONDS.toMillis(Long.parseLong(retryAfter)); return new Date(currentTimeMillis() + deltaMillis); } <START> synchronized (rfc822Format) { <END> try { return rfc822Format.parse(retryAfter); } catch (ParseException ignored) { return null; } } }</code><technical_language>java8 DateTimeFormatter is thread-safe, instead</technical_language>

Target:
public Date apply(String retryAfter) { if (retryAfter == null) { return null; } if (retryAfter.matches("^[0-9]+$")) { long deltaMillis = TimeUnit.SECONDS.toMillis(Long.parseLong(retryAfter)); return new Date(currentTimeMillis() + deltaMillis); } synchronized (rfc822Format) { try { return rfc822Format.parse(retryAfter); } catch (ParseException ignored) { return null; } } }
Source:
<code>protected boolean canDoAction() { if (!super.canDoAction()) { return false; } List<VmDevice> watchdogs = getVmDeviceDao().getVmDeviceByVmIdAndType(getParameters().getVmId(), VmDeviceType.WATCHDOG.getName()); if (watchdogs.isEmpty()) { return failCanDoAction(VdcBllMessages.WATCHDOG_NOT_FOUND); } <START> return super.canDoAction(); <END> }</code><technical_language>calling super.canDoAction twice, i guess return true</technical_language>

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } List<VmDevice> watchdogs = getVmDeviceDao().getVmDeviceByVmIdAndType(getParameters().getId(), VmDeviceType.WATCHDOG.getName()); if (watchdogs.isEmpty()) { return failCanDoAction(VdcBllMessages.WATCHDOG_NOT_FOUND); } return true; }
Source:
<code>public void text_encode_opaque_as_base64_string() { <START> byte[] opaqueValue = new byte[] { 1, 2, 3, 4, 5 }; <END> byte[] encoded = encoder.encode(LwM2mSingleResource.newBinaryResource(0, opaqueValue), ContentFormat.TEXT, new LwM2mPath("/5/0/0"), model); Assert.assertEquals("AQIDBAU=", new String(encoded, StandardCharsets.UTF_8)); }</code><technical_language>a detail, spec talk hex hex notation? java byte[] opaqueValue = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5 };</technical_language>

Target:
public void text_encode_opaque_as_base64_string() { byte[] opaqueValue = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5 }; byte[] encoded = encoder.encode(LwM2mSingleResource.newBinaryResource(0, opaqueValue), ContentFormat.TEXT, new LwM2mPath("/5/0/0"), model); Assert.assertEquals("AQIDBAU=", new String(encoded, StandardCharsets.UTF_8)); }
Source:
<code>public void testRetryCount() { AtomicInteger scheduleCalls = new AtomicInteger(); AtomicReference<TaskRunner> runner = new AtomicReference<>(); <START> ScheduledExecutorService mockedExecutor = mock(ScheduledExecutorService.class); <END> when(mockedExecutor.schedule(any(TaskRunner.class), anyLong(), eq(TimeUnit.MILLISECONDS))).then(a -> { scheduleCalls.getAndIncrement(); runner.set((TaskRunner) a.getArguments()[0]); return null; }); RetryStrategy retryStrategy = new RetryStrategy(mockedExecutor); long initialDelay = 150L; long retryDelay = 50L; int targetRetryCount = 3; TestCounterTask retryTask = new TestCounterTask( initialDelay, retryDelay, false, targetRetryCount); assertEquals(0, scheduleCalls.get()); retryStrategy.runRetryingTask(retryTask); assertEquals(1, scheduleCalls.get()); assertEquals(0, retryTask.counter); runner.get().run(); assertEquals(1, retryTask.counter); assertEquals(2, scheduleCalls.get()); runner.get().run(); assertEquals(3, scheduleCalls.get()); runner.get().run(); assertEquals(3, retryTask.counter); assertEquals(3, scheduleCalls.get()); assertEquals(3, retryTask.counter); }</code><technical_language>FakeScheduledExecutorService work here. give scheduleCalls, numPendingJobs achieve I think</technical_language>

Target:
public void testRetryCount() { FakeScheduledExecutorService mockedExecutor = mock( FakeScheduledExecutorService.class, withSettings() .useConstructor() .defaultAnswer(CALLS_REAL_METHODS) ); RetryStrategy retryStrategy = new RetryStrategy(mockedExecutor); long initialDelay = 150L; long retryDelay = 50L; int targetRetryCount = 3; TestCounterTask retryTask = new TestCounterTask( initialDelay, retryDelay, false, targetRetryCount); retryStrategy.runRetryingTask(retryTask); mockedExecutor.run(); assertEquals(0, retryTask.counter); mockedExecutor.getClock().elapse(Duration.ofMillis(initialDelay + 10L)); mockedExecutor.run(); assertEquals(1, retryTask.counter); mockedExecutor.getClock().elapse(Duration.ofMillis(retryDelay + 10L)); mockedExecutor.run(); mockedExecutor.getClock().elapse(Duration.ofMillis(retryDelay + 10L)); mockedExecutor.run(); assertEquals(3, retryTask.counter); mockedExecutor.getClock().elapse(Duration.ofMillis(retryDelay + 10L)); mockedExecutor.run(); assertEquals(3, retryTask.counter); }
Source:
<code>KafkaConsumer<byte[], byte[]> newConsumer() throws IOException { ClassLoader currCtxCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); <START> final Map<String, Object> configs = new HashMap<>(); <END> for (Map.Entry<String, Object> entry : ioConfig.getConsumerProperties().entrySet()) { String propertyKey = entry.getKey(); if (propertyKey.equals(KafkaSupervisorIOConfig.TRUST_STORE_PASSWORD_KEY) || propertyKey.equals(KafkaSupervisorIOConfig.KEY_STORE_PASSWORD_KEY) || propertyKey.equals(KafkaSupervisorIOConfig.KEY_PASSWORD_KEY)) { PasswordProvider configPasswordProvider = configMapper.readValue( configMapper.writeValueAsString(entry.getValue()), PasswordProvider.class ); configs.put(propertyKey, (configPasswordProvider.getPassword())); } else { configs.put(propertyKey, entry.getValue()); } } configs.put("enable.auto.commit", "false"); configs.put("auto.offset.reset", "none"); configs.put("key.deserializer", ByteArrayDeserializer.class.getName()); configs.put("value.deserializer", ByteArrayDeserializer.class.getName()); return new KafkaConsumer<>(configs); } finally { Thread.currentThread().setContextClassLoader(currCtxCl); } }</code><technical_language>this Map<String, String></technical_language>

Target:
KafkaConsumer<byte[], byte[]> newConsumer() { ClassLoader currCtxCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); final Properties props = new Properties(); addConsumerPropertiesFromConfig(props, configMapper, ioConfig.getConsumerProperties()); props.setProperty("enable.auto.commit", "false"); props.setProperty("auto.offset.reset", "none"); props.setProperty("key.deserializer", ByteArrayDeserializer.class.getName()); props.setProperty("value.deserializer", ByteArrayDeserializer.class.getName()); return new KafkaConsumer<>(props); } finally { Thread.currentThread().setContextClassLoader(currCtxCl); } }
Source:
<code>public String digestParams(RestInvocation i) { String path = i.getPath(); try { path = URLDecoder.decode(path, "utf8"); } catch (UnsupportedEncodingException ignored) { <START> } <END> Object nonce = i.getParamValue(HeaderParam.class, BitfinexAuthenticated.BFX_NONCE); String body = i.getRequestBody(); if (body == null || body.isEmpty()) { body = "{}"; } String toEncode = "/api/" + path + nonce + body; try { byte[] sig = getMac().doFinal(toEncode.getBytes(UTF_8)); String signature = DigestUtils.bytesToHex(sig); return signature; } catch (IllegalStateException | UnsupportedEncodingException e) { throw new ExchangeException("Could not sign the request", e); } }</code><technical_language>silent errors evil, "its impossible" ;) surround entire methods body try - catch a good catch handles in end</technical_language>

Target:
public String digestParams(RestInvocation i) { String path = i.getPath(); try { path = URLDecoder.decode(path, "utf8"); } catch (UnsupportedEncodingException e) { log.warn("Could not url decode the path {}.", path, e); } Object nonce = i.getParamValue(HeaderParam.class, BitfinexAuthenticated.BFX_NONCE); String body = i.getRequestBody(); if (body == null || body.isEmpty()) { body = "{}"; } String toEncode = "/api/" + path + nonce + body; try { byte[] sig = getMac().doFinal(toEncode.getBytes(UTF_8)); String signature = DigestUtils.bytesToHex(sig); return signature; } catch (IllegalStateException | UnsupportedEncodingException e) { throw new ExchangeException("Could not sign the request", e); } }
Source:
<code>protected void onMethodInvocationFound(MethodInvocationTree mit) { Integer methodFirstArgumentAsInteger = LiteralUtils.intLiteralValue(mit.arguments().get(0)); if (methodFirstArgumentAsInteger == null) { return; } boolean isMethodFromJavaSqlResultSet = mit.symbol().owner().type().is(JAVA_SQL_RESULTSET); int methodFirstArgumentValue = methodFirstArgumentAsInteger.intValue(); if (isMethodFromJavaSqlResultSet && methodFirstArgumentValue == 0) { addIssue(mit, "ResultSet indices start at 1."); } else if (!isMethodFromJavaSqlResultSet) { if (methodFirstArgumentValue == 0) { addIssue(mit, "PreparedStatement indices start at 1."); } else { Tree preparedStatementReference = getPreparedStatementReference(mit); Integer numberParameters = getPreparedStatementNumberOfParameters(preparedStatementReference); <START> if (numberParameters != null && methodFirstArgumentValue > numberParameters.intValue()) { <END> addIssue(mit, "This \"PreparedStatement\" " + (numberParameters == 0 ? "has no" : ("only has " + numberParameters)) + " parameters."); } } } }</code><technical_language>@m-g-sonar unnecessary unboxing .intValue() line 92. eclipse notify it</technical_language>

Target:
protected void onMethodInvocationFound(MethodInvocationTree mit) { Integer methodFirstArgumentAsInteger = LiteralUtils.intLiteralValue(mit.arguments().get(0)); if (methodFirstArgumentAsInteger == null) { return; } boolean isMethodFromJavaSqlResultSet = mit.symbol().owner().type().is(JAVA_SQL_RESULTSET); int methodFirstArgumentValue = methodFirstArgumentAsInteger.intValue(); if (isMethodFromJavaSqlResultSet && methodFirstArgumentValue == 0) { addIssue(mit, "ResultSet indices start at 1."); } else if (!isMethodFromJavaSqlResultSet) { if (methodFirstArgumentValue == 0) { addIssue(mit, "PreparedStatement indices start at 1."); } else { Tree preparedStatementReference = getPreparedStatementReference(mit); Integer numberParameters = getPreparedStatementNumberOfParameters(preparedStatementReference); if (numberParameters != null && methodFirstArgumentValue > numberParameters) { addIssue(mit, "This \"PreparedStatement\" " + (numberParameters == 0 ? "has no" : ("only has " + numberParameters)) + " parameters."); } } } }
Source:
<code>protected void populateExtendedInfo(LogEntry entry, DocumentModel source, ExpressionContext context, Collection<ExtendedInfoDescriptor> extInfos) { if (extInfos != null) { Map<String, ExtendedInfo> extendedInfos = entry.getExtendedInfos(); for (ExtendedInfoDescriptor descriptor : extInfos) { String exp = descriptor.getExpression(); Serializable value = null; try { value = expressionEvaluator.evaluateExpression(context, exp, Serializable.class); } catch (PropertyException | UnsupportedOperationException e) { if (source instanceof DeletedDocumentModel) { log.debug("Can not evaluate the expression: " + exp + " on a DeletedDocumentModel, skipping."); } continue; } catch (DocumentNotFoundException e) { <START> if (entry.getEventId() != "documentRemoved") { <END> log.error("Not found: " + e.getMessage() + ", entry: " + entry, e); } continue; } catch (ELException e) { continue; } if (value == null) { continue; } extendedInfos.put(descriptor.getKey(), newExtendedInfo(value)); } } }</code><technical_language>equals</technical_language>

Target:
protected void populateExtendedInfo(LogEntry entry, DocumentModel source, ExpressionContext context, Collection<ExtendedInfoDescriptor> extInfos) { if (extInfos != null) { Map<String, ExtendedInfo> extendedInfos = entry.getExtendedInfos(); for (ExtendedInfoDescriptor descriptor : extInfos) { String exp = descriptor.getExpression(); Serializable value = null; try { value = expressionEvaluator.evaluateExpression(context, exp, Serializable.class); } catch (PropertyException | UnsupportedOperationException e) { if (source instanceof DeletedDocumentModel) { log.debug("Can not evaluate the expression: " + exp + " on a DeletedDocumentModel, skipping."); } continue; } catch (DocumentNotFoundException e) { if (! DocumentEventTypes.DOCUMENT_REMOVED.equals(entry.getEventId())) { log.error(String.format("Not found: %s, entry: %s", e.getMessage(), entry, e)); } continue; } catch (ELException e) { continue; } if (value == null) { continue; } extendedInfos.put(descriptor.getKey(), newExtendedInfo(value)); } } }
Source:
<code>public void saveCredentialsOrFinish(FirebaseUser firebaseUser, @Nullable String password, @Nullable IdpResponse response) { mResponse = response; if (!getFlowParams().enableCredentials) { finish(); return; } final Credential credential = CredentialsUtil.buildCredential( firebaseUser.getEmail(), password, firebaseUser.getDisplayName(), firebaseUser.getPhotoUrl() == null ? null : firebaseUser.getPhotoUrl().toString(), mResponse); if (credential == null) { Log.e(TAG, "Unable to save null credential!"); finish(); return; } <START> getLifecycle().addObserver(new LifecycleObserver() { <END> @OnLifecycleEvent(Lifecycle.Event.ON_START) public void save() { getCredentialsClient().save(credential) .addOnCompleteListener(SaveSmartLock.this); } }); }</code><technical_language>A questions this: * Is for this fire multiple times? * Is onStart happened this observer is registered</technical_language>

Target:
public void saveCredentialsOrFinish(FirebaseUser firebaseUser, @Nullable String password, @Nullable IdpResponse response) { mResponse = response; if (!getFlowParams().enableCredentials) { finish(); return; } final Credential credential = CredentialsUtil.buildCredential( firebaseUser.getEmail(), password, firebaseUser.getDisplayName(), firebaseUser.getPhotoUrl() == null ? null : firebaseUser.getPhotoUrl().toString(), mResponse); if (credential == null) { Log.e(TAG, "Unable to save null credential!"); finish(); return; } getLifecycle().addObserver(new LifecycleObserver() { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void save() { getCredentialsClient().save(credential) .addOnCompleteListener(SaveSmartLock.this); } }); }
Source:
<code>public void testSendRegistrationInviteToStudent() throws Exception { ______TS("typical case: send invite to one student"); restoreTypicalDataInDatastore(); dataBundle = getTypicalDataBundle(); StudentAttributes student1InCourse1 = dataBundle.students.get("student1InCourse1"); String studentEmail = student1InCourse1.email; String courseId = student1InCourse1.course; MimeMessage msgToStudent = studentsLogic.sendRegistrationInviteToStudent(courseId, studentEmail); Emails emailMgr = new Emails(); @SuppressWarnings("static-access") String emailInfo = emailMgr.getEmailInfo(msgToStudent); String expectedEmailInfo = "[Email sent]to=student1InCourse1@gmail.com|from=" + "\"TEAMMATES Admin (noreply)\" <noreply@null.appspotmail.com>|subject=TEAMMATES:" + " Invitation to join course [Typical Course 1 with 2 Evals][Course ID: idOfTypicalCourse1]"; assertEquals(expectedEmailInfo, emailInfo); ______TS("invalid course id"); String invalidCourseId = "invalidCourseId"; try { studentsLogic.sendRegistrationInviteToStudent(invalidCourseId, studentEmail); signalFailureToDetectException(); <START> } catch (EntityDoesNotExistException e) { <END> } ______TS("invalid student email"); String invalidStudentEmail = "invalidStudentEmail"; try { studentsLogic.sendRegistrationInviteToStudent(courseId, invalidStudentEmail); signalFailureToDetectException(); } catch (EntityDoesNotExistException e) { } }</code><technical_language>ignoreExpectedException() here. Otherwise, flagged 'empty catch' code quality checking tools</technical_language>

Target:
public void testSendRegistrationInviteToStudent() throws Exception { ______TS("typical case: send invite to one student"); restoreTypicalDataInDatastore(); StudentAttributes student1InCourse1 = dataBundle.students.get("student1InCourse1"); String studentEmail = student1InCourse1.email; String courseId = student1InCourse1.course; MimeMessage msgToStudent = studentsLogic.sendRegistrationInviteToStudent(courseId, studentEmail); Emails emailMgr = new Emails(); @SuppressWarnings("static-access") String emailInfo = emailMgr.getEmailInfo(msgToStudent); String expectedEmailInfo = "[Email sent]to=student1InCourse1@gmail.com|from=" + "\"TEAMMATES Admin (noreply)\" <noreply@null.appspotmail.com>|subject=TEAMMATES:" + " Invitation to join course [Typical Course 1 with 2 Evals][Course ID: idOfTypicalCourse1]"; assertEquals(expectedEmailInfo, emailInfo); ______TS("invalid course id"); String invalidCourseId = "invalidCourseId"; try { studentsLogic.sendRegistrationInviteToStudent(invalidCourseId, studentEmail); signalFailureToDetectException(); } catch (EntityDoesNotExistException e) { ignoreExpectedException(); } ______TS("invalid student email"); String invalidStudentEmail = "invalidStudentEmail"; try { studentsLogic.sendRegistrationInviteToStudent(courseId, invalidStudentEmail); signalFailureToDetectException(); } catch (EntityDoesNotExistException e) { ignoreExpectedException(); } }
Source:
<code>public void setup() throws Exception { final RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework curator = CuratorFrameworkFactory.newClient(zk.connectString(), retryPolicy); curator.start(); client = new DefaultZooKeeperClient(curator); client.ensurePath(Paths.configHosts()); client.ensurePath(Paths.configJobs()); client.ensurePath(Paths.configJobRefs()); client.ensurePath(Paths.statusHosts()); client.ensurePath(Paths.statusMasters()); client.ensurePath(Paths.historyJobs()); final ZooKeeperClientProvider zkProvider = new ZooKeeperClientProvider(client, ZooKeeperModelReporter.noop()); <START> final KafkaSender kafkaSender = <END> new KafkaSender(Optional.<KafkaProducer<String, byte[]>>absent()); model = new ZooKeeperMasterModel(zkProvider, getClass().getName(), kafkaSender); }</code><technical_language>pass in a mocked KafkaSender</technical_language>

Target:
public void setup() throws Exception { final RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework curator = CuratorFrameworkFactory.newClient(zk.connectString(), retryPolicy); curator.start(); client = new DefaultZooKeeperClient(curator); client.ensurePath(Paths.configHosts()); client.ensurePath(Paths.configJobs()); client.ensurePath(Paths.configJobRefs()); client.ensurePath(Paths.statusHosts()); client.ensurePath(Paths.statusMasters()); client.ensurePath(Paths.historyJobs()); final ZooKeeperClientProvider zkProvider = new ZooKeeperClientProvider(client, ZooKeeperModelReporter.noop()); final KafkaSender kafkaSender = mock(KafkaSender.class); model = new ZooKeeperMasterModel(zkProvider, getClass().getName(), kafkaSender); }
Source:
<code>public int hashCode() { <START> return Objects.hash(storageFormat, location, bucketProperty, skewed, serdeParameters); <END> }</code><technical_language>fields in order in toString equals? skewed is</technical_language>

Target:
public int hashCode() { return Objects.hash(skewed, storageFormat, location, bucketProperty, serdeParameters); }
Source:
<code>public void init() { if <START> (getVm().getMigrationSupport() <END> == MigrationSupport.IMPLICITLY_NON_MIGRATABLE && getDestinationVds() == null && !getVm().isUseHostCpuFlags() && getVm().getVmType() != VmType.HighPerformance) { isVmNumaNodesExist = !vmNumaNodeDao.getAllVmNumaNodeByVmId(getParameters().getVmId()).isEmpty(); } }</code><technical_language>getVm() return null this point</technical_language>

Target:
public void init() { if (getVm() != null && getVm().getMigrationSupport() == MigrationSupport.IMPLICITLY_NON_MIGRATABLE && !getVm().isUseHostCpuFlags() && getVm().getVmType() != VmType.HighPerformance) { isVmNumaNodesExist = !vmNumaNodeDao.getAllVmNumaNodeByVmId(getParameters().getVmId()).isEmpty(); } }
Source:
<code>public void testWriteToFileSystem() { SavedPageSyncService syncService = mock(SavedPageSyncService.class); Page dummyPage = mock(Page.class); ArrayList<ReadingListPageDiskRow> unsyncedPages = removeSynced(pages); LinkedList<ReadingListPageDiskRow> queue = (LinkedList<ReadingListPageDiskRow>) syncService.getQueue(); queue.addAll(unsyncedPages); int pagesSaved = 0; for (ReadingListPageDiskRow row : queue) { when(syncService.save(row, dummyPage)).thenReturn(true); <START> boolean b = syncService.save(row, dummyPage); <END> pagesSaved += b ? 1 : 0; } assertEquals(pagesSaved, 3); }</code><technical_language>minor: I this is save status. thought calling saved? line next line, pagesSaved</technical_language>

Target:
public void testWriteToFileSystem() { SavedPageSyncService syncService = mock(SavedPageSyncService.class); List<ReadingListPageDiskRow> queue = syncService.getQueue(); List<ReadingListPageDiskRow> rows = getRows(); queue.addAll(rows); int pagesSaved = saveAndCount(syncService, rows); assertEquals(pagesSaved, 4); }
Source:
<code>protected void reconfigureProcessorByHandler(EnumMap<VmwareStorageProcessorConfigurableFields,Object> params) { VmwareStorageSubsystemCommandHandler handler = (VmwareStorageSubsystemCommandHandler) storageHandler; boolean success = handler.reconfigureStorageProcessor(params); if (success){ s_logger.info("VmwareStorageProcessor and VmwareStorageSubsystemCommandHandler successfully reconfigured"); } else { <START> s_logger.error("Error while reconfiguring VmwareStorageProcessor and VmwareStorageSubsystemCommandHandler"); <END> } }</code><technical_language>Please include values contained in params in log message operators diagnose of error</technical_language>

Target:
protected void reconfigureProcessorByHandler(EnumMap<VmwareStorageProcessorConfigurableFields,Object> params) { VmwareStorageSubsystemCommandHandler handler = (VmwareStorageSubsystemCommandHandler) storageHandler; boolean success = handler.reconfigureStorageProcessor(params); if (success){ s_logger.info("VmwareStorageProcessor and VmwareStorageSubsystemCommandHandler successfully reconfigured"); } else { s_logger.error("Error while reconfiguring VmwareStorageProcessor and VmwareStorageSubsystemCommandHandler, params=" + _gson.toJson(params)); } }
Source:
<code>public void setVoiceMailNumber(String alphaTag, String voiceNumber, Message onComplete){ <START> Log.e(LOG_TAG, "method setVoiceMailNumber is not implemented"); <END> }</code><technical_language>is voicemail number fixed in CDMA? If no, return a boolean notify set voicemail unsuccess, instead of put Log.e</technical_language>

Target:
public void setVoiceMailNumber(String alphaTag, String voiceNumber, Message onComplete){ AsyncResult.forMessage((onComplete)).exception = new IccException("setVoiceMailNumber not implemented"); onComplete.sendToTarget(); Log.e(LOG_TAG, "method setVoiceMailNumber is not implemented"); }
Source:
<code>private void addResource(final BackendResource resource) { resource.setMessageBundle(messageBundle); resource.setBackend(backend); resource.setSessionHelper(sessionHelper); if (resource instanceof AbstractBackendResource) { ((AbstractBackendResource) resource).setMappingLocator(mappingLocator); } else if (resource instanceof CapabilitiesResource) { ((BackendCapabilitiesResource) resource).setMappingLocator(mappingLocator); } <START> resource.setValidatorLocator(validatorLocator); <END> singletons.add(resource); }</code><technical_language>this approach root collections validatorLocator, sub-collections/resources get NPE, try it, need inject in runtime resource</technical_language>

Target:
private void addResource(final BackendResource resource) { resource.setMessageBundle(messageBundle); resource.setBackend(backend); resource.setSessionHelper(sessionHelper); if (resource instanceof AbstractBackendResource) { ((AbstractBackendResource) resource).setMappingLocator(mappingLocator); } else if (resource instanceof CapabilitiesResource) { ((BackendCapabilitiesResource) resource).setMappingLocator(mappingLocator); } singletons.add(resource); }