auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ActionEventRequest buildUpdateProgramEnrollmentAction(String configName) { SortedSet<ActionParameterRequest> parameters = new TreeSet<>(); int order = 0; String serviceMethod = "updateProgramEnrollment"; parameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, false, true, order++)); parameters.addAll(prepareProgramEnrollmentParameters(order)); order = parameters.size(); <START> parameters.add(prepareParameter(Keys.PROGRAM_ATTRIBUTES, DisplayNames.PROGRAM_ATTRIBUTES, MAP, false, order)); <END> return new ActionEventRequestBuilder() .setDisplayName(getDisplayName(UPDATE_PROGRAM_ENROLLMENT, configName)) .setServiceInterface(OPENMRS_ACTION_PROXY_SERVICE) .setServiceMethod(serviceMethod) .setSubject(getSubject(serviceMethod, configName)) .setActionParameters(parameters) .createActionEventRequest(); }</code><technical_language>add this param in prepareProgramEnrollmentParameters method. add a flag exclude/include this param depends chosen action</technical_language>

Target:
private ActionEventRequest buildUpdateProgramEnrollmentAction(String configName) { SortedSet<ActionParameterRequest> parameters = new TreeSet<>(); int order = 0; String serviceMethod = "updateProgramEnrollment"; parameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, false, true, order++)); parameters.addAll(prepareProgramEnrollmentParameters(order, true)); return new ActionEventRequestBuilder() .setDisplayName(getDisplayName(UPDATE_PROGRAM_ENROLLMENT, configName)) .setServiceInterface(OPENMRS_ACTION_PROXY_SERVICE) .setServiceMethod(serviceMethod) .setSubject(getSubject(serviceMethod, configName)) .setActionParameters(parameters) .createActionEventRequest(); }
Source:
<code>public Object instantiateItem(@NonNull ViewGroup container, int position) { LayoutInflater inflater = LayoutInflater.from(container.getContext()); View view = inflater.inflate(R.layout.view_reference_pager_item, container, false); <START> view.setTag(position); <END> TextView referenceText = view.findViewById(R.id.reference_text); referenceText.setText(StringUtil.fromHtml(items.get(position).getHref())); referenceText.setMovementMethod(new LinkMovementMethodExt(linkHandler)); TextView titleText = view.findViewById(R.id.reference_title_text); titleText.setText(getContext().getString(R.string.reference_title, items.get(position).getLinkText())); container.addView(view); return view; }</code><technical_language>tag relate action</technical_language>

Target:
public Object instantiateItem(@NonNull ViewGroup container, int position) { LayoutInflater inflater = LayoutInflater.from(container.getContext()); View view = inflater.inflate(R.layout.view_reference_pager_item, container, false); TextView referenceText = view.findViewById(R.id.reference_text); referenceText.setText(StringUtil.fromHtml(items.get(position).getHref())); referenceText.setMovementMethod(new LinkMovementMethodExt(linkHandler)); TextView titleText = view.findViewById(R.id.reference_title_text); titleText.setText(getContext().getString(R.string.reference_title, items.get(position).getLinkText())); container.addView(view); return view; }
Source:
<code>public void log(AuditLogable auditLogable, AuditLogType logType, String message) { if (!logType.shouldBeLogged()) { return; } EventFloodRegulator eventFloodRegulator = new EventFloodRegulator(auditLogable, logType); if (eventFloodRegulator.isLegal()) { AuditLog[] savedAuditLog = { null }; <START> TransactionSupport.executeInNewTransaction(() -> { <END> savedAuditLog[0] = saveToDb(auditLogable, logType, message); return null; }); if (savedAuditLog[0] == null) { log.warn("Unable to create AuditLog"); } else { logMessage(savedAuditLog[0]); } } }</code><technical_language>I 2 points this one: 1. AFAIK, TransactionSupport.executeInNewTransaction() is capable return a in case created saved auditLog. is need create array a deliver data code is executed transaction it. able do: AuditLog savedAuditLog = TransactionSupport.executeInNewTransaction(() -> saveToDb(auditLogable, logType, message)); 2. suggest wrap persistence DB a new transaction entire saveToDb method performs additional work impact result of event (creating event persisted require access DB, in a new transaction hit issues avoid). Therefore, recommend restrict scope of transaction line in saveToDb: getDbFacadeInstance().getAuditLogDao().save(auditLog);</technical_language>

Target:
public void log(AuditLogable auditLogable, AuditLogType logType, String message) { if (!logType.shouldBeLogged()) { return; } EventFloodRegulator eventFloodRegulator = new EventFloodRegulator(auditLogable, logType); if (eventFloodRegulator.isLegal()) { AuditLog savedAuditLog = saveToDb(auditLogable, logType, message); if (savedAuditLog == null) { log.warn("Unable to create AuditLog"); } else { logMessage(savedAuditLog); } } }
Source:
<code>private void addListeners() { comboBox.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { widgetEntryChanged(); } }); comboBox.addTextChangedListener(new TextWatcher() { <START> @Override <END> public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { clearWarningMessage(); } }); }</code><technical_language>signal for "the user typing out a correct entry, clicking entry in list, clicking next question" results in set? Clicking ">" swiping do it, triggers a "get answer", I if, say, losing focus attempt set it</technical_language>

Target:
private void addListeners() { comboBox.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { widgetEntryChanged(); } }); comboBox.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { comboBox.showDropDown(); } else { comboBox.autoCorrectCapitalization(); widgetEntryChanged(); } } }); comboBox.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { clearWarningMessage(); } }); }
Source:
<code>public String localize(final String errorMsg, final Locale requestLocale) { Locale locale = requestLocale == null ? Locale.getDefault() : requestLocale; String ret = ""; Map<String, String> messages = getMessages(locale); if (messages != null && messages.containsKey(errorMsg)) { ret = messages.get(errorMsg); } else { <START> if (!(errorMsg == null || errorMsg.isEmpty())) { <END> String[] splitted = errorMsg.toLowerCase().split("[_]", -1); ret = StringUtils.join(splitted, " "); } } return ret; }</code><technical_language>Please optimize: if (messages != null && messages.containsKey(errorMsg)) { ... } else if (!StringUtils.isEmpty(errorMsg)) { ... }</technical_language>

