auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public MatchableDataTable getDataTable() throws SQLException { if (queryOrSymbol == null) { queryOrSymbol = args[0]; } if (isSymbolGetter(queryOrSymbol)) { return new MatchableDataTable(getFromSymbol()); } Log.log("Query: '%s'", queryOrSymbol); <START> try (DbStatement st = <END> dbEnvironment.createStatementWithBoundFixtureSymbols( FitNesseTestHost.getInstance(), queryOrSymbol)) { return new MatchableDataTable(new DataTable(st.executeQuery())); } }</code><technical_language>Worth expanding st</technical_language>

Target:
public MatchableDataTable getDataTable() throws SQLException { if (queryOrSymbol == null) { queryOrSymbol = args[0]; } if (isSymbolGetter(queryOrSymbol)) { return new MatchableDataTable(getFromSymbol()); } Log.log("Query: '%s'", queryOrSymbol); return new MatchableDataTable(dbEnvironment.getQueryTable(queryOrSymbol)); }
Source:
<code>public String render(AnalyzerResultFuture<? extends AnalyzerResult> renderable) { final StringBuilder resultString = new StringBuilder(); try { AnalyzerResult result = renderable.get(); Renderer<? super AnalyzerResult, ? extends CharSequence> renderer = _rendererFactory.getRenderer( result, TextRenderingFormat.class); if (renderer != null) { logger.debug("renderer.render({})", result); final CharSequence component = renderer.render(result); resultString.append(component); return resultString.toString(); } else { final String message = "No renderer found for result type " + result.getClass().getName(); logger.error(message); throw new IllegalStateException(message); } } catch (RuntimeException error) { String message = "Unable to fetch result"; logger.error(message, error); <START> throw new IllegalStateException(message); <END> } }</code><technical_language>Add error a also</technical_language>

Target:
public String render(AnalyzerResultFuture<? extends AnalyzerResult> renderable) { final StringBuilder resultString = new StringBuilder(); try { AnalyzerResult result = renderable.get(); Renderer<? super AnalyzerResult, ? extends CharSequence> renderer = _rendererFactory.getRenderer( result, TextRenderingFormat.class); if (renderer != null) { logger.debug("renderer.render({})", result); final CharSequence component = renderer.render(result); resultString.append(component); return resultString.toString(); } else { final String message = "No renderer found for result type " + result.getClass().getName(); logger.error(message); throw new IllegalStateException(message); } } catch (RuntimeException error) { String message = "Unable to fetch result"; logger.error(message, error); throw new IllegalStateException(message, error); } }
Source:
<code>private static final int findLocalizedModifier(String modifierName) { <START> if (modifierName == null) <END> return 0; if (modifierName.equalsIgnoreCase(Action.findModifierString(SWT.CTRL))) return SWT.CTRL; if (modifierName.equalsIgnoreCase(Action.findModifierString(SWT.SHIFT))) return SWT.SHIFT; if (modifierName.equalsIgnoreCase(Action.findModifierString(SWT.ALT))) return SWT.ALT; if (modifierName .equalsIgnoreCase(Action.findModifierString(SWT.COMMAND))) return SWT.COMMAND; return 0; }</code><technical_language>3.7 braces single line blocks <LINK_0></technical_language>

Target:
private static final int findLocalizedModifier(String modifierName) { if (modifierName == null) { return 0; } if (modifierName .equalsIgnoreCase(Action.findModifierString(SWT.CTRL))) { return SWT.CTRL; } if (modifierName .equalsIgnoreCase(Action.findModifierString(SWT.SHIFT))) { return SWT.SHIFT; } if (modifierName.equalsIgnoreCase(Action.findModifierString(SWT.ALT))) { return SWT.ALT; } if (modifierName .equalsIgnoreCase(Action.findModifierString(SWT.COMMAND))) { return SWT.COMMAND; } return 0; }
Source:
<code>public final synchronized int read(ByteBuffer dst) throws IOException { <START> int read = read(dst, position); <END> position += read; return read; }</code><technical_language>read() lock? need protect usage of "position" field (or atomic instead) actual read() / write() concurrency care of underlying FileChannel</technical_language>

