auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void createTagOptionGroup(Composite parent) { <START> final Group tagsGroup = new Group(parent, SWT.NULL); <END> tagsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); tagsGroup.setText(UIText.RefSpecPage_annotatedTagsGroup); tagsGroup.setLayout(new GridLayout()); createTagOptionButton(tagsGroup, TagOpt.AUTO_FOLLOW, UIText.RefSpecPage_annotatedTagsAutoFollow); createTagOptionButton(tagsGroup, TagOpt.FETCH_TAGS, UIText.RefSpecPage_annotatedTagsFetchTags); createTagOptionButton(tagsGroup, TagOpt.NO_TAGS, UIText.RefSpecPage_annotatedTagsNoTags); }</code><technical_language>This a large group radio buttons. a drop-down combo better</technical_language>

Target:
private void createTagOptionGroup(Composite parent) { final Group tagsGroup = new Group(parent, SWT.NULL); tagsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); tagsGroup.setText("tag fetching strategy" ); tagsGroup.setLayout(new GridLayout(3, false)); createTagOptionButton(tagsGroup, TagOpt.AUTO_FOLLOW, "Fetch tags on tracked branches", UIText.RefSpecPage_annotatedTagsAutoFollow); createTagOptionButton(tagsGroup, TagOpt.FETCH_TAGS, "Fetch all tags", UIText.RefSpecPage_annotatedTagsFetchTags); createTagOptionButton(tagsGroup, TagOpt.NO_TAGS, "Fetch no tags", UIText.RefSpecPage_annotatedTagsNoTags); }
Source:
<code>public void runAll(){ for(TestCase test: testcases){ <START> server.newGame(GridLoader.loadGrid("grid1.json")); <END> test.run(); } }</code><technical_language>"test/testGrid2.json". is grid1.json is reserved for tests</technical_language>

Target:
public void runAll(){ for(TestCase test: testcases){ server.newGame(GridLoader.loadGrid("test/testGrid2.json")); test.run(); } }
Source:
<code>public int emitBatches() { AtomicInteger numberOfBatches = new AtomicInteger(maxBatches); AtomicInteger scheduledTasks = new AtomicInteger(0); <START> emitter.computeBatches(MongoReplicationTask.class, qry -> enhanceQuery(qry, true), batchSize, batch -> { <END> distributedTasks.submitFIFOTask(ReplicationTaskExecutor.class, batch); scheduledTasks.addAndGet(batchSize); markTasksAsScheduled(batch); return numberOfBatches.decrementAndGet() > 0; }); return scheduledTasks.get(); }</code><technical_language>qry -> query</technical_language>

Target:
public int emitBatches() { AtomicInteger numberOfBatches = new AtomicInteger(maxBatches); AtomicInteger scheduledTasks = new AtomicInteger(0); emitter.computeBatches(MongoReplicationTask.class, qry -> filterOnExecutableTasks(qry, true), batchSize, batch -> { distributedTasks.submitFIFOTask(ReplicationTaskExecutor.class, batch); scheduledTasks.addAndGet(batchSize); markTasksAsScheduled(batch); return numberOfBatches.decrementAndGet() > 0; }); return scheduledTasks.get(); }
Source:
<code>public OAuthToken getToken(String oauthProviderName, String userId) throws IOException { <START> if (!userId.isEmpty()) { <END> try { UriBuilder ub = UriBuilder.fromUri(apiEndpoint) .path("/oauth/token/") .queryParam("oauth_provider", oauthProviderName); Link getTokenLink = DtoFactory.newDto(Link.class).withHref(ub.build().toString()).withMethod("GET"); OAuthToken token = HttpJsonHelper.request(OAuthToken.class, getTokenLink); if (token == null) { LOG.warn("Token not found for user {}", userId); return null; } return token; } catch (ServerException | NotFoundException | ForbiddenException | UnauthorizedException | ConflictException e) { LOG.error("Exception on token retrieval, message : {}", e.getLocalizedMessage()); return null; } } return null; }</code><technical_language>negative check avoid nesting, : java if (userId.isEmpty()) { return null; }</technical_language>

Target:
public OAuthToken getToken(String oauthProviderName, String userId) throws IOException { if (userId.isEmpty()) { return null; } try { UriBuilder ub = UriBuilder.fromUri(apiEndpoint) .path(OAuthAuthenticationService.class, "token") .queryParam("oauth_provider", oauthProviderName); Link getTokenLink = DtoFactory.newDto(Link.class).withHref(ub.build().toString()).withMethod("GET"); OAuthToken token = HttpJsonHelper.request(OAuthToken.class, getTokenLink); if (token == null) { LOG.warn("Token not found for user {}", userId); return null; } return token; } catch (ServerException | NotFoundException | ForbiddenException | UnauthorizedException | ConflictException e) { LOG.error("Exception on token retrieval, message : {}", e.getLocalizedMessage()); return null; } }
Source:
<code>public boolean areLoaded() { boolean result = true; String[] tags = getTags(); for (int i = 0; i < tags.length; i++) { <START> if (!isWidgetVisible(i)) { <END> result = false; PageObjectLogging.log(getTagName() + " #" + i, MercuryMessages.VISIBLE_MSG, result); break; } PageObjectLogging.log(getTagName() + " #" + i, MercuryMessages.VISIBLE_MSG, result); } PageObjectLogging.log("all " + getTagName() + " widgets", MercuryMessages.VISIBLE_MSG, result); return result; }</code><technical_language>more OO if tags list WidgetPageObject objects loop call: widget.isVisible() widget implement method</technical_language>