Target:
public String localize(final String errorMsg, final Locale requestLocale) { String localizedErrorMsg = ""; ResourceBundle resourceBundle = getResourceBundle(requestLocale == null ? Locale.getDefault() : requestLocale); if (resourceBundle != null && resourceBundle.containsKey(errorMsg)) { localizedErrorMsg = resourceBundle.getString(errorMsg); } else if (!StringUtils.isEmpty(errorMsg)) { localizedErrorMsg = StringUtils.join(errorMsg.toLowerCase().split("[_]", -1), " "); } return localizedErrorMsg; }
Source:
<code>public void mergeStatistics(Statistics stats) { if (stats.isEmpty()) return; <START> if (this.getClass() == stats.getClass() && Objects.equals(comparator(), stats.comparator())) { <END> incrementNumNulls(stats.getNumNulls()); if (stats.hasNonNullValue()) { mergeStatisticsMinMax(stats); markAsNotEmpty(); } } else { throw StatisticsClassException.create(this, stats); } }</code><technical_language>I this check stronger. checking comparator's equality, check underlying type? This check allow merging stats for binary binary/UTF8 types, I right</technical_language>

Target:
public void mergeStatistics(Statistics stats) { if (stats.isEmpty()) return; if (type.equals(stats.type)) { incrementNumNulls(stats.getNumNulls()); if (stats.hasNonNullValue()) { mergeStatisticsMinMax(stats); markAsNotEmpty(); } } else { throw StatisticsClassException.create(this, stats); } }
Source:
<code>public void visitNode(Tree tree) { MethodInvocationTree mit = (MethodInvocationTree) tree; Arguments arguments = mit.arguments(); int nbrArgument = arguments.size(); if (nbrArgument <= 1) { return; } Set<ExpressionTree> reported = new HashSet<>(); for (int i = 0; i < nbrArgument; i++) { <START> ExpressionTree arg = arguments.get(i); <END> if (isLiteral(arg) || arg.is(Tree.Kind.IDENTIFIER) || arg.is(Tree.Kind.NEW_CLASS)) { continue; } for (int j = i + 1; j < nbrArgument; j++) { ExpressionTree otherArg = arguments.get(j); if (!reported.contains(otherArg) && SyntacticEquivalence.areEquivalent(arg, otherArg)) { reportIssue( otherArg, String.format("Verify that this is the intended value; it is the same as the %s argument.", argumentNumber(i + 1)), Collections.singletonList(new JavaFileScannerContext.Location("", arg)), null); reported.add(otherArg); } } } }</code><technical_language>Arguable I fo for ExpressionUtils.skipParentheses(arguments.get(i)) get cases foo(point.x, (point.y)) exclude faster cases foo(("bla"), "flah");and remark extracting "otherArg"</technical_language>

Target:
public void visitNode(Tree tree) { MethodInvocationTree mit = (MethodInvocationTree) tree; Arguments arguments = mit.arguments(); int arity = arguments.size(); if (arity <= 1) { return; } Set<ExpressionTree> reported = new HashSet<>(); for (int i = 0; i < arity; i++) { ExpressionTree arg = ExpressionUtils.skipParentheses(arguments.get(i)); if (isLiteral(arg) || arg.is(Tree.Kind.IDENTIFIER) || arg.is(Tree.Kind.NEW_CLASS)) { continue; } for (int j = i + 1; j < arity; j++) { ExpressionTree otherArg = ExpressionUtils.skipParentheses(arguments.get(j)); if (!reported.contains(otherArg) && SyntacticEquivalence.areEquivalent(arg, otherArg)) { reportIssue( otherArg, String.format("Verify that this is the intended value; it is the same as the %s argument.", argumentNumber(i + 1)), Collections.singletonList(new JavaFileScannerContext.Location("", arg)), null); reported.add(otherArg); } } } }
Source:
<code>public String getFileNameRegexToDownload(String version) { <START> return null; <END> }</code><technical_language>return null</technical_language>

Target:
public String getFileNameRegexToDownload(String version) { if (version.equals(FIRST_VERSION)) { return FIRST_FILE.getName(); } else { return LATEST_FILE.getName(); } }
Source:
<code>public void onMessage(ClientMessage msg) { boolean messageWasDiverted = msg.containsProperty(AMQ_ORIG_MSG_ID); String origMsgId = messageWasDiverted ? String.valueOf(msg.getLongProperty(AMQ_ORIG_MSG_ID)) : String.valueOf(msg.getMessageID()); String msgId = String.valueOf(msg.getMessageID()); String body = ""; try { if (messageWasDiverted) { log.debug("Message was diverted from: {}:{} -> {}:{}", msg.getStringProperty(AMQ_ORIG_ADDRESS), origMsgId, msg.getAddress(), msg.getMessageID()); } body = msg.getBodyBuffer().readString(); log.debug("Got event: {}", body); Event event = mapper.readValue(body, Event.class); listener.onEvent(event); log.debug("Message listener processed message: [{}]: SUCCESS", listener, msgId, origMsgId); msg.acknowledge(); session.commit(); } catch (Exception e) { log.debug("Message listener processed message: [{}]: FAILED", listener, msgId, origMsgId); log.error("Unable to process message {}[{}]: {}", msgId, origMsgId, e); <START> log.debug("Unable to process message. Rolling back client session.\n{}", body, e); <END> if (!(e instanceof QpidConnectionException)) { log.warn("Unexpected exception thrown by listener. This message will be discarded: [{}]", msgId, origMsgId, e); try { msg.acknowledge(); } catch (ActiveMQException amqe) { log.error("Unable to acknowledge message.", amqe); } try { session.rollback(); } catch (ActiveMQException amqe) { log.warn("Unable to roll back session.", amqe); } } } }</code><technical_language>This extra debug output is largely redundant now. update longer doubly prints exception duplicate message. This fine body message (i.e. log.debug("{}", body))</technical_language>

