auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private FeedbackSessionAttributes extractFeedbackSessionData() { <START> InstructorFeedbackAddAction feedbackData = new InstructorFeedbackAddAction(); <END> return feedbackData.extractFeedbackSessionData(); }</code><technical_language>This dependency is right. actions independent of other. If common methods, actions inheriting abstract class. a InstructorCourseInstructorAbstractAction classes inheriting for example</technical_language>

Target:
protected FeedbackSessionAttributes extractFeedbackSessionData() { return super.extractFeedbackSessionData(); }
Source:
<code>public void setUp() { <START> final Handle h = this.dbRule.getSharedHandle(); <END> h.execute("CREATE TABLE uniq (id INTEGER PRIMARY KEY)"); }</code><technical_language>I avoid declaring this handle invoke execute shared handle</technical_language>

Target:
public void setUp() { this.dbRule.getSharedHandle().execute("CREATE TABLE uniq (id INTEGER PRIMARY KEY)"); }
Source:
<code>public Page<PoolTaskRest> findByUser(@Parameter(value = "uuid") UUID userID, Pageable pageable) { List<PoolTask> tasks = null; try { Context context = obtainContext(); EPerson ep = epersonService.find(context, userID); tasks = poolTaskService.findByEperson(context, ep); } catch (SQLException | AuthorizeException | IOException e) { <START> throw new RuntimeException(e.getMessage(), e); <END> } Page<PoolTaskRest> page = utils.getPage(tasks, pageable).map(converter); return page; }</code><technical_language>Again, a more useful error message. "Could find Pooled Tasks for user ID" + userID</technical_language>

Target:
public Page<PoolTaskRest> findByUser(@Parameter(value = "uuid") UUID userID, Pageable pageable) { List<PoolTask> tasks = null; try { Context context = obtainContext(); EPerson currentUser = context.getCurrentUser(); if (currentUser == null) { throw new RESTAuthorizationException( "This endpoint is available only to logged-in user" + " to search for their own pool tasks or the admins"); } if (authorizeService.isAdmin(context) || userID.equals(currentUser.getID())) { EPerson ep = epersonService.find(context, userID); tasks = poolTaskService.findByEperson(context, ep); } else { throw new RESTAuthorizationException("Only administrators can search for pool tasks of other users"); } } catch (AuthorizeException e) { throw new RESTAuthorizationException(e); } catch (SQLException | IOException e) { throw new RuntimeException(e.getMessage(), e); } Page<PoolTaskRest> page = utils.getPage(tasks, pageable).map(converter); return page; }
Source:
<code>private synchronized void onReceipt(TransactionReceipt receipt, Block block, PendingTransactionState state) { ByteArrayWrapper txHashW = new ByteArrayWrapper(receipt.getTransaction().getHash()); if (contractAddressFilter.matchBloom(receipt.getBloomFilter())) { int txCount = 0; List<EventData> matchedTxs = new ArrayList<>(); for (LogInfo logInfo : receipt.getLogInfoList()) { <START> if (contractAddressFilter.matchBloom(logInfo.getBloom()) && <END> contractAddressFilter.matchesExactly(logInfo)) { EventData matchedTx = onLogMatch(logInfo, block, receipt, txCount, state); if (matchedTx != null) { txCount++; matchedTxs.add(matchedTx); } } } if (!matchedTxs.isEmpty()) { onEventData(receipt, block, state, matchedTxs); } } else if (state == PendingTransactionState.DROPPED && pendings.containsKey(txHashW)) { PendingEvent event = pendings.get(txHashW); onEventData(receipt, block, state, event.eventData); } }</code><technical_language>Current implementation allow user instantiate a listener topics filtering out of box. I worth extended feature</technical_language>

Target:
private synchronized void onReceipt(TransactionReceipt receipt, Block block, PendingTransactionState state) { if (!initialized) throw new RuntimeException("Event listener should be initialized"); byte[] txHash = receipt.getTransaction().getHash(); if (logFilter.matchBloom(receipt.getBloomFilter())) { int txCount = 0; List<EventData> matchedTxs = new ArrayList<>(); for (LogInfo logInfo : receipt.getLogInfoList()) { if (logFilter.matchBloom(logInfo.getBloom()) && logFilter.matchesExactly(logInfo)) { EventData matchedTx = onLogMatch(logInfo, block, receipt, txCount, state); if (matchedTx != null) { txCount++; matchedTxs.add(matchedTx); } } } if (!matchedTxs.isEmpty()) { onEventData(receipt, block, state, matchedTxs); } } else if (state == PendingTransactionState.DROPPED && pendings.containsKey(txHash)) { PendingEvent event = pendings.get(txHash); onEventData(receipt, block, state, event.eventData); } }
Source:
<code>private void processEmails(List<EmailMessage> emails, AbstractFile abstractFile) { List<AbstractFile> derivedFiles = new ArrayList<>(); EmailMessageThreader threader = new EmailMessageThreader(); <START> threader.threadMessages(emails, String.format("%d", abstractFile.getId())); <END> for (EmailMessage email : emails) { BlackboardArtifact msgArtifact = addEmailArtifact(email, abstractFile); if ((msgArtifact != null) && (email.hasAttachment())) { derivedFiles.addAll(handleAttachments(email.getAttachments(), abstractFile, msgArtifact )); } } if (derivedFiles.isEmpty() == false) { for (AbstractFile derived : derivedFiles) { services.fireModuleContentEvent(new ModuleContentEvent(derived)); } } context.addFilesToJob(derivedFiles); services.fireModuleDataEvent(new ModuleDataEvent(EmailParserModuleFactory.getModuleName(), BlackboardArtifact.ARTIFACT_TYPE.TSK_EMAIL_MSG)); }</code><technical_language>Add try/catch</technical_language>