Target:
public boolean areLoaded() { boolean result = true; String[] tags = getTags(); for (int i = 0; i < tags.length; i++) { if (!isWidgetVisible(i)) { result = false; PageObjectLogging.log(getTagName() + " #" + i, MercuryMessages.INVISIBLE_MSG, result); return result; } PageObjectLogging.log(getTagName() + " #" + i, MercuryMessages.VISIBLE_MSG, result); } PageObjectLogging.log("all " + getTagName() + " widgets", MercuryMessages.VISIBLE_MSG, result); return result; }
Source:
<code>public AlleleFractionInitializer(final AlleleFractionData data) { <START> parameters = INITIAL_PARAMETERS; <END> minorFractions = initialMinorFractions(data); double previousIterationLogLikelihood; double nextIterationLogLikelihood = Double.NEGATIVE_INFINITY; logger.info(String.format("Initializing allele-fraction model. Iterating until log likelihood converges to within %.3f.", LOG_LIKELIHOOD_CONVERGENCE_THRESHOLD)); int iteration = 1; do { previousIterationLogLikelihood = nextIterationLogLikelihood; parameters = new AllelicBiasParameters(estimateMeanBias(data), estimateBiasVariance(data), estimateOutlierProbability(data)); minorFractions = estimateMinorFractions(data); nextIterationLogLikelihood = AlleleFractionLikelihoods.logLikelihood(parameters, minorFractions, data); logger.info(String.format("Iteration %d, model log likelihood = %.3f.", iteration, nextIterationLogLikelihood)); iteration++; } while (iteration < MAX_ITERATIONS && nextIterationLogLikelihood - previousIterationLogLikelihood > LOG_LIKELIHOOD_CONVERGENCE_THRESHOLD); }</code><technical_language>disadvantage of breaking state is doubling of lines below</technical_language>

Target:
public AlleleFractionInitializer(final AlleleFractionData data) { globalParameters = INITIAL_GLOBAL_PARAMETERS; minorFractions = initialMinorFractions(data); double previousIterationLogLikelihood; double nextIterationLogLikelihood = Double.NEGATIVE_INFINITY; logger.info(String.format("Initializing allele-fraction model. Iterating until log likelihood converges to within %.3f.", LOG_LIKELIHOOD_CONVERGENCE_THRESHOLD)); int iteration = 1; do { previousIterationLogLikelihood = nextIterationLogLikelihood; globalParameters = new AlleleFractionGlobalParameters(estimateMeanBias(data), estimateBiasVariance(data), estimateOutlierProbability(data)); minorFractions = estimateMinorFractions(data); nextIterationLogLikelihood = AlleleFractionLikelihoods.logLikelihood(globalParameters, minorFractions, data); logger.info(String.format("Iteration %d, model log likelihood = %.3f.", iteration, nextIterationLogLikelihood)); iteration++; } while (iteration < MAX_ITERATIONS && nextIterationLogLikelihood - previousIterationLogLikelihood > LOG_LIKELIHOOD_CONVERGENCE_THRESHOLD); }
Source:
<code>protected void testAccessControl() throws Exception { String[] submissionParams = new String[] {}; verifyAccessibleForStudents(submissionParams); <START> verifyAccessibleForAdminToMasqueradeAsInstructor(submissionParams); <END> }</code><technical_language>masquerade instructor</technical_language>

Target:
protected void testAccessControl() throws Exception { String[] submissionParams = new String[] {}; verifyAccessibleForStudents(submissionParams); }
Source:
<code>public void newArticleShowsUpOnSpecialNewPages() { ArticleContent articleContent = new ArticleContent(); String articleTitle = articleContent.createUniqueArticle(); SpecialNewPages specialNewPages = new SpecialNewPages(); specialNewPages.openSpecialNewPages(wikiURL); <START> specialNewPages.verifyContainsLinkToArticle(articleTitle); <END> }</code><technical_language>If possible, please assertion explicite in tests, wrap a check page-specific method</technical_language>

Target:
public void newArticleShowsUpOnSpecialNewPages() { ArticleContent articleContent = new ArticleContent(); String articleTitle = articleContent.createUniqueArticle(); SpecialNewPages specialNewPages = new SpecialNewPages().open(); Assert.assertTrue( specialNewPages.containsLinkToArticle(articleTitle), "Special:NewPages does not contain link to article named " + articleTitle ); }
Source:
<code><START> public SingleKeyJWSKeySelector(JWSAlgorithm expectedJwsAlgorithm, Key key) { <END> Assert.notNull(expectedJwsAlgorithm, "expectedJwsAlgorithm cannot be null"); Assert.notNull(key, "key cannot be null"); this.keySet = Arrays.asList(key); this.expectedJwsAlgorithm = expectedJwsAlgorithm; }</code><technical_language>remove public modifier class is package-private</technical_language>

Target:
SingleKeyJWSKeySelector(JWSAlgorithm expectedJwsAlgorithm, Key key) { Assert.notNull(expectedJwsAlgorithm, "expectedJwsAlgorithm cannot be null"); Assert.notNull(key, "key cannot be null"); this.keySet = Arrays.asList(key); this.expectedJwsAlgorithm = expectedJwsAlgorithm; }
Source:
<code>public int hashCode() { int hash = 7; final int prime = 31; <START> for (Entry<VdcParameter, Object> entry : paramsMap.entrySet()) { <END> hash = prime * hash + entry.getKey().hashCode(); hash = prime * hash + entry.getValue().hashCode(); } return hash; }</code><technical_language>AbstractMap::hashCode is enough</technical_language>

Target:
public int hashCode() { return paramsMap.hashCode(); }
Source:
<code><START> public String setClearAlarmRegister(final DlmsConnectionHolder conn, final DlmsDevice device, <END> final ClearAlarmRegisterRequestDto clearAlarmRegisterRequestDto) throws ProtocolAdapterException { this.clearAlarmRegisterCommandExecutor.execute(conn, device, clearAlarmRegisterRequestDto); return "Clear alarm register result is OK for device: " + device.getDeviceIdentification(); }</code><technical_language>Change method return type String void</technical_language>