Target:
public void onMessage(ClientMessage msg) { boolean messageWasDiverted = msg.containsProperty(AMQ_ORIG_MSG_ID); String origMsgId = messageWasDiverted ? String.valueOf(msg.getLongProperty(AMQ_ORIG_MSG_ID)) : String.valueOf(msg.getMessageID()); String msgId = String.valueOf(msg.getMessageID()); String body = ""; try { if (messageWasDiverted) { log.debug("Message was diverted from: {}:{} -> {}:{}", msg.getStringProperty(AMQ_ORIG_ADDRESS), origMsgId, msg.getAddress(), msg.getMessageID()); } body = msg.getBodyBuffer().readString(); log.debug("Got event: {}", body); Event event = mapper.readValue(body, Event.class); listener.onEvent(event); log.debug("Message listener processed message: [{}]: SUCCESS", listener, msgId, origMsgId); msg.acknowledge(); session.commit(); } catch (Exception e) { log.debug("Message listener processed message: [{}]: FAILED", listener, msgId, origMsgId); log.error("Unable to process message {}[{}]: {}", msgId, origMsgId, e); log.debug("Unable to process message. Rolling back client session.\n{}", body); if (!(e instanceof QpidConnectionException)) { log.warn("Unexpected exception thrown by listener. This message will be discarded: [{}]", msgId, origMsgId, e); try { msg.acknowledge(); } catch (ActiveMQException amqe) { log.error("Unable to acknowledge message.", amqe); } try { session.rollback(); } catch (ActiveMQException amqe) { log.warn("Unable to roll back session.", amqe); } } } }
Source:
<code>void callUpgradeCdhCommand(String stackProductVersion, ClustersResourceApi clustersResourceApi, Stack stack, ApiClient apiClient) throws ApiException, CloudbreakException { LOGGER.info("Upgrading the CDP Runtime..."); Optional<ApiCommand> optionalUpgradeCommand = findUpgradeApiCommand(clustersResourceApi, stack); try { ApiCommand upgradeCommand; if (optionalUpgradeCommand.isPresent()) { upgradeCommand = optionalUpgradeCommand.get(); LOGGER.debug("Upgrade of CDP Runtime is already running with id: [{}]", upgradeCommand.getId()); } else { ApiCdhUpgradeArgs upgradeArgs = new ApiCdhUpgradeArgs(); upgradeArgs.setCdhParcelVersion(stackProductVersion); upgradeCommand = clustersResourceApi.upgradeCdhCommand(stack.getName(), upgradeArgs); } PollingResult pollingResult = clouderaManagerPollingServiceProvider.startPollingCdpRuntimeUpgrade(stack, apiClient, upgradeCommand.getId()); <START> if (isExited(pollingResult)) { throw new CancellationException("Cluster was terminated while waiting for CDP Runtime to be upgraded"); } else if (isTimeout(pollingResult)) { throw new CloudbreakException("Timeout during CDP Runtime upgrade."); } <END> } catch (ApiException ex) { if (ex.getResponseBody().contains("Cannot upgrade because the version is already CDH")) { LOGGER.info("The Runtime has already been upgraded to {}", stackProductVersion); } else { throw ex; } } LOGGER.info("Runtime is successfully upgraded!"); }</code><technical_language>kinda here, duplicating 5 lines, moved some util a component</technical_language>

Target:
void callUpgradeCdhCommand(String stackProductVersion, ClustersResourceApi clustersResourceApi, Stack stack, ApiClient apiClient) throws ApiException, CloudbreakException { LOGGER.info("Upgrading the CDP Runtime..."); Optional<ApiCommand> optionalUpgradeCommand = findUpgradeApiCommand(clustersResourceApi, stack); try { ApiCommand upgradeCommand; if (optionalUpgradeCommand.isPresent()) { upgradeCommand = optionalUpgradeCommand.get(); LOGGER.debug("Upgrade of CDP Runtime is already running with id: [{}]", upgradeCommand.getId()); } else { ApiCdhUpgradeArgs upgradeArgs = new ApiCdhUpgradeArgs(); upgradeArgs.setCdhParcelVersion(stackProductVersion); upgradeCommand = clustersResourceApi.upgradeCdhCommand(stack.getName(), upgradeArgs); } PollingResult pollingResult = clouderaManagerPollingServiceProvider.startPollingCdpRuntimeUpgrade(stack, apiClient, upgradeCommand.getId()); pollingResultErrorHandler.handlePollingResult(pollingResult, "Cluster was terminated while waiting for CDP Runtime to be upgraded", "Timeout during CDP Runtime upgrade."); } catch (ApiException ex) { String responseBody = ex.getResponseBody(); if (StringUtils.hasText(responseBody) && responseBody.contains("Cannot upgrade because the version is already CDH")) { LOGGER.info("The Runtime has already been upgraded to {}", stackProductVersion); } else { throw ex; } } LOGGER.info("Runtime is successfully upgraded!"); }
Source:
<code>private void chooseDcForCheckingIfGetNamesFromExternalProviderSupported() { Version chosenDataCenterVersion = null; Guid chosenDataCenterId = provider.getAdditionalProperties().getStoragePoolId(); if (chosenDataCenterId == null) { for (StoragePool sp : <START> dbFacade.getStoragePoolDao().getAll()) { <END> if (chosenDataCenterVersion == null || chosenDataCenterVersion.less(sp.getCompatibilityVersion())) { chosenDataCenterVersion = sp.getCompatibilityVersion(); chosenDataCenterId = sp.getId(); } } provider.getAdditionalProperties().setStoragePoolId(chosenDataCenterId); } }</code><technical_language>need query storage pools up, right? (getAllByStatus)</technical_language>

