auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void showForm(ModelMap model, @RequestParam(value = "uuid", required = false) String uuid, @RequestParam(value = "copyFromUuid", required = false) String copyFromUuid) { if (uuid == null) { model.addAttribute("definition", new ScriptedCompositionPatientDataDefinition()); } else { <START> PatientDataDefinition def = Context.getService(PatientDataService.class).getDefinitionByUuid(uuid); <END> if (def instanceof ScriptedCompositionPatientDataDefinition) { ScriptedCompositionPatientDataDefinition definition = (ScriptedCompositionPatientDataDefinition) def; model.addAttribute("definition", definition); } else { throw new RuntimeException("This definition is not of the right class"); } } }</code><technical_language>put else statement a new line a style preference</technical_language>

Target:
public void showForm(ModelMap model, @RequestParam(value = "uuid", required = false) String uuid, @RequestParam(value = "copyFromUuid", required = false) String copyFromUuid) { model.put("scriptTypes", TemplateEngineManager.getAvailableTemplateEngineNames()); if (uuid == null) { model.addAttribute("definition", new ScriptedCompositionPatientDataDefinition()); } else { PatientDataDefinition def = Context.getService(PatientDataService.class).getDefinitionByUuid(uuid); if (def instanceof ScriptedCompositionPatientDataDefinition) { ScriptedCompositionPatientDataDefinition definition = (ScriptedCompositionPatientDataDefinition) def; model.addAttribute("definition", definition); } else { throw new RuntimeException("This definition is not of the right class"); } } }
Source:
<code>private Map<Long, InProgressTx> txnBackwardsCompatCheck(Map<Long, InProgressTx> inProgress) { for (Map.Entry<Long, InProgressTx> entry : inProgress.entrySet()) { if (entry.getValue().getExpiration() < 0) { InProgressTx compatTx = <START> new InProgressTx(entry.getValue().getVisibilityUpperBound(), getTxExpiration(defaultLongTimeout), <END> TransactionType.LONG); entry.setValue(compatTx); } else if (entry.getValue().getType() == null) { InProgressTx compatTx = new InProgressTx(entry.getValue().getVisibilityUpperBound(), entry.getValue().getExpiration(), TransactionType.SHORT); entry.setValue(compatTx); } } return inProgress; }</code><technical_language>right this is give a expiration time depending snapshot is restored. Essentially expiration is extended/reset snapshot restore. base system time for expiration transaction write pointer (time in millis = write pointer / TxConstants.MAX_TX_PER_MS)</technical_language>

Target:
private Map<Long, InProgressTx> txnBackwardsCompatCheck(Map<Long, InProgressTx> inProgress) { for (Map.Entry<Long, InProgressTx> entry : inProgress.entrySet()) { if (entry.getValue().getExpiration() < 0) { long writePointer = entry.getKey(); long expiration = getTxExpirationFromWritePointer(writePointer, defaultLongTimeout); InProgressTx compatTx = new InProgressTx(entry.getValue().getVisibilityUpperBound(), expiration, TransactionType.LONG); entry.setValue(compatTx); } else if (entry.getValue().getType() == null) { InProgressTx compatTx = new InProgressTx(entry.getValue().getVisibilityUpperBound(), entry.getValue().getExpiration(), TransactionType.SHORT); entry.setValue(compatTx); } } return inProgress; }
Source:
<code>public void testAsExtend() { final TestSubscriber<Object> subscriber = new TestSubscriber<Object>(); final Object value = new Object(); Flowable.just(value).as(new FlowableConverter<Object, Object>() { @Override public Object apply(Flowable<Object> onSubscribe) { onSubscribe.subscribe(subscriber); subscriber.assertNoErrors(); <START> subscriber.assertComplete(); <END> subscriber.assertValue(value); return subscriber.values().get(0); } }); }</code><technical_language>this run asserting if Converter is called</technical_language>

Target:
public void testAsExtend() { final TestSubscriber<Object> subscriber = new TestSubscriber<Object>(); final Object value = new Object(); Object returned = Flowable.just(value).as(new FlowableConverter<Object, Object>() { @Override public Object apply(Flowable<Object> onSubscribe) { onSubscribe.subscribe(subscriber); subscriber.assertNoErrors(); subscriber.assertComplete(); subscriber.assertValue(value); return subscriber.values().get(0); } }); assertSame(returned, value); }
Source:
<code>protected Constraint periodDurationTooShort(ConstraintFactory constraintFactory) { <END> <START> return constraintFactory.fromUnfiltered(Exam.class) .filter(exam -> exam.getPeriod() != null) .filter(exam -> exam.getTopicDuration() > exam.getPeriodDuration()) .penalize("Period duration too short", HardSoftScore.ONE_HARD, Exam::getTopicStudentSize); }</code><technical_language>fromUnfiltered(), if filter anyway</technical_language>

Target:
protected Constraint periodDurationTooShort(ConstraintFactory constraintFactory) { return constraintFactory.from(Exam.class) .filter(exam -> exam.getTopicDuration() > exam.getPeriodDuration()) .penalizeConfigurable("periodDurationTooShort", Exam::getTopicStudentSize); }
Source:
<code>protected ReqWriter newReqWriter(XmlRpcRequest pRequest) throws XmlRpcException, IOException, SAXException { <START> if (METHOD_LIST.contains(pRequest.getMethodName())) { <END> pRequest = new XmlRpcClientRequestImpl(pRequest.getConfig(), pRequest.getMethodName(), normalizeDoubles(pRequest)); } return super.newReqWriter(pRequest); }</code><technical_language>contains a List is effective. a Set instead</technical_language>

Target:
protected ReqWriter newReqWriter(XmlRpcRequest pRequest) throws XmlRpcException, IOException, SAXException { if (METHOD_LIST.contains(pRequest.getMethodName())) { pRequest = new XmlRpcClientRequestImpl(pRequest.getConfig(), pRequest.getMethodName(), normalizeLongs(pRequest)); } return super.newReqWriter(pRequest); }
Source:
<code>public UserDTO getByName(final String userName) throws UserRetrievalException { <START> loginAdminUser(); <END> UserDTO dto = securedUserManager.getBySubjectName(userName); logoutAdminUser(); return dto; }</code><technical_language>is this called in new code is requiring a user logged in called? place calling DAO instead of manager</technical_language>

