auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public IFileInfo getFileInfo(IFileStore store) { ICVSRemoteFolder folder=null; String resourceName = null; CVSURI cvsUri = CVSURI.fromUri(store.toURI()); folder = cvsUri.getParentFolder(); resourceName = cvsUri.getLastSegment(); if (folder.getName().equals(ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME)) { FileInfo info = new FileInfo(); info.setExists(true); info.setName(resourceName); info.setDirectory(true); return info; } try { RemoteFolderTree remoteFolder = (RemoteFolderTree) remoteFolders.get(folder.getName()); if (remoteFolder == null){ String repoPath = folder.getRepositoryRelativePath(); IPath repoPath2 = new Path(repoPath); repoPath2 = repoPath2.removeFirstSegments(1); remoteFolder = (RemoteFolderTree) remoteFolders.get(repoPath2.toString()); } if (remoteFolder == null) remoteFolder = remoteTree; ICVSRemoteResource[] children =remoteFolder.getChildren(); ICVSResource resource = null; for (ICVSRemoteResource c : children) { <START> ICVSResource child = c; <END> if (child.getName().equals(resourceName)) { resource = child; break; } } return getFileInfo(resource, new NullProgressMonitor()); } catch (CoreException e) { CVSProviderPlugin.log(e); return null; } }</code><technical_language>moved in for loop</technical_language>

Target:
public IFileInfo getFileInfo(IFileStore store) { ICVSRemoteFolder folder=null; String resourceName = null; CVSURI cvsUri = CVSURI.fromUri(store.toURI()); folder = cvsUri.getParentFolder(); resourceName = cvsUri.getLastSegment(); if (folder.getName().equals(ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME)) { FileInfo info = new FileInfo(); info.setExists(true); info.setName(resourceName); info.setDirectory(true); return info; } try { RemoteFolderTree remoteFolder = (RemoteFolderTree) remoteFolders.get(folder.getName()); if (remoteFolder == null){ String repoPath = folder.getRepositoryRelativePath(); IPath repoPath2 = new Path(repoPath); repoPath2 = repoPath2.removeFirstSegments(1); remoteFolder = (RemoteFolderTree) remoteFolders.get(repoPath2.toString()); } if (remoteFolder == null) remoteFolder = remoteTree; ICVSRemoteResource[] children =remoteFolder.getChildren(); ICVSResource resource = null; for (ICVSRemoteResource child : children) { if (child.getName().equals(resourceName)) { resource = child; break; } } return getFileInfo(resource, new NullProgressMonitor()); } catch (CoreException e) { CVSProviderPlugin.log(e); return null; } }
Source:
<code>public Message sign$getLine(int index) throws IndexOutOfBoundsException { <START> if(index > signText.length) throw new IndexOutOfBoundsException(); <END> return SpongeMessage.of(signText[index]); }</code><technical_language>Guava a [checkElementIndex](<LINK_0>, int%29) below, this check currently fails detect negative indexes</technical_language>

Target:
public Message sign$getLine(int index) throws IndexOutOfBoundsException { checkElementIndex(index, signText.length); return SpongeMessage.of(signText[index]); }
Source:
<code>public static void inspectGcsFile() throws InterruptedException, ExecutionException, IOException { String projectId = "your-project-id"; <START> String gcsUri = "gs://" + "your-bucket-name" + "/path/to/your/test.txt"; <END> String pubSubTopicId = "your-pubsub-topic-id"; String pubSubSubscriptionId = "your-pubsub-subscription-id"; inspectGcsFile(projectId, gcsUri, pubSubTopicId, pubSubSubscriptionId); }</code><technical_language>nit: suggestion String gcsUri = "gs://" + "your-bucket-name" + "/path/to/your/file.txt";</technical_language>

Target:
public static void inspectGcsFile() throws InterruptedException, ExecutionException, IOException { String projectId = "your-project-id"; String gcsUri = "gs://" + "your-bucket-name" + "/path/to/your/file.txt"; String pubSubTopicId = "your-pubsub-topic-id"; String pubSubSubscriptionId = "your-pubsub-subscription-id"; inspectGcsFile(projectId, gcsUri, pubSubTopicId, pubSubSubscriptionId); }
Source:
<code>public static <R extends Product> QuantityTrade.Builder<R> builder(Security<R> security) { <START> return QuantityTrade.<R>builder().securityLink(SecurityLink.resolved(security)); <END> }</code><technical_language>return builder(SecurityLink.resolved(security)); simpler</technical_language>

Target:
public static <R extends Product> QuantityTrade.Builder<R> builder(Security<R> security) { return QuantityTrade.builder(SecurityLink.resolved(security)); }
Source:
<code>public void deleteScope(ScopeEvent event) { Scope scope = new Scope(); scope.setName(event.getName()); scope.setTimeStamp(event.getTimeStamp()); SubscriptionDataStore store = SubscriptionDataHolder.getInstance() .getTenantSubscriptionStore(event.getTenantDomain()); if (store == null) { if (log.isDebugEnabled()) { <START> log.debug("Ignoring the Event due to tenant " + event.getTenantDomain() + " not loaded"); <END> } return; } store.deleteScope(scope); }</code><technical_language>suggestion log.debug("Ignoring event tenant " + event.getTenantDomain() + " is loaded");</technical_language>

Target:
public void deleteScope(ScopeEvent event) { Scope scope = new Scope(); scope.setName(event.getName()); scope.setTimeStamp(event.getTimeStamp()); SubscriptionDataStore store = SubscriptionDataHolder.getInstance() .getTenantSubscriptionStore(event.getTenantDomain()); if (store == null) { if (log.isDebugEnabled()) { log.debug("Ignoring the event as the tenant " + event.getTenantDomain() + " is not loaded"); } return; } store.deleteScope(scope); }
Source:
<code>public boolean shouldRun() { final boolean shouldRun = <START> pendingPartitions != null && <END> pendingPartitions.size() > 0; return shouldRun; }</code><technical_language>null? This means locks throw NPE? accessing this object synchronized lock? I get is strategy is here. Again: object set null FOR SYNCHRONIZATION. Please null objects for synchronization</technical_language>