Target:
public final synchronized int read(ByteBuffer dst) throws IOException { int read = read(dst, position); if (read > 0) { position += read; } return read; }
Source:
<code>public void init() { Font.loadFont(FafClientApplication.class.getResourceAsStream("/font/dfc-icons.ttf"), 10); JavaFxUtil.fixTooltipDuration(); CountDownLatch runAndWaitLatch = new CountDownLatch(1); Platform.runLater(() -> { applicationContext = new SpringApplicationBuilder(FafClientApplication.class) .profiles(getAdditionalProfiles()) .bannerMode(Mode.OFF) .run(getParameters().getRaw().toArray(new String[0])); runAndWaitLatch.countDown(); }); try { runAndWaitLatch.await(); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>re-throw log, printStacktrace()</technical_language>

Target:
public void init() { Font.loadFont(FafClientApplication.class.getResourceAsStream("/font/dfc-icons.ttf"), 10); JavaFxUtil.fixTooltipDuration(); CountDownLatch runAndWaitLatch = new CountDownLatch(1); Platform.runLater(() -> { applicationContext = new SpringApplicationBuilder(FafClientApplication.class) .profiles(getAdditionalProfiles()) .bannerMode(Mode.OFF) .run(getParameters().getRaw().toArray(new String[0])); runAndWaitLatch.countDown(); }); noCatch((NoCatchRunnable) runAndWaitLatch::await); }
Source:
<code>public String execute(final TransactionContext context) { <START> validateCodeSystem(context); <END> final CodeSystem codeSystem = createCodeSystem(context); context.add(codeSystem); return codeSystem.getShortName(); }</code><technical_language>Rename validateCodeSystem checkCodeSystem</technical_language>

Target:
public String execute(final TransactionContext context) { checkCodeSystem(context); final CodeSystem codeSystem = createCodeSystem(context); context.add(codeSystem); return codeSystem.getShortName(); }
Source:
<code><START> public long getEntityOwnerId() { <END> return Account.ACCOUNT_ID_SYSTEM; }</code><technical_language>above, get caller user/account current context</technical_language>

Target:
public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getAccountId(); }
Source:
<code>KQueueDomainTransportFactory() { <START> try { <END> Class.forName("io.netty.channel.kqueue.KQueue"); } catch (ClassNotFoundException e) { throw new IllegalStateException("The kqueue transport is not available"); } if (!KQueue.isAvailable()) { throw new IllegalStateException("The kqueue transport is not supported"); } }</code><technical_language>Duplicated code, try share/reuse</technical_language>

Target:
KQueueDomainTransportFactory() { ReflectionUtil.loadKQueueClass(); }
Source:
<code>public static Module module() { return new CacheModule() { @Override protected void configure() { persist(WebSessionManager.CACHE_NAME, String.class, Val.class) .maximumWeight(1024) .expireAfterWrite(CacheBasedWebSession.MAX_AGE_MINUTES, MINUTES) ; install(new FactoryModuleBuilder() .build(WebSessionManagerFactory.class)); <START> DynamicItem.itemOf(binder(), WebSession.class, true); <END> DynamicItem.bind(binder(), WebSession.class) .to(H2CacheBasedWebSession.class) .in(RequestScoped.class); } }; }</code><technical_language>I boolean replaceable confusing read this line. important binding swapped unclear that</technical_language>

Target:
public static Module module() { return new CacheModule() { @Override protected void configure() { persist(WebSessionManager.CACHE_NAME, String.class, Val.class) .maximumWeight(1024) .expireAfterWrite(CacheBasedWebSession.MAX_AGE_MINUTES, MINUTES) ; install(new FactoryModuleBuilder() .build(WebSessionManagerFactory.class)); DynamicItem.itemOf(binder(), WebSession.class); DynamicItem.bind(binder(), WebSession.class) .to(H2CacheBasedWebSession.class) .in(RequestScoped.class); } }; }
Source:
<code>public List<String> getBuildCauses() { List<ModelNode> causes = get(TRIGGERED_BY).asList(); <START> ArrayList<String> ret = new ArrayList<String>(); <END> for (ModelNode cause : causes) { ret.add(cause.asString()); } return ret; }</code><technical_language>new ArrayList<>();</technical_language>

Target:
public List<String> getBuildCauses() { List<ModelNode> causes = get(TRIGGERED_BY).asList(); ArrayList<String> ret = new ArrayList<>(); for (ModelNode cause : causes) { ret.add(cause.asString()); } return ret; }
Source:
<code>public ArrayList<Attachment> createAttachmentList() { ArrayList<Attachment> result = new ArrayList<>(); for (Attachment attachment : attachments.values()) { if(account.getResizeEnabled() && !attachment.overrideDefault && Utility.isImage(context, attachment.uri)){ float factor = 1.0f / account.getResizeFactor(); String newFilename = ""; long size = 0; if(factor != 1.0f) { newFilename = Utility.getResizedImageFile(context, attachment.uri, factor); <START> size = (new File(newFilename)).length(); <END> } if(!newFilename.equals("")) { Attachment newAttachment = attachment.createResizedCopy(newFilename, size); result.add(newAttachment); } else { result.add(attachment); } } else if(attachment.overrideDefault && Utility.isImage(context, attachment.uri)){ float factor = attachment.resizeFactor; String newFilename = ""; long size = 0; if(factor != 1.0f) { newFilename = Utility.getResizedImageFile(context, attachment.uri, factor); size = (new File(newFilename)).length(); } if(!newFilename.equals("")) { Attachment newAttachment = attachment.createResizedCopy(newFilename, size); result.add(newAttachment); } else { result.add(attachment); } } else { result.add(attachment); } } return result; }</code><technical_language>brackets redundant</technical_language>

Target:
public ArrayList<Attachment> createAttachmentList() { ArrayList<Attachment> result = new ArrayList<>(); for (Attachment attachment : attachments.values()) { if (account.getImageResizeEnabled() && !attachment.overrideDefault && Utility.isImage(context, attachment.uri)) { float factor = 1.0f / account.getResizeFactor(); String newFilename = Utility.getResizedImageFile(context, attachment.uri, factor); long size; if (factor != 1.0f && !newFilename.equals("")) { size = (new File(newFilename)).length(); Attachment newAttachment = attachment.createResizedCopy(newFilename, size); result.add(newAttachment); } else { result.add(attachment); } } else if (attachment.overrideDefault && Utility.isImage(context, attachment.uri)) { float factor = attachment.resizeFactor; String newFilename = Utility.getResizedImageFile(context, attachment.uri, factor); long size; if (factor != 1.0f && !newFilename.equals("")) { size = (new File(newFilename)).length(); Attachment newAttachment = attachment.createResizedCopy(newFilename, size); result.add(newAttachment); } else { result.add(attachment); } } else { result.add(attachment); } } return result; }
Source:
<code>protected CommandResult doUndoWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { <START> return null; <END> }</code><technical_language>raise exception "not implemented"</technical_language>

Target:
protected CommandResult doUndoWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { throw new ExecutionException("not implemented"); }
Source:
<code>private List<AccountInfo> suggestAccount(VisibilityControl visibilityControl) throws OrmException { final String a = query; final String b = a + MAX_SUFFIX; <START> final LinkedHashMap<Account.Id, <END> AccountInfo> r = Maps.newLinkedHashMap(); for (final Account p : dbProvider.get().accounts() .suggestByFullName(a, b, limit)) { addSuggestion(r, p, new AccountInfo(p.getId()), visibilityControl); } if (r.size() < limit) { for (final Account p : dbProvider.get().accounts() .suggestByPreferredEmail(a, b, limit - r.size())) { addSuggestion(r, p, new AccountInfo(p.getId()), visibilityControl); } } if (r.size() < limit) { for (final AccountExternalId e : dbProvider.get().accountExternalIds() .suggestByEmailAddress(a, b, limit - r.size())) { if (!r.containsKey(e.getAccountId())) { final Account p = accountCache.get(e.getAccountId()).getAccount(); final AccountInfo info = new AccountInfo(p.getId()); addSuggestion(r, p, info, visibilityControl); } } } return new ArrayList<AccountInfo>(r.values()); }</code><technical_language>final is unnecessary</technical_language>

Target:
private List<AccountInfo> suggestAccount(VisibilityControl visibilityControl) throws OrmException { String a = query; String b = a + MAX_SUFFIX; LinkedHashMap<Account.Id, AccountInfo> r = Maps.newLinkedHashMap(); for (Account p : dbProvider.get().accounts() .suggestByFullName(a, b, limit)) { addSuggestion(r, p, new AccountInfo(p.getId()), visibilityControl); } if (r.size() < limit) { for (Account p : dbProvider.get().accounts() .suggestByPreferredEmail(a, b, limit - r.size())) { addSuggestion(r, p, new AccountInfo(p.getId()), visibilityControl); } } if (r.size() < limit) { for (AccountExternalId e : dbProvider.get().accountExternalIds() .suggestByEmailAddress(a, b, limit - r.size())) { if (!r.containsKey(e.getAccountId())) { Account p = accountCache.get(e.getAccountId()).getAccount(); AccountInfo info = new AccountInfo(p.getId()); addSuggestion(r, p, info, visibilityControl); } } } return Lists.newArrayList(r.values()); }
Source:
<code>private synchronized JSONObject _request(Method m, String url, String json, List<String> hostsArray, int connectTimeout, int readTimeout) throws AlgoliaException { String cacheKey = null; if (isCacheEnabled) { cacheKey = String.format("%s:%s(%s)", m, url, json); final JSONObject value = cache.get(cacheKey); if (value != null) { return value; } } try { final JSONObject result = _getJSONObject(_requestRaw(m, url, json, hostsArray, connectTimeout, readTimeout)); if (isCacheEnabled) { <START> cache.put(cacheKey, result); <END> } return result; } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new AlgoliaException("UTF-8 decode error:" + e.getMessage()); } }</code><technical_language>I I store string (raw) version of JSON answer regenerate JSONObject time ensure returning a new object. a bunch of issues in JavaScript beginning soon JSON object is modified (can happen display time, for convenience purpose) a mess debug</technical_language>

