auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>LRESULT WM_CHAR (long wParam, long lParam) { if (ignoreCharacter) return null; LRESULT result = super.WM_CHAR (wParam, lParam); if (result != null) return result; switch ((int) wParam) { case SWT.DEL: if (OS.GetKeyState (OS.VK_CONTROL) < 0) { if ((style & SWT.READ_ONLY) != 0) return <START> LRESULT.ZERO; <END> Point selection = getSelection (); int x = selection.x; int y = selection.y; if (x == y) { String actText = getText (0, getCaretPosition ()); java.util.regex.Matcher m = CTRL_BS_PATTERN.matcher (actText); if (m.find ()) { x = m.start (); y = m.end (); OS.SendMessage (handle, OS.EM_SETSEL, x, y); } } if (x < y) { OS.SendMessage (handle, OS.EM_REPLACESEL, 1, 0); } return LRESULT.ZERO; } } if ((style & SWT.SINGLE) != 0) { switch ((int) wParam) { case SWT.CR: sendSelectionEvent (SWT.DefaultSelection); case SWT.TAB: case SWT.ESC: return LRESULT.ZERO; } } return result; }</code><technical_language>suggest apply Ctrl_BackSpace feature for Passwords Text field, instead return. For this include PASSWORD in if condition: if ((style & SWT.READ_ONLY) != 0 || (style & SWT.PASSWORD) != 0)</technical_language>

Target:
LRESULT WM_CHAR (long wParam, long lParam) { if (ignoreCharacter) return null; LRESULT result = super.WM_CHAR (wParam, lParam); if (result != null) return result; switch ((int) wParam) { case SWT.DEL: if (OS.GetKeyState (OS.VK_CONTROL) < 0) { if ((style & SWT.READ_ONLY) != 0 || (style & SWT.PASSWORD) != 0) return LRESULT.ZERO; Point selection = getSelection (); int x = selection.x; int y = selection.y; if (x == y) { String actText = getText (0, x - 1); java.util.regex.Matcher m = CTRL_BS_PATTERN.matcher (actText); if (m.find ()) { x = m.start (); y = m.end (); OS.SendMessage (handle, OS.EM_SETSEL, x, y); } } if (x < y) { OS.SendMessage (handle, OS.EM_REPLACESEL, 1, 0); } return LRESULT.ZERO; } } if ((style & SWT.SINGLE) != 0) { switch ((int) wParam) { case SWT.CR: sendSelectionEvent (SWT.DefaultSelection); case SWT.TAB: case SWT.ESC: return LRESULT.ZERO; } } return result; }
Source:
<code>public static String getUnoccupiedWorkspaceLocation(String name) { String stringPath = getDefaultWorkspaceLocation(name); try { if (isLocked(stringPath)) { int i = 1; String newStringPath; do { i++; newStringPath = getDefaultWorkspaceLocation(name + "-" + i); } while (isLocked(newStringPath)); stringPath = newStringPath; } } catch (IOException e) { <START> Q7UIPlugin.log(e); <END> return stringPath; } return stringPath; }</code><technical_language>eat exceptions</technical_language>

Target:
private String getUnoccupiedWorkspaceLocation(String name) { String stringPath = getDefaultWorkspaceLocation(name); try { if (isLocationExists(stringPath)) { int i = 1; String newStringPath; do { i++; newStringPath = getDefaultWorkspaceLocation(name + "-" + i); } while (isLocationExists(newStringPath)); stringPath = newStringPath; } } catch (CoreException e) { Q7UIPlugin.log(e); } return stringPath; }
Source:
<code>private void printProgress(final ProgressMessage message) { final String id = message.id(); Integer line = idsToLines.get(id); int diff = 0; if (line == null) { line = idsToLines.size(); idsToLines.put(id, line); } else { diff = idsToLines.size() - line; } if (diff > 0) { out.printf("%c[%dA", ESC_CODE, diff); out.printf("%c[2K\r", ESC_CODE); } String progress = message.progress(); if (progress == null) { progress = ""; } <START> out.printf("%s: %s %s\r\n", id, message.status(), progress); <END> if (diff > 0) { out.printf("%c[%dB", ESC_CODE, diff - 1); } }</code><technical_language>\r in there</technical_language>

Target:
private void printProgress(final ProgressMessage message) { final String id = message.id(); Integer line = idsToLines.get(id); int diff = 0; if (line == null) { line = idsToLines.size(); idsToLines.put(id, line); } else { diff = idsToLines.size() - line; } if (diff > 0) { out.printf("%c[%dA", ESC_CODE, diff); out.printf("%c[2K\r", ESC_CODE); } String progress = message.progress(); if (progress == null) { progress = ""; } out.printf("%s: %s %s%n", id, message.status(), progress); if (diff > 0) { out.printf("%c[%dB", ESC_CODE, diff - 1); } }
Source:
<code>public void theSetPushSetupSmsRequestIsReceived(final Map<String, String> settings) throws Throwable { <START> final SetPushSetupSmsRequest smsrequest = SetPushSetupSmsRequestFactory.fromParameterMap(settings); <END> final SetPushSetupSmsAsyncResponse smsasyncResponse = this.smartMeteringConfigurationClient .setPushSetupSms(smsrequest); LOGGER.info("Set special days response is received {}", smsasyncResponse); assertNotNull("Set special days response should not be null", smsasyncResponse); ScenarioContext.current().put(PlatformSmartmeteringKeys.KEY_CORRELATION_UID, smsasyncResponse.getCorrelationUid()); ScenarioContext.current().put(PlatformSmartmeteringKeys.HOSTNAME, settings.get(PlatformSmartmeteringKeys.HOSTNAME)); ScenarioContext.current().put(PlatformSmartmeteringKeys.PORT, settings.get(PlatformSmartmeteringKeys.PORT)); }</code><technical_language>Write Camel case: smsRequest</technical_language>