Target:
public UserDTO getByName(final String userName) throws UserRetrievalException { UserDTO dto = securedUserManager.getBySubjectName(userName); return dto; }
Source:
<code>public String getBrokerHost(String table) { try { List<String> brokers = brokersForTableCache.get(table); if (brokers.isEmpty()) { throw new PinotException(PinotErrorCode.PINOT_UNABLE_TO_FIND_BROKER, Optional.empty(), "No valid brokers found for " + table); <START> } <END> return brokers.get(ThreadLocalRandom.current().nextInt(brokers.size())); } catch (ExecutionException e) { Throwable err = e.getCause(); if (err instanceof PinotException) { throw (PinotException) err; } else { throw new PinotException(PinotErrorCode.PINOT_UNABLE_TO_FIND_BROKER, Optional.empty(), "Error when getting brokers for table " + table, err); } } }</code><technical_language>List<String></technical_language>

Target:
public String getBrokerHost(String table) { try { List<String> brokers = brokersForTableCache.get(table); if (brokers.isEmpty()) { throw new PinotException(PINOT_UNABLE_TO_FIND_BROKER, Optional.empty(), "No valid brokers found for " + table); } return brokers.get(ThreadLocalRandom.current().nextInt(brokers.size())); } catch (ExecutionException e) { Throwable throwable = e.getCause(); if (throwable instanceof PinotException) { throw (PinotException) throwable; } else { throw new PinotException(PINOT_UNABLE_TO_FIND_BROKER, Optional.empty(), "Error when getting brokers for table " + table, throwable); } } }
Source:
<code>private void writeCanceledFromThreadToMainThread() { mainHandler.post(new Runnable() { @Override public void run() { thread.quit(); boolean success = file.delete(); if (!success) { <START> Log.d(getClass().getSimpleName(), "Failed to delete file " + file.toString()); <END> } } }); }</code><technical_language>a lot of inconsistency logging. Backbone a LogExt class is elsewhere. I a preference, consistency nice</technical_language>

Target:
private void writeCanceledFromThreadToMainThread() { mainHandler.post(new Runnable() { @Override public void run() { thread.quit(); boolean success = file.delete(); if (!success) { LogExt.d(getClass(), "Failed to delete file " + file.toString()); } } }); }
Source:
<code>private Map<String, String> getTraceProperties() { <START> for (ITmfTrace fTrace : TmfTraceManager.getInstance().getOpenedTraces()) { <END> if (fTrace.getResource().equals(this.getResource())) { if (fTrace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) fTrace; return traceProperties.getTraceProperties(); } } } return new HashMap<String, String>(); }</code><technical_language>fTrace, f prefix is for member variables. support trace properties of traces opened in experiment adding loop for traces in getTraceSet(openedTrace)..</technical_language>

Target:
private Map<String, String> getTraceProperties() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (trace.getResource().equals(this.getResource())) { if (trace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) trace; return traceProperties.getTraceProperties(); } } } return new HashMap<String, String>(); }
Source:
<code>RequestBuilder(Picasso picasso, Uri uri, int resourceId) { if (picasso.shutdown) { throw new IllegalStateException( <START> "Picasso instance already shut down. " + "Cannot submit new requests."); <END> } this.picasso = picasso; this.uri = uri; this.resourceId = resourceId; }</code><technical_language>Combine strings</technical_language>

Target:
RequestBuilder(Picasso picasso, Uri uri, int resourceId) { if (picasso.shutdown) { throw new IllegalStateException( "Picasso instance already shut down. Cannot submit new requests."); } this.picasso = picasso; this.uri = uri; this.resourceId = resourceId; }
Source:
<code>public int getResultFiles(ZipOutputStream target, String provider, String organization, String activity, String resultId) { <START> LOG.trace("Getting file for: providers/{}/organizations/{}/activities/{}/results/{}", organization, activity, resultId); <END> StreamingCallbackHandler handler = new StreamingCallbackHandler(target); jdbcTemplate.query("select object_name, object_content from result_object where data_source = ? and organization = ? and activity = ? and result_id = ?::int order by object_id", new Object[] {provider, organization, activity, resultId}, handler); return handler.getRowCount(); }</code><technical_language>LOG statement</technical_language>

Target:
public int getResultFiles(ZipOutputStream target, String provider, String organization, String activity, String resultId) { LOG.trace("Getting file for: providers/{}/organizations/{}/activities/{}/results/{}", provider, organization, activity, resultId); StreamingCallbackHandler handler = new StreamingCallbackHandler(target); jdbcTemplate.query("select object_name, object_content from result_object where data_source = ? and organization = ? and activity = ? and result_id = ?::int order by object_id", new Object[] {provider, organization, activity, resultId}, handler); return handler.getRowCount(); }
Source:
<code>private static boolean validate(CLIParse parser) { boolean fOK = true; if ((!parser.hasArg("enc")) && (!parser.hasArg("dec")) && (!parser.hasArg("pvk")) && (!parser.hasArg("pubkey2ssh"))) { <START> System.out.println("What do you wish me to do? -please specify -enc, -dec, -pvk or -pubkey2ssh"); <END> fOK = false; } if ((parser.hasArg("enc") || parser.hasArg("dec")) && (!parser.hasArg("string"))) { System.out.println("Can't find a string to work with :( -please specify -string='something'."); fOK = false; } if ((!parser.hasArg("store")) || (!new File(parser.getArg("store")).exists())) { System.out.println("Can't find a keystore to work with :( -please specify -store with the correct keystore path."); fOK = false; } if (!parser.hasArg("pass")) { System.out.println("Can't find a keystore pass :( -please specify -pass with the correct keystore password."); fOK = false; } if (!fOK) { printUsage(); } return fOK; }</code><technical_language>Please remove pvk</technical_language>

