auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>ExecutorService createGetRangesExecutor(int numThreads) { BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>() { @Override public boolean offer(Runnable e) { sanityCheckQueueSize(); return super.offer(e); } <START> private void sanityCheckQueueSize() { <END> int currentSize = this.size(); if (currentSize >= GET_RANGES_QUEUE_SIZE_WARNING_THRESHOLD) { log.warn("You have pending getRanges tasks. Please sanity check both your level" + "of concurrency and size of batched range requests. If necessary you can" + "increase the value of maxConcurrentGetRanges to allow for a larger" + "thread pool.", currentSize); } } }; return new ThreadPoolExecutor( numThreads, numThreads, 0L, TimeUnit.MILLISECONDS, workQueue, new ThreadFactoryBuilder().setNameFormat(getClass().getSimpleName() + "-get-ranges-%d").build()); }</code><technical_language>nittier nit: blank line needed methods (this break baseline checkstyle, atlasdb-client - - baseline-enabled)</technical_language>

Target:
ExecutorService createGetRangesExecutor(int numThreads) { BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>() { private final RateLimiter warningRateLimiter = RateLimiter.create(1); @Override public boolean offer(Runnable runnable) { sanityCheckQueueSize(); return super.offer(runnable); } private void sanityCheckQueueSize() { int currentSize = this.size(); if (currentSize >= GET_RANGES_QUEUE_SIZE_WARNING_THRESHOLD && warningRateLimiter.tryAcquire()) { log.warn("You have pending getRanges tasks. Please sanity check both your level " + "of concurrency and size of batched range requests. If necessary you can " + "increase the value of concurrentGetRangesThreadPoolSize to allow for a larger " + "thread pool.", currentSize); } } }; return new ThreadPoolExecutor( numThreads, numThreads, 0L, TimeUnit.MILLISECONDS, workQueue, new ThreadFactoryBuilder().setNameFormat( AbstractTransactionManager.this.getClass().getSimpleName() + "-get-ranges-%d").build()); }
Source:
<code>public static boolean isPullRequestLoaded(String url) { <START> return url.matches("<LINK_0>[^/]+)/([^/]+)/pull/([0-9]+)([/commits,/files]*)"); <END> }</code><technical_language>part right. [/commits,/files]* is a character class, match cc, ,, -- 0 more of character in brackets. parenthesise groups refer to. regex a tiny bit faster. This tests, mistakes in regexes subtle</technical_language>

Target:
public static boolean isPullRequestLoaded(String url) { return url.matches("<LINK_0>[^/]+)/([^/]+)/pull/([0-9]+)(/|/commits|/files)?"); }
Source:
<code>public static void setUp() throws IOException, JsonException, ServerConfigurationException { LOG.info().$("begin").$(); root = temp.newFolder("dbRoot").getAbsolutePath(); TestUtils.copyMimeTypes(temp.getRoot().getAbsolutePath()); serverConfiguration = new PropServerConfiguration(temp.getRoot().getAbsolutePath(), new Properties()) { @Override public CairoConfiguration getCairoConfiguration() { <START> return new DefaultCairoConfiguration(root); <END> } }; configuration = serverConfiguration.getCairoConfiguration(); messageBus = new MessageBusImpl(serverConfiguration); }</code><technical_language>returning new instance of configuration getCairoConfiguration() call inefficient lead memory churn in tests. implement this method so: java private final CairoConfiguration conf = new DefaultCairoConfiguration(root); @Override public CairoConfiguration getCairoConfiguration() { return conf; }</technical_language>

Target:
public static void setUp() throws IOException, JsonException, ServerConfigurationException { LOG.info().$("begin").$(); root = temp.newFolder("dbRoot").getAbsolutePath(); configuration = new DefaultCairoConfiguration(root); TestUtils.copyMimeTypes(temp.getRoot().getAbsolutePath()); serverConfiguration = new PropServerConfiguration(temp.getRoot().getAbsolutePath(), new Properties()) { @Override public CairoConfiguration getCairoConfiguration() { return configuration; } }; configuration = serverConfiguration.getCairoConfiguration(); messageBus = new MessageBusImpl(serverConfiguration); }
Source:
<code>GarbageCollectWriteAheadLogs(final AccumuloServerContext context, final VolumeManager fs, final LiveTServerSet liveServers, boolean useTrash) throws IOException { this.context = context; this.fs = fs; this.useTrash = useTrash; <START> this.liveServers = liveServers; <END> this.walMarker = new WalStateManager(context.getInstance(), ZooReaderWriter.getInstance()); this.store = new Iterable<TabletLocationState>() { @Override public Iterator<TabletLocationState> iterator() { return Iterators.concat(new RootTabletStateStore(context).iterator(), new MetaDataStateStore(context).iterator()); } }; }</code><technical_language>call liveServers.scanServers() making more functionally equivalent code. code call liveServers.startListeningForTabletServerChanges() internally called scanServers() registered a timer call scanServers(). I registering timer is needed</technical_language>

Target:
GarbageCollectWriteAheadLogs(final AccumuloServerContext context, final VolumeManager fs, final LiveTServerSet liveServers, boolean useTrash) throws IOException { this.context = context; this.fs = fs; this.useTrash = useTrash; this.liveServers = liveServers; this.walMarker = new WalStateManager(context.getInstance(), ZooReaderWriter.getInstance()); this.store = new Iterable<TabletLocationState>() { @Override public Iterator<TabletLocationState> iterator() { try { return Iterators.concat(new ZooTabletStateStore().iterator(), new RootTabletStateStore(context).iterator(), new MetaDataStateStore(context).iterator()); } catch (DistributedStoreException e) { throw new RuntimeException(e); } } }; }
Source:
<code>public void shutdown() { try { logger.info("Shutting down server"); for (Acceptor acceptor : acceptors) { <START> if (acceptor != null && acceptor.isRunning()) { <END> acceptor.shutdown(); } } for (Processor processor : processors) { if (processor.isRunning()) { processor.shutdown(); } } logger.info("Shutdown completed"); } catch (Exception e) { logger.error("Error shutting down socket server {}", e); } }</code><technical_language>do need check is running here</technical_language>