Target:
public void setClearAlarmRegister(final DlmsConnectionHolder conn, final DlmsDevice device, final ClearAlarmRegisterRequestDto clearAlarmRegisterRequestDto) throws ProtocolAdapterException { this.clearAlarmRegisterCommandExecutor.execute(conn, device, clearAlarmRegisterRequestDto); }
Source:
<code>public void initialize(ConfigurableListableBeanFactory beanFactory) throws BeansException { <START> beanFactory.addBeanPostProcessor(new ChannelSecurityInterceptorBeanPostProcessor(beanFactory.getBeansOfType(ChannelSecurityInterceptor.class).values())); <END> }</code><technical_language>This suffers problem global channel interceptors. I subclass ChannelSecurityInterceptor, send a Message<?> a security violation occurs. This early instantiation channel referenced and, if implicit channel (input-channel), exist yet. proxying done channel initializer performed task. Another min_value phase SmartLifecyle</technical_language>

Target:
public void initialize(ConfigurableListableBeanFactory beanFactory) throws BeansException { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; if (!registry.containsBeanDefinition(CHANNEL_SECURITY_INTERCEPTOR_BPP_BEAN_NAME)) { registry.registerBeanDefinition(CHANNEL_SECURITY_INTERCEPTOR_BPP_BEAN_NAME, new RootBeanDefinition(ChannelSecurityInterceptorBeanPostProcessor.class)); } }
Source:
<code>private synchronized static String bindSessionWithConfig(String sessionPath) { final SyncSession syncSession = sessions.get(sessionPath); if (syncSession == null) { <START> throw new IllegalStateException("Matching Java SyncSession could not be found for: " + sessionPath); <END> } else { return syncSession.accessToken(authServer); } }</code><technical_language>this propagate correctly? I assume is called SyncClient thread</technical_language>

Target:
private synchronized static String bindSessionWithConfig(String sessionPath) { final SyncSession syncSession = sessions.get(sessionPath); if (syncSession == null) { RealmLog.error("Matching Java SyncSession could not be found for: " + sessionPath); } else { try { return syncSession.accessToken(authServer); } catch (Exception exception) { RealmLog.error(exception); } } return null; }
Source:
<code>public Shell getShell() { Display currentDisplay = Display.getCurrent(); <START> IWorkbenchWindow workbenchWindow = getWorkbenchWindow(); <END> if (currentDisplay == null) { return workbenchWindow != null ? workbenchWindow.getShell() : null; } Control control = (Control) model.getWidget(); if (control != null && !control.isDisposed()) { return control.getShell(); } if (e4Context == null) { WorkbenchPlugin.log(new IllegalStateException( "IWorkbenchSite.getShell() was called after part disposal: " + this)); return PlatformUI.getWorkbench().getDisplay().getActiveShell(); } MWindow window = e4Context.get(MWindow.class); return window == null ? workbenchWindow.getShell() : (Shell) window.getWidget(); }</code><technical_language>please revert changes here, needed / hide errors code re-use disposed parts</technical_language>

Target:
public Shell getShell() { Display currentDisplay = Display.getCurrent(); if (currentDisplay == null) { return getWorkbenchWindow().getShell(); } Control control = (Control) model.getWidget(); if (control != null && !control.isDisposed()) { return control.getShell(); } if (e4Context == null) { WorkbenchPlugin.log(new IllegalStateException( "IWorkbenchSite.getShell() was called after part disposal: " + this)); return PlatformUI.getWorkbench().getDisplay().getActiveShell(); } MWindow window = e4Context.get(MWindow.class); return window == null ? getWorkbenchWindow().getShell() : (Shell) window.getWidget(); }
Source:
<code>private void initButtons(){ <START> bGrad = new JRadioButton(I18N.tr("")); <END> bPal = new JRadioButton(""); bGrad.addActionListener( EventHandler.create(ActionListener.class, this, "onClickGrad")); bPal.addActionListener( EventHandler.create(ActionListener.class, this, "onClickPal")); bPal.setSelected(true); ButtonGroup bg = new ButtonGroup(); bg.add(bGrad); bg.add(bPal); onClickPal(); }</code><technical_language>set empty string I18N. Gathering strings in source code fail</technical_language>

Target:
private void initButtons(){ bGrad = new JRadioButton(""); bPal = new JRadioButton(""); bGrad.addActionListener( EventHandler.create(ActionListener.class, this, "onClickGrad")); bPal.addActionListener( EventHandler.create(ActionListener.class, this, "onClickPal")); bPal.setSelected(true); ButtonGroup bg = new ButtonGroup(); bg.add(bGrad); bg.add(bPal); onClickPal(); }
Source:
<code>private void tearDown() { try { processDestroyer.clean(); tmpDir.dispose(); } catch (IOException e) { <START> throw new UncheckedIOException(e); <END> } catch (InterruptedException e) { e.printStackTrace(System.err); } }</code><technical_language>Test methods more simply throws Exception</technical_language>

Target:
private void tearDown() throws IOException { try { processDestroyer.clean(); } catch (InterruptedException e) { e.printStackTrace(System.err); } }
Source:
<code>private ComputeEngineCredentials( HttpTransportFactory transportFactory, Collection<String> scopes) { this.transportFactory = firstNonNull( transportFactory, getFromServiceLoader(HttpTransportFactory.class, OAuth2Utils.HTTP_TRANSPORT_FACTORY)); this.transportFactoryClassName = this.transportFactory.getClass().getName(); <START> this.scopes = (scopes == null) ? ImmutableSet.<String>of() : ImmutableSet.copyOf(scopes); <END> }</code><technical_language>if collection is empty a string in collection is null empty</technical_language>

