auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected EmbeddedMysql(final MysqldConfig config) { logger.info("Preparing EmbeddedMysql version '{}'...", config.getVersion()); this.config = config; IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(config.getVersion()).build(); lock.lock(); try { <START> this.executable = new MysqldStarter(runtimeConfig).prepare(config); <END> } finally { lock.unlock(); } try { executable.start(); getClient(SCHEMA).executeCommands( format("CREATE USER '%s'@'%%' IDENTIFIED BY '%s';", config.getUsername(), config.getPassword())); } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>Do need lock calls? I try extract locking in a helper method interfere MySql startup</technical_language>

Target:
protected EmbeddedMysql(final MysqldConfig config) { logger.info("Preparing EmbeddedMysql version '{}'...", config.getVersion()); this.config = config; IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(config.getVersion()).build(); MysqldStarter mysqldStarter = new MysqldStarter(runtimeConfig); localRepository.lock(); try { this.executable = mysqldStarter.prepare(config); } finally { localRepository.unlock(); } try { executable.start(); getClient(SCHEMA).executeCommands( format("CREATE USER '%s'@'%%' IDENTIFIED BY '%s';", config.getUsername(), config.getPassword())); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>private boolean isStackOrClusterStatusFailed(Status status) { <START> return (Status.BACKUP_FAILED.equals(status) || Status.RESTORE_FAILED.equals(status)) ? true : false; <END> }</code><technical_language>return Status.BACKUP_FAILED.equals(status) || Status.RESTORE_FAILED.equals(status);</technical_language>

Target:
private boolean isStackOrClusterStatusFailed(Status status) { return Status.BACKUP_FAILED.equals(status) || Status.RESTORE_FAILED.equals(status); }
Source:
<code>public SecretBoxOpener(byte[] key) { checkNotNull(key, "null key passed"); <START> checkArgument(key.length == 32, "key should be 32B, is: " + key.length + "B"); <END> this.key = key; }</code><technical_language>suggestion checkArgument(key.length == 32, "key length 32 bytes, is " + key.length + " bytes");</technical_language>

Target:
public SecretBoxOpener(byte[] key) { checkNotNull(key, "null key passed"); checkArgument(key.length == 32, "key length must be 32 bytes, but is " + key.length + " bytes"); this.key = key; }
Source:
<code>void run() throws Throwable; } <START> public static Throwable expectThrows(ThrowingRunnable runnable) { <END> return expectThrows(null, runnable); }</code><technical_language>I addresses concern a good error message if unexpected exception is thrown. I explicit provides a cleaner, more obvious easier API</technical_language>

Target:
void run() throws Throwable; } public static void assertThrows(Class<? extends Throwable> expectedThrowable, ThrowingRunnable runnable) { expectThrows(expectedThrowable, runnable); }
Source:
<code>protected Response performRemove(String id) { <START> return null; <END> }</code><technical_language>in other classes throw UnsupportedOperation</technical_language>

Target:
protected Response performRemove(String id) { throw new UnsupportedOperationException(); }
Source:
<code>private void validateAddTaskConfigs(String workflowName, String jobName, TaskConfig taskConfig) { WorkflowConfig workflowConfig = TaskUtil.getWorkflowConfig(_accessor, workflowName); String nameSpaceJobName = TaskUtil.getNamespacedJobName(workflowName, jobName); JobConfig jobConfig = TaskUtil.getJobConfig(_accessor, nameSpaceJobName); if (workflowConfig == null) { throw new IllegalArgumentException( String.format("Workflow config for workflow %s does not exist!", workflowName)); } if (jobConfig == null) { throw new IllegalArgumentException( String.format("Job config for job %s does not exist!", nameSpaceJobName)); } if (taskConfig == null) { throw new IllegalArgumentException("TaskConfig is null!"); } if (taskConfig.getId() == null) { throw new HelixException("Task cannot be added because taskID is null!"); } if (jobConfig.getTargetResource() != null) { throw new HelixException(String.format( "Job %s is a targeted job. New task cannot be added to this job!", nameSpaceJobName)); } if (taskConfig.getCommand() == null && jobConfig.getCommand() == null) { throw new HelixException( "Task cannot be added because both of the job and task have null command!"); } <START> if (taskConfig.getCommand() != null && jobConfig.getCommand() != null) { <END> throw new HelixException( "Task cannot be added because command existed for both of job and task!"); } for (String taskEntry : jobConfig.getMapConfigs().keySet()) { if (taskEntry.equals(taskConfig.getId())) { throw new HelixException( "Task cannot be added because another task with the same ID already exists!"); } } }</code><technical_language>nit: combine (taskConfig.getCommand() == null != jobConfig.getCommand() == null) "Command exist in job task, both"</technical_language>

Target:
private void validateAddTaskConfigs(String workflowName, String jobName, TaskConfig taskConfig) { WorkflowConfig workflowConfig = TaskUtil.getWorkflowConfig(_accessor, workflowName); String nameSpaceJobName = TaskUtil.getNamespacedJobName(workflowName, jobName); JobConfig jobConfig = TaskUtil.getJobConfig(_accessor, nameSpaceJobName); if (workflowConfig == null) { throw new IllegalArgumentException( String.format("Workflow config for workflow %s does not exist!", workflowName)); } if (jobConfig == null) { throw new IllegalArgumentException( String.format("Job config for job %s does not exist!", nameSpaceJobName)); } if (taskConfig == null) { throw new IllegalArgumentException("TaskConfig is null!"); } if (taskConfig.getId() == null) { throw new HelixException("Task cannot be added because taskID is null!"); } if (jobConfig.getTargetResource() != null) { throw new HelixException(String.format( "Job %s is a targeted job. New task cannot be added to this job!", nameSpaceJobName)); } if ((taskConfig.getCommand() == null) == (jobConfig.getCommand() == null)) { throw new HelixException("Command must exist in either job or task, not both!"); } for (String taskEntry : jobConfig.getMapConfigs().keySet()) { if (taskEntry.equals(taskConfig.getId())) { throw new HelixException( "Task cannot be added because another task with the same ID already exists!"); } } }
Source:
<code>public void onAssignmentChange(List<DatastreamTask> tasks) { _logger.info("onAssignmentChange called with tasks {}", tasks); HashSet<DatastreamTask> toCancel = new HashSet<>(_runningTasks.keySet()); toCancel.removeAll(tasks); for (DatastreamTask task : toCancel) { AbstractKafkaBasedConnectorTask connectorTask = _runningTasks.remove(task); connectorTask.stop(); } for (DatastreamTask task : tasks) { AbstractKafkaBasedConnectorTask kafkaBasedConnectorTask = _runningTasks.get(task); if (kafkaBasedConnectorTask != null) { kafkaBasedConnectorTask.checkAndUpdateTask(task); <START> _runningTasks.remove(task); <END> _runningTasks.put(task, kafkaBasedConnectorTask); continue; } _logger.info("creating task for {}.", task); AbstractKafkaBasedConnectorTask connectorTask = createKafkaBasedConnectorTask(task); _runningTasks.put(task, connectorTask); _executor.submit(connectorTask); } }</code><technical_language>need remove() replaced in put()</technical_language>

Target:
public void onAssignmentChange(List<DatastreamTask> tasks) { _logger.info("onAssignmentChange called with tasks {}", tasks); HashSet<DatastreamTask> toCancel = new HashSet<>(_runningTasks.keySet()); toCancel.removeAll(tasks); for (DatastreamTask task : toCancel) { AbstractKafkaBasedConnectorTask connectorTask = _runningTasks.remove(task); connectorTask.stop(); } for (DatastreamTask task : tasks) { AbstractKafkaBasedConnectorTask kafkaBasedConnectorTask = _runningTasks.get(task); if (kafkaBasedConnectorTask != null) { kafkaBasedConnectorTask.checkForUpdateTask(task); _runningTasks.put(task, kafkaBasedConnectorTask); continue; } _logger.info("creating task for {}.", task); AbstractKafkaBasedConnectorTask connectorTask = createKafkaBasedConnectorTask(task); _runningTasks.put(task, connectorTask); _executor.submit(connectorTask); } }
Source:
<code>public List<ArtifactId> getBranchViewsForApplicability(BranchId branch, ApplicabilityId applId) { List<ArtifactId> arts = new ArrayList<>(); <START> <END> for (Iterator<Long> iterator = queryFactory.tupleQuery().getTuple2E1ListRaw(CoreTupleTypes.ViewApplicability, branch, applId.getId()).iterator(); iterator.hasNext();) { Long long1 = iterator.next(); arts.add(ArtifactId.valueOf(long1)); } return arts; }</code><technical_language>need access iterator, just: for (Long long1: queryFactory.tupleQuery().getTuple2E1ListRaw(CoreTupleTypes.ViewApplicability, branch, applId.getId()) { ... }</technical_language>

Target:
public List<ArtifactId> getBranchViewsForApplicability(BranchId branch, ApplicabilityId applId) { List<ArtifactId> arts = new ArrayList<>(); for (Long long1 : queryFactory.tupleQuery().getTuple2E1ListRaw(CoreTupleTypes.ViewApplicability, branch, applId.getId())) { arts.add(ArtifactId.valueOf(long1)); } return arts; }
Source:
<code>static double convertTimeUnit(final double valueFrom, final TimeUnit unitFrom, final TimeUnit unitTo) { <START> if (unitFrom.ordinal() < unitTo.ordinal()) { <END> return valueFrom / unitFrom.convert(1, unitTo); } else { return valueFrom * unitTo.convert(1, unitFrom); } }</code><technical_language>Relying enum ordering scary. instead java double toPerFrom = unitTo.convert(1, unitFrom) if (toPerFrom == 0) { toPerFrom = 1 / unitFrom.convert(1, unitTo) } return valueFrom * multiplicativeFactor final double result = valueFrom * toPerFrom semantically equivalent</technical_language>

Target:
static double convertTimeUnit(final double valueFrom, final TimeUnit unitFrom, final TimeUnit unitTo) { final long conversionRateTo = unitTo.convert(1, unitFrom); if (conversionRateTo == 0) { return valueFrom / unitFrom.convert(1, unitTo); } return valueFrom * conversionRateTo; }
Source:
<code>public void finish() { String shellText = new DefaultShell().getText(); new PushButton("Finish").click(); <START> new WaitWhile(new ShellIsActive(shellText)); <END> }</code><technical_language>ShellIsAvailable</technical_language>

Target:
public void finish() { String shellText = new DefaultShell().getText(); new PushButton("Finish").click(); new WaitWhile(new ShellIsAvailable(shellText)); }
Source:
<code>@Override public E peek() { lock.lock(); try { if (queue.isEmpty()) { <START> return null; <END> } return queue.peek(); } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); return null; } finally { lock.unlock(); } }</code><technical_language>here, simply return queue.peek(); (avoiding redundant isEmpty check)</technical_language>