Target:
public void shutdown() { try { logger.info("Shutting down server"); for (Acceptor acceptor : acceptors) { if (acceptor != null) { acceptor.shutdown(); } } for (Processor processor : processors) { processor.shutdown(); } logger.info("Shutdown completed"); } catch (Exception e) { logger.error("Error shutting down socket server {}", e); } }
Source:
<code>public void decorate(Object element, IDecoration decoration) { <START> final Activator activator = Activator.getDefault(); <END> if (activator == null) return; if (!PlatformUI.isWorkbenchRunning()) return; final IResource resource = getResource(element); if (resource == null) { decorateResourceMapping(element, decoration); } else { try { decorateResource(resource, decoration); } catch(CoreException e) { handleException(resource, e); } } }</code><technical_language>this local variable needed</technical_language>

Target:
public void decorate(Object element, IDecoration decoration) { if (Activator.getDefault() == null) return; if (!PlatformUI.isWorkbenchRunning()) return; final IResource resource = getResource(element); if (resource == null) { decorateResourceMapping(element, decoration); } else { try { decorateResource(resource, decoration); } catch(CoreException e) { handleException(resource, e); } } }
Source:
<code>public static BaseFloatColumnValueSelector makeColumnValueSelectorWithFloatDefault( final ColumnSelectorFactory metricFactory, final ExprMacroTable macroTable, final String fieldName, final String fieldExpression, @Nullable final Float nullValue ) { if (fieldName != null && fieldExpression == null) { return metricFactory.makeColumnValueSelector(fieldName); } if (fieldName == null && fieldExpression != null) { final Expr expr = Parser.parse(fieldExpression, macroTable); final ColumnValueSelector<ExprEval> baseSelector = ExpressionSelectors.makeExprEvalSelector(metricFactory, expr); class ExpressionFloatColumnSelector implements FloatColumnSelector { @Override public float getFloat() { final ExprEval exprEval = baseSelector.getObject(); return exprEval.isNull() ? nullValue : (float) exprEval.asDouble(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } @Override public boolean isNull() { <START> return baseSelector.getObject().isNull(); <END> } } return new ExpressionFloatColumnSelector(); } throw new IllegalArgumentException("Must have a valid, non-null fieldName or expression"); }</code><technical_language>Please align impl Long Double variants</technical_language>

Target:
public static BaseFloatColumnValueSelector makeColumnValueSelectorWithFloatDefault( final ColumnSelectorFactory metricFactory, final ExprMacroTable macroTable, final String fieldName, final String fieldExpression, @Nullable final Float nullValue ) { if (fieldName != null && fieldExpression == null) { return metricFactory.makeColumnValueSelector(fieldName); } if (fieldName == null && fieldExpression != null) { final Expr expr = Parser.parse(fieldExpression, macroTable); final ColumnValueSelector<ExprEval> baseSelector = ExpressionSelectors.makeExprEvalSelector(metricFactory, expr); class ExpressionFloatColumnSelector implements FloatColumnSelector { @Override public float getFloat() { final ExprEval exprEval = baseSelector.getObject(); return exprEval.isNull() ? nullValue : (float) exprEval.asDouble(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } @Override public boolean isNull() { final ExprEval exprEval = baseSelector.getObject(); return exprEval.isNull(); } } return new ExpressionFloatColumnSelector(); } throw new IllegalArgumentException("Must have a valid, non-null fieldName or expression"); }
Source:
<code>private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("<LINK_0>", payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; <START> }).onErrorResume(t -> Mono.error(new CredentialUnavailableException( <END> "ManagedIdentityCredential authentication unavailable." + t.getMessage(), t))); }</code><technical_language>onErrorMap</technical_language>

Target:
private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("<LINK_0>", payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw logger.logExceptionAsError( new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); }
Source:
<code>private static List<OpenMrsXformIndexEntry> getLocalFormEntries() { List<OpenMrsXformIndexEntry> entries = new ArrayList<>(); final ContentResolver resolver = App.getInstance().getContentResolver(); <START> Cursor c = resolver.query(Contracts.Forms.CONTENT_URI, null, null, null, null); <END> try { while (c.moveToNext()) { String uuid = Utils.getString(c, Contracts.Forms.UUID); String name = Utils.getString(c, Contracts.Forms.NAME); long date = 0; entries.add(new OpenMrsXformIndexEntry(uuid, name, date)); } } finally { c.close(); } return entries; }</code><technical_language>generally projection (the columns) for database reads, in case database schema changes in future</technical_language>

Target:
private static List<OpenMrsXformIndexEntry> getLocalFormEntries() { List<OpenMrsXformIndexEntry> entries = new ArrayList<>(); final ContentResolver resolver = App.getInstance().getContentResolver(); Cursor c = resolver.query(Contracts.Forms.CONTENT_URI, new String[] {Contracts.Forms.UUID, Contracts.Forms.NAME}, null, null, null); try { while (c.moveToNext()) { String uuid = Utils.getString(c, Contracts.Forms.UUID); String name = Utils.getString(c, Contracts.Forms.NAME); long date = 0; entries.add(new OpenMrsXformIndexEntry(uuid, name, date)); } } finally { c.close(); } return entries; }
Source:
<code>public void initialize_with_empty_builder() { final Stand.Builder builder = Stand.newBuilder(); final Stand stand = builder.build(); assertNotNull(stand); assertTrue("Available types must be empty after the initialization.", stand.getAvailableTypes() .isEmpty()); assertTrue("Known aggregate types must be empty after the initialization", stand.getKnownAggregateTypes() .isEmpty()); <START> <END> }</code><technical_language>Please remove excessive empty line</technical_language>