Target:
private ComputeEngineCredentials( HttpTransportFactory transportFactory, Collection<String> scopes) { this.transportFactory = firstNonNull( transportFactory, getFromServiceLoader(HttpTransportFactory.class, OAuth2Utils.HTTP_TRANSPORT_FACTORY)); this.transportFactoryClassName = this.transportFactory.getClass().getName(); if (scopes == null) { this.scopes = ImmutableSet.<String>of(); } else { List<String> scopeList = new ArrayList<String>(scopes); scopeList.removeAll(Arrays.asList("", null)); this.scopes = ImmutableSet.<String>copyOf(scopeList); } }
Source:
<code>private long getMemoryAlreadyBeingRevoked(Collection<SqlTask> sqlTasks, MemoryPool memoryPool) { AtomicLong memoryAlreadyBeingRevoked = new AtomicLong(); sqlTasks.stream() .filter(task -> task.getTaskInfo().getTaskStatus().getState() == TaskState.RUNNING) .filter(task -> task.getQueryContext().getMemoryPool() == memoryPool) <START> .forEach(task -> task.getQueryContext().accept(new TraversingQueryContextVisitor<Void, Void>() <END> { @Override public Void visitOperatorContext(OperatorContext operatorContext, Void context) { if (operatorContext.isMemoryRevokingRequested()) { memoryAlreadyBeingRevoked.addAndGet(operatorContext.getReservedRevocableBytes()); } return null; } }, null)); return memoryAlreadyBeingRevoked.get(); }</code><technical_language>I this simpler if change this forEach mapToLong, returning 0 getReservedRevocableBytes, LongStream.sum()</technical_language>

Target:
private long getMemoryAlreadyBeingRevoked(Collection<SqlTask> sqlTasks, MemoryPool memoryPool) { return sqlTasks.stream() .filter(task -> task.getTaskInfo().getTaskStatus().getState() == TaskState.RUNNING) .filter(task -> task.getQueryContext().getMemoryPool() == memoryPool) .mapToLong(task -> task.getQueryContext().accept(new TraversingQueryContextVisitor<Void, Long>() { @Override public Long visitOperatorContext(OperatorContext operatorContext, Void context) { if (operatorContext.isMemoryRevokingRequested()) { return operatorContext.getReservedRevocableBytes(); } return 0L; } @Override public Long mergeResults(List<Long> childrenResults) { return childrenResults.stream() .mapToLong(i -> i).sum(); } }, null)) .sum(); }
Source:
<code>private static void validateTableSource(ElideTableConfig elideTableConfig, String tableSource) { if (isNullOrEmpty(tableSource)) { return; } String[] split = tableSource.split("\\."); if (split.length != 2) { throw new IllegalStateException("Invalid tableSource: " + tableSource + ". tableSource must be in format: modelName.columnName"); } String modelName = split[0]; String fieldName = split[1]; if (!staticModelContainsField(modelName, NO_VERSION, fieldName) && !dynamicModelContainsField(elideTableConfig, modelName, fieldName)) { throw new IllegalStateException("Invalid tableSource : " + tableSource + " . Either model : " + modelName <START> + " is undefined or field : " + fieldName + " is undefined for this model."); <END> } }</code><technical_language>break errors out developer</technical_language>

Target:
private static void validateTableSource(ElideTableConfig elideTableConfig, String tableSource) { if (isNullOrEmpty(tableSource)) { return; } String[] split = tableSource.split("\\."); if (split.length != 2) { throw new IllegalStateException("Invalid tableSource : " + tableSource + " . " + "More than one dot(.) found, tableSource must be in format: modelName.logicalColumnName"); } String modelName = split[0]; String fieldName = split[1]; if (elideTableConfig.hasTable(modelName)) { Table table = elideTableConfig.getTable(modelName); if (!table.hasField(elideTableConfig, fieldName)) { throw new IllegalStateException("Invalid tableSource : " + tableSource + " . Field : " + fieldName + " is undefined for hjson model: " + modelName); } return; } if (isStaticModel(modelName, NO_VERSION)) { if (!staticModelHasField(modelName, NO_VERSION, fieldName)) { throw new IllegalStateException("Invalid tableSource : " + tableSource + " . Field : " + fieldName + " is undefined for non-hjson model: " + modelName); } return; } throw new IllegalStateException("Invalid tableSource : " + tableSource + " . Undefined model: " + modelName); }
Source:
<code>public boolean equals(final Object other) { if (this == other) { return true; } if (other == null) { return false; } if (!(other instanceof ITmfTimestamp)) { return false; } final ITmfTimestamp ts = ((ITmfTimestamp) other); <START> return (fValue == ts.getValue() && fScale == ts.getScale()); <END> }</code><technical_language>this 1 ms 1000000 ns equal. Do want that</technical_language>

Target:
public boolean equals(final Object other) { if (this == other) { return true; } if (other == null) { return false; } if (!(other instanceof ITmfTimestamp)) { return false; } final ITmfTimestamp ts = (ITmfTimestamp) other; return (compareTo(ts) == 0); }
Source:
<code>public void visitFunctionCall(FunctionCallTree tree) { String functionName = CheckUtils.getFunctionName(tree); List<ExpressionTree> arguments = tree.arguments(); if (CURL_SETOPT.equals(functionName) && arguments.size() > 2) { ExpressionTree optionArgument = arguments.get(1); <START> if (optionArgument.is(Tree.Kind.NAMESPACE_NAME) && <END> CURLOPT_SSL_VERIFYHOST.equals(((NamespaceNameTree) optionArgument).name().text())) { checkCURLSSLVerifyHost(getAssignedValue(arguments.get(2))); } else if (optionArgument.is(Tree.Kind.NAMESPACE_NAME) && CURLOPT_SSL_VERIFYPEER.equals(((NamespaceNameTree) optionArgument).name().text())) { checkCURLSSLVerifyPeer(getAssignedValue(arguments.get(2))); } } super.visitFunctionCall(tree); }</code><technical_language>I extract check if argument method (to avoid duplicate in next condition improve readability)</technical_language>