Target:
@Override public E peek() { lock.lock(); try { return queue.peek(); } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
<code>protected static String performInstanceDataMatching(final QName infrastructureNodeType, final Map<String, String> infrastructureProperties) { <START> if (infrastructureNodeType != null) { <END> final Set<Entry<String, String>> infrastructureEntrySet = getEntrySetWithoutState(infrastructureProperties); final NodeTemplateInstance matchingInstance = nodeTemplateInstanceRepository.findByTemplateType(infrastructureNodeType).stream() .filter((instance) -> instance.getServiceTemplateInstance().getState() .equals(ServiceTemplateInstanceState.CREATED)) .filter((instance) -> instance.getState() .equals(NodeTemplateInstanceState.STARTED)) .filter((instance) -> isBuildPlanFinished(instance)) .filter((instance) -> getEntrySetWithoutState(instance.getPropertiesAsMap()).equals(infrastructureEntrySet)) .findFirst().orElse(null); if (matchingInstance != null) { if (matchingInstance.getManagingContainer() == null) { return Settings.OPENTOSCA_CONTAINER_HOSTNAME; } else { return matchingInstance.getManagingContainer(); } } } return null; }</code><technical_language>this is a check of argument. Annotate @NonNull static code-analysis handle this</technical_language>

Target:
protected static String performInstanceDataMatching(final QName infrastructureNodeType, final Map<String, String> infrastructureProperties) { Objects.requireNonNull(infrastructureNodeType, "QName for NodeType of infrastructure node must not be null for instance data matching"); final Set<Entry<String, String>> infrastructureEntrySet = getEntrySetWithoutState(infrastructureProperties); final NodeTemplateInstance matchingInstance = nodeTemplateInstanceRepository.findByTemplateType(infrastructureNodeType).stream() .filter(instance -> instance.getServiceTemplateInstance().getState() .equals(ServiceTemplateInstanceState.CREATED)) .filter(instance -> instance.getState() .equals(NodeTemplateInstanceState.STARTED)) .filter(instance -> isBuildPlanFinished(instance)) .filter(instance -> getEntrySetWithoutState(instance.getPropertiesAsMap()).equals(infrastructureEntrySet)) .findFirst().orElse(null); if (Objects.nonNull(matchingInstance)) { if (Objects.isNull(matchingInstance.getManagingContainer())) { return Settings.OPENTOSCA_CONTAINER_HOSTNAME; } else { return matchingInstance.getManagingContainer(); } } return null; }
Source:
<code>private CompletableFuture<Layout> getLatestLayout(List<String> layoutServers) { <START> CompletableFuture<Layout> latestLayoutFuture = null; <END> long latestEpoch = -1; List<CompletableFuture<Layout>> layoutFutures = new ArrayList<>(); for (String layoutServer : layoutServers) { try { log.debug("Trying to connect to layout server: {}", layoutServer); IClientRouter router = getRouter(layoutServer); CompletableFuture<Layout> layoutFuture = new LayoutClient(router, Layout.INVALID_EPOCH).getLayout(); layoutFutures.add(layoutFuture); } catch (Exception ex) { log.warn("Tried to connect to layoutServer but failed with exception:", layoutServer, ex); } } for (CompletableFuture<Layout> layoutFuture : layoutFutures) { try { Layout l = layoutFuture.get(); if (l.getEpoch() > latestEpoch) { latestEpoch = l.getEpoch(); latestLayoutFuture = layoutFuture; } } catch (Exception e) { log.warn("Tried to get layout from server but failed with exception:", layoutFuture, e); } } if (latestLayoutFuture == null) { latestLayoutFuture = new CompletableFuture<>(); latestLayoutFuture.completeExceptionally( new Exception("Could not fetch layout from any of the layout servers.")); } return latestLayoutFuture; }</code><technical_language>getLatestLayout return a Layout, if null return a dummy layout -1 epoch. in fetchLayout wrap this a future return</technical_language>

Target:
private Layout getLatestLayout(List<String> layoutServers) { long latestEpoch = -1; Layout latestLayout = null; int quorum = (layoutServers.size() / 2) + 1; CompletableFuture<Layout>[] layoutFutures = new CompletableFuture[layoutServers.size()]; for(int i = 0; i < layoutServers.size(); i++) { try { log.debug("Trying to connect to layout server: {}", layoutServers.get(i)); IClientRouter router = getRouter(layoutServers.get(i)); CompletableFuture<Layout> layoutFuture = new LayoutClient(router, Layout.INVALID_EPOCH).getLayout(); layoutFutures[i] = layoutFuture; } catch (Exception ex) { CompletableFuture<Layout> future = new CompletableFuture<Layout>(); future.completeExceptionally(ex); layoutFutures[i] = future; } } int responseCount = 0; for(int i = 0; i < layoutFutures.length; i++) { try { Layout l = (Layout) CompletableFuture.anyOf(layoutFutures).get(); responseCount++; if (l.getEpoch() > latestEpoch) { latestEpoch = l.getEpoch(); latestLayout = l; } if(responseCount >= quorum) { return latestLayout; } }catch(Exception ex) { log.warn("Tried to get layout from server but failed with exception:{}", layoutServers.get(i), ex); } } return latestLayout; }
Source:
<code><START> public void testValidationDomainClass() { TreeIterator<EObject> elements = modelerForDomainClassValidation.eAllContents(); int rand = 0; while (elements.hasNext()) { EObject current = elements.next(); for (EAttribute attribute : current.eClass().getEAllAttributes()) { if ("domainClass".equals(attribute.getName())) { editDomainClassValue(current, attribute, rand); if (rand < 3) { rand++; } else { rand = 0; } } } } Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(modelerForDomainClassValidation); assertEquals("The VSM is not valid, it should have popup error message", Diagnostic.ERROR, diagnostic.getSeverity()); } <END></code><technical_language>duplication previous method</technical_language>

Target:
public void testValidationDomainClass() { TreeIterator<EObject> elements = modelerForDomainClassValidation.eAllContents(); int i = 0; while (elements.hasNext()) { EObject current = elements.next(); for (EAttribute attribute : current.eClass().getEAllAttributes()) { if ("domainClass".equals(attribute.getName())) { editDomainClassValue(current, attribute, i); if (i < 3) { i++; } else { i = 0; } } } } Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(modelerForDomainClassValidation); assertEquals("The VSM is not valid, it should have popup error message", Diagnostic.ERROR, diagnostic.getSeverity()); }
Source:
<code>public void writeObject(ObjectOutput output, CompositeKeyFilter object) throws IOException { <START> output.writeInt(object.filters.length); <END> for (KeyFilter filter : object.filters) { output.writeObject(filter); } }</code><technical_language>able writeUnsignedInt method UnsignedNumeric class</technical_language>

Target:
public void writeObject(ObjectOutput output, CompositeKeyFilter object) throws IOException { UnsignedNumeric.writeUnsignedInt(output, object.filters.length); for (KeyFilter filter : object.filters) { output.writeObject(filter); } }
Source:
<code>protected void modified(Map<String, Object> config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { <START> logger.error("Invalid configuration value: {}. It MUST be Number.", value); <END> } }</code><technical_language>I prefer a warning default - means runtime easily recover invalid config value</technical_language>

Target:
protected void modified(Map<String, Object> config) { Object value = config == null ? null : config.get(CONFIG_PROPERTY_REINITIALIZATION_DELAY); this.scheduleReinitializationDelay = (value != null && value instanceof Number) ? (((Number) value).longValue()) : DEFAULT_REINITIALIZATION_DELAY; if (value != null && !(value instanceof Number)) { logger.warn("Invalid configuration value: {}. It MUST be Number.", value); } }
Source:
<code><START> public ProjectQualityGate getQualityGate52() throws Exception { <END> String url = serverUrl + API_PROJECT_STATUS + "?projectKey=" + projectKey; String text = client.getHttp(url, username, password); JSONObject json = (JSONObject) JSONSerializer.toJSON(text); JSONObject projectStatus = json.getJSONObject("projectStatus"); String status = projectStatus.getString("status"); String projectName = getProjectName(); return new ProjectQualityGate(projectName, status); }</code><technical_language>![MAJOR](<LINK_0> Define throw a dedicated exception instead of a generic one. [![rule](<LINK_2>](<LINK_1></technical_language>

Target:
public ProjectQualityGate getQualityGate52() throws Exception { String url = serverUrl + API_PROJECT_STATUS + encode(projectKey); String text = client.getHttp(url, username, password); JSONObject json = (JSONObject) JSONSerializer.toJSON(text); JSONObject projectStatus = json.getJSONObject("projectStatus"); String status = projectStatus.getString("status"); String projectName = getProjectName(); return new ProjectQualityGate(projectName, status); }
Source:
<code>public static void main(String[] args) throws IOException, TimeoutException, TException { FProtocolFactory protocolFactory = new FProtocolFactory(new TBinaryProtocol.Factory()); ConnectionFactory cf = new ConnectionFactory(ConnectionFactory.DEFAULT_URL); Connection conn = cf.createConnection(); FTransport transport = new FNatsTransport(conn, NatsServer.SERVICE_SUBJECT); transport.open(); FStore.Client storeClient = new FStore.Client(transport, protocolFactory); FContext context = new FContext(); context.setTimeout(1000); Album album = storeClient.buyAlbum(context, "ASIN-1290AIUBOA89", "ACCOUNT-12345"); System.out.println("Bought the album: " + album); <START> storeClient.enterAlbumGiveaway(context, "kevin@workiva.com", "Kevin"); <END> transport.close(); conn.close(); }</code><technical_language>Reusing FContext in other examples still</technical_language>

Target:
public static void main(String[] args) throws IOException, TimeoutException, TException { FProtocolFactory protocolFactory = new FProtocolFactory(new TBinaryProtocol.Factory()); ConnectionFactory cf = new ConnectionFactory(ConnectionFactory.DEFAULT_URL); Connection conn = cf.createConnection(); FTransport transport = new FNatsTransport(conn, NatsServer.SERVICE_SUBJECT); transport.open(); FStore.Client storeClient = new FStore.Client(transport, protocolFactory); Album album = storeClient.buyAlbum(new FContext("corr-id-1"), "ASIN-1290AIUBOA89", "ACCOUNT-12345"); System.out.println("Bought the album: " + album); storeClient.enterAlbumGiveaway(new FContext("corr-id-2"), "kevin@workiva.com", "Kevin"); transport.close(); conn.close(); }
Source:
<code>public void shutdown() { fListeners = new ListenerList<>(); fLaunchesListeners = new ListenerList<>(); fLaunchConfigurationListeners = new ListenerList<>(); ILaunch[] launches = getLaunches(); ILaunch launch = null; for (ILaunch <START> launche : <END> launches) { launch = launche; if(launch != null) { try { if (launch instanceof IDisconnect) { IDisconnect disconnect = (IDisconnect)launch; if (disconnect.canDisconnect()) { disconnect.disconnect(); } } if (launch.canTerminate()) { launch.terminate(); } } catch (DebugException e) { DebugPlugin.log(e); } } } persistPreferredLaunchDelegates(); clearAllLaunchConfigurations(); fStepFilterManager = null; ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); }</code><technical_language>rename launch</technical_language>

Target:
public void shutdown() { fListeners = new ListenerList<>(); fLaunchesListeners = new ListenerList<>(); fLaunchConfigurationListeners = new ListenerList<>(); for (ILaunch launch : getLaunches()) { if(launch != null) { try { if (launch instanceof IDisconnect) { IDisconnect disconnect = (IDisconnect)launch; if (disconnect.canDisconnect()) { disconnect.disconnect(); } } if (launch.canTerminate()) { launch.terminate(); } } catch (DebugException e) { DebugPlugin.log(e); } } } persistPreferredLaunchDelegates(); clearAllLaunchConfigurations(); fStepFilterManager = null; ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); }
Source:
<code>public long reload() { Long adjustedValue = jdbcTemplate.queryForObject(adjustedValueQuery, Long.class); if (adjustedValue == null) { adjustedValue = cachedAdjustedValue.get(); logger.warn("adjusted value is null. use {}", adjustedValue); } else if (isUseCache()) { <START> logger.debug("cache adjustd value = {}", adjustedValue); <END> cachedAdjustedValue.set(adjustedValue); } return adjustedValue; }</code><technical_language>typo. modify adjusted</technical_language>

Target:
public long reload() { Long adjustedValue = jdbcTemplate.queryForObject(adjustedValueQuery, Long.class); if (adjustedValue == null) { adjustedValue = cachedAdjustedValue.get(); logger.warn("adjusted value is null. use {}", adjustedValue); } else if (isUseCache()) { logger.debug("cache adjusted value = {}", adjustedValue); cachedAdjustedValue.set(adjustedValue); } return adjustedValue; }
Source:
<code>private JSONObject updateContainers(JSONObject containersPayload) throws RestServiceException { Short accountId = RestUtils.getNumericalHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_ID, false, Short::parseShort); String accountName = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_NAME, false); if (accountId == null && accountName == null) { throw new RestServiceException("Missing required header: " + RestUtils.Headers.TARGET_ACCOUNT_NAME, RestServiceErrorCode.BadRequest); } Account account = accountName != null ? accountService.getAccountByName(accountName) : accountService.getAccountById(accountId); if (account == null) { <START> throw new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.BadRequest); <END> } accountId = account.getId(); accountName = account.getName(); Collection<Container> containersToUpdate; try { containersToUpdate = AccountCollectionSerde.containersFromJson(containersPayload, accountId); } catch (JSONException e) { throw new RestServiceException("Bad container update request body", e, RestServiceErrorCode.BadRequest); } try { Collection<Container> updatedContainers = accountService.updateContainers(accountName, containersToUpdate); return AccountCollectionSerde.containersToJson(updatedContainers); } catch (AccountServiceException ex) { throw new RestServiceException("Container update failed for accountId " + accountId, RestServiceErrorCode.BadRequest); } }</code><technical_language>NotFound error code</technical_language>