Target:
private synchronized JSONObject _request(Method m, String url, String json, List<String> hostsArray, int connectTimeout, int readTimeout) throws AlgoliaException { String cacheKey = null; String jsonStr = null; if (isCacheEnabled) { cacheKey = String.format("%s:%s(%s)", m, url, json); jsonStr = cache.get(cacheKey); } try { if (jsonStr == null) { final byte[] requestRaw = _requestRaw(m, url, json, hostsArray, connectTimeout, readTimeout); jsonStr = new String(requestRaw, "UTF-8"); if (isCacheEnabled) { cache.put(cacheKey, jsonStr); } } return new JSONObject(jsonStr); } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new AlgoliaException("UTF-8 decode error:" + e.getMessage()); } }
Source:
<code>public OAuth2UserRecord getUserRecord(String code, @NotNull OAuth20Service service) throws IOException, OAuth2Exception, InterruptedException, ExecutionException { OAuth2AccessToken accessToken = service.getAccessToken(code); <START> final String userEndpoint = getUserEndpoint(accessToken); <END> if ( ( accessToken.getScope() != null && ! getScope().stream().allMatch(accessToken.getScope()::contains) ) || ( accessToken.getScope() == null && ! getSpacedScope().isEmpty() ) ) { throw new OAuth2Exception(200, BundleUtil.getStringFromBundle("auth.providers.insufficientScope", Arrays.asList(this.getTitle())), ""); } OAuthRequest request = new OAuthRequest(Verb.GET, getUserEndpoint(accessToken)); request.setCharset("UTF-8"); if (id.equals("microsoft")) { request.addHeader("Accept", "application/json"); } service.signRequest(accessToken, request); Response response = service.execute(request); int responseCode = response.getCode(); String body = response.getBody(); logger.log(Level.FINE, "In requestUserRecord. Body: {0}", body); if ( responseCode == 200 && body != null ) { return getUserRecord(body, accessToken, service); } else { throw new OAuth2Exception(responseCode, body, BundleUtil.getStringFromBundle("auth.providers.exception.userinfo", Arrays.asList(this.getTitle()))); } }</code><technical_language>This userEndpoint variable I assume deleted</technical_language>

Target:
public OAuth2UserRecord getUserRecord(String code, @NotNull OAuth20Service service) throws IOException, OAuth2Exception, InterruptedException, ExecutionException { OAuth2AccessToken accessToken = service.getAccessToken(code); if ( ( accessToken.getScope() != null && ! getScope().stream().allMatch(accessToken.getScope()::contains) ) || ( accessToken.getScope() == null && ! getSpacedScope().isEmpty() ) ) { throw new OAuth2Exception(200, BundleUtil.getStringFromBundle("auth.providers.insufficientScope", Arrays.asList(this.getTitle())), ""); } OAuthRequest request = new OAuthRequest(Verb.GET, getUserEndpoint(accessToken)); request.setCharset("UTF-8"); if (id.equals("microsoft")) { request.addHeader("Accept", "application/json"); } service.signRequest(accessToken, request); Response response = service.execute(request); int responseCode = response.getCode(); String body = response.getBody(); logger.log(Level.FINE, "In requestUserRecord. Body: {0}", body); if ( responseCode == 200 && body != null ) { return getUserRecord(body, accessToken, service); } else { throw new OAuth2Exception(responseCode, body, BundleUtil.getStringFromBundle("auth.providers.exception.userinfo", Arrays.asList(this.getTitle()))); } }
Source:
<code>private String getKeyFromBackDoor(String courseId, String studentEmail) { String key = "[BACKDOOR_STATUS_FAILURE]"; while (key.startsWith("[BACKDOOR_STATUS_FAILURE]")) { key = BackDoor.getKeyForStudent(courseId, studentEmail); } return key; <START> } <END></code><technical_language>Retry is a bit risky. Limit a fixed number of tries. Also, a delay tries</technical_language>