Target:
private static boolean validate(CLIParse parser) { boolean fOK = true; if ((!parser.hasArg("enc")) && (!parser.hasArg("dec")) && (!parser.hasArg("pvk")) && (!parser.hasArg("pubkey2ssh"))) { System.out.println("What do you wish me to do? -please specify -enc, -dec or -pubkey2ssh"); fOK = false; } if ((parser.hasArg("enc") || parser.hasArg("dec")) && (!parser.hasArg("string"))) { System.out.println("Can't find a string to work with :( -please specify -string='something'."); fOK = false; } if ((!parser.hasArg("store")) || (!new File(parser.getArg("store")).exists())) { System.out.println("Can't find a keystore to work with :( -please specify -store with the correct keystore path."); fOK = false; } if (!parser.hasArg("pass")) { System.out.println("Can't find a keystore pass :( -please specify -pass with the correct keystore password."); fOK = false; } if (!fOK) { printUsage(); } return fOK; }
Source:
<code>protected void run() { try { runInterceptHook(); Transaction preparedDelayedPayoutTx = checkNotNull(processModel.getPreparedDelayedPayoutTx()); BtcWalletService btcWalletService = processModel.getBtcWalletService(); NetworkParameters params = btcWalletService.getParams(); <START> Transaction preparedDepositTx = new Transaction(params, processModel.getPreparedDepositTx()); <END> Coin delayedPayoutTxInputValue = preparedDepositTx.getOutput(0).getValue(); String id = processModel.getOffer().getId(); byte[] buyerMultiSigPubKey = processModel.getMyMultiSigPubKey(); DeterministicKey myMultiSigKeyPair = btcWalletService.getMultiSigKeyPair(id, buyerMultiSigPubKey); checkArgument(Arrays.equals(buyerMultiSigPubKey, btcWalletService.getOrCreateAddressEntry(id, AddressEntry.Context.MULTI_SIG).getPubKey()), "buyerMultiSigPubKey from AddressEntry must match the one from the trade data. trade id =" + id); byte[] sellerMultiSigPubKey = processModel.getTradingPeer().getMultiSigPubKey(); byte[] delayedPayoutTxSignature = processModel.getTradeWalletService().signDelayedPayoutTx( preparedDelayedPayoutTx, delayedPayoutTxInputValue, myMultiSigKeyPair, buyerMultiSigPubKey, sellerMultiSigPubKey); processModel.setDelayedPayoutTxSignature(delayedPayoutTxSignature); complete(); } catch (Throwable t) { failed(t); } }</code><technical_language>input preparedDelayedPayoutTx? If is possible, I prefer pass deposit tx signDelayedPayoutTx method do deail work in TradeWalletService transaction domain more isolated there</technical_language>

Target:
protected void run() { try { runInterceptHook(); Transaction preparedDelayedPayoutTx = checkNotNull(processModel.getPreparedDelayedPayoutTx()); BtcWalletService btcWalletService = processModel.getBtcWalletService(); NetworkParameters params = btcWalletService.getParams(); Transaction preparedDepositTx = new Transaction(params, processModel.getPreparedDepositTx()); String id = processModel.getOffer().getId(); byte[] buyerMultiSigPubKey = processModel.getMyMultiSigPubKey(); DeterministicKey myMultiSigKeyPair = btcWalletService.getMultiSigKeyPair(id, buyerMultiSigPubKey); checkArgument(Arrays.equals(buyerMultiSigPubKey, btcWalletService.getOrCreateAddressEntry(id, AddressEntry.Context.MULTI_SIG).getPubKey()), "buyerMultiSigPubKey from AddressEntry must match the one from the trade data. trade id =" + id); byte[] sellerMultiSigPubKey = processModel.getTradingPeer().getMultiSigPubKey(); byte[] delayedPayoutTxSignature = processModel.getTradeWalletService().signDelayedPayoutTx( preparedDelayedPayoutTx, preparedDepositTx, myMultiSigKeyPair, buyerMultiSigPubKey, sellerMultiSigPubKey); processModel.setDelayedPayoutTxSignature(delayedPayoutTxSignature); complete(); } catch (Throwable t) { failed(t); } }
Source:
<code>public void visitPrefixExpression(UnaryExpressionTree tree) { <START> if (tree.is(Kind.LOGICAL_COMPLEMENT) && tree.expression().is(Kind.PARENTHESISED_EXPRESSION)) { <END> checkParenthesisedExpression(tree, (ParenthesisedExpressionTree) tree.expression()); } super.visitPrefixExpression(tree); }</code><technical_language>I checking tree.expression().is(Kind.PARENTHESISED_EXPRESSION) is kind of redundant here. I remove this condition adapt checkParenthesisedExpression (and rename checkParenthesisedExpression)</technical_language>

Target:
public void visitPrefixExpression(UnaryExpressionTree tree) { if (tree.is(Kind.LOGICAL_COMPLEMENT)) { checkComplementParenthesisedExpression(tree, tree.expression()); } super.visitPrefixExpression(tree); }
Source:
<code>public Iterable<Person> people(Iterable<Publisher> publishers, ApplicationConfiguration config, Selection selection) { <START> Iterable<LookupEntry> entries = selection.apply(peopleLookupEntryStore.entriesForPublishers(publishers, null)); <END> Map<String, LookupEntry> entriesIndex = Maps.uniqueIndex(entries, Functions.compose(LookupRef.TO_URI, LookupEntry.TO_SELF)); Map<String, Person> peopleIndex = Maps.uniqueIndex(peopleForEntries(entriesIndex, config), Identified.TO_URI); ListMultimap<String, Person> idToPeople = keysToPeople(entriesIndex, peopleIndex, LookupRef.TO_URI); return findOrMerge(peopleIndex.keySet(), idToPeople, Identified.TO_URI, config); }</code><technical_language>pass selection in</technical_language>