Target:
private JSONObject updateContainers(JSONObject containersPayload) throws RestServiceException { Short accountId = RestUtils.getNumericalHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_ID, false, Short::parseShort); String accountName = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_NAME, false); if (accountId == null && accountName == null) { throw new RestServiceException("Missing required header: " + RestUtils.Headers.TARGET_ACCOUNT_NAME, RestServiceErrorCode.BadRequest); } Account account = accountName != null ? accountService.getAccountByName(accountName) : accountService.getAccountById(accountId); if (account == null) { throw new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.NotFound); } accountId = account.getId(); accountName = account.getName(); Collection<Container> containersToUpdate; try { containersToUpdate = AccountCollectionSerde.containersFromJson(containersPayload, accountId); } catch (JSONException e) { throw new RestServiceException("Bad container update request body", e, RestServiceErrorCode.BadRequest); } try { Collection<Container> updatedContainers = accountService.updateContainers(accountName, containersToUpdate); return AccountCollectionSerde.containersToJson(updatedContainers); } catch (AccountServiceException ex) { throw new RestServiceException("Container update failed for accountId " + accountId, RestServiceErrorCode.getRestServiceErrorCode(ex.getErrorCode())); } }
Source:
<code>public void drawGridLines(Rectangle bounds, GC gc) { if (!fGridLinesVisible) { return; } gc.setForeground(fGridLineColor); gc.setAlpha(fGridLineColor.getAlpha()); for (int x : fTimeGraphScale.getTickList()) { gc.drawLine(x, bounds.y, x, bounds.y + bounds.height); } <START> gc.setAlpha(BLACK.getAlpha()); <END> }</code><technical_language>OPAQUE</technical_language>