Target:
private String getKeyFromBackDoor(String courseId, String studentEmail) { int NUMBER_OF_REMAINING_RETRIES = 10; String key = "[BACKDOOR_STATUS_FAILURE]"; while (key.startsWith("[BACKDOOR_STATUS_FAILURE]") && NUMBER_OF_REMAINING_RETRIES > 0) { key = BackDoor.getKeyForStudent(courseId, studentEmail); NUMBER_OF_REMAINING_RETRIES--; ThreadHelper.waitFor(100); } return key; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setFullScreenDialogClose(Activity.RESULT_CANCELED, true); final Intent intent = new Intent(this, org.sufficientlysecure.keychain.ui.ImportKeysActivity.class); new AlertDialog.Builder(this) .setTitle("Import key attempt") <START> .setMessage("You scanned a fingerprint with another app, please scan with Openkeychain directly to be safe" ) <END> .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startActivity(intent); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); }</code><technical_language>text in string resources translated</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startQrCodeCaptureActivity(); }
Source:
<code>public void onActivityCreated(@Nullable Bundle savedInstanceState) { if (savedInstanceState != null) { mInProgressMessageId = savedInstanceState.getInt(KEY_IN_PROGRESS_MESSAGE_ID, 0); mOldSitesIDs = savedInstanceState.getIntegerArrayList(KEY_OLD_SITES_IDS); } else { AnalyticsTracker.track(AnalyticsTracker.Stat.LOGIN_TWO_FACTOR_FORM_VIEWED); if (mService != null) { AnalyticsTracker.track(AnalyticsTracker.Stat.LOGIN_SOCIAL_2FA_NEEDED); <START> } <END> } super.onActivityCreated(savedInstanceState); }</code><technical_language>Is LOGIN_SOCIAL_2FA_NEEDED stat meant tracked two-factor authentication screen is shown a social login? If so, [LoginActivity.needs2faSocial](<LINK_0> [LoginActivity.needs2faSocialConnect](<LINK_1> methods locations for that. methods called Login2FaFragment is shown LoginGoogleFragment LoginEmailPasswordFragment (i.e. places two-factor authentication shown social login)</technical_language>

Target:
public void onActivityCreated(@Nullable Bundle savedInstanceState) { if (savedInstanceState != null) { mInProgressMessageId = savedInstanceState.getInt(KEY_IN_PROGRESS_MESSAGE_ID, 0); mOldSitesIDs = savedInstanceState.getIntegerArrayList(KEY_OLD_SITES_IDS); } else { AnalyticsTracker.track(AnalyticsTracker.Stat.LOGIN_TWO_FACTOR_FORM_VIEWED); } super.onActivityCreated(savedInstanceState); }
Source:
<code>public Blob run(Blob blob) throws IOException { String srcMT = blob.getMimeType(); String destMT = MimetypeRegistry.PDF_MIMETYPE; String extension = MimetypeRegistry.PDF_EXTENSION; Blob result = service.convertBlob(service.getConverterName(srcMT, destMT), new SimpleBlobHolder(blob), extension, destMT); <START> service.adjustBlobName(blob.getFilename(), result, extension, destMT); <END> return result; }</code><technical_language>need adjust blob name, done in convertBlob method. remove adjustBlobName ConfigurationService interface</technical_language>

Target:
public Blob run(Blob blob) throws IOException { return service.convertToMimeType(MimetypeRegistry.PDF_MIMETYPE, new SimpleBlobHolder(blob), Collections.emptyMap()).getBlob(); }
Source:
<code>protected Object readResolve() { projectUpdateLock = new ReentrantLock(); issueCache = makeIssueCache(); jiraSession = null; if (StringUtils.isNotBlank(credentialsId)) { <START> StandardUsernamePasswordCredentials credentials = CredentialsHelper.lookupSystemCredentials(credentialsId, url != null ? url.toExternalForm() : null); <END> setCredentials(credentials); } else if (userName != null && password != null) { StandardUsernamePasswordCredentials credentials = CredentialsHelper.migrateCredentials(userName, password.getPlainText(), url != null ? url.toExternalForm() : null); setCredentials(credentials); setCredentialsId(credentials.getId()); } return this; }</code><technical_language>move url null check lookupSystemCredentials</technical_language>

Target:
protected Object readResolve() { if (credentialsId == null && userName != null && password != null) { return new JiraSite(url, alternativeUrl, userName, password.getPlainText(), supportsWikiStyleComment, recordScmChanges, userPattern, updateJiraIssueForAllStatus, groupVisibility, roleVisibility, useHTTPAuth); } return new JiraSite(url, alternativeUrl, credentialsId, supportsWikiStyleComment, recordScmChanges, userPattern, updateJiraIssueForAllStatus, groupVisibility, roleVisibility, useHTTPAuth); }
Source:
<code>public ImmutableList<LocalDate> getUnadjustedDates() { ImmutableList.Builder<LocalDate> dates = ImmutableList.builder(); <START> dates.add(periods.get(0).getUnadjustedStartDate()); <END> for (SchedulePeriod period : periods) { dates.add(period.getUnadjustedEndDate()); } return dates.build(); }</code><technical_language>this is logic of getUnadjustedStartDate(), call</technical_language>

Target:
public ImmutableList<LocalDate> getUnadjustedDates() { ImmutableList.Builder<LocalDate> dates = ImmutableList.builder(); dates.add(getUnadjustedStartDate()); for (SchedulePeriod period : periods) { dates.add(period.getUnadjustedEndDate()); } return dates.build(); }
Source:
<code>public GenericItemBlockUsingDamageDescriptor(String name, String iconName) { <START> changeDefaultIcon(iconName); <END> this.name = name; }</code><technical_language>named "setDefaultIcon"</technical_language>

Target:
public GenericItemBlockUsingDamageDescriptor(String name, String iconName) { setDefaultIcon(iconName); this.name = name; }
Source:
<code>private Optional<VersionMessage> attemptHandshakeForVersionMessage() { Peer peer; try { peer = createLocalPeer(port); } catch (UnknownHostException ex) { log.error("Local bitcoin node handshake attempt unexpectedly threw: {}", ex); return Optional.empty(); } var originalNioClientLoggerLevel = silence(NioClient.class); var originalNioClientManagerLoggerLevel = silence(NioClientManager.class); NioClient client; <START> <END> try { log.info("Initiating attempt to connect to and handshake with a local " + "Bitcoin node (which may or may not be running) on port {}.", port); client = createClient(peer, port, CONNECTION_TIMEOUT); } catch (IOException ex) { log.error("Local bitcoin node handshake attempt unexpectedly threw: {}", ex); return Optional.empty(); } ListenableFuture<VersionMessage> peerVersionMessageFuture = getVersionMessage(peer); Optional<VersionMessage> optionalPeerVersionMessage; try { var peerVersionMessage = peerVersionMessageFuture.get(); optionalPeerVersionMessage = Optional.of(peerVersionMessage); } catch (ExecutionException | InterruptedException | CancellationException ex) { optionalPeerVersionMessage = Optional.empty(); } peer.close(); client.closeConnection(); restoreLoggerLevel(NioClient.class, originalNioClientLoggerLevel); restoreLoggerLevel(NioClientManager.class, originalNioClientManagerLoggerLevel); return optionalPeerVersionMessage; }</code><technical_language>Blank line</technical_language>

Target:
private Optional<VersionMessage> attemptHandshakeForVersionMessage() { Peer peer; try { peer = createLocalPeer(port); } catch (UnknownHostException ex) { log.error("Local bitcoin node handshake attempt was unexpectedly interrupted", ex); return Optional.empty(); } var originalNioClientLoggerLevel = silence(NioClient.class); var originalNioClientManagerLoggerLevel = silence(NioClientManager.class); NioClient client; try { log.info("Initiating attempt to connect to and handshake with a local " + "Bitcoin node (which may or may not be running) on port {}.", port); client = createClient(peer, port, CONNECTION_TIMEOUT); } catch (IOException ex) { log.error("Local bitcoin node handshake attempt was unexpectedly interrupted", ex); return Optional.empty(); } ListenableFuture<VersionMessage> peerVersionMessageFuture = getVersionMessage(peer); Optional<VersionMessage> optionalPeerVersionMessage; try { var peerVersionMessage = peerVersionMessageFuture.get(); optionalPeerVersionMessage = Optional.of(peerVersionMessage); } catch (ExecutionException | InterruptedException | CancellationException ex) { optionalPeerVersionMessage = Optional.empty(); } peer.close(); client.closeConnection(); restoreLoggerLevel(NioClient.class, originalNioClientLoggerLevel); restoreLoggerLevel(NioClientManager.class, originalNioClientManagerLoggerLevel); return optionalPeerVersionMessage; }
Source:
<code>public FileSystem getFileSystem() { <START> return fs; <END> }</code><technical_language>suggestion return fileSystem;</technical_language>

Target:
public FileSystem getFileSystem() { return fileSystem; }
Source:
<code>public OrcsBranch getBranchOps() { OrcsSession session = getSession(); LazyObject<ArtifactReadable> systemUser = new LazyObject<ArtifactReadable>() { @Override protected final FutureTask<ArtifactReadable> createLoaderTask() { Callable<ArtifactReadable> callable = new Callable<ArtifactReadable>() { @Override public ArtifactReadable call() throws Exception { return getQueryFactory().fromBranch(CoreBranches.COMMON).andIds(SystemUser.OseeSystem).getResults().getExactlyOne(); } }; return new FutureTask<ArtifactReadable>(callable); } }; <START> QueryFactory queryFactory = getQueryFactory(); <END> return new OrcsBranchImpl(logger, session, module.getBranchDataStore(), queryFactory, systemUser, getOrcsTypes()); }</code><technical_language>done here, remove file commit</technical_language>

Target:
public OrcsBranch getBranchOps() { OrcsSession session = getSession(); LazyObject<ArtifactReadable> systemUser = new LazyObject<ArtifactReadable>() { @Override protected final FutureTask<ArtifactReadable> createLoaderTask() { Callable<ArtifactReadable> callable = new Callable<ArtifactReadable>() { @SuppressWarnings("unchecked") @Override public ArtifactReadable call() throws Exception { return getQueryFactory().fromBranch(CoreBranches.COMMON).andIds(SystemUser.OseeSystem).getResults().getExactlyOne(); } }; return new FutureTask<ArtifactReadable>(callable); } }; QueryFactory queryFactory = getQueryFactory(); return new OrcsBranchImpl(logger, session, module.getBranchDataStore(), queryFactory, systemUser, getOrcsTypes()); }
Source:
<code>protected String getEffectiveEmulatedMachine() { <START> if (getVm().getCustomEmulatedMachine() != null) { <END> if (getVm().getClusterArch().getFamily() == ArchitectureType.ppc) { return findEmulatedMachineByPrefix(EMULATED_MACHINE_PREFIX_PPC); } else if (getVm().getCustomEmulatedMachine() == EmulatedMachine.i440fx_seabios) { return findEmulatedMachineByPrefix(EMULATED_MACHINE_PREFIX_I440); } else { return findEmulatedMachineByPrefix(EMULATED_MACHINE_PREFIX_Q35); } } String recentClusterDefault = (getVm().getClusterArch().getFamily() == ArchitectureType.ppc) ? findEmulatedMachineByPrefix(EMULATED_MACHINE_PREFIX_PPC) : findEmulatedMachineByPrefix(EMULATED_MACHINE_PREFIX_I440); if (getVm().getCustomCompatibilityVersion() == null) { return recentClusterDefault; } String bestMatch = findBestMatchForEmulatedMachine( recentClusterDefault, Config.getValue( ConfigValues.ClusterEmulatedMachines, getVm().getCustomCompatibilityVersion().getValue())); log.info("Emulated machine '{}' selected since Custom Compatibility Version is set for '{}'", bestMatch, getVm()); return bestMatch; }</code><technical_language>do like: findEmulatedMachineByChipset(getVm().getCustomEmulatedMachine().getChipset()) instead of if-else block a bit more future proof - add a new EmulatedMachines enum, work change</technical_language>

Target:
protected String getEffectiveEmulatedMachine() { if (getVm().getCustomEmulatedMachine() != null) { return findEmulatedMachineByPrefix(getVm().getCustomEmulatedMachine()); } String recentClusterDefault = (getVm().getClusterArch().getFamily() == ArchitectureType.ppc) ? findEmulatedMachineByPrefix(EmulatedMachine.pseries) : findEmulatedMachineByPrefix(EmulatedMachine.i440fx_seabios); if (getVm().getCustomCompatibilityVersion() == null) { return recentClusterDefault; } String bestMatch = findBestMatchForEmulatedMachine( recentClusterDefault, Config.getValue( ConfigValues.ClusterEmulatedMachines, getVm().getCustomCompatibilityVersion().getValue())); log.info("Emulated machine '{}' selected since Custom Compatibility Version is set for '{}'", bestMatch, getVm()); return bestMatch; }
Source:
<code><START> public void testMultiHighlightMessage() { <END> final Rectangle cellBounds = SWTBotUtils.getCellBounds(fTableBot.widget, ROW, 6); ImageHelper before = ImageHelper.getScreenGrab(cellBounds); Map<RGB, Integer> colorBefore = before.getHistogram(); fTableBot.click(0, 6); fBot.text().typeText("e\n", 100); fTableBot.select(4); ImageHelper after = ImageHelper.getScreenGrab(cellBounds); Map<RGB, Integer> colorAfter = after.getHistogram(); assertTrue(colorBefore.containsKey(BLACK)); assertTrue(colorBefore.containsKey(WHITE)); assertFalse(colorBefore.containsKey(YELLOW)); assertTrue(colorAfter.containsKey(BLACK)); assertTrue(colorAfter.containsKey(WHITE)); assertTrue(colorAfter.containsKey(YELLOW)); int start = -1; int end; List<Point> intervals = new ArrayList<>(); List<RGB> pixelRow = after.getPixelRow(2); for (int i = 1; i < pixelRow.size(); i++) { RGB prevPixel = pixelRow.get(i - 1); RGB pixel = pixelRow.get(i); if (!prevPixel.equals(YELLOW) && pixel.equals(YELLOW)) { start = i; } if (prevPixel.equals(YELLOW) && pixel.equals(WHITE)) { end = i; if (start == -1) { fail(); } intervals.add(new Point(start, end)); } } assertEquals(2, intervals.size()); assertEquals(intervals.get(1).y - intervals.get(1).x, intervals.get(0).y - intervals.get(0).x); }</code><technical_language>more natural test basic highlight first</technical_language>

Target:
public void testMultiHighlightMessage() { final Rectangle cellBounds = SWTBotUtils.getCellBounds(fTableBot.widget, ROW, MESSAGE_COLUMN); ImageHelper before = ImageHelper.getScreenGrab(cellBounds); fTableBot.click(0, MESSAGE_COLUMN); fBot.text().typeText("e\n", 100); fTableBot.select(ROW - 1); ImageHelper after = ImageHelper.getScreenGrab(cellBounds); Map<RGB, Integer> colorBefore = before.getHistogram(); Map<RGB, Integer> colorAfter = after.getHistogram(); assertTrue(colorBefore.containsKey(fBackground)); assertTrue(colorBefore.containsKey(fForeground)); assertFalse(colorBefore.containsKey(YELLOW)); assertTrue(colorAfter.containsKey(fBackground)); assertTrue(colorAfter.containsKey(fForeground)); assertTrue(colorAfter.containsKey(YELLOW)); int start = -1; int end; List<Point> intervals = new ArrayList<>(); List<RGB> pixelRow = after.getPixelRow(2); for (int i = 1; i < pixelRow.size(); i++) { RGB prevPixel = pixelRow.get(i - 1); RGB pixel = pixelRow.get(i); if (prevPixel.equals(fBackground) && pixel.equals(YELLOW)) { start = i; } if (prevPixel.equals(YELLOW) && pixel.equals(fBackground)) { end = i; if (start == -1) { fail(); } intervals.add(new Point(start, end)); } } assertEquals(2, intervals.size()); }
Source:
<code>public Object[] getChildren(Object parentElement) { if (parentElement instanceof IProductModel) { IProductModel productModel = (IProductModel) parentElement; <START> return productModel.getProduct().getFeatures(); <END> } else if (parentElement instanceof IFeatureModel) { IFeatureModel featureModel = (IFeatureModel) parentElement; Object[] features = featureModel.getFeature().getIncludedFeatures(); if (!fInput.isIncludePlugins()) { return features; } Object[] plugins = featureModel.getFeature().getPlugins(); List<Object> all = new ArrayList<>(features.length + plugins.length); all.addAll(Arrays.asList(features)); all.addAll(Arrays.asList(plugins)); return all.toArray(); } else if (parentElement instanceof IFeatureChild) { IFeatureChild featureChild = (IFeatureChild) parentElement; IFeatureModel featureModel = fFeatureModelManager.findFeatureModel(featureChild.getId()); return getChildren(featureModel); } else if (parentElement instanceof IProductFeature) { IProductFeature productFeature = (IProductFeature) parentElement; IFeatureModel featureModel = fFeatureModelManager.findFeatureModel(productFeature.getId()); return getChildren(featureModel); } return new Object[0]; }</code><technical_language>this return product's plugins (when includePlugins is active). avoid cluttering content provider, I suggest extract includePlugins handling a ViewerFilter</technical_language>

Target:
public Object[] getChildren(Object parentElement) { if (parentElement instanceof IProductModel) { IProductModel productModel = (IProductModel) parentElement; Object[] features = productModel.getProduct().getFeatures(); if (!fInput.getFeaturesViewInput().isIncludePlugins()) { return features; } Object[] plugins = productModel.getProduct().getPlugins(); List<Object> all = new ArrayList<>(features.length + plugins.length); all.addAll(Arrays.asList(features)); all.addAll(Arrays.asList(plugins)); return all.toArray(); } else if (parentElement instanceof IFeatureModel) { IFeatureModel featureModel = (IFeatureModel) parentElement; Object[] features = featureModel.getFeature().getIncludedFeatures(); if (!fInput.getFeaturesViewInput().isIncludePlugins()) { return features; } Object[] plugins = featureModel.getFeature().getPlugins(); List<Object> all = new ArrayList<>(features.length + plugins.length); all.addAll(Arrays.asList(features)); all.addAll(Arrays.asList(plugins)); return all.toArray(); } else if (parentElement instanceof IFeatureChild) { IFeatureChild featureChild = (IFeatureChild) parentElement; IFeatureModel featureModel = fFeatureModelManager.findFeatureModel(featureChild.getId()); return getChildren(featureModel); } else if (parentElement instanceof IProductFeature) { IProductFeature productFeature = (IProductFeature) parentElement; IFeatureModel featureModel = fFeatureModelManager.findFeatureModel(productFeature.getId()); return getChildren(featureModel); } return new Object[0]; }
Source:
<code><START> public static Metadata extractMetadata(Metadata metadata) { <END> Metadata toCheck = metadata; while (toCheck != null) { if (toCheck instanceof InternalMetadataImpl) { toCheck = ((InternalMetadataImpl) toCheck).actual(); } else { break; } } return toCheck; }</code><technical_language>public? If else used, leave private</technical_language>

Target:
private static Metadata extractMetadata(Metadata metadata) { Metadata toCheck = metadata; while (toCheck != null) { if (toCheck instanceof InternalMetadataImpl) { toCheck = ((InternalMetadataImpl) toCheck).actual(); } else { break; } } return toCheck; }
Source:
<code>public CompletableFuture<Long> write(long entryId, ByteBuf data) { SyncAddCallback callback = new SyncAddCallback(); <START> PendingAddOp op = new PendingAddOp(this, callback, null); <END> op.setEntryId(entryId); if ((entryId <= this.lastAddConfirmed) || pendingAddOps.contains(op)) { LOG.error("Trying to re-add duplicate entryid:{}", entryId); CompletableFuture<Long> result = createFuture(); completeExceptionally(result, BKException.create(BKException.Code.DuplicateEntryIdException)); return result; } doAsyncAddEntry(op, data, callback, null); return callback; }</code><technical_language>hmm... moved logic write function... I understand do need duplicate logic in asyncAddEntry. new write(long entryId, ByteBuf data) a shortcut of legacy asyncAddEntry method, no</technical_language>

Target:
public CompletableFuture<Long> write(long entryId, ByteBuf data) { SyncAddCallback callback = new SyncAddCallback(); asyncAddEntry(entryId, data, callback, data); return callback; }
Source:
<code><START> public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, final Callable realMethod, Object... args) { <END> RealMethod.FromCallable superMethod = new RealMethod.FromCallable(realMethod); return MockMethodInterceptor.createInvocation(target, method, args, superMethod, settings); }</code><technical_language>Nit: need add final</technical_language>

Target:
public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, final Callable realMethod, Object... args) { RealMethod superMethod = new RealMethod.FromCallable(realMethod); return createInvocation(target, settings, method, superMethod, args); }
Source:
<code>public void messageExpired(MessageReference message, SimpleString messageExpiryAddress, ServerConsumer consumer) { final ManagementService managementService = getManagementService(); if (managementService != null && sendExpiredNotifications) { try { if (!message.getQueue().getAddress().equals(managementService.getManagementNotificationAddress())) { final TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, message.getQueue().getAddress()); props.putByteProperty(ManagementHelper.HDR_ROUTING_TYPE, message.getQueue().getRoutingType().getType()); props.putSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME, message.getQueue().getName()); props.putLongProperty(ManagementHelper.HDR_MESSAGE_ID, message.getMessageID()); if (message.hasConsumerId()) { long consumerId = message.getConsumerId(); <START> if (consumerId >= 0) { <END> props.putLongProperty(ManagementHelper.HDR_CONSUMER_NAME, consumerId); } } managementService.sendNotification(new Notification(null, CoreNotificationType.MESSAGE_EXPIRED, props)); } } catch (Exception e) { logger.warn("Error sending notification: " + CoreNotificationType.MESSAGE_EXPIRED, e.getMessage(), e); } } }</code><technical_language>Redudent check message.hasConsumerId check 2 lines</technical_language>