Target:
public void initialize_with_empty_builder() { final Stand.Builder builder = Stand.newBuilder(); final Stand stand = builder.build(); assertNotNull(stand); assertTrue("Exposed types must be empty after the initialization.", stand.getExposedTypes() .isEmpty()); assertTrue("Exposed aggregate types must be empty after the initialization", stand.getExposedAggregateTypes() .isEmpty()); }
Source:
<code>private void startPollingForChanges() { changesPollingThread = new Thread() { @Override public void run() { this.setName(THREAD_NAME); pollForChanges = true; while (pollForChanges) { if (dialogRunnable == null && isScriptUpdatedOnDisk() ) { <START> if (script.isChanged()) { <END> dialogRunnable = new Runnable() { @Override public void run() { if (JOptionPane.showOptionDialog( ConsolePanel.this, Constant.messages.getString("scripts.console.changedOnDiskAndConsole"), Constant.PROGRAM_NAME, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, SCRIPT_CHANGED_BUTTONS, null) == JOptionPane.YES_OPTION) { try { extension.getExtScript().saveScript(script); } catch (IOException e) { LOG.error(e.getMessage(), e); } } else { reloadScript(); } dialogRunnable = null; } }; } else { dialogRunnable = new Runnable() { @Override public void run() { if (JOptionPane.showOptionDialog( ConsolePanel.this, Constant.messages.getString("scripts.console.changedOnDisk"), Constant.PROGRAM_NAME, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, SCRIPT_CHANGED_BUTTONS, null) == JOptionPane.YES_OPTION) { try { extension.getExtScript().saveScript(script); } catch (IOException e) { LOG.error(e.getMessage(), e); } } else { reloadScript(); } dialogRunnable = null; } }; } SwingUtilities.invokeLater(dialogRunnable); } try { sleep(5000); } catch (InterruptedException e) { } } changesPollingThread = null; } }; changesPollingThread.setDaemon(true); changesPollingThread.start(); if (dialogRunnable != null) { return; } }</code><technical_language>Runnable for (use a variable for message ternary operator in invocation?)</technical_language>

Target:
private void startPollingForChanges() { changesPollingThread = new Thread() { @Override public void run() { this.setName(THREAD_NAME); pollForChanges = true; while (pollForChanges) { if (dialogRunnable == null && isScriptUpdatedOnDisk() ) { dialogRunnable = new Runnable() { @Override public void run() { String message; if (script.isChanged()) { message = Constant.messages.getString("scripts.console.changedOnDiskAndConsole"); } else { message = Constant.messages.getString("scripts.console.changedOnDisk"); } if (JOptionPane.showOptionDialog( ConsolePanel.this, message, Constant.PROGRAM_NAME, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, SCRIPT_CHANGED_BUTTONS, null) == JOptionPane.YES_OPTION) { try { extension.getExtScript().saveScript(script); } catch (IOException e) { LOG.error(e.getMessage(), e); } } else { reloadScript(); } dialogRunnable = null; } }; try { SwingUtilities.invokeAndWait(dialogRunnable); } catch (Exception e) { LOG.error(e.getMessage(), e); } } try { sleep(5000); } catch (InterruptedException e) { } } changesPollingThread = null; } }; changesPollingThread.setDaemon(true); changesPollingThread.start(); if (dialogRunnable != null) { return; } }
Source:
<code>public Object getFragmentManager(Object fragment) { if (mMethodGetFragmentManager == null) { return null; } try { return mMethodGetFragmentManager.invoke(fragment); } catch (Exception e) { <START> LogUtil.w(e, "Could not call Fragment.getFragmentManager()"); <END> return null; } }</code><technical_language>advice applies account of fact proven method exists. invokable else unusual occurred want about</technical_language>

Target:
public Object getFragmentManager(Object fragment) { return ReflectionUtil.invokeMethod(mMethodGetFragmentManager, fragment); }
Source:
<code>public Optional<Achievement> getById(String id) { <START> return Optional.ofNullable(this.achievementMappings.get(checkNotNull(id).toLowerCase())); <END> }</code><technical_language>This define a locale for lowercase method</technical_language>

Target:
public Optional<Achievement> getById(String id) { return Optional.ofNullable(this.achievementMappings.get(checkNotNull(id).toLowerCase(Locale.ENGLISH))); }
Source:
<code>protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String credentials = (String) token.getCredentials(); String[] userpass = credentials.split(":"); if (userpass.length != 2) { LOGGER.debug("Credentials were not in the correct format."); } String user = new String(Base64.getDecoder().decode(userpass[0]), StandardCharsets.UTF_8); String pass = new String(Base64.getDecoder().decode(userpass[1]), StandardCharsets.UTF_8); Subject subject = null; for (JaasRealm jaasRealm : realmList) { try { subject = login(user, pass, jaasRealm.getName()); LOGGER.trace("Login succeeded for against realm {}", user, jaasRealm.getName()); break; } catch (LoginException e) { <START> LOGGER.trace("Login failed for against realm {}", user, jaasRealm.getName()); <END> } } if (subject != null) { SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(); SimplePrincipalCollection principalCollection = createPrincipalCollectionFromSubject(subject); simpleAuthenticationInfo.setPrincipals(principalCollection); simpleAuthenticationInfo.setCredentials(credentials); return simpleAuthenticationInfo; } throw new AuthenticationException("Login failed for user: " + user); }</code><technical_language>username password separately base64 encoded? if username:password string is base64 encoded a whole, : converted base64, able split it. I AuthenticationTokenFactory encodes separately, if token is comming factory</technical_language>