Target:
public void drawGridLines(Rectangle bounds, GC gc) { if (!fGridLinesVisible) { return; } gc.setForeground(fGridLineColor); gc.setAlpha(fGridLineColor.getAlpha()); for (int x : fTimeGraphScale.getTickList()) { gc.drawLine(x, bounds.y, x, bounds.y + bounds.height); } gc.setAlpha(OPAQUE); }
Source:
<code>private static Version parseBuiltInMetricsVersion(final String builtInMetricsVersion) { <START> if (builtInMetricsVersion.equals("latest")) { <END> return Version.LATEST; } else { return Version.FROM_100_TO_23; } }</code><technical_language>confused this, removed StreamsConfig.METRICS_LATEST config, replaced a literal string of thing. EDIT: NM re-reading PR I I get</technical_language>

Target:
private static Version parseBuiltInMetricsVersion(final String builtInMetricsVersion) { if (builtInMetricsVersion.equals(StreamsMetricsImpl.METRICS_LATEST)) { return Version.LATEST; } else { return Version.FROM_100_TO_23; } }
Source:
<code>GoogleAnalyticsNavigationTracker( @GaAccount String gaAccount, PlaceManager placeManager, EventBus eventBus, GoogleAnalytics analytics) { this.gaAccount = gaAccount; this.placeManager = placeManager; this.eventBus = eventBus; this.analytics = analytics; <START> if (GWT.isScript()) { <END> Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { init(); } }); } }</code><technical_language>needed anymore, fixed bug "localhost" ga.js</technical_language>