Target:
public boolean shouldRun() { final boolean shouldRun = pendingPartitions.size() > 0; return shouldRun; }
Source:
<code>public void levelLost() { stop(); <START> addToLog("[GAME}\t[LOST]\tYou just lost the game, kind of."); <END> loadCurrentLevel(); }</code><technical_language>Type-o here: [GAME} <naming</technical_language>

Target:
public void levelLost() { stop(); gameOver(); addToLog("[GAME]\t[LOST]\tYou just lost the game, kind of."); }
Source:
<code>public void updateAsync(T value, Executor executor) { if (!running) throw new IllegalLifecycleStateException(); lastValue = Objects.requireNonNull(value); try { executor.execute(() -> checkConditions(value)); } catch (Throwable t) { <START> for (Data data : futures.values()) { <END> data.cancelFuture.cancel(false); data.completeExceptionally(t); } } }</code><technical_language>need synchronized well? futures.values()</technical_language>

Target:
public void updateAsync(T value, Executor executor) { if (!running) throw new IllegalLifecycleStateException(); lastValue = Objects.requireNonNull(value); try { executor.execute(() -> checkConditions(value)); } catch (Throwable t) { List<CompletableFuture<?>> completed; synchronized (futures) { completed = new ArrayList<>(futures.size()); for (Data data : futures.values()) { data.cancelFuture.cancel(false); completed.add(data); } } for (CompletableFuture<?> future : completed) { future.completeExceptionally(t); } } }
Source:
<code>public void start() throws Exception { if (!clusteringService.isOpen()) { throw new IllegalStateException("The clustering service has not been started"); } localJournal.start(); long lastChangeSetTime = -1; Records allLocalRecords = localJournal.allRecords(true); <START> if (allLocalRecords.size() > 0) { <END> lastChangeSetTime = allLocalRecords.iterator().next().getChangeTimeMillisUTC(); } clusteringService.addConsumer(this); if (clusteringService.multipleMembersInCluster()) { deltaReconciliationCompleted.set(false); this.expectedNumberOfDeltaResponses.compareAndSet(0, clusteringService.membersInCluster() - 1); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending delta request from journal {0} as part of cluster {1}", journalId(), clusterName()); } clusteringService.sendMessage(DeltaMessage.request(journalId(), lastChangeSetTime)); waitForReconciliationToComplete(); } else { this.deltaReconciliationCompleted.set(true); } }</code><technical_language>Records isEmpty method? easier more efficient implement that, care size (and size large). Is a find Record</technical_language>

Target:
public void start() throws Exception { if (!clusteringService.isOpen()) { throw new IllegalStateException("The clustering service has not been started"); } localJournal.start(); clusteringService.addConsumer(this); if (clusteringService.multipleMembersInCluster()) { int numberOfExpectedResponses = clusteringService.membersInCluster() - 1; reconciliationLatch = new CountDownLatch(numberOfExpectedResponses); this.expectedNumberOfDeltaResponses.compareAndSet(0, numberOfExpectedResponses); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending delta request from journal {0} as part of cluster {1}", journalId(), clusterName()); } JournalRecord lastRecord = lastRecord(); DateTime lastChangeSetTimeMillis = lastRecord != null ? new DateTime(lastRecord.getChangeTimeMillis()) : null; clusteringService.sendMessage(DeltaMessage.request(journalId(), lastChangeSetTimeMillis)); waitForReconciliationToComplete(); } else { this.reconciliationLatch = new CountDownLatch(0); } }
Source:
<code>public <T extends Entity> T createEntityProxy(EntitySpec<T> spec, T entity) { MutableSet.Builder<Class<?>> builder = MutableSet.<Class<?>>builder() .add(EntityProxy.class, Entity.class, EntityLocal.class, EntityInternal.class); if (spec.getType().isInterface()) { builder.add(spec.getType()); } else { log.warn("EntitySpec declared in terms of concrete type "+spec.getType()+"; should be supplied in terms of interface"); } builder.addAll(spec.getAdditionalInterfaces()); Set<Class<?>> interfaces = builder.build(); <START> AggregateClassLoader aggregateClassLoader = AggregateClassLoader.newInstanceWithNoLoaders(); <END> aggregateClassLoader.addFirst(entity.getClass().getClassLoader()); for(Class<?> iface : interfaces) { aggregateClassLoader.addLast(iface.getClassLoader()); } return (T) java.lang.reflect.Proxy.newProxyInstance( aggregateClassLoader, interfaces.toArray(new Class[interfaces.size()]), new EntityProxyImpl(entity)); }</code><technical_language>case is a classloader for spec.getImplementation() is entity.getClass() ? i sure. sure, worth a check if (spec.getImplementation()!=null && !spec.getImplementation().equals(entity.getClass()) { /\* log warn add original spec.getImplementation().getClassLoader() */ }</technical_language>

Target:
public <T extends Entity> T createEntityProxy(EntitySpec<T> spec, T entity) { MutableSet.Builder<Class<?>> builder = MutableSet.<Class<?>>builder() .add(EntityProxy.class, Entity.class, EntityLocal.class, EntityInternal.class); if (spec.getType().isInterface()) { builder.add(spec.getType()); } else { log.warn("EntitySpec declared in terms of concrete type "+spec.getType()+"; should be supplied in terms of interface"); } builder.addAll(spec.getAdditionalInterfaces()); Set<Class<?>> interfaces = builder.build(); Collection<ClassLoader> loaders = Sets.newLinkedHashSet(); addClassLoaders(entity.getClass(), loaders); for(Class<?> iface : interfaces) { loaders.add(iface.getClassLoader()); } AggregateClassLoader aggregateClassLoader = AggregateClassLoader.newInstanceWithNoLoaders(); for (ClassLoader cl : loaders) { aggregateClassLoader.addLast(cl); } return (T) java.lang.reflect.Proxy.newProxyInstance( aggregateClassLoader, interfaces.toArray(new Class[interfaces.size()]), new EntityProxyImpl(entity)); }
Source:
<code><START> protected void runNow(String ruleUID, boolean considerConditions){ <END> RuntimeRule rule = getRuntimeRule(ruleUID); if (rule == null) { logger.warn("Fail to execute rule '{}': {}", ruleUID, "Invalid Rule UID."); return; } synchronized (this) { final RuleStatus ruleStatus = getRuleStatus(ruleUID); if (ruleStatus != RuleStatus.IDLE) { logger.error("Failed to execute rule ‘{}' with status '{}'", ruleUID, ruleStatus.name()); return; } setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.RUNNING),true); } try { clearContext(rule); if (considerConditions) { if (calculateConditions(rule)) { executeActions(rule, false); } } else { executeActions(rule, false); } logger.debug("The rule '{}' is executed.", ruleUID); } catch (Throwable t) { logger.error("Fail to execute rule '{}': {}", new Object[] { ruleUID, t.getMessage() }, t); } synchronized (this) { if (getRuleStatus(ruleUID) == RuleStatus.RUNNING) { setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.IDLE),true); } } }</code><technical_language>code formatter missing? a space curly bracket a lot of tabs in here..</technical_language>

Target:
protected void runNow(String ruleUID, boolean considerConditions) { RuntimeRule rule = getRuntimeRule(ruleUID); if (rule == null) { logger.warn("Failed to execute rule '{}': Invalid Rule UID", ruleUID); return; } synchronized (this) { final RuleStatus ruleStatus = getRuleStatus(ruleUID); if (ruleStatus != RuleStatus.IDLE) { logger.error("Failed to execute rule ‘{}' with status '{}'", ruleUID, ruleStatus.name()); return; } setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.RUNNING), true); } try { clearContext(rule); if (considerConditions) { if (calculateConditions(rule)) { executeActions(rule, false); } } else { executeActions(rule, false); } logger.debug("The rule '{}' is executed.", ruleUID); } catch (Throwable t) { logger.error("Fail to execute rule '{}': {}", new Object[] { ruleUID, t.getMessage() }, t); } synchronized (this) { if (getRuleStatus(ruleUID) == RuleStatus.RUNNING) { setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.IDLE), true); } } }
Source:
<code>private void processSignal(Signal signal) { logger.debug("Processing signal: {}", signal); switch (signal.getType()) { case START: start(signal.getTarget(), signal.getPayload()); break; case RETRANSMIT: process(signal).accept(signal); break; case UPDATE_SUBSCRIPTION: case UPDATE_TOPIC: process(signal).accept(signal); <START> break; <END> case RESTART: case KILL_RESTART: kill(process(signal)); taskQueue.offer(Signal.of(Signal.SignalType.START, signal.getTarget())); break; case STOP: process(signal).accept(signal); taskQueue.offer(Signal.of(Signal.SignalType.CLEANUP, signal.getTarget())); break; case CLEANUP: cleanup(process(signal)); break; default: break; } }</code><technical_language>I RETRANSMIT, UPDATE_SUBSCRIPTION UPDATE_TOPIC handled way</technical_language>