Target:
public void messageExpired(MessageReference message, SimpleString messageExpiryAddress, ServerConsumer consumer) { final ManagementService managementService = getManagementService(); if (managementService != null && sendExpiredNotifications) { try { if (!message.getQueue().getAddress().equals(managementService.getManagementNotificationAddress())) { final TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, message.getQueue().getAddress()); props.putByteProperty(ManagementHelper.HDR_ROUTING_TYPE, message.getQueue().getRoutingType().getType()); props.putSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME, message.getQueue().getName()); props.putLongProperty(ManagementHelper.HDR_MESSAGE_ID, message.getMessageID()); if (message.hasConsumerId()) { props.putLongProperty(ManagementHelper.HDR_CONSUMER_NAME, message.getConsumerId()); } managementService.sendNotification(new Notification(null, CoreNotificationType.MESSAGE_EXPIRED, props)); } } catch (Exception e) { logger.warn("Error sending notification: " + CoreNotificationType.MESSAGE_EXPIRED, e.getMessage(), e); } } }
Source:
<code><START> public String toString() { <END> return this.getClass().getSimpleName() + " { " + getPayload().getPayloadId() + " }"; }</code><technical_language>Recommend ToStringBuilder</technical_language>

Target:
public String toString() { return new ToStringBuilder(this) .append("myPayload", myPayload) .toString(); }
Source:
<code>public void testImportVMFromConfigurationWhenVMDoesNotExists() { initCommand(null); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue() .getCanDoActionMessages() <START> .contains(VdcBllMessages.ACTION_TYPE_FAILED_UNSUPPORTED_OVF.toString())); <END> }</code><technical_language>Please CanDoActionAssertUtils</technical_language>