Target:
private void processEmails(List<EmailMessage> emails, AbstractFile abstractFile) { List<AbstractFile> derivedFiles = new ArrayList<>(); try{ EmailMessageThreader.threadMessages(emails, String.format("%d", abstractFile.getId())); } catch(Exception ex) { logger.log(Level.WARNING, String.format("Exception thrown parsing emails from %s", abstractFile.getName()), ex); } for (EmailMessage email : emails) { BlackboardArtifact msgArtifact = addEmailArtifact(email, abstractFile); if ((msgArtifact != null) && (email.hasAttachment())) { derivedFiles.addAll(handleAttachments(email.getAttachments(), abstractFile, msgArtifact )); } } if (derivedFiles.isEmpty() == false) { for (AbstractFile derived : derivedFiles) { services.fireModuleContentEvent(new ModuleContentEvent(derived)); } } context.addFilesToJob(derivedFiles); services.fireModuleDataEvent(new ModuleDataEvent(EmailParserModuleFactory.getModuleName(), BlackboardArtifact.ARTIFACT_TYPE.TSK_EMAIL_MSG)); }
Source:
<code>private static String exceptionName(TypeTree typeTree) { switch (typeTree.kind()) { case IDENTIFIER: return ((IdentifierTree) typeTree).name(); case MEMBER_SELECT: return ExpressionsHelper.concatenate((MemberSelectExpressionTree) typeTree); default: <START> return null; <END> } }</code><technical_language>returning ? I prefer stick throwing explicit exception. AFAI understand return test in existing test : create a dedicated test for case explicit failure</technical_language>

Target:
private static String exceptionName(TypeTree typeTree) { switch (typeTree.kind()) { case IDENTIFIER: return ((IdentifierTree) typeTree).name(); case MEMBER_SELECT: return ExpressionsHelper.concatenate((MemberSelectExpressionTree) typeTree); default: throw new IllegalStateException("Exceptions can not be specified other than with an identifier or a fully qualified name."); } }
Source:
<code>public Observable<CategoryItem> searchAll(String term, List<String> imageTitleList) { if (TextUtils.isEmpty(term)) { Observable<CategoryItem> categoryItemObservable = gpsCategories() .concatWith(titleCategories(imageTitleList)); if (hasDirectCategories()) { categoryItemObservable.concatWith(directCategories().concatWith(recentCategories())); } return categoryItemObservable; } if (cacheContainsKey(term)) { return Observable.fromIterable(getCachedCategories(term)) .map(name -> new CategoryItem(name, false)); } <START> return categoryClient <END> .searchCategories(term, SEARCH_CATS_LIMIT) .map(name -> new CategoryItem(name, false)); }</code><technical_language>searchCategories allcategories return kind of responses. supposed allcategories searches based prefix. For if search for christchurch APIs response different. for allcategories: <LINK_0> for searchCategories: <LINK_1></technical_language>

Target:
public Observable<CategoryItem> searchAll(String term, List<String> imageTitleList) { if (TextUtils.isEmpty(term)) { Observable<CategoryItem> categoryItemObservable = gpsCategories() .concatWith(titleCategories(imageTitleList)); if (hasDirectCategories()) { categoryItemObservable.concatWith(directCategories().concatWith(recentCategories())); } return categoryItemObservable; } if (cacheContainsKey(term)) { return Observable.fromIterable(getCachedCategories(term)) .map(name -> new CategoryItem(name, false)); } return categoryClient .searchCategoriesForPrefix(term, SEARCH_CATS_LIMIT) .map(name -> new CategoryItem(name, false)); }
Source:
<code>public Set<String> getRequiredParameterNames() { <START> Set<String> result = new HashSet<>(groupId.getRequiredParameterNames()); <END> result.addAll(artifactId.getRequiredParameterNames()); return result; }</code><technical_language>suggestion Set<String> result = new HashSet<>(); if (groupId != null) result.addAll(groupId.getRequiredParameterNames());</technical_language>

Target:
public Set<String> getRequiredParameterNames() { Set<String> result = new HashSet<>(); if (groupId != null) result.addAll(groupId.getRequiredParameterNames()); if (artifactId != null) result.addAll(artifactId.getRequiredParameterNames()); return result; }
Source:
<code>private boolean removeUDAFInSchema(String functionName) { for (int idx = 0; idx < m_schema.children.size(); idx++) { VoltXMLElement func = m_schema.children.get(idx); if ("ud_function".equals(func.name)) { String fnm = func.attributes.get("name"); if (fnm != null && functionName.equals(fnm)) { m_schema.children.remove(idx); m_tracker.addDroppedFunction(functionName); <START> m_logger.debug(String.format("Removed XML for" <END> + " function named %s", functionName)); return true; } } } return false; }</code><technical_language>For debug trace log messages if performing string concatenation formatting for log message surround call logger a check if log level is enabled</technical_language>

Target:
private boolean removeUDAFInSchema(String functionName) { for (int idx = 0; idx < m_schema.children.size(); idx++) { VoltXMLElement func = m_schema.children.get(idx); if ("ud_function".equals(func.name)) { String fnm = func.attributes.get("name"); if (fnm != null && functionName.equals(fnm)) { m_schema.children.remove(idx); m_tracker.addDroppedFunction(functionName); if (m_logger.isDebugEnabled()) { m_logger.debug(String.format("Removed XML for" + " function named %s", functionName)); } return true; } } } return false; }
Source:
<code>protected ViewModel onValidSubmit(HttpServletRequest request, HttpServletResponse response, Form form) { Application application = (Application) request.getAttribute(Application.class.getName()); String email = form.getFieldValue("email"); Map<String, Object> model = new HashMap<String, Object>(); try { request.setAttribute("form", form); AccountStore accountStore = accountStoreResolver.getAccountStore(request, response); if (accountStore != null) { application.sendPasswordResetEmail(email, accountStore); } else { application.sendPasswordResetEmail(email); } } catch (ResourceException e) { if (isJsonPreferred(request, response)) { <START> model.put("status", 200); <END> model.put("message", "OK"); return new DefaultViewModel("stormpathJsonView", model); } if (e.getCode() != 404) { throw e; } } if (isJsonPreferred(request, response)) { model.put("status", 200); model.put("message", "OK"); return new DefaultViewModel("stormpathJsonView", model); } return new DefaultViewModel(nextUri).setRedirect(true); }</code><technical_language>HttpServletResponse.SC_OK instead of hardcoding 200 please</technical_language>