Target:
public void theSetPushSetupSmsRequestIsReceived(final Map<String, String> settings) throws Throwable { final SetPushSetupSmsRequest setPushSetupSmsRequest = SetPushSetupSmsRequestFactory.fromParameterMap(settings); final SetPushSetupSmsAsyncResponse setPushSetupSmsAsyncResponse = this.smartMeteringConfigurationClient .setPushSetupSms(setPushSetupSmsRequest); LOGGER.info("Set push setup sms response is received {}", setPushSetupSmsAsyncResponse); assertNotNull("Set push setup sms response should not be null", setPushSetupSmsAsyncResponse); ScenarioContext.current().put(PlatformSmartmeteringKeys.KEY_CORRELATION_UID, setPushSetupSmsAsyncResponse.getCorrelationUid()); ScenarioContext.current().put(PlatformSmartmeteringKeys.HOSTNAME, settings.get(PlatformSmartmeteringKeys.HOSTNAME)); ScenarioContext.current().put(PlatformSmartmeteringKeys.PORT, settings.get(PlatformSmartmeteringKeys.PORT)); }
Source:
<code>public void testRawQuery() throws ErrnoException { for (Network network : getTestableNetworks()) { CountDownLatch latch = new CountDownLatch(1); final int TIMEOUT_MS = 12_000; final String dname = "www.google.com"; mDns.query(network, dname, CLASS_IN, TYPE_AAAA, FLAG_NO_CACHE_LOOKUP, mHandler, answer -> { try { new <START> DnsRawAnswer(answer); <END> Log.d(TAG, "Reported blob:" + byteArrayToHexString(answer)); latch.countDown(); } catch (DnsPacket.ParseException e) { Log.d(TAG, e.getMessage()); } } ); String msg = "Raw query " + dname + " but no valid answer after " + TIMEOUT_MS + "ms."; try { assertTrue(msg, latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }</code><technical_language>This nullable (as showcased previous code) passing a @NonNull argument. below</technical_language>

Target:
public void testRawQuery() throws ErrnoException { for (Network network : getTestableNetworks()) { CountDownLatch latch = new CountDownLatch(1); final int TIMEOUT_MS = 12_000; final String dname = "www.google.com"; String msg = "Raw query " + dname; mDns.query(network, dname, CLASS_IN, TYPE_AAAA, FLAG_NO_CACHE_LOOKUP, mHandler, answer -> { if (answer == null) { fail(msg + " no answer returned"); } try { new CheckedDnsPacket(answer); Log.d(TAG, "Reported blob:" + byteArrayToHexString(answer)); latch.countDown(); } catch (DnsPacket.ParseException e) { Log.d(TAG, e.getMessage()); fail(msg + " no valid answer"); } } ); try { assertTrue(msg + " but no answer after " + TIMEOUT_MS + "ms.", latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }
Source:
<code>public static void main(String[] args) { DefaultCacheManager cacheManager = new DefaultCacheManager(); MultimapCacheManager multimapCacheManager = EmbeddedMultimapCacheManagerFactory.from(cacheManager); multimapCacheManager.defineConfiguration("multimap", new ConfigurationBuilder().build()); MultimapCache<String, String> multimap = multimapCacheManager.get("multimap"); multimap.put("key", "value1"); multimap.put("key", "value2"); multimap.put("key", "value3"); <START> multimap.get("key").whenComplete((values, ex) -> { <END> System.out.println(values); cacheManager.stop(); }); }</code><technical_language>guarantee get called puts complete. This confuse users. put returns, create a a CompletableFuture of calling CompletableFuture.allOf, completes do get. this tutorial reliable</technical_language>

Target:
public static void main(String[] args) { DefaultCacheManager cacheManager = new DefaultCacheManager(); MultimapCacheManager multimapCacheManager = EmbeddedMultimapCacheManagerFactory.from(cacheManager); multimapCacheManager.defineConfiguration("multimap", new ConfigurationBuilder().build()); MultimapCache<String, String> multimap = multimapCacheManager.get("multimap"); CompletableFuture.allOf( multimap.put("key", "value1"), multimap.put("key", "value2"), multimap.put("key", "value3")) .whenComplete((nil, ex) -> { multimap.get("key").whenComplete((values, ex2) -> { System.out.println(values); cacheManager.stop(); }); }); }
Source:
<code>private boolean transitionToWithWorkingBranchRuleExists(IAtsStateDefinition toStateDef) { <START> return (toStateDef.hasRule(RuleDefinitionOption.AllowTransitionWithWorkingBranch.name())); <END> }</code><technical_language>remove unnecessary surrounding parenthesis</technical_language>

Target:
private boolean transitionToWithWorkingBranchRuleExists(IAtsStateDefinition toStateDef) { return toStateDef.hasRule(RuleDefinitionOption.AllowTransitionWithWorkingBranch.name()); }
Source:
<code>public void set(byte[] utf8) { <START> if(utf8.length == 0){ <END> bytes = EMPTY_BYTES; length = 0; textLength = -1; return; } set(utf8, 0, utf8.length); }</code><technical_language>nit: add spaces side of () ,e.g if (utf8.length == 0) {</technical_language>

Target:
public void set(byte[] utf8) { if (utf8.length == 0) { bytes = EMPTY_BYTES; length = 0; textLength = -1; } else { set(utf8, 0, utf8.length); } }
Source:
<code>public void testWindowsCount() { System.out.println("java.vendor: " + System.getProperty("java.vendor")); System.out.println("java.version: " + System.getProperty("java.version")); System.out.println("os.version: " + System.getProperty("os.version")); System.out.println("os.arch: " + System.getProperty("os.arch")); System.out.println("os.name: " + System.getProperty("os.name")); ShellApplication sa = new ShellApplication(); System.out.println("Shell.Application.Windows found: " + sa.Windows().Count()); assertTrue(sa.Windows().Count() > 0); for (InternetExplorer ie : sa.Windows()) { System.out.println(); System.out.println("============================================"); if (ie != null) { System.out.println("Title: " + ie.getTitle()); System.out.println("URL: " + ie.getURL()); System.out.println("App Name: " + ie.getName()); System.out.println("Window Handle: " + ie.getWindowHandle()); } else { System.out.println("Null encountered."); } System.out.println("============================================"); System.out.println(); <START> } <END> }</code><technical_language>assert titles, URLs, name, jut print out. Similarly, assertNotNull(ie), test failing unexpected, need print "null encountered", a bug</technical_language>

Target:
public void testWindowsCount() { ShellApplication sa = new ShellApplication(); assertTrue(sa.Windows().Count() > 0); boolean pageFound = false; for (InternetExplorer ie : sa.Windows()) { if (ie != null && "about:blank".equals(ie.getURL())) { pageFound = true; } } assertTrue(pageFound); }
Source:
<code>private static Path installForm(Path formDir, final String formName) { Path sourceForm = getPath(formName + ".xml"); Path targetForm = formDir.resolve("form.xml"); copy(sourceForm, targetForm); Path instancesDir = formDir.resolve("instances"); createDirectories(instancesDir); maybeGetPath(formName + "_submission.xml") .filter(Files::exists) .ifPresent(path -> { String instanceId = readInstanceId(path); Path submissionDir = instancesDir.resolve(instanceId.replace(":", "")); createDirectories(submissionDir); walk(path.getParent()) .filter(file -> file.getFileName().toString().startsWith(formName + "_")) <START> .filter(file -> !file.getFileName().toString().endsWith(".pem")) <END> .filter(file -> !file.getFileName().toString().endsWith(".tpl")) .forEach(file -> { Path target = submissionDir.resolve(file.getFileName().toString().substring(formName.length() + 1)); log.debug("Install " + submissionDir.getFileName() + "/" + target.getFileName()); copy(file, target); }); }); return targetForm; }</code><technical_language>I find this more readable. You? .filter(file -> { String name = file.getFileName().toString(); return name.startsWith(formName + "_") && !name.endsWith(".pem") && !name.endsWith(".tpl"); }).forEach(file -> {</technical_language>

Target:
private static Path installForm(Path formDir, final String formName) { Path sourceForm = getPath(formName + ".xml"); Path targetForm = formDir.resolve("form.xml"); copy(sourceForm, targetForm); Path instancesDir = formDir.resolve("instances"); createDirectories(instancesDir); maybeGetPath(formName + "-submission.xml") .filter(Files::exists) .ifPresent(path -> { String instanceId = readInstanceId(path); Path submissionDir = instancesDir.resolve(instanceId.replace(":", "")); createDirectories(submissionDir); walk(path.getParent()) .filter(isRelatedToForm(formName)) .filter(isPemFile().negate()) .filter(isTemplateFile().negate()) .filter(isExpectedContentsFile().negate()) .forEach(file -> { Path target = submissionDir.resolve(file.getFileName().toString().substring(formName.length() + 1)); log.debug("Install " + submissionDir.getFileName() + "/" + target.getFileName()); copy(file, target); }); }); return targetForm; }
Source:
<code>public AbstractMailer(Props props) { this.azkabanName = props.getString("azkaban.name", "azkaban"); this.mailHost = props.getString("mail.host", "localhost"); <START> this.mailPort = props.getString("mail.port", Emailer.DEFAULT_SMTP_PORT); <END> this.mailUser = props.getString("mail.user", ""); this.mailPassword = props.getString("mail.password", ""); long maxAttachmentSizeInMB = props.getInt("mail.max.attachment.size.mb", 100); attachmentMazSizeInByte = maxAttachmentSizeInMB * MB_IN_BYTES; this.mailSender = props.getString("mail.sender", ""); this.usesAuth = props.getBoolean("mail.useAuth", true); this.clientHostname = props.get("server.hostname"); this.clientPort = props.getInt("server.port"); this.usesSSL = props.getBoolean("server.useSSL"); if (usesSSL) { referenceURL = "https://" + clientHostname + (clientPort == 443 ? "/" : ":" + clientPort + "/"); } else { referenceURL = "http://" + clientHostname + (clientPort == 80 ? "/" : ":" + clientPort + "/"); } }</code><technical_language>is a getInteger method, if int mailPoint</technical_language>

Target:
public AbstractMailer(Props props) { this.azkabanName = props.getString("azkaban.name", "azkaban"); this.mailHost = props.getString("mail.host", "localhost"); this.mailPort = props.getInt("mail.port", DEFAULT_SMTP_PORT); this.mailUser = props.getString("mail.user", ""); this.mailPassword = props.getString("mail.password", ""); this.tls = props.getString("mail.tls", "false"); long maxAttachmentSizeInMB = props.getInt("mail.max.attachment.size.mb", 100); attachmentMazSizeInByte = maxAttachmentSizeInMB * MB_IN_BYTES; this.mailSender = props.getString("mail.sender", ""); this.usesAuth = props.getBoolean("mail.useAuth", true); this.clientHostname = props.get("server.hostname"); this.clientPort = props.getInt("server.port"); this.usesSSL = props.getBoolean("server.useSSL"); if (usesSSL) { referenceURL = "https://" + clientHostname + (clientPort == 443 ? "/" : ":" + clientPort + "/"); } else { referenceURL = "http://" + clientHostname + (clientPort == 80 ? "/" : ":" + clientPort + "/"); } }
Source:
<code>public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.isEmpty()) { return ExprEval.of(null); } ExprAnalysis exprAnalysis = analyzeExprs(args, bindings); if (exprAnalysis == null) { <START> return ExprEval.of(null); <END> } Stream<ExprEval<?>> exprEvalStream = exprAnalysis.exprEvals.stream(); switch (exprAnalysis.comparisonType) { case DOUBLE: return ExprEval.of(exprEvalStream.mapToDouble(ExprEval::asDouble).reduce(doubleReducer).getAsDouble()); case LONG: return ExprEval.of(exprEvalStream.mapToLong(ExprEval::asLong).reduce(longReducer).getAsLong()); default: return ExprEval.of(exprEvalStream.map(ExprEval::asString).reduce(stringReducer).get()); } }</code><technical_language>if mis-reading this. this patch introduces expressions calculate greatest / multiple expressions. Native druid queries a post aggregator do this. I thinking of implementing this I thought a translation sql native druid query correct post aggregator (maybe in - OperatorConversions#toPostAggregator) want this behavior stays in sync Double/LongPostAggregators</technical_language>

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.isEmpty()) { return ExprEval.of(null); } ExprAnalysis exprAnalysis = analyzeExprs(args, bindings); if (exprAnalysis.exprEvals.isEmpty()) { return ExprEval.of(null); } Stream<ExprEval<?>> exprEvalStream = exprAnalysis.exprEvals.stream(); switch (exprAnalysis.comparisonType) { case DOUBLE: return ExprEval.of(exprEvalStream.mapToDouble(ExprEval::asDouble).reduce(doubleReducer).getAsDouble()); case LONG: return ExprEval.of(exprEvalStream.mapToLong(ExprEval::asLong).reduce(longReducer).getAsLong()); default: return ExprEval.of(exprEvalStream.map(ExprEval::asString).reduce(stringReducer).get()); } }
Source:
<code>@Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); for (IgniteConfiguration cfg : configurations()) <START> Ignition.start(cfg); <END> node().cluster().state(ClusterState.ACTIVE); }</code><technical_language>Do a reason startGrid(cfg) here</technical_language>

Target:
@Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); for (IgniteConfiguration cfg : configurations()) startGrid(cfg); node().cluster().state(ClusterState.ACTIVE); }
Source:
<code>public AzureClientRegistrationRepository clientRegistrationRepository() { return new AzureClientRegistrationRepository( createDefaultClient(), createAuthzClients(), <START> properties.getAuthorization()); <END> }</code><technical_language>pass properties instead of properties.getAuthorization()? need other property item in AzureClientRegistrationRepository</technical_language>

Target:
public AzureClientRegistrationRepository clientRegistrationRepository() { return new AzureClientRegistrationRepository( createDefaultClient(), createAuthzClients(), properties); }
Source:
<code>public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { url = getRegistryUrl(url); Registry registry = registryFactory.getRegistry(url); if (RegistryService.class.equals(type)) { return proxyFactory.getInvoker((T) registry, type, url); } Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)); String group = qs.get(GROUP_KEY); if (group != null && group.length() > 0) { if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) { return doRefer(Cluster.getCluster("mergeable"), registry, type, url); } } <START> Cluster cluster = Cluster.getCluster(qs.get(CLUSTER_KEY)); <END> return doRefer(cluster, registry, type, url); }</code><technical_language>a default better</technical_language>