Target:
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String credentials = (String) token.getCredentials(); String[] userpass = credentials.split(":"); if (userpass.length != 2) { throw new AuthenticationException("Credentials were not in the correct format."); } String user = new String(Base64.getDecoder().decode(userpass[0]), StandardCharsets.UTF_8); String pass = new String(Base64.getDecoder().decode(userpass[1]), StandardCharsets.UTF_8); Subject subject = null; for (JaasRealm jaasRealm : realmList) { try { subject = login(user, pass, jaasRealm.getName()); LOGGER.trace("Login succeeded for against realm {}", user, jaasRealm.getName()); break; } catch (LoginException e) { LOGGER.trace("Login failed for against realm {}", user, jaasRealm.getName()); } } if (subject != null) { SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(); SimplePrincipalCollection principalCollection = createPrincipalCollectionFromSubject(subject); simpleAuthenticationInfo.setPrincipals(principalCollection); simpleAuthenticationInfo.setCredentials(credentials); return simpleAuthenticationInfo; } throw new AuthenticationException("Login failed for user: " + user); }
Source:
<code>public static GermplasmListNewColumnsInfo createGermplasmListNewColumnsInfo(final String columnHeader, final String columnValue) { final GermplasmListNewColumnsInfo germplasmListNewColumnsInfo = new GermplasmListNewColumnsInfo(1); <START> final LinkedHashMap<String, List<ListDataColumnValues>> columnValuesMap = new LinkedHashMap<>(); <END> final List<ListDataColumnValues> listDataColumnValues = new ArrayList<>(); listDataColumnValues.add(new ListDataColumnValues(columnHeader, 1, columnValue)); columnValuesMap.put(columnHeader, listDataColumnValues); germplasmListNewColumnsInfo.setColumnValuesMap(columnValuesMap); germplasmListNewColumnsInfo.addColumn(columnHeader); return germplasmListNewColumnsInfo; }</code><technical_language>Declare columnValuesMap Map</technical_language>

Target:
public static GermplasmListNewColumnsInfo createGermplasmListNewColumnsInfo(final String columnHeader, final String columnValue) { final GermplasmListNewColumnsInfo germplasmListNewColumnsInfo = new GermplasmListNewColumnsInfo(1); final Map<String, List<ListDataColumnValues>> columnValuesMap = new LinkedHashMap<>(); final List<ListDataColumnValues> listDataColumnValues = new ArrayList<>(); listDataColumnValues.add(new ListDataColumnValues(columnHeader, 1, columnValue)); columnValuesMap.put(columnHeader, listDataColumnValues); germplasmListNewColumnsInfo.setColumnValuesMap(columnValuesMap); germplasmListNewColumnsInfo.addColumn(columnHeader); return germplasmListNewColumnsInfo; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { final IResource resource = getSelectedResources(event)[0]; if (resource instanceof IFile){ final IFile baseFile = (IFile) resource; final ITypedElement base = SaveableCompareEditorInput .createFileElement(baseFile); final ITypedElement next; try { next = getHeadTypedElement(baseFile); } catch (IOException e) { Activator.handleError( UIText.CompareWithIndexAction_errorOnAddToIndex, e, true); return null; } final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( base, next, null); <START> CompareUI.openCompareEditor(in); <END> } if (resource instanceof IContainer){ CompareTreeView view; try { view = (CompareTreeView) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage() .showView(CompareTreeView.ID); view.setInput(resource, CompareTreeView.INDEX_VERSION); } catch (PartInitException e) { Activator.handleError(e.getMessage(), e, true); } } return null; }</code><technical_language>Lines 56-71 indented while if statement in line 55</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { final IResource resource = getSelectedResources(event)[0]; if (resource instanceof IFile) { final IFile baseFile = (IFile) resource; final ITypedElement base = SaveableCompareEditorInput .createFileElement(baseFile); final ITypedElement next; try { next = getHeadTypedElement(baseFile); } catch (IOException e) { Activator.handleError( UIText.CompareWithIndexAction_errorOnAddToIndex, e, true); return null; } final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( base, next, null); CompareUI.openCompareEditor(in); } else if (resource instanceof IContainer) { CompareTreeView view; try { view = (CompareTreeView) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage().showView( CompareTreeView.ID); view.setInput(resource, CompareTreeView.INDEX_VERSION); } catch (PartInitException e) { Activator.handleError(e.getMessage(), e, true); } } return null; }
Source:
<code>public void testControllerConnectThenDisconnect() { ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "TestController"); long start = System.currentTimeMillis(); controller.syncStart(); verifyControllerIsLeader(controller); System.out.println(System.currentTimeMillis() - start + "ms spent on becoming the leader"); start = System.currentTimeMillis(); controller.syncStop(); verifyControllerIsNotLeader(controller); verifyZKDisconnected(controller); <START> System.out.println( <END> System.currentTimeMillis() - start + "ms spent on becoming the standby node from leader"); }</code><technical_language>Please test cases silent possible. log throw error asserts failure case</technical_language>