Target:
public Iterable<Person> people(Iterable<Publisher> publishers, ApplicationConfiguration config, Selection selection) { Iterable<LookupEntry> entries = peopleLookupEntryStore.entriesForPublishers(publishers, selection); Map<String, LookupEntry> entriesIndex = Maps.uniqueIndex(entries, Functions.compose(LookupRef.TO_URI, LookupEntry.TO_SELF)); Map<String, Person> peopleIndex = Maps.uniqueIndex(peopleForEntries(entriesIndex, config), Identified.TO_URI); ListMultimap<String, Person> idToPeople = keysToPeople(entriesIndex, peopleIndex, LookupRef.TO_URI); return findOrMerge(peopleIndex.keySet(), idToPeople, Identified.TO_URI, config); }
Source:
<code>private void autoDiscoverLaTeXPath() { try { String command; <START> if (System.getProperty("os.name").contains("Windows")) { <END> command = "where " + ApplicationUtils.TEX_NAME; } else { command = "which " + ApplicationUtils.TEX_NAME; } Process p = Runtime.getRuntime().exec(command); p.waitFor(); File path = new File(new Scanner(p.getInputStream()).nextLine()); if (path != null && path.exists() && path.isFile()) { ApplicationSettings.Setting.LATEX_PATH.setValue(path.getParent()); ApplicationSettings.INSTANCE.save(); } } catch (IOException | InterruptedException | NoSuchElementException | IllegalStateException ex) { } }</code><technical_language>OS discovery logic is implemented in ApplicationUtils</technical_language>

Target:
private void autoDiscoverLaTeXPath() { try { String command = (ApplicationUtils.isWindows() ? "where " : "which ") + ApplicationUtils.TEX_NAME; Process p = Runtime.getRuntime().exec(command); p.waitFor(); File path = new File(new Scanner(p.getInputStream()).nextLine()); if (path.exists() && path.isFile() && path.canExecute()) { ApplicationSettings.Setting.LATEX_PATH.setValue(path.getParent()); ApplicationSettings.INSTANCE.save(); } } catch (IOException | InterruptedException | NoSuchElementException | IllegalStateException ex) { LOGGER.log("Couldn't find LaTeX installed on your computer."); LOGGER.log("Go to Tools -> Options -> LaTeX to specify LaTeX directory."); ex.printStackTrace(); } }
Source:
<code>private String formatPlan(PlanNode plan, TypeProvider types) { <START> return inTransaction(session -> textLogicalPlan(plan, types, metadata.getFunctionRegistry(), statsCalculator, costCalculator, session)); <END> }</code><technical_language>indent 2 here. Now, if correctly, is 0</technical_language>

Target:
private String formatPlan(PlanNode plan, TypeProvider types) { return inTransaction(session -> textLogicalPlan(plan, types, metadata.getFunctionRegistry(), statsCalculator, costCalculator, session, 2, false)); }
Source:
<code>public void createIndexWhileClearOnReplicateRegion() throws Exception { invokeInEveryMember(() -> { Cache cache = ClusterStartupRule.getCache(); cache.createRegionFactory(RegionShortcut.PARTITION) .create("replicateCities"); }, server1, server2); Region replicateCities = clientCacheRule.createProxyRegion("replicateCities"); IntStream.range(0, 100).forEach(i -> replicateCities.put(i, new City(i))); AsyncInvocation createIndex = server1.invokeAsync("create index on replicate regions", () -> { Cache cache = ClusterStartupRule.getCache(); QueryService queryService = cache.getQueryService(); Index cityZip = queryService.createIndex("cityZip_replicate", "c.zip", "/replicateCities c"); assertThat(cityZip).isNotNull(); }); replicateCities.clear(); createIndex.await(); QueryService queryService = clientCache.getQueryService(); Query query = queryService .newQuery("select * from /replicateCities c where c.zip < " + (City.ZIP_START + 10)); <START> assertThat(((SelectResults) query.execute()).size()).isEqualTo(0); <END> IntStream.range(0, 10).forEach(i -> replicateCities.put(i, new City(i))); assertThat(((SelectResults) query.execute()).size()).isEqualTo(10); }</code><technical_language>This is a entries in index. this need query index. nice validate index storage size: done calling isEmpty() Index class index stats (as done in other places in this test)</technical_language>

Target:
public void createIndexWhileClearOnReplicateRegion() throws Exception { invokeInEveryMember(() -> { Cache cache = ClusterStartupRule.getCache(); cache.createRegionFactory(RegionShortcut.PARTITION) .create("replicateCities"); }, server1, server2); Region replicateCities = clientCacheRule.createProxyRegion("replicateCities"); IntStream.range(0, 1000).forEach(i -> replicateCities.put(i, new City(i))); AsyncInvocation createIndex = server1.invokeAsync("create index on replicate regions", () -> { Cache cache = ClusterStartupRule.getCache(); QueryService queryService = cache.getQueryService(); Index cityZip = queryService.createIndex("cityZip_replicate", "c.zip", "/replicateCities c"); assertThat(cityZip).isNotNull(); }); for (int i = 0; i < 3; i++) { replicateCities.clear(); } createIndex.await(); invokeInEveryMember(() -> { verifyIndexesAfterClear("replicateCities", "cityZip_replicate"); }, server1, server2); QueryService queryService = clientCache.getQueryService(); Query query = queryService .newQuery("select * from /replicateCities c where c.zip < " + (City.ZIP_START + 10)); assertThat(((SelectResults) query.execute()).size()).isEqualTo(0); IntStream.range(0, 10).forEach(i -> replicateCities.put(i, new City(i))); assertThat(((SelectResults) query.execute()).size()).isEqualTo(10); }
Source:
<code>CallbackThrottle create() { switch (type) { case THROTTLE_BY_TIME: <START> return new CallbackThrottleByTime(SchedulerFactory.createFixedRateTimerScheduler(timeUnit.toMillis(frequency))); <END> case THROTTLE_BY_PROGRESS_INCREASE: return new CallbackThrottleByProgressIncrease(); case CUSTOM: return createCallbackThrottle(); default: throw new IllegalStateException("type " + type + " not supported"); } }</code><technical_language>extract out Scheduler creation a local var. clear is created</technical_language>