Target:
private void processSignal(Signal signal) { try { logger.debug("Processing signal: {}", signal); metrics.counter("supervisor.signal." + signal.getType().name()).inc(); switch (signal.getType()) { case START: start(signal.getTarget(), signal.getPayload()); break; case RETRANSMIT: process(signal).accept(signal); break; case UPDATE_SUBSCRIPTION: case UPDATE_TOPIC: process(signal).accept(signal); break; case RESTART: case KILL_RESTART: Consumer consumer = process(signal).getConsumer(); kill(process(signal)); taskQueue.offer(Signal.of(Signal.SignalType.START, signal.getTarget(), consumer)); break; case STOP: process(signal).accept(signal); taskQueue.offer(Signal.of(Signal.SignalType.CLEANUP, signal.getTarget())); break; case CLEANUP: cleanup(process(signal)); break; default: break; } } catch (Exception exception) { logger.error("Supervisor failed to process signal {}", signal, exception); } }
Source:
<code>public void validateFindingNotificationId() { String notificationURI = "<LINK_0>"; String expectedNotifcationId = "gWu2zdPNXG6oQHp0VDaEmNn77NGJ5aQ9rww"; String actualNotificationId = concurEventNotificationServiceImpl.findNotificationId(notificationURI); <START> assertEquals("Expeted NotificationId and ActualNotificationId should be the same", expectedNotifcationId, actualNotificationId); <END> }</code><technical_language>Minor typo in message</technical_language>

Target:
public void validateFindingNotificationId() { String notificationURI = "<LINK_0>"; String expectedNotifcationId = "gWu2zdPNXG6oQHp0VDaEmNn77NGJ5aQ9rww"; String actualNotificationId = concurEventNotificationServiceImpl.findNotificationId(notificationURI); assertEquals("Expected NotificationId and ActualNotificationId should be the same", expectedNotifcationId, actualNotificationId); }
Source:
<code><START> public void validateEmail(final String token, <END> final AsyncCallback<VoidResult> callback) { try { final ValidToken t = authConfig.getEmailRegistrationToken().checkToken(token, null); if (t == null || t.getData() == null || "".equals(t.getData())) { callback.onFailure(new IllegalStateException("Invalid token")); return; } final String newEmail = new String(Base64.decode(t.getData()), "UTF-8"); accountManager.link(user.get().getAccountId(), AuthRequest .forEmail(newEmail)); callback.onSuccess(VoidResult.INSTANCE); } catch (XsrfException e) { callback.onFailure(e); } catch (UnsupportedEncodingException e) { callback.onFailure(e); } catch (AccountException e) { callback.onFailure(e); } }</code><technical_language>'validateEmail' method removed check for '@' character in e-mail address. This method is ValidateEmailScreen play a role for feature implementing. This is I this method reverted, stays was</technical_language>

