### Complete Example Setup Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/camera-auto-switch Imports for a comprehensive example demonstrating automatic camera switching. ```typescript import { camera } from '@kit.CameraKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { abilityAccessCtrl } from '@kit.AbilityKit'; const TAG = 'AutoSwitchCameraDemo '; ``` -------------------------------- ### Install a Plugin Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/bm-tool Example of installing a plugin for the application 'com.ohos.app' from the specified file path. ```bash bm install-plugin -n com.ohos.app -p /data/plugin.hsp ``` -------------------------------- ### Complete Example Setup with Imports Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-common-events-drag-event This is the complete ArkTS code for the drag-and-drop example, including necessary imports from '@kit.ArkUI' and '@kit.ArkData'. It initializes component states and properties. ```ArkTS 1. import { dragController } from '@kit.ArkUI'; 2. import { unifiedDataChannel, uniformTypeDescriptor } from '@kit.ArkData'; 3. 4. // ... 5. 6. @Entry 7. @ComponentV2 8. export struct SpringLoadingPage { 9. context1 = this.getUIContext().getHostContext(); 10. @Local isShowSheet: boolean = false; 11. // 请将$r('app.string.Select_Result')替换为实际资源文件,在本示例中该资源文件的value值为"搜索结果:\n 设备 1\n 设备 2\n 设备 3\n ... ..." 12. private searchResult: string = this.context1?.resourceManager.getStringSync($r('app.string.Select_Result').id)!; 13. @Local isSearchDone: boolean = false; 14. private reminderColor: Color = Color.Green; 15. private normalColor: Color = Color.Blue; 16. @Local buttonBackgroundColor: Color = this.normalColor; 17. ``` -------------------------------- ### Entry Ability Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/application-adaptation-freeform-window This snippet shows the entry point for an example application, demonstrating how to load content and store the window stage. It's a basic setup for an ArkUI application. ```typescript 1. // EntryAbility.ets 2. // 示例应用的入口 3. import { UIAbility } from '@kit.AbilityKit'; 4. import { window } from '@kit.ArkUI'; 5. export default class EntryAbility extends UIAbility { 6. onWindowStageCreate(windowStage: window.WindowStage): void { 7. windowStage.loadContent('pages/Index', (err) => { 8. if (err.code) { 9. console.info('Failed to load the content. Cause: %{public}s', JSON.stringify(err)); 10. return; 11. } 12. AppStorage.setOrCreate('windowStage', windowStage); 13. }); 14. } 15. } ``` -------------------------------- ### run.sh Example Script Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-large-language-one-stop A comprehensive example of the run.sh script, demonstrating environment variable setup, device selection (CUDA or NPU), and the Python command to execute the quantization optimization process. ```bash #!/bin/bash set -e qlibs='path/to/dopt_pytorch_py3' export WANDB_DISABLED=true export HF_DATASETS_OFFLINE=0 export PYTHONPATH=${qlibs}:$PYTHONPATH # 设置为cuda或npu模式,二选一 # cuda模式 export DEVICE=cuda export CUDA_VISIBLE_DEVICES=1 # npu模式 # export DEVICE=npu # export ASCEND_RT_VISIBLE_DEVICES=2,3 ROOT=. testcase='output_dir' RUN_FILE=${qlibs}/dopt/dopt_lm/opt_main.py output_dir=${ROOT}/${testcase}/train_output mkdir -p ${output_dir} cp ${ROOT}/config.yaml $output_dir model_path='path/to/model' dopt_config=./${testcase}/dopt_config.json quant_stage=$1 block_size=128 python -u \ ${RUN_FILE} --model-path $model_path \ --dopt-config $dopt_config \ --optimize-config ${ROOT}/config.yaml \ --quant-stage $quant_stage \ --block-size $block_size \ --output-dir ${output_dir} 2>&1 | tee ${output_dir}/logs.log ``` -------------------------------- ### Install Prefetch Cloud Function Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cloudfoundation-prefetch-cloud-interdev Example of a cloud function for installation prefetching. Requires the axios library (version 1.7.7 or higher) to be added as a dependency. This function handles application ID and makes an HTTP POST request. ```javascript 1. import axios from 'axios'; 2. 3. let myHandler = async function (event, context, callback, logger) { 4. logger.info("event:" + JSON.stringify(event)); 5. let env1 = context.env.env1; // 环境变量 6. logger.info("env1: " + env1) 7. try { 8. let body = event.body ? JSON.parse(event.body) : event; 9. let appId = body.appId; 10. 11. logger.info("appId: " + appId); 12. 13. // http请求示例,请按照实际业务修改 14. let url = 'https://example.com/prefetchApi'; // 页面资源数据的请求url 15. let headers = { 'k1': 'v1' }; // 请求header 16. let res; // 返回数据 17. await axios.post(url, {}, { headers }) // http post请求 18. .then(response => { 19. res = response.data; 20. }) 21. logger.info("--------Finished-------"); 22. callback(res); 23. } catch (error) { 24. logger.error("--------Error-------"); 25. logger.error("error: " + error); 26. callback(error); 27. } 28. }; 29. 30. export { myHandler }; ``` -------------------------------- ### Example of Upgrading Operator Project Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-project-upgrade This example demonstrates how to run the upgrade script with specific paths for the DDK tools installation and the operator project. ```bash 1. chmod +x /usr/local/ddk/tools/tools_ascendc/upgrade_project.sh 2. /usr/local/ddk/tools/tools_ascendc/upgrade_project.sh /home/AddCustom ``` -------------------------------- ### Start Service with URL Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/aa-tool Launches a browser and navigates to a specified URL. Replace the example URL with your actual URL. ```bash 1. aa start -A ohos.want.action.viewData -U https://www.example.com ``` -------------------------------- ### System Stack Frame Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cppcrash-guidelines This example shows the format of a system stack frame, which typically starts with '/system/lib' or '/system/lib64' and should be filtered out for clustering. ```text 1. /system/lib/platformsdk/libace_napi.z.so(panda::JSValueRef ArkNativeFunctionCallBack(panda::JsiRuntimeCallInfo*)+272) ``` -------------------------------- ### Start UIAbility and Get Launch Result Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/application-startup-options This snippet demonstrates how to start a UIAbility and handle its launch result using a completion handler. Ensure you have imported the necessary modules from '@kit.AbilityKit' and '@kit.PerformanceAnalysisKit'. ```typescript import { AbilityConstant, CompletionHandler, StartOptions, UIAbility, Want, bundleManager } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; const DOMAIN = 0x0000; const TAG: string = '[StartAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class GetLaunchResultAbility extends UIAbility { // ... onForeground(): void { // Ability has brought to foreground hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); let want: Want = { deviceId: '', // deviceId为空表示本设备 bundleName: 'com.example.startoptions', abilityName: 'EntryAbility', parameters: { // 自定义信息 info: '从EntryAbility启动' } }; let completionHandler: CompletionHandler = { onRequestSuccess: (elementName: bundleManager.ElementName, message: string): void => { console.info(`${elementName.bundleName}-${elementName.moduleName}-${elementName.abilityName} start succeeded: ${message}`); }, onRequestFailure: (elementName: bundleManager.ElementName, message: string): void => { console.error(`${elementName.bundleName}-${elementName.moduleName}-${elementName.abilityName} start failed: ${message}`); } }; let options: StartOptions = { completionHandler: completionHandler }; this.context.startAbility(want, options).then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in starting ability.'); }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `Failed to start ability. Code is ${err.code}, message is ${err.message}`); }); } // ... } ``` -------------------------------- ### Implement Install Prefetching Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cloudfoundation-call-installprefetch Import PrefetchWrapper and call doInstallPrefetch in the onCreate method of your EntryAbility.ets file. This method initiates the prefetching process and retrieves cached installation data. Note that this method can only be called once and will be destroyed afterward. The system caches cloud-side data locally when an application starts installation. ```typescript 1. import { GlobalContext } from '../common/GlobalContext'; 2. import { PrefetchWrapper } from '../prefetchUtil/PrefetchWrapper'; 3. 4. onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 5. GlobalContext.initContext(this.context); // Initialize global context 6. PrefetchWrapper.getInstance().doInstallPrefetch(); 7. } ``` -------------------------------- ### Get Function Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-get This example demonstrates how to use the Get function to retrieve the memory address of the first element (index 0) in a ContinuousVector object. ```cpp 1. // 创建ContinuousVectorVector对象cvv 2. // ... 3. // 增加元素 4. // ... 5. auto cv = cvv->add(inner_vector_capacity); 6. // ... 7. // 获取第0个元素的首地址 8. auto cv1 = cvv->Get(0U); ``` -------------------------------- ### Get Deferred Link on App Launch (TypeScript) Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/applinking-deferredlink Call the popDeferredLink() interface in your entry class file (e.g., Index.ets) when the application first starts to retrieve the deferred link clicked by the user. This is useful for ensuring users land on the intended page immediately after installation. ```typescript import { deferredLink } from '@kit.AppLinkingKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; @Entry @Component struct Index { pageStack: NavPathStack = new NavPathStack(); build() { Column() { Navigation(this.pageStack) { Button("获取延迟链接").onClick(() => { // 应用首次启动时,获取用户此前点击的该应用相关链接 deferredLink.popDeferredLink().then((link: string) => { hilog.info(0x0000, 'testTag', `Succeeded in getting deferred link, result: ${link}`); }).catch(() => { // 发生未知错误 hilog.error(0x0000, 'testTag', `Failed to get deferred link.`); }) }) // ... } // ... } } } ``` -------------------------------- ### GetListFloat Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-getlistfloat Example demonstrating how to get a TypedContinuousVector attribute using GetListFloat from RuntimeAttrs. ```cpp const RuntimeAttrs * runtime_attrs = kernel_context->GetAttrs(); const TypedContinuousVector *attr0 = runtime_attrs->GetListFloat(0); ``` -------------------------------- ### GetIrInputsNum Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-getirinputsnum This example demonstrates how to call GetIrInputsNum on a ComputeNodeInfo object to get the number of inputs for the operator. ```cpp size_t index = compute_node_info->GetIrInputsNum(); ``` -------------------------------- ### Startup Task Configuration Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/app-startup Defines multiple startup tasks with their dependencies, execution threads, and wait-on-main-thread settings. Use this to manage application initialization order and concurrency. ```json { "startupTasks": [ { "name": "StartupTask_001", "srcEntry": "./ets/startup/StartupTask_001.ets", "dependencies": [ "StartupTask_002", "StartupTask_003" ], "runOnThread": "taskPool", "waitOnMainThread": false }, { "name": "StartupTask_002", "srcEntry": "./ets/startup/StartupTask_002.ets", "dependencies": [ "StartupTask_003", "StartupTask_004" ], "runOnThread": "taskPool", "waitOnMainThread": false }, { "name": "StartupTask_003", "srcEntry": "./ets/startup/StartupTask_003.ets", "dependencies": [ "StartupTask_004" ], "runOnThread": "taskPool", "waitOnMainThread": false }, { "name": "StartupTask_004", "srcEntry": "./ets/startup/StartupTask_004.ets", "runOnThread": "taskPool", "waitOnMainThread": false }, { "name": "StartupTask_005", "srcEntry": "./ets/startup/StartupTask_005.ets", "dependencies": [ "StartupTask_006" ], "runOnThread": "mainThread", "waitOnMainThread": true, "excludeFromAutoStart": true }, { "name": "StartupTask_006", "srcEntry": "./ets/startup/StartupTask_006.ets", "runOnThread": "mainThread", "waitOnMainThread": false, "excludeFromAutoStart": true } ], "appPreloadHintStartupTasks": [ // 预加载so任务 ], "configEntry": "./ets/startup/StartupConfig.ets" } ``` -------------------------------- ### Tune Application Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/aa-tool Example of tuning an application using the process command, specifying the bundle name, ability name, a performance command, and entering the app sandbox. ```bash aa process -b com.example.myapplication -a EntryAbility -p perf-cmd [-S] ``` -------------------------------- ### GetInt Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-getint Example demonstrating how to get the RuntimeAttrs object and then retrieve an integer attribute using its index. ```cpp 1. const RuntimeAttrs * runtime_attrs = kernel_context->GetAttrs(); 2. const int64_t *attr0 = runtime_attrs->GetInt(0); ``` -------------------------------- ### Install Dependent HSP Module Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/bm-tool Example of installing a dependent HSP module before installing the main HAP. This is one of several methods to resolve module dependency issues. ```bash * 方法一:先通过bm install -p命令安装依赖的动态共享包(HSP)模块,再在应用运行配置页勾选Keep Application Data,点击OK保存配置,再运行/调试。 ``` -------------------------------- ### Complete Camera Preconfiguration Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/camera-preconfig This snippet demonstrates the full lifecycle of camera preconfiguration, from checking support to starting the session and configuring flash and focus modes. Ensure necessary imports and context are available. ```typescript // 查询Preconfig能力 try { let isPreconfigSupport = photoSession.canPreconfig(camera.PreconfigType.PRECONFIG_1080P); if (!isPreconfigSupport) { console.error('PhotoSession canPreconfig check fail.'); return; } } catch (error) { let err = error as BusinessError; console.error('Failed to call canPreconfig. errorCode = ' + err.code); return; } // 配置Preconfig try { photoSession.preconfig(camera.PreconfigType.PRECONFIG_1080P); } catch (error) { let err = error as BusinessError; console.error('Failed to call preconfig. errorCode = ' + err.code); return; } // 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface let previewOutput: camera.PreviewOutput | undefined = undefined; try { previewOutput = cameraManager.createPreviewOutput(surfaceId); } catch (error) { let err = error as BusinessError; console.error(`Failed to create the PreviewOutput instance. error code: ${err.code}`); } if (previewOutput === undefined) { return; } // 监听预览输出错误信息 previewOutput.on('error', (error: BusinessError) => { console.error(`Preview output error code: ${error.code}`); }); // 创建拍照输出流 let photoOutput: camera.PhotoOutput | undefined = undefined; try { photoOutput = cameraManager.createPhotoOutput(); } catch (error) { let err = error as BusinessError; console.error('Failed to createPhotoOutput errorCode = ' + err.code); } if (photoOutput === undefined) { return; } // 调用上面的回调函数来保存图片 setPhotoOutputCb(photoOutput, context); // 开始配置会话 try { photoSession.beginConfig(); } catch (error) { let err = error as BusinessError; console.error('Failed to beginConfig. errorCode = ' + err.code); } // 向会话中添加相机输入流 try { photoSession.addInput(cameraInput); } catch (error) { let err = error as BusinessError; console.error('Failed to addInput. errorCode = ' + err.code); } // 向会话中添加预览输出流 try { photoSession.addOutput(previewOutput); } catch (error) { let err = error as BusinessError; console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code); } // 向会话中添加拍照输出流 try { photoSession.addOutput(photoOutput); } catch (error) { let err = error as BusinessError; console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code); } // 提交会话配置 await photoSession.commitConfig(); // 启动会话 await photoSession.start().then(() => { console.info('Promise returned to indicate the session start success.'); }); // 判断设备是否支持闪光灯 let flashStatus: boolean = false; try { flashStatus = photoSession.hasFlash(); } catch (error) { let err = error as BusinessError; console.error('Failed to hasFlash. errorCode = ' + err.code); } console.info('Returned with the flash light support status:' + flashStatus); if (flashStatus) { // 判断是否支持自动闪光灯模式 let flashModeStatus: boolean = false; try { let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); flashModeStatus = status; } catch (error) { let err = error as BusinessError; console.error('Failed to check whether the flash mode is supported. errorCode = ' + err.code); } if(flashModeStatus) { // 设置自动闪光灯模式 try { photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); } catch (error) { let err = error as BusinessError; console.error('Failed to set the flash mode. errorCode = ' + err.code); } } } // 判断是否支持连续自动变焦模式 let focusModeStatus: boolean = false; try { let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); focusModeStatus = status; } catch (error) { let err = error as BusinessError; console.error('Failed to check whether the focus mode is supported. errorCode = ' + err.code); } if (focusModeStatus) { // 设置连续自动变焦模式 try { photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); } catch (error) { let err = error as BusinessError; console.error('Failed to set the focus mode. errorCode = ' + err.code); } } ``` -------------------------------- ### Complete Camera Background Recovery Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/camera-background-recovery This snippet demonstrates the full process of setting up a camera session for photo capture, including creating output streams, configuring the session, starting it, and capturing a photo. It also includes checks and settings for flash and focus modes, and zoom functionality. ```typescript // 创建拍照输出流。 let photoOutput: camera.PhotoOutput | undefined = undefined; try { photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]); } catch (error) { let err = error as BusinessError; console.error('Failed to createPhotoOutput errorCode = ' + err.code); } if (photoOutput === undefined) { return; } // 创建会话。 let photoSession: camera.PhotoSession | undefined = undefined; try { photoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession; } catch (error) { let err = error as BusinessError; console.error('Failed to create the session instance. errorCode = ' + err.code); } if (photoSession === undefined) { return; } // 监听session错误信息。 photoSession.on('error', (error: BusinessError) => { console.error(`Capture session error code: ${error.code}`); }); // 开始配置会话。 try { photoSession.beginConfig(); } catch (error) { let err = error as BusinessError; console.error('Failed to beginConfig. errorCode = ' + err.code); } // 向会话中添加相机输入流。 try { photoSession.addInput(cameraInput); } catch (error) { let err = error as BusinessError; console.error('Failed to addInput. errorCode = ' + err.code); } // 向会话中添加预览输出流。 try { photoSession.addOutput(previewOutput); } catch (error) { let err = error as BusinessError; console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code); } // 向会话中添加拍照输出流。 try { photoSession.addOutput(photoOutput); } catch (error) { let err = error as BusinessError; console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code); } // 提交会话配置。 await photoSession.commitConfig(); // 启动会话。 await photoSession.start().then(() => { console.info('Promise returned to indicate the session start success.'); }); // 判断设备是否支持闪光灯。 let flashStatus: boolean = false; try { flashStatus = photoSession.hasFlash(); } catch (error) { let err = error as BusinessError; console.error('Failed to hasFlash. errorCode = ' + err.code); } console.info('Returned with the flash light support status:' + flashStatus); if (flashStatus) { // 判断是否支持自动闪光灯模式。 let flashModeStatus: boolean = false; try { let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); flashModeStatus = status; } catch (error) { let err = error as BusinessError; console.error('Failed to check whether the flash mode is supported. errorCode = ' + err.code); } if(flashModeStatus) { // 设置自动闪光灯模式。 try { photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); } catch (error) { let err = error as BusinessError; console.error('Failed to set the flash mode. errorCode = ' + err.code); } } } // 判断是否支持连续自动变焦模式。 let focusModeStatus: boolean = false; try { let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); focusModeStatus = status; } catch (error) { let err = error as BusinessError; console.error('Failed to check whether the focus mode is supported. errorCode = ' + err.code); } if (focusModeStatus) { // 设置连续自动变焦模式。 try { photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); } catch (error) { let err = error as BusinessError; console.error('Failed to set the focus mode. errorCode = ' + err.code); } } // 获取相机支持的可变焦距比范围。 let zoomRatioRange: Array = []; try { zoomRatioRange = photoSession.getZoomRatioRange(); } catch (error) { let err = error as BusinessError; console.error('Failed to get the zoom ratio range. errorCode = ' + err.code); } if (zoomRatioRange.length <= 0) { return; } // 设置可变焦距比。 try { photoSession.setZoomRatio(zoomRatioRange[0]); } catch (error) { let err = error as BusinessError; console.error('Failed to set the zoom ratio value. errorCode = ' + err.code); } let photoCaptureSetting: camera.PhotoCaptureSetting = { quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高。 rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0。 } // 使用当前拍照设置进行拍照。 photoOutput.capture(photoCaptureSetting, (err: BusinessError) => { if (err) { console.error(`Failed to capture the photo ${err.message}`); return; } console.info('Callback invoked to indicate the photo capture request success.'); }); console.info('onForeGround recovery end.'); } ``` -------------------------------- ### GetShapeSize Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-getshapesize This example shows how to create a Tensor and then use the GetShapeSize function to get the total number of elements in the tensor. ```cpp Tensor tensor{{{8, 3, 224, 224}, {16, 3, 224, 224}}, // shape {ge::FORMAT_ND, ge::FORMAT_FRACTAL_NZ, {}}, // format kOnDeviceHbm, // placement ge::DT_FLOAT16, // dt nullptr}; auto shape_size = tensor.GetShapeSize(); // 16*3*224*224 ``` -------------------------------- ### Example: Using Constructors with PlatformAscendC for Tiling Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-matmul-tiling-constructor Demonstrates using constructors that take PlatformAscendC for single-core, multi-core, and BatchMatmul tiling. Includes setting types and retrieving tiling data. ```cpp // 单核Tiling auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); matmul_tiling::MatmulApiTiling tiling(ascendcPlatform); tiling.SetAType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_FLOAT16); // ... optiling::TCubeTiling tilingData; int ret = tiling.GetTiling(tilingData); // 若返回值ret为-1,表示Tiling参数生成失败 // 多核Tiling auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); matmul_tiling::MultiCoreMatmulTiling tiling(ascendcPlatform); tiling.SetDim(1); // ... optiling::TCubeTiling tilingData; int ret = tiling.GetTiling(tilingData); // 若返回值ret为-1,表示Tiling参数生成失败 // BatchMatmul Tiling auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); matmul_tiling::BatchMatmulTiling bmmTiling(ascendcPlatform); bmmTiling.SetAType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_FLOAT16); // ... optiling::TCubeTiling tilingData; int ret = bmmTiling.GetTiling(tilingData); // 若返回值ret为-1,表示Tiling参数生成失败 ``` -------------------------------- ### GetOverHeadLength Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-getoverheadlength Example demonstrating how to call GetOverHeadLength to get the data description length. Ensure the capacity is defined before calling. ```cpp size_t capacity = 100U; auto length = ContinuousVectorVector::GetOverHeadLength(capacity); ``` -------------------------------- ### Complete Camera Shooting Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/camera-shooting-case This snippet demonstrates the full lifecycle of setting up a camera for photo capture. It includes obtaining supported modes and capabilities, creating and configuring input/output streams, setting up the capture session, and initiating the capture process. Ensure all necessary resources and callbacks are properly managed. ```typescript // 获取支持的模式类型。 let sceneModes: Array = cameraManager.getSupportedSceneModes(cameraArray[0]); let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0; if (!isSupportPhotoMode) { console.error('photo mode not support'); releaseResources(); return; } // 获取相机设备支持的输出流能力。 let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO); if (!cameraOutputCap) { console.error("cameraManager.getSupportedOutputCapability error"); return; } console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); let previewProfilesArray: Array = cameraOutputCap.previewProfiles; if (!previewProfilesArray || previewProfilesArray.length <= 0) { console.error("previewProfilesArray is null or []"); releaseResources(); return; } let photoProfilesArray: Array = cameraOutputCap.photoProfiles; if (!photoProfilesArray || photoProfilesArray.length <= 0) { console.error("photoProfilesArray is null or []"); releaseResources(); return; } // 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface。 resources.previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); if (!resources.previewOutput) { console.error('previewOutput is null'); releaseResources(); return; } try { // 监听预览输出错误信息。 resources.previewOutput.on('error', (error: BusinessError) => { console.error(`Preview output error code: ${error.code}`); }); } catch (e) { console.error(`previewOutput.on call failed, error: ${JSON.stringify(e)}`); } // 创建拍照输出流。 resources.photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]); if (!resources.photoOutput) { console.error('photoOutput is null'); releaseResources(); return; } // 调用上面的回调函数来保存图片。 setPhotoOutputCb(resources.photoOutput); // 创建会话。 let photoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO); if (!photoSession) { console.error('photoSession is null'); releaseResources(); return; } resources.photoSession = photoSession as camera.PhotoSession; try { // 监听session错误信息。 resources.photoSession.on('error', (error: BusinessError) => { console.error(`Capture session error code: ${error.code}`); }); } catch (e) { console.error(`photoSession.on call failed, error: ${JSON.stringify(e)}`); } // 开始配置会话。 resources.photoSession.beginConfig(); // 向会话中添加相机输入流。 resources.photoSession.addInput(resources.cameraInput); // 向会话中添加预览输出流。 resources.photoSession.addOutput(resources.previewOutput); // 向会话中添加拍照输出流。 resources.photoSession.addOutput(resources.photoOutput); // 提交会话配置。 await resources.photoSession.commitConfig(); // 启动会话。 await resources.photoSession.start() // 判断设备是否支持闪光灯。 let flashStatus: boolean = false; flashStatus = resources.photoSession.hasFlash(); console.info('Returned with the flash light support status:' + flashStatus); if (flashStatus) { // 判断是否支持自动闪光灯模式。 let flashModeStatus: boolean = resources.photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); if(flashModeStatus) { // 设置自动闪光灯模式。 resources.photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); } } // 判断是否支持连续自动变焦模式。 let focusModeStatus: boolean = resources.photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); if (focusModeStatus) { // 设置连续自动变焦模式。 resources.photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); } // 获取相机支持的可变焦距比范围。 let zoomRatioRange: Array = []; try { zoomRatioRange = resources.photoSession.getZoomRatioRange(); } catch (error) { let err = error as BusinessError; console.error('Failed to get the zoom ratio range. errorCode = ' + err.code); } if (zoomRatioRange.length > 0) { // 设置可变焦距比。 try { resources.photoSession.setZoomRatio(zoomRatioRange[0]); } catch (error) { let err = error as BusinessError; console.error('Failed to set the zoom ratio value. errorCode = ' + err.code); } } let photoCaptureSetting: camera.PhotoCaptureSetting = { quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高。 rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0。 } // 使用当前拍照设置进行拍照。 try { await resources.photoOutput.capture(photoCaptureSetting); } catch (error) { let err = error as BusinessError; console.error(`capture call failed, err: ${JSON.stringify(err)}`); } // 需要在拍照结束之后调用以下关闭相机和释放会话流程,避免拍照未结束就将会话释放。 ``` -------------------------------- ### Example: Using No-Argument Constructors for Tiling Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-matmul-tiling-constructor Demonstrates the usage of no-argument constructors for single-core, multi-core, and BatchMatmul tiling. Includes setting types and getting tiling data. ```cpp // 单核Tiling matmul_tiling::MatmulApiTiling tiling; tiling.SetAType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_FLOAT16); // ... optiling::TCubeTiling tilingData; int ret = tiling.GetTiling(tilingData); // 若返回值ret为-1,表示Tiling参数生成失败 // 多核Tiling matmul_tiling::MultiCoreMatmulTiling tiling; tiling.SetDim(1); // ... optiling::TCubeTiling tilingData; int ret = tiling.GetTiling(tilingData); // 若返回值ret为-1,表示Tiling参数生成失败 // BatchMatmul Tiling matmul_tiling::BatchMatmulTiling bmmTiling; bmmTiling.SetAType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_FLOAT16); // ... optiling::TCubeTiling tilingData; int ret = bmmTiling.GetTiling(tilingData); // 若返回值ret为-1,表示Tiling参数生成失败 ``` -------------------------------- ### Configure UIAbility Startup Window Parameters Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/application-startup-options This snippet demonstrates how to import necessary modules, create a Want object, and configure StartOptions with window parameters like start window icon, background color, and dimensions before starting a UIAbility. It also shows how to create a PixelMap for the start window icon. ```typescript import { AbilityConstant, StartOptions, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; import { image } from '@kit.ImageKit'; const DOMAIN = 0x0000; const TAG: string = '[StartAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class SetBackgroundColorAbility extends UIAbility { // ... async onForeground(): Promise { // Ability has brought to foreground hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); let want: Want = { deviceId: '', // deviceId为空表示本设备 bundleName: 'com.example.startoptions', abilityName: 'EntryAbility', parameters: { // 自定义信息 info: '从EntryAbility启动' } }; // 创建PixelMap对象 let color = new ArrayBuffer(512 * 512 * 4); let bufferArr = new Uint8Array(color); for (let i = 0; i < bufferArr.length; i += 4) { bufferArr[i] = 255; bufferArr[i+1] = 0; bufferArr[i+2] = 122; bufferArr[i+3] = 255; } let windowParam: window.WindowCreateParams = {}; let options: StartOptions = { startWindowIcon: await image.createPixelMap(color, { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 512, width: 512 } }), startWindowBackgroundColor: '#E510FFFF', // ARGB格式 minWindowWidth: 320, minWindowHeight: 240, maxWindowWidth: 2560, maxWindowHeight: 2560, windowCreateParams: windowParam }; this.context.startAbility(want, options).then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in starting ability.'); }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `Failed to start ability. Code is ${err.code}, message is ${err.message}`); }); } // ... } ``` -------------------------------- ### GetAttrNum Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-getattrnum Example demonstrating how to get the number of attributes using GetAttrNum. It first retrieves the RuntimeAttrs object and then calls GetAttrNum on it. ```cpp const RuntimeAttrs * runtime_attrs = kernel_context->GetAttrs(); size_t attr_num = runtime_attrs->GetAttrNum(); ``` -------------------------------- ### FreeAllEvent Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-tque-freeallevent This example demonstrates the usage of FreeAllEvent after dequeuing and freeing a tensor. It shows the typical setup involving TPipe and TQueBind. ```c++ 1. // 接口:DeQue Tensor 2. AscendC::TPipe pipe; 3. AscendC::TQueBind que; 4. int num = 4; 5. int len = 1024; 6. pipe.InitBuffer(que, num, len); 7. AscendC::LocalTensor tensor1 = que.AllocTensor(); 8. que.EnQue(tensor1); 9. tensor1 = que.DeQue(); // 将tensor从VECOUT的Queue中搬出 10. que.FreeTensor(tensor1); 11. que.FreeAllEvent(); ```