Target:
GoogleAnalyticsNavigationTracker(@GaAccount String gaAccount, PlaceManager placeManager, EventBus eventBus, GoogleAnalytics analytics) { this.gaAccount = gaAccount; this.placeManager = placeManager; this.eventBus = eventBus; this.analytics = analytics; Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { init(); } }); }
Source:
<code>public void deleteDefaultReadGroups(Collection collection) throws Exception { try (Context c = new Context()) { c.turnOffAuthorisationSystem(); Group defaultItemReadGroup = groupService.findByName(c, "COLLECTION_" + collection.getID().toString() + "_ITEM_DEFAULT_READ"); Group defaultBitstreamReadGroup = groupService.findByName(c, "COLLECTION_" + collection.getID().toString() + "_BITSTREAM_DEFAULT_READ"); if (defaultItemReadGroup != null) { groupService.delete(c, defaultItemReadGroup); } if (defaultBitstreamReadGroup != null) { groupService.delete(c, defaultBitstreamReadGroup); } c.complete(); } <START> indexingService.commit(); <END> }</code><technical_language>this is needed. do need commit indexing service here? need do this deleting other type of Group (see other delete methods in this Builder). If unnecessary, recommend removing</technical_language>

Target:
public void deleteDefaultReadGroups(Collection collection) throws Exception { try (Context c = new Context()) { c.turnOffAuthorisationSystem(); Group defaultItemReadGroup = groupService.findByName(c, "COLLECTION_" + collection.getID().toString() + "_ITEM_DEFAULT_READ"); Group defaultBitstreamReadGroup = groupService.findByName(c, "COLLECTION_" + collection.getID().toString() + "_BITSTREAM_DEFAULT_READ"); if (defaultItemReadGroup != null) { groupService.delete(c, defaultItemReadGroup); } if (defaultBitstreamReadGroup != null) { groupService.delete(c, defaultBitstreamReadGroup); } c.complete(); } }
Source:
<code>public boolean operate(ITreeTraverserContext<INodePO> ctx, INodePO parent, INodePO node, boolean alreadyVisited) { <START> if (alreadyVisited) { return true; } <END> clearNodeFromTeststyleProblem(node); for (BaseCheck chk : ProblemCont.instance.getChecksFor(node)) { int severity = getIntForSeverity(chk.getSeverity()); String message = chk.getDescription(); if (severity > IStatus.INFO) { node.addProblem(ProblemFactory.createProblem( new Status(severity, Activator.PLUGIN_ID, message))); } } if (node instanceof IExecTestCasePO) { IExecTestCasePO execTestCase = (IExecTestCasePO) node; handleExecTestCase(execTestCase); } return true; }</code><technical_language>This check is adding removing problem / nodes. Returning true leads a prune of child-tree branch beneath node. this "rule" (skipping visited nodes) applied node types e.g. ExecTCs e.g. if parent is re-used in contexts, occurring multiple times a traversing run relevant problem cleanup new problem creation</technical_language>