Target:
public void visitFunctionCall(FunctionCallTree tree) { String functionName = CheckUtils.getFunctionName(tree); List<ExpressionTree> arguments = tree.arguments(); if (CURL_SETOPT.equals(functionName) && arguments.size() > 2) { ExpressionTree optionArgument = arguments.get(1); ExpressionTree valueArgument = arguments.get(2); nameOf(optionArgument).ifPresent(name -> { if (name.equals(CURLOPT_SSL_VERIFYHOST)) { this.checkCURLSSLVerify(valueArgument, verifyHostCompliantValues); } else if (name.equals(CURLOPT_SSL_VERIFYPEER)) { this.checkCURLSSLVerify(valueArgument, verifyPeerCompliantValues); } }); } super.visitFunctionCall(tree); }
Source:
<code>private String fetchAccessToken() { String token = StringUtils.EMPTY; <START> try(CloseableHttpClient client = createDefault()) { <END> HttpPost post = new HttpPost(jwtServiceConfig.getEndpoint()); post.addHeader("Cache-Control", "no-cache"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); List<BasicNameValuePair> params = Lists.newArrayList(); params.add(new BasicNameValuePair("client_id", jwtServiceConfig.getClientId())); params.add(new BasicNameValuePair("client_secret", jwtServiceConfig.getClientSecret())); params.add(new BasicNameValuePair("jwt_token", getJwtToken())); post.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { LOGGER.info("response code ", response.getStatusLine().getStatusCode()); } String result = IOUtils.toString(response.getEntity().getContent()); LOGGER.info("JSON Response : {}", result); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(result).getAsJsonObject(); if (json.has(JSON_ACCESS_TOKEN)) { token = json.get(JSON_ACCESS_TOKEN).getAsString(); } else { LOGGER.error("JSON does not contain an access_token"); } } catch (Exception e) { LOGGER.error(e.getMessage()); } LOGGER.info("JWT Access Token : {}", token); return token; }</code><technical_language>missing timeouts (I think)</technical_language>

Target:
private String fetchAccessToken() { String token = StringUtils.EMPTY; try(CloseableHttpClient client = helper.getHttpClient(getTimeoutinMilliSeconds())) { HttpPost post = new HttpPost(jwtServiceConfig.endpoint()); post.addHeader(CACHE_CONTRL, NO_CACHE); post.addHeader(CONTENT_TYPE, CONTENT_TYPE_URL_ENCODED); List<BasicNameValuePair> params = Lists.newArrayList(); params.add(new BasicNameValuePair(CLIENT_ID, jwtServiceConfig.clientId())); params.add(new BasicNameValuePair(CLIENT_SECRET, jwtServiceConfig.clientSecret())); params.add(new BasicNameValuePair(JWT_TOKEN, getJwtToken())); post.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { LOGGER.info("response code ", response.getStatusLine().getStatusCode()); } String result = IOUtils.toString(response.getEntity().getContent()); LOGGER.info("JSON Response : {}", result); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(result).getAsJsonObject(); if (json.has(JSON_ACCESS_TOKEN)) { token = json.get(JSON_ACCESS_TOKEN).getAsString(); } else { LOGGER.error("JSON does not contain an access_token"); } } catch (Exception e) { LOGGER.error(e.getMessage()); } LOGGER.info("JWT Access Token : {}", token); return token; }
Source:
<code>Korean() { NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder(); builder.add("\u00B7", "\u0020"); builder.add("\u318D", "\u0020"); <START> builder.add("\u00AD", "\""); builder.add("\u200C", "\""); <END> charMap = builder.build(); }</code><technical_language>u00AD u200C map "" (empty string) "\"" (double quote). original JSON "\\u00AD=>" ... quotes mapping \\u00AD=> (map nothing) part of mapping</technical_language>

Target:
Korean() { NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder(); builder.add("\u00B7", "\u0020"); builder.add("\u318D", "\u0020"); builder.add("\u00AD", ""); builder.add("\u200C", ""); charMap = builder.build(); }
Source:
<code>private static TimelockService getTimelockService(String client) { return RemoteTimelockServiceAdapter.create( <START> getProxyForRootService(client, TimelockRpcClient.class), client); <END> }</code><technical_language>this work? types match right? I impression RemoteTimelockServiceAdapter in a NamespaceAwareTimelockRpcClient</technical_language>