Target:
public void testImportVMFromConfigurationWhenVMDoesNotExists() { initCommand(null); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_UNSUPPORTED_OVF); }
Source:
<code>public String getTypeElementsList() throws ParseException { final StringBuilder outputBuilder = new StringBuilder(); <START> for ( final Ds3Element element : this.elements) { <END> LOG.debug("element[" + element.getName() + "][" + element.getType() + "]"); outputBuilder.append(CHelper.indent(1)); outputBuilder.append(CHelper.elementTypeToString(element)); outputBuilder.append(" "); outputBuilder.append(Helper.camelToUnderscore(Helper.unqualifiedName(element.getName()))); outputBuilder.append(";"); outputBuilder.append(System.lineSeparator()); } return outputBuilder.toString(); }</code><technical_language>extra space (</technical_language>

Target:
public String getTypeElementsList() throws ParseException { final StringBuilder outputBuilder = new StringBuilder(); for (final Ds3Element element : this.elements) { outputBuilder.append(CHelper.indent(1)) .append(CHelper.elementTypeToString(element)) .append(" ") .append(Helper.camelToUnderscore(Helper.unqualifiedName(element.getName()))) .append(";") .append(System.lineSeparator()); } return outputBuilder.toString(); }
Source:
<code>public boolean processFile(String requestExtractFileName) { boolean processingSuccess = true; <START> Object parsedFile; <END> try { parsedFile = loadFile(requestExtractFileName); processingSuccess = requestExtractHeaderRowValidatesToFileContents(parsedFile); } catch (RuntimeException re) { LOG.error("Caught exception trying to load: " + requestExtractFileName, re); processingSuccess = false; } return processingSuccess; }</code><technical_language>this is try I sense move this try parsedFile is</technical_language>

Target:
public boolean processFile(String requestExtractFileName) { boolean processingSuccess = true; Object parsedFile = loadFile(requestExtractFileName); List<ConcurRequestExtractFile> requestExtractFiles = (ArrayList<ConcurRequestExtractFile>) parsedFile; processingSuccess = getConcurRequestExtractFileValidationService().requestExtractHeaderRowValidatesToFileContents(requestExtractFiles); return processingSuccess; }
Source:
<code>public void testInitiateConnection(long sid) throws Exception { LOG.debug("Opening channel to server " + sid); Socket sock = new Socket(); setSockOpts(sock); InetSocketAddress address; <START> try { <END> address = self.getVotingView().get(sid).electionAddr.getValidAddress(); } catch (NoRouteToHostException e) { address = self.getVotingView().get(sid).electionAddr.getOne(); } sock.connect(address, cnxTO); initiateConnection(sock, sid); }</code><technical_language>This logic is common board. located in a parent helper class. For example in MultipleAddresses class getReachableOrOne</technical_language>

Target:
public void testInitiateConnection(long sid) throws Exception { LOG.debug("Opening channel to server " + sid); Socket sock = new Socket(); setSockOpts(sock); InetSocketAddress address = self.getVotingView().get(sid).electionAddr.getReachableOrOne(); sock.connect(address, cnxTO); initiateConnection(sock, sid); }
Source:
<code>public void testSetNewLogFileConfiguration() throws Exception { LogFileConfiguration config = new LogFileConfiguration(tempDirPath); final FileLogger fileLogger = Database.log.getFile(); fileLogger.setConfig(config); fileLogger.setConfig(null); <START> fileLogger.setConfig(null); <END> fileLogger.setConfig(config); fileLogger.setConfig(new LogFileConfiguration(tempDirPath + "/foo")); }</code><technical_language>I guessed this is intention double test null, right</technical_language>

Target:
public void testSetNewLogFileConfiguration() throws Exception { LogFileConfiguration config = new LogFileConfiguration(tempDirPath); final FileLogger fileLogger = Database.log.getFile(); fileLogger.setConfig(config); assertEquals(fileLogger.getConfig(), config); fileLogger.setConfig(config); assertEquals(fileLogger.getConfig(), config); fileLogger.setConfig(null); assertNull(fileLogger.getConfig()); fileLogger.setConfig(null); assertNull(fileLogger.getConfig()); fileLogger.setConfig(config); assertEquals(fileLogger.getConfig(), config); fileLogger.setConfig(new LogFileConfiguration(tempDirPath + "/foo")); assertEquals(fileLogger.getConfig(), new LogFileConfiguration(tempDirPath + "/foo")); }
Source:
<code>private MemoryImageBuilder createMemoryImageBuilder() { boolean archSupportSnapshot = isSnapshotSupportedByArchitecture(getVm().getClusterArch(), getVm().getVdsGroupCompatibilityVersion()); <START> if (!FeatureSupported.memorySnapshot(getVm().getVdsGroupCompatibilityVersion()) || archSupportSnapshot) { <END> return new NullableMemoryImageBuilder(); } if (getParameters().getSnapshotType() == SnapshotType.STATELESS) { return new StatelessSnapshotMemoryImageBuilder(getVm()); } if (getParameters().isSaveMemory() && isLiveSnapshotApplicable()) { return new LiveSnapshotMemoryImageBuilder(getVm(), getStorageDomainIdForVmMemory(), getStoragePool(), this); } return new NullableMemoryImageBuilder(); }</code><technical_language>!archSupportSnapshot, right</technical_language>

Target:
private MemoryImageBuilder createMemoryImageBuilder() { if (!isMemorySnapshotSupported()) { return new NullableMemoryImageBuilder(); } if (getParameters().getSnapshotType() == SnapshotType.STATELESS) { return new StatelessSnapshotMemoryImageBuilder(getVm()); } if (getParameters().isSaveMemory() && isLiveSnapshotApplicable()) { return new LiveSnapshotMemoryImageBuilder(getVm(), getStorageDomainIdForVmMemory(), getStoragePool(), this); } return new NullableMemoryImageBuilder(); }
Source:
<code>private String columnsFromMetadata(String tableName) { List<String> columnNames = jdbc.query("select * from " + tableName + " where 1 = 0", columnNamesExtractor); <START> return join(columnNames.toArray(), ","); <END> }</code><technical_language>need for toArray conversion here? StringUtils join supports collections directly</technical_language>

Target:
private String columnsFromMetadata(String tableName) { List<String> columnNames = jdbc.query("select * from " + tableName + " where 1 = 0", columnNamesExtractor); return join(columnNames, ","); }