Target:
CallbackThrottle create() { switch (type) { case THROTTLE_BY_TIME: ActionScheduler actionScheduler = SchedulerFactory.createFixedRateTimerScheduler(timeUnit.toMillis(frequency)); return new CallbackThrottleByTime(actionScheduler); case THROTTLE_BY_PROGRESS_INCREASE: return new CallbackThrottleByProgressIncrease(); case CUSTOM: return createCallbackThrottle(); default: throw new IllegalStateException("type " + type + " not supported"); } }
Source:
<code>public boolean validateChecksum() { if (StringUtils.isNotBlank(checksum)) { int retry = 3; boolean valid = false; ChecksumValue providedChecksum = new ChecksumValue(checksum); String algorithm = providedChecksum.getAlgorithm(); String checksumCommand = "echo '%s %s' | %s -c --quiet"; String cmd = String.format(checksumCommand, providedChecksum.getChecksum(), downloadedFilePath, getChecksumCommandFromAlgorithm(algorithm)); int result; while (!valid && retry > 0) { s_logger.debug("Performing checksum validation for downloaded template " + templateId + ", retries left: " + retry); <START> result = Script.runSimpleBashScriptForExitValue(cmd); <END> valid = result == 0; retry--; if (!valid && retry > 0) { s_logger.debug("Checksum validation failded, re-downloading template"); resetDownloadFile(); downloadTemplate(); } } return valid; } return true; }</code><technical_language>please refactor touse java implementation of checksum code</technical_language>

Target:
public boolean validateChecksum() { if (StringUtils.isNotBlank(checksum)) { int retry = 3; boolean valid = false; try { while (!valid && retry > 0) { s_logger.info("Performing checksum validation for downloaded template " + templateId + ", retries left: " + retry); valid = DigestHelper.check(checksum, new FileInputStream(downloadedFilePath)); retry--; if (!valid && retry > 0) { s_logger.info("Checksum validation failded, re-downloading template"); redownload = true; resetDownloadFile(); downloadTemplate(); } } s_logger.info("Checksum validation for template " + templateId + ": " + (valid ? "succeeded" : "failed")); return valid; } catch (IOException e) { throw new CloudRuntimeException("could not check sum for file: " + downloadedFilePath, e); } catch (NoSuchAlgorithmException e) { throw new CloudRuntimeException("Unknown checksum algorithm: " + checksum, e); } } s_logger.info("No checksum provided, skipping checksum validation"); return true; }
Source:
<code>public CohortDefinition getAnyEncounterDuringPeriodWithOccurrence() { EncounterCohortDefinition cd = new EncounterCohortDefinition(); cd.addParameter(new Parameter("onOrAfter", "reporting.parameter.startDate", Date.class)); cd.addParameter(new Parameter("onOrBefore", "reporting.parameter.endDate", Date.class)); cd.addParameter(new Parameter("atLeastCount", "reporting.parameter.atleast", Integer.class)); cd.addParameter(new Parameter("atMostCount", "reporting.parameter.atMost", Integer.class)); cd.addParameter(new Parameter("encounterTypeList", "reporting.parameter.encounterTypeList", EncounterType.class, List.class, null)); cd.addParameter(new Parameter("formList", "reporting.parameter.formList", Form.class, List.class, null)); cd.addParameter(new Parameter("locationList", "reporting.parameter.location", Location.class, List.class, null)); <START> return new MappedParametersCohortDefinition(cd, "onOrAfter", "fromDate", "onOrBefore", "toDate", "encounterTypeList", "encounterTypes", "locationList", "location", "atLeastCount", "atLeast", "atMostCount", "atMost", "formList", "form"); <END> }</code><technical_language>This fine, consistent exposing parameters libraries. I vote for either: a) Exposing parameters names in underlying Java classes, people expect, b) (a), exposing properties standard names (eg. startDate, endDate, location). this in mind, I favor simply exposing parameters named, modifying onOrAfter=startDate onOrBefore=endDate locationList=location @djazayeri other visions for libraries expose parameters</technical_language>

Target:
public CohortDefinition getAnyEncounterDuringPeriodWithOccurrence() { EncounterCohortDefinition cd = new EncounterCohortDefinition(); cd.addParameter(new Parameter("onOrAfter", "reporting.parameter.startDate", Date.class)); cd.addParameter(new Parameter("onOrBefore", "reporting.parameter.endDate", Date.class)); cd.addParameter(new Parameter("atLeastCount", "reporting.parameter.atleast", Integer.class)); cd.addParameter(new Parameter("atMostCount", "reporting.parameter.atMost", Integer.class)); cd.addParameter(new Parameter("encounterTypeList", "reporting.parameter.encounterTypeList", EncounterType.class, List.class, null)); cd.addParameter(new Parameter("formList", "reporting.parameter.formList", Form.class, List.class, null)); cd.addParameter(new Parameter("locationList", "reporting.parameter.location", Location.class, List.class, null)); return new MappedParametersCohortDefinition(cd, "onOrAfter", "startDate", "onOrBefore", "endDate", "encounterTypeList", "encounterTypes", "locationList", "locations", "atLeastCount", "atLeast", "atMostCount", "atMost", "formList", "forms"); }
Source:
<code>public String getDisplayName() { <START> return ""; <END> }</code><technical_language>worth a displayName</technical_language>

Target:
public String getDisplayName() { return Messages.Plot_Series(); }
Source:
<code>@Override public Class getClass(int typeId, ClassLoader ldr) throws ClassNotFoundException, IgniteCheckedException { String clsName; ClassNotFoundException err = null; <START> for (byte platformId : new byte[] {JAVA_ID, DOTNET_ID}) { <END> try { clsName = getClassName(platformId, typeId); if (clsName != null) return U.forName(clsName, ldr, clsFilter); } catch (ClassNotFoundException e) { if (err == null) err = e; } } if (err != null) throw err; throw new ClassNotFoundException("Unknown type ID: " + typeId); }</code><technical_language>JAVA_ID - in cases, platform type resolved, a Java type</technical_language>

Target:
@Override public Class getClass(int typeId, ClassLoader ldr) throws ClassNotFoundException, IgniteCheckedException { String clsName = getClassName(JAVA_ID, typeId); if (clsName == null) throw new ClassNotFoundException("Unknown type ID: " + typeId); return U.forName(clsName, ldr, clsFilter); }
Source:
<code>public CompletableFuture<JobMasterGateway> getJobMasterGateway() { Preconditions.checkState( isRunning(), "JobMaster Gateway is not available during initialization"); try { return jobManagerRunnerFuture.thenCompose(JobManagerRunner::getJobMasterGateway); <START> } catch (Throwable e) { throw new IllegalStateException("JobMaster gateway is not available", e); } <END> }</code><technical_language>is this catch block necessary</technical_language>