Target:
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { url = getRegistryUrl(url); Registry registry = registryFactory.getRegistry(url); if (RegistryService.class.equals(type)) { return proxyFactory.getInvoker((T) registry, type, url); } Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)); String group = qs.get(GROUP_KEY); if (group != null && group.length() > 0) { if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) { return doRefer(Cluster.getCluster(MergeableCluster.NAME), registry, type, url); } } Cluster cluster = Cluster.getCluster(qs.get(CLUSTER_KEY)); return doRefer(cluster, registry, type, url); }
Source:
<code>private void saveHookContent(List<Callable<Pair<GlusterHookEntity, VDSReturnValue>>> contentTasksList) { if (contentTasksList.isEmpty()) { return; } List<Pair<GlusterHookEntity, VDSReturnValue>> pairResults = ThreadPoolUtil.invokeAll(contentTasksList); for (Pair<GlusterHookEntity, VDSReturnValue> pairResult: pairResults) { final GlusterHookEntity hook = pairResult.getFirst(); <START> final String content = (String)pairResult.getSecond().getReturnValue(); <END> getHooksDao().updateGlusterHookContent(hook.getId(), hook.getChecksum(), content); } }</code><technical_language>vds command failure handled here</technical_language>

Target:
private void saveHookContent(List<Callable<Pair<GlusterHookEntity, VDSReturnValue>>> contentTasksList) { if (contentTasksList.isEmpty()) { return; } List<Pair<GlusterHookEntity, VDSReturnValue>> pairResults = ThreadPoolUtil.invokeAll(contentTasksList); for (Pair<GlusterHookEntity, VDSReturnValue> pairResult: pairResults) { final GlusterHookEntity hook = pairResult.getFirst(); if (!pairResult.getSecond().getSucceeded()) { log.infoFormat("Failed to get content of hook {0} with error {1} ", hook.getHookKey(), pairResult.getSecond().getVdsError().getMessage()); logMessage(hook.getClusterId(), hook.getHookKey(), AuditLogType.GLUSTER_HOOK_GETCONTENT_FAILED); continue; } final String content = (String)pairResult.getSecond().getReturnValue(); getHooksDao().updateGlusterHookContent(hook.getId(), hook.getChecksum(), content); } }
Source:
<code>public static BigDecimal numberToBigDecimal(Number number) { if (number instanceof QuantityType) { QuantityType<?> state = ((QuantityType<?>) number) .toUnit(((QuantityType<?>) number).getUnit().getSystemUnit()); <START> if (state != null) { <END> return new BigDecimal(state.doubleValue()); } return null; } if (number != null) { return new BigDecimal(number.toString()); } else { return null; } }</code><technical_language>more precise, "atLeastOneIsQuantity"</technical_language>