Target:
public boolean operate(ITreeTraverserContext<INodePO> ctx, INodePO parent, INodePO node, boolean alreadyVisited) { clearNodeFromTeststyleProblem(node); for (BaseCheck chk : ProblemCont.instance.getChecksFor(node)) { int severity = getIntForSeverity(chk.getSeverity()); String message = chk.getDescription(); if (severity > IStatus.INFO) { node.addProblem(ProblemFactory.createProblem( new Status(severity, Activator.PLUGIN_ID, message))); } } if (node instanceof IExecTestCasePO) { IExecTestCasePO execTestCase = (IExecTestCasePO) node; handleExecTestCase(execTestCase); } return true; }
Source:
<code>public boolean configure(StaplerRequest req, JSONObject json) throws FormException { Jenkins j = Jenkins.get(); if (json.has("primaryView")) { final String viewName = json.getString("primaryView"); final View newPrimaryView = j.getView(viewName); if (newPrimaryView == null) { throw new FormException(Messages.GlobalDefaultViewConfiguration_ViewDoesNotExist(viewName), "primaryView"); } j.setPrimaryView(newPrimaryView); } else { <START> if(j.getViews().iterator().hasNext()) { <END> j.setPrimaryView(j.getViews().iterator().next()); } } return true; }</code><technical_language>Related</technical_language>

Target:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { Jenkins j = Jenkins.get(); if (json.has("primaryView")) { final String viewName = json.getString("primaryView"); final View newPrimaryView = j.getView(viewName); if (newPrimaryView == null) { throw new FormException(Messages.GlobalDefaultViewConfiguration_ViewDoesNotExist(viewName), "primaryView"); } j.setPrimaryView(newPrimaryView); } else { Iterator<View> iter = j.getViews().iterator(); if(iter.hasNext()) { j.setPrimaryView(iter.next()); } } return true; }
Source:
<code>protected void initializeExtraSubystemsAndModel(ExtensionRegistry registry, Resource root, ManagementResourceRegistration registration, RuntimeCapabilityRegistry capabilityRegistry) { <START> List<String> list = new ArrayList<>(); <END> for (String requirement : this.requirements) { list.add(requirement); } registerCapabilities(capabilityRegistry, list.toArray(new String[0])); }</code><technical_language>Intermediate ArrayList is unnecessary</technical_language>

Target:
protected void initializeExtraSubystemsAndModel(ExtensionRegistry registry, Resource root, ManagementResourceRegistration registration, RuntimeCapabilityRegistry capabilityRegistry) { registerCapabilities(capabilityRegistry, this.requirements.stream().toArray(String[]::new)); }
Source:
<code>public DoubleStream stream() { <START> return Arrays.stream(elements); <END> }</code><technical_language>is this needed</technical_language>

Target:
public DoubleStream stream() { int effectiveSize = Math.min(count, samples.length); return Arrays.stream(samples, 0, effectiveSize); }
Source:
<code>public MesosCluster(String clusterId) { this.clusterId = clusterId; List<Container> containers = dockerClient.listContainersCmd().exec(); Collections.sort(containers, (c1,c2) -> Long.compare(c1.getCreated(), c2.getCreated())); for (Container container : containers) { for (String name : container.getNames()) { <START> if (name.matches("^/minimesos-.+-" + clusterId + "-\\d+$")) { <END> String[] parts = name.split("-"); String role = parts[1]; String uuid = parts[3]; switch (role) { case "zookeeper": this.containers.add(new ZooKeeper(dockerClient, clusterId, uuid)); break; case "agent": this.containers.add(new MesosSlave(dockerClient, clusterId, uuid)); break; case "master": this.containers.add(new MesosMaster(dockerClient, clusterId, uuid)); break; case "marathon": this.containers.add(new Marathon(dockerClient, clusterId, uuid)); } break; } } } if (containers.isEmpty()) { throw new RuntimeException("No containers found for cluster ID " + clusterId); } if (getZkContainer() != null) { for (MesosSlave mesosSlave : getSlaves()) { mesosSlave.setZooKeeperContainer(getZkContainer()); } getMesosMasterContainer().setZooKeeperContainer(getZkContainer()); getMarathonContainer().setZooKeeper(getZkContainer()); } }</code><technical_language>enforce naming convention, put composing parsing containers' names a separated class</technical_language>