Target:
protected ViewModel onValidSubmit(HttpServletRequest request, HttpServletResponse response, Form form) { Application application = (Application) request.getAttribute(Application.class.getName()); String email = form.getFieldValue("email"); try { request.setAttribute("form", form); AccountStore accountStore = accountStoreResolver.getAccountStore(request, response); if (accountStore != null) { application.sendPasswordResetEmail(email, accountStore); } else { application.sendPasswordResetEmail(email); } } catch (ResourceException e) { if (isJsonPreferred(request, response)) { return new DefaultViewModel("stormpathJsonView"); } } if (isJsonPreferred(request, response)) { return new DefaultViewModel("stormpathJsonView"); } return new DefaultViewModel(nextUri).setRedirect(true); }
Source:
<code>void run() throws Exception; } @AfterEach void tearDown(TestUtils setup, TestReference reference) throws Exception { <START> runAsUser(setup, U2_USERNAME, USERS_PWD, () -> { <END> setup.gotoPage("Main", "WebHome"); NotificationsTrayPage tray = new NotificationsTrayPage(); tray.clearAllNotifications(); }); runAsSuperAdmin(setup, () -> setup.deletePage(reference)); }</code><technical_language>deleting users test instead</technical_language>

Target:
void run() throws Exception; } @Test @Order(1) void documentBody(TestUtils setup, TestReference reference) throws Exception { String pageName = "Mention Test Page"; runAsSuperAdmin(setup, () -> { setup.createUser(U1_USERNAME, USERS_PWD, null); setup.createUser(U2_USERNAME, USERS_PWD, null); }); runAsUser(setup, U1_USERNAME, USERS_PWD, () -> { setup.deletePage(reference); setup.createPage(reference, "{{mention reference=\"xwiki:XWiki.U2\" style=\"LOGIN\" anchor=\"test-mention-1\" /}}", pageName); }); runAsUser(setup, U2_USERNAME, USERS_PWD, () -> { setup.gotoPage("Main", "WebHome"); waitOnNotificationCount("xwiki:XWiki.U2", "xwiki", 1); reload(setup); NotificationsTrayPage tray = new NotificationsTrayPage(); tray.showNotificationTray(); assertEquals(1, tray.getNotificationsCount()); assertEquals(1, tray.getUnreadNotificationsCount()); assertEquals("mentions.mention", tray.getNotificationType(0)); String notificationContent = tray.getNotificationContent(0); String expected = "You have received one mention."; assertTrue(notificationContent.contains(expected), String.format("Notification content should contain [%s] but is [%s].", expected, notificationContent)); final WebElement rootElement = tray.getNotificationsButton(); MentionNotificationPage mentionNotificationPage = new MentionNotificationPage(rootElement); mentionNotificationPage.openGroup(0); assertEquals("mentioned you on page Mention Test Page", mentionNotificationPage.getText(0, 0)); assertEquals("U1", mentionNotificationPage.getEmitter(0, 0)); assertTrue(mentionNotificationPage.hasSummary(0, 0)); assertEquals("@U2", mentionNotificationPage.getSummary(0, 0)); tray.clearAllNotifications(); }); }
Source:
<code>private Broker findNewLeader(Broker oldLeader) throws InterruptedException { long retryCnt = 0; while (true) { PartitionMetadata metadata = findLeader(); if (metadata != null) { replicaBrokers.clear(); for (Broker replica : metadata.replicas()) { replicaBrokers.add(new KafkaBroker(replica.host(), replica.port())); } log.debug("Got new Kafka leader metadata : [%s], previous leader : [%s]", metadata, oldLeader); Broker newLeader = metadata.leader(); if (newLeader != null) { if (oldLeader == null || isValidNewLeader(newLeader) || retryCnt != 0) { return newLeader; } } } Thread.sleep(RETRY_INTERVAL); retryCnt++; <START> if (retryCnt >= 3 && (retryCnt - 3) % 5 == 0) { <END> log.warn("cannot find leader for [%s] - [%s] after [%s] retries", topic, partitionId, retryCnt); replicaBrokers.clear(); replicaBrokers.addAll(allBrokers); } } }</code><technical_language>%5</technical_language>

Target:
private Broker findNewLeader(Broker oldLeader) throws InterruptedException { long retryCnt = 0; while (true) { PartitionMetadata metadata = findLeader(); if (metadata != null) { replicaBrokers.clear(); for (Broker replica : metadata.replicas()) { replicaBrokers.add( HostAndPort.fromParts(replica.host(), replica.port()) ); } log.debug("Got new Kafka leader metadata : [%s], previous leader : [%s]", metadata, oldLeader); Broker newLeader = metadata.leader(); if (newLeader != null) { if (oldLeader == null || isValidNewLeader(newLeader) || retryCnt != 0) { return newLeader; } } } Thread.sleep(RETRY_INTERVAL); retryCnt++; if (retryCnt >= 3 && (retryCnt - 3) % 5 == 0) { log.warn("cannot find leader for [%s] - [%s] after [%s] retries", topic, partitionId, retryCnt); replicaBrokers.clear(); replicaBrokers.addAll(allBrokers); } } }
Source:
<code>public void run(SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input) throws Exception { if (input == null) { return; } JavaSparkContext javaSparkContext = context.getSparkContext(); SQLContext sqlContext = new SQLContext(javaSparkContext); Set<String> inputCols = new LinkedHashSet<>(); inputCols.add(config.inputCol); List<StructField> structField = SparkUtils.getStructFieldList(input.first().getSchema().getFields(), inputCols); schema = new StructType(structField.toArray(new StructField[structField.size()])); <START> JavaRDD<Row> rowRDD = SparkUtils.convertJavaRddStructuredRecordToJavaRddRows(input, schema); <END> DataFrame documentDF = sqlContext.createDataFrame(rowRDD, schema); Word2Vec word2Vec = new Word2Vec() .setInputCol(config.inputCol + "-transformed") .setVectorSize(config.vectorSize) .setMinCount(config.minCount) .setNumPartitions(config.numPartitions) .setMaxIter(config.numIterations) .setWindowSize(config.windowSize); Word2VecModel model = word2Vec.fit(documentDF); FileSet outputFS = context.getDataset(config.fileSetName); model.save(outputFS.getBaseLocation().append(config.path).toURI().getPath()); }</code><technical_language>need DataFrame version do this conversion. do like: final String fieldName = config.inputCol; final Splitter splitter = config.getSplitt(); JavaRDD<Iterable<String>> textRDD = input.map(new Function<StructuredRecord, Iterable<String>>() { @Override public Iterable<String> call(StructuredRecord input) throws Exception { String text = input.get(fieldName); return splitter.split(text); } }); Word2Vec word2Vec = new Word2Vec() .setVectorSize(config.vectorSize) ... Word2VecModel model = word2Vec.fit(textRDD); model.save(...)</technical_language>