Target:
public static BigDecimal numberToBigDecimal(Number number) { if (number instanceof QuantityType) { QuantityType<?> state = ((QuantityType<?>) number) .toUnit(((QuantityType<?>) number).getUnit().getSystemUnit()); if (state != null) { return state.toBigDecimal(); } return null; } if (number != null) { return new BigDecimal(number.toString()); } else { return null; } }
Source:
<code>public double getLogProb(int value) { <START> return Math.log(getProb(value)); <END> }</code><technical_language>is faster method calculate log directly</technical_language>

Target:
public double getLogProb(int value) { checkHasParams(); int k = value; if (k >= 0 && k <= n) { return Util.logPartialFactorial(n, k) - Util.logFactorial(k) + k * Math.log(p) + (n - k) * Math.log(1 - p); } else { return Double.NEGATIVE_INFINITY; } }
Source:
<code>public long verify(CountWorkCall actualCall) { assertThat( actualCall.indexNames ) <START> .as( "Search work did not target the expected indexes: " ) <END> .isEqualTo( indexNames ); assertThat( actualCall.expectedResult ) .as( "Actual Call should not curry an expectedResult" ) .isNull(); return expectedResult; }</code><technical_language>"Count work", maybe</technical_language>

Target:
public long verify(CountWorkCall actualCall) { assertThat( actualCall.indexNames ) .as( "Count work did not target the expected indexes: " ) .isEqualTo( indexNames ); assertThat( actualCall.expectedResult ) .as( "Actual Call should not carry an expectedResult" ) .isNull(); return expectedResult; }
Source:
<code>public <T> OpenPgpDataResult<T> executeApi(Intent data, OpenPgpDataSource dataSource, OpenPgpDataSink<T> dataSink) { ParcelFileDescriptor input = null; ParcelFileDescriptor output = null; try { if (dataSource != null) { Long expectedSize = dataSource.getSizeForProgress(); if (expectedSize != null) { data.putExtra(EXTRA_DATA_LENGTH, (long) expectedSize); } else { data.removeExtra(EXTRA_PROGRESS_MESSENGER); } input = dataSource.startPumpThread(); } DataSinkTransferThread<T> pumpThread = null; int outputPipeId = 0; if (dataSink != null) { outputPipeId = mPipeIdGen.incrementAndGet(); output = mService.createOutputPipe(outputPipeId); pumpThread = ParcelFileDescriptorUtil.asyncPipeToDataSink(dataSink, output); } Intent result = executeApi(data, input, outputPipeId); if (pumpThread == null) { return new OpenPgpDataResult<>(result, null); } pumpThread.join(); return new OpenPgpDataResult<>(result, pumpThread.getResult()); } catch (Exception e) { Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e); Intent result = new Intent(); result.putExtra(RESULT_CODE, RESULT_CODE_ERROR); result.putExtra(RESULT_ERROR, new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage())); return new OpenPgpDataResult<>(result, null); } finally { if (output != null) { try { output.close(); } catch (IOException e) { Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e); } <START> } <END> } }</code><technical_language>pull finally handler a method Common's IO closeQuietly helpers. (closeLoudly()). do here</technical_language>