Target:
public void testControllerConnectThenDisconnect() { ClusterControllerManager controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "TestController"); long start = System.currentTimeMillis(); controller.syncStart(); verifyControllerIsLeader(controller); LOG.info(System.currentTimeMillis() - start + "ms spent on becoming the leader"); start = System.currentTimeMillis(); controller.syncStop(); verifyControllerIsNotLeader(controller); verifyZKDisconnected(controller); LOG.info( System.currentTimeMillis() - start + "ms spent on becoming the standby node from leader"); }
Source:
<code>public void setFilterText(String filter) { this.langLinks.clear(); filter = filter.toLowerCase(); for (PageTitle l: origLangLinks) { Locale locale = new Locale(Utils.toJavaLanguageCode(l.getSite().getLanguage())); <START> if (l.getDisplayText().contains(filter) <END> || locale.getDisplayLanguage().toLowerCase().contains(filter) || locale.getDisplayLanguage(locale).toLowerCase().contains(filter)) { this.langLinks.add(l); } } notifyDataSetInvalidated(); }</code><technical_language>is this missing a toLowerCase()</technical_language>

Target:
public void setFilterText(String filter) { this.langLinks.clear(); filter = filter.toLowerCase(); for (PageTitle l: origLangLinks) { Locale locale = new Locale(Utils.toJavaLanguageCode(l.getSite().getLanguage())); if (l.getDisplayText().toLowerCase().contains(filter) || locale.getDisplayLanguage().toLowerCase().contains(filter) || locale.getDisplayLanguage(locale).toLowerCase().contains(filter)) { this.langLinks.add(l); } } notifyDataSetInvalidated(); }
Source:
<code>public void testRemoveElement() { <START> int i = fullList.remove(2); <END> assertEquals(i, 3); assertTrue(!fullList.contains(3)); }</code><technical_language>remove(Integer.valueOf(3))</technical_language>

Target:
public void testRemoveElement() { fullList.remove(Integer.valueOf(3)); assertFalse(fullList.contains(3)); }
Source:
<code>protected Artifact getJenkinsWarArtifact() throws MojoExecutionException { for( Artifact a : resolveDependencies("test") ) { boolean match; if (jenkinsWarId!=null) match = (a.getGroupId()+':'+a.getArtifactId()).equals(jenkinsWarId); else <START> match = (a.getArtifactId().equals("jenkins-war") || a.getArtifactId().equals("hudson-war")) && a.getType().equals("executable-war"); <END> if(match) return a; } if (jenkinsWarId!=null) { getLog().error("Unable to locate jenkins.war in '"+jenkinsWarId+"'"); } else { getLog().error( "Unable to locate jenkins.war. Add the following dependency in your POM:\n" + "\n" + "<dependency>\n" + " <groupId>org.jenkins-ci.main</groupId>\n" + " <artifactId>jenkins-war</artifactId>\n" + " <type>war</type>\n" + " <version>1.396<!-- replace this with the version you want--></version>\n" + " <scope>test</scope>\n" + "</dependency>" ); } throw new MojoExecutionException("Unable to find jenkins.war"); }</code><technical_language>want fallback finding if this newer match fails</technical_language>

Target:
protected Artifact getJenkinsWarArtifact() throws MojoExecutionException { for( Artifact a : resolveDependencies("test") ) { boolean match; if (jenkinsWarId!=null) match = (a.getGroupId()+':'+a.getArtifactId()).equals(jenkinsWarId); else match = (a.getArtifactId().equals("jenkins-war") || a.getArtifactId().equals("hudson-war")) && (a.getType().equals("executable-war") || a.getType().equals("war")); if(match) return a; } if (jenkinsWarId!=null) { getLog().error("Unable to locate jenkins.war in '"+jenkinsWarId+"'"); } else { getLog().error( "Unable to locate jenkins.war. Add the following dependency in your POM:\n" + "\n" + "<dependency>\n" + " <groupId>org.jenkins-ci.main</groupId>\n" + " <artifactId>jenkins-war</artifactId>\n" + " <type>war</type>\n" + " <version>1.396<!-- replace this with the version you want--></version>\n" + " <scope>test</scope>\n" + "</dependency>" ); } throw new MojoExecutionException("Unable to find jenkins.war"); }
Source:
<code>private void validate() { long currencyCount = amounts.stream() .map(ArgChecker::notNullItem) .map(CurrencyAmount::getCurrency) .distinct() .count(); if (currencyCount < amounts.size()) { <START> throw new IllegalArgumentException("Duplicate currency not allowed"); <END> } }</code><technical_language>of letting user duplicate was? add toString end of exception message</technical_language>

Target:
private void validate() { long currencyCount = amounts.stream() .map(ArgChecker::notNullItem) .map(CurrencyAmount::getCurrency) .distinct() .count(); if (currencyCount < amounts.size()) { throw new IllegalArgumentException("Duplicate currency not allowed: " + amounts); } }
Source:
<code>private void validateInput() { if (getShell() == null) { return; } String tagNameMessage = tagNameValidator.isValid(tagNameText.getText()); setErrorMessage(tagNameMessage); String tagMessageVal = tagMessageText.getText().trim(); boolean isLightWeight = lightweightButton.getSelection(); Control button = getButton(IDialogConstants.OK_ID); if (button != null) { boolean containsTagNameAndMessage = (tagNameMessage == null || tagMessageVal .length() == 0) && tagMessageVal.length() != 0; boolean shouldOverwriteTag = (overwriteButton.getSelection() && Repository .isValidRefName(Constants.R_TAGS + tagNameText.getText())); boolean enabled = containsTagNameAndMessage || shouldOverwriteTag || (isLightWeight && tagNameMessage == null && !tagNameText.getText().isEmpty()); button.setEnabled(enabled); Button createTagAndStartPush = getButton(CREATE_AND_START_PUSH_ID); if (createTagAndStartPush != null) createTagAndStartPush.setEnabled(enabled); } boolean existingTagSelected = existingTag != null; boolean <START> editable = <END> (existingTagSelected && !overwriteButton.getSelection()) || isLightWeight; tagMessageText.getTextWidget().setEditable(editable); overwriteButton.setEnabled(existingTagSelected); if (!existingTagSelected) overwriteButton.setSelection(false); }</code><technical_language>I this is condition for !editable, i.e., readOnly</technical_language>