Target:
public void run(SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input) throws Exception { if (input.isEmpty()) { return; } final String fieldName = config.inputCol; JavaRDD<Iterable<String>> textRDD = input.map(new Function<StructuredRecord, Iterable<String>>() { @Override public Iterable<String> call(StructuredRecord input) throws Exception { splitter = (splitter == null) ? Splitter.on(Pattern.compile(config.pattern)) : splitter; return SparkUtils.getInputFieldValue(input, fieldName, splitter); } }); Word2Vec word2Vec = new Word2Vec() .setVectorSize(config.vectorSize) .setMinCount(config.minCount) .setNumPartitions(config.numPartitions) .setNumIterations(config.numIterations) .setWindowSize(config.windowSize); Word2VecModel model = word2Vec.fit(textRDD); FileSet outputFS = context.getDataset(config.fileSetName); model.save(context.getSparkContext().sc(), outputFS.getBaseLocation().append(config.path).toURI().getPath()); }
Source:
<code>public Page<Event> getEvents(Set<String> tenantIds, EventsCriteria criteria, Pager pager) throws Exception { if (isEmpty(tenantIds)) { throw new IllegalArgumentException("TenantIds must be not null"); } List<Event> events = new ArrayList<>(); if (tenantIds.size() == 1) { events.addAll(getEvents(tenantIds.iterator().next(), criteria)); } else { <START> TreeSet<String> orderedTenantsIds = new TreeSet<>(tenantIds); <END> List<Future> futures = new ArrayList<>(); orderedTenantsIds.stream().forEach(tenantId -> { futures.add(executor.submit(() -> { try { List<Event> tenantEvents = getEvents(tenantId, criteria); synchronized (events) { events.addAll(tenantEvents); } } catch (Exception e) { msgLog.errorDatabaseException(e.getMessage()); } })); }); futures.stream().forEach(f -> { try { f.get(); } catch (Exception e) { msgLog.errorDatabaseException(e.getMessage()); } }); } if (events.isEmpty()) { return new Page<>(events, pager, 0); } else { return prepareEventsPage(events, pager); } }</code><technical_language>trivial: orderedTenantsIds -> orderedTenantIds</technical_language>

Target:
public Page<Event> getEvents(Set<String> tenantIds, EventsCriteria criteria, Pager pager) throws Exception { if (isEmpty(tenantIds)) { throw new IllegalArgumentException("TenantIds must be not null"); } List<Event> events = new ArrayList<>(); if (tenantIds.size() == 1) { events.addAll(getEvents(tenantIds.iterator().next(), criteria)); } else { TreeSet<String> orderedTenantIds = new TreeSet<>(tenantIds); List<Future> futures = new ArrayList<>(); orderedTenantIds.stream().forEach(tenantId -> { futures.add(executor.submit(() -> { try { List<Event> tenantEvents = getEvents(tenantId, criteria); synchronized (events) { events.addAll(tenantEvents); } } catch (Exception e) { msgLog.errorDatabaseException(e.getMessage()); } })); }); futures.stream().forEach(f -> { try { f.get(); } catch (Exception e) { msgLog.errorDatabaseException(e.getMessage()); } }); } if (events.isEmpty()) { return new Page<>(events, pager, 0); } else { return prepareEventsPage(events, pager); } }
Source:
<code>public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { PluginResult.Status status = PluginResult.Status.OK; String result = ""; try { if (action.equals("clearCache")) { this.clearCache(); } else if (action.equals("show")) { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { webView.getPluginManager().postMessage("spinner", "stop"); } }); } else if (action.equals("loadUrl")) { this.loadUrl(args.getString(0), args.optJSONObject(1)); } else if (action.equals("cancelLoadUrl")) { } else if (action.equals("clearHistory")) { this.clearHistory(); } else if (action.equals("backHistory")) { this.backHistory(); } else if (action.equals("overrideButton")) { this.overrideButton(args.getString(0), args.getBoolean(1)); } else if (action.equals("overrideBackbutton")) { this.overrideBackbutton(args.getBoolean(0)); } else if (action.equals("exitApp")) { this.exitApp(); } else if (action.equals("messageChannel")) { messageChannel = callbackContext; <START> if(pendingResume != null) { <END> sendEventMessage(pendingResume); pendingResume = null; } return true; } callbackContext.sendPluginResult(new PluginResult(status, result)); return true; } catch (JSONException e) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return false; } }</code><technical_language>nit: space 'if' line 342</technical_language>