Target:
public <T> OpenPgpDataResult<T> executeApi(Intent data, OpenPgpDataSource dataSource, OpenPgpDataSink<T> dataSink) { ParcelFileDescriptor input = null; ParcelFileDescriptor output = null; try { if (dataSource != null) { Long expectedSize = dataSource.getSizeForProgress(); if (expectedSize != null) { data.putExtra(EXTRA_DATA_LENGTH, (long) expectedSize); } else { data.removeExtra(EXTRA_PROGRESS_MESSENGER); } input = dataSource.startPumpThread(); } DataSinkTransferThread<T> pumpThread = null; int outputPipeId = 0; if (dataSink != null) { outputPipeId = mPipeIdGen.incrementAndGet(); output = mService.createOutputPipe(outputPipeId); pumpThread = ParcelFileDescriptorUtil.asyncPipeToDataSink(dataSink, output); } Intent result = executeApi(data, input, outputPipeId); if (pumpThread == null) { return new OpenPgpDataResult<>(result, null); } pumpThread.join(); return new OpenPgpDataResult<>(result, pumpThread.getResult()); } catch (Exception e) { Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e); Intent result = new Intent(); result.putExtra(RESULT_CODE, RESULT_CODE_ERROR); result.putExtra(RESULT_ERROR, new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage())); return new OpenPgpDataResult<>(result, null); } finally { closeLoudly(output); } }
Source:
<code>public PlainDoubleDictionary(DictionaryPage dictionaryPage) throws IOException { super(dictionaryPage); final ByteBuffer dictionaryByteBuf = dictionaryPage.getBytes().toByteBuffer(); doubleDictionaryContent = new double[dictionaryPage.getDictionarySize()]; DoublePlainValuesReader doubleReader = new DoublePlainValuesReader(); <START> doubleReader.initFromPage(dictionaryPage.getDictionarySize(), dictionaryByteBuf, dictionaryByteBuf.position()); <END> for (int i = 0; i < doubleDictionaryContent.length; i++) { doubleDictionaryContent[i] = doubleReader.readDouble(); } }</code><technical_language>position() == 0</technical_language>

Target:
public PlainDoubleDictionary(DictionaryPage dictionaryPage) throws IOException { super(dictionaryPage); final ByteBuffer dictionaryByteBuf = dictionaryPage.getBytes().toByteBuffer(); doubleDictionaryContent = new double[dictionaryPage.getDictionarySize()]; DoublePlainValuesReader doubleReader = new DoublePlainValuesReader(); doubleReader.initFromPage(dictionaryPage.getDictionarySize(), dictionaryByteBuf, 0); for (int i = 0; i < doubleDictionaryContent.length; i++) { doubleDictionaryContent[i] = doubleReader.readDouble(); } }
Source:
<code>public <START> CollectedUpdateMetrics loadUrl(String <END> sparql) { return execute("uri", UPDATE_METRICS_RESPONSE, sparql); }</code><technical_language>do need this here? this simplify code if support this case UPDATE_COUNT_RESPONSE for this one</technical_language>

Target:
public Integer loadUrl(String sparql) { return execute("uri", UPDATE_COUNT_RESPONSE, sparql); }
Source:
<code>public void testAtsProgramInsertionBadProgramIdRestCall() throws Exception { <START> String result = <END> doRequestString("/ats/program/" + getSawTeam().getArtId() + "/insertion", HttpMethod.GET, null, javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertTrue(result.contains("SERVER_ERROR")); }</code><technical_language>getUuid instead of getArtId,</technical_language>

Target:
public void testAtsProgramInsertionBadProgramIdRestCall() throws Exception { String result = doRequestString("/ats/program/" + getSawTeam() + "/insertion", HttpMethod.GET, null, javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertTrue(result.contains("SERVER_ERROR")); }
Source:
<code>public static World readWorld(GlowServer server, CompoundTag compound) { <START> final World[] world = {null}; <END> compound.readUuid("WorldUUIDMost", "WorldUUIDLeast", uuid -> world[0] = server.getWorld(uuid)); if (world[0] == null) { compound.readString("World", name -> world[0] = server.getWorld(name)); } if (world[0] == null) { compound.readInt("Dimension", dim -> { for (World serverWorld : server.getWorlds()) { if (serverWorld.getEnvironment().getId() == dim) { world[0] = serverWorld; break; } } }); } return world[0]; }</code><technical_language>Chaining able done here, if messy though</technical_language>

Target:
public static World readWorld(GlowServer server, CompoundTag compound) { World world = compound .tryGetUuid("WorldUUIDMost", "WorldUUIDLeast") .map(server::getWorld) .orElseGet(() -> compound.tryGetString("World") .map(server::getWorld) .orElse(null)); if (world == null) { world = compound .tryGetInt("Dimension") .map(World.Environment::getEnvironment) .flatMap(env -> server.getWorlds().stream() .filter(serverWorld -> env == serverWorld.getEnvironment()) .findFirst()) .orElse(null); } return world; }
Source:
<code>private LockManager getLockManager() { try { return (LockManager) new InitialContext().lookup("java:global/engine/bll/LockManager"); } catch (NamingException e) { return <START> null; <END> } }</code><technical_language>blow up. Rethrow it, get instance. Lets obfuscate this</technical_language>

Target:
private LockManager getLockManager() { try { return (LockManager) new InitialContext().lookup("java:global/engine/bll/LockManager"); } catch (NamingException e) { throw new RuntimeException("Could not find LockManager via JNDI lookup", e); } }
Source:
<code>public void testGetBucketLocation() { <START> assertEquals("us-west-1", s3.getBucketLocation(EXPECTED_BUCKET_NAME)); <END> }</code><technical_language>While in neighborhood... a constant instead of this magic string</technical_language>

Target:
public void testGetBucketLocation() { assertEquals(Regions.US_WEST_1.getName(), s3.getBucketLocation(EXPECTED_BUCKET_NAME)); }
Source:
<code>public ActivityCalendar convertTo(final com.alliander.osgp.dto.valueobjects.smartmetering.ActivityCalendar source, final Type<ActivityCalendar> destinationType) { if (source == null) { return null; } final ActivityCalendar activityCalendar = new ActivityCalendar(); <START> <END> return activityCalendar; }</code><technical_language>Is need for a more meaningful mapping DTO object domain object</technical_language>

Target:
public ActivityCalendar convertTo(final com.alliander.osgp.dto.valueobjects.smartmetering.ActivityCalendar source, final Type<ActivityCalendar> destinationType) { throw new IllegalStateException("convertTo is not supported"); }
Source:
<code>protected void pushLiveInstancedata() throws AmazonClientException { <START> Instance inst = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); <END> if (inst != null && tags != null && !tags.isEmpty()) { HashSet<Tag> instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); } List<String> resources = getResourcesToTag(inst); CreateTagsRequest tagRequest = new CreateTagsRequest(); tagRequest.withResources(resources).setTags(instTags); getCloud().connect().createTags(tagRequest); } }</code><technical_language>need propagate handle InterruptedException elsewhere</technical_language>