Target:
private void validateInput() { if (getShell() == null) { return; } String tagNameMessage = tagNameValidator.isValid(tagNameText.getText()); setErrorMessage(tagNameMessage); String tagMessageVal = tagMessageText.getText().trim(); boolean isLightWeight = tagMessageVal.isEmpty(); Control button = getButton(IDialogConstants.OK_ID); if (button != null) { boolean containsTagNameAndMessage = (tagNameMessage == null || tagMessageVal.length() == 0) && tagMessageVal.length() != 0; boolean shouldOverwriteTag = (overwriteButton.getSelection() && Repository.isValidRefName( Constants.R_TAGS + tagNameText.getText())); boolean enabled = containsTagNameAndMessage || shouldOverwriteTag || (isLightWeight && tagNameMessage == null && !tagNameText.getText().isEmpty()); button.setEnabled(enabled); Button createTagAndStartPush = getButton(CREATE_AND_START_PUSH_ID); if (createTagAndStartPush != null) createTagAndStartPush.setEnabled(enabled); } boolean existingTagSelected = existingTag != null; boolean readOnly = (existingTagSelected && !overwriteButton.getSelection()); tagMessageText.getTextWidget().setEditable(!readOnly); overwriteButton.setEnabled(existingTagSelected); if (!existingTagSelected) overwriteButton.setSelection(false); }
Source:
<code>public Object execute(int idxInPartition, WindowFrameState currentFrame, List<? extends CollectExpression<Row, ?>> expressions, Input... args) { final int offset; if (args.length > 1) { <START> offset = ((Number) args[1].value()).intValue(); <END> } else { offset = 1; } if (offset <= idxInPartition) { int lagIdx = idxInPartition - offset; var lagRowCells = currentFrame.getRowInPartitionAtIndexOrNull(lagIdx); if (lagRowCells == null) { return null; } Row lagRow = new RowN(lagRowCells); for (CollectExpression<Row, ?> expression : expressions) { expression.setNextRow(lagRow); } return args[0].value(); } else { if (args.length == 3) { return args[2].value(); } else { return null; } } }</code><technical_language>this raise a NPE</technical_language>

Target:
public Object execute(int idxInPartition, WindowFrameState currentFrame, List<? extends CollectExpression<Row, ?>> expressions, Input... args) { final int offset; if (args.length > 1) { Object offsetValue = args[1].value(); if (offsetValue == null) { return null; } else { offset = ((Number) offsetValue).intValue(); } } else { offset = 1; } var lagRowCells = currentFrame .getRowInPartitionAtIndexOrNull(idxInPartition - offset); if (lagRowCells != null) { var lagRow = new RowN(lagRowCells); for (CollectExpression<Row, ?> expression : expressions) { expression.setNextRow(lagRow); } return args[0].value(); } else { return getDefaultOrNull(args); } }
Source:
<code><START> public Command getCommand() { <END> return this.currentCommand; }</code><technical_language>get selected pattern get command</technical_language>

Target:
public Command getCommand() { return selectionPage.getComboSelection().getPatternCreationCommand(); }
Source:
<code>private Launcher getTaskLauncher(String platformName) { Launcher launcherToUse = null; List<Launcher> launchers = getLaunchers(); for (Launcher launcher : launchers) { if (launcher.getName().equalsIgnoreCase(platformName)) { launcherToUse = launcher; break; } } <START> if (launcherToUse == null && platformName != null) { <END> throw new IllegalArgumentException(String.format("The platform %s does not exist", platformName)); } int launcherCount = 0; if (launcherToUse == null) { if(getPrimaryLauncher() != null) { return getPrimaryLauncher(); } for(Launcher launcher : launchers) { if(launcher.getScheduler() != null) { launcherToUse = launcher; launcherCount++; } } } if (launcherCount > 1 ) { throw new IllegalArgumentException("Must select a platform. " + "A default could not be determined because more than one platform" + " had an associated scheduler"); } if (platformName != null && launcherToUse == null) { throw new IllegalArgumentException(String.format("The platform %s does not support a scheduler service.", platformName)); } else if (platformName == null && launcherToUse == null) { throw new IllegalStateException("Could not find a default scheduler."); } return launcherToUse; }</code><technical_language>empty String check (probably StringUtils)</technical_language>