Target:
private static TimelockService getTimelockService(String client) { return RemoteTimelockServiceAdapter.create( new NamespacedTimelockRpcClient(getProxyForRootService(client, TimelockRpcClient.class), client)); }
Source:
<code>public String run(@Nonnull EnvVars launchEnv, @Nonnull String image, @CheckForNull String args, @CheckForNull String workdir, @Nonnull Map<String, String> volumes, @Nonnull Collection<String> volumesFromContainers, @Nonnull EnvVars containerEnv, @Nonnull String user, @Nonnull String... command) throws IOException, InterruptedException { ArgumentListBuilder argb = new ArgumentListBuilder("docker", "run", "-d", "-t"); if (args != null) { argb.addTokenized(args); } if (workdir != null) { argb.add("-w", workdir); } for (Map.Entry<String, String> volume : volumes.entrySet()) { argb.add("-v", volume.getKey() + ":" + volume.getValue()); } for (String containerId : volumesFromContainers) { argb.add("--volumes-from", containerId); } for (Map.Entry<String, String> variable : containerEnv.entrySet()) { argb.add("-e"); <START> if (variable.getKey().contains("") || variable.getValue().contains(" ")) { <END> argb.addMasked(WindowsUtil.quoteArgument(variable.getKey() + "=" + variable.getValue())); } else { argb.addMasked(variable.getKey() + "=" + variable.getValue()); } } argb.add(image).add(command); LaunchResult result = launch(launchEnv, false, null, argb); if (result.getStatus() == 0) { return result.getOut(); } else { throw new IOException(String.format("Failed to run image '%s'. Error: %s", image, result.getErr())); } }</code><technical_language>Right this branch runs, String.contains("") is true. I meant this: suggestion if (variable.getKey().contains("\"") || variable.getValue().contains(" ")) {</technical_language>

Target:
public String run(@Nonnull EnvVars launchEnv, @Nonnull String image, @CheckForNull String args, @CheckForNull String workdir, @Nonnull Map<String, String> volumes, @Nonnull Collection<String> volumesFromContainers, @Nonnull EnvVars containerEnv, @Nonnull String user, @Nonnull String... command) throws IOException, InterruptedException { ArgumentListBuilder argb = new ArgumentListBuilder("docker", "run", "-d", "-t"); if (args != null) { argb.addTokenized(args); } if (workdir != null) { argb.add("-w", workdir); } for (Map.Entry<String, String> volume : volumes.entrySet()) { argb.add("-v", volume.getKey() + ":" + volume.getValue()); } for (String containerId : volumesFromContainers) { argb.add("--volumes-from", containerId); } for (Map.Entry<String, String> variable : containerEnv.entrySet()) { argb.add("-e"); argb.addMasked(WindowsUtil.quoteArgument(variable.getKey() + "=" + variable.getValue())); } argb.add(image).add(command); LaunchResult result = launch(launchEnv, false, null, argb); if (result.getStatus() == 0) { return result.getOut(); } else { throw new IOException(String.format("Failed to run image '%s'. Error: %s", image, result.getErr())); } }
Source:
<code>protected void internalRefresh(E element) { Control list = getControl(); if (element == null || equals(element, getRoot())) { if (listMap != null) { listMap.clear(); } unmapAllElements(); <START> List selection = getSelectionFromWidget(); <END> int topIndex = -1; if (selection == null || selection.isEmpty()) { topIndex = listGetTopIndex(); } E[] children = null; list.setRedraw(false); try { listRemoveAll(); children = getSortedChildren(getRoot()); String[] items = new String[children.length]; ILabelProvider<E> labelProvider = (ILabelProvider<E>) getLabelProvider(); for (int i = 0; i < items.length; i++) { E el = children[i]; items[i] = getLabelProviderText(labelProvider, el); listMap.add(el); mapElement(el, list); } listSetItems(items); } finally { list.setRedraw(true); } if (topIndex == -1) { setSelectionToWidget(selection, false); } else { listSetTopIndex(Math.min(topIndex, children.length)); } } else { doUpdateItem(list, element, true); } }</code><technical_language>generified</technical_language>

Target:
protected void internalRefresh(E element) { Control list = getControl(); if (element == null || equals(element, getRoot())) { if (listMap != null) { listMap.clear(); } unmapAllElements(); List<E> selection = getSelectionFromWidget(); int topIndex = -1; if (selection == null || selection.isEmpty()) { topIndex = listGetTopIndex(); } E[] children = null; list.setRedraw(false); try { listRemoveAll(); children = getSortedChildren(getRoot()); String[] items = new String[children.length]; ILabelProvider<E> labelProvider = (ILabelProvider<E>) getLabelProvider(); for (int i = 0; i < items.length; i++) { E el = children[i]; items[i] = getLabelProviderText(labelProvider, el); listMap.add(el); mapElement(el, list); } listSetItems(items); } finally { list.setRedraw(true); } if (topIndex == -1) { setSelectionToWidget(selection, false); } else { listSetTopIndex(Math.min(topIndex, children.length)); } } else { doUpdateItem(list, element, true); } }
Source:
<code>public EventDefinition(IEventDeclaration declaration, StreamInputReader streamInputReader) { <START> this.fDeclaration = declaration; <END> this.fStreamInputReader = streamInputReader; }</code><technical_language>Remove this</technical_language>

Target:
public EventDefinition(IEventDeclaration declaration, StreamInputReader streamInputReader) { fDeclaration = declaration; fStreamInputReader = streamInputReader; }
Source:
<code>public void createContainerWithShmVolume() { try ( BrowserWebDriverContainer webDriverContainer = new BrowserWebDriverContainer() .withCapabilities(new FirefoxOptions()) ) { webDriverContainer.start(); <START> assertEquals("Only one shm mount present", countCorrectlyConfiguredShmVolumes(webDriverContainer), 1L); <END> assertEquals("No additional shm mounts present", countAnyShmVolumes(webDriverContainer), 1L); } }</code><technical_language>if assertion fails, run test debug why. WDYT replacing assert expects count of **any** SHM mount 1 comparing source & target? if is 1, source != target, immediately error</technical_language>

Target:
public void createContainerWithShmVolume() { try ( BrowserWebDriverContainer webDriverContainer = new BrowserWebDriverContainer() .withCapabilities(new FirefoxOptions()) ) { webDriverContainer.start(); final List<InspectContainerResponse.Mount> shmVolumes = shmVolumes(webDriverContainer); assertEquals("Only one shm mount present", 1, shmVolumes.size()); assertEquals("Shm mount source is correct", "/dev/shm", shmVolumes.get(0).getSource()); assertEquals("Shm mount mode is correct", "rw", shmVolumes.get(0).getMode()); } }
Source:
<code>private static boolean checkPortAvailability(int port) { boolean isAvailable; try (Socket socket = new Socket()) { <START> socket.connect(new InetSocketAddress("localhost", port)); <END> isAvailable = false; } catch (IOException e) { isAvailable = true; } return isAvailable; }</code><technical_language>need close socket socket connect try check connectivity</technical_language>

Target:
private boolean checkPortAvailability(int port) { boolean isPortAvailable; try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(synapseServer.getHost(), port)); isPortAvailable = false; } catch (IOException e) { isPortAvailable = true; } return isPortAvailable; }
Source:
<code>public synchronized void start() { if (delayMs > 0) { <START> handle = submit.create().startWithFixedDelay(delayMs, MILLISECONDS); <END> } else { handle = submit.create().start(DEFAULT_DELAY_MS, MILLISECONDS); } }</code><technical_language>is a method start delay of 15 seconds, another period for future runs. I is want here</technical_language>

Target:
public void start() { if (delay > 0) { handle = submit.create() .startWithFixedDelay(INITIAL_DELAY_S, delay, SECONDS); } else { handle = submit.create().start(INITIAL_DELAY_S, SECONDS); } }
Source:
<code><START> public void clearPreferredReadReplica(TopicPartition tp) { <END> assignedState(tp).preferredReadReplica = null; }</code><technical_language>I main figure out is in cases switch leader. out of range errors already. a other cases: 1. Leader changes. do validation anyway, reset preferred read replica. 2. preferred read replica is marked offline in metadata. 3. notice changes replica set ISR. Possibly do 1 2. For 3, handle a periodic timer check preferred read replica status. option couple this metadata.max.age.ms, is original KIP proposed</technical_language>