Target:
private void chooseDcForCheckingIfGetNamesFromExternalProviderSupported() { Version chosenDataCenterVersion = null; Guid chosenDataCenterId = provider.getAdditionalProperties().getStoragePoolId(); if (chosenDataCenterId == null) { for (StoragePool sp : storagePoolDao.getAllByStatus(StoragePoolStatus.Up)) { if (chosenDataCenterVersion == null || chosenDataCenterVersion.less(sp.getCompatibilityVersion())) { chosenDataCenterVersion = sp.getCompatibilityVersion(); chosenDataCenterId = sp.getId(); } } provider.getAdditionalProperties().setStoragePoolId(chosenDataCenterId); } }
Source:
<code>private void replicateDiskStart() { if (Guid.Empty.equals(getParameters().getVdsId())) { throw new EngineException(EngineError.down, "VM " + getParameters().getVmId() + " is not running on any VDS"); } StorageType targetType = <START> storageDomainDao.get(getParameters().getStorageDomainId()).getStorageStaticData().getStorageType(); <END> Optional<String> diskType = vmInfoBuildUtils.getNetworkDiskType(getVm(), targetType); VmReplicateDiskParameters migrationStartParams = new VmReplicateDiskParameters(getParameters().getVdsId(), getParameters().getVmId(), getParameters().getStoragePoolId(), getParameters().getSourceStorageDomainId(), getParameters().getTargetStorageDomainId(), getParameters().getImageGroupID(), getParameters().getDestinationImageId(), diskType.orElse(null)); VDSReturnValue ret = resourceManager.runVdsCommand(VDSCommandType.VmReplicateDiskStart, migrationStartParams); if (!ret.getSucceeded()) { log.error("Failed VmReplicateDiskStart (Disk '{}' , VM '{}')", getParameters().getImageGroupID(), getParameters().getVmId()); throw new EngineException(ret.getVdsError().getCode(), ret.getVdsError().getMessage()); } }</code><technical_language>getTargetStorageDomainId() more obvious</technical_language>

Target:
private void replicateDiskStart() { if (Guid.Empty.equals(getParameters().getVdsId())) { throw new EngineException(EngineError.down, "VM " + getParameters().getVmId() + " is not running on any VDS"); } StorageType targetType = this.getStorageDomainById(getParameters().getTargetStorageDomainId(), getParameters().getStoragePoolId()).getStorageStaticData().getStorageType(); Optional<String> diskType = vmInfoBuildUtils.getNetworkDiskType(getVm(), targetType); VmReplicateDiskParameters migrationStartParams = new VmReplicateDiskParameters(getParameters().getVdsId(), getParameters().getVmId(), getParameters().getStoragePoolId(), getParameters().getSourceStorageDomainId(), getParameters().getTargetStorageDomainId(), getParameters().getImageGroupID(), getParameters().getDestinationImageId(), diskType.orElse(null)); VDSReturnValue ret = resourceManager.runVdsCommand(VDSCommandType.VmReplicateDiskStart, migrationStartParams); if (!ret.getSucceeded()) { log.error("Failed VmReplicateDiskStart (Disk '{}' , VM '{}')", getParameters().getImageGroupID(), getParameters().getVmId()); throw new EngineException(ret.getVdsError().getCode(), ret.getVdsError().getMessage()); } }
Source:
<code>public String toString() { <START> return MoreObjects.toStringHelper("") <END> .add("Server", mServer) .add("AuthServerType", mAuthServer.getClass().getSimpleName()) .toString(); }</code><technical_language>I confused this is supposed "" this</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("InternalServer", mServer) .add("AuthServerType", mAuthServer.getClass().getSimpleName()) .toString(); }
Source:
<code>private void injectJsonPayload(Axis2MessageContext messageContext, Map<String, Object> data) { org.apache.axis2.context.MessageContext axis2MessageContext = messageContext.getAxis2MessageContext(); <START> String jsonPayloadString = JsonUtil.jsonPayloadToString(axis2MessageContext); <END> if (JsonUtil.hasAJsonObject(axis2MessageContext)) { injectJsonObject(data, jsonPayloadString); } else { injectJsonArray(data, jsonPayloadString); } }</code><technical_language>this a JSONPrimitive ex:- valid JSON payloads boolean - true false single number single string null</technical_language>

Target:
private void injectJsonPayload(Axis2MessageContext messageContext, Map<String, Object> data) { org.apache.axis2.context.MessageContext axis2MessageContext = messageContext.getAxis2MessageContext(); String jsonPayloadString = JsonUtil.jsonPayloadToString(axis2MessageContext); try { JsonElement jsonElement = new JsonParser().parse(jsonPayloadString); if(jsonElement.isJsonObject()){ injectJsonObject(data, jsonElement); }else if(jsonElement.isJsonArray()){ injectJsonArray(data, jsonElement); }else if(jsonElement.isJsonPrimitive()){ injectJsonPrimitive(data, jsonElement); } else if (jsonElement.isJsonNull()) { data.put(PAYLOAD_INJECTING_NAME, "null"); } } catch (JsonSyntaxException e) { handleException("Invalid JSON payload"); } }
Source:
<code>public void afterPropertiesSet() throws Exception { if (this.mongoTemplate == null) { if (this.mappingMongoConverter == null) { this.mappingMongoConverter = new MappingMongoConverter(this.mongoDbFactory, new MongoMappingContext()); this.mappingMongoConverter.setApplicationContext(this.applicationContext); List<Object> customConverters = new ArrayList<Object>(); customConverters.add(new MongoDbMessageBytesConverter()); this.mappingMongoConverter.setCustomConversions(new CustomConversions(customConverters)); this.mappingMongoConverter.afterPropertiesSet(); } this.mongoTemplate = new MongoTemplate(this.mongoDbFactory, this.mappingMongoConverter); if (this.applicationContext != null) { this.mongoTemplate.setApplicationContext(this.applicationContext); } } IndexOperations indexOperations = this.mongoTemplate.indexOps(this.collectionName); <START> indexOperations.ensureIndex(new Index(MESSAGE_ID, Order.ASCENDING)); <END> indexOperations.ensureIndex(new Index(GROUP_ID, Order.ASCENDING) .on(LAST_MODIFIED_TIME, Order.DESCENDING) .on(SEQUENCE, Order.DESCENDING)); }</code><technical_language>Doh - forget this is for random access</technical_language>