Target:
private Launcher getTaskLauncher(String platformName) { Launcher launcherToUse = null; List<Launcher> launchers = getLaunchers(); for (Launcher launcher : launchers) { if (launcher.getName().equalsIgnoreCase(platformName)) { launcherToUse = launcher; break; } } if (launcherToUse == null && StringUtils.hasText(platformName)) { throw new IllegalArgumentException(String.format("The platform %s does not exist", platformName)); } int launcherCount = 0; if (launcherToUse == null) { if(getPrimaryLauncher() != null) { return getPrimaryLauncher(); } for(Launcher launcher : launchers) { if(launcher.getScheduler() != null) { launcherToUse = launcher; launcherCount++; } } } if (launcherCount > 1 ) { throw new IllegalArgumentException("Must select a platform. " + "A default could not be determined because more than one platform" + " had an associated scheduler"); } if (platformName != null && launcherToUse == null) { throw new IllegalArgumentException(String.format("The platform %s does not support a scheduler service.", platformName)); } else if (platformName == null && launcherToUse == null) { throw new IllegalStateException("Could not find a default scheduler."); } return launcherToUse; }
Source:
<code>public Map<String, String> populateCustomClaims(TokenValidationContext validationContext) throws APIManagementException { Map<ClaimMapping, String> customClaimsWithMapping = new HashMap<>(); Map<String, String> customClaims; Map<String, Object> properties = new HashMap<String, Object>(); String accessToken = validationContext.getAccessToken(); String authCode = validationContext.getAuthorizationCode(); if (accessToken != null) { properties.put(APIConstants.KeyManager.ACCESS_TOKEN, accessToken); } else if (authCode != null) { properties.put(APIConstants.KeyManager.AUTH_CODE, authCode); } else { customClaimsWithMapping.putAll(validationContext.getUser().getUserAttributes()); } String username = validationContext.getValidationInfoDTO().getEndUserName(); int tenantId = APIUtil.getTenantId(username); <START> customClaims = convertClaimMap(customClaimsWithMapping, username); <END> String dialectURI = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService() .getAPIManagerConfiguration().getFirstProperty(APIConstants.CONSUMER_DIALECT_URI); if (!StringUtils.isEmpty(dialectURI)) { properties.put(APIConstants.KeyManager.CLAIM_DIALECT, dialectURI); } String keymanagerName = validationContext.getValidationInfoDTO().getKeyManager(); KeyManager keymanager = KeyManagerHolder.getKeyManagerInstance(APIUtil.getTenantDomainFromTenantId(tenantId), keymanagerName); Map<String, String> retreivedClaims = keymanager.getUserClaims(username, properties); if (log.isDebugEnabled()) { log.debug("Retrieved claims :" + retreivedClaims); } customClaims.putAll(retreivedClaims); ClaimsRetriever claimsRetriever = getClaimsRetriever(); if (claimsRetriever != null) { customClaims.putAll(claimsRetriever.getClaims(username)); } return customClaims; }</code><technical_language>this need done in webapp</technical_language>

Target:
public Map<String, String> populateCustomClaims(TokenValidationContext validationContext) throws APIManagementException { Map<String, String> customClaims; Map<String, Object> properties = new HashMap<String, Object>(); String accessToken = validationContext.getAccessToken(); if (accessToken != null) { properties.put(APIConstants.KeyManager.ACCESS_TOKEN, accessToken); } String username = validationContext.getValidationInfoDTO().getEndUserName(); int tenantId = APIUtil.getTenantId(username); String dialectURI = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService() .getAPIManagerConfiguration().getFirstProperty(APIConstants.CONSUMER_DIALECT_URI); if (!StringUtils.isEmpty(dialectURI)) { properties.put(APIConstants.KeyManager.CLAIM_DIALECT, dialectURI); } String keymanagerName = validationContext.getValidationInfoDTO().getKeyManager(); KeyManager keymanager = KeyManagerHolder.getKeyManagerInstance(APIUtil.getTenantDomainFromTenantId(tenantId), keymanagerName); customClaims = keymanager.getUserClaims(username, properties); if (log.isDebugEnabled()) { log.debug("Retrieved claims :" + customClaims); } ClaimsRetriever claimsRetriever = getClaimsRetriever(); if (claimsRetriever != null) { customClaims.putAll(claimsRetriever.getClaims(username)); } return customClaims; }
Source:
<code>private void saveIllegalDisk(final DiskImage diskImage) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { diskImage.setId(Guid.NewGuid()); diskImage.setimage_group_id(Guid.NewGuid()); diskImage.setParentId(Guid.Empty); diskImage.setit_guid(Guid.Empty); diskImage.setvm_guid(getVmId()); ImagesHandler.addDiskImage(diskImage); <START> ImagesHandler.setDiskAlias(diskImage.getDisk(), getVm()); <END> return null; } }); }</code><technical_language>addDiskImage save db, im disk alias saved</technical_language>

Target:
private void saveIllegalDisk(final DiskImage diskImage) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { diskImage.setId(Guid.NewGuid()); diskImage.setimage_group_id(Guid.NewGuid()); diskImage.setParentId(Guid.Empty); diskImage.setit_guid(Guid.Empty); diskImage.setvm_guid(getVmId()); ImagesHandler.setDiskAlias(diskImage.getDisk(), getVm()); ImagesHandler.addDiskImage(diskImage); return null; } }); }
Source:
<code>public void execute(EObject object) { <START> new ExtendedLoadResourceDialog(Display.getDefault().getActiveShell(), <END> AdapterFactoryEditingDomain.getEditingDomainFor(object)).open(); }</code><technical_language>a complicated dialog, code in wizard creating a new view model</technical_language>

Target:
public void execute(EObject object) { editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(object); new ExtendedLoadResourceDialog(Display.getDefault().getActiveShell(), editingDomain).open(); }
Source:
<code>public void beginCreateSearch() { List<String> phonePlanIds = new ArrayList<>(); phonePlanIds.add("27b53eec-8ff4-4070-8900-fbeaabfd158a"); CreateSearchOptions createSearchOptions = new CreateSearchOptions(); createSearchOptions .setAreaCode(AREA_CODE_FOR_SEARCH) <START> .setDescription("testsearch20200014") <END> .setDisplayName("testsearch20200014") .setPhonePlanIds(phonePlanIds) .setQuantity(2); Duration duration = Duration.ofSeconds(5); PhoneNumberAsyncClient client = this.getClient(); PollerFlux<PhoneNumberSearch, PhoneNumberSearch> res = client.beginCreateSearch(createSearchOptions, duration); SyncPoller<PhoneNumberSearch, PhoneNumberSearch> sync = res.getSyncPoller(); sync.waitForCompletion(); PhoneNumberSearch testResult = sync.getFinalResult(); assertEquals(testResult.getPhoneNumbers().size(), 2); assertNotNull(testResult.getSearchId()); }</code><technical_language>nit: DESCRIPTION_FOR_SEARCH for Name, cleaner</technical_language>