Target:
public CompletableFuture<JobMasterGateway> getJobMasterGateway() { Preconditions.checkState( isInitialized(), "JobMaster Gateway is not available during initialization"); return jobManagerRunnerFuture.thenCompose(JobManagerRunner::getJobMasterGateway); }
Source:
<code>public ItemUseHandler getItemHandler() { return e -> { Player p = e.getPlayer(); UUID uuid = p.getUniqueId(); <START> Boolean keepininv = stayininvonuse.getValue(); <END> if (!e.getClickedBlock().isPresent() && !SlimefunPlugin.getGrapplingHookListener().isGrappling(uuid)) { e.cancel(); if (p.getInventory().getItemInOffHand().getType() == Material.BOW) { return; } ItemStack item = e.getItem(); if (item.getType() == Material.LEAD) { if (!keepininv) { item.setAmount(item.getAmount() - 1); } } Vector direction = p.getEyeLocation().getDirection().multiply(2.0); Arrow arrow = p.getWorld().spawn(p.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), Arrow.class); arrow.setShooter(p); arrow.setVelocity(direction); Bat bat = (Bat) p.getWorld().spawnEntity(p.getLocation(), EntityType.BAT); bat.setCanPickupItems(false); bat.setAI(false); bat.setSilent(true); bat.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 100000, 100000)); bat.setLeashHolder(arrow); boolean state = item.getType() != Material.SHEARS; SlimefunPlugin.getGrapplingHookListener().addGrapplingHook(p, arrow, bat, state, despawnTicks.getValue(), keepininv); } }; }</code><technical_language>Please boxed Boolean class, primitive boolean instead</technical_language>

Target:
public ItemUseHandler getItemHandler() { return e -> { Player p = e.getPlayer(); UUID uuid = p.getUniqueId(); boolean consumeOnUseValue = consumeOnUse.getValue(); if (!e.getClickedBlock().isPresent() && !SlimefunPlugin.getGrapplingHookListener().isGrappling(uuid)) { e.cancel(); if (p.getInventory().getItemInOffHand().getType() == Material.BOW) { return; } ItemStack item = e.getItem(); if (item.getType() == Material.LEAD) { if (consumeOnUseValue) { item.setAmount(item.getAmount() - 1); } } Vector direction = p.getEyeLocation().getDirection().multiply(2.0); Arrow arrow = p.getWorld().spawn(p.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), Arrow.class); arrow.setShooter(p); arrow.setVelocity(direction); Bat bat = (Bat) p.getWorld().spawnEntity(p.getLocation(), EntityType.BAT); bat.setCanPickupItems(false); bat.setAI(false); bat.setSilent(true); bat.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 100000, 100000)); bat.setLeashHolder(arrow); boolean state = item.getType() != Material.SHEARS; SlimefunPlugin.getGrapplingHookListener().addGrapplingHook(p, arrow, bat, state, despawnTicks.getValue(), consumeOnUseValue); } }; }
Source:
<code>public void testServiceUsage() { <START> final DomainModelReferenceConverter converter = mock(DomainModelReferenceConverter.class); <END> final VFeaturePathDomainModelReference reference = mock(VFeaturePathDomainModelReference.class); final ServiceRegistration<DomainModelReferenceConverter> converterService = bundleContext.registerService( DomainModelReferenceConverter.class, converter, null); service.getValueProperty(reference); verify(converter).isApplicable(reference); verify(converter).convert(reference); converterService.unregister(); }</code><technical_language>please isapplicable return explicit</technical_language>

Target:
public void testServiceUsage() { final DomainModelReferenceConverter converter = mock(DomainModelReferenceConverter.class); final VFeaturePathDomainModelReference reference = mock(VFeaturePathDomainModelReference.class); when(converter.isApplicable(reference)).thenReturn(0d); final ServiceRegistration<DomainModelReferenceConverter> converterService = bundleContext.registerService( DomainModelReferenceConverter.class, converter, null); service.getValueProperty(reference); verify(converter).isApplicable(reference); verify(converter).convert(reference); converterService.unregister(); }
Source:
<code>public CompletableFuture<Void> downloadAndInstallMod(URL url, @Nullable DoubleProperty progressProperty, @Nullable StringProperty titleProperty) { InstallModTask task = applicationContext.getBean(InstallModTask.class); task.setUrl(url); if (progressProperty != null) { progressProperty.bind(task.progressProperty()); } if (titleProperty != null) { titleProperty.bind(task.titleProperty()); } return taskService.submitTask(task).getFuture() <START> .thenCompose(aVoid -> loadInstalledMods()); <END> }</code><technical_language>Changing this thenAccept thenCompose difference. proper call thenRun anyway, result of previous future is of interest called method return anything</technical_language>

Target:
public CompletableFuture<Void> downloadAndInstallMod(URL url, @Nullable DoubleProperty progressProperty, @Nullable StringProperty titleProperty) { InstallModTask task = applicationContext.getBean(InstallModTask.class); task.setUrl(url); if (progressProperty != null) { progressProperty.bind(task.progressProperty()); } if (titleProperty != null) { titleProperty.bind(task.titleProperty()); } return taskService.submitTask(task).getFuture() .thenRun(this::loadInstalledMods); }
Source:
<code>public void touchSession() { Date now = new Date(); <START> if (now.getTime() - sessionData.getLastTouchTime() <END> > Prefs.getSessionTimeout() * DateUtils.MINUTE_IN_MILLIS) { long sessionLengthSeconds = (sessionData.getLastTouchTime() - sessionData.getStartTime()) / DateUtils.SECOND_IN_MILLIS; log( "length", sessionLengthSeconds, "fromSearch", sessionData.getPagesFromSearch(), "fromRandom", sessionData.getPagesFromRandom(), "fromLanglink", sessionData.getPagesFromLangLink(), "fromInternal", sessionData.getPagesFromInternal(), "fromExternal", sessionData.getPagesFromExternal(), "fromHistory", sessionData.getPagesFromHistory(), "fromSaved", sessionData.getPagesFromSaved(), "fromNearby", sessionData.getPagesFromNearby(), "fromDisambig", sessionData.getPagesFromDisambig(), "fromBack", sessionData.getPagesFromBack(), "totalPages", sessionData.getTotalPages(), "leadLatency", (long) leadSectionLatency.getAverage(), "restLatency", (long) restSectionsLatency.getAverage(), "apiMode", RbSwitch.INSTANCE.isRestBaseEnabled() ? 1 : 0 ); sessionData = new SessionData(); sessionData.setStartTime(now.getTime()); leadSectionLatency.reset(); restSectionsLatency.reset(); } sessionData.setLastTouchTime(now.getTime()); }</code><technical_language>In interest of keeping methods small, I recommend a method encapsulate this logic. Maybe, isEventDue()</technical_language>