Target:
public void validateEmail(final String token, final AsyncCallback<VoidResult> callback) { try { final ValidToken t = authConfig.getEmailRegistrationToken().checkToken(token, null); if (t == null || t.getData() == null || "".equals(t.getData())) { callback.onFailure(new IllegalStateException("Invalid token")); return; } final String newEmail = new String(Base64.decode(t.getData()), "UTF-8"); if (!newEmail.contains("@")) { callback.onFailure(new IllegalStateException("Invalid token")); return; } accountManager.link(user.get().getAccountId(), AuthRequest .forEmail(newEmail)); callback.onSuccess(VoidResult.INSTANCE); } catch (XsrfException e) { callback.onFailure(e); } catch (UnsupportedEncodingException e) { callback.onFailure(e); } catch (AccountException e) { callback.onFailure(e); } }
Source:
<code>public String getImage(ImageName name) { <START> return u("images/%s/get", name.getNameWithoutTag()) <END> .build(); }</code><technical_language>I name tag Docker reference manual in case image of tags returned. full image name here</technical_language>

Target:
public String getImage(ImageName name) { return u("images/%s/get", name.getFullName()) .build(); }
Source:
<code>public void updateWith(Speaker speaker) { <START> final URI speakerPic = speaker.getPic(); <END> if (speakerPic != null) { imageLoader.load(speakerPic.toString(), avatar); } else { avatar.setImageResource(R.drawable.ic_nav_schedule); } name.setText(speaker.getName()); jobTitle.setText(speaker.getCompany()); }</code><technical_language>Extract method for setSpeakerPicture() business :)</technical_language>

Target:
public void updateWith(Speaker speaker) { setSpeakerPicture(speaker.getPic()); name.setText(speaker.getName()); jobTitle.setText(speaker.getCompany()); }
Source:
<code>public void setVisible (boolean visible) { checkWidget(); Canvas canvas = getParent(); <START> canvas.setBlink(true); <END> canvas.drawFlag = visible; getDisplay().resetCaretTiming(); if (visible == isVisible) return; isVisible = visible; if (!isFocusCaret ()) return; if (isVisible) { showCaret (); } else { hideCaret (); } }</code><technical_language>Again, do canvas.blink = true</technical_language>

Target:
public void setVisible (boolean visible) { checkWidget(); Canvas canvas = getParent(); canvas.blink = true; canvas.drawFlag = visible; getDisplay().resetCaretTiming(); if (visible == isVisible) return; isVisible = visible; if (!isFocusCaret ()) return; if (isVisible) { showCaret (); } else { hideCaret (); } }
Source:
<code>public TerminalPopupMenu(TerminalList terminals) { <START> super(); <END> RStudioGinjector.INSTANCE.injectMembers(this); terminals_ = terminals; }</code><technical_language>A Java constructor automatically a call no-argument super() this needed</technical_language>

Target:
public TerminalPopupMenu(TerminalList terminals) { RStudioGinjector.INSTANCE.injectMembers(this); terminals_ = terminals; }
Source:
<code>public void reload(final Injector injector) { <START> _periodicMetrics.recordCounter("cached_job_reload", 1); <END> final Optional<Job<T>> loaded = _ref.get(injector); if (!loaded.isPresent()) { throw new NoSuchElementException(_ref.toString()); } _cached = loaded.get(); _lastRun = _ref.getRepository(injector).getLastRun(_ref.getJobId(), _ref.getOrganization()); }</code><technical_language>as: if (!loaded.isPresent()) { _periodicMetrics.recordCounter("cached_job_reload", 0); throw ...; } _periodicMetrics.recordCounter("cached_job_reload", 1); ... Captures reloads count reload success rate (aka actual reloads) avg. missing here</technical_language>

Target:
public void reload(final Injector injector) throws NoSuchJobException { final Optional<Job<T>> loaded = _ref.get(injector); if (!loaded.isPresent()) { _periodicMetrics.recordCounter("cached_job_reload_success", 0); throw new NoSuchJobException(_ref.toString()); } _periodicMetrics.recordCounter("cached_job_reload_success", 1); _cached = loaded.get(); _lastRun = _ref.getRepository(injector).getLastRun(_ref.getJobId(), _ref.getOrganization()); }
Source:
<code>protected void dispose() { <START> ReentrantReadWriteLock.WriteLock lock = this.lock.writeLock(); <END> lock.lock(); try { referenceCount--; if (referenceCount <= 0) { LifecycleUtil.dispose(wrapped); wrapped = null; } } finally { lock.unlock(); } }</code><technical_language>I this is code correct, I rename local variable writeLock avoid confusion class variable</technical_language>

Target:
private void dispose() { ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); writeLock.lock(); try { referenceCount--; if (referenceCount <= 0) { LifecycleUtil.dispose(wrapped); wrapped = null; } } finally { writeLock.unlock(); } }
Source:
<code>public void removeProcessedGroupingRequests() { Iterator<Entry<String, GroupingRequest>> itr = groupingRequests.entrySet().iterator(); while (itr.hasNext()) { Entry<String, GroupingRequest> request = itr.next(); if (request.getValue().isProcessed()) { <START> LOG.debug("Removing Grouping request for :" + request.getKey()); <END> itr.remove(); } } }</code><technical_language>sl4j</technical_language>