Target:
private MesosCluster(String clusterId) { this.clusterId = clusterId; List<Container> containers = dockerClient.listContainersCmd().exec(); Collections.sort(containers, (c1,c2) -> Long.compare(c1.getCreated(), c2.getCreated())); ZooKeeper zkKeeper = null; for (Container container : containers) { String name = ContainerName.getFromDockerNames(container.getNames()); if (ContainerName.belongsToCluster(name, clusterId)) { String containerId = container.getId(); String[] parts = name.split("-"); String role = parts[1]; String uuid = parts[3]; switch (role) { case "zookeeper": zkKeeper = new ZooKeeper(dockerClient, clusterId, uuid, containerId); this.containers.add(zkKeeper); break; case "agent": this.containers.add(new MesosSlave(dockerClient, clusterId, uuid, containerId)); break; case "master": this.containers.add(new MesosMaster(dockerClient, clusterId, uuid, containerId)); break; case "marathon": this.containers.add(new Marathon(dockerClient, clusterId, uuid, containerId)); break; } } } if (containers.isEmpty()) { throw new RuntimeException("No containers found for cluster ID " + clusterId); } if (zkKeeper != null) { for (MesosSlave mesosSlave : getSlaves()) { mesosSlave.setZooKeeperContainer(zkKeeper); } getMasterContainer().setZooKeeperContainer(zkKeeper); getMarathonContainer().setZooKeeper(zkKeeper); } }
Source:
<code>public void testOptions() throws Exception { mockMvc.perform(get("/tasks/ctr/options").accept(MediaType.APPLICATION_JSON)) <START> .andDo(print()) <END> .andExpect(status().isOk()) .andExpect(jsonPath("$.[?(@.id == 'oauth2-client-credentials-scopes')].name", hasItems("oauth2-client-credentials-scopes"))); }</code><technical_language>remove print()</technical_language>