Target:
public void afterPropertiesSet() throws Exception { if (this.mongoTemplate == null) { if (this.mappingMongoConverter == null) { this.mappingMongoConverter = new MappingMongoConverter(this.mongoDbFactory, new MongoMappingContext()); this.mappingMongoConverter.setApplicationContext(this.applicationContext); List<Object> customConverters = new ArrayList<Object>(); customConverters.add(new MongoDbMessageBytesConverter()); this.mappingMongoConverter.setCustomConversions(new CustomConversions(customConverters)); this.mappingMongoConverter.afterPropertiesSet(); } this.mongoTemplate = new MongoTemplate(this.mongoDbFactory, this.mappingMongoConverter); if (this.applicationContext != null) { this.mongoTemplate.setApplicationContext(this.applicationContext); } } IndexOperations indexOperations = this.mongoTemplate.indexOps(this.collectionName); indexOperations.ensureIndex(new Index(MessageDocumentFields.MESSAGE_ID, Order.ASCENDING)); indexOperations.ensureIndex(new Index(MessageDocumentFields.GROUP_ID, Order.ASCENDING) .on(MessageDocumentFields.LAST_MODIFIED_TIME, Order.DESCENDING) .on(MessageDocumentFields.SEQUENCE, Order.DESCENDING)); }
Source:
<code>public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } <START> final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); <END> cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); cmd.add("--localbrname", _linkLocalBridgeName); final String result = cmd.execute(); if (result != null) { return false; } return true; }</code><technical_language>Please consider adding overridden version of Script(String, int, Logger) constructor accepts Duration encapsulate this type conversion</technical_language>

Target:
public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); cmd.add("--localbrname", _linkLocalBridgeName); final String result = cmd.execute(); if (result != null) { return false; } return true; }
Source:
<code>private void verifyVersion(String aBundleStr) { final Bundle bdleCurrent = Platform.getBundle(aBundleStr); if (bdleCurrent != null) { Version ver = bdleCurrent.getVersion(); if (ver.getQualifier().equals(DASHBOARD_VERSION_QUALIFIER)) { <START> Ftracer.traceDebug("In a runtime environment for " + aBundleStr + Messages.GerritPlugin_Version + ver.toString()); END> return; } } IBundleGroupProvider[] grpprovider = Platform.getBundleGroupProviders(); for (IBundleGroupProvider element : grpprovider) { IBundleGroup[] bdlgrp = element.getBundleGroups(); Ftracer.traceDebug("bundle group count: " + bdlgrp.length); for (int j = 0; j < bdlgrp.length; j++) { if (bdlgrp[j].getIdentifier().contains(aBundleStr)) { Ftracer.traceDebug("\t bdlgrp[" + j + "] : " + bdlgrp[j].getName() + "\t : " + bdlgrp[j].getProviderName() + "\t version: " + bdlgrp[j].getVersion() + "\t : " + bdlgrp[j].getIdentifier()); break; } } } }</code><technical_language>NLSBind {0} {1} in message is preferred method</technical_language>

Target:
private void verifyVersion(String aBundleStr) { final Bundle bdleCurrent = Platform.getBundle(aBundleStr); if (bdleCurrent != null) { Version ver = bdleCurrent.getVersion(); if (ver.getQualifier().equals(DASHBOARD_VERSION_QUALIFIER)) { Ftracer.traceDebug(NLS.bind(Messages.GerritPlugin_Version, aBundleStr, ver.toString())); return; } } IBundleGroupProvider[] grpprovider = Platform.getBundleGroupProviders(); for (IBundleGroupProvider element : grpprovider) { IBundleGroup[] bdlgrp = element.getBundleGroups(); Ftracer.traceDebug("bundle group count: " + bdlgrp.length); for (int j = 0; j < bdlgrp.length; j++) { if (bdlgrp[j].getIdentifier().contains(aBundleStr)) { Ftracer.traceDebug("\t bdlgrp[" + j + "] : " + bdlgrp[j].getName() + "\t : " + bdlgrp[j].getProviderName() + "\t version: " + bdlgrp[j].getVersion() + "\t : " + bdlgrp[j].getIdentifier()); break; } } } }
Source:
<code>public void updateEntry(@RequestBody EntryDTO entryDTO) { Entry entry = entryService.getEntryById(entryDTO.getId()); entry.updateEntry(entryDTO); <START> if (UserServiceImpl.hasRole(0)) { <END> smtpMailSender.sendToParticipants(entry, "Trainings", emailMessages.modifyEntry(entry)); } else { entry.getTraining().setStatus(TrainingStatus.DRAFTED); trainingService.updateTraining(entry.getTraining()); trainingEventService.addEvent(new TrainingEvent(entryDTO)); } }</code><technical_language>do need ask service for current user role? Principal added a method parameter</technical_language>

Target:
public void updateEntry(@RequestBody EntryDTO entryDTO) { Entry entry = entryService.getEntryById(entryDTO.getId()); entry.updateEntry(entryDTO); if (UserUtil.hasRole(0)) { smtpMailSender.sendToUsers(trainingService.getTrainingById(entry.getTraining().getId()).getParticipants(), "Trainings", emailMessages.modifyEntry(entry)); } else { entry.getTraining().setStatus(TrainingStatus.DRAFTED); trainingService.updateTraining(entry.getTraining()); trainingEventService.addEvent(new TrainingEvent(entryDTO)); smtpMailSender.sendToUsers(userService.getUsersByRole(UserRole.ADMIN), "Changes in training", entryDTO.getEventDescription()); } }
Source:
<code>public void register(CraftingRecipe recipe) { if (!(recipe instanceof IRecipe)) { recipe = new DelegateSpongeCraftingRecipe(recipe); } <START> recipes.add((IRecipe) recipe); <END> SpongeImplHooks.onCraftingRecipeRegister(recipe); }</code><technical_language>this</technical_language>