Target:
public void removeProcessedGroupingRequests() { Iterator<Entry<String, GroupingRequest>> itr = groupingRequests.entrySet().iterator(); while (itr.hasNext()) { Entry<String, GroupingRequest> entry = itr.next(); if (entry.getValue().isProcessed()) { LOG.debug("Removing Grouping request for : {}", entry.getKey()); itr.remove(); } } }
Source:
<code>public <C extends Credential> C getCredential(Class<C> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { if (BearerTokenCredential.class.equals(credentialType)) { try { HttpRequest request = HttpClient.builder().sslContext(resolveSSLContext()).build() .post(tokenEndpointUri.toURL()) .param("grant_type", grantType); clientAuthenticator.accept(request); if (scopes != null) { request.param("scope", scopes); } return request.execute((inputStream, throwable) -> { if (throwable != null) { throw log.httpClientUnexpectedResponseFromServer(throwable); } JsonObject jsonObject = Json.createReader(inputStream).readObject(); String accessToken = jsonObject.getString("access_token"); <START> return (C) new BearerTokenCredential(accessToken); <END> }); } catch (Exception cause) { throw log.mechCallbackHandlerFailedForUnknownReason("OAuth2 Credentials Grant Type", cause); } } return null; }</code><technical_language>do credentialType.cast(...) instead of unsafe (C) cast generates a warning</technical_language>

Target:
public <C extends Credential> C getCredential(Class<C> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { if (credentialType.isAssignableFrom(credentialType)) { try { HttpURLConnection connection = null; try { connection = openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); HashMap<String, String> parameters = new HashMap<>(); parameters.put("grant_type", grantType); consumer.accept(parameters); if (scopes != null) { parameters.put("scope", scopes); } byte[] paramBytes = buildParameters(parameters); try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(paramBytes); } try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) { JsonObject jsonObject = Json.createReader(inputStream).readObject(); String accessToken = jsonObject.getString("access_token"); return credentialType.cast(new BearerTokenCredential(accessToken)); } } catch (IOException ioe) { InputStream errorStream = null; if (connection != null && connection.getErrorStream() != null) { errorStream = connection.getErrorStream(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) { StringBuffer response = reader.lines().reduce(new StringBuffer(), StringBuffer::append, (buffer1, buffer2) -> buffer1); log.errorf(ioe, "Unexpected response from server [%s]. Response: [%s]", tokenEndpointUri, response); } catch (IOException ignore) { } } throw log.mechUnableToHandleResponseFromServer("OAuth2CredentialSource", ioe); } } catch (Exception cause) { throw log.mechCallbackHandlerFailedForUnknownReason("OAuth2CredentialSource", cause); } } return null; }
Source:
<code>public synchronized KafkaPositionTracker build() { <START> if (_built) { <END> throw new IllegalStateException("Builder already used"); } _built = true; return new KafkaPositionTracker(_datastreamTaskPrefix, _datastreamTaskName, _connectorTaskStartTime, _enableBrokerOffsetFetcher, _isConnectorTaskAlive, _consumerSupplier); }</code><technical_language>1. Why? wrong builder construct multiple instances? 2. If insist, Apache Commons' Validate.isTrue() instead? 3. is _built volatile if build() is synchronized</technical_language>

Target:
public KafkaPositionTracker build() { return new KafkaPositionTracker(_datastreamTaskPrefix, _datastreamTaskName, _connectorTaskStartTime, _enableBrokerOffsetFetcher, _isConnectorTaskAlive, _consumerSupplier); }
Source:
<code>public void setDefinedSize_rangeEndEqualsAssumedSize_flushRequested() { fakeClientCommunication(); StateNode stateNode = Mockito.spy(element.getNode()); DataCommunicator<Item> dataCommunicator = new DataCommunicator<>( dataGenerator, arrayUpdater, data -> {}, stateNode); dataCommunicator.setPageSize(pageSize); dataCommunicator.setDataProvider(createDataProvider(), null); fakeClientCommunication(); dataCommunicator.setRequestedRange(0, 100); fakeClientCommunication(); Mockito.reset(stateNode); dataCommunicator.setDefinedSize(false); <START> Mockito.verify(stateNode).runWhenAttached(Mockito.anyObject()); <END> }</code><technical_language>(most?) other tests here, this (estimated) count is increased properly (which is desired outcome in terms of internal DC logic) instead of relying call flush done</technical_language>

Target:
public void setDefinedSize_rangeEndEqualsAssumedSize_flushRequested() { fakeClientCommunication(); StateNode stateNode = Mockito.spy(element.getNode()); DataCommunicator<Item> dataCommunicator = new DataCommunicator<>( dataGenerator, arrayUpdater, data -> {}, stateNode); dataCommunicator.setPageSize(pageSize); dataCommunicator.setDataProvider(createDataProvider(), null); fakeClientCommunication(); dataCommunicator.setRequestedRange(0, 100); fakeClientCommunication(); Mockito.reset(stateNode); dataCommunicator.setDefinedSize(false); fakeClientCommunication(); Mockito.verify(stateNode).runWhenAttached(Mockito.anyObject()); Assert.assertEquals(300, dataCommunicator.getItemCount()); }
Source:
<code>private void parseSegmentNodeChildren(Segment segment) throws XMLStreamException, TypeImportException { processChildren(LibraryElementTags.SEGMENT_ELEMENT, name -> { if <START> (name.equals(LibraryElementTags.ATTRIBUTE_ELEMENT)) <END> { if (isColorAttributeNode()) { parseColor(segment); } else { parseGenericAttributeNode(segment); } proceedToEndElementNamed(LibraryElementTags.ATTRIBUTE_ELEMENT); return true; } return false; }); }</code><technical_language>call equals constant</technical_language>

Target:
private void parseSegmentNodeChildren(Segment segment) throws XMLStreamException, TypeImportException { processChildren(LibraryElementTags.SEGMENT_ELEMENT, name -> { if (LibraryElementTags.ATTRIBUTE_ELEMENT.equals(name)) { if (isColorAttributeNode()) { parseColor(segment); } else { parseGenericAttributeNode(segment); } proceedToEndElementNamed(LibraryElementTags.ATTRIBUTE_ELEMENT); return true; } return false; }); }
Source:
<code>public void saveInEnvironment(String value, String envVar) throws Exception { <START> if (value == null) { <END> throw new Exception("Element to be saved: " + value + " is null"); } else { ThreadProperty.set(envVar, value); } }</code><technical_language>envVar wont null, empty strings, check valuable</technical_language>

Target:
public void saveInEnvironment(String value, String envVar) throws Exception { if (envVar.isEmpty()) { throw new Exception("Environment variable must be specified!"); } else { ThreadProperty.set(envVar, value); } }
Source:
<code>public void test_setForegroundLorg_eclipse_swt_graphics_Color() { Color color = new Color(control.getDisplay(), 255, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); control.setForeground(null); assertFalse(control.getForeground().equals(color)); <START> if (SwtTestUtil.isGTK3()) { <END> color = new Color (control.getDisplay(), 255, 0, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); } if ("gtk".equals(SWT.getPlatform ())) { Color bg = new Color(control.getDisplay(), 0, 255, 0); control.setForeground(color); control.setBackground(bg); assertEquals("Setting a background disrupted the foreground color for " + control, color, control.getForeground()); assertEquals("Setting a background onto a widget with a foreground failed for " + control, bg, control.getBackground()); } color.dispose(); }</code><technical_language>This runs Gtk3. set this run gtk2 instead? this work cocoa/win32</technical_language>