Target:
public void touchSession() { if (hasTimedOut()) { logSessionData(); sessionData = new SessionData(); sessionData.setStartTime(System.currentTimeMillis()); } sessionData.setLastTouchTime(System.currentTimeMillis()); }
Source:
<code>public Integer random(int digit_number) { switch (digit_number) { case 1: return new Random().nextInt(9); case 2: <START> return new Random().nextInt(99); <END> case 3: return new Random().nextInt(999); case 4: return new Random().nextInt(9999); case 5: return new Random().nextInt(99999); case 6: return new Random().nextInt(999999); case 7: return new Random().nextInt(9999999); case 8: return new Random().nextInt(99999999); case 9: return new Random().nextInt(999999999); default: return null; } }</code><technical_language>of argument is exclusive, this code generate 99 random number. set this 100</technical_language>

Target:
public Integer random(int digit_number) throws TemplateException { if (digit_number < 1 || digit_number > 9) { throw new TemplateException("Random number " + digit_number + " is out of range", null); } int max = Integer.parseInt(StringUtils.repeat("9", digit_number)); return ThreadLocalRandom.current().nextInt(0, max + 1); }
Source:
<code>public VolumePopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants) { super(eventBus, resources); initListBoxEditors(); initCheckboxEditors(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); ViewIdHandler.idHandler.generateAndSetIds(this); localize(constants); initAddBricksButton(); initBricksCountLabele(); driver.initialize(this); <START> virtStoreOptimiseWarningLabel.setText(constants.newVolumeOptimiseForVirtStoreWarning()); <END> virtStoreOptimiseWarningLabel.setVisible(false); }</code><technical_language>this moved localize() method</technical_language>

Target:
public VolumePopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants) { super(eventBus, resources); initListBoxEditors(); initCheckboxEditors(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); ViewIdHandler.idHandler.generateAndSetIds(this); localize(constants); setVisibilities(); initAddBricksButton(); initBricksCountLabele(); driver.initialize(this); }
Source:
<code>public MongoConnector build() throws SchedulerConfigException { if (connector != null) { validateForConnector(); return connector; } final WriteConcern writeConcern = createWriteConcern(); if (database != null) { validateForDatabase(); return new ExternalMongoConnector(writeConcern, database); } if (client != null) { validateForClient(); return new ExternalMongoConnector(writeConcern, client, dbName); } if (uri != null) { validateForUri(); <START> MongoClientURI mongoUri=new MongoClientURI(uri); <END> return new InternalMongoConnector(writeConcern, mongoUri); } checkNotNull(addresses, "At least one MongoDB address or a MongoDB URI must be specified."); final List<ServerAddress> serverAddresses = collectServerAddresses(); final List<MongoCredential> credentials = createCredentials(); final MongoClientOptions options = createOptions(); return new InternalMongoConnector(writeConcern, serverAddresses, credentials, options, dbName); }</code><technical_language>Please spaces assignment operator</technical_language>

Target:
public MongoConnector build() throws SchedulerConfigException { if (connector != null) { validateForConnector(); return connector; } final WriteConcern writeConcern = createWriteConcern(); if (database != null) { validateForDatabase(); return new ExternalMongoConnector(writeConcern, database); } if (uri != null) { validateForUri(); MongoClientURI mongoUri = new MongoClientURI(uri); if(dbName == null){ dbName = mongoUri.getDatabase(); } return new InternalMongoConnector(writeConcern, mongoUri); } checkNotNull(dbName, "'Database name' parameter is required."); if (client != null) { validateForClient(); return new ExternalMongoConnector(writeConcern, client, dbName); } checkNotNull(addresses, "At least one MongoDB address or a MongoDB URI must be specified."); final List<ServerAddress> serverAddresses = collectServerAddresses(); final List<MongoCredential> credentials = createCredentials(); final MongoClientOptions options = createOptions(); return new InternalMongoConnector(writeConcern, serverAddresses, credentials, options, dbName); }
Source:
<code>public T INTO_VALUES(String... values) { List<List<String>> list = sql().values; if(list.isEmpty()){ list.add(new ArrayList<>()); <START> } <END> int index = list.size() - 1; for (String value : values) { list.get(index).add(value); } return getSelf(); }</code><technical_language>This empty check removed if add element values in constructor</technical_language>

Target:
public T INTO_VALUES(String... values) { List<String> list = sql().valuesList.get(sql().valuesList.size() - 1); for (String value : values) { list.add(value); } return getSelf(); }
Source:
<code>public static void registerMBean(Object mBeanInstance, ObjectName objectName, MBeanServer mBeanServer) throws Exception { try { SecurityActions.registerMBean(mBeanInstance, objectName, mBeanServer); if (log.isTraceEnabled()) { log.tracef("Registered MBean %s under %s", mBeanInstance, objectName); } } catch (InstanceAlreadyExistsException e) { <START> throw CONTAINER.jmxMBeanAlreadyRegistered(objectName); <END> } catch (Exception e) { throw CONTAINER.jmxCouldNotRegisterMBean(objectName, e); } }</code><technical_language>I before. This is proper place handle domain conflicts. done in AbstractJmxRegistration. Also, error message, mentioning cache manager name is specific needed. This is supposedly a generic utility method, remote client</technical_language>