Target:
protected void pushLiveInstancedata() throws AmazonClientException { Instance inst = null; try { inst = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); } catch (InterruptedException e) { LOGGER.fine("InterruptedException while get " + getInstanceId() + " Exception: " + e); } if (inst != null && tags != null && !tags.isEmpty()) { HashSet<Tag> instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); } List<String> resources = getResourcesToTag(inst); CreateTagsRequest tagRequest = new CreateTagsRequest(); tagRequest.withResources(resources).setTags(instTags); getCloud().connect().createTags(tagRequest); } }
Source:
<code>public MinecraftVersion getMinecraftVersion() { MinecraftVersion mcvToReturn; ServerStatusResponse.MinecraftProtocolVersionIdentifier protocolVersionInfo = MinecraftServer.getServer().getServerStatusResponse().getProtocolVersionInfo(); String name = protocolVersionInfo.getName(); int protocolVersion = protocolVersionInfo.getProtocol(); double numberVersion = Double.valueOf(name); <START> if (numberVersion < 1.7) { <END> if (numberVersion >= 1.6) mcvToReturn = SpongeLegacyMinecraftVersion.V1_6; else if (numberVersion >= 1.4 && numberVersion <= 1.5) mcvToReturn = SpongeLegacyMinecraftVersion.V1_5; else mcvToReturn = SpongeLegacyMinecraftVersion.V1_3; } else { mcvToReturn = new SpongeMinecraftVersion(name, protocolVersion); } return mcvToReturn; }</code><technical_language>implementation support legacy is need check for 1.7 under</technical_language>

Target:
public MinecraftVersion getMinecraftVersion() { return (MinecraftVersion) MinecraftServer.getServer().getServerStatusResponse().getProtocolVersionInfo(); }
Source:
<code>public void raiseAlert(Alert a) throws AlertingException { if (!mailProps.containsKey("mail.smtp.host")) { log.error("No SMTP host specified in the mail.properties configuration file. Cannot send email."); throw new AlertingException("No SMTP host specified in the mail.properties configuration file. Cannot send email."); } else { String from = mailProps.getProperty("mail.from"); <START> if (!isStringEmptyOrNull(from)) { <END> from = "miso@your.miso.server"; } String to = a.getAlertUser().getEmail(); String subject = "MISO ALERT: " + a.getAlertTitle(); String text = "Hello " + a.getAlertUser().getFullName() + ",\n\nMISO would like to tell you about something:\n\n" + a.getAlertTitle() + " (" + a.getAlertDate() + ")" + "\n\n" + a.getAlertText(); try { EmailUtils.send(to, from, subject, text, mailProps); } catch (MessagingException e) { log.error("Cannot send email to alert recipients", e); throw new AlertingException("Cannot send email to alert recipients", e); } } }</code><technical_language>This is different! this checking if string is null (as removed line). This change set address miso@your.miso.server long null. :confounded:</technical_language>

Target:
public void raiseAlert(Alert a) throws AlertingException { if (!mailProps.containsKey("mail.smtp.host")) { log.error("No SMTP host specified in the mail.properties configuration file. Cannot send email."); throw new AlertingException("No SMTP host specified in the mail.properties configuration file. Cannot send email."); } else { String from = mailProps.getProperty("mail.from", "miso@your.miso.server"); String to = a.getAlertUser().getEmail(); String subject = "MISO ALERT: " + a.getAlertTitle(); String text = "Hello " + a.getAlertUser().getFullName() + ",\n\nMISO would like to tell you about something:\n\n" + a.getAlertTitle() + " (" + a.getAlertDate() + ")" + "\n\n" + a.getAlertText(); try { EmailUtils.send(to, from, subject, text, mailProps); } catch (MessagingException e) { log.error("Cannot send email to alert recipients", e); throw new AlertingException("Cannot send email to alert recipients", e); } } }
Source:
<code><START> public static Object unmarshall(ByteBuffer payload) { <END> try { return new ObjectInputStream(new ByteBufferInputStream(payload)).readObject(); } catch (IOException ex) { throw new IllegalArgumentException(ex); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException(ex); } }</code><technical_language>This method is anywhere. This class findbugs failures</technical_language>