Target:
public void register(CraftingRecipe recipe) { if (!(recipe instanceof IRecipe)) { recipe = new DelegateSpongeCraftingRecipe(recipe); } this.recipes.add((IRecipe) recipe); SpongeImplHooks.onCraftingRecipeRegister(recipe); }
Source:
<code>private PingResult getPingResultFromLegacyEndpoint(LeaderPingerContext<PingableLeader> leader) { boolean isLeader = leader.pinger().ping(); return PingResult.builder().isLeader(isLeader).build(); <START> } <END></code><technical_language>main concern this is for users access ping v2, this is performance of ping worse a full RPC. hottest codepath this necessarily terrible, is do avoid repeatedly if is ping v2</technical_language>

Target:
private PingResult getPingResultFromLegacyEndpoint(LeaderPingerContext<PingableLeader> leader) { return PingResult.builder().isLeader(leader.pinger().ping()).build(); }
Source:
<code>private Optional<Node> retrieveNode(RMContainer container) { String hostname = container.getContainer().getNodeId().getHost(); return Optional.fromNullable(nodeStore.getNode(hostname)); <START> } <END></code><technical_language>This more sense forcing consumer empty case</technical_language>

Target:
private Node retrieveNode(RMContainer container) { String hostname = container.getContainer().getNodeId().getHost(); return nodeStore.getNode(hostname); }
Source:
<code>public void scan(ScanContext context) throws InterruptedException { InetAddress agentAddress = context.getAgentAddress("SNMP"); <START> String location = context.getSysLocation(); <END> if (agentAddress == null) { return; } SnmpAgentConfig agentConfig = m_snmpAgentConfigFactory.getAgentConfig(agentAddress, location); SnmpWalker walker = SnmpUtils.createWalker(agentConfig, getName(), createCollectionTracker(context)); walker.start(); walker.waitFor(); }</code><technical_language>sysLocation (<LINK_0> is necessarily node's location</technical_language>

Target:
public void scan(ScanContext context) throws InterruptedException { InetAddress agentAddress = context.getAgentAddress("SNMP"); if (agentAddress == null) { return; } SnmpAgentConfig agentConfig = m_snmpAgentConfigFactory.getAgentConfig(agentAddress, null); SnmpWalker walker = SnmpUtils.createWalker(agentConfig, getName(), createCollectionTracker(context)); walker.start(); walker.waitFor(); }
Source:
<code>public ValidationResult snapshotAlreadyExists(Map<Guid, Guid> diskToImageIds) { Set<Guid> diskIds = diskImages.stream() .flatMap(diskImage -> getDiskImageDao().getAllSnapshotsForImageGroup(diskImage.getId()).stream()) <START> .map(diskImage -> diskImage.getImageId()) <END> .collect(Collectors.toSet()); Set<Guid> passedImageIds = new HashSet(diskToImageIds.values()); Set<Guid> existingGuids = passedImageIds.stream().filter(diskIds::contains).collect(Collectors.toSet()); if (!existingGuids.isEmpty()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_IMAGE_ALREADY_EXISTS, ReplacementUtils.createSetVariableString("ImageId", existingGuids)); } return ValidationResult.VALID; }</code><technical_language>DiskImage::getImageId</technical_language>

Target:
public ValidationResult snapshotAlreadyExists(Map<Guid, Guid> diskToImageIds) { Set<Guid> diskIds = diskImages.stream() .flatMap(diskImage -> getDiskImageDao().getAllSnapshotsForImageGroup(diskImage.getId()).stream()) .map(DiskImage::getImageId) .collect(Collectors.toSet()); Set<Guid> providedImageIds = new HashSet(diskToImageIds.values()); Set<Guid> existingGuids = providedImageIds.stream().filter(diskIds::contains).collect(Collectors.toSet()); if (!existingGuids.isEmpty()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_IMAGE_ALREADY_EXISTS, ReplacementUtils.replaceWith("ImageIds", existingGuids)); } return ValidationResult.VALID; }
Source:
<code>public DistinctCountAggregator( DimensionSelector selector, MutableBitmap mutableBitmap ) { this.selector = selector; this.mutableBitmap = mutableBitmap; <START> this.idForNull = selector.nameLookupPossibleInAdvance() ? selector.idLookup().lookupId(null) : -1; <END> }</code><technical_language>Please throw exception if ! nameLookupPossibleInAdvance() getValueCardinality() == CARDINALITY_UNKNOWN, please throw UnsupportedOperationException. If ! nameLookupPossibleInAdvance(), getValueCardinality() returns non-negative, code in hot loop optimized, idForNull assigned soon selector.lookupName(index) returns null for time</technical_language>

Target:
public DistinctCountAggregator( DimensionSelector selector, MutableBitmap mutableBitmap ) { this.selector = selector; this.mutableBitmap = mutableBitmap; Preconditions.checkArgument( selector.nameLookupPossibleInAdvance() || selector.getValueCardinality() != DimensionSelector.CARDINALITY_UNKNOWN, "DistinctCountAggregator not supported for selector" ); this.idForNull = selector.nameLookupPossibleInAdvance() ? selector.idLookup().lookupId(null) : UNKNOWN; }
Source:
<code><START> public void loadCMISpawn() { <END> File cmiFolder = pluginHookService.getCMIDataFolder(); if (cmiFolder == null) { return; } File cmiConfig = new File(cmiFolder, "config.yml"); if (cmiConfig.exists()) { cmiSpawn = getLocationFromConfigurationUpper( YamlConfiguration.loadConfiguration(cmiConfig), "Spawn.Main"); } else { cmiSpawn = null; ConsoleLogger.info("CMI config file not found: '" + cmiConfig.getAbsolutePath() + "'"); } }</code><technical_language>Excellent</technical_language>