Target:
public static void registerMBean(Object mBeanInstance, ObjectName objectName, MBeanServer mBeanServer) throws Exception { try { SecurityActions.registerMBean(mBeanInstance, objectName, mBeanServer); if (log.isTraceEnabled()) { log.tracef("Registered MBean %s under %s", mBeanInstance, objectName); } } catch (InstanceAlreadyExistsException e) { log.couldNotRegisterObjectName(objectName, e); throw e; } }
Source:
<code>public Void execute(Context context) { KieSession ksession = ((RegistryContext) context).lookup( KieSession.class ); ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId); DynamicNodeInstance dynamicContext = (DynamicNodeInstance) ((WorkflowProcessInstanceImpl) processInstance).getNodeInstances(true).stream() .filter(ni -> (ni instanceof DynamicNodeInstance) && stageId.equals(ni.getNode().getMetaData().get("UniqueId"))) .findFirst() <START> .orElse(null); <END> if (dynamicContext == null) { throw new StageNotFoundException("No stage found with id " + stageId); } dynamicContext.signalEvent(fragmentName, data); return null; }</code><technical_language>this changed orElseThrow</technical_language>

Target:
public Void execute(Context context) { KieSession ksession = ((RegistryContext) context).lookup( KieSession.class ); ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId); DynamicNodeInstance dynamicContext = (DynamicNodeInstance) ((WorkflowProcessInstanceImpl) processInstance).getNodeInstances(true).stream() .filter(ni -> (ni instanceof DynamicNodeInstance) && stageId.equals(ni.getNode().getMetaData().get("UniqueId"))) .findFirst() .orElseThrow(() -> new StageNotFoundException("No stage found with id " + stageId)); dynamicContext.signalEvent(fragmentName, data); return null; }
Source:
<code><START> public static File locateExecutable() throws IngestModule.IngestModuleException, IOException { <END> File exeFile = null; Path execName = null; String photorec_linux_directory = "/usr/bin"; if (PlatformUtil.isWindowsOS()) { execName = Paths.get(PHOTOREC_DIRECTORY, PHOTOREC_EXECUTABLE); exeFile = InstalledFileLocator.getDefault().locate(execName.toString(), PhotoRecCarverFileIngestModule.class.getPackage().getName(), false); } else { File usrBin = new File("/usr/bin/photorec"); File usrLocalBin = new File("/usr/local/bin/photorec"); if (usrBin.canExecute() && usrBin.exists() && !usrBin.isDirectory()) { photorec_linux_directory = "/usr/bin"; }else if(usrLocalBin.canExecute() && usrLocalBin.exists() && !usrLocalBin.isDirectory()){ photorec_linux_directory = "/usr/local/bin"; }else{ exeFile = null; } execName = Paths.get(photorec_linux_directory, PHOTOREC_LINUX_EXECUTABLE); exeFile = new File(execName.toString()); } if (null == exeFile) { throw new IngestModule.IngestModuleException(Bundle.missingExecutable_message()); } if (!exeFile.canExecute()) { throw new IngestModule.IngestModuleException(Bundle.cannotRunExecutable_message()); } return exeFile; }</code><technical_language>is throwing IOException? catch in this method deal appropriately</technical_language>

Target:
public static File locateExecutable() throws IngestModule.IngestModuleException { File exeFile = null; Path execName = null; String photorec_linux_directory = "/usr/bin"; if (PlatformUtil.isWindowsOS()) { execName = Paths.get(PHOTOREC_DIRECTORY, PHOTOREC_EXECUTABLE); exeFile = InstalledFileLocator.getDefault().locate(execName.toString(), PhotoRecCarverFileIngestModule.class.getPackage().getName(), false); } else { File usrBin = new File("/usr/bin/photorec"); File usrLocalBin = new File("/usr/local/bin/photorec"); if (usrBin.canExecute() && usrBin.exists() && !usrBin.isDirectory()) { photorec_linux_directory = "/usr/bin"; }else if(usrLocalBin.canExecute() && usrLocalBin.exists() && !usrLocalBin.isDirectory()){ photorec_linux_directory = "/usr/local/bin"; }else{ throw new IngestModule.IngestModuleException("Photorec not found"); } execName = Paths.get(photorec_linux_directory, PHOTOREC_LINUX_EXECUTABLE); exeFile = new File(execName.toString()); } if (null == exeFile) { throw new IngestModule.IngestModuleException(Bundle.missingExecutable_message()); } if (!exeFile.canExecute()) { throw new IngestModule.IngestModuleException(Bundle.cannotRunExecutable_message()); } return exeFile; }
Source:
<code>protected void addShards() { MongoDBRouter router = getParent().getAttribute(MongoDBShardedDeployment.ROUTER_CLUSTER).getAttribute(MongoDBRouterCluster.ANY_ROUTER); if (router == null) return; MongoDBClientSupport client; try { client = MongoDBClientSupport.forServer(router); } catch (UnknownHostException e) { throw Exceptions.propagate(e); } for (Entity member : this.getMembers()) { if (member.getAttribute(Startable.SERVICE_UP) && !addedMembers.contains(member)) { MongoDBServer primary = null; primary = member.getAttribute(MongoDBReplicaSet.PRIMARY_ENTITY); String replicaSetURL = ((MongoDBReplicaSet) member).getName() + "/" <START> + Strings.removeFromStart(primary.getAttribute(MongoDBServer.MONGO_SERVER_ENDPOINT), "http://"); <END> LOG.info("Using to add shard URL {}...", router, replicaSetURL); client.addShardToRouter(replicaSetURL); addedMembers.add(member); } } }</code><technical_language>simplify line assigning url a variable; assigning variable endpoint:port extracting url here</technical_language>

Target:
protected void addShards() { MongoDBRouter router = getParent().getAttribute(MongoDBShardedDeployment.ROUTER_CLUSTER).getAttribute(MongoDBRouterCluster.ANY_RUNNING_ROUTER); if (router == null) return; MongoDBClientSupport client; try { client = MongoDBClientSupport.forServer(router); } catch (UnknownHostException e) { throw Exceptions.propagate(e); } for (Entity member : this.getMembers()) { if (member.getAttribute(Startable.SERVICE_UP) && !addedMembers.contains(member)) { MongoDBServer primary = member.getAttribute(MongoDBReplicaSet.PRIMARY_ENTITY); String addr = Strings.removeFromStart(primary.getAttribute(MongoDBServer.MONGO_SERVER_ENDPOINT), "http://"); String replicaSetURL = ((MongoDBReplicaSet) member).getName() + "/" + addr; LOG.info("Using to add shard URL {}...", router, replicaSetURL); client.addShardToRouter(replicaSetURL); addedMembers.add(member); } } }