Target:
public void testOptions() throws Exception { mockMvc.perform(get("/tasks/ctr/options").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.[?(@.id == 'oauth2-client-credentials-scopes')].name", hasItems("oauth2-client-credentials-scopes"))); }
Source:
<code>public Mono<Void> runAsync() { return receiverAsync .receiveMessages() .map(messageContext -> { <START> return messageContext; <END> }) .take(options.getMessagesToReceive()) .then(); }</code><technical_language>checking received msg count > 0 other places</technical_language>

Target:
public Mono<Void> runAsync() { return receiverAsync .receiveMessages() .take(options.getMessagesToReceive()) .map(serviceBusReceivedMessageContext -> { return serviceBusReceivedMessageContext; }).then(); }
Source:
<code>private void processBufferWindow( List<RowMetaAndData> list ) { if ( isProcessing.compareAndSet( false, true ) ) { if ( this.fallbackSubject != null ) { this.fallbackSubject.dispose(); this.fallbackSubject = this.fallbackBuffer.subscribe( bufferList -> processFallbackWindow( bufferList ) ); } hasWindow.compareAndSet( false, true ); unSubscribeStarter(); setCacheWindow( list ); <START> isProcessing.compareAndSet( true, false ); <END> } }</code><technical_language>set compare</technical_language>

Target:
private void processBufferWindow( List<RowMetaAndData> list ) { if ( isProcessing.compareAndSet( false, true ) ) { if ( this.fallbackSubject != null ) { this.fallbackSubject.dispose(); this.fallbackSubject = this.fallbackBuffer.subscribe( bufferList -> processFallbackWindow( bufferList ) ); } hasWindow.set( true ); unSubscribeStarter(); setCacheWindow( list ); isProcessing.set( false ); } }
Source:
<code>public void create(String namespace) throws AccumuloException, AccumuloSecurityException, NamespaceExistsException { checkArgument(namespace != null, "namespace is null"); checkArgument(namespace.length() <= MAX_NAMESPACE_LEN, <START> "Namespace is longer than 1024 characters"); <END> try { doNamespaceFateOperation(FateOperation.NAMESPACE_CREATE, Arrays.asList(ByteBuffer.wrap(namespace.getBytes(UTF_8))), Collections.emptyMap(), namespace); } catch (NamespaceNotFoundException e) { throw new AssertionError(e); } }</code><technical_language>suggestion "Namespace is longer "+MAX_NAMESPACE_LEN+" characters");</technical_language>

Target:
public void create(String namespace) throws AccumuloException, AccumuloSecurityException, NamespaceExistsException { checkArgument(namespace != null, "namespace is null"); checkArgument(namespace.length() <= MAX_NAMESPACE_LEN, "Namespace is longer than " + MAX_NAMESPACE_LEN + " characters"); try { doNamespaceFateOperation(FateOperation.NAMESPACE_CREATE, Arrays.asList(ByteBuffer.wrap(namespace.getBytes(UTF_8))), Collections.emptyMap(), namespace); } catch (NamespaceNotFoundException e) { throw new AssertionError(e); } }
Source:
<code>public void visit(QueryMetadata.Builder queryBuilder) { <START> System.out.println(queryBuilder.getNodeId()); <END> ids.add(queryBuilder.getNodeId()); super.visit(queryBuilder); }</code><technical_language>do need print a test</technical_language>

Target:
public void visit(QueryMetadata.Builder queryBuilder) { ids.add(queryBuilder.getNodeId()); super.visit(queryBuilder); }
Source:
<code>static Object[][] roleNameProvider() { return new Object[][] { new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, <START> new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, <END> new Object[] {"patientenfederatie-nederland", "Member", "patientenfederatie-nederland_MEMBER"} }; }</code><technical_language>In new situation this line duplicated</technical_language>

Target:
static Object[][] roleNameProvider() { return new Object[][] { new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, new Object[] {"patientenfederatie-nederland", "Member", "patientenfederatie-nederland_MEMBER"} }; }
Source:
<code>public void initialize() { logger.debug("Initializing IOTA bridge"); Configuration config = getThing().getConfiguration(); <START> setHost(getOrDefault(config.get(IotaBindingConstants.HOST), getHost())); <END> setProtocol(getOrDefault(config.get(IotaBindingConstants.PROTOCOL), getProtocol())); setPort(getOrDefault(config.get(IotaBindingConstants.PORT), getPort())); setUtils(new IotaUtils(protocol, host, port)); if (utils.checkAPI()) { logger.debug("IOTA API checked, connexion successfull: bridge can be set ONLINE"); updateStatus(ThingStatus.ONLINE); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Node unreachable"); } }</code><technical_language>again, default please</technical_language>

Target:
public void initialize() { logger.debug("Initializing IOTA bridge"); Configuration configuration = getThing().getConfiguration(); setHost((String) configuration.get(IotaBindingConstants.HOST)); setProtocol((String) configuration.get(IotaBindingConstants.PROTOCOL)); int port = configuration.get(IotaBindingConstants.PORT) == null ? 0 : ((BigDecimal) configuration.get(IotaBindingConstants.PORT)).intValue(); setPort(port); try { this.utils.setIotaAPI(protocol, host, port); } catch (IllegalStateException e) { logger.warn("Wrong configuration detected: please check your configuration {}", e); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Node unreachable"); } if (utils.checkAPI()) { logger.debug("IOTA API checked, connexion successfull: bridge can be set ONLINE"); updateStatus(ThingStatus.ONLINE); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Node unreachable"); } }
Source:
<code>public ExtractRepresentationAction(Session session, Collection<DRepresentation> selection) { super(); this.session = session; this.representations = Collections2.filter(selection, new Predicate<DRepresentation>() { @Override public boolean apply(DRepresentation input) { EObject container = input.eContainer(); if (container instanceof DRepresentationContainer) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(container); if (permissionAuthority != null && <START> !permissionAuthority.canCreateIn(container)) { <END> return false; } } return true; } }); final ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(SiriusEditPlugin.ID, "/icons/full/others/export.gif"); this.setImageDescriptor(descriptor); this.setText("Extract to ." + SiriusUtil.SESSION_RESOURCE_EXTENSION + " file ..."); if (this.representations.isEmpty()) { this.setEnabled(false); } }</code><technical_language>call a canDeleteInstance(input)</technical_language>

Target:
public ExtractRepresentationAction(Session session, Collection<DRepresentation> selection) { super(); this.session = session; this.representations = Collections2.filter(selection, new Predicate<DRepresentation>() { @Override public boolean apply(DRepresentation input) { EObject container = input.eContainer(); if (container instanceof DRepresentationContainer) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(container); if (permissionAuthority != null && !permissionAuthority.canDeleteInstance(container)) { return false; } } return true; } }); final ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(SiriusEditPlugin.ID, "/icons/full/others/export.gif"); this.setImageDescriptor(descriptor); this.setText("Extract to ." + SiriusUtil.SESSION_RESOURCE_EXTENSION + " file ..."); if (this.representations.isEmpty()) { this.setEnabled(false); } }
Source:
<code>protected Collection<Event> analyzePosition(Position position) { Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); if (device == null) { return null; } if (!Context.getDeviceManager().isLatestPosition(position) || !position.getValid()) { return null; } Collection<Event> events = new ArrayList<>(); double speed = position.getSpeed(); double speedLimit = 0; if (device.getAttributes().containsKey(ATTRIBUTE_SPEED_LIMIT)) { speedLimit = Double.parseDouble((String) device.getAttributes().get(ATTRIBUTE_SPEED_LIMIT)); } if (speedLimit == 0 && checkGroups) { long groupId = device.getGroupId(); while (groupId != 0) { if (Context.getDeviceManager().getGroupById(groupId).getAttributes() .containsKey(ATTRIBUTE_SPEED_LIMIT)) { speedLimit = Double.parseDouble((String) Context.getDeviceManager().getGroupById(groupId) .getAttributes().get(ATTRIBUTE_SPEED_LIMIT)); if (speedLimit != 0) { break; } } if (Context.getDeviceManager().getGroupById(groupId) != null) { groupId = Context.getDeviceManager().getGroupById(groupId).getGroupId(); } else { groupId = 0; } } } if (speedLimit == 0) { try { Server server = Context.getDataManager().getServer(); if (server.getAttributes().containsKey(ATTRIBUTE_SPEED_LIMIT)) { speedLimit = Double.parseDouble((String) server.getAttributes().get(ATTRIBUTE_SPEED_LIMIT)); } } catch (SQLException error) { Log.warning(error); } } double oldSpeed = 0; if (riseOnce) { Position lastPosition = Context.getDeviceManager().getLastPosition(position.getDeviceId()); if (lastPosition != null) { oldSpeed = lastPosition.getSpeed(); } } speedLimit = UnitsConverter.knotsFromKph(speedLimit); <START> if (speedLimit != 0 && speed > speedLimit && oldSpeed <= speedLimit) { <END> try { if (Context.getDataManager().getLastEvents( position.getDeviceId(), Event.TYPE_DEVICE_OVERSPEED, suppressRepeated).isEmpty()) { events.add(new Event(Event.TYPE_DEVICE_OVERSPEED, position.getDeviceId(), position.getId())); } } catch (SQLException error) { Log.warning(error); } } return events; }</code><technical_language>Great, thanks again</technical_language>

Target:
protected Collection<Event> analyzePosition(Position position) { Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); if (device == null) { return null; } if (!Context.getDeviceManager().isLatestPosition(position) || !position.getValid()) { return null; } Collection<Event> events = new ArrayList<>(); double speed = position.getSpeed(); double speedLimit = 0; String speedLimitAttribute = Context.getDeviceManager().lookupAttribute(device.getId(), ATTRIBUTE_SPEED_LIMIT); if (speedLimitAttribute != null) { speedLimit = Double.parseDouble(speedLimitAttribute); } if (speedLimit == 0) { return null; } double oldSpeed = 0; if (notRepeat) { Position lastPosition = Context.getDeviceManager().getLastPosition(position.getDeviceId()); if (lastPosition != null) { oldSpeed = lastPosition.getSpeed(); } } speedLimit = UnitsConverter.knotsFromKph(speedLimit); if (speed > speedLimit && oldSpeed <= speedLimit) { events.add(new Event(Event.TYPE_DEVICE_OVERSPEED, position.getDeviceId(), position.getId())); } return events; }