Target:
public void loadCMISpawn() { File cmiFolder = pluginHookService.getCmiDataFolder(); if (cmiFolder == null) { return; } File cmiConfig = new File(cmiFolder, "config.yml"); if (cmiConfig.exists()) { cmiSpawn = getLocationFromConfigurationUpper( YamlConfiguration.loadConfiguration(cmiConfig), "Spawn.Main"); } else { cmiSpawn = null; ConsoleLogger.info("CMI config file not found: '" + cmiConfig.getAbsolutePath() + "'"); } }
Source:
<code>public void patchNetIdMissingValue() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .build(); String newId = "newId"; <START> <END> String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/netid", newId); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is(newId)));; List<Operation> ops2 = new ArrayList<Operation>(); ReplaceOperation replaceOperation2 = new ReplaceOperation("/netid", null); ops2.add(replaceOperation2); patchBody = getPatchContent(ops2); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isBadRequest()); getClient(token).perform(get("/api/eperson/epersons/" + ePerson.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is(newId))); }</code><technical_language>I suggest check metadata path operation stay untouched</technical_language>

Target:
public void patchNetIdMissingValue() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withNetId("testId") .build(); String newId = "newId"; String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/netid", newId); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is(newId))); List<Operation> ops2 = new ArrayList<Operation>(); ReplaceOperation replaceOperation2 = new ReplaceOperation("/netid", null); ops2.add(replaceOperation2); patchBody = getPatchContent(ops2); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isBadRequest()); getClient(token).perform(get("/api/eperson/epersons/" + ePerson.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is(newId))) .andExpect(jsonPath("$.email", Matchers.is("johndoe@fake-email.com"))) .andExpect(jsonPath("$.canLogIn", Matchers.is(false))); }
Source:
<code><START> public Job jobStatus(String projectId, String jobId) <END> throws IOException { return client.jobs() .get(projectId, jobId) .execute(); }</code><technical_language>[minor] This public removed</technical_language>

Target:
Job jobStatus(String projectId, String jobId) throws IOException { return client.jobs() .get(projectId, jobId) .execute(); }
Source:
<code>public double getFailRate() { <START> double failed = this.failed.get(); <END> if(failed == 0.0 && this.passed.get() == 0) { return 0.0; } return failed / (this.passed.get() + failed); }</code><technical_language>declare double passed = this.passed.get() call twice</technical_language>

Target:
public double getFailRate() { double failed = this.failed.get(); double passed = this.passed.get(); if(failed == 0.0 && passed == 0) { return 0.0; } return failed / (passed + failed); }
Source:
<code>private void setStatusIfNotTheSame(InstanceMetaData instanceMetaData, InstanceStatus newStatus) { if (instanceMetaData.getInstanceStatus() != newStatus) { if (updateStatus) { instanceMetaData.setInstanceStatus(newStatus); <START> instanceMetaDataService.save(instanceMetaData); <END> LOGGER.info(":::Auto sync::: The instance status updated from to {}", instanceMetaData.getInstanceStatus(), newStatus); } else { LOGGER.info(":::Auto sync::: The instance status would be had to update from to {}", instanceMetaData.getInstanceStatus(), newStatus); } } }</code><technical_language>I saved stack sure. If a missing status save here, please test a changes, HA instance's status change if is issue. thanks</technical_language>

Target:
private void setStatusIfNotTheSame(InstanceMetaData instanceMetaData, InstanceStatus newStatus) { if (instanceMetaData.getInstanceStatus() != newStatus) { if (updateStatus) { instanceMetaData.setInstanceStatus(newStatus); LOGGER.info(":::Auto sync::: The instance status updated from to {}", instanceMetaData.getInstanceStatus(), newStatus); } else { LOGGER.info(":::Auto sync::: The instance status would be had to update from to {}", instanceMetaData.getInstanceStatus(), newStatus); } } }
Source:
<code>public void resumeNode(String id) { <START> waitServerUntilAvailable.apply(getNode(id)); <END> api.serverApi().updateStatus(id, Server.UpdateStatus.create(Types.ServerAction.POWER_ON, Types.ServerActionMethod.HARDWARE)); }</code><technical_language>This work? wait node is powered want resume it. This forever</technical_language>

Target:
public void resumeNode(String id) { api.serverApi().updateStatus(id, Server.UpdateStatus.create(Types.ServerAction.POWER_ON, Types.ServerActionMethod.HARDWARE)); }
Source:
<code>public Object transcode(Object content, MediaType contentType, MediaType destinationType) { if (destinationType.match(APPLICATION_JSON)) { try { return ProtobufUtil.toCanonicalJSON(ctx, (byte[]) content); } catch (IOException e) { throw new CacheException(e); } } else { if (destinationType.match(APPLICATION_PROTOSTREAM)) { try { Reader reader = new InputStreamReader(new ByteArrayInputStream((byte[]) content)); return ProtobufUtil.fromCanonicalJSON(ctx, reader); } catch (IOException e) { <START> e.printStackTrace(); <END> } } } throw new IllegalArgumentException("Not supported"); }</code><technical_language>rethrow a CacheException</technical_language>