Target:
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { PluginResult.Status status = PluginResult.Status.OK; String result = ""; try { if (action.equals("clearCache")) { this.clearCache(); } else if (action.equals("show")) { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { webView.getPluginManager().postMessage("spinner", "stop"); } }); } else if (action.equals("loadUrl")) { this.loadUrl(args.getString(0), args.optJSONObject(1)); } else if (action.equals("cancelLoadUrl")) { } else if (action.equals("clearHistory")) { this.clearHistory(); } else if (action.equals("backHistory")) { this.backHistory(); } else if (action.equals("overrideButton")) { this.overrideButton(args.getString(0), args.getBoolean(1)); } else if (action.equals("overrideBackbutton")) { this.overrideBackbutton(args.getBoolean(0)); } else if (action.equals("exitApp")) { this.exitApp(); } else if (action.equals("messageChannel")) { synchronized(messageChannelLock) { messageChannel = callbackContext; if (pendingResume != null) { sendEventMessage(pendingResume); pendingResume = null; } } return true; } callbackContext.sendPluginResult(new PluginResult(status, result)); return true; } catch (JSONException e) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return false; } }
Source:
<code>public DummyExchangeAndWalletAndSource(String fiatCurrency, String cryptoCurrency, String walletAddress) throws IllegalArgumentException { if (fiatCurrency == null || cryptoCurrency == null) { throw new NullPointerException("Fiat and crypto currency has to be specified."); } if (cryptoCurrency.equals(Currencies.BTC) || cryptoCurrency.equals(Currencies.ETH) || cryptoCurrency.equals(Currencies.DASH) || cryptoCurrency.equals(Currencies.XMR) || cryptoCurrency.equals(Currencies.LTC)) { if (walletAddress != null) { <START> throw new IllegalArgumentException("Build in wallet is used for BTC, LTC, ETH, DASH, XMR crypto currencies."); <END> } } else { if (walletAddress == null || "".equals(walletAddress)) { throw new IllegalArgumentException("Wallet address has to be specified."); } this.walletAddress = walletAddress; } this.cryptoCurrency = cryptoCurrency; this.fiatCurrency = fiatCurrency; }</code><technical_language>Build in -> Built-in</technical_language>

Target:
public DummyExchangeAndWalletAndSource(String fiatCurrency, String cryptoCurrency, String walletAddress) throws IllegalArgumentException { if (fiatCurrency == null || cryptoCurrency == null) { throw new NullPointerException("Fiat and crypto currency has to be specified."); } if (cryptoCurrency.equals(Currencies.BTC) || cryptoCurrency.equals(Currencies.ETH) || cryptoCurrency.equals(Currencies.DASH) || cryptoCurrency.equals(Currencies.XMR) || cryptoCurrency.equals(Currencies.LTC)) { if (walletAddress != null) { throw new IllegalArgumentException("Built-in wallet is used for BTC, LTC, ETH, DASH, XMR crypto currencies."); } } else { if (walletAddress == null || "".equals(walletAddress)) { throw new IllegalArgumentException("Wallet address has to be specified."); } this.walletAddress = walletAddress; } this.cryptoCurrency = cryptoCurrency; this.fiatCurrency = fiatCurrency; }
Source:
<code>private void checkIfDeleteIsAllowed(EntitySelection entitySelection, XClassBreakingQuestion question) { DocumentReference documentReference = (DocumentReference) entitySelection.getEntityReference(); String query = "select distinct doc.fullName from XWikiDocument doc, BaseObject obj where " + "doc.fullName=obj.name and obj.className=:className"; String serializedReference = serializer.serialize(documentReference); String className = serializedReference.substring(serializedReference.indexOf(":") + 1); try { List<String> results = this.queryManager.createQuery(query, Query.HQL) .bindValue("className", className) <START> .setWiki(documentReference.getWikiReference().getName()).setLimit(10) <END> .<String>execute(); if (results.isEmpty()) { question.markAsFreePage(entitySelection); } else { for (String documentObjectName : results) { question.markImpactedObject(entitySelection, serializedReference, documentObjectName); } } } catch (QueryException e) { e.printStackTrace(); } }</code><technical_language>retrieve objects of other wikis a problem. official limitation of classes in wiki</technical_language>

Target:
private void checkIfDeleteIsAllowed(EntitySelection entitySelection, XClassBreakingQuestion question) { int queryLimit = 25; DocumentReference classReference = (DocumentReference) entitySelection.getEntityReference(); String query = "select distinct obj.name from BaseObject obj where obj.className=:className " + "order by obj.name asc"; String className = localSerializer.serialize(classReference); try { List<String> results = this.queryManager.createQuery(query, Query.HQL) .setLimit(queryLimit) .bindValue("className", className) .setWiki(classReference.getWikiReference().getName()) .<String>execute(); if (results.isEmpty()) { question.markAsFreePage(entitySelection); } else { if (results.size() == queryLimit) { question.setObjectsPotentiallyHidden(true); } for (String documentObjectName : results) { EntityReference documentObjectReference = this.resolver.resolve(documentObjectName, EntityType.DOCUMENT, classReference); question.markImpactedObject(entitySelection, documentObjectReference); } } } catch (QueryException e) { logger.error("Error while executing query to retrieve objects linked to an XClass.", e); } }
Source:
<code>public FeedbackQuestionAttributes createFeedbackQuestionNoIntegrityCheck( <START> FeedbackQuestionAttributes fqa, int questionNumber) throws InvalidParametersException, <END> EntityDoesNotExistException { fqa.questionNumber = questionNumber; fqa.removeIrrelevantVisibilityOptions(); return fqDb.createFeedbackQuestionWithoutIntegrityCheck(fqa); }</code><technical_language>write throws InvalidParametersException next line (with EntityDoesNotExistException)</technical_language>

Target:
public FeedbackQuestionAttributes createFeedbackQuestionNoIntegrityCheck( FeedbackQuestionAttributes fqa, int questionNumber) throws InvalidParametersException { fqa.questionNumber = questionNumber; fqa.removeIrrelevantVisibilityOptions(); return fqDb.createFeedbackQuestionWithoutIntegrityCheck(fqa); }
Source:
<code>private static List<Allele> makeAlleles(Collection<Allele> alleles) { final List<Allele> alleleList = new ArrayList<>(alleles.size()); boolean sawRef = false; for ( final Allele a : alleles ) { for ( int i = 0; i < alleleList.size(); i++ ) { <START> if ( a.equals(alleleList.get(i), true) ) { <END> throw new IllegalArgumentException("Duplicate allele added to VariantContext: " + a); } } if ( a.isReference() ) { if ( sawRef ) throw new IllegalArgumentException("Alleles for a VariantContext must contain at most one reference allele: " + alleles); alleleList.add(0, a); sawRef = true; } else alleleList.add(a); } if ( alleleList.isEmpty() ) throw new IllegalArgumentException("Cannot create a VariantContext with an empty allele list"); if ( alleleList.get(0).isNonReference() ) throw new IllegalArgumentException("Alleles for a VariantContext must contain at least one reference allele: " + alleles); return alleleList; }</code><technical_language>this a doubly indexed array? faster</technical_language>