Target:
public Optional<Integer> clearPreferredReadReplica(TopicPartition tp) { return assignedState(tp).clearPreferredReadReplica(); }
Source:
<code>private KafkaProducer createKafkaProducer() { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaHosts); producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, io.confluent.kafka.serializers.KafkaAvroSerializer.class); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, io.confluent.kafka.serializers.KafkaAvroSerializer.class); producerProperties.put("schema.registry.url", schemaRegistries); <START> kafkaProducer = new KafkaProducer(producerProperties); <END> return kafkaProducer; }</code><technical_language>Nit: kafkaProducer field is set, returned, set value</technical_language>

Target:
private KafkaProducer createKafkaProducer() { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaHosts); producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, io.confluent.kafka.serializers.KafkaAvroSerializer.class); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, io.confluent.kafka.serializers.KafkaAvroSerializer.class); producerProperties.put(KafkaAvroSerializerConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistries); return new KafkaProducer(producerProperties); }
Source:
<code>public static List<MediaModel> getPendingMediaForPost(PostModel postModel) { for (UploadingPost uploadingPost : sPostsWithPendingMedia) { if (uploadingPost.postModel.getId() == postModel.getId()) { return uploadingPost.pendingMedia; } } <START> return null; <END> }</code><technical_language>do returning Collections.emptyList() instead? annotate method returning @NonNull (and drop [this check](<LINK_0></technical_language>

Target:
public static @NonNull List<MediaModel> getPendingMediaForPost(PostModel postModel) { for (UploadingPost uploadingPost : sPostsWithPendingMedia) { if (uploadingPost.postModel.getId() == postModel.getId()) { return uploadingPost.pendingMedia; } } return Collections.emptyList(); }
Source:
<code>public Target getTarget() { <START> return thingIfApi.getTarget(); <END> }</code><technical_language>Adding this a field is good manner</technical_language>

Target:
public Target getTarget() { return this.thingIfApi.getTarget(); }
Source:
<code>public FeedbackResponseCommentRow buildFeedbackResponseCommentFormForAdding(FeedbackQuestionAttributes question, String responseId, String giverName, String recipientName, ZoneId timezone, boolean isCommentFromFeedbackParticipant) { FeedbackResponseCommentAttributes frca = FeedbackResponseCommentAttributes .builder(question.courseId, question.feedbackSessionName, "", new Text("")) .withFeedbackResponseId(responseId) .withFeedbackQuestionId(question.getFeedbackQuestionId()) .withCommentFromFeedbackParticipant(isCommentFromFeedbackParticipant) .build(); <START> if (isCommentFromFeedbackParticipant) { <END> frca.commentGiverType = question.giverType; } else { frca.commentGiverType = FeedbackParticipantType.INSTRUCTORS; } frca.showCommentTo = new ArrayList<>(); frca.showGiverNameTo = new ArrayList<>(); FeedbackParticipantType[] relevantTypes = { FeedbackParticipantType.GIVER, FeedbackParticipantType.RECEIVER, FeedbackParticipantType.OWN_TEAM_MEMBERS, FeedbackParticipantType.RECEIVER_TEAM_MEMBERS, FeedbackParticipantType.STUDENTS, FeedbackParticipantType.INSTRUCTORS }; for (FeedbackParticipantType type : relevantTypes) { if (isResponseCommentVisibleTo(question, type)) { frca.showCommentTo.add(type); } if (isResponseCommentGiverNameVisibleTo(question, type)) { frca.showGiverNameTo.add(type); } } return new FeedbackResponseCommentRow(frca, giverName, recipientName, getResponseCommentVisibilityString(question), getResponseCommentGiverNameVisibilityString(question), getResponseVisibilityMap(question), timezone); }</code><technical_language>I is need for this check</technical_language>

Target:
public FeedbackResponseCommentRow buildFeedbackResponseCommentFormForAdding(FeedbackQuestionAttributes question, String responseId, String giverName, String recipientName, ZoneId timezone, boolean isCommentFromFeedbackParticipant) { FeedbackResponseCommentAttributes frca = FeedbackResponseCommentAttributes .builder(question.courseId, question.feedbackSessionName, "", new Text("")) .withFeedbackResponseId(responseId) .withFeedbackQuestionId(question.getFeedbackQuestionId()) .withCommentFromFeedbackParticipant(isCommentFromFeedbackParticipant) .build(); frca.showCommentTo = new ArrayList<>(); frca.showGiverNameTo = new ArrayList<>(); FeedbackParticipantType[] relevantTypes = { FeedbackParticipantType.GIVER, FeedbackParticipantType.RECEIVER, FeedbackParticipantType.OWN_TEAM_MEMBERS, FeedbackParticipantType.RECEIVER_TEAM_MEMBERS, FeedbackParticipantType.STUDENTS, FeedbackParticipantType.INSTRUCTORS }; for (FeedbackParticipantType type : relevantTypes) { if (isResponseCommentVisibleTo(question, type)) { frca.showCommentTo.add(type); } if (isResponseCommentGiverNameVisibleTo(question, type)) { frca.showGiverNameTo.add(type); } } return new FeedbackResponseCommentRow(frca, giverName, recipientName, getResponseCommentVisibilityString(question), getResponseCommentGiverNameVisibilityString(question), getResponseVisibilityMap(question), timezone); }
Source:
<code>public SpaceBetweenAlphabeticalWordValidator() { super("forbidden", false, <START> "skip_before_chars", "", <END> "skip_after_chars", ""); }</code><technical_language>I shorten configuration names. If ok, please rename skip_before_chars skip_before skip_after_chars skip_after</technical_language>

Target:
public SpaceBetweenAlphabeticalWordValidator() { super("forbidden", false, "skip_before", "", "skip_after", ""); }
Source:
<code>private BasicDocumentRevision updateDocument(SQLDatabase db,String docId, String prevRevId, final DocumentBody body, boolean validateBody, boolean copyAttachments) throws ConflictException, AttachmentException { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(docId), "Input document id can not be empty"); Preconditions.checkArgument(!Strings.isNullOrEmpty(prevRevId), "Input previous revision id can not be empty"); Preconditions.checkNotNull(body, "Input document body can not be null"); if (validateBody) { this.validateDBBody(body); } CouchUtils.validateRevisionId(prevRevId); try { BasicDocumentRevision preRevision = this.getDocumentInQueue(db, docId, prevRevId); if (!preRevision.isCurrent()) { throw new ConflictException("Revision to be updated is not current revision."); } this.setCurrent(db, preRevision, false); String newRevisionId = this.insertNewWinnerRevision(db, body, preRevision, copyAttachments); return this.getDocumentInQueue(db, preRevision.getId(), newRevisionId); } catch (DocumentNotFoundException e){ <START> throw new IllegalArgumentException("The document trying to update does not exist."); <END> } }</code><technical_language>Also, is IllegalArgumentException correct? wrong argument of itself, DocNotFound more logical here</technical_language>

Target:
private BasicDocumentRevision updateDocument(SQLDatabase db,String docId, String prevRevId, final DocumentBody body, boolean validateBody, boolean copyAttachments) throws ConflictException, AttachmentException, DocumentNotFoundException, DatastoreException { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(docId), "Input document id can not be empty"); Preconditions.checkArgument(!Strings.isNullOrEmpty(prevRevId), "Input previous revision id can not be empty"); Preconditions.checkNotNull(body, "Input document body can not be null"); if (validateBody) { this.validateDBBody(body); } CouchUtils.validateRevisionId(prevRevId); BasicDocumentRevision preRevision = this.getDocumentInQueue(db, docId, prevRevId); if (!preRevision.isCurrent()) { throw new ConflictException("Revision to be updated is not current revision."); } this.setCurrent(db, preRevision, false); String newRevisionId = this.insertNewWinnerRevision(db, body, preRevision, copyAttachments); return this.getDocumentInQueue(db, preRevision.getId(), newRevisionId); }
Source:
<code>private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { throw new IllegalStateException("PartitionKeyRange list cannot be null"); } <START> List<FeedRange> feedRanges = new ArrayList<FeedRange>(); <END> partitionKeyRangeList.forEach(pkRange -> { feedRanges.add(toFeedRange(pkRange)); }); return feedRanges; }</code><technical_language>List<FeedRange> feedRanges = new ArrayList<FeedRange>(feedRanges.size());</technical_language>