Target:
public void beginCreateSearch() { List<String> phonePlanIds = new ArrayList<>(); phonePlanIds.add(PHONE_PLAN_ID); CreateSearchOptions createSearchOptions = new CreateSearchOptions(); createSearchOptions .setAreaCode(AREA_CODE_FOR_SEARCH) .setDescription(SEARCH_OPTIONS_DESCRIPTION) .setDisplayName(SEARCH_OPTIONS_NAME) .setPhonePlanIds(phonePlanIds) .setQuantity(2); Duration duration = Duration.ofSeconds(1); PhoneNumberAsyncClient client = this.getClient(); PollerFlux<PhoneNumberSearch, PhoneNumberSearch> poller = client.beginCreateSearch(createSearchOptions, duration); AsyncPollResponse<PhoneNumberSearch, PhoneNumberSearch> asyncRes = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); PhoneNumberSearch testResult = asyncRes.getValue(); assertEquals(testResult.getPhoneNumbers().size(), 2); assertNotNull(testResult.getSearchId()); }
Source:
<code><START> public synchronized void postJobMessage(JobMessage jobMessage) throws JobMessageDispatchException { <END> try { CPMSession session = this.getSession(); CPMMessage message = session.createMessage() .setDurable(true) .setProperty(JOB_KEY_MESSAGE_PROPERTY, jobMessage.getJobKey()); String serializedJobMessage = this.objMapper.writeValueAsString(jobMessage); message.setBody(serializedJobMessage); log.debug("Sending job message to {}: {}", JOB_MESSAGE_ADDRESS, serializedJobMessage); this.getProducer().send(JOB_MESSAGE_ADDRESS, message); } catch (Exception e) { throw new JobMessageDispatchException(e); } }</code><technical_language>this is a restriction of Artemis, care this level, try adding synchronized flag Artemis implementations of messaging system. In this case, ArtemisProducer.send, ArtemisSession.commit .rollback (probably .close, too)</technical_language>

Target:
public void postJobMessage(JobMessage jobMessage) throws JobMessageDispatchException { try { CPMSession session = this.getSession(); CPMMessage message = session.createMessage() .setDurable(true) .setProperty(JOB_KEY_MESSAGE_PROPERTY, jobMessage.getJobKey()); String serializedJobMessage = this.objMapper.writeValueAsString(jobMessage); message.setBody(serializedJobMessage); log.debug("Sending job message to {}: {}", JOB_MESSAGE_ADDRESS, serializedJobMessage); this.getProducer().send(JOB_MESSAGE_ADDRESS, message); } catch (Exception e) { throw new JobMessageDispatchException(e); } }
Source:
<code>public BlockingTaskAwareExecutorServiceImpl(String controllerThreadName, ExecutorService executorService, TimeService timeService) { <START> this.blockedTasks = new LinkedBlockingQueue<>(); <END> this.executorService = executorService; this.timeService = timeService; this.shutdown = false; this.controllerThread = new ControllerThread(controllerThreadName); controllerThread.start(); }</code><technical_language>I is a reason this is specifically a BlockingQueue? block waiting for elements added, instead semaphore a bounds (besides Integer.MAX_VALUE). this a standard ConcurrentLinkedQueue</technical_language>

Target:
public BlockingTaskAwareExecutorServiceImpl(String controllerThreadName, ExecutorService executorService, TimeService timeService) { this.blockedTasks = new ConcurrentLinkedQueue<>(); this.executorService = executorService; this.timeService = timeService; this.shutdown = false; this.controllerThread = new ControllerThread(controllerThreadName); controllerThread.start(); }
Source:
<code>private void addXmlAttributesToContextMap( final StartElement startElement, final Map<String, String> contextMap) { <START> for (final Iterator attributeIterator = startElement.getAttributes(); <END> attributeIterator.hasNext(); ) { final javax.xml.stream.events.Attribute attribute = (javax.xml.stream.events.Attribute) attributeIterator.next(); final String attributeKey = startElement.getName().getLocalPart() + "@" + attribute.getName().getLocalPart(); contextMap.put(attributeKey, attribute.getValue()); } }</code><technical_language>this written a stream iterator? like: Iterable<Attribute> iterable = () -> startElement.getAttributes(); StreamUtils.stream(iterable.spliterator(), false) .map(attribute -> ...do map stuff...) .forEach(mapEntry -> contextMap.put(mapEntry.getKey(), mapEntry.getValue()); if not, compound statement in clause is a tad odd</technical_language>

Target:
private void addXmlAttributesToContextMap( final StartElement startElement, final Map<String, String> contextMap) { final Iterator<javax.xml.stream.events.Attribute> attributeIterator = startElement.getAttributes(); while (attributeIterator.hasNext()) { final javax.xml.stream.events.Attribute attribute = attributeIterator.next(); final String attributeKey = startElement.getName().getLocalPart() + "@" + attribute.getName().getLocalPart(); contextMap.put(attributeKey, attribute.getValue()); } }
Source:
<code>public static void startServer() throws Exception { LOG = LoggerFactory.getLogger(HDFSDDFManagerTests.class); manager = new HDFSDDFManager(System.getenv("HDFS_URI")); try { new HDFSDDFManager("invalidpath"); assert false; <START> } catch (Exception e) <END> }</code><technical_language>catch exact exception wanted thrown</technical_language>

Target:
public static void startServer() throws Exception { LOG = LoggerFactory.getLogger(HDFSDDFManagerTests.class); manager = new HDFSDDFManager(System.getenv("HDFS_URI")); }