Target:
public void test_setForegroundLorg_eclipse_swt_graphics_Color() { Color color = new Color(control.getDisplay(), 255, 0, 0); control.setForeground(color); assertEquals(color, control.getForeground()); control.setForeground(null); assertFalse(control.getForeground().equals(color)); if ("gtk".equals(SWT.getPlatform ())) { Color bg = new Color(control.getDisplay(), 0, 255, 0); control.setForeground(color); control.setBackground(bg); assertEquals("Setting a background disrupted the foreground color for " + control, color, control.getForeground()); assertEquals("Setting a background onto a widget with a foreground failed for " + control, bg, control.getBackground()); } color.dispose(); }
Source:
<code>private String getContentType() { <START> switch (gcsTargetConfig.dataFormat.getLabel()) { <END> case "JSON": return "text/json"; case "CSV": return "text/csv"; } return null; }</code><technical_language>For simplicity, i suggest switch gcsTargetConfig.dataFormat instead of string</technical_language>

Target:
private String getContentType() { switch (gcsTargetConfig.dataFormat) { case JSON: return "text/json"; default: break; } return null; }
Source:
<code>public Session<String> getSession() { try { Session<String> session = mock(Session.class); willReturn(new String[] { "/foo/foo", "/foo/bar" }).given(session).list("/foo"); ByteArrayInputStream foo = new ByteArrayInputStream("foo\nbar".getBytes()); ByteArrayInputStream bar = new ByteArrayInputStream("baz\nqux".getBytes()); willReturn(foo).given(session).readRaw("/foo/foo"); willReturn(bar).given(session).readRaw("/foo/bar"); willReturn(new String[] { "/bar/foo", "/bar/bar" }).given(session).list("/bar"); ByteArrayInputStream foo2 = new ByteArrayInputStream("foo\r\nbar".getBytes()); ByteArrayInputStream bar2 = new ByteArrayInputStream("baz\r\nqux".getBytes()); willReturn(foo2).given(session).readRaw("/bar/foo"); willReturn(bar2).given(session).readRaw("/bar/bar"); given(session.finalizeRaw()).willReturn(true); return session; } catch (Exception e) { <START> fail("failed to mock session"); <END> } return null; }</code><technical_language>rethrow some RuntimeException enough? this fail() hide real issue, if modify mocking wrong way</technical_language>

Target:
public Session<String> getSession() { try { Session<String> session = mock(Session.class); willReturn(new String[] { "/foo/foo", "/foo/bar" }).given(session).list("/foo"); ByteArrayInputStream foo = new ByteArrayInputStream("foo\nbar".getBytes()); ByteArrayInputStream bar = new ByteArrayInputStream("baz\nqux".getBytes()); willReturn(foo).given(session).readRaw("/foo/foo"); willReturn(bar).given(session).readRaw("/foo/bar"); willReturn(new String[] { "/bar/foo", "/bar/bar" }).given(session).list("/bar"); ByteArrayInputStream foo2 = new ByteArrayInputStream("foo\r\nbar".getBytes()); ByteArrayInputStream bar2 = new ByteArrayInputStream("baz\r\nqux".getBytes()); willReturn(foo2).given(session).readRaw("/bar/foo"); willReturn(bar2).given(session).readRaw("/bar/bar"); given(session.finalizeRaw()).willReturn(true); return session; } catch (Exception e) { throw new RuntimeException("failed to mock session", e); } }
Source:
<code><START> boolean isDuplicatedIntervalEvent(AuditEvent newAuditEvent) { <END> if (newAuditEvent.isIntervalAuditEventType()) { for (AuditEvent aev : auditEvents) { if (aev.isIntervalAuditEventType() && newAuditEvent.getAuditEventType().equals(aev.getAuditEventType()) && newAuditEvent.getNode().equals(aev.getNode())) { return true; } } } return false; }</code><technical_language>this happen anymore limited a question refreshed. safe in for add a TODO: if needed ee784a1 if agree a chance longer needed</technical_language>