Target:
public Object transcode(Object content, MediaType contentType, MediaType destinationType) { try { if (destinationType.match(APPLICATION_JSON)) { return ProtobufUtil.toCanonicalJSON(ctx, (byte[]) content); } if (destinationType.match(APPLICATION_PROTOSTREAM)) { Reader reader = new InputStreamReader(new ByteArrayInputStream((byte[]) content)); return ProtobufUtil.fromCanonicalJSON(ctx, reader); } } catch (IOException e) { throw log.errorTranscoding(e); } throw log.unsupportedContent(content); }
Source:
<code>public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { List<ScalingPolicy> scalingPoliciesRequest = (List<ScalingPolicy>) postParams.get("scalingPolicies"); List<Map<String, Object>> scalingPoliciesList = Lists.newArrayList(); for(ScalingPolicy scalingPolicy : scalingPoliciesRequest) { <START> Map<String,Object> scalingPolicyMap = Maps.newHashMap(); <END> scalingPoliciesList.add(scalingPolicyMap); scalingPolicyMap.put("cooldown", scalingPolicy.getCooldown()); scalingPolicyMap.put("type", scalingPolicy.getType().toString()); scalingPolicyMap.put("name", scalingPolicy.getName()); String targetString = scalingPolicy.getTarget(); Integer targetInt = Ints.tryParse(targetString); Float targetFloat; if (targetInt != null) { scalingPolicyMap.put(scalingPolicy.getTargetType().toString(), targetInt); } else if ((targetFloat = Floats.tryParse(targetString)) != null) { scalingPolicyMap.put(scalingPolicy.getTargetType().toString(), targetFloat); } else { scalingPolicyMap.put(scalingPolicy.getTargetType().toString(), targetString); } } return jsonBinder.bindToRequest(request, scalingPoliciesList); }</code><technical_language>[minor] Space Object</technical_language>

Target:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { return jsonBinder.bindToRequest(request, ParseHelper.buildScalingPoliciesRequestList(postParams)); }
Source:
<code>private List<BrickDetails> getBrickDetails() { <START> List<BrickDetails> brickDetialsList = new ArrayList<BrickDetails>(); <END> BrickDetails brickDetails = new BrickDetails(); brickDetails.setBrickProperties(getBrickProperties()); brickDetails.setClients(getClientInfo()); brickDetails.setMemoryStatus(getMemoryStatus()); brickDetialsList.add(brickDetails); return brickDetialsList; }</code><technical_language>Collections.singletonList</technical_language>

Target:
private List<BrickDetails> getBrickDetails() { BrickDetails brickDetails = new BrickDetails(); brickDetails.setBrickProperties(getBrickProperties()); brickDetails.setClients(getClientInfo()); brickDetails.setMemoryStatus(getMemoryStatus()); return Collections.singletonList(brickDetails); }
Source:
<code>private QueryResult executeQueryTest() { Query query = queryPair.getTest(); QueryResult setupResult = null; QueryResult queryResult = null; try { setupResult = setup(query, testPreQueryResults, testPrequery -> executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), testPrequery, testTimeout, sessionProperties)); if (setupResult.getState() == State.SUCCESS) { queryResult = executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), query.getQuery(), testTimeout, sessionProperties); } } finally { int retry = 0; QueryResult tearDownResult; do { tearDownResult = tearDown(query, testPostQueryResults, testPostquery -> executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), testPostquery, testTimeout, sessionProperties)); if (tearDownResult.getState() == State.SUCCESS) { break; } try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } retry++; } while (retry < testTeardownRetries); if (tearDownResult.getState() != State.SUCCESS) { <START> queryResult = tearDownResult; <END> if (tearDownResult.getException() != null) { if (setupResult.getException() != null) { tearDownResult.addSuppressed(setupResult.getException()); } if (queryResult.getException() != null) { tearDownResult.addSuppressed(queryResult.getException()); } } } } return queryResult; }</code><technical_language>move this line if? I logic easier comprehend way</technical_language>

Target:
private QueryResult executeQueryTest() { Query query = queryPair.getTest(); QueryResult setupResult = null; QueryResult queryResult = null; try { setupResult = setup(query, testPreQueryResults, testPrequery -> executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), testPrequery, testTimeout, sessionProperties)); if (setupResult.getState() == State.SUCCESS) { queryResult = executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), query.getQuery(), testTimeout, sessionProperties); } } finally { int retry = 0; QueryResult tearDownResult; do { tearDownResult = tearDown(query, testPostQueryResults, testPostquery -> executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), testPostquery, testTimeout, sessionProperties)); if (tearDownResult.getState() == State.SUCCESS) { break; } try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } retry++; } while (retry < testTeardownRetries); if (tearDownResult.getState() != State.SUCCESS) { if (tearDownResult.getException() != null) { if (setupResult.getException() != null) { tearDownResult.addSuppressed(setupResult.getException()); } if (queryResult.getException() != null) { tearDownResult.addSuppressed(queryResult.getException()); } } queryResult = tearDownResult; } } return queryResult; }
Source:
<code>public void asyncAndAwait() { setRootRule(PythonGrammar.FUNCDEF); <START> assertThat(p).matches("async def fun(): pass"); <END> setRootRule(PythonGrammar.ASYNC_STMT); assertThat(p).matches("async with x.bar() as foo: pass"); assertThat(p).matches("async for var in x: pass"); setRootRule(PythonGrammar.STATEMENT); assertThat(p).matches("async = 2"); assertThat(p).matches("await async_func"); }</code><technical_language>@ivandalbosco i worth test decorated function declaration</technical_language>

Target:
public void asyncAndAwait() { setRootRule(PythonGrammar.FUNCDEF); assertThat(p).matches("async def fun(): pass"); assertThat(p).matches("@someAnnotation\nasync def fun(): pass"); setRootRule(PythonGrammar.ASYNC_STMT); assertThat(p).matches("async with x.bar() as foo: pass"); assertThat(p).matches("async for var in x: pass"); setRootRule(PythonGrammar.EXPRESSION_STMT); assertThat(p).matches("await async_func()"); setRootRule(PythonGrammar.STATEMENT); assertThat(p).matches("async = 1"); assertThat(p).matches("await = 1"); setRootRule(PythonGrammar.FUNCDEF); assertThat(p).matches("def async(args): pass"); assertThat(p).matches("def await(args): pass"); }