Target:
public static Object unmarshall(ByteBuffer payload) { ObjectInputStream objectInputStream = null; try { objectInputStream = new ObjectInputStream(new ByteBufferInputStream(payload)); return objectInputStream.readObject(); } catch (IOException ex) { throw new IllegalArgumentException(ex); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException(ex); } finally { closeSilently(objectInputStream); } }
Source:
<code><START> public static FtRemote secure(final Take take) throws IOException { <END> final ServerSocket skt = SSLServerSocketFactory.getDefault() .createServerSocket(0); return new FtRemote( new FtSecure(new BkBasic(take), skt), skt, true ); }</code><technical_language>@bdragan public</technical_language>

Target:
private static FtRemote secure(final Take take) throws IOException { final ServerSocket skt = SSLServerSocketFactory.getDefault() .createServerSocket(0); return new FtRemote( new FtSecure(new BkBasic(take), skt), skt, true ); }
Source:
<code>public synchronized void checkAssignFrom(String nodeIdentifier) { int currentNodeCount = nodeSupplier.getWorkerNodes().size(); if (currentNodeCount < minimumNodeCount) { <START> throw new PrestoException(RAPTOR_NOT_ENOUGH_NODES, format("Too many nodes down (required: %s, current: %s)", minimumNodeCount, currentNodeCount)); <END> } if (offlineNodes.contains(nodeIdentifier)) { return; } long now = ticker.read(); long start = delayedNodes.computeIfAbsent(nodeIdentifier, key -> now); Duration delay = new Duration(now - start, NANOSECONDS); if (delay.compareTo(reassignmentDelay) < 0) { throw new PrestoException(RAPTOR_REASSIGNMENT_DELAY, format( "Reassignment delay is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit())); } if (lastOfflined.isPresent()) { delay = new Duration(now - lastOfflined.getAsLong(), NANOSECONDS); if (delay.compareTo(reassignmentInterval) < 0) { throw new PrestoException(RAPTOR_REASSIGNMENT_THROTTLE, format( "Reassignment throttle is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit())); } } delayedNodes.remove(nodeIdentifier); offlineNodes.add(nodeIdentifier); lastOfflined = OptionalLong.of(now); }</code><technical_language>is specific - I confidently. I recommend 'Not enough nodes (required: %s, current: %s)'</technical_language>

Target:
public synchronized void checkAssignFrom(String nodeIdentifier) { int currentNodeCount = nodeSupplier.getWorkerNodes().size(); if (currentNodeCount < minimumNodeCount) { throw new PrestoException(RAPTOR_NOT_ENOUGH_NODES, format("Not enough nodes available (required: %s, current: %s)", minimumNodeCount, currentNodeCount)); } if (offlineNodes.contains(nodeIdentifier)) { return; } long now = ticker.read(); long start = delayedNodes.computeIfAbsent(nodeIdentifier, key -> now); Duration delay = new Duration(now - start, NANOSECONDS); if (delay.compareTo(reassignmentDelay) < 0) { throw new PrestoException(RAPTOR_REASSIGNMENT_DELAY, format( "Reassignment delay is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit())); } if (lastOfflined.isPresent()) { delay = new Duration(now - lastOfflined.getAsLong(), NANOSECONDS); if (delay.compareTo(reassignmentInterval) < 0) { throw new PrestoException(RAPTOR_REASSIGNMENT_THROTTLE, format( "Reassignment throttle is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit())); } } delayedNodes.remove(nodeIdentifier); offlineNodes.add(nodeIdentifier); lastOfflined = OptionalLong.of(now); }
Source:
<code>public TextArea createWidget() { final TextArea textArea = GWT.create(TextArea.class); textArea.addKeyDownHandler(keyDownEvent -> { final int keyCode = keyDownEvent.getNativeKeyCode(); <START> if (keyCode == KeyCodes.KEY_TAB) { <END> destroyResources(); gridPanel.setFocus(true); keyDownEvent.preventDefault(); } keyDownEvent.stopPropagation(); }); textArea.addMouseDownHandler(DomEvent::stopPropagation); return textArea; }</code><technical_language>@jomarko A couple of question: 1) ticket description TAB ESC managed (in way) I do here: is ESC managed in way? 2) is this kind of interaction specific ot ScenarioSImulation? Is for other grid editor? If behavior component, create a builder/getter else (some abstract/parent class) avoid duplicate this snippet</technical_language>

Target:
public TextArea createWidget() { final TextArea textArea = GWT.create(TextArea.class); textArea.addMouseDownHandler(DomEvent::stopPropagation); return textArea; }
Source:
<code>public void readEmptyMetadataInOtherTransaction() { String testValue = "testValue"; String testKey = "test"; <START> GraphDatabaseFacade localGraph = neo.getLocalGraph(); <END> try ( Transaction transaction = localGraph.beginTx() ) { localGraph.execute( "CALL dbms.setTXMetaData", map( "data", map( testKey, testValue ) ) ); transaction.success(); } try ( Transaction ignored = localGraph.beginTx() ) { Map<String,Object> metadata = (Map<String,Object>) localGraph.execute( "CALL dbms.getTXMetaData " ).next().get( "metadata" ); assertNull( metadata.get( testKey ) ); } }</code><technical_language>need get localGraph create separate transactions here. Perhaps: assertEmpty( writeSubject, "CALL dbms.setTXMetaData( { "+testKey+":"+testValue+" } )" ); assertSuccess( writeSubject, "CALL dbms.getTXMetaData()", r -> {...} );</technical_language>

Target:
public void readEmptyMetadataInOtherTransaction() { String testValue = "testValue"; String testKey = "test"; assertEmpty( writeSubject, "CALL dbms.setTXMetaData({" + testKey + ":'" + testValue + "'})" ); assertSuccess( writeSubject, "CALL dbms.getTXMetaData", mapResourceIterator -> { Map<String,Object> metadata = mapResourceIterator.next(); assertNull( metadata.get( testKey ) ); mapResourceIterator.close(); } ); }
Source:
<code>private boolean isExpired(long expirationTimeInMs, long referenceTimeInMs) { <START> return expirationTimeInMs < referenceTimeInMs && expirationTimeInMs != Utils.Infinite_Time; <END> }</code><technical_language>flip order of checks - more intuitive IMO. "time is valid is than" "time is valid"</technical_language>