Target:
private boolean isDuplicatedIntervalEvent(AuditEvent newAuditEvent) { if (newAuditEvent.isIntervalAuditEventType()) { for (AuditEvent aev : auditEvents) { if (aev.isIntervalAuditEventType() && newAuditEvent.getAuditEventType().equals(aev.getAuditEventType()) && newAuditEvent.getFormIndex().equals(aev.getFormIndex())) { return true; } } } return false; }
Source:
<code><START> @Test public void smokes() throws Exception { <END> assertRoundTrip("test"); assertRoundTrip("."); assertRoundTrip(".."); assertRoundTrip("test/foo"); assertRoundTrip("test%bar"); assertRoundTrip("test #1"); }</code><technical_language>suggestion @Test public void smokes() throws Exception {</technical_language>

Target:
public void smokes() throws Exception { assertRoundTrip("test"); assertRoundTrip("."); assertRoundTrip(".."); assertRoundTrip("test/foo"); assertRoundTrip("test%bar"); assertRoundTrip("test #1"); }
Source:
<code>private Map<String, String[]> getQueryParameters(String queryString) { Map<String, String[]> queryParameters = new HashMap<>(); if (StringUtils.isEmpty(queryString)) { return queryParameters; } String[] parameters = queryString.split(QUERY_SEPERATOR); for (String parameter : parameters) { String[] keyValuePair = parameter.split(EQUAL); <START> String[] values = queryParameters.get(keyValuePair[0]); <END> values = (String[]) ArrayUtils.add(values, keyValuePair.length == 1 ? "" : keyValuePair[1]); queryParameters.put(keyValuePair[0], values); } return queryParameters; }</code><technical_language>URL Decode necessary for parameter name</technical_language>

Target:
private Map<String, String[]> getQueryParameters(String queryString) { Map<String, String[]> queryParameters = new HashMap<>(); if (StringUtils.isEmpty(queryString)) { return queryParameters; } String[] parameters = queryString.split(SPLITTING_CHAR); for (String parameter : parameters) { String[] keyValuePair = parameter.split(PADDING_CHAR); String[] values = queryParameters.get(keyValuePair[0]); values = (String[]) ArrayUtils.add(values, keyValuePair.length == 1 ? "" : keyValuePair[1]); queryParameters.put(keyValuePair[0], values); } return queryParameters; }
Source:
<code>public boolean isCompatible(Bundle bundle, IPath prefixedPath) { URL url = FileLocator.find(bundle, prefixedPath.append(SearchIndex.DEPENDENCIES_VERSION_FILENAME), null); if (url == null) { HelpBasePlugin.logError( prefixedPath.append(SearchIndex.DEPENDENCIES_VERSION_FILENAME) + " file missing from help index \"" + path + "\" of plugin " + getPluginId(), null); return false; } try (InputStream in = ProxyUtil.getStream(url)) { Properties prop = new Properties(); prop.load(in); String lucene = prop .getProperty(SearchIndex.DEPENDENCIES_KEY_LUCENE); String analyzer = prop .getProperty(SearchIndex.DEPENDENCIES_KEY_ANALYZER); if (!targetIndex.isLuceneCompatible(lucene) || !targetIndex.isAnalyzerCompatible(analyzer)) { HelpBasePlugin.logWarning( "Unable to consume Lucene index from bundle <START> " + <END> bundle.toString() + ". Index should be rebuilt with Lucene 6.1.", null); return false; } } catch (MalformedURLException mue) { return false; } catch (IOException ioe) { HelpBasePlugin.logError( "IOException accessing prebuilt index.", ioe); } return true; }</code><technical_language>' "</technical_language>

Target:
public boolean isCompatible(Bundle bundle, IPath prefixedPath) { URL url = FileLocator.find(bundle, prefixedPath.append(SearchIndex.DEPENDENCIES_VERSION_FILENAME), null); if (url == null) { HelpBasePlugin.logError( prefixedPath.append(SearchIndex.DEPENDENCIES_VERSION_FILENAME) + " file missing from help index \"" + path + "\" of plugin " + getPluginId(), null); return false; } try (InputStream in = ProxyUtil.getStream(url)) { Properties prop = new Properties(); prop.load(in); String lucene = prop .getProperty(SearchIndex.DEPENDENCIES_KEY_LUCENE); String analyzer = prop .getProperty(SearchIndex.DEPENDENCIES_KEY_ANALYZER); if (!targetIndex.isLuceneCompatible(lucene) || !targetIndex.isAnalyzerCompatible(analyzer)) { String message = "Not able to consume Lucene index from bundle " + bundle.toString() + ". The index should be rebuilt with Lucene 6.1."; Status warningStatus = new Status(IStatus.WARNING, HelpBasePlugin.PLUGIN_ID, IStatus.OK, message, null); HelpBasePlugin.logStatus(warningStatus); return false; } } catch (MalformedURLException mue) { return false; } catch (IOException ioe) { HelpBasePlugin.logError( "IOException accessing prebuilt index.", ioe); } return true; }
Source:
<code>public RssUpdate parseUpdate(String content){ <START> if(!StringUtils.isEmptyOrNull(content)) { <END> content = content.replaceAll("</?div>(\\n)?", ""); String[] parts = content.split("\n", 3); if (parts.length == 3) { return new RssUpdate(parts[0], parts[1], parts[2]); } } return null; }</code><technical_language>Please add a space if</technical_language>

Target:
public RssUpdate parseUpdate(String content){ if (!StringUtils.isEmptyOrNull(content)) { String[] parts = content.split("\n", 3); if (parts.length == 3) { return new RssUpdate(parts[0], parts[1], parts[2]); } } return null; }
Source:
<code>private CreateWsResponse doHandle(CreateRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { OrganizationDto organization = support.getOrganization(dbSession, ofNullable(request.getOrganization()) .orElseGet(defaultOrganizationProvider.get()::getKey)); userSession.checkPermission(PROVISION_PROJECTS, organization); String visibility = request.getVisibility(); Boolean changeToPrivate = visibility == null ? dbClient.organizationDao().getNewProjectPrivate(dbSession, organization) : "private".equals(visibility); <START> <END> ComponentDto componentDto = componentUpdater.create(dbSession, newComponentBuilder() .setOrganizationUuid(organization.getUuid()) .setKey(request.getKey()) .setName(request.getName()) .setBranch(request.getBranch()) .setPrivate(changeToPrivate) .setQualifier(PROJECT) .build(), userSession.isLoggedIn() ? userSession.getUserId() : null); return toCreateResponse(componentDto); } }</code><technical_language>remark: I understand getNewProjectPrivate name follow name conventions. I create method</technical_language>

Target:
private CreateWsResponse doHandle(CreateRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { OrganizationDto organization = support.getOrganization(dbSession, ofNullable(request.getOrganization()) .orElseGet(defaultOrganizationProvider.get()::getKey)); userSession.checkPermission(PROVISION_PROJECTS, organization); String visibility = request.getVisibility(); Boolean changeToPrivate = visibility == null ? dbClient.organizationDao().getNewProjectPrivate(dbSession, organization) : "private".equals(visibility); support.checkCanUpdateProjectsVisibility(organization, changeToPrivate); ComponentDto componentDto = componentUpdater.create(dbSession, newComponentBuilder() .setOrganizationUuid(organization.getUuid()) .setKey(request.getKey()) .setName(request.getName()) .setBranch(request.getBranch()) .setPrivate(changeToPrivate) .setQualifier(PROJECT) .build(), userSession.isLoggedIn() ? userSession.getUserId() : null); return toCreateResponse(componentDto); } }
Source:
<code><START> public static String <END> composeObjectId(AuditLogableBase logable, AuditLogType logType) { return composeObjectId(logable, logType, logable.getUserId()); }</code><technical_language>this method non-static private - of class</technical_language>

Target:
private String composeObjectId(AuditLogableBase logable, AuditLogType logType) { return composeObjectId(logable, logType, logable.getUserId()); }
Source:
<code>public void onApplicationEvent(UpdateFailedEvent event) { long autoscaleClusterId = event.getClusterId(); Cluster cluster = clusterService.findById(autoscaleClusterId); if (cluster == null) { return; } MDCBuilder.buildMdcContext(cluster); LOGGER.debug("Analysing Cluster Status '{}' ", cluster.getStackCrn()); StackV4Response stackResponse = getStackById(cluster.getStackCrn()); String stackStatus = getStackStatus(stackResponse); <START> if (stackResponse == null || stackStatus.startsWith(STOPPED_STATUSES_PREFIX)) { <END> LOGGER.debug("Suspending cluster '{}', Cloudbreak stack status '{}'", cluster.getStackCrn(), stackStatus); suspendCluster(cluster); return; } if (stackStatus.equalsIgnoreCase(DELETE_STATUS)) { clusterService.removeById(autoscaleClusterId); LOGGER.debug("Delete cluster '{}', Cloudbreak stack status '{}'.", cluster.getStackCrn(), stackStatus); return; } Integer failed = updateFailures.get(autoscaleClusterId); if (failed == null) { LOGGER.debug("New failed cluster : [{}]", cluster.getStackCrn()); updateFailures.put(autoscaleClusterId, 1); } else if (RETRY_THRESHOLD - 1 == failed) { Status clusterStatus = stackResponse.getCluster().getStatus(); if (stackStatus.equals(AVAILABLE) && clusterStatus != null && clusterStatus.name().equals(AVAILABLE)) { LOGGER.debug("Suspend cluster monitoring for cluster '{}' due to failing update attempts and Cloudbreak stack status '{}'", cluster.getStackCrn(), stackStatus); } else { LOGGER.debug("Suspend cluster monitoring for cluster '{}'", cluster.getStackCrn()); } suspendCluster(cluster); updateFailures.remove(autoscaleClusterId); } else { int value = failed + 1; LOGGER.debug("Increase failed count[{}] for cluster id: [{}]", value, cluster.getStackCrn()); updateFailures.put(autoscaleClusterId, value); } }</code><technical_language>create a list suspended statuses check contains not</technical_language>

Target:
public void onApplicationEvent(UpdateFailedEvent event) { long autoscaleClusterId = event.getClusterId(); Cluster cluster = clusterService.findById(autoscaleClusterId); if (cluster == null) { return; } MDCBuilder.buildMdcContext(cluster); Integer failed = Optional.ofNullable(updateFailures.get(autoscaleClusterId)) .map(failedCount -> failedCount + 1) .orElse(1); if (failed < RETRY_THRESHOLD) { updateFailures.put(autoscaleClusterId, failed); LOGGER.debug("Increased failed count '{}' for cluster '{}'", failed, cluster.getStackCrn()); } else { suspendCluster(cluster); updateFailures.remove(autoscaleClusterId); LOGGER.debug("Suspended cluster monitoring for cluster '{}' due to failing update attempts", cluster.getStackCrn()); } }
Source:
<code>public void setInformationStatus(RemoteServerState remoteServerState) { text.setText(""); String panelContent = ""; if (remoteServerState.getActualState() == RemoteServerState.State.OK || remoteServerState.getActualState() == RemoteServerState.State.NO_CREDIT) { panelContent = addLine(panelContent, "Connected as " + remoteServerState.getRealName()); panelContent = addLine(panelContent, "(email: " + remoteServerState.getEmail() + ")"); if (remoteServerState.getCredit() > 0) { panelContent = addLine(panelContent, "Your credit balance: " + creditFormatter(remoteServerState.getCredit())); } else { panelContent = addLine(panelContent, "Your credit: <font color=\"red\">" + creditFormatter(remoteServerState.getCredit()) + " </font>"); } if (!remoteServerState.isEmailConfirmed()) { panelContent = addLine(panelContent, "Email is not confirmed."); } } if (remoteServerState.getActualState() == RemoteServerState.State.UNKNOWN) { panelContent = addLine(panelContent, "Datacloud is not configured."); panelContent = addLine(panelContent, "You can set your credentials in"); <START> panelContent = addLine(panelContent, "<b>Options dialog - DataCloud</b>"); <END> } if (remoteServerState.getActualState() == RemoteServerState.State.ERROR) { panelContent = addLine(panelContent, "Cannot connect as " + remoteServerState.getEmail()); panelContent = addLine(panelContent, "<font color=\"red\">" + remoteServerState.getErrorMessage() + " </font>"); } text.setText(panelContent); }</code><technical_language>of this is do. this standard Swing components instead of inline HTML</technical_language>

Target:
public void setInformationStatus(RemoteServerState remoteServerState) { text.setText(""); String panelContent = ""; if (remoteServerState.getActualState() == RemoteServerState.State.OK || remoteServerState.getActualState() == RemoteServerState.State.NO_CREDIT) { panelContent = addLine(panelContent, "Connected as " + remoteServerState.getRealName()); panelContent = addLine(panelContent, "(email: " + remoteServerState.getEmail() + ")"); if (remoteServerState.getCredit() > 0) { panelContent = addLine(panelContent, "Your credit balance: " + String.format("%,d", remoteServerState.getCredit())); } else { panelContent = addLine(panelContent, "Your credit: <font color=\"red\">" + String.format("%,d", remoteServerState.getCredit()) + " </font>"); } if (!remoteServerState.isEmailConfirmed()) { panelContent = addLine(panelContent, "Email is not confirmed."); } } if (remoteServerState.getActualState() == RemoteServerState.State.NOT_CONNECTED) { panelContent = addLine(panelContent, "Datacloud is not configured."); panelContent = addLine(panelContent, "You can set your credentials in"); panelContent = addLine(panelContent, "<b>Options dialog - DataCloud</b>"); } if (remoteServerState.getActualState() == RemoteServerState.State.ERROR) { panelContent = addLine(panelContent, "Cannot connect as " + remoteServerState.getEmail()); panelContent = addLine(panelContent, "<font color=\"red\">" + remoteServerState.getErrorMessage() + " </font>"); } text.setText(panelContent); }