Target:
private static List<Allele> makeAlleles(Collection<Allele> alleles) { final List<Allele> alleleList = new ArrayList<>(alleles.size()); boolean sawRef = false; for ( final Allele a : alleles ) { for (int i = 0, alleleListSize = alleleList.size(); i < alleleListSize; i++) { if (a.equals(alleleList.get(i), true)) { throw new IllegalArgumentException("Duplicate allele added to VariantContext: " + a); } } if ( a.isReference() ) { if ( sawRef ) throw new IllegalArgumentException("Alleles for a VariantContext must contain at most one reference allele: " + alleles); alleleList.add(0, a); sawRef = true; } else alleleList.add(a); } if ( alleleList.isEmpty() ) throw new IllegalArgumentException("Cannot create a VariantContext with an empty allele list"); if ( alleleList.get(0).isNonReference() ) throw new IllegalArgumentException("Alleles for a VariantContext must contain at least one reference allele: " + alleles); return alleleList; }
Source:
<code><START> public JdbcConnectivityParamsState( <END> String name, String driverClass, String url, String user, String password, boolean pooling, Optional<String> jar, Optional<String> prepareStatement, Optional<String> kerberosPrincipal, Optional<String> kerberosKeytab) { this.name = name; this.driverClass = driverClass; this.url = url; this.user = user; this.password = password; this.pooling = pooling; this.jar = jar; this.prepareStatement = prepareStatement; this.kerberosPrincipal = kerberosPrincipal; this.kerberosKeytab = kerberosKeytab; }</code><technical_language>create builder - number of constuructor arguments is big</technical_language>

Target:
private JdbcConnectivityParamsState( String name, String driverClass, String url, String user, String password, boolean pooling, Optional<String> jar, Optional<String> prepareStatement, Optional<String> kerberosPrincipal, Optional<String> kerberosKeytab) { this.name = requireNonNull(name, "name is null"); this.driverClass = requireNonNull(driverClass, "driverClass is null"); this.url = requireNonNull(url, "url is null"); this.user = requireNonNull(user, "user is null"); this.password = requireNonNull(password, "password is null"); this.pooling = pooling; this.jar = requireNonNull(jar, "jar is null"); this.prepareStatement = requireNonNull(prepareStatement, "prepareStatement is null"); this.kerberosPrincipal = requireNonNull(kerberosPrincipal, "kerberosPrincipal is null"); this.kerberosKeytab = requireNonNull(kerberosKeytab, "kerberosKeytab is null"); }
Source:
<code>public void setUp() { h = dbRule.getSharedHandle(); <START> h.registerRowMapper(ImmutablesMapperFactory.mapImmutable(Train.class, ImmutableTrain.class, ImmutableTrain::builder)); <END> h.execute("create table train (name varchar, carriages int, observation_car boolean)"); dao = h.attach(Dao.class); }</code><technical_language>Feels want annotations register Immutables mappers, e.g. @RegisterImmutablesMapper(value = Train.class) annotation. impl builder method name default attributes for Immutable* Immutable*.builder(), respectively</technical_language>

Target:
public void setUp() { h = dbRule.getSharedHandle(); h.execute("create table train (name varchar, carriages int, observation_car boolean)"); dao = h.attach(Dao.class); }
Source:
<code>private void assertPaginatedClients(int start, int end, List<ClientRepresentation> actual) { List<String> expected = new LinkedList<>(); for (int i = start; i <= end; i++) { expected.add("ccx-" + (i < 10 ? "0" + i : i)); } List<String> a = actual.stream().map(rep -> rep.getClientId()).collect(Collectors.toList()); assertThat(a, Matchers.hasSize(expected.size())); <START> assertThat(a, Matchers.containsInAnyOrder(expected.toArray())); <END> }</code><technical_language>check in order clients sorted</technical_language>

Target:
private void assertPaginatedClients(int start, int end, List<ClientRepresentation> actual) { List<String> expected = new LinkedList<>(); for (int i = start; i <= end; i++) { expected.add("ccx-" + (i < 10 ? "0" + i : i)); } List<String> a = actual.stream().map(rep -> rep.getClientId()).collect(Collectors.toList()); assertThat(a, is(expected)); }
Source:
<code>public void setup(){ MockitoAnnotations.initMocks(this); <START> executorService = Executors.newCachedThreadPool(); <END> }</code><technical_language>needed</technical_language>

Target:
public void setup(){ MockitoAnnotations.initMocks(this); }
Source:
<code>private int getUpdatedCaretPosition(StringBuilder currentCalculatedMessage, int currentCaretPosition, CommitMessageWithCaretPosition messageWithPosition, ICommitMessageProvider2 provider) { int pos = currentCaretPosition; <START> if (!isCaretPositionSet) { <END> pos += currentCalculatedMessage.length(); if (currentCalculatedMessage.length() > 0) { pos += MESSAGE_SEPARATOR.length(); } pos += messageWithPosition.getDesiredCaretPosition(); isCaretPositionSet = true; } else { Activator .logWarning( MessageFormat.format( UIText.CommitDialog_MultipleCommitMessageProvider2Implementations, provider.getClass().getName()), null); } return pos; }</code><technical_language>Independent of 0 -1 default position, validate messageWithPosition.getDesiredCaretPosition() here. if is -300?? message 100 characters, position is 3000? ICommitMessageProviders untrusted code; return things. EGit fail wreck havoc is a misbehaving ICommitMessageProvider</technical_language>