Target:
private boolean isExpired(long expirationTimeInMs, long referenceTimeInMs) { return expirationTimeInMs != Utils.Infinite_Time && expirationTimeInMs < referenceTimeInMs; }
Source:
<code>private String buildLargeString(int sizeInMB) { char[] filler = new char[sizeInMB * 1024 * 1024]; <START> for (int i = 0; i < filler.length; i++) { <END> filler[i] = '0'; } return new String(filler); }</code><technical_language>Arrays.fill(filler, '0');</technical_language>

Target:
private String buildLargeString(int sizeInMB) { char[] filler = new char[sizeInMB * 1024 * 1024]; Arrays.fill(filler, '0'); return new String(filler); }
Source:
<code>public PoolDTO createPool(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "pool", required = true) PoolDTO inputPoolDTO) { log.info("Creating custom pool for owner {}: {}", ownerKey, inputPoolDTO); Pool pool = new Pool(); Owner owner = findOwnerByKey(ownerKey); pool.setOwner(owner); this.populateEntity(pool, inputPoolDTO); pool.setContractNumber(inputPoolDTO.getContractNumber()); pool.setOrderNumber(inputPoolDTO.getOrderNumber()); pool.setAccountNumber(inputPoolDTO.getAccountNumber()); pool.setUpstreamPoolId(inputPoolDTO.getUpstreamPoolId()); pool.setSubscriptionSubKey(inputPoolDTO.getSubscriptionSubKey()); pool.setSubscriptionId(inputPoolDTO.getSubscriptionId()); <START> pool.setLocked(false); <END> if (inputPoolDTO.getProductId() == null || inputPoolDTO.getProductId().isEmpty()) { throw new BadRequestException(i18n.tr("Pool product ID not specified")); } pool.setProduct(findProduct(pool.getOwner(), inputPoolDTO.getProductId())); if (inputPoolDTO.getDerivedProductId() != null) { pool.setDerivedProduct(findProduct(pool.getOwner(), inputPoolDTO.getDerivedProductId())); } if (inputPoolDTO.getSourceEntitlement() != null) { pool.setSourceEntitlement(findEntitlement(inputPoolDTO.getSourceEntitlement().getId())); } pool = poolManager.createAndEnrichPools(pool); return this.translator.translate(pool, PoolDTO.class); }</code><technical_language>default is false, this basically no-op in majority of cases. do is, instead, set locked flag true refresh (which covers manifest import), non-custom pools coming in anyway</technical_language>

Target:
public PoolDTO createPool(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "pool", required = true) PoolDTO inputPoolDTO) { log.info("Creating custom pool for owner {}: {}", ownerKey, inputPoolDTO); Pool pool = new Pool(); Owner owner = findOwnerByKey(ownerKey); pool.setOwner(owner); this.populateEntity(pool, inputPoolDTO); pool.setContractNumber(inputPoolDTO.getContractNumber()); pool.setOrderNumber(inputPoolDTO.getOrderNumber()); pool.setAccountNumber(inputPoolDTO.getAccountNumber()); pool.setUpstreamPoolId(inputPoolDTO.getUpstreamPoolId()); pool.setSubscriptionSubKey(inputPoolDTO.getSubscriptionSubKey()); pool.setSubscriptionId(inputPoolDTO.getSubscriptionId()); if (inputPoolDTO.getProductId() == null || inputPoolDTO.getProductId().isEmpty()) { throw new BadRequestException(i18n.tr("Pool product ID not specified")); } pool.setProduct(findProduct(pool.getOwner(), inputPoolDTO.getProductId())); if (inputPoolDTO.getDerivedProductId() != null) { pool.setDerivedProduct(findProduct(pool.getOwner(), inputPoolDTO.getDerivedProductId())); } if (inputPoolDTO.getSourceEntitlement() != null) { pool.setSourceEntitlement(findEntitlement(inputPoolDTO.getSourceEntitlement().getId())); } pool = poolManager.createAndEnrichPools(pool); return this.translator.translate(pool, PoolDTO.class); }
Source:
<code>private void recoverFromTranslogInternal(TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo) throws IOException { final int opsRecovered; final long localCheckpoint = getProcessedLocalCheckpoint(); if (localCheckpoint < recoverUpToSeqNo) { try (Translog.Snapshot snapshot = translog.newSnapshot(localCheckpoint + 1, recoverUpToSeqNo)) { opsRecovered = translogRecoveryRunner.run(this, snapshot); } catch (Exception e) { throw new EngineException(shardId, "failed to recover from translog", e); } } else { opsRecovered = 0; } assert pendingTranslogRecovery.get() : "translogRecovery is not pending but should be"; pendingTranslogRecovery.set(false); logger.trace(() -> new ParameterizedMessage( "flushing post recovery from translog: ops recovered [{}], current translog generation [{}]", opsRecovered, translog.currentFileGeneration())); flush(false, true); <START> if (opsRecovered > 0) { <END> refresh("translog_recovery"); } translog.trimUnreferencedReaders(); }</code><technical_language>refresh in flush method is internal refresh, external one. I external refresh is necessary (we do relevant refresh in IndexShard.postRecovery, is called moving shard started). if remove refresh call here</technical_language>

Target:
private void recoverFromTranslogInternal(TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo) throws IOException { final int opsRecovered; final long localCheckpoint = getProcessedLocalCheckpoint(); if (localCheckpoint < recoverUpToSeqNo) { try (Translog.Snapshot snapshot = translog.newSnapshot(localCheckpoint + 1, recoverUpToSeqNo)) { opsRecovered = translogRecoveryRunner.run(this, snapshot); } catch (Exception e) { throw new EngineException(shardId, "failed to recover from translog", e); } } else { opsRecovered = 0; } assert pendingTranslogRecovery.get() : "translogRecovery is not pending but should be"; pendingTranslogRecovery.set(false); logger.trace(() -> new ParameterizedMessage( "flushing post recovery from translog: ops recovered [{}], current translog generation [{}]", opsRecovered, translog.currentFileGeneration())); flush(false, true); translog.trimUnreferencedReaders(); }
Source:
<code>public void doesNotReuseResiduesIfNotNeeded() { <START> givenGeneratorHasModulus(3); <END> requestResiduesAndAssertBalanced(3); }</code><technical_language>This sounds assertion. rename setupGeneratorWithModulus</technical_language>

Target:
public void doesNotReuseResiduesIfNotNeeded() { setupGeneratorWithModulus(3); requestResiduesAndAssertEachUsedOnce(3); }