Target:
private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { throw new IllegalStateException("PartitionKeyRange list cannot be null"); } List<FeedRange> feedRanges = new ArrayList<FeedRange>(partitionKeyRangeList.size()); partitionKeyRangeList.forEach(pkRange -> { feedRanges.add(toFeedRange(pkRange)); }); return feedRanges; }
Source:
<code>public void put(List<Metric> metrics) { requireNotDisposed(); SystemAssert.requireArgument(metrics != null, "Metric list cannot be null."); List<Metric> metricsToPut = new ArrayList<>(metrics.size()); Set<String> scopesToPut = new HashSet<>(metrics.size()); Set<Metric> scopesAndMetricsNamesToPut = new HashSet<>(metrics.size()); for(Metric metric : metrics) { if(metric.getTags().isEmpty()) { String key = constructKey(metric, null); boolean found = bloomFilter.mightContain(key); if(!found) { metricsToPut.add(metric); } } else { boolean newTags = false; for(Entry<String, String> tagEntry : metric.getTags().entrySet()) { String key = constructKey(metric, tagEntry); boolean found = bloomFilter.mightContain(key); if(!found) { newTags = true; } } if(newTags) { metricsToPut.add(metric); } } String scopeName = metric.getScope(); String metricName = metric.getMetric(); String key = constructScopeOnlyKey(scopeName); boolean found = bloomFilterScopeOnly.mightContain(key); if(!found) { scopesToPut.add(scopeName); } key = constructScopeAndMetricOnlyKey(scopeName, metricName); found = bloomFilterScopeAndMetricOnly.mightContain(key); if(!found) { scopesAndMetricsNamesToPut.add(new Metric(scopeName, metricName)); } } List<Metric> scopesAndMetricsToPut = new ArrayList<>(scopesAndMetricsNamesToPut); <START> implementationSpecificPut(metricsToPut, scopesToPut, scopesAndMetricsToPut); <END> }</code><technical_language>a Set for scopesAndMetricsNamesToPut, similar scopesToPut</technical_language>

Target:
public void put(List<Metric> metrics) { requireNotDisposed(); SystemAssert.requireArgument(metrics != null, "Metric list cannot be null."); List<Metric> metricsToPut = new ArrayList<>(metrics.size()); Set<String> scopesToPut = new HashSet<>(metrics.size()); Set<Pair<String, String>> scopesAndMetricsNamesToPut = new HashSet<>(metrics.size()); for(Metric metric : metrics) { if(metric.getTags().isEmpty()) { String key = constructKey(metric, null); boolean found = bloomFilter.mightContain(key); if(!found) { metricsToPut.add(metric); } } else { boolean newTags = false; for(Entry<String, String> tagEntry : metric.getTags().entrySet()) { String key = constructKey(metric, tagEntry); boolean found = bloomFilter.mightContain(key); if(!found) { newTags = true; } } if(newTags) { metricsToPut.add(metric); } } String scopeName = metric.getScope(); String metricName = metric.getMetric(); String key = constructScopeOnlyKey(scopeName); boolean found = bloomFilterScopeOnly.mightContain(key); if(!found) { scopesToPut.add(scopeName); } key = constructScopeAndMetricOnlyKey(scopeName, metricName); found = bloomFilterScopeAndMetricOnly.mightContain(key); if(!found) { scopesAndMetricsNamesToPut.add(Pair.of(scopeName, metricName)); } } implementationSpecificPut(metricsToPut, scopesToPut, scopesAndMetricsNamesToPut); }