Target:
private int getUpdatedCaretPosition(StringBuilder currentCalculatedMessage, int currentCaretPosition, CommitMessageWithCaretPosition messageWithPosition, ICommitMessageProvider2 provider) { int pos = currentCaretPosition; if (currentCaretPosition == CommitMessageWithCaretPosition.NO_POSITION) { if (messageWithPosition .getDesiredCaretPosition() == CommitMessageWithCaretPosition.NO_POSITION) { return pos; } if (messageWithPosition .getDesiredCaretPosition() > messageWithPosition .getMessage().length() || messageWithPosition .getDesiredCaretPosition() < CommitMessageWithCaretPosition.NO_POSITION) { Activator.logWarning( MessageFormat.format( UIText.CommitDialog_CaretPositionOutOfBounds, provider.getClass().getName(), messageWithPosition.getDesiredCaretPosition()), null); return CommitMessageWithCaretPosition.NO_POSITION; } else { pos = currentCalculatedMessage.length(); if (currentCalculatedMessage.length() > 0) { pos += MESSAGE_SEPARATOR.length(); } pos += messageWithPosition.getDesiredCaretPosition(); } } else { Activator .logWarning( MessageFormat.format( UIText.CommitDialog_MultipleCommitMessageProvider2Implementations, provider.getClass().getName()), null); } return pos; }
Source:
<code>private CoordinateConverter() { double <START> lineHeigth = <END> FigureUtilities.getFontMetrics(null).getHeight(); transformationScale = lineHeigth / 100.0; }</code><technical_language>lineHeight lineHeigth</technical_language>

Target:
private CoordinateConverter() { double lineHeight = FigureUtilities.getFontMetrics(null).getHeight(); transformationScale = lineHeight / 100.0; }
Source:
<code>private List<Future<UpdateCenter.UpdateCenterJob>> install(@Nonnull Collection<String> plugins, boolean dynamicLoad, @CheckForNull UUID correlationId) { List<Future<UpdateCenter.UpdateCenterJob>> installJobs = new ArrayList<>(); for (String n : plugins) { int index = n.indexOf('.'); UpdateSite.Plugin p = null; if (index == -1) { p = getPlugin(n, UpdateCenter.ID_DEFAULT); } else { while (index != -1) { if (index + 1 >= n.length()) { break; } String pluginName = n.substring(0, index); String siteName = n.substring(index + 1); UpdateSite.Plugin plugin = getPlugin(pluginName, siteName); if (plugin != null) { if (p != null) { throw new Failure("Ambiguous plugin: " + n); } p = plugin; } index = n.indexOf('.', index + 1); } } if (p == null) { throw new Failure("No such plugin: " + n); } <START> for(PluginWrapper.Dependency previouslyBundledDependency : ClassicPluginStrategy.getPreviouslyBundledDependencies(p.requiredCore)) { <END> if(getPlugin(previouslyBundledDependency.shortName) == null) { UpdateSite.Plugin previouslyBundledPlugin = getPlugin(previouslyBundledDependency.shortName, UpdateCenter.ID_DEFAULT); Future<UpdateCenter.UpdateCenterJob> jobFuture = previouslyBundledPlugin.deploy(dynamicLoad, correlationId); installJobs.add(jobFuture); } } Future<UpdateCenter.UpdateCenterJob> jobFuture = p.deploy(dynamicLoad, correlationId); installJobs.add(jobFuture); } if (Jenkins.getActiveInstance().getInstallState() == InstallState.NEW) { trackInitialPluginInstall(installJobs); } return installJobs; }</code><technical_language>bug: This smells wrong place this. detached plugin mapping logically applied incoming metadata, UC JSON a plugin manifest. adding in dependencies minute, considered dependencies start. I suspect difference is tangible: if setup wizard check box next some ancient plugin, box for detached dependency matrix-project get checked (which of _also_ means wind installing it, special handling _here_)</technical_language>

Target:
private List<Future<UpdateCenter.UpdateCenterJob>> install(@Nonnull Collection<String> plugins, boolean dynamicLoad, @CheckForNull UUID correlationId) { List<Future<UpdateCenter.UpdateCenterJob>> installJobs = new ArrayList<>(); for (String n : plugins) { int index = n.indexOf('.'); UpdateSite.Plugin p = null; if (index == -1) { p = getPlugin(n, UpdateCenter.ID_DEFAULT); } else { while (index != -1) { if (index + 1 >= n.length()) { break; } String pluginName = n.substring(0, index); String siteName = n.substring(index + 1); UpdateSite.Plugin plugin = getPlugin(pluginName, siteName); if (plugin != null) { if (p != null) { throw new Failure("Ambiguous plugin: " + n); } p = plugin; } index = n.indexOf('.', index + 1); } } if (p == null) { throw new Failure("No such plugin: " + n); } Future<UpdateCenter.UpdateCenterJob> jobFuture = p.deploy(dynamicLoad, correlationId); installJobs.add(jobFuture); } if (Jenkins.getActiveInstance().getInstallState() == InstallState.NEW) { trackInitialPluginInstall(installJobs); } return installJobs; }
Source:
<code>public PlanNode visitFilter(FilterNode node, RewriteContext<Expression> context) { PlanNode rewrittenPlan = context.rewrite(node.getSource(), combineConjuncts(node.getPredicate(), context.get())); if (!(rewrittenPlan instanceof FilterNode) <START> || !expressionEquivalence.areExpressionsEquivalent(session, ((FilterNode) rewrittenPlan).getPredicate(), node.getPredicate(), types)) { <END> return rewrittenPlan; } return node; }</code><technical_language>more readable of isEqualFilter(PlanNode node) method do checks a single line</technical_language>

Target:
public PlanNode visitFilter(FilterNode node, RewriteContext<Expression> context) { PlanNode rewrittenPlan = context.rewrite(node.getSource(), combineConjuncts(node.getPredicate(), context.get())); if (!(rewrittenPlan instanceof FilterNode)) { return rewrittenPlan; } FilterNode rewrittenFilterNode = (FilterNode) rewrittenPlan; if (!areExpressionsEquivalent(rewrittenFilterNode.getPredicate(), node.getPredicate()) || node.getSource() != rewrittenFilterNode.getSource()) { return rewrittenPlan; } return node; }
Source:
<code>public void iamRevokeAccess(String projectId, String secretId, String member) throws IOException { try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) { SecretName name = SecretName.of(projectId, secretId); GetIamPolicyRequest getRequest = GetIamPolicyRequest.newBuilder().setResource(name.toString()).build(); Policy policy = client.getIamPolicy(getRequest); String roleToFind = "roles/secretmanager.secretAccessor"; <START> for (Binding b : policy.getBindingsList()) { <END> if (b.getRole() == roleToFind && b.getMembersList().contains(member)) { b.getMembersList().remove(member); } } SetIamPolicyRequest setRequest = SetIamPolicyRequest.newBuilder().setResource(name.toString()).setPolicy(policy).build(); client.setIamPolicy(setRequest); System.out.printf("Updated IAM policy for %s\n", secretId); } }</code><technical_language>nit: variable name for b</technical_language>

Target:
public void iamRevokeAccess(String projectId, String secretId, String member) throws IOException { try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) { SecretName name = SecretName.of(projectId, secretId); GetIamPolicyRequest getRequest = GetIamPolicyRequest.newBuilder().setResource(name.toString()).build(); Policy policy = client.getIamPolicy(getRequest); String roleToFind = "roles/secretmanager.secretAccessor"; for (Binding binding : policy.getBindingsList()) { if (binding.getRole() == roleToFind && binding.getMembersList().contains(member)) { binding.getMembersList().remove(member); } } SetIamPolicyRequest setRequest = SetIamPolicyRequest.newBuilder().setResource(name.toString()).setPolicy(policy).build(); client.setIamPolicy(setRequest); System.out.printf("Updated IAM policy for %s\n", secretId); } }
Source:
<code>private void validateServerSettingsForm(ServerSettingsForm form, BindingResult bindingResult) { <START> if (form != null) <END> { if (!isProxyConfigurationFormEmpty(form.getProxyConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, ProxyConfigurationForm.ProxyConfigurationFormChecks.class); } if (!isSmtpConfigurationFormEmpty(form.getSmtpConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, SmtpConfigurationForm.SmtpConfigurationFormChecks.class); } ValidationUtils.invokeValidator(validator, form, bindingResult); } }</code><technical_language>else clause adds error bindingResult, in setServerSettings method overwrite null (or get NPE)</technical_language>

Target:
private void validateServerSettingsForm(ServerSettingsForm form, BindingResult bindingResult) { if (!isProxyConfigurationFormEmpty(form.getProxyConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, ProxyConfigurationForm.ProxyConfigurationFormChecks.class); } if (!isSmtpConfigurationFormEmpty(form.getSmtpConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, SmtpConfigurationForm.SmtpConfigurationFormChecks.class); } ValidationUtils.invokeValidator(validator, form, bindingResult); }
Source:
<code>public static BuckCommandHandler getTestConfigurationDataHandler( @Nonnull TestConfiguration testConfiguration, @Nonnull String name, final Optional<String> testSelectors, final Project project, VirtualFile containingFile, VirtualFile buckFile, @Nullable Function<TestConfiguration, Void> testConfigurationProcessor) { BuckCommandHandler handler = new BuckQueryCommandHandler( project, buckFile.getParent(), BuckCommand.QUERY, new Function<List<String>, Void>() { @Nullable @Override public Void apply(@Nullable List<String> strings) { if (!(strings == null || strings.isEmpty() || strings.get(0) == null || strings.get(0).isEmpty())) { testConfiguration.setName(name); testConfiguration.data.target = strings.get(0); testConfiguration.data.testSelectors = testSelectors.orElse(""); } if (testConfigurationProcessor != null) { testConfigurationProcessor.apply(testConfiguration); } return null; } }); <START> handler.command().addParameter("kind('java_test', owner(" + containingFile.getPath() + "))"); <END> return handler; }</code><technical_language>change filter out non-java_test targets? if robolectric_test else</technical_language>

Target:
public static BuckCommandHandler getTestConfigurationDataHandler( @Nonnull TestConfiguration testConfiguration, @Nonnull String name, final Optional<String> testSelectors, final Project project, VirtualFile containingFile, VirtualFile buckFile, @Nullable Function<TestConfiguration, Void> testConfigurationProcessor) { BuckCommandHandler handler = new BuckQueryCommandHandler( project, buckFile.getParent(), BuckCommand.QUERY, new Function<List<String>, Void>() { @Nullable @Override public Void apply(@Nullable List<String> strings) { if (!(strings == null || strings.isEmpty() || strings.get(0) == null || strings.get(0).isEmpty())) { testConfiguration.setName(name); testConfiguration.data.target = strings.get(0); testConfiguration.data.testSelectors = testSelectors.orElse(""); } if (testConfigurationProcessor != null) { testConfigurationProcessor.apply(testConfiguration); } return null; } }, false); handler.command().addParameter("kind('.*_test', owner(" + containingFile.getPath() + "))"); return handler; }
Source:
<code>public static RGB getRGBFromCssString(String cssValue) { try { String[] rgbValues = cssValue.substring(4, cssValue.length() - 1).split(","); return new RGB(Integer.parseInt(rgbValues[0].trim()), Integer.parseInt(rgbValues[1].trim()), Integer.parseInt(rgbValues[2].trim())); <START> } catch (IndexOutOfBoundsException ioobe) { <END> return null; } catch (NumberFormatException nfe) { return null; } }</code><technical_language>check length is enough 4 characters expect be</technical_language>

Target:
public static RGB getRGBFromCssString(String cssValue) { try { if (cssValue.startsWith("rgb(") && cssValue.endsWith(")")) { String[] rgbValues = cssValue.substring(4, cssValue.length() - 1).split(","); if (rgbValues.length == 3) { return new RGB(Integer.parseInt(rgbValues[0].trim()), Integer.parseInt(rgbValues[1].trim()), Integer.parseInt(rgbValues[2].trim())); } } throw new E4CssParseException("RGB", cssValue); } catch (NumberFormatException | E4CssParseException e) { if (!loggedError) { StatusHandler.log(new Status(IStatus.ERROR, CommonsUiConstants.ID_PLUGIN, e.getMessage(), e)); loggedError = true; } return null; } }
Source:
<code><START> public Boolean isUserRequired() { <END> return auditConfig != null && auditConfig.isIdentifyUserEnabled(); }</code><technical_language>For performance hit, problems nulls cause. I find especially bad Boolean end states feels wrong</technical_language>

Target:
public boolean isUserRequired() { return auditConfig != null && auditConfig.isIdentifyUserEnabled(); }