content
stringlengths
12
2.72M
<reponame>Eduardop/VES /*======================================================================== VES --- VTK OpenGL ES Rendering Toolkit http://www.kitware.com/ves Copyright 2011 Kitware, Inc. Copyright 2012 <NAME>, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ========================================================================*/ #ifndef VESRENDERSTATE_H #define VESRENDERSTATE_H // VES includes #include "vesMaterial.h" #include "vesMath.h" #include "vesSetGet.h" // Forward declarations class vesMapper; /*! Data structure to hold objects and states related to rendering. */ class vesRenderState { public: vesTypeMacro(vesRenderState); vesRenderState() { this->m_identity = new vesMatrix4x4f; m_identity->setIdentity(); this->m_modelViewMatrix = this->m_identity; this->m_projectionMatrix = this->m_identity; } ~vesRenderState() { delete this->m_identity; this->m_identity = 0x0; } void applyMaterial(const vesSharedPtr<vesMaterial> &material) { if (material && material != this->m_material) { this->m_material = material; } } void removeMaterial(const vesSharedPtr<vesMaterial> &material) { if (material && material == this->m_material) { this->m_material->remove(*this); } } void applyMapper(const vesSharedPtr<vesMapper> &mapper) { if (mapper && mapper != this->m_mapper) { this->m_mapper = mapper; } } void applyModelViewMatrix(vesMatrix4x4f *modelViewMatrix) { if (modelViewMatrix && modelViewMatrix != this->m_modelViewMatrix) { this->m_modelViewMatrix = modelViewMatrix; } } void applyProjectionMatrix(vesMatrix4x4f *projectionMatrix) { if (projectionMatrix && projectionMatrix != m_projectionMatrix) { this->m_projectionMatrix = projectionMatrix; } } vesSharedPtr<vesMaterial> m_material; vesSharedPtr<vesMapper> m_mapper; vesMatrix4x4f *m_identity; vesMatrix4x4f *m_projectionMatrix; vesMatrix4x4f *m_modelViewMatrix; }; #endif // VESRENDERSTATE_H
/*********************** auth: <EMAIL> date: 2020-03-21 18:05:16 name: VloudStream.h ************************/ #import <Foundation/Foundation.h> #import <UIKit/UIImage.h> #import "RTCMacros.h" #import "RTCVideoRenderer.h" NS_ASSUME_NONNULL_BEGIN typedef enum VloudStreamConnectionState : NSInteger VloudStreamConnectionState; enum VloudStreamConnectionState : NSInteger { VloudStreamInited, VloudStreamConnecting, VloudStreamFailed, VloudStreamDisconnected, VloudStreamConnected, VloudStreamClosed, }; @class VloudStream; @class VloudStatsReport; @class VloudStreamConfig; @class VloudVideoRenderer; @protocol VloudVideoCapture; RTC_OBJC_EXPORT @protocol VloudStreamDelegate <NSObject> @optional /** * 当前流的视频轨准备好时,该函数被调用 * @param vloudStream 准备好视频轨的 VloudStream */ - (void)vloudStreamDidAddVideoTrack:(VloudStream *)vloudStream; /** * 当前流的视频轨被移除时,该函数被调用 * @param vloudStream 被移除了视频轨的 VloudStream */ - (void)vloudStreamDidRemoveVideoTrack:(VloudStream *)vloudStream; /** * 当前流的音频轨准备好时,该函数被调用 * @param vloudStream 准备好音频轨的 VloudStream */ - (void)vloudStreamDidAddAudioTrack:(VloudStream *)vloudStream; /** * 当前流的音频轨被移除时,该函数被调用 * @param vloudStream 被移除了音频轨的 VloudStream */ - (void)vloudStreamDidRemoveAudioTrack:(VloudStream *)vloudStream; /** * 当前流的音视频状态发生变化时,该函数被调用 * @param vloudStream 状态发生变化的 VloudStream * @param enableAudio 是否启用音频 * @param enableVideo 是否启用视频 */ - (void)vloudStream:(VloudStream *)vloudStream didAudioStateChange:(BOOL)enableAudio didVideoStateChange:(BOOL)enableVideo; /** * 当前流的连接状态变化时,该函数被调用 * @param vloudStream 状态发生变化的 VloudStream * @param newState 变化后的状态 */ - (void)vloudStream:(VloudStream *)vloudStream connectionChange:(VloudStreamConnectionState)newState; /** * 启用 [VloudClient statisticsStatus:delay:updateInterval:] * 并调用 [VloudStream startReportStatus] 方法后,会定期调用该函数 * @param vloudStream 获取信息的 VloudStream * @param statsReport VloudStream 流的信息 */ - (void)vloudStream:(VloudStream *)vloudStream didStatsReport:(VloudStatsReport *)statsReport; /** * 当前流的转推流状态变化时,该函数被调用 * @param vloudStream 状态发生变化的 VloudStream * @param bridge 是否开启转推流 */ - (void)vloudStream:(VloudStream *)vloudStream didBridgeStateChange:(BOOL)bridge; @end RTC_OBJC_EXPORT @interface VloudStream : NSObject + (VloudStream *)create:(VloudStreamConfig *)config; /// 用于接收 VloudStream 事件回调 @property(nonatomic, weak, nullable) id<VloudStreamDelegate> delegate; /// 当前流所在的房间 @property(nonatomic, readonly) NSString *roomId; /// 当前流所属用户 @property(nonatomic, readonly) NSString *userId; /// 当前流的 ID @property(nonatomic, readonly) NSString *streamId; /// 当前流的配置信息 @property(nonatomic, copy) VloudStreamConfig *config; /// 是否开启音频,更改该属性会设置音频状态 @property(nonatomic, assign) BOOL enableAudio; /// 是否开启视频,更改该属性会设置视频状态 @property(nonatomic, assign) BOOL enableVideo; /// 是否是本地流 @property(nonatomic, readonly) BOOL isLocal; /// 当前流是否含有音频 @property(nonatomic, readonly) BOOL hasAudio; /// 当前流是否含有视频 @property(nonatomic, readonly) BOOL hasVideo; /// 当前流是否为推流镜像 @property(nonatomic, readonly) BOOL isMirror; /// 当前流的转推流地址 @property(nonatomic, readonly) NSString *bridgeUrl; - (instancetype)init NS_UNAVAILABLE; /** * 设置视频源 * @param capture 视频源 */ - (void)setVideoCaptrue:(id<VloudVideoCapture>)capture; /** * 添加当前流的渲染 View * @param renderer @see <VloudVideoRenderer> */ - (void)addRenderer:(VloudVideoRenderer *)renderer; /** * 为当前流移除视频渲染 View * @param renderer @see <VloudVideoRenderer> */ - (void)removeRenderer:(VloudVideoRenderer *)renderer; /** * 设置当前流的音频音量 * @param volume 设置的音量值,范围为0~10 */ - (void)setAudioVolume:(double)volume; /** * 设置采集的音量 * @param volume 设置的音量值,范围为0~100 */ - (void)setRecordVolume:(int)volume; /** * 读取采集音量值 */ - (int)recordVolume; /** * 开始获取当前流状态的信息,该信息会通过 [VloudStreamDelegate vloudStream:didStatsReport:] 方法回调 */ - (void)startReportStatus; /** * 停止获取流状态的信息 */ - (void)stopReportStatus; /** * 开始转推流 * @param url 转推流地址 * @param delay 转推流的延迟,单位是毫秒 */ - (void)startBridge:(NSString *)url delay:(NSInteger)delay; /** * 开始转推流 * @param url 转推流地址 * @param delay 转推流的延迟,单位是毫秒 * @param interval 转推流的关键帧间隔,单位是毫秒 */ - (void)startBridge:(NSString *)url delay:(NSInteger)delay interval:(NSInteger)interval; /** * 推流镜像 * @param isMirror 是否推流镜像 */ - (void)adjustMirror:(BOOL)isMirror; /** * 停止转推流 */ - (void)stopBridge; /** * 开启预览 */ - (void)previewCapture; /** * 关闭预览 */ - (void)unPreviewCapture; /** * 调用该方法的 VloudStream 是本地流时,推送本地流 */ - (void)publish; /** * 调用该方法的 VloudStream 是本地流时,停止推送本地流 */ - (void)unPublish; /** * 调用该方法的 VloudStream 是本地流时,停止推送本地流 * @param unPreview 取消推流时是否不保留预览  */ - (void)unPublishWithUnPreview:(BOOL)unPreview; /** * 调用该方法的 VloudStream 是远端流时,拉取远端流 */ - (void)subscribe; /** * 调用该方法的 VloudStream 是远端流时,停止拉取远端流 */ - (void)unsubscribe; /** * 切换当前流的视频流 * @param index 视频流的索引,索引从0开始。视频流根据索引,从低分辨率到高分辨率递增。 * 视频流的数量可通过 VloudStreamConfig.videoStreamCount 属性获取 */ - (void)toggleVideoStream:(NSInteger)index; /** * 添加图片水印 * * @param logoId 水印 id,用于替换或者移除水印 * @param image UIImage 对象 * @param left 水印打印位置的左坐标点 * @param top 水印打印位置的上坐标点 * @param alpha 水印透明度 0 ~ 1.0 */ - (void)addImageLogoWithId:(NSString *_Nonnull)logoId image:(UIImage *)image left:(int)left top:(int)top alpha:(double)alpha; /** * 添加图片水印 * * @param logoId 水印 id,用于替换或者移除水印 * @param image UIImage 对象 * @param left 水印打印位置的左坐标点 * @param top 水印打印位置的上坐标点 * @param scaleWidth 水印图片缩放的宽度 * @param scaleHeight 水印图片缩放的高度 * @param alpha 水印透明度 0 ~ 1.0 */ - (void)addImageLogoWithId:(NSString *_Nonnull)logoId image:(UIImage *)image left:(int)left top:(int)top scaleWidth:(int)scaleWidth scaleHeight:(int)scaleHeight alpha:(double)alpha; /** * 添加文字水印 * * @param logoId 水印 id,用于替换或者移除水印 * @param text <p>水印文字内容,支持添加时间戳。需要添加时间戳时,文本内需带有 "${timestamp:{format}}" 字样。</p> * <p>{format} 内容请参考 strftime 函数: http://www.cplusplus.com/reference/ctime/strftime/</p> * <p>例如: ${timestamp:%Y-%m-%d %H:%M:%S} </p> * @param path <p>字体文件的路径,如该参数为nil,则使用 SDK 内附带的思源开源可商用字体: * https://github.com/adobe-fonts/source-han-sans/blob/release/SubsetOTF/CN/SourceHanSansCN-Regular.otf</p> * <p>注意:如该路径的字体有问题,则可能导致崩溃!!!</p> * @param left 水印打印位置的左坐标点 * @param top 水印打印位置的上坐标点 * @param color 水印文字的颜色 * @param size 水印文字的大小 * @param alpha 水印文字的透明度 */ - (void)addTextLogoWithId:(NSString *_Nonnull)logoId text:(NSString *)text path:(NSString *)path left:(int)left top:(int)top color:(int)color size:(int)size alpha:(double)alpha; /** * 删除水印 * * @param id 需要删除的水印的 id */ - (void)removeLogoWithId:(NSString *_Nonnull)logoId; - (void)resetAudioModule; /** * 当前流是本地流时,销毁 */ - (void)destroy; @end NS_ASSUME_NONNULL_END
// // MyBeautyPlanDailyViewController.h // MyBeautyPlanDailyViewController // // Created by yanglinxia on 16/9/17. // Copyright © 2016年 yanglinxia. All rights reserved. // #import <UIKit/UIKit.h> @interface MyBeautyPlanDailyViewController : UIViewController @end
// // GMOPersonViewController.h // GauchoMobile // // GMOPersonViewController is a subclass of ABPersonViewController that adds a Done button // to allow it to be dismissed when presented modally on the iPad. // #import <AddressBookUI/AddressBookUI.h> @interface GMOPersonViewController : ABPersonViewController @end
#pragma once #include "GameBase.h" class CTetrisGame : public CGameBase { public: // Start virtual void Start(); // Update // param: dt, millisecond virtual void Update(float dt); // Get game id virtual EnGameID GetGameID(); // Button event virtual void OnButtonEvent(const SEventContextButton* pButtonEvent); // Save data virtual bool SaveData(bool bForceFlag); public: // Get shape count virtual int GetShapeCount(); // On tetris move finish virtual void OnTetrisMoveFinish(); // Check game over virtual bool CheckShapePos(const POSITION& stNextPos, int nShapeID); // Get shape brick state virtual bool GetShapeBrickState(int nShapeID, int nRowIdx, int nColIdx); // Update other virtual void UpdateOther(float dt, bool& bUpdateFlag); // Update valid brick state virtual void UpdateValidBricksState(); // Load tetris record virtual bool LoadTetrisData(); // Save tetris record virtual bool SaveTetrisData(bool bForceFlag = false); public: // Remove rows bool RemoveRows(); // Update tetris shape void UpdateShape(int nShapeID, const POSITION& stNewPos, bool bSyncFlag = false); // Random tetris shape virtual void RandomShape(bool bUpdateFlag = false, int nCurShapeID = TETRIS_SHAPE_COUNT, int nNextShapeID = TETRIS_SHAPE_COUNT); // Get shape row offset int GetShapeRowOffset(int nShapeID); // Get shape column offset int GetShapeColOffset(int nShapeID); // Get shape brick state (origin) bool GetShapeBrickOriginState(int nShapeID, int nRowIdx, int nColIdx); private: // Update tetris void __TetrisControlMove(float dt, bool& bUpdateFlag); // Tetris move down void __TetrisMoveDown(float dt, bool& bUpdateFlag); // Check one row full bool __CheckOneRowFull(int nRowIdx); // Remove one row void __RemoveOneRow(int nRowIdx); // Get next shape id int __GetNextShapeID(); ////////////////////////////////////////////////////////////////////////// // Get move interval int __GetTetrisMoveInterval(); public: enum { REMOVE_ONE_ROW_ADD_SCORE = 10, TETRIS_MOVE_INTERVAL = 500, CONTROL_MOVE_INTERVAL = 115, }; struct _TTetrisData { int nShapeID; POSITION stPos; int nMoveInterval; int nDir; int nControlInterval; bool bSpeedUpFlag; }; protected: // Current tetris data _TTetrisData m_stTetrisData; // Next shape int m_nNextShapeID; };
<reponame>scivision/hwloc<gh_stars>0 /* * Copyright © 2012-2022 Inria. All rights reserved. * See COPYING in top-level directory. */ #include "private/autogen/config.h" #include "hwloc.h" #include "hwloc/plugins.h" /* private headers allowed for convenience because this plugin is built within hwloc */ #include "private/misc.h" #include "private/debug.h" #include <nvml.h> #ifdef NVML_NVLINK_MAX_LINKS static unsigned hwloc__nvml_get_peer_gpu_by_pci(nvmlPciInfo_t peer, unsigned nb, nvmlPciInfo_t *gpus) { unsigned i; for(i=0; i<nb; i++) if (gpus[i].domain == peer.domain && gpus[i].bus == peer.bus && gpus[i].device == peer.device) return i; return (unsigned)-1; } static hwloc_obj_t hwloc__nvml_get_peer_obj_by_pci(struct hwloc_topology *topology, hwloc_obj_t gpu, nvmlPciInfo_t peer_bdf) { hwloc_obj_t obj; /* we want the exact object here because we'll use it PCI class below * (we can't use hwloc_pci_find_parent_by_busid() which is enough for inserting OSdev by locality). */ obj = hwloc_pci_find_by_busid(topology, peer_bdf.domain, peer_bdf.bus, peer_bdf.device, 0); if (!obj) { enum hwloc_type_filter_e pfilter; hwloc_topology_get_type_filter(topology, HWLOC_OBJ_PCI_DEVICE, &pfilter); /* we need PCI devices to be filtered-in */ if (pfilter != HWLOC_TYPE_FILTER_KEEP_NONE) { static int warned = 0; if (!warned && !hwloc_hide_errors()) fprintf(stderr, "hwloc failed to find NVLink peer %04x:%02x:%02x\n", peer_bdf.domain, peer_bdf.bus, peer_bdf.device); warned = 1; } else { static int warned = 0; if (!warned) hwloc_debug("hwloc failed to find NVLink peer %04x:%02x:%02x because PCI devices are filtered-out\n", peer_bdf.domain, peer_bdf.bus, peer_bdf.device); warned = 1; } return NULL; } /* We want a non-PCI bridge. * On POWER8/9, it's class 0680 vendor 1014 (IBM) model 04ea prog-if 00. * For NVSwitch, it's class 0680 with prog-if 01 vendor 10de (NVIDIA). * Baseclass 0x06 is enough to avoid GPUs (baseclass 0x03), * and that's needed because some GPUs may be hidden from us because of cgroups. */ if (obj->type != HWLOC_OBJ_PCI_DEVICE || (obj->attr->pcidev.class_id >> 8 != 0x06)) return NULL; switch (obj->attr->pcidev.vendor_id) { case 0x1014: { /* IBM OpenCAPI port, return the CPU object. */ if (!getenv("HWLOC_NVML_USE_OPENCAPI_LOCALITY")) { /* OpenCAPI Bridge PCI locality is wrong on POWER8 (equal to the entire machine). * Both POWER8 and POWER9 have correct GPU locality, use that one instead. * This will only break if PCI and NVLink are not connected to the same location, unlikely. */ obj = gpu; } /* return a CPU side parent */ while (!obj->cpuset) obj = obj->parent; return obj; } case 0x10de: { /* NVIDIA NVSwitch, return the PCI object, we don't have anything better. * Mark it as subtype NVSwitch so that the core doesn't remove it. */ if (!obj->subtype) obj->subtype = strdup("NVSwitch"); return obj; } default: { static int warned = 0; if (!warned && !hwloc_hide_errors()) fprintf(stderr, "hwloc failed to recognize NVLink peer %04x:%02x:%02x class %04x vendor %04x device %04x\n", peer_bdf.domain, peer_bdf.bus, peer_bdf.device, obj->attr->pcidev.class_id, obj->attr->pcidev.vendor_id, obj->attr->pcidev.device_id); warned = 1; return NULL; } } } static unsigned hwloc__nvml_store_peer_obj(hwloc_obj_t obj, unsigned nbgpus, unsigned *nbobjs, hwloc_obj_t *objs) { unsigned i; /* is it already in the array? */ for(i=nbgpus; i<*nbobjs; i++) if (objs[i] == obj) return i; /* append it */ objs[*nbobjs] = obj; return (*nbobjs)++; } static int hwloc__nvml_add_nvlink_bandwidth(hwloc_topology_t topology, unsigned nbobjs, hwloc_obj_t *objs, hwloc_uint64_t *bws) { void *handle; int err; handle = hwloc_backend_distances_add_create(topology, "NVLinkBandwidth", HWLOC_DISTANCES_KIND_FROM_OS|HWLOC_DISTANCES_KIND_MEANS_BANDWIDTH, 0); if (!handle) goto out; err = hwloc_backend_distances_add_values(topology, handle, nbobjs, objs, bws, 0); if (err < 0) goto out; /* arrays are now attached to the handle */ objs = NULL; bws = NULL; err = hwloc_backend_distances_add_commit(topology, handle, 0 /* don't group GPUs */); if (err < 0) goto out; return 0; out: free(objs); free(bws); return -1; } #endif /* NVML_NVLINK_MAX_LINKS */ static int hwloc_nvml_discover(struct hwloc_backend *backend, struct hwloc_disc_status *dstatus) { /* * This backend uses the underlying OS. * However we don't enforce topology->is_thissystem so that * we may still force use this backend when debugging with !thissystem. */ struct hwloc_topology *topology = backend->topology; enum hwloc_type_filter_e filter; nvmlReturn_t ret; unsigned nb, i; #ifdef NVML_NVLINK_MAX_LINKS unsigned nbobjs, j; hwloc_obj_t *objs; unsigned *peer_indexes; nvmlPciInfo_t *gpu_bdfs; hwloc_uint64_t *bws; int found_nvlinks = 0; #endif assert(dstatus->phase == HWLOC_DISC_PHASE_IO); hwloc_topology_get_type_filter(topology, HWLOC_OBJ_OS_DEVICE, &filter); if (filter == HWLOC_TYPE_FILTER_KEEP_NONE) return 0; ret = nvmlInit(); if (NVML_SUCCESS != ret) { if (!hwloc_hide_errors()) { const char *error = nvmlErrorString(ret); fprintf(stderr, "hwloc/nvml: Failed to initialize with nvmlInit(): %s\n", error); } return -1; } ret = nvmlDeviceGetCount(&nb); if (NVML_SUCCESS != ret || !nb) { nvmlShutdown(); return 0; } #ifdef NVML_NVLINK_MAX_LINKS /* the PCI BDF of each GPU */ gpu_bdfs = calloc(nb, sizeof(*gpu_bdfs)); /* the nvlink matrix will require one slot per GPU and possibly additional slots for non-GPU endpoints, * usually one per CPU, but let's take an easy upper bound. */ objs = calloc(nb * NVML_NVLINK_MAX_LINKS, sizeof(*objs)); bws = calloc(nb * NVML_NVLINK_MAX_LINKS * nb * NVML_NVLINK_MAX_LINKS, sizeof(*bws)); /* array to translate peer of i-th link of j-th GPU into an peer object index inside objs */ peer_indexes = calloc(nb * NVML_NVLINK_MAX_LINKS, sizeof(*peer_indexes)); if (!gpu_bdfs || !objs || !gpu_bdfs || !bws || !peer_indexes) { free(gpu_bdfs); free(objs); free(bws); free(peer_indexes); return -1; } #endif for(i=0; i<nb; i++) { nvmlPciInfo_t pci; nvmlDevice_t device; hwloc_obj_t osdev, parent; char buffer[64]; ret = nvmlDeviceGetHandleByIndex(i, &device); assert(ret == NVML_SUCCESS); osdev = hwloc_alloc_setup_object(topology, HWLOC_OBJ_OS_DEVICE, HWLOC_UNKNOWN_INDEX); snprintf(buffer, sizeof(buffer), "nvml%u", i); osdev->name = strdup(buffer); osdev->subtype = strdup("NVML"); osdev->depth = HWLOC_TYPE_DEPTH_UNKNOWN; osdev->attr->osdev.type = HWLOC_OBJ_OSDEV_GPU; hwloc_obj_add_info(osdev, "Backend", "NVML"); hwloc_obj_add_info(osdev, "GPUVendor", "NVIDIA Corporation"); buffer[0] = '\0'; ret = nvmlDeviceGetName(device, buffer, sizeof(buffer)); hwloc_obj_add_info(osdev, "GPUModel", buffer); /* these may fail with NVML_ERROR_NOT_SUPPORTED on old devices */ buffer[0] = '\0'; ret = nvmlDeviceGetSerial(device, buffer, sizeof(buffer)); if (buffer[0] != '\0') hwloc_obj_add_info(osdev, "NVIDIASerial", buffer); buffer[0] = '\0'; ret = nvmlDeviceGetUUID(device, buffer, sizeof(buffer)); if (buffer[0] != '\0') hwloc_obj_add_info(osdev, "NVIDIAUUID", buffer); parent = NULL; if (NVML_SUCCESS == nvmlDeviceGetPciInfo(device, &pci)) { #ifdef NVML_NVLINK_MAX_LINKS gpu_bdfs[i] = pci; #endif parent = hwloc_pci_find_parent_by_busid(topology, pci.domain, pci.bus, pci.device, 0); #if HAVE_DECL_NVMLDEVICEGETMAXPCIELINKGENERATION if (parent && parent->type == HWLOC_OBJ_PCI_DEVICE) { unsigned maxwidth = 0, maxgen = 0; float lanespeed; nvmlDeviceGetMaxPcieLinkWidth(device, &maxwidth); nvmlDeviceGetMaxPcieLinkGeneration(device, &maxgen); /* PCIe Gen1 = 2.5GT/s signal-rate per lane with 8/10 encoding = 0.25GB/s data-rate per lane * PCIe Gen2 = 5 GT/s signal-rate per lane with 8/10 encoding = 0.5 GB/s data-rate per lane * PCIe Gen3 = 8 GT/s signal-rate per lane with 128/130 encoding = 1 GB/s data-rate per lane */ lanespeed = maxgen <= 2 ? 2.5 * maxgen * 0.8 : 8.0 * 128/130; /* Gbit/s per lane */ if (lanespeed * maxwidth != 0.) /* we found the max link speed, replace the current link speed found by pci (or none) */ parent->attr->pcidev.linkspeed = lanespeed * maxwidth / 8; /* GB/s */ } #endif } if (!parent) parent = hwloc_get_root_obj(topology); hwloc_insert_object_by_parent(topology, parent, osdev); #ifdef NVML_NVLINK_MAX_LINKS objs[i] = osdev; #endif } #ifdef NVML_NVLINK_MAX_LINKS nbobjs = nb; /* list peer objects */ for(i=0; i<nb; i++) { /* look at nvlinks */ nvmlDevice_t device; nvmlPciInfo_t pci; ret = nvmlDeviceGetHandleByIndex(i, &device); assert(ret == NVML_SUCCESS); hwloc_debug("looking at NVLinks for NVML GPU #%u...\n", i); for(j=0; j<NVML_NVLINK_MAX_LINKS; j++) { nvmlEnableState_t isActive; /* mark the peer as unknown for now */ peer_indexes[i*NVML_NVLINK_MAX_LINKS+j] = (unsigned) -1; ret = nvmlDeviceGetNvLinkState(device, j, &isActive); if (ret != NVML_SUCCESS) break; if (isActive != NVML_FEATURE_ENABLED) continue; found_nvlinks++; hwloc_debug(" NVLink #%u is active\n", j); ret = nvmlDeviceGetNvLinkRemotePciInfo(device, j, &pci); if (ret == NVML_SUCCESS) { unsigned peer_index; hwloc_debug(" goes to PCI %04x:%02x:%02x\n", pci.domain, pci.bus, pci.device); peer_index = hwloc__nvml_get_peer_gpu_by_pci(pci, nb, gpu_bdfs); if (peer_index == (unsigned)-1) { hwloc_obj_t peer_obj = hwloc__nvml_get_peer_obj_by_pci(topology, objs[i], pci); if (!peer_obj) continue; peer_index = hwloc__nvml_store_peer_obj(peer_obj, nb, &nbobjs, objs); hwloc_debug(" adding NVML peer index #%u\n", peer_index); } else { hwloc_debug(" reusing NVML peer index #%u\n", peer_index); } peer_indexes[i*NVML_NVLINK_MAX_LINKS+j] = peer_index; } } } hwloc_debug("NVML found %u GPUs within %u peers total, with %u nvlinks total\n", nb, nbobjs, found_nvlinks); if (hwloc_topology_get_flags(topology) & HWLOC_TOPOLOGY_FLAG_NO_DISTANCES) found_nvlinks = 0; if (found_nvlinks) { /* now build the matrix */ found_nvlinks = 0; /* reset back in case the version is unknown below and the matrix remains empty */ for(i=0; i<nb; i++) { nvmlDevice_t device; ret = nvmlDeviceGetHandleByIndex(i, &device); assert(ret == NVML_SUCCESS); for(j=0; j<NVML_NVLINK_MAX_LINKS; j++) { unsigned version; hwloc_uint64_t bw; unsigned peer_index = peer_indexes[i*NVML_NVLINK_MAX_LINKS+j]; if (peer_index == (unsigned)-1) continue; /* For GPU-to-GPU link, we'll get info for both direction, while GPU-to-CPU info is unique. * Only store once on both sides of diagonal. */ if (peer_index < i) continue; ret = nvmlDeviceGetNvLinkVersion(device, j, &version); if (ret != NVML_SUCCESS) continue; hwloc_debug("GPU #%u NVLink #%u has version %u\n", i, j, version); /* version1 = 20GB/s, version2=25GB/s */ if (version == 1) { bw = 20000; /* multiple links may connect same GPUs */ } else if (version == 2) { bw = 25000; /* multiple links may connect same GPUs */ } else { static int warned = 0; if (!warned && !hwloc_hide_errors()) fprintf(stderr, "Failed to recognize NVLink version %u\n", version); warned = 1; continue; } bws[i*nbobjs+peer_index] += bw; bws[peer_index*nbobjs+i] += bw; found_nvlinks++; } } if (found_nvlinks) { /* add very high artifical values on the diagonal since local is faster than remote. * there are 6 link per GPU max for now, 150GB/s, use 1TB/s for local, it somehow matches the HBM. */ for(i=0; i<nbobjs; i++) bws[i*nbobjs+i] = 1000000; hwloc__nvml_add_nvlink_bandwidth(topology, nbobjs, objs, bws); /* matrices don't need to be freed anymore */ objs = NULL; bws = NULL; } } free(objs); free(bws); free(gpu_bdfs); free(peer_indexes); #endif /* NVML_NVLINK_MAX_LINKS */ nvmlShutdown(); return 0; } static struct hwloc_backend * hwloc_nvml_component_instantiate(struct hwloc_topology *topology, struct hwloc_disc_component *component, unsigned excluded_phases __hwloc_attribute_unused, const void *_data1 __hwloc_attribute_unused, const void *_data2 __hwloc_attribute_unused, const void *_data3 __hwloc_attribute_unused) { struct hwloc_backend *backend; backend = hwloc_backend_alloc(topology, component); if (!backend) return NULL; backend->discover = hwloc_nvml_discover; return backend; } static struct hwloc_disc_component hwloc_nvml_disc_component = { "nvml", HWLOC_DISC_PHASE_IO, HWLOC_DISC_PHASE_GLOBAL, hwloc_nvml_component_instantiate, 5, /* after pci, and after cuda since likely less useful */ 1, NULL }; static int hwloc_nvml_component_init(unsigned long flags) { if (flags) return -1; if (hwloc_plugin_check_namespace("nvml", "hwloc_backend_alloc") < 0) return -1; return 0; } #ifdef HWLOC_INSIDE_PLUGIN HWLOC_DECLSPEC extern const struct hwloc_component hwloc_nvml_component; #endif const struct hwloc_component hwloc_nvml_component = { HWLOC_COMPONENT_ABI, hwloc_nvml_component_init, NULL, HWLOC_COMPONENT_TYPE_DISC, 0, &hwloc_nvml_disc_component };
<gh_stars>0 /* --------------------------------------------------------------------------- Assimp to Scene Kit Library (AssimpKit) --------------------------------------------------------------------------- Copyright (c) 2016, <NAME>, Ison Apps, AssimpKit team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the AssimpKit team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the AssimpKit team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ #import <Foundation/Foundation.h> #include <GLKit/GLKit.h> #import <SceneKit/SceneKit.h> #import "SCNAssimpScene.h" #import "PostProcessingFlags.h" /** An importer that imports the files with formats supported by Assimp and converts the assimp scene graph into a scenekit scene graph. */ @interface AssimpImporter : NSObject #pragma mark - Creating an importer /** @name Creating an importer */ /** Creates an importer to import files supported by AssimpKit. @return A new importer. */ - (id)init; #pragma mark - Loading a scene /** Loads a scene from the specified file path. @param filePath The path to the scene file to load. @param postProcessFlags The flags for all possible post processing steps. @return A new scene object, or nil if no scene could be loaded. */ - (SCNAssimpScene *)importScene:(NSString *)filePath postProcessFlags:(AssimpKitPostProcessSteps)postProcessFlags DEPRECATED_MSG_ATTRIBUTE("Please use importScene:postProcessFlags:error:"); /** Loads a scene from the specified file path. @param filePath The path to the scene file to load. @param postProcessFlags The flags for all possible post processing steps. @param error Scene import error. @return A new scene object, or nil if no scene could be loaded. */ - (SCNAssimpScene *)importScene:(NSString *)filePath postProcessFlags:(AssimpKitPostProcessSteps)postProcessFlags error:(NSError **)error; @end
<filename>practical_6/p2.c #include<sys/wait.h> #include<stdio.h> int main() { int p1, p2, p3, p4; p1 = fork (); if (p1 == -1) { printf ("Error"); return 0; } if (p1 == 0) { p2 = fork (); if (p2 == 0) { printf ("Parent is %d \n", getppid ()); printf ("child is %d \n", getpid ()); } p3 = fork (); if (p3 == -1) { printf ("Error"); return 0; } if (p3 == 0) { printf ("Parent is %d \n", getppid ()); printf ("child is %d \n", getpid ()); p4 = fork (); if (p4 == 0) { printf ("Parent is %d \n", getppid ()); printf ("child is %d \n", getpid ()); return 0; } } } return 0; }
<gh_stars>1-10 /* * $Revision: 2593 $ * * last checkin: * $Author: gutwenger $ * $Date: 2012-07-15 15:33:53 +0200 (So, 15. Jul 2012) $ ***************************************************************/ /** \file * \brief Declaration of simple graph algorithms. * * \author <NAME> and <NAME> * * \par License: * This file is part of the Open Graph Drawing Framework (OGDF). * * \par * Copyright (C)<br> * See README.txt in the root directory of the OGDF installation for details. * * \par * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * Version 2 or 3 as published by the Free Software Foundation; * see the file LICENSE.txt included in the packaging of this file * for details. * * \par * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * \par * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * * \see http://www.gnu.org/copyleft/gpl.html ***************************************************************/ #ifdef _MSC_VER #pragma once #endif #ifndef OGDF_SIMPLE_GRAPH_ALG_H #define OGDF_SIMPLE_GRAPH_ALG_H #include <ogdf/basic/EdgeArray.h> #include <ogdf/basic/SList.h> #include <ogdf/basic/BoundedStack.h> namespace ogdf { //--------------------------------------------------------- // Methods for loops //--------------------------------------------------------- //! Returns true iff \a G contains no self-loop. /** * @param G is the input graph. * @return true if \a G contains no self-loops (edges whose two endpoints are the same), false otherwise. */ OGDF_EXPORT bool isLoopFree(const Graph &G); //! Removes all self-loops from \a G and returns all nodes with self-loops in \a L. /** * @tparam NODELIST is the type of the node list for returning the nodes with self-loops. * @param G is the input graph. * @param L is assigned the list of nodes with self-loops. */ template<class NODELIST> void makeLoopFree(Graph &G, NODELIST &L) { L.clear(); edge e, eNext; for (e = G.firstEdge(); e; e = eNext) { eNext = e->succ(); if (e->isSelfLoop()) { L.pushBack(e->source()); G.delEdge(e); } } } //! Removes all self-loops from \a G. /** * @param G is the input graph. */ OGDF_EXPORT void makeLoopFree(Graph &G); //--------------------------------------------------------- // Methods for parallel edges //--------------------------------------------------------- //! Sorts the edges of \a G such that parallel edges come after each other in the list. /** * @param G is the input graph. * @param edges is assigned the list of sorted edges. */ OGDF_EXPORT void parallelFreeSort(const Graph &G, SListPure<edge> &edges); //! Returns true iff \a G contains no paralle edges. /** * A parallel edge is an edge e1=(v,w) such that there exists another edge e2=(v,w) in * the graph. Reversal edges (e.g. (v,w) and (w,v)) are not parallel edges. If you want to * test if a graph contains no undirected parallel edges, use isParallelFreeUndirected(). * * @param G is the input graph. * @return true if \a G contains no multi-edges (edges with the same source and target). */ OGDF_EXPORT bool isParallelFree(const Graph &G); //! Returns the number of parallel edges in \a G. /** * A parallel edge is an edge e1=(v,w) such that there exists another edge e2=(v,w) in * the graph. Reversal edges (e.g. (v,w) and (w,v)) are not parallel edges. If you want to * also take reversal edges into account, use numParallelEdgesUndirected(). * * @param G is the input graph. * @return is the number of parallel edges: for each bundle of parallel edges between two nodes * v and w, all but one are counted. */ OGDF_EXPORT int numParallelEdges(const Graph &G); //! Removes all but one of each bundle of parallel edges. /** * A parallel edge is an edge e1=(v,w) such that there exists another edge e2=(v,w) in * the graph. Reversal edges (e.g. (v,w) and (w,v)) are not multi-edges. If you want to * remove parallel and reversal edges, use makeParallelFreeUndirected(Graph&,EDGELIST&). * * @tparam EDGELIST is the type of edge list that will be assigned the list of parallel edges. * @param G is the input graph. * @param parallelEdges is assigned the list of remaining edges in \a G that were part of a * bundle of parallel edges in the input graph. */ template <class EDGELIST> void makeParallelFree(Graph &G, EDGELIST &parallelEdges) { parallelEdges.clear(); if (G.numberOfEdges() <= 1) return; SListPure<edge> edges; parallelFreeSort(G,edges); SListConstIterator<edge> it = edges.begin(); edge ePrev = *it++, e; bool bAppend = true; while(it.valid()) { e = *it++; if (ePrev->source() == e->source() && ePrev->target() == e->target()) { G.delEdge(e); if (bAppend) { parallelEdges.pushBack(ePrev); bAppend = false; } } else { ePrev = e; bAppend = true; } } } //! Removes all but one edge of each bundle of parallel edges in \a G. /** * A parallel edge is an edge e1=(v,w) such that there exists another edge e2=(v,w) in * the graph. Reversal edges (e.g. (v,w) and (w,v)) are not parallel edges. If you want to * remove parallel and reversal edges, use makeParallelFreeUndirected(Graph&). * * @param G is the input graph. */ inline void makeParallelFree(Graph &G) { List<edge> parallelEdges; makeParallelFree(G,parallelEdges); } //! Sorts the edges of \a G such that undirected parallel edges come after each other in the list. /** * An undirected parallel edges is an edge e1=(v,w) such that there exists another edge e2=(v,w) or (w,v) * in the graph. * * @param G is the input graph. * @param edges is assigned the list of sorted edges. * @param minIndex is assigned for each edge (v,w) the index min(index(v),index(w)). * @param maxIndex is assigned for each edge (v,w) the index max(index(v),index(w)). */ OGDF_EXPORT void parallelFreeSortUndirected( const Graph &G, SListPure<edge> &edges, EdgeArray<int> &minIndex, EdgeArray<int> &maxIndex); //! Returns true iff \a G contains no undirected parallel edges. /** * An undirected parallel edges is an edge e1=(v,w) such that there exists another edge e2=(v,w) or (w,v) * in the graph. * * @param G is the input graph. * @return true if \a G contains no undirected parallel edges. */ OGDF_EXPORT bool isParallelFreeUndirected(const Graph &G); //! Returns the number of undirected parallel edges in \a G. /** * An undirected parallel edges is an edge e1=(v,w) such that there exists another edge e2=(v,w) or (w,v) * in the graph. * * @param G is the input graph. * @return the number of undirected parallel edges; for each unordered pair {v,w} of nodes, all * but one of the edges with endpoints v and w (in any order) are counted. */ OGDF_EXPORT int numParallelEdgesUndirected(const Graph &G); //! Removes all but one of each bundle of undirected parallel edges. /** * An undirected parallel edges is an edge e1=(v,w) such that there exists another edge e2=(v,w) or (w,v) * in the graph. The function removes unordered pair {v,w} of nodes all but one of the edges with * endpoints v and w (in any order). * * @tparam EDGELIST is the type of edge list that will be assigned the list of edges. * @param G is the input graph. * @param parallelEdges is assigned the list of remaining edges that were part of a bundle * of undirected parallel edges in the input graph. */ template <class EDGELIST> void makeParallelFreeUndirected(Graph &G, EDGELIST &parallelEdges) { parallelEdges.clear(); if (G.numberOfEdges() <= 1) return; SListPure<edge> edges; EdgeArray<int> minIndex(G), maxIndex(G); parallelFreeSortUndirected(G,edges,minIndex,maxIndex); SListConstIterator<edge> it = edges.begin(); edge ePrev = *it++, e; bool bAppend = true; while(it.valid()) { e = *it++; if (minIndex[ePrev] == minIndex[e] && maxIndex[ePrev] == maxIndex[e]) { G.delEdge(e); if (bAppend) { parallelEdges.pushBack(ePrev); bAppend = false; } } else { ePrev = e; bAppend = true; } } } //! Removes all but one of each bundle of undirected parallel edges. /** * An undirected parallel edges is an edge e1=(v,w) such that there exists another edge e2=(v,w) or (w,v) * in the graph. The function removes unordered pair {v,w} of nodes all but one of the edges with * endpoints v and w (in any order). * * @param G is the input graph. */ inline void makeParallelFreeUndirected(Graph &G) { List<edge> parallelEdges; makeParallelFreeUndirected(G,parallelEdges); } //! Removes all but one of each bundle of undirected parallel edges. /** * An undirected parallel edges is an edge e1=(v,w) such that there exists another edge e2=(v,w) or (w,v) * in the graph. The function removes unordered pair {v,w} of nodes all but one of the edges with * endpoints v and w (in any order). * * @tparam EDGELIST is the type of edge list that is assigned the list of edges. * @param G is the input graph. * @param parallelEdges is assigned the list of remaining edges that were * part of a bundle of undirected parallel edges in the input graph. * @param cardPositive contains for each edge the number of removed undirected parallel edges * pointing in the same direction. * @param cardNegative contains for each edge the number of removed undirected parallel edges * pointing in the opposite direction. */ template <class EDGELIST> void makeParallelFreeUndirected( Graph &G, EDGELIST &parallelEdges, EdgeArray<int> &cardPositive, EdgeArray<int> &cardNegative) { parallelEdges.clear(); cardPositive.fill(0); cardNegative.fill(0); if (G.numberOfEdges() <= 1) return; SListPure<edge> edges; EdgeArray<int> minIndex(G), maxIndex(G); parallelFreeSortUndirected(G,edges,minIndex,maxIndex); SListConstIterator<edge> it = edges.begin(); edge ePrev = *it++, e; bool bAppend = true; int counter = 0; while(it.valid()) { e = *it++; if (minIndex[ePrev] == minIndex[e] && maxIndex[ePrev] == maxIndex[e]) { if (ePrev->source() == e->source() && ePrev->target() == e->target()) cardPositive[ePrev]++; else if (ePrev->source() == e->target() && ePrev->target() == e->source()) cardNegative[ePrev]++; G.delEdge(e); if (bAppend) { parallelEdges.pushBack(ePrev); bAppend = false; } } else { ePrev = e; bAppend = true; } } } //! Computes the bundles of undirected parallel edges in \a G. /** * Stores for one (arbitrarily chosen) reference edge all edges belonging to the same bundle of * undirected parallel edges; no edge is removed from the graph. * * @tparam EDGELIST is the type of edge list that is assigned the list of edges. * @param G is the input graph. * @param parallelEdges is assigned for each reference edge the list of edges belonging to the * bundle of undirected parallel edges. */ template <class EDGELIST> void getParallelFreeUndirected(const Graph &G, EdgeArray<EDGELIST> &parallelEdges) { if (G.numberOfEdges() <= 1) return; SListPure<edge> edges; EdgeArray<int> minIndex(G), maxIndex(G); parallelFreeSortUndirected(G,edges,minIndex,maxIndex); SListConstIterator<edge> it = edges.begin(); edge ePrev = *it++, e; while(it.valid()) { e = *it++; if (minIndex[ePrev] == minIndex[e] && maxIndex[ePrev] == maxIndex[e]) parallelEdges[ePrev].pushBack(e); else ePrev = e; } } //--------------------------------------------------------- // Methods for simple graphs //--------------------------------------------------------- //! Returns true iff \a G contains neither self-loops nor parallel edges. /** * @param G is the input graph. * @return true if \a G is simple, i.e. contains neither self-loops nor parallel edges, false otherwise. */ inline bool isSimple(const Graph &G) { return isLoopFree(G) && isParallelFree(G); } //! Removes all self-loops and all but one edge of each bundle of parallel edges. /** * @param G is the input graph. */ inline void makeSimple(Graph &G) { makeLoopFree(G); makeParallelFree(G); } //! Returns true iff \a G contains neither self-loops nor undirected parallel edges. /** * @param G is the input graph. * @return true if \a G is (undirected) simple, i.e. contains neither self-loops * nor undirected parallel edges, false otherwise. */ inline bool isSimpleUndirected(const Graph &G) { return isLoopFree(G) && isParallelFreeUndirected(G); } //! Removes all self-loops and all but one edge of each bundle of undirected parallel edges. /** * @param G is the input graph. */ inline void makeSimpleUndirected(Graph &G) { makeLoopFree(G); makeParallelFreeUndirected(G); } //--------------------------------------------------------- // Methods for connectivity //--------------------------------------------------------- //! Returns true iff \a G is connected. /** * @param G is the input graph. * @return true if \a G is connected, false otherwise. */ OGDF_EXPORT bool isConnected(const Graph &G); //! Makes \a G connected by adding a minimum number of edges. /** * @param G is the input graph. * @param added is assigned the added edges. */ OGDF_EXPORT void makeConnected(Graph &G, List<edge> &added); //! makes \a G connected by adding a minimum number of edges. /** * @param G is the input graph. */ inline void makeConnected(Graph &G) { List<edge> added; makeConnected(G,added); } //! Computes the connected components of \a G. /** * Assigns component numbers (0, 1, ...) to the nodes of \a G. The component number of each * node is stored in the node array \a component. * * @param G is the input graph. * @param component is assigned a mapping from nodes to component numbers. * @return the number of connected components. */ OGDF_EXPORT int connectedComponents(const Graph &G, NodeArray<int> &component); //! Computes the connected components of \a G and returns the list of isolated nodes. /** * Assigns component numbers (0, 1, ...) to the nodes of \a G. The component number of each * node is stored in the node array \a component. * * @param G is the input graph. * @param isolated is assigned the list of isolated nodes. An isolated * node is a node without incident edges. * @param component is assigned a mapping from nodes to component numbers. * @return the number of connected components. */ OGDF_EXPORT int connectedIsolatedComponents( const Graph &G, List<node> &isolated, NodeArray<int> &component); //! Returns true iff \a G is biconnected. /** * @param G is the input graph. * @param cutVertex If false is returned, \a cutVertex is assigned either 0 if \a G is not connected, * or a cut vertex in \a G. */ OGDF_EXPORT bool isBiconnected(const Graph &G, node &cutVertex); //! Returns true iff \a G is biconnected. /** * @param G is the input graph. */ inline bool isBiconnected(const Graph &G) { node cutVertex; return isBiconnected(G,cutVertex); } //! Makes \a G biconnected by adding edges. /** * @param G is the input graph. * @param added is assigned the list of inserted edges. */ OGDF_EXPORT void makeBiconnected(Graph &G, List<edge> &added); //! Makes \a G biconnected by adding edges. /** * @param G is the input graph. */ inline void makeBiconnected(Graph &G) { List<edge> added; makeBiconnected(G,added); } //! Computes the biconnected components of \a G. /** * Assigns component numbers (0, 1, ...) to the edges of \ G. The component number of each edge * is stored in the edge array \a component. * * @param G is the input graph. * @param component is assigned a mapping from edges to component numbers. * @return the number of biconnected components (including isolated nodes). */ OGDF_EXPORT int biconnectedComponents(const Graph &G, EdgeArray<int> &component); //! Returns true iff \a G is triconnected. /** * If true is returned, then either * - \a s1 and \a s2 are either both 0 if \a G is not connected; or * - \a s1 is a cut vertex and \a s2 = 0 if \a G is not biconnected; or * - \a s1 and \a s2 are a separation pair otherwise. * * @param G is the input graph. * @param s1 is assigned a cut vertex of one node of a separation pair, if \a G is not triconnected (see above). * @param s2 is assigned one node of a separation pair, if \a G is not triconnected (see above). * @return true if \a G is triconnected, false otherwise. */ OGDF_EXPORT bool isTriconnected(const Graph &G, node &s1, node &s2); //! Returns true iff \a G is triconnected. /** * @param G is the input graph. * @return true if \a G is triconnected, false otherwise. */ inline bool isTriconnected(const Graph &G) { node s1, s2; return isTriconnected(G,s1,s2); } //! Returns true iff \a G is triconnected (using a quadratic time algorithm!). /** * If true is returned, then either * - \a s1 and \a s2 are either both 0 if \a G is not connected; or * - \a s1 is a cut vertex and \a s2 = 0 if \a G is not biconnected; or * - \a s1 and \a s2 are a separation pair otherwise. * * \warning This method has quadratic running time. An efficient linear time * version is provided by isTriconnected(). * * @param G is the input graph. * @param s1 is assigned a cut vertex of one node of a separation pair, if \a G is not triconnected (see above). * @param s2 is assigned one node of a separation pair, if \a G is not triconnected (see above). * @return true if \a G is triconnected, false otherwise. */ OGDF_EXPORT bool isTriconnectedPrimitive(const Graph &G, node &s1, node &s2); //! Returns true iff \a G is triconnected (using a quadratic time algorithm!). /** * \warning This method has quadratic running time. An efficient linear time * version is provided by isTriconnected(). * * @param G is the input graph. * @return true if \a G is triconnected, false otherwise. */ inline bool isTriconnectedPrimitive(const Graph &G) { node s1, s2; return isTriconnectedPrimitive(G,s1,s2); } //! Triangulates a planarly embedded graph \a G by adding edges. /** * The result of this function is that \a G is made maximally planar by adding new edges. * \a G will also be planarly embedded such that each face is a triangle. * * \pre \a G is planar, simple and represents a combinatorial embedding (i.e. \a G is planarly embedded). * * @param G is the input graph to which edges will be added. */ void triangulate(Graph &G); //--------------------------------------------------------- // Methods for directed graphs //--------------------------------------------------------- //! Returns true iff the digraph \a G is acyclic. /** * @param G is the input graph * @param backedges is assigned the backedges of a DFS-tree. * @return true if \a G contains no directed cycle, false otherwise. */ OGDF_EXPORT bool isAcyclic(const Graph &G, List<edge> &backedges); //! Returns true iff the digraph \a G is acyclic. /** * @param G is the input graph * @return true if \a G contains no directed cycle, false otherwise. */ inline bool isAcyclic(const Graph &G) { List<edge> backedges; return isAcyclic(G,backedges); } //! Returns true iff the undirected graph \a G is acyclic. /** * @param G is the input graph * @param backedges is assigned the backedges of a DFS-tree. * @return true if \a G contains no undirected cycle, false otherwise. */ OGDF_EXPORT bool isAcyclicUndirected(const Graph &G, List<edge> &backedges); //! Returns true iff the undirected graph \a G is acyclic. /** * @param G is the input graph * @return true if \a G contains no undirected cycle, false otherwise. */ inline bool isAcyclicUndirected(const Graph &G) { List<edge> backedges; return isAcyclicUndirected(G,backedges); } //! Makes the digraph \a G acyclic by removing edges. /** * The implementation removes all backedges of a DFS tree. * * @param G is the input graph */ OGDF_EXPORT void makeAcyclic(Graph &G); //! Makes the digraph G acyclic by reversing edges. /** * \remark The implementation ignores self-loops and reverses * the backedges of a DFS-tree. * * @param G is the input graph */ OGDF_EXPORT void makeAcyclicByReverse(Graph &G); //! Returns true iff the digraph \a G contains exactly one source node (or is empty). /** * @param G is the input graph. * @param source is assigned the single source if true is returned, or 0 otherwise. * @return true if \a G has a single source, false otherwise. */ OGDF_EXPORT bool hasSingleSource(const Graph &G, node &source); //! Returns true iff the digraph \a G contains exactly one source node (or is empty). /** * @param G is the input graph. * @return true if \a G has a single source, false otherwise. */ inline bool hasSingleSource(const Graph &G) { node source; return hasSingleSource(G,source); } //! Returns true iff the digraph \a G contains exactly one sink node (or is empty). /** * @param G is the input graph. * @param sink is assigned the single sink if true is returned, or 0 otherwise. * @return true if \a G has a single sink, false otherwise. */ OGDF_EXPORT bool hasSingleSink(const Graph &G, node &sink); //! Returns true iff the digraph \a G contains exactly one sink node (or is empty). /** * @param G is the input graph. * @return true if \a G has a single sink, false otherwise. */ inline bool hasSingleSink(const Graph &G) { node sink; return hasSingleSink(G,sink); } //! Returns true iff \a G is an st-digraph. /** * A directed graph is an st-digraph if it is acyclic, contains exactly one source s * and one sink t, and the edge (s,t). * * @param G is the input graph. * @param s is assigned the single source (if true is returned). * @param t is assigned the single sink (if true is returned). * @param st is assigned the edge (s,t) (if true is returned). * @return true if \a G is an st-digraph, false otherwise. */ OGDF_EXPORT bool isStGraph(const Graph &G, node &s, node &t, edge &st); //! Returns true if \a G is an st-digraph. /** * A directed graph is an st-digraph if it is acyclic, contains exactly one source s * and one sink t, and the edge (s,t). * @param G is the input graph. * @return true if \a G is an st-digraph, false otherwise. */ inline bool isStGraph(const Graph &G) { node s, t; edge st; return isStGraph(G,s,t,st); } //! Computes a topological numbering of an acyclic digraph \a G. /** * \pre \a G is an acyclic directed graph. * * @param G is the input graph. * @param num is assigned the topological numbering (0, 1, ...). */ OGDF_EXPORT void topologicalNumbering(const Graph &G, NodeArray<int> &num); //! Computes the strongly connected components of the digraph \a G. /** * The function implements the algorithm by Tarjan. * * @param G is the input graph. * @param component is assigned a mapping from nodes to component numbers (0, 1, ...). * @return the number of strongly connected components. */ OGDF_EXPORT int strongComponents(const Graph& G, NodeArray<int>& component); //--------------------------------------------------------- // Methods for trees and forests //--------------------------------------------------------- //! Returns true iff \a G is a free forest, i.e. contains no undirected cycle. /** * @param G is the input graph. * @return true if \ G is contains no undirected cycle, false otherwise. */ OGDF_EXPORT bool isFreeForest(const Graph &G); //! Returns true iff \a G represents a forest, i.e., a collection of rooted trees. /** * @param G is the input graph. * @param roots is assigned the list of root nodes of the trees in the forest. * @return true if \a G represents a forest, false otherwise. */ OGDF_EXPORT bool isForest(const Graph& G, List<node> &roots); //! Returns true iff \a G represents a forest, i.e. a collection of rooted trees. /** * @param G is the input graph. * @return true if \a G represents a forest, false otherwise. */ inline bool isForest(const Graph &G) { List<node> roots; return isForest(G,roots); } //! Returns true iff \a G represents a tree /** * @param G is the input graph. * @param root is assigned the root node (if true is returned). * @return true if \a G represents a tree, false otherwise. */ OGDF_EXPORT bool isTree (const Graph& G, node &root); //! Returns true iff \a G represents a tree /** * @param G is the input graph. * @return true if \a G represents a tree, false otherwise. */ inline bool isTree(const Graph &G) { node root; return isTree(G,root); } } // end namespace ogdf #endif
<reponame>Aaron911/mindspore /** * Copyright 2020-2022 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_INCLUDE_DATASET_VISION_H_ #define MINDSPORE_CCSRC_MINDDATA_DATASET_INCLUDE_DATASET_VISION_H_ #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "include/api/dual_abi_helper.h" #include "include/api/status.h" #include "include/dataset/constants.h" #include "include/dataset/transforms.h" #include "include/dataset/vision_lite.h" namespace mindspore { namespace dataset { class TensorOperation; // Transform operations for performing computer vision. namespace vision { /// \brief AdjustGamma TensorTransform. /// \note Apply gamma correction on input image. class MS_API AdjustGamma final : public TensorTransform { public: /// \brief Constructor. /// \param[in] gamma Non negative real number, which makes the output image pixel value /// exponential in relation to the input image pixel value. /// \param[in] gain The constant multiplier. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto adjust_gamma_op = vision::AdjustGamma(10.0); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, adjust_gamma_op}, // operations /// {"image"}); // input columns /// \endcode explicit AdjustGamma(float gamma, float gain = 1); /// \brief Destructor. ~AdjustGamma() = default; protected: /// \brief Function to convert TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Apply AutoAugment data augmentation method. class MS_API AutoAugment final : public TensorTransform { public: /// \brief Constructor. /// \param[in] policy An enum for the data auto augmentation policy (default=AutoAugmentPolicy::kImageNet). /// - AutoAugmentPolicy::kImageNet, AutoAugment policy learned on the ImageNet dataset. /// - AutoAugmentPolicy::kCifar10, AutoAugment policy learned on the Cifar10 dataset. /// - AutoAugmentPolicy::kSVHN, AutoAugment policy learned on the SVHN dataset. /// \param[in] interpolation An enum for the mode of interpolation (default=InterpolationMode::kNearestNeighbour). /// - InterpolationMode::kNearestNeighbour, Interpolation method is nearest-neighbor interpolation. /// - InterpolationMode::kLinear, Interpolation method is blinear interpolation. /// - InterpolationMode::kCubic, Interpolation method is bicubic interpolation. /// - InterpolationMode::kArea, Interpolation method is pixel area interpolation. /// \param[in] fill_value A vector representing the pixel intensity of the borders (default={0, 0, 0}). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto auto_augment_op = vision::AutoAugment(AutoAugmentPolicy::kImageNet, /// InterpolationMode::kNearestNeighbour, {0, 0, 0}); /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, auto_augment_op}, // operations /// {"image"}); // input columns /// \endcode explicit AutoAugment(AutoAugmentPolicy policy = AutoAugmentPolicy::kImageNet, InterpolationMode interpolation = InterpolationMode::kNearestNeighbour, const std::vector<uint8_t> &fill_value = {0, 0, 0}); /// \brief Destructor. ~AutoAugment() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Apply automatic contrast on the input image. class MS_API AutoContrast final : public TensorTransform { public: /// \brief Constructor. /// \param[in] cutoff Percent of pixels to cut off from the histogram, the valid range of cutoff value is 0 to 50. /// \param[in] ignore Pixel values to ignore. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto autocontrast_op = vision::AutoContrast(10.0, {10, 20}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, autocontrast_op}, // operations /// {"image"}); // input columns /// \endcode explicit AutoContrast(float cutoff = 0.0, const std::vector<uint32_t> &ignore = {}); /// \brief Destructor. ~AutoContrast() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief BoundingBoxAugment TensorTransform. /// \note Apply a given image transform on a random selection of bounding box regions of a given image. class MS_API BoundingBoxAugment final : public TensorTransform { public: /// \brief Constructor. /// \param[in] transform Raw pointer to the TensorTransform operation. /// \param[in] ratio Ratio of bounding boxes to apply augmentation on. Range: [0, 1] (default=0.3). /// \par Example /// \code /// /* Define operations */ /// TensorTransform *rotate_op = new vision::RandomRotation({-180, 180}); /// auto bbox_aug_op = vision::BoundingBoxAugment(rotate_op, 0.5); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({bbox_aug_op}, // operations /// {"image", "bbox"}); // input columns /// \endcode explicit BoundingBoxAugment(TensorTransform *transform, float ratio = 0.3); /// \brief Constructor. /// \param[in] transform Smart pointer to the TensorTransform operation. /// \param[in] ratio Ratio of bounding boxes where augmentation is applied to. Range: [0, 1] (default=0.3). /// \par Example /// \code /// /* Define operations */ /// std::shared_ptr<TensorTransform> flip_op = std::make_shared<vision::RandomHorizontalFlip>(0.5); /// std::shared_ptr<TensorTransform> bbox_aug_op = std::make_shared<vision::BoundingBoxAugment>(flip_op, 0.1); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({bbox_aug_op}, // operations /// {"image", "bbox"}); // input columns /// \endcode explicit BoundingBoxAugment(const std::shared_ptr<TensorTransform> &transform, float ratio = 0.3); /// \brief Constructor. /// \param[in] transform Object pointer to the TensorTransform operation. /// \param[in] ratio Ratio of bounding boxes where augmentation is applied to. Range: [0, 1] (default=0.3). /// \par Example /// \code /// /* Define operations */ /// vision::RandomColor random_color_op = vision::RandomColor(0.5, 1.0); /// vision::BoundingBoxAugment bbox_aug_op = vision::BoundingBoxAugment(random_color_op, 0.8); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({bbox_aug_op}, // operations /// {"image", "bbox"}); // input columns /// \endcode explicit BoundingBoxAugment(const std::reference_wrapper<TensorTransform> &transform, float ratio = 0.3); /// \brief Destructor. ~BoundingBoxAugment() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Change the color space of the image. class MS_API ConvertColor final : public TensorTransform { public: /// \brief Constructor. /// \param[in] convert_mode The mode of image channel conversion. /// \par Example /// \code /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({std::make_shared<vision::Decode>(), /// std::make_shared<vision::ConvertColor>(ConvertMode::COLOR_BGR2RGB)}, // operations /// {"image"}); // input columns /// \endcode explicit ConvertColor(ConvertMode convert_mode); /// \brief Destructor. ~ConvertColor() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Mask a random section of each image with the corresponding part of another randomly /// selected image in that batch. class MS_API CutMixBatch final : public TensorTransform { public: /// \brief Constructor. /// \param[in] image_batch_format The format of the batch. /// \param[in] alpha The hyperparameter of beta distribution (default = 1.0). /// \param[in] prob The probability by which CutMix is applied to each image (default = 1.0). /// \par Example /// \code /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Batch(5); /// dataset = dataset->Map({std::make_shared<vision::CutMixBatch>(ImageBatchFormat::kNHWC)}, // operations /// {"image", "label"}); // input columns /// \endcode explicit CutMixBatch(ImageBatchFormat image_batch_format, float alpha = 1.0, float prob = 1.0); /// \brief Destructor. ~CutMixBatch() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Randomly cut (mask) out a given number of square patches from the input image. class MS_API CutOut final : public TensorTransform { public: /// \brief Constructor. /// \param[in] length Integer representing the side length of each square patch. /// \param[in] num_patches Integer representing the number of patches to be cut out of an image. /// \par Example /// \code /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({std::make_shared<vision::Decode>(), /// std::make_shared<vision::CutOut>(1, 4)}, // operations /// {"image"}); // input columns /// \endcode explicit CutOut(int32_t length, int32_t num_patches = 1); /// \brief Destructor. ~CutOut() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Apply histogram equalization on the input image. class MS_API Equalize final : public TensorTransform { public: /// \brief Constructor. /// \par Example /// \code /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({std::make_shared<vision::Decode>(), /// std::make_shared<vision::Equalize>()}, // operations /// {"image"}); // input columns /// \endcode Equalize(); /// \brief Destructor. ~Equalize() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; }; /// \brief Flip the input image horizontally. class MS_API HorizontalFlip final : public TensorTransform { public: /// \brief Constructor. /// \par Example /// \code /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({std::make_shared<vision::Decode>(), /// std::make_shared<vision::HorizontalFlip>()}, // operations /// {"image"}); // input columns /// \endcode HorizontalFlip(); /// \brief Destructor. ~HorizontalFlip() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; }; /// \brief Transpose the input image; shape (H, W, C) to shape (C, H, W). class MS_API HWC2CHW final : public TensorTransform { public: /// \brief Constructor. /// \par Example /// \code /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({std::make_shared<vision::Decode>(), /// std::make_shared<vision::HWC2CHW>()}, // operations /// {"image"}); // input columns /// \endcode HWC2CHW(); /// \brief Destructor. ~HWC2CHW() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; }; /// \brief Apply invert on the input image in RGB mode. class MS_API Invert final : public TensorTransform { public: /// \brief Constructor. /// \par Example /// \code /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({std::make_shared<vision::Decode>(), /// std::make_shared<vision::Invert>()}, // operations /// {"image"}); // input columns /// \endcode Invert(); /// \brief Destructor. ~Invert() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; }; /// \brief Apply MixUp transformation on an input batch of images and labels. The labels must be in /// one-hot format and Batch must be called before calling this function. class MS_API MixUpBatch final : public TensorTransform { public: /// \brief Constructor. /// \param[in] alpha hyperparameter of beta distribution (default = 1.0). /// \par Example /// \code /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Batch(5); /// dataset = dataset->Map({std::make_shared<vision::MixUpBatch>()}, // operations /// {"image"}); // input columns /// \endcode explicit MixUpBatch(float alpha = 1); /// \brief Destructor. ~MixUpBatch() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Normalize the input image with respect to mean and standard deviation and pads an extra /// channel with value zero. class MS_API NormalizePad final : public TensorTransform { public: /// \brief Constructor. /// \param[in] mean A vector of mean values for each channel, with respect to channel order. /// The mean values must be in range [0.0, 255.0]. /// \param[in] std A vector of standard deviations for each channel, with respect to channel order. /// The standard deviation values must be in range (0.0, 255.0]. /// \param[in] dtype The output datatype of Tensor. /// The standard deviation values must be "float32" or "float16"(default = "float32"). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto normalize_pad_op = vision::NormalizePad({121.0, 115.0, 100.0}, {70.0, 68.0, 71.0}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, normalize_pad_op}, // operations /// {"image"}); // input columns /// \endcode NormalizePad(const std::vector<float> &mean, const std::vector<float> &std, const std::string &dtype = "float32") : NormalizePad(mean, std, StringToChar(dtype)) {} NormalizePad(const std::vector<float> &mean, const std::vector<float> &std, const std::vector<char> &dtype); /// \brief Destructor. ~NormalizePad() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Pad the image according to padding parameters. class MS_API Pad final : public TensorTransform { public: /// \brief Constructor. /// \param[in] padding A vector representing the number of pixels to pad the image. /// If the vector has one value, it pads all sides of the image with that value. /// If the vector has two values, it pads left and top with the first and /// right and bottom with the second value. /// If the vector has four values, it pads left, top, right, and bottom with /// those values respectively. /// \param[in] fill_value A vector representing the pixel intensity of the borders. Only valid if the /// padding_mode is BorderType.kConstant. If 1 value is provided, it is used for all RGB channels. /// If 3 values are provided, it is used to fill R, G, B channels respectively. /// \param[in] padding_mode The method of padding (default=BorderType.kConstant). /// Can be any of /// [BorderType.kConstant, BorderType.kEdge, BorderType.kReflect, BorderType.kSymmetric] /// - BorderType.kConstant, means it fills the border with constant values /// - BorderType.kEdge, means it pads with the last value on the edge /// - BorderType.kReflect, means it reflects the values on the edge omitting the last value of edge /// - BorderType.kSymmetric, means it reflects the values on the edge repeating the last value of edge /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto pad_op = vision::Pad({10, 10, 10, 10}, {255, 255, 255}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, pad_op}, // operations /// {"image"}); // input columns /// \endcode explicit Pad(const std::vector<int32_t> &padding, const std::vector<uint8_t> &fill_value = {0}, BorderType padding_mode = BorderType::kConstant); /// \brief Destructor. ~Pad() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Automatically adjust the contrast of the image with a given probability. class MS_API RandomAutoContrast final : public TensorTransform { public: /// \brief Constructor. /// \param[in] cutoff Percent of the lightest and darkest pixels to be cut off from /// the histogram of the input image. The value must be in range of [0.0, 50.0) (default=0.0). /// \param[in] ignore The background pixel values to be ignored, each of which must be /// in range of [0, 255] (default={}). /// \param[in] prob A float representing the probability of AutoContrast, which must be /// in range of [0, 1] (default=0.5). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_auto_contrast_op = vision::RandomAutoContrast(5.0); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_auto_contrast_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomAutoContrast(float cutoff = 0.0, const std::vector<uint32_t> &ignore = {}, float prob = 0.5); /// \brief Destructor. ~RandomAutoContrast() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Randomly adjust the sharpness of the input image with a given probability. class MS_API RandomAdjustSharpness final : public TensorTransform { public: /// \brief Constructor. /// \param[in] degree A float representing sharpness adjustment degree, which must be non negative. /// \param[in] prob A float representing the probability of the image being sharpness adjusted, which /// must in range of [0, 1] (default=0.5). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_adjust_sharpness_op = vision::RandomAdjustSharpness(30.0); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_adjust_sharpness_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomAdjustSharpness(float degree, float prob = 0.5); /// \brief Destructor. ~RandomAdjustSharpness() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Blend an image with its grayscale version with random weights /// t and 1 - t generated from a given range. If the range is trivial /// then the weights are determinate and t equals to the bound of the interval. class MS_API RandomColor final : public TensorTransform { public: /// \brief Constructor. /// \param[in] t_lb Lower bound random weights. /// \param[in] t_ub Upper bound random weights. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_color_op = vision::RandomColor(5.0, 50.0); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_color_op}, // operations /// {"image"}); // input columns /// \endcode RandomColor(float t_lb, float t_ub); /// \brief Destructor. ~RandomColor() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Randomly adjust the brightness, contrast, saturation, and hue of the input image. class MS_API RandomColorAdjust final : public TensorTransform { public: /// \brief Constructor. /// \param[in] brightness Brightness adjustment factor. Must be a vector of one or two values /// if it is a vector of two values it needs to be in the form of [min, max] (Default={1, 1}). /// \param[in] contrast Contrast adjustment factor. Must be a vector of one or two values /// if it is a vector of two values, it needs to be in the form of [min, max] (Default={1, 1}). /// \param[in] saturation Saturation adjustment factor. Must be a vector of one or two values /// if it is a vector of two values, it needs to be in the form of [min, max] (Default={1, 1}). /// \param[in] hue Hue adjustment factor. Must be a vector of one or two values /// if it is a vector of two values, it must be in the form of [min, max] where -0.5 <= min <= max <= 0.5 /// (Default={0, 0}). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_color_adjust_op = vision::RandomColorAdjust({1.0, 5.0}, {10.0, 20.0}, {40.0, 40.0}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_color_adjust_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomColorAdjust(const std::vector<float> &brightness = {1.0, 1.0}, const std::vector<float> &contrast = {1.0, 1.0}, const std::vector<float> &saturation = {1.0, 1.0}, const std::vector<float> &hue = {0.0, 0.0}); /// \brief Destructor. ~RandomColorAdjust() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Crop the input image at a random location. class MS_API RandomCrop final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size A vector representing the output size of the cropped image. /// If the size is a single value, a squared crop of size (size, size) is returned. /// If the size has 2 values, it should be (height, width). /// \param[in] padding A vector representing the number of pixels to pad the image. /// If the vector has one value, it pads all sides of the image with that value. /// If the vector has two values, it pads left and top with the first and /// right and bottom with the second value. /// If the vector has four values, it pads left, top, right, and bottom with /// those values respectively. /// \param[in] pad_if_needed A boolean indicating that whether to pad the image /// if either side is smaller than the given output size. /// \param[in] fill_value A vector representing the pixel intensity of the borders if the padding_mode is /// BorderType.kConstant. If 1 value is provided, it is used for all RGB channels. /// If 3 values are provided, it is used to fill R, G, B channels respectively. /// \param[in] padding_mode The method of padding (default=BorderType::kConstant).It can be any of /// [BorderType::kConstant, BorderType::kEdge, BorderType::kReflect, BorderType::kSymmetric]. /// - BorderType::kConstant, Fill the border with constant values. /// - BorderType::kEdge, Fill the border with the last value on the edge. /// - BorderType::kReflect, Reflect the values on the edge omitting the last value of edge. /// - BorderType::kSymmetric, Reflect the values on the edge repeating the last value of edge. /// \note If the input image is more than one, then make sure that the image size is the same. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_crop_op = vision::RandomCrop({255, 255}, {10, 10, 10, 10}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_crop_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomCrop(const std::vector<int32_t> &size, const std::vector<int32_t> &padding = {0, 0, 0, 0}, bool pad_if_needed = false, const std::vector<uint8_t> &fill_value = {0, 0, 0}, BorderType padding_mode = BorderType::kConstant); /// \brief Destructor. ~RandomCrop() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Equivalent to RandomResizedCrop TensorTransform, but crop the image before decoding. class MS_API RandomCropDecodeResize final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size A vector representing the output size of the cropped image. /// If the size is a single value, a squared crop of size (size, size) is returned. /// If the size has 2 values, it should be (height, width). /// \param[in] scale Range [min, max) of respective size of the /// original size to be cropped (default=(0.08, 1.0)). /// \param[in] ratio Range [min, max) of aspect ratio to be /// cropped (default=(3. / 4., 4. / 3.)). /// \param[in] interpolation An enum for the mode of interpolation. /// - InterpolationMode::kLinear, Interpolation method is blinear interpolation. /// - InterpolationMode::kNearestNeighbour, Interpolation method is nearest-neighbor interpolation. /// - InterpolationMode::kCubic, Interpolation method is bicubic interpolation. /// - InterpolationMode::kArea, Interpolation method is pixel area interpolation. /// - InterpolationMode::kCubicPil, Interpolation method is bicubic interpolation like implemented in pillow. /// \param[in] max_attempts The maximum number of attempts to propose a valid crop_area (default=10). /// If exceeded, fall back to use center_crop instead. /// \par Example /// \code /// /* Define operations */ /// auto random_op = vision::RandomCropDecodeResize({255, 255}, {0.1, 0.5}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomCropDecodeResize(const std::vector<int32_t> &size, const std::vector<float> &scale = {0.08, 1.0}, const std::vector<float> &ratio = {3. / 4, 4. / 3}, InterpolationMode interpolation = InterpolationMode::kLinear, int32_t max_attempts = 10); /// \brief Destructor. ~RandomCropDecodeResize() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Crop the input image at a random location and adjust bounding boxes accordingly. /// If the cropped area is out of bbox, the returned bbox will be empty. class MS_API RandomCropWithBBox final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size A vector representing the output size of the cropped image. /// If the size is a single value, a squared crop of size (size, size) is returned. /// If the size has 2 values, it should be (height, width). /// \param[in] padding A vector representing the number of pixels to pad the image /// If the vector has one value, it pads all sides of the image with that value. /// If the vector has two values, it pads left and top with the first and /// right and bottom with the second value. /// If the vector has four values, it pads left, top, right, and bottom with /// those values respectively. /// \param[in] pad_if_needed A boolean indicating that whether to pad the image /// if either side is smaller than the given output size. /// \param[in] fill_value A vector representing the pixel intensity of the borders. Only valid /// if the padding_mode is BorderType.kConstant. If 1 value is provided, it is used for all /// RGB channels. If 3 values are provided, it is used to fill R, G, B channels respectively. /// \param[in] padding_mode The method of padding (default=BorderType::kConstant).It can be any of /// [BorderType::kConstant, BorderType::kEdge, BorderType::kReflect, BorderType::kSymmetric]. /// - BorderType::kConstant, Fill the border with constant values. /// - BorderType::kEdge, Fill the border with the last value on the edge. /// - BorderType::kReflect, Reflect the values on the edge omitting the last value of edge. /// - BorderType::kSymmetric, Reflect the values on the edge repeating the last value of edge. /// \par Example /// \code /// /* Define operations */ /// auto random_op = vision::RandomCropWithBBox({224, 224}, {0, 0, 0, 0}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_op}, // operations /// {"image", "bbox"}); // input columns /// \endcode explicit RandomCropWithBBox(const std::vector<int32_t> &size, const std::vector<int32_t> &padding = {0, 0, 0, 0}, bool pad_if_needed = false, const std::vector<uint8_t> &fill_value = {0, 0, 0}, BorderType padding_mode = BorderType::kConstant); /// \brief Destructor. ~RandomCropWithBBox() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Randomly apply histogram equalization on the input image with a given probability. class MS_API RandomEqualize final : public TensorTransform { public: /// \brief Constructor. /// \param[in] prob A float representing the probability of equalization, which /// must be in range of [0, 1] (default=0.5). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomEqualize(0.5); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomEqualize(float prob = 0.5); /// \brief Destructor. ~RandomEqualize() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Randomly flip the input image horizontally with a given probability. class MS_API RandomHorizontalFlip final : public TensorTransform { public: /// \brief Constructor. /// \param[in] prob A float representing the probability of flip. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomHorizontalFlip(0.8); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomHorizontalFlip(float prob = 0.5); /// \brief Destructor. ~RandomHorizontalFlip() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Randomly flip the input image horizontally with a given probability and adjust bounding boxes accordingly. class MS_API RandomHorizontalFlipWithBBox final : public TensorTransform { public: /// \brief Constructor. /// \param[in] prob A float representing the probability of flip. /// \par Example /// \code /// /* Define operations */ /// auto random_op = vision::RandomHorizontalFlipWithBBox(1.0); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_op}, // operations /// {"image", "bbox"}); // input columns /// \endcode explicit RandomHorizontalFlipWithBBox(float prob = 0.5); /// \brief Destructor. ~RandomHorizontalFlipWithBBox() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Randomly invert the input image with a given probability. class MS_API RandomInvert final : public TensorTransform { public: /// \brief Constructor. /// \param[in] prob A float representing the probability of the image being inverted, which /// must be in range of [0, 1] (default=0.5). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomInvert(0.8); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomInvert(float prob = 0.5); /// \brief Destructor. ~RandomInvert() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Add AlexNet-style PCA-based noise to an image. class MS_API RandomLighting final : public TensorTransform { public: /// \brief Constructor. /// \param[in] alpha A float representing the intensity of the image (default=0.05). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomLighting(0.1); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomLighting(float alpha = 0.05); /// \brief Destructor. ~RandomLighting() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Reduce the number of bits for each color channel randomly. class MS_API RandomPosterize final : public TensorTransform { public: /// \brief Constructor. /// \param[in] bit_range Range of random posterize to compress image. /// uint8_t vector representing the minimum and maximum bit in range of [1,8] (Default={4, 8}). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomPosterize({4, 8}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomPosterize(const std::vector<uint8_t> &bit_range = {4, 8}); /// \brief Destructor. ~RandomPosterize() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Resize the input image using a randomly selected interpolation mode. class MS_API RandomResize final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size A vector representing the output size of the resized image. /// If the size is a single value, the smaller edge of the image will be resized to this value with /// the same image aspect ratio. If the size has 2 values, it should be (height, width). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomResize({32, 32}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomResize(const std::vector<int32_t> &size); /// \brief Destructor. ~RandomResize() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Resize the input image using a randomly selected interpolation mode and adjust /// bounding boxes accordingly. class MS_API RandomResizeWithBBox final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size A vector representing the output size of the resized image. /// If the size is a single value, the smaller edge of the image will be resized to this value with /// the same image aspect ratio. If the size has 2 values, it should be (height, width). /// \par Example /// \code /// /* Define operations */ /// auto random_op = vision::RandomResizeWithBBox({50, 50}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_op}, // operations /// {"image", "bbox"}); // input columns /// \endcode explicit RandomResizeWithBBox(const std::vector<int32_t> &size); /// \brief Destructor. ~RandomResizeWithBBox() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Crop the input image to a random size and aspect ratio. class MS_API RandomResizedCrop final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size A vector representing the output size of the cropped image. /// If the size is a single value, a squared crop of size (size, size) is returned. /// If the size has 2 values, it should be (height, width). /// \param[in] scale Range [min, max) of respective size of the original /// size to be cropped (default=(0.08, 1.0)). /// \param[in] ratio Range [min, max) of aspect ratio to be cropped /// (default=(3. / 4., 4. / 3.)). /// \param[in] interpolation Image interpolation mode (default=InterpolationMode::kLinear). /// - InterpolationMode::kLinear, Interpolation method is blinear interpolation. /// - InterpolationMode::kNearestNeighbour, Interpolation method is nearest-neighbor interpolation. /// - InterpolationMode::kCubic, Interpolation method is bicubic interpolation. /// - InterpolationMode::kArea, Interpolation method is pixel area interpolation. /// - InterpolationMode::kCubicPil, Interpolation method is bicubic interpolation like implemented in pillow. /// \param[in] max_attempts The maximum number of attempts to propose a valid. /// crop_area (default=10). If exceeded, fall back to use center_crop instead. /// \note If the input image is more than one, then make sure that the image size is the same. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomResizedCrop({32, 32}, {0.08, 1.0}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomResizedCrop(const std::vector<int32_t> &size, const std::vector<float> &scale = {0.08, 1.0}, const std::vector<float> &ratio = {3. / 4., 4. / 3.}, InterpolationMode interpolation = InterpolationMode::kLinear, int32_t max_attempts = 10); /// \brief Destructor. ~RandomResizedCrop() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Crop the input image to a random size and aspect ratio. /// If cropped area is out of bbox, the return bbox will be empty. class MS_API RandomResizedCropWithBBox final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size A vector representing the output size of the cropped image. /// If the size is a single value, a squared crop of size (size, size) is returned. /// If the size has 2 values, it should be (height, width). /// \param[in] scale Range [min, max) of respective size of the original /// size to be cropped (default=(0.08, 1.0)). /// \param[in] ratio Range [min, max) of aspect ratio to be cropped /// (default=(3. / 4., 4. / 3.)). /// \param[in] interpolation Image interpolation mode (default=InterpolationMode::kLinear). /// - InterpolationMode::kLinear, Interpolation method is blinear interpolation. /// - InterpolationMode::kNearestNeighbour, Interpolation method is nearest-neighbor interpolation. /// - InterpolationMode::kCubic, Interpolation method is bicubic interpolation. /// - InterpolationMode::kArea, Interpolation method is pixel area interpolation. /// - InterpolationMode::kCubicPil, Interpolation method is bicubic interpolation like implemented in pillow. /// \param[in] max_attempts The maximum number of attempts to propose a valid /// crop_area (default=10). If exceeded, fall back to use center_crop instead. /// \par Example /// \code /// /* Define operations */ /// auto random_op = vision::RandomResizedCropWithBBox({50, 50}, {0.05, 0.5}, {0.2, 0.4}, /// InterpolationMode::kCubic); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_op}, // operations /// {"image", "bbox"}); // input columns /// \endcode explicit RandomResizedCropWithBBox(const std::vector<int32_t> &size, const std::vector<float> &scale = {0.08, 1.0}, const std::vector<float> &ratio = {3. / 4., 4. / 3.}, InterpolationMode interpolation = InterpolationMode::kLinear, int32_t max_attempts = 10); /// \brief Destructor. ~RandomResizedCropWithBBox() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Rotate the image according to parameters. class MS_API RandomRotation final : public TensorTransform { public: /// \brief Constructor. /// \param[in] degrees A float vector of size 2, representing the starting and ending degrees. /// \param[in] resample An enum for the mode of interpolation. /// - InterpolationMode::kLinear, Interpolation method is blinear interpolation. /// - InterpolationMode::kNearestNeighbour, Interpolation method is nearest-neighbor interpolation. /// - InterpolationMode::kCubic, Interpolation method is bicubic interpolation. /// - InterpolationMode::kArea, Interpolation method is pixel area interpolation. /// - InterpolationMode::kCubicPil, Interpolation method is bicubic interpolation like implemented in pillow. /// \param[in] expand A boolean representing whether the image is expanded after rotation. /// \param[in] center A float vector of size 2 or empty, representing the x and y center of rotation /// or the center of the image. /// \param[in] fill_value A vector representing the value to fill the area outside the transform /// in the output image. If 1 value is provided, it is used for all RGB channels. /// If 3 values are provided, it is used to fill R, G, B channels respectively. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomRotation({30, 60}, InterpolationMode::kNearestNeighbour); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomRotation(const std::vector<float> &degrees, InterpolationMode resample = InterpolationMode::kNearestNeighbour, bool expand = false, const std::vector<float> &center = {}, const std::vector<uint8_t> &fill_value = {0, 0, 0}); /// \brief Destructor. ~RandomRotation() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Choose a random sub-policy from a list to be applied on the input image. A sub-policy is a list of tuples /// (operation, prob), where operation is a TensorTransform operation and prob is the probability that this /// operation will be applied. Once a sub-policy is selected, each operation within the sub-policy with be /// applied in sequence according to its probability. class MS_API RandomSelectSubpolicy final : public TensorTransform { public: /// \brief Constructor. /// \param[in] policy Vector of sub-policies to choose from, in which the TensorTransform objects are raw pointers. /// \par Example /// \code /// /* Define operations */ /// auto invert_op(new vision::Invert()); /// auto equalize_op(new vision::Equalize()); /// /// std::vector<std::pair<TensorTransform *, double>> policy = {{invert_op, 0.5}, {equalize_op, 0.4}}; /// vision::RandomSelectSubpolicy random_select_subpolicy_op = vision::RandomSelectSubpolicy({policy}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_select_subpolicy_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomSelectSubpolicy(const std::vector<std::vector<std::pair<TensorTransform *, double>>> &policy); /// \brief Constructor. /// \param[in] policy Vector of sub-policies to choose from, in which the TensorTransform objects are shared pointers. /// \par Example /// \code /// /* Define operations */ /// std::shared_ptr<TensorTransform> invert_op(new vision::Invert()); /// std::shared_ptr<TensorTransform> equalize_op(new vision::Equalize()); /// std::shared_ptr<TensorTransform> resize_op(new vision::Resize({15, 15})); /// /// auto random_select_subpolicy_op = vision::RandomSelectSubpolicy({ /// {{invert_op, 0.5}, {equalize_op, 0.4}}, /// {{resize_op, 0.1}} /// }); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_select_subpolicy_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomSelectSubpolicy( const std::vector<std::vector<std::pair<std::shared_ptr<TensorTransform>, double>>> &policy); /// \brief Constructor. /// \param[in] policy Vector of sub-policies to choose from, in which the TensorTransform objects are object pointers. /// \par Example /// \code /// /* Define operations */ /// vision::Invert invert_op = vision::Invert(); /// vision::Equalize equalize_op = vision::Equalize(); /// vision::Resize resize_op = vision::Resize({15, 15}); /// /// auto random_select_subpolicy_op = vision::RandomSelectSubpolicy({ /// {{invert_op, 0.5}, {equalize_op, 0.4}}, /// {{resize_op, 0.1}} /// }); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_select_subpolicy_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomSelectSubpolicy( const std::vector<std::vector<std::pair<std::reference_wrapper<TensorTransform>, double>>> &policy); /// \brief Destructor. ~RandomSelectSubpolicy() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Adjust the sharpness of the input image by a fixed or random degree. class MS_API RandomSharpness final : public TensorTransform { public: /// \brief Constructor. /// \param[in] degrees A float vector of size 2, representing the range of random sharpness /// adjustment degrees. It should be in (min, max) format. If min=max, then it is a /// single fixed magnitude operation (default = (0.1, 1.9)). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomSharpness({0.1, 1.5}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomSharpness(const std::vector<float> &degrees = {0.1, 1.9}); /// \brief Destructor. ~RandomSharpness() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Invert pixels randomly within a specified range. class MS_API RandomSolarize final : public TensorTransform { public: /// \brief Constructor. /// \param[in] threshold A vector with two elements specifying the pixel range to invert. /// Threshold values should always be in (min, max) format. /// If min=max, it will to invert all pixels above min(max). /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomSharpness({0, 255}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomSolarize(const std::vector<uint8_t> &threshold = {0, 255}); /// \brief Destructor. ~RandomSolarize() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Randomly flip the input image vertically with a given probability. class MS_API RandomVerticalFlip final : public TensorTransform { public: /// \brief Constructor. /// \param[in] prob A float representing the probability of flip. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto random_op = vision::RandomVerticalFlip(); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, random_op}, // operations /// {"image"}); // input columns /// \endcode explicit RandomVerticalFlip(float prob = 0.5); /// \brief Destructor. ~RandomVerticalFlip() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Randomly flip the input image vertically with a given probability and adjust bounding boxes accordingly. class MS_API RandomVerticalFlipWithBBox final : public TensorTransform { public: /// \brief Constructor. /// \param[in] prob A float representing the probability of flip. /// \par Example /// \code /// /* Define operations */ /// auto random_op = vision::RandomVerticalFlipWithBBox(); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_op}, // operations /// {"image", "bbox"}); // input columns /// \endcode explicit RandomVerticalFlipWithBBox(float prob = 0.5); /// \brief Destructor. ~RandomVerticalFlipWithBBox() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Rescale the pixel value of input image. class MS_API Rescale final : public TensorTransform { public: /// \brief Constructor. /// \param[in] rescale Rescale factor. /// \param[in] shift Shift factor. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto rescale_op = vision::Rescale(1.0, 0.0); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, rescale_op}, // operations /// {"image"}); // input columns /// \endcode Rescale(float rescale, float shift); /// \brief Destructor. ~Rescale() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Resize the input image to the given size and adjust bounding boxes accordingly. class MS_API ResizeWithBBox final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size The output size of the resized image. /// If the size is an integer, smaller edge of the image will be resized to this value with the same image aspect /// ratio. If the size is a sequence of length 2, it should be (height, width). /// \param[in] interpolation An enum for the mode of interpolation (default=InterpolationMode::kLinear). /// - InterpolationMode::kLinear, Interpolation method is blinear interpolation. /// - InterpolationMode::kNearestNeighbour, Interpolation method is nearest-neighbor interpolation. /// - InterpolationMode::kCubic, Interpolation method is bicubic interpolation. /// - InterpolationMode::kArea, Interpolation method is pixel area interpolation. /// - InterpolationMode::kCubicPil, Interpolation method is bicubic interpolation like implemented in pillow. /// \par Example /// \code /// /* Define operations */ /// auto random_op = vision::ResizeWithBBox({100, 100}, InterpolationMode::kNearestNeighbour); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({random_op}, // operations /// {"image", "bbox"}); // input columns /// \endcode explicit ResizeWithBBox(const std::vector<int32_t> &size, InterpolationMode interpolation = InterpolationMode::kLinear); /// \brief Destructor. ~ResizeWithBBox() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Change the format of input tensor from 4-channel RGBA to 3-channel BGR. class MS_API RGBA2BGR final : public TensorTransform { public: /// \brief Constructor. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto rgb2bgr_op = vision::RGBA2BGR(); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, rgb2bgr_op}, // operations /// {"image"}); // input columns /// \endcode RGBA2BGR(); /// \brief Destructor. ~RGBA2BGR() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; }; /// \brief Change the input 4 channel RGBA tensor to 3 channel RGB. class MS_API RGBA2RGB final : public TensorTransform { public: /// \brief Constructor. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto rgba2rgb_op = vision::RGBA2RGB(); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, rgba2rgb_op}, // operations /// {"image"}); // input columns /// \endcode RGBA2RGB(); /// \brief Destructor. ~RGBA2RGB() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; }; /// \note Slice the tensor to multiple patches in horizontal and vertical directions. class MS_API SlicePatches final : public TensorTransform { public: /// \brief Constructor. /// \param[in] num_height The number of patches in vertical direction (default=1). /// \param[in] num_width The number of patches in horizontal direction (default=1). /// \param[in] slice_mode An enum for the mode of slice (default=SliceMode::kPad). /// \param[in] fill_value A value representing the pixel to fill the padding area in right and /// bottom border if slice_mode is kPad. Then padded tensor could be just sliced to multiple patches (default=0). /// \note The usage scenerio is suitable to tensor with large height and width. The tensor will keep the same /// if set both num_height and num_width to 1. And the number of output tensors is equal to num_height*num_width. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto slice_patch_op = vision::SlicePatches(255, 255); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, slice_patch_op}, // operations /// {"image"}); // input columns /// \endcode explicit SlicePatches(int32_t num_height = 1, int32_t num_width = 1, SliceMode slice_mode = SliceMode::kPad, uint8_t fill_value = 0); /// \brief Destructor. ~SlicePatches() = default; protected: /// \brief Function to convert TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Decode, randomly crop and resize a JPEG image using the simulation algorithm of /// Ascend series chip DVPP module. The application scenario is consistent with SoftDvppDecodeResizeJpeg. /// The input image size should be in range [32*32, 8192*8192]. /// The zoom-out and zoom-in multiples of the image length and width should be in the range [1/32, 16]. /// Only images with an even resolution can be output. The output of odd resolution is not supported. class MS_API SoftDvppDecodeRandomCropResizeJpeg final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size A vector representing the output size of the resized image. /// If the size is a single value, smaller edge of the image will be resized to this value with /// the same image aspect ratio. If the size has 2 values, it should be (height, width). /// \param[in] scale Range [min, max) of respective size of the original /// size to be cropped (default=(0.08, 1.0)). /// \param[in] ratio Range [min, max) of aspect ratio to be cropped /// (default=(3. / 4., 4. / 3.)). /// \param[in] max_attempts The maximum number of attempts to propose a valid /// crop_area (default=10). If exceeded, fall back to use center_crop instead. /// \par Example /// \code /// /* Define operations */ /// auto dvpp_op = vision::SoftDvppDecodeRandomCropResizeJpeg({255, 255}, {0.1, 1.0}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({dvpp_op}, // operations /// {"image"}); // input columns /// \endcode explicit SoftDvppDecodeRandomCropResizeJpeg(const std::vector<int32_t> &size, const std::vector<float> &scale = {0.08, 1.0}, const std::vector<float> &ratio = {3. / 4., 4. / 3.}, int32_t max_attempts = 10); /// \brief Destructor. ~SoftDvppDecodeRandomCropResizeJpeg() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Decode and resize a JPEG image using the simulation algorithm of Ascend series /// chip DVPP module. It is recommended to use this algorithm in the following scenarios: /// When training, the DVPP of the Ascend chip is not used, /// and the DVPP of the Ascend chip is used during inference, /// and the accuracy of inference is lower than the accuracy of training; /// and the input image size should be in range [32*32, 8192*8192]. /// The zoom-out and zoom-in multiples of the image length and width should be in the range [1/32, 16]. /// Only images with an even resolution can be output. The output of odd resolution is not supported. class MS_API SoftDvppDecodeResizeJpeg final : public TensorTransform { public: /// \brief Constructor. /// \param[in] size A vector representing the output size of the resized image. /// If the size is a single value, smaller edge of the image will be resized to this value with /// the same image aspect ratio. If the size has 2 values, it should be (height, width). /// \par Example /// \code /// /* Define operations */ /// auto dvpp_op = vision::SoftDvppDecodeResizeJpeg({255, 255}); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({dvpp_op}, // operations /// {"image"}); // input columns /// \endcode explicit SoftDvppDecodeResizeJpeg(const std::vector<int32_t> &size); /// \brief Destructor. ~SoftDvppDecodeResizeJpeg() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Swap the red and blue channels of the input image. class MS_API SwapRedBlue final : public TensorTransform { public: /// \brief Constructor. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto swap_red_blue_op = vision::SwapRedBlue(); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, swap_red_blue_op}, // operations /// {"image"}); // input columns /// \endcode SwapRedBlue(); /// \brief Destructor. ~SwapRedBlue() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; }; /// \brief Randomly perform transformations, as selected from input transform list, on the input tensor. class MS_API UniformAugment final : public TensorTransform { public: /// \brief Constructor. /// \param[in] transforms Raw pointer to vector of TensorTransform operations. /// \param[in] num_ops An integer representing the number of operations to be selected and applied. /// \par Example /// \code /// /* Define operations */ /// auto resize_op(new vision::Resize({30, 30})); /// auto random_crop_op(new vision::RandomCrop({28, 28})); /// auto center_crop_op(new vision::CenterCrop({16, 16})); /// auto uniform_op(new vision::UniformAugment({random_crop_op, center_crop_op}, 2)); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({resize_op, uniform_op}, // operations /// {"image"}); // input columns /// \endcode explicit UniformAugment(const std::vector<TensorTransform *> &transforms, int32_t num_ops = 2); /// \brief Constructor. /// \param[in] transforms Smart pointer to vector of TensorTransform operations. /// \param[in] num_ops An integer representing the number of operations to be selected and applied. /// \par Example /// \code /// /* Define operations */ /// std::shared_ptr<TensorTransform> resize_op(new vision::Resize({30, 30})); /// std::shared_ptr<TensorTransform> random_crop_op(new vision::RandomCrop({28, 28})); /// std::shared_ptr<TensorTransform> center_crop_op(new vision::CenterCrop({16, 16})); /// std::shared_ptr<TensorTransform> uniform_op(new vision::UniformAugment({random_crop_op, center_crop_op}, 2)); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({resize_op, uniform_op}, // operations /// {"image"}); // input columns /// \endcode explicit UniformAugment(const std::vector<std::shared_ptr<TensorTransform>> &transforms, int32_t num_ops = 2); /// \brief Constructor. /// \param[in] transforms Object pointer to vector of TensorTransform operations. /// \param[in] num_ops An integer representing the number of operations to be selected and applied. /// \par Example /// \code /// /* Define operations */ /// vision::Resize resize_op = vision::Resize({30, 30}); /// vision::RandomCrop random_crop_op = vision::RandomCrop({28, 28}); /// vision::CenterCrop center_crop_op = vision::CenterCrop({16, 16}); /// vision::UniformAugment uniform_op = vision::UniformAugment({random_crop_op, center_crop_op}, 2); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({resize_op, uniform_op}, // operations /// {"image"}); // input columns /// \endcode explicit UniformAugment(const std::vector<std::reference_wrapper<TensorTransform>> &transforms, int32_t num_ops = 2); /// \brief Destructor. ~UniformAugment() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; private: struct Data; std::shared_ptr<Data> data_; }; /// \brief Flip the input image vertically. class MS_API VerticalFlip final : public TensorTransform { public: /// \brief Constructor. /// \par Example /// \code /// /* Define operations */ /// auto decode_op = vision::Decode(); /// auto flip_op = vision::VerticalFlip(); /// /// /* dataset is an instance of Dataset object */ /// dataset = dataset->Map({decode_op, flip_op}, // operations /// {"image"}); // input columns /// \endcode VerticalFlip(); /// \brief Destructor. ~VerticalFlip() = default; protected: /// \brief The function to convert a TensorTransform object into a TensorOperation object. /// \return Shared pointer to TensorOperation object. std::shared_ptr<TensorOperation> Parse() override; }; } // namespace vision } // namespace dataset } // namespace mindspore #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_INCLUDE_DATASET_VISION_H_
<reponame>csoap/csoap.github.io //------------------------------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Helpful debugging utilities // //------------------------------------------------------------------------------------------------- #pragma once class DebugUtil { #if DEBUG struct ObjectInfo { WCHAR NameBuffer[250]; void* ObjectPointer; ObjectInfo(const WCHAR* wszName, void* pThis) { ObjectPointer = pThis; (void)StringCchCopy(NameBuffer, _countof(NameBuffer), wszName); } }; public: DebugUtil(); ~DebugUtil(); void TrackCreate(const WCHAR* name, void* pThis); void TrackDestroy(void* pThis); void Check(); private: CriticalSection m_cs; DynamicHashTable<void*,ObjectInfo*> m_objectMap; #endif }; extern class DebugUtil *g_pvbDebugUtil; #if DEBUG #define DUTIL_TRACK_CREATE(className) do { if ( g_pvbDebugUtil ) g_pvbDebugUtil->TrackCreate(_T(#className), this); } while(0) #define DUTIL_TRACK_DESTROY() do { if ( g_pvbDebugUtil ) g_pvbDebugUtil->TrackDestroy(this); } while(0) #define DUTIL_TRACK_CHECK() do { if ( g_pvbDebugUtil ) g_pvbDebugUtil->Check();} while(0) #else #define DUTIL_TRACK_CREATE(className) #define DUTIL_TRACK_DESTROY() #define DUTIL_TRACK_CHECK() #endif
/* MIT License Copyright (c) 2021 Hirrolot Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // The official repository: <https://github.com/Hirrolot/result99>. #ifndef RESULT99_H #define RESULT99_H #include <datatype99.h> #ifndef RESULT99_NO_ALIASES #define IoError IoError99 #define Result Result99 #define isResultOk isResultOk99 #define isResultErr isResultErr99 #define Err Err99 #define tryResult tryResult99 #define tryResultMap tryResultMap99 #endif // RESULT99_NO_ALIASES typedef int IoError99; #define Result99(name, T, _E) datatype99(name##Result, (name##Ok, T), (name##E, _E)) #define isResultOk99(result) ((int)(result).tag == 0) #define isResultErr99(result) ((int)(result).tag == 1) #define Err99(result_ty, failure_expr) result_ty##E(result_ty##E_##failure_expr) #define tryResult99(result, result_ty, ok_var, ...) \ tryResultMap99(result, result_ty, ok_var, (e, result_ty##E(*e)), __VA_ARGS__) // clang-format off #define tryResultMap99(result, result_ty, ok_var, on_failure, ...) \ match99(result) { \ of99(result_ty##Ok, ok_var) __VA_ARGS__ \ of99(result_ty##E, ML99_TUPLE_GET(0)(on_failure)) return ML99_TUPLE_GET(1)(on_failure); \ } \ \ do { \ } while (0) // clang-format on #endif // RESULT99_H
<filename>ManagedScripts/MStaticAnimPhysDefClass.h /* Copyright 2020 Neijwiert Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "MStaticPhysDefClass.h" #pragma managed(push, off) class StaticAnimPhysDefClass; #pragma managed(pop) namespace RenSharp { interface class IAnimCollisionManagerDefClass; interface class IProjectorManagerDefClass; public interface class IStaticAnimPhysDefClass : public IStaticPhysDefClass { literal unsigned int StaticAnimPhysDefClassClassID = 36872; literal String^ StaticAnimPhysDefClassTypeName = "StaticAnimPhysDef"; property IntPtr StaticAnimPhysDefClassPointer { IntPtr get(); } property bool ShadowDynamicObjs { bool get(); } property bool ShadowIsAdditive { bool get(); } property bool ShadowIgnoresZRotation { bool get(); } property float ShadowNearZ { float get(); } property float ShadowFarZ { float get(); } property float ShadowIntensity { float get(); } property bool DoesCollideInPathfind { bool get(); } }; public ref class StaticAnimPhysDefClass : public StaticPhysDefClass, public IStaticAnimPhysDefClass { public: StaticAnimPhysDefClass(IntPtr pointer); property IntPtr StaticAnimPhysDefClassPointer { virtual IntPtr get() sealed; } property bool ShadowDynamicObjs { virtual bool get() sealed; protected: void set(bool value); } property bool ShadowIsAdditive { virtual bool get() sealed; protected: void set(bool value); } property bool ShadowIgnoresZRotation { virtual bool get() sealed; protected: void set(bool value); } property float ShadowNearZ { virtual float get() sealed; protected: void set(float value); } property float ShadowFarZ { virtual float get() sealed; protected: void set(float value); } property float ShadowIntensity { virtual float get() sealed; protected: void set(float value); } property bool DoesCollideInPathfind { virtual bool get() sealed; protected: void set(bool value); } protected: property ::StaticPhysDefClass *InternalStaticPhysDefClassPointer { ::StaticPhysDefClass *get() override; } property ::StaticAnimPhysDefClass *InternalStaticAnimPhysDefClassPointer { virtual ::StaticAnimPhysDefClass *get(); } property bool IsCosmetic { bool get(); void set(bool value); } property IAnimCollisionManagerDefClass ^AnimManagerDef { IAnimCollisionManagerDefClass ^get(); void set(IAnimCollisionManagerDefClass ^value); } property IProjectorManagerDefClass ^ProjectorManagerDef { IProjectorManagerDefClass ^get(); void set(IProjectorManagerDefClass ^value); } }; }
<gh_stars>10-100 #include "bcm283x_systimer.h" #include "bcm283x_systimer_regs.h" #include "bcm283x_io.h" /* ioread32, iowrite32 */ #include "bcm283x_irq.h" /* interrupt registration */ #include "../arm1176jzfs.h" /* read_cpsr */ #include "../trap.h" /* struct tf_regs_t */ #include "../../h/types.h" /* u32 */ #include "../../h/param.h" /* NULL */ #include "../../h/clock.h" /* clock */ #include "../../h/prf.h" /* panic */ #define BCM283X_SYSTMR_FREQUENCY 1000000 /* 1MHz */ #define BCM283X_SYSTMR_TICKS_PER_S BCM283X_SYSTMR_FREQUENCY #define BCM283X_SYSTMR_TICKS_PER_QUANTUM (BCM283X_SYSTMR_TICKS_PER_S / 10) void udelay(u32 us) { DMB; u32 now = ioread32(SYSTMR_CLO_REG); while (ioread32(SYSTMR_CLO_REG) - now < us); /* one tick is one us */ DMB; } static void clkintr(void *arg, struct tf_regs_t *tf) { u32 v; DMB; v = ioread32(SYSTMR_CLO_REG); DMB; iowrite32(SYSTMR_C1_REG, v + BCM283X_SYSTMR_TICKS_PER_QUANTUM); iowrite32(SYSTMR_CS_REG, SYSTMR_CS_M1); clock(-1, tf->r13, tf->r1, read_cpsr(), tf->r0, (caddr_t)tf->r15, tf->cpsr); } void clkinit(void) { u32 v; if (0 != bcm283x_register_timer_irq_handler(GPU_IRQ_SYSTIMER_1_INT, clkintr, NULL)) panic("clkinit: failed to register IRQ handler"); DMB; v = ioread32(SYSTMR_CLO_REG); DMB; iowrite32(SYSTMR_C1_REG, v - 1); }
// // Request.h // SimpleWeibo // // Created by buyi on 16/4/6. // Copyright © 2016年 buyi. All rights reserved. // #import <Foundation/Foundation.h> @interface Request : NSObject -(void)getStatusesWithSinceId:(int)sinceId maxId:(int)maxId count:(int)count page:(int)page feature:(int)feature trimUser:(int)trimUser success:(void (^) (BOOL isSuccess, NSMutableArray *array))isSuccess; @end
<gh_stars>1000+ //#define ENABLE_INC_DEC_FIX using System; using System.Collections.Generic; using System.IO; using ProtoCore.AST; using ProtoCore.AST.AssociativeAST; using ProtoCore.DSASM; using ProtoCore.Utils; -->namespace public class Parser { -->constants const bool T = true; const bool x = false; const int minErrDist = 2; public Scanner scanner; public Errors errors; public Token t; // last recognized token public Token la; // lookahead token int errDist = minErrDist; readonly bool builtinMethodsLoaded; private readonly ProtoCore.Core core; -->declarations public Parser(Scanner scanner, ProtoCore.Core coreObj, bool _builtinMethodsLoaded = false) { this.scanner = scanner; errors = new Errors(); errors.core = coreObj; core = coreObj; builtinMethodsLoaded = _builtinMethodsLoaded; commentNode = new CodeBlockNode(); } void SynErr (int n) { if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n); errDist = 0; } public void SemErr (string msg) { if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg); errDist = 0; } void Get () { for (;;) { t = la; la = scanner.Scan(); if (la.kind <= maxT) { ++errDist; break; } -->pragmas la = t; } } void Expect (int n) { if (la.kind==n) Get(); else { SynErr(n); } } bool StartOf (int s) { return set[s, la.kind]; } void ExpectWeak (int n, int follow) { if (la.kind == n) Get(); else { SynErr(n); while (!StartOf(follow)) Get(); } } bool WeakSeparator(int n, int syFol, int repFol) { int kind = la.kind; if (kind == n) {Get(); return true;} else if (StartOf(repFol)) {return false;} else { SynErr(n); while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) { Get(); kind = la.kind; } return StartOf(syFol); } } -->productions public void Parse() { la = new Token(); la.val = ""; Get(); -->parseRoot } static readonly bool[,] set = { -->initialization }; } // end Parser public class Errors { public int count = 0; // number of errors detected public ProtoCore.Core core = null; //public System.IO.TextWriter errorStream = Console.Out; // error messages go to this stream //public System.IO.TextWriter warningStream = Console.Out; //public string errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text public virtual void SynErr (int line, int col, int n) { string s; switch (n) { -->errors default: s = "error " + n; break; } // errorStream.WriteLine(errMsgFormat, line, col, s); core.BuildStatus.LogSyntaxError(s, core.CurrentDSFileName, line, col); count++; } public virtual void SemErr (int line, int col, string s) { //errorStream.WriteLine(errMsgFormat, line, col, s); core.BuildStatus.LogSyntaxError(s, core.CurrentDSFileName, line, col); count++; } public virtual void SemErr (string s) { //errorStream.WriteLine(s); core.BuildStatus.LogSyntaxError(s, core.CurrentDSFileName); count++; } public virtual void Warning (int line, int col, string s) { // TODO: Jun/Jiong expand parser warnings. core.BuildStatus.LogWarning(ProtoCore.BuildData.WarningID.kParsing, s, core.CurrentDSFileName, line, col); //warningStream.WriteLine(errMsgFormat, line, col, s); } public virtual void Warning(string s) { // TODO: Jun/Jiong expand parser warnings. core.BuildStatus.LogWarning(ProtoCore.BuildData.WarningID.kParsing, s, core.CurrentDSFileName); //warningStream.WriteLine(String.Format("Warning: {0}",s)); } } // Errors public class FatalError: Exception { public FatalError(string m): base(m) {} }
<reponame>jearle/DeckOCards<gh_stars>0 #import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_DeckOCards_TestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_DeckOCards_TestsVersionString[];
<filename>lib_treed/inc/TDTreeNode.h /* This file is part of INDDGO. Copyright (C) 2012, Oak Ridge National Laboratory This product includes software produced by UT-Battelle, LLC under Contract No. DE-AC05-00OR22725 with the Department of Energy. This program is free software; you can redistribute it and/or modify it under the terms of the New BSD 3-clause software license (LICENSE). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE for more details. For more information please contact the INDDGO developers at: <EMAIL> */ #ifndef _TD_TREE_NODE_H_ #define _TD_TREE_NODE_H_ #include <string> #include "bigint.h" #include "Log.h" #include <iostream> #include <list> #include <vector> #include "TDSolution.h" using namespace std; class bigintp_map_compare { public: bigintp_map_compare() { } ; bool operator()(const bigint_t *x, const bigint_t *y) { for (int i = x->S - 1; i >= 0; i--) if (x->words[i] < y->words[i]) return true; // x must be >=y if we get here return false; } }; class bigint_map_compare { public: bigint_map_compare() { } ; bool operator()(const bigint_t x, const bigint_t y) { for (int i = x.S - 1; i >= 0; i--) if (x.words[i] < y.words[i]) return true; // x must be >=y if we get here return false; } }; /** * The TDTreeNode class is used to represent the individual nodes * in the tree decomposition. */ class TDTreeNode { friend ostream &operator<<(ostream &, const TDTreeNode &); private: /** * Flag to keep track whether total independent set table is already computed. */ bool compute_tbl; /** * Keep track of completed children. */ int completed_children; /** * keep num_mask_words in TDTreeNode, want to copy data without access TDTree */ int num_mask_words; /** * flag to mark root node */ bool root; public: TDTreeNode(); // Constructor - no fixed size arrays here so don't need a parameter ~TDTreeNode(); // Destructor // Copy constructor TDTreeNode(const TDTreeNode& rhs); // Assignment operator TDTreeNode& operator=(const TDTreeNode& rhs); /** * Unique id for this node in the tree decomposition. */ int id; /** * List of the indices of adjacent TDTreeNodes in this array. * For rooted decompositions, we adopt the convention that the * first node in this list is the parent and the remainder are * the children. The unique root node of the tree has itself * as a parent. */ list<int> adj; /** *The bag containing the vertices represented by this TreeNode. */ list<int> bag; // Populate the vector with the sorted bag once constructed vector<int> bag_vec; /** * Returns true if the tree node is a leaf, false otherwise. */ bool is_leaf(); /** * Returns the type of node - TD_LEAF_NODE, TD_INTRODUCE_NODE, TD_FORGET_NODE, * TD_JOIN_NODE, or TD_OTHER_NODE */ int node_type(int k); /** * Hash table to store partial solutions in DP */ TDSolution *hash_table; /** * List to store all independent sets */ list<bigint_t *> all_ind_sets; /** * List to keep values for independent sets */ list<int> all_ind_set_values; /** * Place to store best obj_val found in DP at this tree node */ int obj_val; /** * # of edges in the subgraph induced by this tree node's bag. */ int num_subgraph_edges; /** * A place to store the adjacency matrix in a convenient format * for subsequent processing. Set to NULL by the constructor and only * allocated when needed. */ vector<int_bigint *> *nbr_mask_vec; /** * A place to store the intersection of the children's bags with this treenode's * bag. In particular, child_intersection[i] has bit j set if the j-th entry in * the bag of the i-th child is contained in this tree node's bag. */ vector<bigint_t *> *child_intersection; /** * A place to store the position in the parent bag of every vertex in this * tree node's bag. For example, if vertex 93 is the 3rd vertex in this tree node's * bag, and vertex 93 is the 5th vertex in the parent's bag, then * parent_position[3]=5; */ vector<int> *parent_position; /** * A place to store weights for the vertices in the bag. */ vector<int> *vertex_weights; /** * Wrapper to delete the adj mat */ void free_data(); /** * counting completed children for asynchronous table update */ int get_completed_children() const; void set_completed_children(int i); void increase_completed_children(int i = 1); /** * set num_mask_words in TDTreeNodes */ void set_num_mask_words(int i); int get_num_mask_words() const; /** * set root node */ void set_root(bool flag); /** * check for root node */ bool is_root(); }; #endif
//h void display(int n)
<reponame>hansh17/dynamic-RLWE-GKA #include <arpa/inet.h> #include <getopt.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <stdint.h> #include <fcntl.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "fft.h" #include "rlwe.h" #include "rlwe_a.h" #include "rlwe_rand.h" #define MAX_PEER 6 #define POLY_LEN 1024 #define KEY_LEN 16 #define HASH_LEN 129 bool check_augmented_pub_keys[MAX_PEER]; bool option_check[4][MAX_PEER]; uint32_t sec_keys[MAX_PEER][POLY_LEN]; uint32_t pub_keys[MAX_PEER][POLY_LEN]; uint32_t augmented_pub_keys[MAX_PEER][POLY_LEN]; uint64_t session_keys[MAX_PEER][KEY_LEN]; unsigned char hashed_keys[MAX_PEER][HASH_LEN]; uint64_t reconcile[KEY_LEN]; int calculate_pubkey(int peer, const uint32_t *a, uint32_t s[1024], FFT_CTX *ctx); int calculate_augmented_pubkey(int peer, int num_peer, uint32_t s[1024], FFT_CTX *ctx); int calculate_reconcile(int num_peer, uint32_t s[1024], uint64_t rec[16], uint64_t k[16], unsigned char hk[129], FFT_CTX *ctx); void run_server(int num_peer, int server_port); int calculate_pubkey(int peer, const uint32_t *a, uint32_t s[1024], FFT_CTX *ctx) // calculate z_i in Round 1 (i=peer) { if (peer < 0 || peer > MAX_PEER) { printf("peer range error!\n"); return -1; } int ret; uint32_t e[1024]; RAND_CTX rand_ctx; ret = RAND_CHOICE_init(&rand_ctx); // initialize seed if (!ret) { return ret; } #if CONSTANT_TIME rlwe_sample_ct(s, &rand_ctx); // sample s_i (constant) rlwe_sample_ct(e, &rand_ctx); // sample e_i (constant) #else rlwe_sample(s, &rand_ctx); // sample s_i (non-constant) rlwe_sample(e, &rand_ctx); // sample e_i (non-constant) #endif uint32_t tmp[1024]; rlwe_key_gen(tmp, a, s, e, ctx); // compute tmp=as_i+e_i for(int t=0; t<1024; t++) { pub_keys[peer][t]=tmp[t]; // save tmp as pub_keys[peer] } rlwe_memset_volatile(e, 0, 1024 * sizeof(uint32_t)); rlwe_memset_volatile(tmp, 0, 1024 * sizeof(uint32_t)); RAND_CHOICE_cleanup(&rand_ctx); return ret; } int calculate_augmented_pubkey(int peer, int num_peer, uint32_t s[1024], FFT_CTX *ctx) // calculate X_i in Round 2 (i=peer) { int ret; uint32_t e[1024]; RAND_CTX rand_ctx; ret = RAND_CHOICE_init(&rand_ctx); // initialize seed if (!ret) { return ret; } uint32_t result[1024]={0,}; uint32_t tmp1[1024]; uint32_t tmp2[1024]; if (peer==num_peer-1) // if i = N-1 { #if CONSTANT_TIME rlwe_sample_ct(e, &rand_ctx); // sample e'_{N-1} (constant) #else rlwe_sample(e, &rand_ctx); // sample e'_{N-1} (non-constant) #endif for(int t=0; t<1024; t++) { tmp1[t]=pub_keys[0][t]; // tmp1 = z_0 tmp2[t]=pub_keys[peer-1][t]; // tmp2 = z_{N-2} } FFT_sub(result, tmp1, tmp2); // result = z_0 - z_{N-2} FFT_mul(result, result, s, ctx); // result = (z_0 - z_{N-2}) * s_{N-1} FFT_add(result, result, e); // result = (z_0 - z_{N-2}) * s_{N-1} + e'_{N-1} } else if (peer==0) // if i = 0 { #if CONSTANT_TIME rlwe_sample2_ct(e, &rand_ctx); // sample e'_0 from sigma2 (constant) #else rlwe_sample2(e, &rand_ctx); // sample e'_0 from sigma2 (non-constant) #endif for(int t=0; t<1024; t++) { tmp1[t]=pub_keys[peer+1][t]; // tmp1 = z_1 tmp2[t]=pub_keys[num_peer-1][t]; // tmp2 = z_{N-1} } FFT_sub(result, tmp1, tmp2); // result = z_1 - z_{N-1} FFT_mul(result, result, s, ctx); // result = (z_1 - z_{N-1}) * s_0 FFT_add(result, result, e); // result = (z_1 - z_{N-1}) * s_0 + e'_0 } else // if 1<= i <= N-2 { #if CONSTANT_TIME rlwe_sample_ct(e, &rand_ctx); // sample e'_i (constant) #else rlwe_sample(e, &rand_ctx); // sample e'_i (non-constant) #endif for(int t=0; t<1024; t++) { tmp1[t]=pub_keys[peer+1][t]; // tmp1= z_{i+1} tmp2[t]=pub_keys[peer-1][t]; // tmp2 = z_{i-1} } FFT_sub(result, tmp1, tmp2); // result = z_{i+1} - z_{i-1} FFT_mul(result, result, s, ctx); // result = (z_{i+1} - z_{i-1}) * s_i FFT_add(result, result, e); // result = (z_{i+1} - z_{i-1}) * s_i + e'_i } for(int t=0; t<1024; t++) { augmented_pub_keys[peer][t]=result[t]; // save result as augmented_pub_keys[peer] } rlwe_memset_volatile(result, 0, 1024 * sizeof(uint32_t)); rlwe_memset_volatile(tmp1, 0, 1024 * sizeof(uint32_t)); rlwe_memset_volatile(tmp2, 0, 1024 * sizeof(uint32_t)); rlwe_memset_volatile(e, 0, 1024 * sizeof(uint32_t)); RAND_CHOICE_cleanup(&rand_ctx); return ret; } void sha512_session_key(uint64_t *in, char outputBuffer[129]) // calculate hash value of session key (SHA-512) { unsigned char hash[SHA512_DIGEST_LENGTH]; // SHA512_DIGEST_LENGTH=64 SHA512_CTX sha512; SHA512_Init(&sha512); SHA512_Update(&sha512, in, 8*16); SHA512_Final(hash, &sha512); int i = 0; for(i = 0; i < SHA512_DIGEST_LENGTH; i++) { sprintf(outputBuffer + (i * 2), "%02x", hash[i]); } outputBuffer[128]=0; } int calculate_reconcile(int num_peer, uint32_t s[1024], uint64_t rec[16], uint64_t k[16], unsigned char hk[129], FFT_CTX *ctx){ // calculate reconcile int ret; uint32_t e[1024]; RAND_CTX rand_ctx; ret = RAND_CHOICE_init(&rand_ctx); // initialize seed if (!ret) { return ret; } #if CONSTANT_TIME rlwe_sample_ct(e, &rand_ctx); // sample e''_{N-1} (constant) #else rlwe_sample(e, &rand_ctx); // sample e''_{N-1} (non-constant) #endif uint32_t Y[MAX_PEER][POLY_LEN]; uint32_t tmp[1024]; uint32_t tmp2[1024]; for(int t=0; t<1024; t++){ tmp[t]=pub_keys[num_peer-2][t]; // tmp = z_{N-2} tmp2[t]=augmented_pub_keys[num_peer-1][t]; // tmp2 = X_{N-1} } FFT_mul(tmp, tmp, s, ctx); // tmp = z_{N-2} * s_{N-1} FFT_add(tmp, tmp, tmp2); // tmp = z_{N-2} * s_{N-1} + X_{N-1} FFT_add(tmp, tmp, e); // tmp = z_{N-2} * s_{N-1} + X_{N-1} + e''_{N-1} for(int k=0; k<1024; k++){ Y[num_peer-1][k]=tmp[k]; // save tmp as Y_{N-1} tmp2[k]=augmented_pub_keys[0][k]; // tmp2 = X_0 } FFT_add(tmp, tmp, tmp2); // tmp = Y_{N-1} + X_0 for(int k=0; k<1024; k++){ Y[0][k]=tmp[k]; // save tmp as Y_0 tmp2[k]=augmented_pub_keys[1][k]; // tmp2 = X_1 } for (int j=1; j<num_peer-1; j++){ FFT_add(tmp, tmp, tmp2); // tmp = Y_{j-1} + X_j for(int k=0; k<1024; k++){ Y[j][k]=tmp[k]; // save tmp as Y_j tmp2[k]=augmented_pub_keys[j+1][k]; // tmp2 = X_{j+1} } } uint32_t result[1024]={0,}; for (int i = 0; i < num_peer; i++) // compute b_{N-1} { for(int k=0; k<1024; k++) { tmp[k]=Y[i][k]; // tmp = Y_i } FFT_add(result, result, tmp); // result = result + Y_i } #if CONSTANT_TIME rlwe_crossround2_ct(rec, result, &rand_ctx); // compute rec (constant) rlwe_round2_ct(k, result); // compute key k_{N-1} (constant) #else rlwe_crossround2(rec, result, &rand_ctx); // compute rec (non-constant) rlwe_round2(k, result); // compute key k_{N-1} (non-constant) #endif sha512_session_key(k, hk); // compute hash value of k_{N-1} and save as hk_{N-1} rlwe_memset_volatile(result, 0, 1024 * sizeof(uint32_t)); rlwe_memset_volatile(e, 0, 1024 * sizeof(uint32_t)); rlwe_memset_volatile(Y, 0, 1024 * MAX_PEER * sizeof(uint32_t)); rlwe_memset_volatile(tmp, 0, 1024 * sizeof(uint32_t)); rlwe_memset_volatile(tmp2, 0, 1024 * sizeof(uint32_t)); RAND_CHOICE_cleanup(&rand_ctx); return ret; } int next_option(int option, int num_peer) // To check whether (step i) finish or not { bool check = true; for (int i = 0; i < num_peer - 1; i++) { check = check && option_check[option][i]; } if (check) return option + 1; return option; } void run_server(int num_peer, int server_port) // Communication between peers and arbiter { int server_socket; server_socket = socket(PF_INET, SOCK_STREAM, 0); if (server_socket == -1) { printf("socket() error!\n"); exit(1); } struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(server_port); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { printf("bind() error!\n"); exit(1); } if (listen(server_socket, 5) == -1) { printf("listen() error!\n"); exit(1); } struct sockaddr_in client_addr; socklen_t client_addr_size; client_addr_size = sizeof(client_addr); int client_socket[MAX_PEER]; for (int i = 0; i < num_peer; i++) { client_socket[i] = 0; } fd_set readfds; int sd, max_sd; int activity; int new_socket; int peer; int option = 0; bool first_process; uint32_t result[POLY_LEN]; memset(check_augmented_pub_keys, false, sizeof(check_augmented_pub_keys)); memset(option_check, false, sizeof(option_check)); bool reconcile_calculated = false; FFT_CTX ctx; FFT_CTX_init(&ctx); calculate_pubkey(num_peer - 1, rlwe_a, sec_keys[num_peer - 1], &ctx); // calculate z_{N-1} while (option < 4) { FD_ZERO(&readfds); FD_SET(server_socket, &readfds); max_sd = server_socket; for (int i = 0; i < num_peer-1; i++) { sd = client_socket[i]; if (sd > 0) FD_SET(sd, &readfds); if (sd > max_sd) max_sd = sd; } activity = select(max_sd + 1, &readfds, NULL, NULL, NULL); if (FD_ISSET(server_socket, &readfds)) // peer and arbiter connect { new_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_size); for (int i = 0; i < num_peer-1; i++) { if (client_socket[i] == 0) { client_socket[i] = new_socket; break; } } } for (int p = 0; p < num_peer-1; p++) { sd = client_socket[p]; if (FD_ISSET(sd, &readfds)) { recv(sd, &peer, sizeof(peer), 0); if (!(0 <= peer && peer < num_peer)) { printf("peer number error\n"); close(sd); continue; } if (!reconcile_calculated) // if rec is not computed { bool all_augmented_pub_keys = true; for (int i = 0; i < num_peer; i++) { if (!check_augmented_pub_keys[i]) { all_augmented_pub_keys = false; break; } } if (all_augmented_pub_keys) // if receive all X_i (0<=i<=N-2) { calculate_reconcile(num_peer, sec_keys[num_peer - 1], reconcile, session_keys[num_peer - 1], hashed_keys[num_peer-1], &ctx); reconcile_calculated = true; } } send(sd, &option, sizeof(option), 0); // send step i (i=option) if (option == 1) // if step 0 is done, compute X_{N-1} { calculate_augmented_pubkey(num_peer - 1, num_peer, sec_keys[num_peer - 1], &ctx); check_augmented_pub_keys[num_peer - 1] = true; } first_process = !option_check[option][peer]; send(sd, &first_process, sizeof(first_process), 0); if (!first_process) continue; switch (option) { case 0: { recv(sd, pub_keys[peer], POLY_LEN * sizeof(uint32_t), 0); // receive z_i printf("option 0 clear with peer %d!\n", peer); break; } case 1: { send(sd, pub_keys, sizeof(uint32_t) * num_peer * POLY_LEN, 0); // broadcast z recv(sd, result, sizeof(result), 0); // receive X_i memcpy(augmented_pub_keys[peer], result, sizeof(augmented_pub_keys[peer])); check_augmented_pub_keys[peer] = true; printf("option 1 clear with peer %d!\n", peer); break; } case 2: { send(sd, augmented_pub_keys, sizeof(uint32_t) * num_peer * POLY_LEN, 0); // broadcast X printf("option 2 clear with peer %d!\n", peer); break; } case 3: { send(sd, reconcile, sizeof(reconcile), 0); // broadcast rec recv(sd, hashed_keys[peer], sizeof(hashed_keys[peer]), 0); // receive sk_i printf("option 3 clear with peer %d!\n", peer); } } option_check[option][peer] = true; option = next_option(option, num_peer); // if communication with all peers is done, go to next step } } } printf("Arbiter hashed key : "); // print sk_{N-1} for (int i = 0; i < 129; i++) printf("%c", hashed_keys[num_peer - 1][i]); printf("\n"); } int main(int argc, char *argv[]) { int num_peer = 3; // N=3 int server_port = 4000; // default port = 4000 char op; while ((op = getopt(argc, argv, "p:")) != -1) { switch (op) { case 'p': server_port = atoi(optarg); break; } } run_server(num_peer, server_port); return 0; }
<gh_stars>10-100 /*++ Copyright (C) 2000-2001 Microsoft Corporation Module Name: SVCMRSH.H Abstract: IWbemServices marshaling History: --*/ #include <unk.h> #include <wbemidl.h> #include <wbemint.h> #include <wbemcomn.h> #include "mrshbase.h" #include "svcwrap.h" //*************************************************************************** // // class CSvcFactoryBuffer // // DESCRIPTION: // // This class provides the proxy stub factory so that we can provide custom // facelets and stublets for the IWbemService interface. // //*************************************************************************** class CSvcFactoryBuffer : public CUnkInternal { IRpcProxyBuffer* m_pOldProxy; IRpcStubBuffer* m_pOldStub; // We don't want to AddRef the life control, but // we need to let objects we create AddRef it, so the // base class won't keep this pointer, but we will. CLifeControl* m_pLifeControl; protected: class XSvcFactory : public CImpl<IPSFactoryBuffer, CSvcFactoryBuffer> { public: XSvcFactory(CSvcFactoryBuffer* pObj) : CImpl<IPSFactoryBuffer, CSvcFactoryBuffer>(pObj) {} STDMETHOD(CreateProxy)(IN IUnknown* pUnkOuter, IN REFIID riid, OUT IRpcProxyBuffer** ppProxy, void** ppv); STDMETHOD(CreateStub)(IN REFIID riid, IN IUnknown* pUnkServer, OUT IRpcStubBuffer** ppStub); } m_XSvcFactory; public: CSvcFactoryBuffer(CLifeControl* pControl) : CUnkInternal(pControl), m_pLifeControl( pControl ), m_XSvcFactory(this) { } ~CSvcFactoryBuffer() { } void* GetInterface(REFIID riid); friend XSvcFactory; }; //*************************************************************************** // // class CSvcProxyBuffer // // DESCRIPTION: // // This class provides the facelet for the IWbemServices interface. // // Trick #1: This object is derived from IRpcProxyBuffer since IRpcProxyBuffer // is its "internal" interface --- the interface that does not delegate to the // aggregator. (Unlike in normal objects, where that interface is IUnknown) // //*************************************************************************** class CSvcProxyBuffer : public CBaseProxyBuffer { protected: IWbemServices* m_pOldProxySvc; CWbemSvcWrapper* m_pWrapperProxy; protected: // Pure Virtuals from base class void* GetInterface( REFIID riid ); void** GetOldProxyInterfacePtr( void ); void ReleaseOldProxyInterface( void ); // Special overrides STDMETHOD(Connect)(IRpcChannelBuffer* pChannel); STDMETHOD_(void, Disconnect)(); public: CSvcProxyBuffer(CLifeControl* pControl, IUnknown* pUnkOuter); ~CSvcProxyBuffer(); HRESULT Init( void ); }; //*************************************************************************** // // class CSvcStubBuffer // // DESCRIPTION: // // This class provides the stublet for the IWbemServices interface. // //*************************************************************************** class CSvcStubBuffer : public CBaseStubBuffer { protected: class XSvcStublet : public CBaseStublet { IWbemServices* m_pServer; protected: virtual IUnknown* GetServerInterface( void ); virtual void** GetServerPtr( void ); virtual void ReleaseServerPointer( void ); public: XSvcStublet(CSvcStubBuffer* pObj); ~XSvcStublet(); private: friend CSvcStubBuffer; } m_XSvcStublet; friend XSvcStublet; public: CSvcStubBuffer(CLifeControl* pControl, IUnknown* pUnkOuter = NULL) : CBaseStubBuffer( pControl, pUnkOuter ), m_XSvcStublet(this) {} void* GetInterface(REFIID riid); };
/* Copyright (c) 2018-2019, Hisilicon Tech. Co., Ltd. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include "hisi_dss_ion.h" #include "hisi_fb.h" /* * this function allocate physical memory, * and make them to scatter lista. * table is global . */ /*lint -e574 -e737 -e570 -e613 -e647*/ static struct iommu_page_info *__hisifb_dma_create_node(void) { /* alloc 8kb each time */ unsigned int order = 1; struct iommu_page_info *info = NULL; struct page *page = NULL ; info = kzalloc(sizeof(struct iommu_page_info), GFP_KERNEL); if (!info) { HISI_FB_INFO("kzalloc info failed\n"); return NULL; } page = alloc_pages(GFP_KERNEL, order); if (!page) { HISI_FB_INFO("alloc page error\n"); kfree(info); return NULL; } info->page = page; info->order = order; INIT_LIST_HEAD(&info->list); return info; } static struct sg_table *__hisifb_dma_alloc_memory(unsigned int size) { unsigned int map_size; unsigned int sum = 0; struct list_head pages; struct iommu_page_info *info = NULL; struct iommu_page_info *tmp_info = NULL; unsigned int i = 0, ret = 0; struct sg_table *table = NULL; struct scatterlist *sg = NULL; if ((size > SZ_512M) || (size == 0)) { return NULL; } map_size = size; INIT_LIST_HEAD(&pages); do { info = __hisifb_dma_create_node(); if (!info) goto error; list_add_tail(&info->list, &pages); sum += (1 << info->order) * PAGE_SIZE; i++; } while (sum < map_size); table = kzalloc(sizeof(struct sg_table), GFP_KERNEL); if (!table) { goto error; } ret = sg_alloc_table(table, i, GFP_KERNEL); if (ret) { kfree(table); goto error; } sg = table->sgl; list_for_each_entry_safe(info, tmp_info, &pages, list) { struct page *page = info->page; sg_set_page(sg, page, (1 << info->order) * PAGE_SIZE, 0); sg = sg_next(sg); list_del(&info->list); kfree(info); } HISI_FB_INFO("alloc total memory size 0x%x\n", sum); return table; error: list_for_each_entry_safe(info, tmp_info, &pages, list) { __free_pages(info->page, info->order); list_del(&info->list); kfree(info); } return NULL; } static int __hisifb_dma_free_memory(struct sg_table *table) { int i; struct scatterlist *sg = NULL; unsigned int mem_size = 0; if (table) { for_each_sg(table->sgl, sg, table->nents, i) { __free_pages(sg_page(sg), get_order(sg->length)); mem_size += sg->length; } sg_free_table(table); kfree(table); } HISI_FB_INFO("free total memory size 0x%x\n", mem_size); table = NULL; return 0; } unsigned long hisifb_alloc_fb_buffer(struct hisi_fb_data_type *hisifd) { size_t buf_len = 0; unsigned long buf_addr = 0; unsigned long buf_size = 0; struct sg_table *sg = NULL; struct fb_info *fbi = NULL; if (NULL == hisifd) { HISI_FB_ERR("hisifd is NULL\n"); return 0; } fbi = hisifd->fbi; if (NULL == fbi) { HISI_FB_ERR("fbi is NULL\n"); return 0; } buf_len = fbi->fix.smem_len; // align to PAGE_SIZE sg = __hisifb_dma_alloc_memory(buf_len); if (!sg) { HISI_FB_ERR("__hdss_dma_alloc_memory failed!\n"); return 0; } buf_addr = hisi_iommu_map_sg(__hdss_get_dev(), sg->sgl, 0, &buf_size); if (!buf_addr) { HISI_FB_ERR("hisi_iommu_map_sg failed!\n"); __hisifb_dma_free_memory(sg); return 0; } HISI_FB_INFO("fb%d alloc framebuffer map sg 0x%zxB succuss\n", hisifd->index, buf_size); fbi->screen_base = hisifb_iommu_map_kernel(sg, buf_len); if (!fbi->screen_base) { HISI_FB_ERR("hisifb_iommu_map_kernel failed!\n"); hisi_iommu_unmap_sg(__hdss_get_dev(), sg->sgl, buf_addr); __hisifb_dma_free_memory(sg); return 0; } fbi->fix.smem_start = buf_addr; fbi->screen_size = buf_len; hisifd->fb_sg_table = sg; return buf_addr; } void hisifb_free_fb_buffer(struct hisi_fb_data_type *hisifd) { struct fb_info *fbi = NULL; if (NULL == hisifd) { HISI_FB_ERR("hisifd is NULL\n"); return; } fbi = hisifd->fbi; if (NULL == fbi) { HISI_FB_ERR("fbi is NULL\n"); return; } if ((hisifd->fb_sg_table) && (fbi->screen_base != 0)) { hisifb_iommu_unmap_kernel(fbi->screen_base); hisi_iommu_unmap_sg(__hdss_get_dev(), hisifd->fb_sg_table->sgl, fbi->fix.smem_start); __hisifb_dma_free_memory(hisifd->fb_sg_table); hisifd->fb_sg_table = NULL; fbi->screen_base = 0; fbi->fix.smem_start = 0; } } void *hisifb_iommu_map_kernel(struct sg_table *sg_table, size_t size) { int i, j; void *vaddr = NULL; pgprot_t pgprot; struct scatterlist *sg = NULL; struct sg_table *table = sg_table; int npages = PAGE_ALIGN(size) / PAGE_SIZE; struct page **pages = vmalloc(sizeof(struct page *) * npages); struct page **tmp = pages; if (IS_ERR_OR_NULL(pages)) { pr_err("%s: vmalloc failed. \n", __func__); return NULL; } if (table == NULL) { pr_err("%s: table is NULL \n", __func__); vfree(pages); return NULL; } pgprot = pgprot_writecombine(PAGE_KERNEL); for_each_sg(table->sgl, sg, table->nents, i) { int npages_this_entry = PAGE_ALIGN(sg->length) / PAGE_SIZE; struct page *page = sg_page(sg); BUG_ON(i >= npages); for (j = 0; j < npages_this_entry; j++) { *(tmp++) = page++; } } vaddr = vmap(pages, npages, VM_MAP, pgprot); vfree(pages); if (vaddr == NULL) { pr_err("%s: vmap failed.\n", __func__); return NULL; } return vaddr; } void hisifb_iommu_unmap_kernel(const void *vaddr) { vunmap(vaddr); } int hisifb_create_buffer_client(struct hisi_fb_data_type *hisifd) { return 0; } void hisifb_destroy_buffer_client(struct hisi_fb_data_type *hisifd) { } int hisi_fb_mmap(struct fb_info *info, struct vm_area_struct * vma) { struct hisi_fb_data_type *hisifd = NULL; struct sg_table *table = NULL; struct scatterlist *sg = NULL; struct page *page = NULL; unsigned long remainder = 0; unsigned long len = 0; unsigned long addr = 0; unsigned long offset = 0; unsigned long size = 0; int i = 0; int ret = 0; if (!info || !vma) return -EINVAL; hisifd = (struct hisi_fb_data_type *)info->par; if (!hisifd || !hisifd->pdev) return -EINVAL; if (hisifd->index != PRIMARY_PANEL_IDX) { HISI_FB_INFO("fb%u, no fb buffer!\n", hisifd->index); return -EFAULT; } if (!lock_fb_info(info)) return -ENODEV; if (hisifd->fb_mem_free_flag) { if (!hisifb_alloc_fb_buffer(hisifd)) { HISI_FB_ERR("fb%d, hisifb_alloc_buffer failed!\n", hisifd->index); ret = -ENOMEM; goto return_unlock; } hisifd->fb_mem_free_flag = false; } table = hisifd->fb_sg_table; if (!table) { HISI_FB_ERR("fb%d, table is NULL!\n", hisifd->index); ret = -EFAULT; goto return_unlock; } vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); addr = vma->vm_start; offset = vma->vm_pgoff * PAGE_SIZE; size = vma->vm_end - vma->vm_start; if (size > info->fix.smem_len) { HISI_FB_ERR("fb%d, size=%lu is out of range(%u)!\n", hisifd->index, size, info->fix.smem_len); ret = -EFAULT; goto return_unlock; } for_each_sg(table->sgl, sg, table->nents, i) {/* lint !e574 */ page = sg_page(sg); remainder = vma->vm_end - addr; len = sg->length; if (offset >= sg->length) { offset -= sg->length; continue; } if (offset) { page += offset / PAGE_SIZE; len = sg->length - offset; offset = 0; } len = min(len, remainder); ret = remap_pfn_range(vma, addr, page_to_pfn(page), len, vma->vm_page_prot); if (ret != 0) { HISI_FB_ERR("fb%d, failed to remap_pfn_range! ret=%d\n", hisifd->index, ret); goto return_unlock; } addr += len; if (addr >= vma->vm_end) { ret = 0; break; } } return_unlock: unlock_fb_info(info); return ret; } void hisifb_free_logo_buffer(struct hisi_fb_data_type *hisifd) { uint32_t i; struct fb_info *fbi = NULL; uint32_t logo_buffer_base_temp = 0; if (NULL == hisifd) { HISI_FB_ERR("hisifd is NULL\n"); return; } fbi = hisifd->fbi;//lint !e838 if (NULL == fbi) { HISI_FB_ERR("fbi is NULL\n"); return; } logo_buffer_base_temp = g_logo_buffer_base; for (i = 0; i < (g_logo_buffer_size / PAGE_SIZE); i++) { free_reserved_page(phys_to_page(logo_buffer_base_temp)); logo_buffer_base_temp += PAGE_SIZE; } memblock_free(g_logo_buffer_base, g_logo_buffer_size); g_logo_buffer_size = 0; g_logo_buffer_base = 0; } /*lint +e574 +e737 -e570 -e613 -e647*/
#pragma once #include "tdd_shape.h" #include "boxdrawing.h" #include "tdd_surface.h" namespace TDD::Shape { class Box : public Shape { public: std::wstring GetShapeTypeName() const override { return L"Box"; } void Paint(Surface& sf, const Location& offset) override; void SetSize(const Size& s) override; std::shared_ptr<Shape> Duplicate() override; void Copy(std::shared_ptr<Shape> s) override; void to_json(json& j) const override; void from_json(const json & j, Instance& instance) override; public: std::vector<std::wstring> GetPopupMenu() override; void ExecuteCommand(std::wstring& cmd) override; private: Boxdrawing::Type border_type = Boxdrawing::Type::Normal; std::optional<Boxdrawing::Type> u_type; std::optional<Boxdrawing::Type> r_type; std::optional<Boxdrawing::Type> d_type; std::optional<Boxdrawing::Type> l_type; }; }
<reponame>MouchenHung-QUANTA/OpenBIC #ifndef SENSOR_HANDLER_H #define SENSOR_HANDLER_H #include "ipmi.h" void SENSOR_GET_SENSOR_READING(ipmi_msg *msg); void IPMI_SENSOR_handler(ipmi_msg *msg); #endif
#pragma once class Vector3 { public: Vector3(); Vector3(float x, float y, float z); ~Vector3(); Vector3 Copy(); float Length(); float SqrLength(); Vector3 Normalize(); Vector3 Negate(); Vector3 Add(const Vector3 &v); Vector3 Subtract(const Vector3 &v); Vector3 Multiply(float f); Vector3 Divide(float f); float Dot(const Vector3 &v); Vector3 Cross(const Vector3 &v); static Vector3 s_zero; public: float m_x; float m_y; float m_z; }; class Ray3 { public: Ray3(); Ray3(const Vector3 &origin, const Vector3 &direction); ~Ray3(); Vector3 GetPoint(float t); public: Vector3 m_origin; Vector3 m_direction; }; class Geometry; class IntersectResult { public: IntersectResult(); ~IntersectResult(); public: Geometry *m_geometry; float m_distance; Vector3 m_position; Vector3 m_normal; public: static IntersectResult s_noHit; }; class Material; class Geometry { public: Geometry(); virtual void Initialize() = 0; virtual void Intersect(Ray3 *ray, IntersectResult *intersectResult) = 0; public: Material *m_material; }; class Sphere : public Geometry { public: Sphere(Vector3 center, float radius); ~Sphere(); void Initialize() override; void Intersect(Ray3 *ray, IntersectResult *intersectResult) override; public: Vector3 m_center; float m_radius; private: float m_sqrRadius; }; class Plane : public Geometry { public: Plane(Vector3 normal, float d); ~Plane(); void Initialize() override; void Intersect(Ray3 *ray, IntersectResult *intersectResult) override; public: Vector3 m_normal; float m_d; private: Vector3 m_position; }; class Union : public Geometry { public: Union(); ~Union(); void AddGeometry(Geometry *geometry); void Initialize() override; void Intersect(Ray3 *ray, IntersectResult *intersectResult) override; public: std::vector<Geometry *> m_geometies; }; class PerspectiveCamera { public: PerspectiveCamera(const Vector3 &eye, const Vector3 &front, const Vector3 &up, float fov); ~PerspectiveCamera(); void Initialize(); void GenerateRay(float x, float y, Ray3 *ray); public: Vector3 m_eye; Vector3 m_front; Vector3 m_refUp; float m_fov; public: Vector3 m_right; Vector3 m_up; float m_fovScale; }; class Color { public: Color(); Color(float r, float g, float b); ~Color(); Color Add(const Color &c); Color Multiply(float s); Color Modulate(const Color &c); void Saturate(); public: float m_r; float m_g; float m_b; public: static Color s_black; static Color s_white; static Color s_red; static Color s_green; static Color s_blue; static Color s_yellow; }; class Material { public: virtual Color Sample(Ray3 *ray, Vector3 *position, Vector3 *normal) = 0; public: float m_reflectiveness; }; class CheckerMaterial : public Material { public: CheckerMaterial(float scale, float reflectiveness); Color Sample(Ray3 *ray, Vector3 *position, Vector3 *normal) override; public: float m_scale; }; class PhongMaterial : public Material { public: PhongMaterial(const Color &diffuse, const Color &specular, float shininess, float reflectiveness); ~PhongMaterial(); Color Sample(Ray3 *ray, Vector3 *position, Vector3 *normal) override; public: Color m_diffuse; Color m_specular; float m_shininess; }; class LightSample { public: LightSample(); LightSample(const Vector3 &L, const Color &EL); ~LightSample(); static LightSample s_zero; public: Vector3 m_L; Color m_EL; }; class Light { public: Light(); virtual void Initialize() = 0; virtual void Sample(LightSample *lightSample, Geometry *scene, const Vector3 &position) = 0; bool m_shadow; }; class DirectionalLight : public Light { public: DirectionalLight(const Color &irradiance, const Vector3 &direction); ~DirectionalLight(); void Initialize() override; void Sample(LightSample *lightSample, Geometry *scene, const Vector3 &position) override; private: Color m_irradiance; Vector3 m_direction; Vector3 m_L; }; class PointLight : public Light { public: PointLight(const Color &intensity, const Vector3 &position); ~PointLight(); void Initialize() override; void Sample(LightSample *lightSample, Geometry *scene, const Vector3 &position) override; private: Color m_intensity; Vector3 m_position; }; class SpotLight : public Light { public: SpotLight(const Color &intensity, const Vector3 &position, const Vector3 &direction, float theta, float phi, float falloff); ~SpotLight(); void Initialize() override; void Sample(LightSample *lightSample, Geometry *scene, const Vector3 &position) override; private: Color m_intensity; Vector3 m_position; Vector3 m_direction; float m_theta; float m_phi; float m_falloff; private: Vector3 m_S; float m_cosTheta; float m_cosPhi; float m_baseMultiplier; };
<reponame>rlourette/TI_SDK_u-boot-2019.01 /* SPDX-License-Identifier: GPL-2.0 */ /* * Copyright (c) 2014-2016, NVIDIA CORPORATION. */ #ifndef _ABI_BPMP_ABI_H_ #define _ABI_BPMP_ABI_H_ #ifdef LK #include <stdint.h> #endif #ifndef __ABI_PACKED #define __ABI_PACKED __attribute__((packed)) #endif #ifdef NO_GCC_EXTENSIONS #define EMPTY char empty; #define EMPTY_ARRAY 1 #else #define EMPTY #define EMPTY_ARRAY 0 #endif #ifndef __UNION_ANON #define __UNION_ANON #endif /** * @file */ /** * @defgroup MRQ MRQ Messages * @brief Messages sent to/from BPMP via IPC * @{ * @defgroup MRQ_Format Message Format * @defgroup MRQ_Codes Message Request (MRQ) Codes * @defgroup MRQ_Payloads Message Payloads * @defgroup Error_Codes Error Codes * @} */ /** * @addtogroup MRQ_Format Message Format * @{ * The CPU requests the BPMP to perform a particular service by * sending it an IVC frame containing a single MRQ message. An MRQ * message consists of a @ref mrq_request followed by a payload whose * format depends on mrq_request::mrq. * * The BPMP processes the data and replies with an IVC frame (on the * same IVC channel) containing and MRQ response. An MRQ response * consists of a @ref mrq_response followed by a payload whose format * depends on the associated mrq_request::mrq. * * A well-defined subset of the MRQ messages that the CPU sends to the * BPMP can lead to BPMP eventually sending an MRQ message to the * CPU. For example, when the CPU uses an #MRQ_THERMAL message to set * a thermal trip point, the BPMP may eventually send a single * #MRQ_THERMAL message of its own to the CPU indicating that the trip * point has been crossed. * @} */ /** * @ingroup MRQ_Format * @brief header for an MRQ message * * Provides the MRQ number for the MRQ message: #mrq. The remainder of * the MRQ message is a payload (immediately following the * mrq_request) whose format depends on mrq. * * @todo document the flags */ struct mrq_request { /** @brief MRQ number of the request */ uint32_t mrq; /** @brief flags for the request */ uint32_t flags; } __ABI_PACKED; /** * @ingroup MRQ_Format * @brief header for an MRQ response * * Provides an error code for the associated MRQ message. The * remainder of the MRQ response is a payload (immediately following * the mrq_response) whose format depends on the associated * mrq_request::mrq * * @todo document the flags */ struct mrq_response { /** @brief error code for the MRQ request itself */ int32_t err; /** @brief flags for the response */ uint32_t flags; } __ABI_PACKED; /** * @ingroup MRQ_Format * Minimum needed size for an IPC message buffer */ #define MSG_MIN_SZ 128 /** * @ingroup MRQ_Format * Minimum size guaranteed for data in an IPC message buffer */ #define MSG_DATA_MIN_SZ 120 /** * @ingroup MRQ_Codes * @name Legal MRQ codes * These are the legal values for mrq_request::mrq * @{ */ #define MRQ_PING 0 #define MRQ_QUERY_TAG 1 #define MRQ_MODULE_LOAD 4 #define MRQ_MODULE_UNLOAD 5 #define MRQ_TRACE_MODIFY 7 #define MRQ_WRITE_TRACE 8 #define MRQ_THREADED_PING 9 #define MRQ_MODULE_MAIL 11 #define MRQ_DEBUGFS 19 #define MRQ_RESET 20 #define MRQ_I2C 21 #define MRQ_CLK 22 #define MRQ_QUERY_ABI 23 #define MRQ_PG_READ_STATE 25 #define MRQ_PG_UPDATE_STATE 26 #define MRQ_THERMAL 27 #define MRQ_CPU_VHINT 28 #define MRQ_ABI_RATCHET 29 #define MRQ_EMC_DVFS_LATENCY 31 #define MRQ_TRACE_ITER 64 /** @} */ /** * @ingroup MRQ_Codes * @brief Maximum MRQ code to be sent by CPU software to * BPMP. Subject to change in future */ #define MAX_CPU_MRQ_ID 64 /** * @addtogroup MRQ_Payloads Message Payloads * @{ * @defgroup Ping * @defgroup Query_Tag Query Tag * @defgroup Module Loadable Modules * @defgroup Trace * @defgroup Debugfs * @defgroup Reset * @defgroup I2C * @defgroup Clocks * @defgroup ABI_info ABI Info * @defgroup MC_Flush MC Flush * @defgroup Powergating * @defgroup Thermal * @defgroup Vhint CPU Voltage hint * @defgroup MRQ_Deprecated Deprecated MRQ messages * @defgroup EMC * @} */ /** * @ingroup MRQ_Codes * @def MRQ_PING * @brief A simple ping * * * Platforms: All * * Initiators: Any * * Targets: Any * * Request Payload: @ref mrq_ping_request * * Response Payload: @ref mrq_ping_response * * @ingroup MRQ_Codes * @def MRQ_THREADED_PING * @brief A deeper ping * * * Platforms: All * * Initiators: Any * * Targets: BPMP * * Request Payload: @ref mrq_ping_request * * Response Payload: @ref mrq_ping_response * * Behavior is equivalent to a simple #MRQ_PING except that BPMP * responds from a thread context (providing a slightly more robust * sign of life). * */ /** * @ingroup Ping * @brief request with #MRQ_PING * * Used by the sender of an #MRQ_PING message to request a pong from * recipient. The response from the recipient is computed based on * #challenge. */ struct mrq_ping_request { /** @brief arbitrarily chosen value */ uint32_t challenge; } __ABI_PACKED; /** * @ingroup Ping * @brief response to #MRQ_PING * * Sent in response to an #MRQ_PING message. #reply should be the * mrq_ping_request challenge left shifted by 1 with the carry-bit * dropped. * */ struct mrq_ping_response { /** @brief response to the MRQ_PING challege */ uint32_t reply; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_QUERY_TAG * @brief Query BPMP firmware's tag (i.e. version information) * * * Platforms: All * * Initiators: CCPLEX * * Targets: BPMP * * Request Payload: @ref mrq_query_tag_request * * Response Payload: N/A * */ /** * @ingroup Query_Tag * @brief request with #MRQ_QUERY_TAG * * Used by #MRQ_QUERY_TAG call to ask BPMP to fill in the memory * pointed by #addr with BPMP firmware header. * * The sender is reponsible for ensuring that #addr is mapped in to * the recipient's address map. */ struct mrq_query_tag_request { /** @brief base address to store the firmware header */ uint32_t addr; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_MODULE_LOAD * @brief dynamically load a BPMP code module * * * Platforms: All * * Initiators: CCPLEX * * Targets: BPMP * * Request Payload: @ref mrq_module_load_request * * Response Payload: @ref mrq_module_load_response * * @note This MRQ is disabled on production systems * */ /** * @ingroup Module * @brief request with #MRQ_MODULE_LOAD * * Used by #MRQ_MODULE_LOAD calls to ask the recipient to dynamically * load the code located at #phys_addr and having size #size * bytes. #phys_addr is treated as a void pointer. * * The recipient copies the code from #phys_addr to locally allocated * memory prior to responding to this message. * * @todo document the module header format * * The sender is responsible for ensuring that the code is mapped in * the recipient's address map. * */ struct mrq_module_load_request { /** @brief base address of the code to load. Treated as (void *) */ uint32_t phys_addr; /* (void *) */ /** @brief size in bytes of code to load */ uint32_t size; } __ABI_PACKED; /** * @ingroup Module * @brief response to #MRQ_MODULE_LOAD * * @todo document mrq_response::err */ struct mrq_module_load_response { /** @brief handle to the loaded module */ uint32_t base; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_MODULE_UNLOAD * @brief unload a previously loaded code module * * * Platforms: All * * Initiators: CCPLEX * * Targets: BPMP * * Request Payload: @ref mrq_module_unload_request * * Response Payload: N/A * * @note This MRQ is disabled on production systems */ /** * @ingroup Module * @brief request with #MRQ_MODULE_UNLOAD * * Used by #MRQ_MODULE_UNLOAD calls to request that a previously loaded * module be unloaded. */ struct mrq_module_unload_request { /** @brief handle of the module to unload */ uint32_t base; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_TRACE_MODIFY * @brief modify the set of enabled trace events * * * Platforms: All * * Initiators: CCPLEX * * Targets: BPMP * * Request Payload: @ref mrq_trace_modify_request * * Response Payload: @ref mrq_trace_modify_response * * @note This MRQ is disabled on production systems */ /** * @ingroup Trace * @brief request with #MRQ_TRACE_MODIFY * * Used by %MRQ_TRACE_MODIFY calls to enable or disable specify trace * events. #set takes precedence for any bit set in both #set and * #clr. */ struct mrq_trace_modify_request { /** @brief bit mask of trace events to disable */ uint32_t clr; /** @brief bit mask of trace events to enable */ uint32_t set; } __ABI_PACKED; /** * @ingroup Trace * @brief response to #MRQ_TRACE_MODIFY * * Sent in repsonse to an #MRQ_TRACE_MODIFY message. #mask reflects the * state of which events are enabled after the recipient acted on the * message. * */ struct mrq_trace_modify_response { /** @brief bit mask of trace event enable states */ uint32_t mask; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_WRITE_TRACE * @brief Write trace data to a buffer * * * Platforms: All * * Initiators: CCPLEX * * Targets: BPMP * * Request Payload: @ref mrq_write_trace_request * * Response Payload: @ref mrq_write_trace_response * * mrq_response::err depends on the @ref mrq_write_trace_request field * values. err is -#BPMP_EINVAL if size is zero or area is NULL or * area is in an illegal range. A positive value for err indicates the * number of bytes written to area. * * @note This MRQ is disabled on production systems */ /** * @ingroup Trace * @brief request with #MRQ_WRITE_TRACE * * Used by MRQ_WRITE_TRACE calls to ask the recipient to copy trace * data from the recipient's local buffer to the output buffer. #area * is treated as a byte-aligned pointer in the recipient's address * space. * * The sender is responsible for ensuring that the output * buffer is mapped in the recipient's address map. The recipient is * responsible for protecting its own code and data from accidental * overwrites. */ struct mrq_write_trace_request { /** @brief base address of output buffer */ uint32_t area; /** @brief size in bytes of the output buffer */ uint32_t size; } __ABI_PACKED; /** * @ingroup Trace * @brief response to #MRQ_WRITE_TRACE * * Once this response is sent, the respondent will not access the * output buffer further. */ struct mrq_write_trace_response { /** * @brief flag whether more data remains in local buffer * * Value is 1 if the entire local trace buffer has been * drained to the outputbuffer. Value is 0 otherwise. */ uint32_t eof; } __ABI_PACKED; /** @private */ struct mrq_threaded_ping_request { uint32_t challenge; } __ABI_PACKED; /** @private */ struct mrq_threaded_ping_response { uint32_t reply; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_MODULE_MAIL * @brief send a message to a loadable module * * * Platforms: All * * Initiators: Any * * Targets: BPMP * * Request Payload: @ref mrq_module_mail_request * * Response Payload: @ref mrq_module_mail_response * * @note This MRQ is disabled on production systems */ /** * @ingroup Module * @brief request with #MRQ_MODULE_MAIL */ struct mrq_module_mail_request { /** @brief handle to the previously loaded module */ uint32_t base; /** @brief module-specific mail payload * * The length of data[ ] is unknown to the BPMP core firmware * but it is limited to the size of an IPC message. */ uint8_t data[EMPTY_ARRAY]; } __ABI_PACKED; /** * @ingroup Module * @brief response to #MRQ_MODULE_MAIL */ struct mrq_module_mail_response { /** @brief module-specific mail payload * * The length of data[ ] is unknown to the BPMP core firmware * but it is limited to the size of an IPC message. */ uint8_t data[EMPTY_ARRAY]; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_DEBUGFS * @brief Interact with BPMP's debugfs file nodes * * * Platforms: T186 * * Initiators: Any * * Targets: BPMP * * Request Payload: @ref mrq_debugfs_request * * Response Payload: @ref mrq_debugfs_response */ /** * @addtogroup Debugfs * @{ * * The BPMP firmware implements a pseudo-filesystem called * debugfs. Any driver within the firmware may register with debugfs * to expose an arbitrary set of "files" in the filesystem. When * software on the CPU writes to a debugfs file, debugfs passes the * written data to a callback provided by the driver. When software on * the CPU reads a debugfs file, debugfs queries the driver for the * data to return to the CPU. The intention of the debugfs filesystem * is to provide information useful for debugging the system at * runtime. * * @note The files exposed via debugfs are not part of the * BPMP firmware's ABI. debugfs files may be added or removed in any * given version of the firmware. Typically the semantics of a debugfs * file are consistent from version to version but even that is not * guaranteed. * * @} */ /** @ingroup Debugfs */ enum mrq_debugfs_commands { CMD_DEBUGFS_READ = 1, CMD_DEBUGFS_WRITE = 2, CMD_DEBUGFS_DUMPDIR = 3, CMD_DEBUGFS_MAX }; /** * @ingroup Debugfs * @brief parameters for CMD_DEBUGFS_READ/WRITE command */ struct cmd_debugfs_fileop_request { /** @brief physical address pointing at filename */ uint32_t fnameaddr; /** @brief length in bytes of filename buffer */ uint32_t fnamelen; /** @brief physical address pointing to data buffer */ uint32_t dataaddr; /** @brief length in bytes of data buffer */ uint32_t datalen; } __ABI_PACKED; /** * @ingroup Debugfs * @brief parameters for CMD_DEBUGFS_READ/WRITE command */ struct cmd_debugfs_dumpdir_request { /** @brief physical address pointing to data buffer */ uint32_t dataaddr; /** @brief length in bytes of data buffer */ uint32_t datalen; } __ABI_PACKED; /** * @ingroup Debugfs * @brief response data for CMD_DEBUGFS_READ/WRITE command */ struct cmd_debugfs_fileop_response { /** @brief always 0 */ uint32_t reserved; /** @brief number of bytes read from or written to data buffer */ uint32_t nbytes; } __ABI_PACKED; /** * @ingroup Debugfs * @brief response data for CMD_DEBUGFS_DUMPDIR command */ struct cmd_debugfs_dumpdir_response { /** @brief always 0 */ uint32_t reserved; /** @brief number of bytes read from or written to data buffer */ uint32_t nbytes; } __ABI_PACKED; /** * @ingroup Debugfs * @brief request with #MRQ_DEBUGFS. * * The sender of an MRQ_DEBUGFS message uses #cmd to specify a debugfs * command to execute. Legal commands are the values of @ref * mrq_debugfs_commands. Each command requires a specific additional * payload of data. * * |command |payload| * |-------------------|-------| * |CMD_DEBUGFS_READ |fop | * |CMD_DEBUGFS_WRITE |fop | * |CMD_DEBUGFS_DUMPDIR|dumpdir| */ struct mrq_debugfs_request { uint32_t cmd; union { struct cmd_debugfs_fileop_request fop; struct cmd_debugfs_dumpdir_request dumpdir; } __UNION_ANON; } __ABI_PACKED; /** * @ingroup Debugfs */ struct mrq_debugfs_response { /** @brief always 0 */ int32_t reserved; union { /** @brief response data for CMD_DEBUGFS_READ OR * CMD_DEBUGFS_WRITE command */ struct cmd_debugfs_fileop_response fop; /** @brief response data for CMD_DEBUGFS_DUMPDIR command */ struct cmd_debugfs_dumpdir_response dumpdir; } __UNION_ANON; } __ABI_PACKED; /** * @addtogroup Debugfs * @{ */ #define DEBUGFS_S_ISDIR (1 << 9) #define DEBUGFS_S_IRUSR (1 << 8) #define DEBUGFS_S_IWUSR (1 << 7) /** @} */ /** * @ingroup MRQ_Codes * @def MRQ_RESET * @brief reset an IP block * * * Platforms: T186 * * Initiators: Any * * Targets: BPMP * * Request Payload: @ref mrq_reset_request * * Response Payload: N/A */ /** * @ingroup Reset */ enum mrq_reset_commands { CMD_RESET_ASSERT = 1, CMD_RESET_DEASSERT = 2, CMD_RESET_MODULE = 3, CMD_RESET_MAX, /* not part of ABI and subject to change */ }; /** * @ingroup Reset * @brief request with MRQ_RESET * * Used by the sender of an #MRQ_RESET message to request BPMP to * assert or or deassert a given reset line. */ struct mrq_reset_request { /** @brief reset action to perform (@enum mrq_reset_commands) */ uint32_t cmd; /** @brief id of the reset to affected */ uint32_t reset_id; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_I2C * @brief issue an i2c transaction * * * Platforms: T186 * * Initiators: Any * * Targets: BPMP * * Request Payload: @ref mrq_i2c_request * * Response Payload: @ref mrq_i2c_response */ /** * @addtogroup I2C * @{ */ #define TEGRA_I2C_IPC_MAX_IN_BUF_SIZE (MSG_DATA_MIN_SZ - 12) #define TEGRA_I2C_IPC_MAX_OUT_BUF_SIZE (MSG_DATA_MIN_SZ - 4) /** @} */ /** * @ingroup I2C * @name Serial I2C flags * Use these flags with serial_i2c_request::flags * @{ */ #define SERIALI2C_TEN 0x0010 #define SERIALI2C_RD 0x0001 #define SERIALI2C_STOP 0x8000 #define SERIALI2C_NOSTART 0x4000 #define SERIALI2C_REV_DIR_ADDR 0x2000 #define SERIALI2C_IGNORE_NAK 0x1000 #define SERIALI2C_NO_RD_ACK 0x0800 #define SERIALI2C_RECV_LEN 0x0400 /** @} */ /** @ingroup I2C */ enum { CMD_I2C_XFER = 1 }; /** * @ingroup I2C * @brief serializable i2c request * * Instances of this structure are packed (little-endian) into * cmd_i2c_xfer_request::data_buf. Each instance represents a single * transaction (or a portion of a transaction with repeated starts) on * an i2c bus. * * Because these structures are packed, some instances are likely to * be misaligned. Additionally because #data is variable length, it is * not possible to iterate through a serialized list of these * structures without inspecting #len in each instance. It may be * easier to serialize or deserialize cmd_i2c_xfer_request::data_buf * manually rather than using this structure definition. */ struct serial_i2c_request { /** @brief I2C slave address */ uint16_t addr; /** @brief bitmask of SERIALI2C_ flags */ uint16_t flags; /** @brief length of I2C transaction in bytes */ uint16_t len; /** @brief for write transactions only, #len bytes of data */ uint8_t data[]; } __ABI_PACKED; /** * @ingroup I2C * @brief trigger one or more i2c transactions */ struct cmd_i2c_xfer_request { /** @brief valid bus number from mach-t186/i2c-t186.h*/ uint32_t bus_id; /** @brief count of valid bytes in #data_buf*/ uint32_t data_size; /** @brief serialized packed instances of @ref serial_i2c_request*/ uint8_t data_buf[TEGRA_I2C_IPC_MAX_IN_BUF_SIZE]; } __ABI_PACKED; /** * @ingroup I2C * @brief container for data read from the i2c bus * * Processing an cmd_i2c_xfer_request::data_buf causes BPMP to execute * zero or more I2C reads. The data read from the bus is serialized * into #data_buf. */ struct cmd_i2c_xfer_response { /** @brief count of valid bytes in #data_buf*/ uint32_t data_size; /** @brief i2c read data */ uint8_t data_buf[TEGRA_I2C_IPC_MAX_OUT_BUF_SIZE]; } __ABI_PACKED; /** * @ingroup I2C * @brief request with #MRQ_I2C */ struct mrq_i2c_request { /** @brief always CMD_I2C_XFER (i.e. 1) */ uint32_t cmd; /** @brief parameters of the transfer request */ struct cmd_i2c_xfer_request xfer; } __ABI_PACKED; /** * @ingroup I2C * @brief response to #MRQ_I2C */ struct mrq_i2c_response { struct cmd_i2c_xfer_response xfer; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_CLK * * * Platforms: T186 * * Initiators: Any * * Targets: BPMP * * Request Payload: @ref mrq_clk_request * * Response Payload: @ref mrq_clk_response * @addtogroup Clocks * @{ */ /** * @name MRQ_CLK sub-commands * @{ */ enum { CMD_CLK_GET_RATE = 1, CMD_CLK_SET_RATE = 2, CMD_CLK_ROUND_RATE = 3, CMD_CLK_GET_PARENT = 4, CMD_CLK_SET_PARENT = 5, CMD_CLK_IS_ENABLED = 6, CMD_CLK_ENABLE = 7, CMD_CLK_DISABLE = 8, CMD_CLK_GET_ALL_INFO = 14, CMD_CLK_GET_MAX_CLK_ID = 15, CMD_CLK_MAX, }; /** @} */ #define MRQ_CLK_NAME_MAXLEN 40 #define MRQ_CLK_MAX_PARENTS 16 /** @private */ struct cmd_clk_get_rate_request { EMPTY } __ABI_PACKED; struct cmd_clk_get_rate_response { int64_t rate; } __ABI_PACKED; struct cmd_clk_set_rate_request { int32_t unused; int64_t rate; } __ABI_PACKED; struct cmd_clk_set_rate_response { int64_t rate; } __ABI_PACKED; struct cmd_clk_round_rate_request { int32_t unused; int64_t rate; } __ABI_PACKED; struct cmd_clk_round_rate_response { int64_t rate; } __ABI_PACKED; /** @private */ struct cmd_clk_get_parent_request { EMPTY } __ABI_PACKED; struct cmd_clk_get_parent_response { uint32_t parent_id; } __ABI_PACKED; struct cmd_clk_set_parent_request { uint32_t parent_id; } __ABI_PACKED; struct cmd_clk_set_parent_response { uint32_t parent_id; } __ABI_PACKED; /** @private */ struct cmd_clk_is_enabled_request { EMPTY } __ABI_PACKED; struct cmd_clk_is_enabled_response { int32_t state; } __ABI_PACKED; /** @private */ struct cmd_clk_enable_request { EMPTY } __ABI_PACKED; /** @private */ struct cmd_clk_enable_response { EMPTY } __ABI_PACKED; /** @private */ struct cmd_clk_disable_request { EMPTY } __ABI_PACKED; /** @private */ struct cmd_clk_disable_response { EMPTY } __ABI_PACKED; /** @private */ struct cmd_clk_get_all_info_request { EMPTY } __ABI_PACKED; struct cmd_clk_get_all_info_response { uint32_t flags; uint32_t parent; uint32_t parents[MRQ_CLK_MAX_PARENTS]; uint8_t num_parents; uint8_t name[MRQ_CLK_NAME_MAXLEN]; } __ABI_PACKED; /** @private */ struct cmd_clk_get_max_clk_id_request { EMPTY } __ABI_PACKED; struct cmd_clk_get_max_clk_id_response { uint32_t max_id; } __ABI_PACKED; /** @} */ /** * @ingroup Clocks * @brief request with #MRQ_CLK * * Used by the sender of an #MRQ_CLK message to control clocks. The * clk_request is split into several sub-commands. Some sub-commands * require no additional data. Others have a sub-command specific * payload * * |sub-command |payload | * |----------------------------|-----------------------| * |CMD_CLK_GET_RATE |- | * |CMD_CLK_SET_RATE |clk_set_rate | * |CMD_CLK_ROUND_RATE |clk_round_rate | * |CMD_CLK_GET_PARENT |- | * |CMD_CLK_SET_PARENT |clk_set_parent | * |CMD_CLK_IS_ENABLED |- | * |CMD_CLK_ENABLE |- | * |CMD_CLK_DISABLE |- | * |CMD_CLK_GET_ALL_INFO |- | * |CMD_CLK_GET_MAX_CLK_ID |- | * */ struct mrq_clk_request { /** @brief sub-command and clock id concatenated to 32-bit word. * - bits[31..24] is the sub-cmd. * - bits[23..0] is the clock id */ uint32_t cmd_and_id; union { /** @private */ struct cmd_clk_get_rate_request clk_get_rate; struct cmd_clk_set_rate_request clk_set_rate; struct cmd_clk_round_rate_request clk_round_rate; /** @private */ struct cmd_clk_get_parent_request clk_get_parent; struct cmd_clk_set_parent_request clk_set_parent; /** @private */ struct cmd_clk_enable_request clk_enable; /** @private */ struct cmd_clk_disable_request clk_disable; /** @private */ struct cmd_clk_is_enabled_request clk_is_enabled; /** @private */ struct cmd_clk_get_all_info_request clk_get_all_info; /** @private */ struct cmd_clk_get_max_clk_id_request clk_get_max_clk_id; } __UNION_ANON; } __ABI_PACKED; /** * @ingroup Clocks * @brief response to MRQ_CLK * * Each sub-command supported by @ref mrq_clk_request may return * sub-command-specific data. Some do and some do not as indicated in * the following table * * |sub-command |payload | * |----------------------------|------------------------| * |CMD_CLK_GET_RATE |clk_get_rate | * |CMD_CLK_SET_RATE |clk_set_rate | * |CMD_CLK_ROUND_RATE |clk_round_rate | * |CMD_CLK_GET_PARENT |clk_get_parent | * |CMD_CLK_SET_PARENT |clk_set_parent | * |CMD_CLK_IS_ENABLED |clk_is_enabled | * |CMD_CLK_ENABLE |- | * |CMD_CLK_DISABLE |- | * |CMD_CLK_GET_ALL_INFO |clk_get_all_info | * |CMD_CLK_GET_MAX_CLK_ID |clk_get_max_id | * */ struct mrq_clk_response { union { struct cmd_clk_get_rate_response clk_get_rate; struct cmd_clk_set_rate_response clk_set_rate; struct cmd_clk_round_rate_response clk_round_rate; struct cmd_clk_get_parent_response clk_get_parent; struct cmd_clk_set_parent_response clk_set_parent; /** @private */ struct cmd_clk_enable_response clk_enable; /** @private */ struct cmd_clk_disable_response clk_disable; struct cmd_clk_is_enabled_response clk_is_enabled; struct cmd_clk_get_all_info_response clk_get_all_info; struct cmd_clk_get_max_clk_id_response clk_get_max_clk_id; } __UNION_ANON; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_QUERY_ABI * @brief check if an MRQ is implemented * * * Platforms: All * * Initiators: Any * * Targets: Any * * Request Payload: @ref mrq_query_abi_request * * Response Payload: @ref mrq_query_abi_response */ /** * @ingroup ABI_info * @brief request with MRQ_QUERY_ABI * * Used by #MRQ_QUERY_ABI call to check if MRQ code #mrq is supported * by the recipient. */ struct mrq_query_abi_request { /** @brief MRQ code to query */ uint32_t mrq; } __ABI_PACKED; /** * @ingroup ABI_info * @brief response to MRQ_QUERY_ABI */ struct mrq_query_abi_response { /** @brief 0 if queried MRQ is supported. Else, -#BPMP_ENODEV */ int32_t status; } __ABI_PACKED; /** * @ingroup MRQ_Codes * @def MRQ_PG_READ_STATE * @brief read the power-gating state of a partition * * * Platforms: T186 * * Initiators: Any * * Targets: BPMP * * Request Payload: @ref mrq_pg_read_state_request * * Response Payload: @ref mrq_pg_read_state_response * @addtogroup Powergating * @{ */ /** * @brief request with #MRQ_PG_READ_STATE * * Used by MRQ_PG_READ_STATE call to read the current state of a * partition. */ struct mrq_pg_read_state_request { /** @brief ID of partition */ uint32_t partition_id; } __ABI_PACKED; /** * @brief response to MRQ_PG_READ_STATE * @todo define possible errors. */ struct mrq_pg_read_state_response { /** @brief read as don't care */ uint32_t sram_state; /** @brief state of power partition * * 0 : off * * 1 : on */ uint32_t logic_state; } __ABI_PACKED; /** @} */ /** * @ingroup MRQ_Codes * @def MRQ_PG_UPDATE_STATE * @brief modify the power-gating state of a partition * * * Platforms: T186 * * Initiators: Any * * Targets: BPMP * * Request Payload: @ref mrq_pg_update_state_request * * Response Payload: N/A * @addtogroup Powergating * @{ */ /** * @brief request with mrq_pg_update_state_request * * Used by #MRQ_PG_UPDATE_STATE call to request BPMP to change the * state of a power partition #partition_id. */ struct mrq_pg_update_state_request { /** @brief ID of partition */ uint32_t partition_id; /** @brief secondary control of power partition * @details Ignored by many versions of the BPMP * firmware. For maximum compatibility, set the value * according to @logic_state * * 0x1: power ON partition (@ref logic_state == 0x3) * * 0x3: power OFF partition (@ref logic_state == 0x1) */ uint32_t sram_state; /** @brief controls state of power partition, legal values are * * 0x1 : power OFF partition * * 0x3 : power ON partition */ uint32_t logic_state; /** @brief change state of clocks of the power partition, legal values * * 0x0 : do not change clock state * * 0x1 : disable partition clocks (only applicable when * @ref logic_state == 0x1) * * 0x3 : enable partition clocks (only applicable when * @ref logic_state == 0x3) */ uint32_t clock_state; } __ABI_PACKED; /** @} */ /** * @ingroup MRQ_Codes * @def MRQ_THERMAL * @brief interact with BPMP thermal framework * * * Platforms: T186 * * Initiators: Any * * Targets: Any * * Request Payload: TODO * * Response Payload: TODO * * @addtogroup Thermal * * The BPMP firmware includes a thermal framework. Drivers within the * bpmp firmware register with the framework to provide thermal * zones. Each thermal zone corresponds to an entity whose temperature * can be measured. The framework also has a notion of trip points. A * trip point consists of a thermal zone id, a temperature, and a * callback routine. The framework invokes the callback when the zone * hits the indicated temperature. The BPMP firmware uses this thermal * framework interally to implement various temperature-dependent * functions. * * Software on the CPU can use #MRQ_THERMAL (with payload @ref * mrq_thermal_host_to_bpmp_request) to interact with the BPMP thermal * framework. The CPU must It can query the number of supported zones, * query zone temperatures, and set trip points. * * When a trip point set by the CPU gets crossed, BPMP firmware issues * an IPC to the CPU having mrq_request::mrq = #MRQ_THERMAL and a * payload of @ref mrq_thermal_bpmp_to_host_request. * @{ */ enum mrq_thermal_host_to_bpmp_cmd { /** * @brief Check whether the BPMP driver supports the specified * request type. * * Host needs to supply request parameters. * * mrq_response::err is 0 if the specified request is * supported and -#BPMP_ENODEV otherwise. */ CMD_THERMAL_QUERY_ABI = 0, /** * @brief Get the current temperature of the specified zone. * * Host needs to supply request parameters. * * mrq_response::err is * * 0: Temperature query succeeded. * * -#BPMP_EINVAL: Invalid request parameters. * * -#BPMP_ENOENT: No driver registered for thermal zone.. * * -#BPMP_EFAULT: Problem reading temperature measurement. */ CMD_THERMAL_GET_TEMP = 1, /** * @brief Enable or disable and set the lower and upper * thermal limits for a thermal trip point. Each zone has * one trip point. * * Host needs to supply request parameters. Once the * temperature hits a trip point, the BPMP will send a message * to the CPU having MRQ=MRQ_THERMAL and * type=CMD_THERMAL_HOST_TRIP_REACHED * * mrq_response::err is * * 0: Trip successfully set. * * -#BPMP_EINVAL: Invalid request parameters. * * -#BPMP_ENOENT: No driver registered for thermal zone. * * -#BPMP_EFAULT: Problem setting trip point. */ CMD_THERMAL_SET_TRIP = 2, /** * @brief Get the number of supported thermal zones. * * No request parameters required. * * mrq_response::err is always 0, indicating success. */ CMD_THERMAL_GET_NUM_ZONES = 3, /** @brief: number of supported host-to-bpmp commands. May * increase in future */ CMD_THERMAL_HOST_TO_BPMP_NUM }; enum mrq_thermal_bpmp_to_host_cmd { /** * @brief Indication that the temperature for a zone has * exceeded the range indicated in the thermal trip point * for the zone. * * BPMP needs to supply request parameters. Host only needs to * acknowledge. */ CMD_THERMAL_HOST_TRIP_REACHED = 100, /** @brief: number of supported bpmp-to-host commands. May * increase in future */ CMD_THERMAL_BPMP_TO_HOST_NUM }; /* * Host->BPMP request data for request type CMD_THERMAL_QUERY_ABI * * zone: Request type for which to check existence. */ struct cmd_thermal_query_abi_request { uint32_t type; } __ABI_PACKED; /* * Host->BPMP request data for request type CMD_THERMAL_GET_TEMP * * zone: Number of thermal zone. */ struct cmd_thermal_get_temp_request { uint32_t zone; } __ABI_PACKED; /* * BPMP->Host reply data for request CMD_THERMAL_GET_TEMP * * error: 0 if request succeeded. * -BPMP_EINVAL if request parameters were invalid. * -BPMP_ENOENT if no driver was registered for the specified thermal zone. * -BPMP_EFAULT for other thermal zone driver errors. * temp: Current temperature in millicelsius. */ struct cmd_thermal_get_temp_response { int32_t temp; } __ABI_PACKED; /* * Host->BPMP request data for request type CMD_THERMAL_SET_TRIP * * zone: Number of thermal zone. * low: Temperature of lower trip point in millicelsius * high: Temperature of upper trip point in millicelsius * enabled: 1 to enable trip point, 0 to disable trip point */ struct cmd_thermal_set_trip_request { uint32_t zone; int32_t low; int32_t high; uint32_t enabled; } __ABI_PACKED; /* * BPMP->Host request data for request type CMD_THERMAL_HOST_TRIP_REACHED * * zone: Number of thermal zone where trip point was reached. */ struct cmd_thermal_host_trip_reached_request { uint32_t zone; } __ABI_PACKED; /* * BPMP->Host reply data for request type CMD_THERMAL_GET_NUM_ZONES * * num: Number of supported thermal zones. The thermal zones are indexed * starting from zero. */ struct cmd_thermal_get_num_zones_response { uint32_t num; } __ABI_PACKED; /* * Host->BPMP request data. * * Reply type is union mrq_thermal_bpmp_to_host_response. * * type: Type of request. Values listed in enum mrq_thermal_type. * data: Request type specific parameters. */ struct mrq_thermal_host_to_bpmp_request { uint32_t type; union { struct cmd_thermal_query_abi_request query_abi; struct cmd_thermal_get_temp_request get_temp; struct cmd_thermal_set_trip_request set_trip; } __UNION_ANON; } __ABI_PACKED; /* * BPMP->Host request data. * * type: Type of request. Values listed in enum mrq_thermal_type. * data: Request type specific parameters. */ struct mrq_thermal_bpmp_to_host_request { uint32_t type; union { struct cmd_thermal_host_trip_reached_request host_trip_reached; } __UNION_ANON; } __ABI_PACKED; /* * Data in reply to a Host->BPMP request. */ union mrq_thermal_bpmp_to_host_response { struct cmd_thermal_get_temp_response get_temp; struct cmd_thermal_get_num_zones_response get_num_zones; } __ABI_PACKED; /** @} */ /** * @ingroup MRQ_Codes * @def MRQ_CPU_VHINT * @brief Query CPU voltage hint data * * * Platforms: T186 * * Initiators: CCPLEX * * Targets: BPMP * * Request Payload: @ref mrq_cpu_vhint_request * * Response Payload: N/A * * @addtogroup Vhint CPU Voltage hint * @{ */ /** * @brief request with #MRQ_CPU_VHINT * * Used by #MRQ_CPU_VHINT call by CCPLEX to retrieve voltage hint data * from BPMP to memory space pointed by #addr. CCPLEX is responsible * to allocate sizeof(cpu_vhint_data) sized block of memory and * appropriately map it for BPMP before sending the request. */ struct mrq_cpu_vhint_request { /** @brief IOVA address for the #cpu_vhint_data */ uint32_t addr; /* struct cpu_vhint_data * */ /** @brief ID of the cluster whose data is requested */ uint32_t cluster_id; /* enum cluster_id */ } __ABI_PACKED; /** * @brief description of the CPU v/f relation * * Used by #MRQ_CPU_VHINT call to carry data pointed by #addr of * struct mrq_cpu_vhint_request */ struct cpu_vhint_data { uint32_t ref_clk_hz; /**< reference frequency in Hz */ uint16_t pdiv; /**< post divider value */ uint16_t mdiv; /**< input divider value */ uint16_t ndiv_max; /**< fMAX expressed with max NDIV value */ /** table of ndiv values as a function of vINDEX (voltage index) */ uint16_t ndiv[80]; /** minimum allowed NDIV value */ uint16_t ndiv_min; /** minimum allowed voltage hint value (as in vINDEX) */ uint16_t vfloor; /** maximum allowed voltage hint value (as in vINDEX) */ uint16_t vceil; /** post-multiplier for vindex value */ uint16_t vindex_mult; /** post-divider for vindex value */ uint16_t vindex_div; /** reserved for future use */ uint16_t reserved[328]; } __ABI_PACKED; /** @} */ /** * @ingroup MRQ_Codes * @def MRQ_ABI_RATCHET * @brief ABI ratchet value query * * * Platforms: T186 * * Initiators: Any * * Targets: BPMP * * Request Payload: @ref mrq_abi_ratchet_request * * Response Payload: @ref mrq_abi_ratchet_response * @addtogroup ABI_info * @{ */ /** * @brief an ABI compatibility mechanism * * BPMP_ABI_RATCHET_VALUE may increase for various reasons in a future * revision of this header file. * 1. That future revision deprecates some MRQ * 2. That future revision introduces a breaking change to an existing * MRQ or * 3. A bug is discovered in an existing implementation of the BPMP-FW * (or possibly one of its clients) which warrants deprecating that * implementation. */ #define BPMP_ABI_RATCHET_VALUE 3 /** * @brief request with #MRQ_ABI_RATCHET. * * #ratchet should be #BPMP_ABI_RATCHET_VALUE from the ABI header * against which the requester was compiled. * * If ratchet is less than BPMP's #BPMP_ABI_RATCHET_VALUE, BPMP may * reply with mrq_response::err = -#BPMP_ERANGE to indicate that * BPMP-FW cannot interoperate correctly with the requester. Requester * should cease further communication with BPMP. * * Otherwise, err shall be 0. */ struct mrq_abi_ratchet_request { /** @brief requester's ratchet value */ uint16_t ratchet; }; /** * @brief response to #MRQ_ABI_RATCHET * * #ratchet shall be #BPMP_ABI_RATCHET_VALUE from the ABI header * against which BPMP firwmare was compiled. * * If #ratchet is less than the requester's #BPMP_ABI_RATCHET_VALUE, * the requster must either interoperate with BPMP according to an ABI * header version with BPMP_ABI_RATCHET_VALUE = ratchet or cease * communication with BPMP. * * If mrq_response::err is 0 and ratchet is greater than or equal to the * requester's BPMP_ABI_RATCHET_VALUE, the requester should continue * normal operation. */ struct mrq_abi_ratchet_response { /** @brief BPMP's ratchet value */ uint16_t ratchet; }; /** @} */ /** * @ingroup MRQ_Codes * @def MRQ_EMC_DVFS_LATENCY * @brief query frequency dependent EMC DVFS latency * * * Platforms: T186 * * Initiators: CCPLEX * * Targets: BPMP * * Request Payload: N/A * * Response Payload: @ref mrq_emc_dvfs_latency_response * @addtogroup EMC * @{ */ /** * @brief used by @ref mrq_emc_dvfs_latency_response */ struct emc_dvfs_latency { /** @brief EMC frequency in kHz */ uint32_t freq; /** @brief EMC DVFS latency in nanoseconds */ uint32_t latency; } __ABI_PACKED; #define EMC_DVFS_LATENCY_MAX_SIZE 14 /** * @brief response to #MRQ_EMC_DVFS_LATENCY */ struct mrq_emc_dvfs_latency_response { /** @brief the number valid entries in #pairs */ uint32_t num_pairs; /** @brief EMC <frequency, latency> information */ struct emc_dvfs_latency pairs[EMC_DVFS_LATENCY_MAX_SIZE]; } __ABI_PACKED; /** @} */ /** * @ingroup MRQ_Codes * @def MRQ_TRACE_ITER * @brief manage the trace iterator * * * Platforms: All * * Initiators: CCPLEX * * Targets: BPMP * * Request Payload: N/A * * Response Payload: @ref mrq_trace_iter_request * @addtogroup Trace * @{ */ enum { /** @brief (re)start the tracing now. Ignore older events */ TRACE_ITER_INIT = 0, /** @brief clobber all events in the trace buffer */ TRACE_ITER_CLEAN = 1 }; /** * @brief request with #MRQ_TRACE_ITER */ struct mrq_trace_iter_request { /** @brief TRACE_ITER_INIT or TRACE_ITER_CLEAN */ uint32_t cmd; } __ABI_PACKED; /** @} */ /* * 4. Enumerations */ /* * 4.1 CPU enumerations * * See <mach-t186/system-t186.h> * * 4.2 CPU Cluster enumerations * * See <mach-t186/system-t186.h> * * 4.3 System low power state enumerations * * See <mach-t186/system-t186.h> */ /* * 4.4 Clock enumerations * * For clock enumerations, see <mach-t186/clk-t186.h> */ /* * 4.5 Reset enumerations * * For reset enumerations, see <mach-t186/reset-t186.h> */ /* * 4.6 Thermal sensor enumerations * * For thermal sensor enumerations, see <mach-t186/thermal-t186.h> */ /** * @defgroup Error_Codes * Negative values for mrq_response::err generally indicate some * error. The ABI defines the following error codes. Negating these * defines is an exercise left to the user. * @{ */ /** @brief No such file or directory */ #define BPMP_ENOENT 2 /** @brief No MRQ handler */ #define BPMP_ENOHANDLER 3 /** @brief I/O error */ #define BPMP_EIO 5 /** @brief Bad sub-MRQ command */ #define BPMP_EBADCMD 6 /** @brief Not enough memory */ #define BPMP_ENOMEM 12 /** @brief Permission denied */ #define BPMP_EACCES 13 /** @brief Bad address */ #define BPMP_EFAULT 14 /** @brief No such device */ #define BPMP_ENODEV 19 /** @brief Argument is a directory */ #define BPMP_EISDIR 21 /** @brief Invalid argument */ #define BPMP_EINVAL 22 /** @brief Timeout during operation */ #define BPMP_ETIMEDOUT 23 /** @brief Out of range */ #define BPMP_ERANGE 34 /** @} */ /** @} */ #endif
<reponame>jakewooker/WAVideoBox // // WAAVSEComposition.h // YCH // // Created by 黄锐灏 on 2017/9/26. // Copyright © 2017 黄锐灏. All rights reserved. // #import <Foundation/Foundation.h> #import <AVFoundation/AVFoundation.h> NS_ASSUME_NONNULL_BEGIN @interface WAAVSEComposition : NSObject /** 视频轨道信息 */ @property (nonatomic , strong) AVMutableComposition *mutableComposition; /** 视频操作指令 */ @property (nonatomic , strong) AVMutableVideoComposition *mutableVideoComposition; /** 音频操作指令 */ @property (nonatomic , strong) AVMutableAudioMix *mutableAudioMix; /** 视频时长(变速/裁剪后) PS:后续版本会为每条轨道单独设置duration */ @property (nonatomic , assign) CMTime duration; /** 视频分辩率 */ @property (nonatomic , copy) NSString *presetName; /** 视频质量 */ @property (nonatomic , assign) NSInteger videoQuality; /** 输出文件格式 */ @property (nonatomic , copy) AVFileType fileType; /** 视频操作参数数组 */ @property (nonatomic , strong) NSMutableArray <AVMutableVideoCompositionInstruction *> *instructions; /** 音频操作参数数组 */ @property (nonatomic , strong) NSMutableArray <AVMutableAudioMixInputParameters *> *audioMixParams; /** 画布父容器 */ @property (nonatomic , strong) CALayer *parentLayer; /** 原视频容器 */ @property (nonatomic , strong) CALayer *videoLayer; @property (nonatomic , assign) CGSize lastInstructionSize; @end NS_ASSUME_NONNULL_END
<gh_stars>1-10 const unsigned char Level2Collision[1024]={ 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x02,0x02,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x02,0x02,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x02,0x02,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x02,0x04,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x02,0x02,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x02,0x01,0x01,0x03,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x02,0x03,0x01,0x03,0x03,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x02,0x02,0x02,0x02,0x01,0x01,0x01,0x02,0x02, 0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x01,0x01,0x03,0x02,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x02,0x02,0x02,0x02,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
/****************************************************************************** * qLibc * * Copyright (c) 2010-2015 <NAME>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ /** * @file qencode.c Encoding/decoding APIs. */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include "qinternal.h" #include "utilities/qstring.h" #include "utilities/qencode.h" /** * Parse URL encoded query string * * @param tbl a pointer of qlisttbl_t container. NULL can be used to * create new table. * @param query URL encoded string. * @param equalchar separater of key, value pair. * @param sepchar separater of line. * @param count if count is not NULL, a number of parsed entries are stored. * * @return qlisttbl container pointer, otherwise returns NULL. * * @code * cont char query = "category=love&str=%C5%A5%B5%F0%C4%DA%B4%F5&sort=asc"; * qlisttbl_t *tbl = qparse_queries(NULL, req->pszQueryString, '=', '&', NULL); * printf("category = %s\n", tbl->get_str(tbl, "category", false)); * printf("str = %s\n", tbl->get_str(tbl, "str", false)); * printf("sort = %s\n", tbl->get_str(tbl, "sort", false)); * tbl->free(tbl); * @endcode */ qlisttbl_t *qparse_queries(qlisttbl_t *tbl, const char *query, char equalchar, char sepchar, int *count) { if (tbl == NULL && (tbl = qlisttbl(0)) == NULL) { return NULL; } if (query == NULL) { return tbl; } int cnt = 0; char *newquery = strdup(query); while (newquery && *newquery) { char *value = _q_makeword(newquery, sepchar); char *name = qstrtrim(_q_makeword(value, equalchar)); qurl_decode(name); qurl_decode(value); if (tbl->putstr(tbl, name, value) == true) { cnt++; } free(name); free(value); } if (count != NULL) { *count = cnt; } free(newquery); return tbl; } /** * Encode data using URL encoding(Percent encoding) algorithm. * * @param bin a pointer of input data. * @param size the length of input data. * * @return a malloced string pointer of URL encoded string in case of * successful, otherwise returns NULL * * @code * const char *text = "hello 'qLibc' world"; * * char *encstr = qurl_encode(text, strlen(text)); * if(encstr == NULL) return -1; * * printf("Original: %s\n", text); * printf("Encoded : %s\n", encstr); * * size_t decsize = qurl_decode(encstr); * * printf("Decoded : %s (%zu bytes)\n", encstr, decsize); * free(encstr); * * --[output]-- * Original: hello 'qLibc' world * Encoded: hello%20%27qLibc%27%20world * Decoded: hello 'qLibc' world (19 bytes) * @endcode */ char *qurl_encode(const void *bin, size_t size) { const char URLCHARTBL[16*16] = { 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // 00-0F 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // 10-1F 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,'-','.','/', // 20-2F '0','1','2','3','4','5','6','7','8','9',':', 0 , 0 , 0 , 0 , 0 , // 30-3F '@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', // 40-4F 'P','Q','R','S','T','U','V','W','X','Y','Z', 0 ,'\\',0 , 0 ,'_', // 50-5F 00 ,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', // 60-6f 'p','q','r','s','t','u','v','w','x','y','z', 0 , 0 , 0 , 0 , 0 , // 70-7F 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // 80-8F 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // 90-9F 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // A0-AF 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // B0-BF 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // C0-CF 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // D0-DF 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // E0-EF 00 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 // F0-FF }; // 0 means must be encoded. if (bin == NULL) return NULL; if (size == 0) return strdup(""); // malloc buffer char *pszEncStr = (char *) malloc((size * 3) + 1); if (pszEncStr == NULL) return NULL; char *pszEncPt = pszEncStr; char *pBinPt = (char *) bin; const char *pBinEnd = (bin + size - 1); for (; pBinPt <= pBinEnd; pBinPt++) { unsigned char c = *pBinPt; if (URLCHARTBL[c] != 0) { *pszEncPt++ = *pBinPt; } else { unsigned char cUpper4 = (c >> 4); unsigned char cLower4 = (c & 0x0F); *pszEncPt++ = '%'; *pszEncPt++ = (cUpper4 < 0x0A) ? (cUpper4 + '0') : ((cUpper4 - 0x0A) + 'a'); *pszEncPt++ = (cLower4 < 0x0A) ? (cLower4 + '0') : ((cLower4 - 0x0A) + 'a'); } } *pszEncPt = '\0'; return pszEncStr; } /** * Decode URL encoded string. * * @param str a pointer of URL encoded string. * * @return the length of bytes stored in the str memory in case of successful, * otherwise returns NULL * * @note * This modify str directly. And the 'str' is always terminated by NULL * character. */ size_t qurl_decode(char *str) { if (str == NULL) { return 0; } char *pEncPt, *pBinPt = str; for (pEncPt = str; *pEncPt != '\0'; pEncPt++) { switch (*pEncPt) { case '+': { *pBinPt++ = ' '; break; } case '%': { *pBinPt++ = _q_x2c(*(pEncPt + 1), *(pEncPt + 2)); pEncPt += 2; break; } default: { *pBinPt++ = *pEncPt; break; } } } *pBinPt = '\0'; return (pBinPt - str); } /** * Encode data using BASE64 algorithm. * * @param bin a pointer of input data. * @param size the length of input data. * * @return a malloced string pointer of BASE64 encoded string in case of * successful, otherwise returns NULL * * @code * const char *text = "hello world"; * * char *encstr = qbase64_encode(text, strlen(text)); * if(encstr == NULL) return -1; * * printf("Original: %s\n", text); * printf("Encoded : %s\n", encstr); * * size_t decsize = qbase64_decode(encstr); * * printf("Decoded : %s (%zu bytes)\n", encstr, decsize); * free(encstr); * * --[output]-- * Original: hello world * Encoded: aGVsbG8gd29ybGQ= * Decoded: hello world (11 bytes) * @endcode */ char *qbase64_encode(const void *bin, size_t size) { const char B64CHARTBL[64] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', // 00-0F 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', // 10-1F 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', // 20-2F 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' // 30-3F }; if (size == 0) { return strdup(""); } // malloc for encoded string char *pszB64 = (char *) malloc( 4 * ((size / 3) + ((size % 3 == 0) ? 0 : 1)) + 1); if (pszB64 == NULL) { return NULL; } char *pszB64Pt = pszB64; unsigned char *pBinPt, *pBinEnd = (unsigned char *) (bin + size - 1); unsigned char szIn[3] = { 0, 0, 0 }; int nOffset; for (pBinPt = (unsigned char *) bin, nOffset = 0; pBinPt <= pBinEnd; pBinPt++, nOffset++) { int nIdxOfThree = nOffset % 3; szIn[nIdxOfThree] = *pBinPt; if (nIdxOfThree < 2 && pBinPt < pBinEnd) continue; *pszB64Pt++ = B64CHARTBL[((szIn[0] & 0xFC) >> 2)]; *pszB64Pt++ = B64CHARTBL[(((szIn[0] & 0x03) << 4) | ((szIn[1] & 0xF0) >> 4))]; *pszB64Pt++ = (nIdxOfThree >= 1) ? B64CHARTBL[(((szIn[1] & 0x0F) << 2) | ((szIn[2] & 0xC0) >> 6))] : '='; *pszB64Pt++ = (nIdxOfThree >= 2) ? B64CHARTBL[(szIn[2] & 0x3F)] : '='; memset((void *) szIn, 0, sizeof(szIn)); } *pszB64Pt = '\0'; return pszB64; } /** * Decode BASE64 encoded string. * * @param str a pointer of Base64 encoded string. * * @return the length of bytes stored in the str memory in case of successful, * otherwise returns NULL * * @note * This modify str directly. And the 'str' is always terminated by NULL * character. */ size_t qbase64_decode(char *str) { const char B64MAPTBL[16 * 16] = { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 00-0F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 10-1F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, // 20-2F 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, // 30-3F 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40-4F 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, // 50-5F 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60-6F 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, // 70-7F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 80-8F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 90-9F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // A0-AF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // B0-BF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // C0-CF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // D0-DF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // E0-EF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 // F0-FF }; char *pEncPt, *pBinPt = str; int nIdxOfFour = 0; char cLastByte = 0; for (pEncPt = str; *pEncPt != '\0'; pEncPt++) { char cByte = B64MAPTBL[(unsigned char) (*pEncPt)]; if (cByte == 64) continue; if (nIdxOfFour == 0) { nIdxOfFour++; } else if (nIdxOfFour == 1) { // 00876543 0021???? //*pBinPt++ = ( ((cLastByte << 2) & 0xFC) | ((cByte >> 4) & 0x03) ); *pBinPt++ = ((cLastByte << 2) | (cByte >> 4)); nIdxOfFour++; } else if (nIdxOfFour == 2) { // 00??8765 004321?? //*pBinPt++ = ( ((cLastByte << 4) & 0xF0) | ((cByte >> 2) & 0x0F) ); *pBinPt++ = ((cLastByte << 4) | (cByte >> 2)); nIdxOfFour++; } else { // 00????87 00654321 //*pBinPt++ = ( ((cLastByte << 6) & 0xC0) | (cByte & 0x3F) ); *pBinPt++ = ((cLastByte << 6) | cByte); nIdxOfFour = 0; } cLastByte = cByte; } *pBinPt = '\0'; return (pBinPt - str); } /** * Encode data to Hexadecimal digit format. * * @param bin a pointer of input data. * @param size the length of input data. * * @return a malloced string pointer of Hexadecimal encoded string in case of * successful, otherwise returns NULL * * @code * const char *text = "hello world"; * * char *encstr = qhex_encode(text, strlen(text)); * if(encstr == NULL) return -1; * * printf("Original: %s\n", text); * printf("Encoded : %s\n", encstr); * * size_t decsize = qhex_decode(encstr); * * printf("Decoded : %s (%zu bytes)\n", encstr, decsize); * free(encstr); * * return 0; * * --[output]-- * Original: hello world * Encoded : 68656c6c6f20776f726c64 * Decoded : hello world (11 bytes) * @endcode */ char *qhex_encode(const void *bin, size_t size) { const char HEXCHARTBL[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' }; char *pHexStr = (char *) malloc(sizeof(char) * ((size * 2) + 1)); if (pHexStr == NULL) return NULL; unsigned char *pSrc = (unsigned char *) bin; char *pHexPt = pHexStr; int i; for (i = 0; i < size; i++) { *pHexPt++ = HEXCHARTBL[(pSrc[i] >> 4)]; *pHexPt++ = HEXCHARTBL[(pSrc[i] & 0x0F)]; } *pHexPt = '\0'; return pHexStr; } /** * Decode Hexadecimal encoded data. * * @param str a pointer of Hexadecimal encoded string. * * @return the length of bytes stored in the str memory in case of successful, * otherwise returns NULL * * @note * This modify str directly. And the 'str' is always terminated by NULL * character. */ size_t qhex_decode(char *str) { const char HEXMAPTBL[16*16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00-0F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 10-1F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20-2F 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // 30-3F 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40-4F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 50-5F 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60-6f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 70-7F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80-8F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 90-9F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A0-AF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B0-BF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C0-CF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D0-DF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E0-EF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F0-FF }; char *pEncPt, *pBinPt = str; for (pEncPt = str; *pEncPt != '\0'; pEncPt += 2) { *pBinPt++ = (HEXMAPTBL[(unsigned char) (*pEncPt)] << 4) + HEXMAPTBL[(unsigned char) (*(pEncPt + 1))]; } *pBinPt = '\0'; return (pBinPt - str); }
<reponame>i5cP7i/gba-sprite-engine //{{BLOCK(GizaPlainsMap) //====================================================================== // // GizaPlainsMap, 512x256@4, // + palette 16 entries, not compressed // + 261 tiles (t|f|p reduced) not compressed // + regular map (flat), not compressed, 64x32 // Total size: 32 + 8352 + 4096 = 12480 // // Time-stamp: 2021-12-12, 23:08:18 // Exported by Cearn's GBA Image Transmogrifier, v0.8.17 // ( http://www.coranac.com/projects/#grit ) // //====================================================================== #ifndef GRIT_GIZAPLAINSMAP_H #define GRIT_GIZAPLAINSMAP_H #define GizaPlainsMapTilesLen 8352 extern const unsigned int GizaPlainsMapTiles[2088]; #define GizaPlainsMapMapLen 4096 extern const unsigned short GizaPlainsMapMap[2048]; #define GizaPlainsMapPalLen 32 extern const unsigned short GizaPlainsMapPal[16]; #endif // GRIT_GIZAPLAINSMAP_H //}}BLOCK(GizaPlainsMap)
<reponame>idraper/Physics-Project<gh_stars>1-10 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ /* * project_hindi * Copyright (C) <NAME> 2010 <<EMAIL>> * * project_hindi is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * project_hindi is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _WAV_FILE_H_ #define _WAV_FILE_H_ #include <iostream> #include <iomanip> #include <cmath> #ifndef CONST84 #define CONST84 /* ----- not CONST84 ----- */ #endif /* ----- not CONST84 ----- */ /* * ===================================================================================== * Class: WavFile * Description: This file is responsible for loading wav file and reading * its content. Wav file data will be loaded into some dat file to be * processed later. * ===================================================================================== */ class WavFile { private: bool isExist; bool isOpen; bool isClose; char* fileName; public: /* ==================== LIFECYCLE ======================================= */ WavFile (); /* constructor */ //WavFile ( char* fileName ); /* copy constructor */ ~WavFile (); /* destructor */ /* ==================== ACCESSORS ======================================= */ /* * === FUNCTION ====================================================================== * Name: getNumSamples * Description: Returns number of samples in file. * ===================================================================================== */ long int getNumSamples(); /* * === FUNCTION ====================================================================== * Name: getNumChannels * Description: Returns no of channels (1 == mono, 2 == stereo ) * ===================================================================================== */ int getNumChannels(); /* * === FUNCTION ====================================================================== * Name: getBitsPerSample * Description: Report the number of bits in each samples. * ===================================================================================== */ int getBitsPerSample(); /* * === FUNCTION ====================================================================== * Name: getSampleRateHz * Description: return sample rate in Hz * ===================================================================================== */ double getSampleRateHz(); /* * === FUNCTION ====================================================================== * Name: displayInformation * Description: get all the information about file. * ===================================================================================== */ int displayInformation(char* fileName); /* ==================== MUTATORS ======================================= */ /* ==================== OPERATORS ======================================= */ /* * === FUNCTION ====================================================================== * Name: readCurrentInput() * Description: Routine for reading one sample from a previously * loaded wave file. Retuens current sample as a double. * ===================================================================================== */ double readCurrentInput(); /* * === FUNCTION ====================================================================== * Name: ifMoreDataAvailable * Description: Check if file is over. * ===================================================================================== */ int ifMoreDataAvailable(); //const WavFile& operator = ( const WavFile &other ); /* assignment operator */ /* ==================== DATA MEMBERS ======================================= */ protected: double fs_hz; int bitsPerSample; int nChannel; double* gWavDataIn; int numInSamples; long int maxInSamples; /* put friends here if he has any else, leave him all alone you crazy objects */ public: /* * === FUNCTION ====================================================================== * Name: openWavFile * Description: This will open the wav file for further processing. * ===================================================================================== */ int openWavFile(char* fileName); /* * === FUNCTION ====================================================================== * Name: loadWavData * Description: This should load the content of wav file in to a * binary file for further processing. * ===================================================================================== */ int writeDataToFile( char* outfile ); /* *-------------------------------------------------------------------------------------- * Class: WavFile * Method: closeWavFile * Description: This should close the file after processing. *-------------------------------------------------------------------------------------- */ int closeWavFile(FILE* pFile); }; /* ----- end of class WavFile ----- */ #endif // _WAV_FILE_H_
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef STORAGE_BROWSER_TEST_FAKE_BLOB_DATA_HANDLE_H_ #define STORAGE_BROWSER_TEST_FAKE_BLOB_DATA_HANDLE_H_ #include <string> #include "base/callback.h" #include "storage/browser/blob/blob_data_item.h" namespace storage { // All callbacks in the FakeBlobDataHandle are called synchronously. class FakeBlobDataHandle : public BlobDataItem::DataHandle { public: FakeBlobDataHandle(std::string body_data, std::string side_data); // BlobDataItem::DataHandle implementation. uint64_t GetSize() const override; void Read(mojo::ScopedDataPipeProducerHandle producer, uint64_t src_offset, uint64_t bytes_to_read, base::OnceCallback<void(int)> callback) override; uint64_t GetSideDataSize() const override; void ReadSideData( base::OnceCallback<void(int, mojo_base::BigBuffer)> callback) override; void PrintTo(::std::ostream* os) const override {} const char* BytesReadHistogramLabel() const override; private: ~FakeBlobDataHandle() override; const std::string body_data_; const std::string side_data_; }; } // namespace storage #endif // STORAGE_BROWSER_TEST_FAKE_BLOB_DATA_HANDLE_H_
<reponame>telecommai/ios // // SystemShareImageView.h // Zone // // Created by 王胜利 on 2018/5/30. // Copyright © 2018年 pansoft. All rights reserved. // #import <UIKit/UIKit.h> @interface SystemShareImageView : UIView - (void)viewWithImageUrls:(NSArray *)imageUrls; - (void)viewWithImagesFile:(NSArray *)imageFiles; @end
<reponame>DICE-UNC/iRODS-FUSE-Mod<gh_stars>1-10 /*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* icCollUtil.c */ #include "icCollUtil.h" #include "icutils.h" int icCollOps (char* collname, char* operation, char* oplist, bytesBuf_t* mybuf, int status) { rsComm_t* rsComm; genQueryInp_t gqin; genQueryOut_t* gqout=NULL; char condStr[MAX_NAME_LEN]; char tmpstr[MAX_NAME_LEN]; /* init stuff */ memset (&gqin, 0, sizeof(genQueryInp_t)); gqin.maxRows = MAX_SQL_ROWS; gqout = (genQueryOut_t*) malloc (sizeof (genQueryOut_t)); memset (gqout, 0, sizeof (genQueryOut_t)); /* Generate a query - we only want subcollection data objects */ addInxIval (&gqin.selectInp, COL_COLL_NAME, 1); addInxIval (&gqin.selectInp, COL_COLL_ID, 1); genAllInCollQCond (collname, condStr); addInxVal (&gqin.sqlCondInp, COL_COLL_NAME, condStr); /* Determine which data we want to receive - ownerstuff, ACL stuff or AVU stuff */ if (!(strcmp(operation,"owner"))) { addInxIval (&gqin.selectInp, COL_COLL_OWNER_NAME, 1); } else if (!(strcmp(operation, "AVU"))) { addInxIval (&gqin.selectInp, COL_META_COLL_ATTR_NAME, 1); addInxIval (&gqin.selectInp, COL_META_COLL_ATTR_VALUE, 1); addInxIval (&gqin.selectInp, COL_META_COLL_ATTR_UNITS, 1); } else if (!(strcmp(operation, "ACL"))) { addInxIval (&gqin.selectInp, COL_COLL_ACCESS_TYPE, 1); addInxIval (&gqin.selectInp, COL_COLL_ACCESS_NAME, 1); } else { rodsLog (LOG_ERROR, "icCollOps: ERROR"); return (-1); } /* This is effectively a recursive query because of the condStr */ status = rsGenQuery (rsComm, &gqin, &gqout); fprintf (stderr, "status=%d\n", status); if ((status==CAT_NO_ROWS_FOUND) || (status < 0)) { snprintf (tmpstr, MAX_NAME_LEN, "No rows found matching input criteria.\n"); appendToByteBuf (mybuf, tmpstr); /* assume at this point we have valid data for all three possible query types */ } else if (!(strcmp(operation,"owner"))) { // process owners query results verifyCollOwners (gqout, oplist, mybuf); } else if (!(strcmp(operation, "AVU"))) { // process AVU query results //verifyCollAVU (gqout, oplist, mybuf); } else if (!(strcmp(operation, "ACL"))) { // process ACL query results //verifyCollACL (gqout, oplist, mybuf); } printGenQueryOut(stderr, NULL, NULL, gqout); return (status); } /* the following functions are wrappers for icCollOps function */ int msiVerifySubCollOwner (msParam_t* collinp, msParam_t* ownerinp, msParam_t *bufout, msParam_t* statout) { bytesBuf_t* mybuf=NULL; char* collname; char* ownerlist; int status; mybuf = (bytesBuf_t *) malloc (sizeof (bytesBuf_t)); memset (mybuf, 0, sizeof (bytesBuf_t)); collname = strdup ((char*)collinp->inOutStruct); ownerlist = strdup ((char*)ownerinp->inOutStruct); status = icCollOps (collname, "owner", ownerlist, mybuf, status); fillStrInMsParam (bufout, (char*)mybuf->buf); fillIntInMsParam (statout, status); return (status); } int msiVerifySubCollAVU (msParam_t* collinp, msParam_t* avunameinp, msParam_t* avuvalueinp, msParam_t* avuattrinp, msParam_t *bufout, msParam_t* statout) { rsComm_t* rsComm; genQueryInp_t gqin; genQueryOut_t* gqout=NULL; char condStr[MAX_NAME_LEN]; char tmpstr[MAX_NAME_LEN]; bytesBuf_t* mybuf=NULL; char* collname; char* myavuname; char* myavuvalue; char* myavuattr;; int status; /* init stuff */ memset (&gqin, 0, sizeof(genQueryInp_t)); gqin.maxRows = MAX_SQL_ROWS; gqout = (genQueryOut_t*) malloc (sizeof (genQueryOut_t)); memset (gqout, 0, sizeof (genQueryOut_t)); mybuf = (bytesBuf_t *) malloc (sizeof (bytesBuf_t)); memset (mybuf, 0, sizeof (bytesBuf_t)); collname = strdup ((char*)collinp->inOutStruct); myavuname = strdup ((char*)avunameinp->inOutStruct); myavuvalue = strdup ((char*)avuvalueinp->inOutStruct); myavuattr = strdup ((char*)avuattrinp->inOutStruct); /* Generate a query - we only want subcollection data objects */ addInxIval (&gqin.selectInp, COL_COLL_NAME, 1); addInxIval (&gqin.selectInp, COL_COLL_ID, 1); genAllInCollQCond (collname, condStr); addInxVal (&gqin.sqlCondInp, COL_COLL_NAME, condStr); /* get the AVU fields */ addInxIval (&gqin.selectInp, COL_META_COLL_ATTR_NAME, 1); addInxIval (&gqin.selectInp, COL_META_COLL_ATTR_VALUE, 1); addInxIval (&gqin.selectInp, COL_META_COLL_ATTR_UNITS, 1); /* This is effectively a recursive query because of the condStr */ status = rsGenQuery (rsComm, &gqin, &gqout); fprintf (stderr, "status=%d\n", status); if ((status==CAT_NO_ROWS_FOUND) || (status < 0)) { snprintf (tmpstr, MAX_NAME_LEN, "No rows found matching input criteria.\n"); appendToByteBuf (mybuf, tmpstr); } else verifyCollAVU (gqout, myavuname, myavuvalue, myavuattr, mybuf); fillStrInMsParam (bufout, (char*)mybuf->buf); fillIntInMsParam (statout, status); return (status); } int msiVerifySubCollACL (msParam_t* collinp, msParam_t* acltypeinp, msParam_t* aclnameinp, msParam_t *bufout, msParam_t* statout) { rsComm_t* rsComm; genQueryInp_t gqin; genQueryOut_t* gqout=NULL; bytesBuf_t* mybuf; char condStr[MAX_NAME_LEN]; char tmpstr[MAX_NAME_LEN]; char* collname; char* myaclname; char* myacltype; int status; /* init stuff */ memset (&gqin, 0, sizeof(genQueryInp_t)); gqin.maxRows = MAX_SQL_ROWS; gqout = (genQueryOut_t*) malloc (sizeof (genQueryOut_t)); memset (gqout, 0, sizeof (genQueryOut_t)); mybuf = (bytesBuf_t *) malloc (sizeof (bytesBuf_t)); memset (mybuf, 0, sizeof (bytesBuf_t)); collname = strdup ((char*)collinp->inOutStruct); myaclname = strdup ((char*)aclnameinp->inOutStruct); myacltype = strdup ((char*)acltypeinp->inOutStruct); /* Generate a query - we only want subcollection data objects */ addInxIval (&gqin.selectInp, COL_COLL_NAME, 1); addInxIval (&gqin.selectInp, COL_COLL_ID, 1); genAllInCollQCond (collname, condStr); addInxVal (&gqin.sqlCondInp, COL_COLL_NAME, condStr); /* Determine which data we want to receive - ownerstuff, ACL stuff or AVU stuff */ addInxIval (&gqin.selectInp, COL_COLL_ACCESS_TYPE, 1); addInxIval (&gqin.selectInp, COL_COLL_ACCESS_NAME, 1); /* This is effectively a recursive query because of the condStr */ status = rsGenQuery (rsComm, &gqin, &gqout); fprintf (stderr, "status=%d\n", status); if ((status==CAT_NO_ROWS_FOUND) || (status < 0)) { snprintf (tmpstr, MAX_NAME_LEN, "No rows found matching input criteria.\n"); appendToByteBuf (mybuf, tmpstr); } else verifyCollACL (gqout, myaclname, myacltype, mybuf); printGenQueryOut(stderr, NULL, NULL, gqout); fillStrInMsParam (bufout, (char*)mybuf->buf); fillIntInMsParam (statout, status); return (status); } int msiListColl (msParam_t* collectionname, msParam_t* buf, ruleExecInfo_t* rei) { rsComm_t* rsComm; sqlResult_t *collectionName; sqlResult_t *collectionID; bytesBuf_t* mybuf=NULL; genQueryInp_t gqin; genQueryOut_t* gqout=NULL; int i,status; char condStr[MAX_NAME_LEN]; char* collname; RE_TEST_MACRO (" Calling msiListColl") /* Sanity check */ if (rei == NULL || rei->rsComm == NULL) { rodsLog (LOG_ERROR, "msiListColl: input rei or rsComm is NULL"); return (SYS_INTERNAL_NULL_INPUT_ERR); } rsComm = rei->rsComm; /* need to turn parameter 1 into a collInp_t struct */ collname = strdup ((char*)collectionname->inOutStruct); /* init stuff */ memset (&gqin, 0, sizeof(genQueryInp_t)); gqin.maxRows = MAX_SQL_ROWS; gqout = (genQueryOut_t*) malloc (sizeof (genQueryOut_t)); memset (gqout, 0, sizeof (genQueryOut_t)); mybuf = (bytesBuf_t *) malloc (sizeof (bytesBuf_t)); memset (mybuf, 0, sizeof (bytesBuf_t)); /* Generate a query - we only want subcollection data objects */ addInxIval (&gqin.selectInp, COL_COLL_NAME, 1); addInxIval (&gqin.selectInp, COL_COLL_ID, 1); genAllInCollQCond (collname, condStr); addInxVal (&gqin.sqlCondInp, COL_COLL_NAME, condStr); /* This is effectively a recursive query */ status = rsGenQuery (rsComm, &gqin, &gqout); if (status < 0) { return (status); } else if (status != CAT_NO_ROWS_FOUND) { collectionName = getSqlResultByInx (gqout, COL_COLL_NAME); collectionID = getSqlResultByInx (gqout, COL_COLL_ID); for (i=1; i<gqout->rowCnt; i++) { char* subcoll; char tmpstr[MAX_NAME_LEN]; subcoll = &collectionName->value[collectionName->len*i]; sprintf (tmpstr, "%s\n", subcoll ); appendToByteBuf (mybuf, tmpstr); } } else { return (status); /* something bad happened */ } fillBufLenInMsParam (buf, mybuf->len, mybuf); return (rei->status); }
<reponame>ckamtsikis/cmssw #ifndef PARTICLEFILTRATIONDECISION_H_ #define PARTICLEFILTRATIONDECISION_H_ #include <string> #include <vector> #include "DataFormats/Common/interface/Ref.h" #include "DataFormats/Common/interface/RefProd.h" #include "DataFormats/Common/interface/RefVector.h" #include "DataFormats/Common/interface/RefToBase.h" namespace pftools { /** * @class ParticleFiltrationDecision * @brief Articulates the decision of the ParticleFilter in RecoParticleFlow/PFAnalyses. * * Despite its generic name, it is currently only suitable for testbeam analysis and * particle gun use. To be reworked for collisions. * * @author <NAME> * @since CMSSW 31X * @date Added July 2009 * */ class ParticleFiltrationDecision { public: ParticleFiltrationDecision(){}; virtual ~ParticleFiltrationDecision(){}; /* Bit field to contain user-defined vetos */ char vetosPassed_; /*User-defined string representing who made this */ std::string filtrationProvenance_; enum TestbeamParticle { PION, PROTON_KAON, PROTON, KAON, ELECTRON, MUON, NOISE, OTHER }; /* This event contains a clean... */ TestbeamParticle type_; }; //Usual framework & EDM incantations typedef std::vector<pftools::ParticleFiltrationDecision> ParticleFiltrationDecisionCollection; typedef edm::Ref<ParticleFiltrationDecisionCollection> ParticleFiltrationDecisionRef; typedef edm::RefProd<ParticleFiltrationDecisionCollection> ParticleFiltrationDecisionRefProd; typedef edm::RefVector<ParticleFiltrationDecisionCollection> ParticleFiltrationDecisionRefVector; typedef ParticleFiltrationDecisionRefVector::iterator particleFiltrationDecision_iterator; typedef edm::RefToBase<pftools::ParticleFiltrationDecision> ParticleFiltrationDecisionBaseRef; } // namespace pftools #endif /* PARTICLEFILTRATIONDECISION_H_ */
/* * Diff Match and Patch * * Copyright 2010 ge<EMAIL>. * http://code.google.com/p/google-diff-match-patch/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: <EMAIL> (<NAME>) * ObjC port: <EMAIL> (<NAME>) */ #ifndef _DIFFMATCHPATCHCFUTILITIES_H #define _DIFFMATCHPATCHCFUTILITIES_H CFStringRef diff_CFStringCreateFromUnichar(UniChar ch); CF_INLINE CFStringRef diff_CFStringCreateSubstring(CFStringRef text, CFIndex start_index, CFIndex length) { CFRange substringRange = { .length = length, .location = start_index, }; CFStringRef substring = CFStringCreateWithSubstring(kCFAllocatorDefault, text, substringRange); return substring; } CF_INLINE CFStringRef diff_CFStringCreateRightSubstring(CFStringRef text, CFIndex text_length, CFIndex new_length) { return diff_CFStringCreateSubstring(text, text_length - new_length, new_length); } CF_INLINE CFStringRef diff_CFStringCreateLeftSubstring(CFStringRef text, CFIndex new_length) { return diff_CFStringCreateSubstring(text, 0, new_length); } CF_INLINE CFStringRef diff_CFStringCreateSubstringWithStartIndex(CFStringRef text, CFIndex start_index) { return diff_CFStringCreateSubstring(text, start_index, (CFStringGetLength(text) - start_index)); } CF_INLINE CFStringRef diff_CFStringCreateJavaSubstring(CFStringRef s, CFIndex begin, CFIndex end) { return diff_CFStringCreateSubstring(s, begin, end - begin); } CFIndex diff_commonPrefix(CFStringRef text1, CFStringRef text2); CFIndex diff_commonSuffix(CFStringRef text1, CFStringRef text2); CFIndex diff_commonOverlap(CFStringRef text1, CFStringRef text2); CFArrayRef diff_halfMatchCreate(CFStringRef text1, CFStringRef text2, const float diffTimeout); CFArrayRef diff_halfMatchICreate(CFStringRef longtext, CFStringRef shorttext, CFIndex i); CFStringRef diff_linesToCharsMungeCFStringCreate(CFStringRef text, CFMutableArrayRef lineArray, CFMutableDictionaryRef lineHash); CFStringRef diff_tokensToCharsMungeCFStringCreate(CFStringRef text, CFMutableArrayRef tokenArray, CFMutableDictionaryRef tokenHash, CFOptionFlags tokenizerOptions); CFStringRef diff_wordsToCharsMungeCFStringCreate(CFStringRef text, CFMutableArrayRef tokenArray, CFMutableDictionaryRef tokenHash); CFStringRef diff_sentencesToCharsMungeCFStringCreate(CFStringRef text, CFMutableArrayRef tokenArray, CFMutableDictionaryRef tokenHash); CFStringRef diff_paragraphsToCharsMungeCFStringCreate(CFStringRef text, CFMutableArrayRef tokenArray, CFMutableDictionaryRef tokenHash); CFStringRef diff_lineBreakDelimiteredToCharsMungeCFStringCreate(CFStringRef text, CFMutableArrayRef tokenArray, CFMutableDictionaryRef tokenHash); CFStringRef diff_rangesToCharsMungeCFStringCreate(CFStringRef text, CFMutableArrayRef substringArray, CFMutableDictionaryRef substringHash, CFRange *ranges, size_t ranges_count); CFStringRef diff_charsToTokenCFStringCreate(CFStringRef charsString, CFArrayRef tokenArray); CFIndex diff_cleanupSemanticScore(CFStringRef one, CFStringRef two); CF_INLINE void diff_CFStringPrepareUniCharBuffer(CFStringRef string, const UniChar **string_chars, UniChar **string_buffer, CFRange string_range) { *string_chars = CFStringGetCharactersPtr(string); if (*string_chars == NULL) { // Fallback in case CFStringGetCharactersPtr() didn’t work. *string_buffer = malloc(string_range.length * sizeof(UniChar)); CFStringGetCharacters(string, string_range, *string_buffer); *string_chars = *string_buffer; } } #define CFIndexArrayLastValueIndex (CFArrayGetCount(theArray)-1) CF_INLINE CFIndex diff_CFArrayLastValueAsCFIndex(CFMutableArrayRef theArray) { return (CFIndex)CFArrayGetValueAtIndex(theArray, CFIndexArrayLastValueIndex); } CF_INLINE void diff_CFArrayRemoveLastValue(CFMutableArrayRef theArray) { CFArrayRemoveValueAtIndex(theArray, CFIndexArrayLastValueIndex); } #undef CFIndexArrayLastValueIndex #endif //ifndef _DIFFMATCHPATCHCFUTILITIES_H
<reponame>kapuusagi/RXMicroComputerDriver /** * @file ソフトウェアFIFOモジュール * @author */ #ifndef DRV_UART_FIFO_H_ #define DRV_UART_FIFO_H_ #include "../../rx_utils/rx_types.h" /** * FIFO */ struct fifo { uint8_t buf[512]; // Buffer uint16_t out; // Read out uint16_t in; // Write in }; void fifo_init(struct fifo *f); void fifo_destroy(struct fifo *f); void fifo_put(struct fifo *f, uint8_t d); uint8_t fifo_get(struct fifo *f); uint8_t fifo_has_data(const struct fifo *f); uint8_t fifo_has_blank(const struct fifo *f); uint16_t fifo_get_data_count(const struct fifo *f); #endif /* DRV_UART_FIFO_H_ */
#include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 30 typedef struct { int codigo; char nome[SIZE]; int idade; float altura; float peso; } Pessoa; void menu() { printf("1 - Cadastrar Usuario\n"); printf("2 - Mostrar Usuarios\n"); printf("0 - Exit Program\n"); } void cadastrarPessoas(Pessoa **ptr,int *qtd){ Pessoa aux; int qtdUsuarios = 0, i; /** * 1. ler para uma memoria aux -- Pessoa aux * 2. Alocar a Memoria * 3. Passar da Memoria aux para a memoria alocada **/ // Cadastrando a pessoa printf("Quantos usuarios deseja inserir: "); scanf("%d", &qtdUsuarios); // Condição de parada for (i = (*qtd); i < (*qtd) + qtdUsuarios; i++) { // 1. Passo printf("Digite o Codigo: "); scanf("%d", &aux.codigo); printf("Digite o nome: "); scanf(" %29[^\n]", aux.nome); printf("Digite a idade: "); scanf("%d", &aux.idade); printf("Digite a altura: "); scanf("%f", &aux.altura); printf("Digite o peso: "); scanf("%f", &aux.peso); // aux está preenchido // 2. Passo (*ptr) = (Pessoa *) realloc((*ptr), (i + 1) * sizeof(Pessoa)); if ((*ptr) == NULL) { printf("ERROR ALLOCATION!! :( \n"); exit(-1); } // 3. Passo // Ptr na posicao i recebe o valor de aux. (*ptr)[i] = aux; } (*qtd) = qtdUsuarios; } void mostrarPessoas(Pessoa *pessoas, int *qtd) { int i; for (i = 0; i < (*qtd); i++){ printf("Usuario %d\n", i+1); printf("Codigo: %d\n", pessoas[i].codigo); printf("Nome: %s\n", pessoas[i].nome); printf("Idade: %d\n", pessoas[i].idade); printf("Altura: %.2f\n", pessoas[i].altura); printf("Peso: %.2f\n\no", pessoas[i].peso); } } int main() { Pessoa *usuario = NULL; int qtd = 0, verif, posicao = 0; // Funcao que cadastra pessoas // Nessa ocasião estamos enviando um ponteiro, logo é preciso usar ponteiro duplo no parametro do { printf("--- Usuarios LTDA ---\n\n"); menu(); scanf("%d", &verif); switch (verif) { // Adicionar Usuario case 1: cadastrarPessoas(&usuario, &qtd); break; // Mostrar as pessoas cadastradas case 2: mostrarPessoas(usuario, &qtd); break; // Sair do programa case 0: exit(1); break; default: printf("ERROR!\n\n"); exit(-1); break; } } while (verif != 0); free(usuario); return 0; }
<filename>resources/usr/lib/root/etc/dictpch/gui/recorder/inc/LinkDef.h<gh_stars>0 // @(#)root/recorder:$Id$ /************************************************************************* * Copyright (C) 1995-2008, <NAME> and <NAME>. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifdef __CINT__ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ class TRecEvent; #pragma link C++ class TRecCmdEvent; #pragma link C++ class TRecExtraEvent; #pragma link C++ class TRecGuiEvent; #pragma link C++ class TRecWinPair; #pragma link C++ class TRecorder; #pragma link C++ class TRecorderState; #pragma link C++ class TRecorderReplaying; #pragma link C++ class TRecorderRecording; #pragma link C++ class TRecorderInactive; #pragma link C++ class TRecorderPaused; #pragma link C++ class TGRecorder; #endif
// Copyright (c) <NAME> <http://jonthysell.com> // Licensed under the MIT License. /** * @file Bitmaps.h * * This file provides a Bitmaps type which contains handles to every * picture resource used by the game, as well as functions for loading * and drawing those pictures. */ #ifndef BITMAPS_H #define BITMAPS_H #include "MacCommon.h" /** The number of numeric digit pictures. */ #define NumCharPictCount 10 /** The number of star pictures. */ #define StarPictCount 3 /** Struct containing handles to every picture resource. */ typedef struct sBitmaps { PicHandle TitlePict; PicHandle NumCharPicts[NumCharPictCount]; PicHandle ACharPict; PicHandle BCharPict; PicHandle SlashCharPict; PicHandle StarPicts[StarPictCount]; PicHandle PrevButtonPict; PicHandle NextButtonPict; PicHandle RetryButtonPict; PicHandle SoundOffPict; PicHandle SoundOnPict; PicHandle LightOffPict; PicHandle LightOnPict; } Bitmaps; /** * Initializes the Bitmaps by loading each picture resource. * @param pBitmaps The Bitmaps. */ void Bitmaps_Init(Bitmaps *pBitmaps); /** * Gets the rect bounding a number drawn using the (scaled) pictures. * @param pBitmaps The Bitmaps. * @param number The target number. * @param scale The scale factor. * @param pDestRect The Rect bounding the scaled picture. */ void Bitmaps_GetNumberRect(const Bitmaps *pBitmaps, const uint32_t number, const uint8_t scale, Rect *pDestRect); /** * Draws a number using the (scaled) pictures at the pen's location. * @param pBitmaps The Bitmaps. * @param number The target number. * @param scale The scale factor. */ void Bitmaps_DrawNumber(const Bitmaps *pBitmaps, const uint32_t number, const uint8_t scale); /** * Draws an "A" using the (scaled) picture at the pen's location. * @param pBitmaps The Bitmaps. * @param scale The scale factor. */ void Bitmaps_DrawAChar(const Bitmaps *pBitmaps, const uint8_t scale); /** * Draws a "B" using the (scaled) picture at the pen's location. * @param pBitmaps The Bitmaps. * @param scale The scale factor. */ void Bitmaps_DrawBChar(const Bitmaps *pBitmaps, const uint8_t scale); /** * Draws an "/" using the (scaled) picture at the pen's location. * @param pBitmaps The Bitmaps. * @param scale The scale factor. */ void Bitmaps_DrawSlashChar(const Bitmaps *pBitmaps, const uint8_t scale); /** * Gets the rect bounding stars drawn using the (scaled) pictures. * @param pBitmaps The Bitmaps. * @param maxStars The number of stars. * @param scale The scale factor. * @param pDestRect The Rect bounding the scaled picture. */ void Bitmaps_GetHalfStarsRect(const Bitmaps *pBitmaps, const uint8_t maxStars, const uint8_t scale, Rect *pDestRect); /** * Draws (partially) filled stars using the (scaled) pictures. * @param pBitmaps The Bitmaps. * @param halfStars The number of half-stars to fill. * @param maxStars The total number of stars. * @param scale The scale factor. */ void Bitmaps_DrawHalfStars(const Bitmaps *pBitmaps, const uint8_t halfStars, const uint8_t maxStars, const uint8_t scale); /** * Gets the rect bounding the sound icon using the (scaled) pictures. * @param pBitmaps The Bitmaps. * @param scale The scale factor. * @param pDestRect The Rect bounding the scaled picture. */ void Bitmaps_GetSoundRect(const Bitmaps *pBitmaps, const uint8_t scale, Rect *pDestRect); /** * Draws the sound icon using the (scaled) pictures. * @param pBitmaps The Bitmaps. * @param enabled Whether sound is enabled or not. * @param scale The scale factor. */ void Bitmaps_DrawSound(const Bitmaps *pBitmaps, const bool enabled, const uint8_t scale); #endif
/*============================================================================== | SOURCE: dir_watch.c | | AUTHOR: <NAME> | | DATE: Dec 3, 2018 | | INFO: Source file for threaded directory watch component of program. | Holds functions for setting up monitor watch on client specified | directory and exfiltrating any new files that are created in the | specified directory. ==============================================================================*/ #include "../include/dir_watch.h" #include "../include/server.h" #include <stdio.h> #include <string.h> #include <sys/inotify.h> #include <sys/select.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <arpa/inet.h> #include <errno.h> /*------------------------------------------------------------------------------ | FUNCTION: void *run_dir_watch(void *ptr) | *ptr - arguments for directory watch thread | | RETURN: void pointer | | AUTHOR: <NAME> | | MODIFIED: <NAME> | | DATE: Dec 3, 2018 | | INFO: Uses inotify to monitor a client specified directory on the | server. Monitors for CREATE events in directory. When a new file | is created it sends the file to client machine. | | Base code was taken from <NAME>'s directory watch notes | that contained code for a basic directory monitor. ------------------------------------------------------------------------------*/ void *run_dir_watch(void *ptr) { Dir_Watch_Args *dw_args = ptr; // get arguments fflush(stdout); int len, i, ret, fd, wd; static struct inotify_event *event; fd_set rfds; char buf[BUF_LEN]; // create inotify file descriptor fd = inotify_init(); if (fd < 0) perror ("inotify_init"); // start watching client specified directory wd = inotify_add_watch (fd, dw_args->dir, (uint32_t)IN_CREATE); if (wd < 0) perror ("inotify_add_watch"); FD_ZERO (&rfds); FD_SET (fd, &rfds); // monitor loop while(1) { ret = select (fd + 1, &rfds, NULL, NULL, NULL); len = read (fd, buf, BUF_LEN); i = 0; if (len < 0) { if (errno == EINTR) /* need to reissue system call */ perror ("read"); else perror ("read"); } else if (!len) /* BUF_LEN too small? */ { printf ("buffer too small!\n"); exit (1); } while (i < len) { event = (struct inotify_event *) &buf[i]; i += EVENT_SIZE + event->len; } if (ret < 0) perror ("select"); else if (FD_ISSET (fd, &rfds)) // CREATE event occured { char filepath[BUF_MED]; memset(filepath, '\0', sizeof(filepath)); strcpy(filepath, dw_args->dir); strcat(filepath, event->name); send_file_name(event->name, &(dw_args->srv_args)); send_file(filepath, 'd', &(dw_args->srv_args)); } } pthread_exit(NULL); } /*------------------------------------------------------------------------------ | FUNCTION: void send_file_name(char *name, Server_Args *srv_args) | *name - name of file to send to client | *srv_args - contains client IP to send to | | RETURN: void | | AUTHOR: <NAME> | | DATE: Dec 3, 2018 | | INFO: Sends the name of the file to the client so the client knows | what the new file is called. ------------------------------------------------------------------------------*/ void send_file_name(char *name, Server_Args *srv_args) { int delay; // random seed time_t t; srand((unsigned) time(&t)); // create socket int sd; if((sd = create_socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) == -1) pthread_exit(NULL); // iterate thru name char by char for(size_t i = 0; i < strlen(name); i++) { struct sockaddr_in sin; Packet pkt; // delay sending delay = rand() % srv_args->max_delay + srv_args->min_delay; sleep(delay); // forge IP and TCP forge_ip(&pkt, 'n', inet_addr(srv_args->my_ip), inet_addr(srv_args->host_ip)); forge_tcp(&pkt); // Encode char into urgent pointer pkt.tcp.urg_ptr = name[i]; // check sums pkt.ip.check = in_cksum((unsigned short *)&pkt.ip, sizeof(struct iphdr)); pkt.tcp.check = in_cksum((unsigned short *)&pkt.tcp, sizeof(struct tcphdr)); // check sums pkt.ip.check = in_cksum((unsigned short *)&pkt.ip, sizeof(struct iphdr)); pkt.tcp.check = in_cksum((unsigned short *)&pkt.tcp, sizeof(struct tcphdr)); // set sockaddr sin.sin_family = AF_INET; sin.sin_addr.s_addr = pkt.ip.daddr; sin.sin_port = pkt.tcp.source; // send packet if(sendto(sd, &pkt, sizeof(pkt), 0, (struct sockaddr *)&sin, sizeof(sin)) == -1) { printf("\nError sending data: %s\n\n", strerror(errno)); close(sd); pthread_exit(NULL); } } // send EOT struct sockaddr_in sin; Packet pkt; // delay sending delay = rand() % srv_args->max_delay + srv_args->min_delay; sleep(delay); // forge IP and TCP forge_ip(&pkt, 'n', inet_addr(srv_args->my_ip), inet_addr(srv_args->host_ip)); forge_tcp(&pkt); // Encode char into urgent pointer pkt.tcp.urg_ptr = '\0'; // check sums pkt.ip.check = in_cksum((unsigned short *)&pkt.ip, sizeof(struct iphdr)); pkt.tcp.check = in_cksum((unsigned short *)&pkt.tcp, sizeof(struct tcphdr)); // check sums pkt.ip.check = in_cksum((unsigned short *)&pkt.ip, sizeof(struct iphdr)); pkt.tcp.check = in_cksum((unsigned short *)&pkt.tcp, sizeof(struct tcphdr)); // set sockaddr sin.sin_family = AF_INET; sin.sin_addr.s_addr = pkt.ip.daddr; sin.sin_port = pkt.tcp.source; // send packet if(sendto(sd, &pkt, sizeof(pkt), 0, (struct sockaddr *)&sin, sizeof(sin)) == -1) { printf("\nError sending data: %s\n\n", strerror(errno)); close(sd); pthread_exit(NULL); } close(sd); }
<filename>media/base/audio_parameters.h // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BASE_AUDIO_PARAMETERS_H_ #define MEDIA_BASE_AUDIO_PARAMETERS_H_ #include <stdint.h> #include <string> #include <vector> #include "base/compiler_specific.h" #include "base/numerics/checked_math.h" #include "base/optional.h" #include "base/time/time.h" #include "build/build_config.h" #include "media/base/audio_bus.h" #include "media/base/audio_latency.h" #include "media/base/audio_point.h" #include "media/base/channel_layout.h" #include "media/base/media_shmem_export.h" #include "media/base/sample_format.h" namespace media { // Use a struct-in-struct approach to ensure that we can calculate the required // size as sizeof(Audio{Input,Output}BufferParameters) + #(bytes in audio // buffer) without using packing. Also align Audio{Input,Output}BufferParameters // instead of in Audio{Input,Output}Buffer to be able to calculate size like so. // Use a macro for the alignment value that's the same as // AudioBus::kChannelAlignment, since MSVC doesn't accept the latter to be used. #if defined(OS_WIN) #pragma warning(push) #pragma warning(disable : 4324) // Disable warning for added padding. #endif #define PARAMETERS_ALIGNMENT 16 static_assert(AudioBus::kChannelAlignment == PARAMETERS_ALIGNMENT, "Audio buffer parameters struct alignment not same as AudioBus"); // ****WARNING****: Do not change the field types or ordering of these fields // without checking that alignment is correct. The structs may be concurrently // accessed by both 32bit and 64bit process in shmem. http://crbug.com/781095. struct MEDIA_SHMEM_EXPORT ALIGNAS(PARAMETERS_ALIGNMENT) AudioInputBufferParameters { double volume; int64_t capture_time_us; // base::TimeTicks in microseconds. uint32_t size; uint32_t id; bool key_pressed; }; struct MEDIA_SHMEM_EXPORT ALIGNAS(PARAMETERS_ALIGNMENT) AudioOutputBufferParameters { int64_t delay_us; // base::TimeDelta in microseconds. int64_t delay_timestamp_us; // base::TimeTicks in microseconds. uint32_t frames_skipped; uint32_t bitstream_data_size; uint32_t bitstream_frames; }; #undef PARAMETERS_ALIGNMENT #if defined(OS_WIN) #pragma warning(pop) #endif static_assert(sizeof(AudioInputBufferParameters) % AudioBus::kChannelAlignment == 0, "AudioInputBufferParameters not aligned"); static_assert(sizeof(AudioOutputBufferParameters) % AudioBus::kChannelAlignment == 0, "AudioOutputBufferParameters not aligned"); struct MEDIA_SHMEM_EXPORT AudioInputBuffer { AudioInputBufferParameters params; int8_t audio[1]; }; struct MEDIA_SHMEM_EXPORT AudioOutputBuffer { AudioOutputBufferParameters params; int8_t audio[1]; }; struct MEDIA_SHMEM_EXPORT AudioRendererAlgorithmParameters { // The maximum size for the audio buffer. base::TimeDelta max_capacity; // The minimum size for the audio buffer. base::TimeDelta starting_capacity; // The minimum size for the audio buffer for encrypted streams. // Set this to be larger than |max_capacity| because the // performance of encrypted playback is always worse than clear playback, due // to decryption and potentially IPC overhead. For the context, see // https://crbug.com/403462, https://crbug.com/718161 and // https://crbug.com/879970. base::TimeDelta starting_capacity_for_encrypted; }; // These convenience function safely computes the size required for // |shared_memory_count| AudioInputBuffers, with enough memory for AudioBus // data, using |paremeters| (or alternatively |channels| and |frames|). The // functions not returning a CheckedNumeric will CHECK on overflow. MEDIA_SHMEM_EXPORT base::CheckedNumeric<uint32_t> ComputeAudioInputBufferSizeChecked(const AudioParameters& parameters, uint32_t audio_bus_count); MEDIA_SHMEM_EXPORT uint32_t ComputeAudioInputBufferSize(const AudioParameters& parameters, uint32_t audio_bus_count); MEDIA_SHMEM_EXPORT uint32_t ComputeAudioInputBufferSize(int channels, int frames, uint32_t audio_bus_count); // These convenience functions safely computes the size required for an // AudioOutputBuffer with enough memory for AudioBus data using |parameters| (or // alternatively |channels| and |frames|). The functions not returning a // CheckedNumeric will CHECK on overflow. MEDIA_SHMEM_EXPORT base::CheckedNumeric<uint32_t> ComputeAudioOutputBufferSizeChecked(const AudioParameters& parameters); MEDIA_SHMEM_EXPORT uint32_t ComputeAudioOutputBufferSize(const AudioParameters& parameters); MEDIA_SHMEM_EXPORT uint32_t ComputeAudioOutputBufferSize(int channels, int frames); class MEDIA_SHMEM_EXPORT AudioParameters { public: // TODO(miu): Rename this enum to something that correctly reflects its // semantics, such as "TransportScheme." enum Format { AUDIO_PCM_LINEAR = 0, // PCM is 'raw' amplitude samples. AUDIO_PCM_LOW_LATENCY, // Linear PCM, low latency requested. AUDIO_BITSTREAM_AC3, // Compressed AC3 bitstream. AUDIO_BITSTREAM_EAC3, // Compressed E-AC3 bitstream. AUDIO_FAKE, // Creates a fake AudioOutputStream object. AUDIO_FORMAT_LAST = AUDIO_FAKE, // Only used for validation of format. }; enum { // Telephone quality sample rate, mostly for speech-only audio. kTelephoneSampleRate = 8000, // CD sampling rate is 44.1 KHz or conveniently 2x2x3x3x5x5x7x7. kAudioCDSampleRate = 44100, }; enum { // The maxmium number of PCM frames can be decoded out of a compressed // audio frame, e.g. MP3, AAC, AC-3. kMaxFramesPerCompressedAudioBuffer = 4096, }; // Bitmasks to determine whether certain platform (typically hardware) audio // effects should be enabled. enum PlatformEffectsMask { NO_EFFECTS = 0x0, ECHO_CANCELLER = 1 << 0, DUCKING = 1 << 1, // Enables ducking if the OS supports it. KEYBOARD_MIC = 1 << 2, HOTWORD = 1 << 3, NOISE_SUPPRESSION = 1 << 4, AUTOMATIC_GAIN_CONTROL = 1 << 5, EXPERIMENTAL_ECHO_CANCELLER = 1 << 6, // Indicates an echo canceller is // available that should only // experimentally be enabled. MULTIZONE = 1 << 7, AUDIO_PREFETCH = 1 << 8, }; struct HardwareCapabilities { HardwareCapabilities(int min_frames_per_buffer, int max_frames_per_buffer) : min_frames_per_buffer(min_frames_per_buffer), max_frames_per_buffer(max_frames_per_buffer) {} HardwareCapabilities() : min_frames_per_buffer(0), max_frames_per_buffer(0) {} // Minimum and maximum buffer sizes supported by the audio hardware. Opening // a device with frames_per_buffer set to a value between min and max should // result in the audio hardware running close to this buffer size, values // above or below will be clamped to the min or max by the audio system. // Either value can be 0 and means that the min or max is not known. int min_frames_per_buffer; int max_frames_per_buffer; }; AudioParameters(); AudioParameters(Format format, ChannelLayout channel_layout, int sample_rate, int frames_per_buffer); AudioParameters(Format format, ChannelLayout channel_layout, int sample_rate, int frames_per_buffer, const HardwareCapabilities& hardware_capabilities); ~AudioParameters(); // Re-initializes all members except for |hardware_capabilities_|. void Reset(Format format, ChannelLayout channel_layout, int sample_rate, int frames_per_buffer); // Checks that all values are in the expected range. All limits are specified // in media::Limits. bool IsValid() const; // Returns a human-readable string describing |*this|. For debugging & test // output only. std::string AsHumanReadableString() const; // Returns size of audio buffer in bytes when using |fmt| for samples. int GetBytesPerBuffer(SampleFormat fmt) const; // Returns the number of bytes representing a frame of audio when using |fmt| // for samples. int GetBytesPerFrame(SampleFormat fmt) const; // Returns the number of microseconds per frame of audio. Intentionally // reported as a double to surface of partial microseconds per frame, which // is common for many sample rates. Failing to account for these nanoseconds // can lead to audio/video sync drift. double GetMicrosecondsPerFrame() const; // Returns the duration of this buffer as calculated from frames_per_buffer() // and sample_rate(). base::TimeDelta GetBufferDuration() const; // Comparison with other AudioParams. bool Equals(const AudioParameters& other) const; // Return true if |format_| is compressed bitstream. bool IsBitstreamFormat() const; void set_format(Format format) { format_ = format; } Format format() const { return format_; } // A setter for channel_layout_ is intentionally excluded. ChannelLayout channel_layout() const { return channel_layout_; } // The number of channels is usually computed from channel_layout_. Setting // this explicitly is only required with CHANNEL_LAYOUT_DISCRETE. void set_channels_for_discrete(int channels) { DCHECK(channel_layout_ == CHANNEL_LAYOUT_DISCRETE || channels == ChannelLayoutToChannelCount(channel_layout_)); channels_ = channels; } int channels() const { return channels_; } void set_sample_rate(int sample_rate) { sample_rate_ = sample_rate; } int sample_rate() const { return sample_rate_; } void set_frames_per_buffer(int frames_per_buffer) { frames_per_buffer_ = frames_per_buffer; } int frames_per_buffer() const { return frames_per_buffer_; } base::Optional<HardwareCapabilities> hardware_capabilities() const { return hardware_capabilities_; } void set_effects(int effects) { effects_ = effects; } int effects() const { return effects_; } void set_mic_positions(const std::vector<Point>& mic_positions) { mic_positions_ = mic_positions; } const std::vector<Point>& mic_positions() const { return mic_positions_; } void set_latency_tag(AudioLatency::LatencyType latency_tag) { latency_tag_ = latency_tag; } AudioLatency::LatencyType latency_tag() const { return latency_tag_; } AudioParameters(const AudioParameters&); AudioParameters& operator=(const AudioParameters&); // Creates reasonable dummy parameters in case no device is available. static AudioParameters UnavailableDeviceParams(); private: Format format_; // Format of the stream. ChannelLayout channel_layout_; // Order of surround sound channels. int channels_; // Number of channels. Value set based on // |channel_layout|. int sample_rate_; // Sampling frequency/rate. int frames_per_buffer_; // Number of frames in a buffer. int effects_; // Bitmask using PlatformEffectsMask. // Microphone positions using Cartesian coordinates: // x: the horizontal dimension, with positive to the right from the camera's // perspective. // y: the depth dimension, with positive forward from the camera's // perspective. // z: the vertical dimension, with positive upwards. // // Usually, the center of the microphone array will be treated as the origin // (often the position of the camera). // // An empty vector indicates unknown positions. std::vector<Point> mic_positions_; // Optional tag to pass latency info from renderer to browser. Set to // AudioLatency::LATENCY_COUNT by default, which means "not specified". AudioLatency::LatencyType latency_tag_; // Audio hardware specific parameters, these are treated as read-only and // changing them has no effect. base::Optional<HardwareCapabilities> hardware_capabilities_; }; // Comparison is useful when AudioParameters is used with std structures. inline bool operator<(const AudioParameters& a, const AudioParameters& b) { if (a.format() != b.format()) return a.format() < b.format(); if (a.channels() != b.channels()) return a.channels() < b.channels(); if (a.sample_rate() != b.sample_rate()) return a.sample_rate() < b.sample_rate(); return a.frames_per_buffer() < b.frames_per_buffer(); } } // namespace media #endif // MEDIA_BASE_AUDIO_PARAMETERS_H_
/* * Copyright 2016-2019 Netronome Systems, Inc. All rights reserved. * * @file app_mac_vlan_config_cmsg.h * @brief NIC application MAC+VLAN lookup cmsg table config * * SPDX-License-Identifier: BSD-2-Clause */ #ifndef _APP_MAC_VLAN_CONFIG_CMSG_H_ #define _APP_MAC_VLAN_CONFIG_CMSG_H_ /* *** NIC MAC+VLAN Table Configuration Settings. *** */ #define NIC_MAC_VLAN_TABLE__NUM_ENTRIES 0x60000 /* *** NIC MAC+VLAN table result types. *** */ #define NIC_MAC_VLAN_RES_TYPE_TO_HOST 0 #define NIC_MAC_VLAN_RES_TYPE_TO_WIRE 1 #define NIC_MAC_VLAN_RES_TYPE_LACP 2 /* *** NIC MAC+VLAN Data Structures. *** */ #define NIC_MAC_VLAN_KEY_SIZE_LW 2 #define MAP_CMSG_IN_WQ_SZ 4096 #define SRIOV_QUEUE 64 #define CMESG_DISPATCH_OK 1 #define CMESG_DISPATCH_FAIL 0xffffffff /** Lookup key for the MAC+VLAN table. */ #if defined(__NFP_LANG_MICROC) struct nic_mac_vlan_key { union { struct { unsigned int vlan_id : 12; /**< VLAN ID */ unsigned int __unused : 4; uint16_t mac_addr_hi; /**< Upper 2 bytes of MAC address */ uint32_t mac_addr_lo; /**< Lower 4 bytes of MAC address */ }; uint32_t __raw[NIC_MAC_VLAN_KEY_SIZE_LW]; }; }; #define NIC_MAC_VLAN_RESULT_SIZE_LW 16 uint32_t action_list[(NIC_MAC_VLAN_RESULT_SIZE_LW)]; #define NIC_MAC_VLAN_ENTRY_SIZE_LW \ (NIC_MAC_VLAN_KEY_SIZE_LW + NIC_MAC_VLAN_RESULT_SIZE_LW) /** Lookup entry for MAC+VLAN table. */ struct nic_mac_vlan_entry { union { struct { struct nic_mac_vlan_key key; uint32_t action_list[(NIC_MAC_VLAN_RESULT_SIZE_LW)]; }; uint32_t __raw[NIC_MAC_VLAN_ENTRY_SIZE_LW]; }; }; #define NIC_MAC_VLAN_CMSG_SIZE_LW \ (NIC_MAC_VLAN_KEY_SIZE_LW + 4) //check this /** Cmsg st MAC+VLAN Structure for table. */ struct nic_mac_vlan_cmsg { union { struct { uint32_t word0; /* CMSG_TYPE_MAP_xxx add, delete, lookup, getnext, getfirst */ uint32_t tid; uint32_t count; uint32_t flags; struct nic_mac_vlan_key key; }; uint32_t __raw[NIC_MAC_VLAN_CMSG_SIZE_LW]; }; }; /* CTM allocation credits */ __asm {.alloc_mem _pkt_buf_ctm_credits cls island 8} #define PKT_BUF_CTM_CREDITS_LINK \ (__cls struct ctm_pkt_credits *) _link_sym(_pkt_buf_ctm_credits) /* *** NIC MAC+VLAN Table Functions. *** */ /** * Add a MAC+VLAN entry to the NIC MAC+VLAN table. * * @param key Key for the entry to add * @param action_list Address of the SRIOV action list * @param operation Add/Del Entry */ int32_t nic_mac_vlan_entry_op_cmsg(__lmem struct nic_mac_vlan_key *key, __lmem uint32_t *action_list, const int operation); #endif #endif /* ndef _APP_MAC_VLAN_CONFIG_CMSG_H_ */
<filename>Anyline.framework/Headers/ALMotionDetector.h // // ALMotionDetector.h // Anyline // // Created by <NAME> on 25.08.16. // Copyright © 2016 9Yards GmbH. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreMotion/CoreMotion.h> @protocol ALMotionDetectorDelegate <NSObject> - (void)motionDetectorAboveThreshold; @end @interface ALMotionDetector : NSObject @property (nonatomic, assign) id <ALMotionDetectorDelegate> delegate; - (void)startListeningForMotion; - (void)stopListeningForMotion; - (instancetype)initWithThreshold:(CGFloat)threshold delegate:(id)delegate; @end
<reponame>emperwang/base-C<filename>Cplusplus/src/static/static_var.h // // Created by Sparks on 2021/8/20. // #ifndef CPLUSPLUS_STATIC_VAR_H #define CPLUSPLUS_STATIC_VAR_H #include <iostream> void test_static_variable_function(); void test_static_variable_class(); void test_static_class_scope(); void test_static_func_in_class(); #endif //CPLUSPLUS_STATIC_VAR_H
<filename>shill/dbus/chromeos_dbus_control.h // Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SHILL_DBUS_CHROMEOS_DBUS_CONTROL_H_ #define SHILL_DBUS_CHROMEOS_DBUS_CONTROL_H_ #include <memory> #include <string> #include <brillo/dbus/exported_object_manager.h> #include "shill/control_interface.h" namespace shill { class EventDispatcher; class Manager; class ChromeosDBusControl : public ControlInterface { public: explicit ChromeosDBusControl(EventDispatcher* dispatcher); ~ChromeosDBusControl() override; void RegisterManagerObject( Manager* manager, const base::Closure& registration_done_callback) override; std::unique_ptr<DeviceAdaptorInterface> CreateDeviceAdaptor( Device* device) override; std::unique_ptr<IPConfigAdaptorInterface> CreateIPConfigAdaptor( IPConfig* ipconfig) override; std::unique_ptr<ManagerAdaptorInterface> CreateManagerAdaptor( Manager* manager) override; std::unique_ptr<ProfileAdaptorInterface> CreateProfileAdaptor( Profile* profile) override; std::unique_ptr<RPCTaskAdaptorInterface> CreateRPCTaskAdaptor( RPCTask* task) override; std::unique_ptr<ServiceAdaptorInterface> CreateServiceAdaptor( Service* service) override; #ifndef DISABLE_VPN std::unique_ptr<ThirdPartyVpnAdaptorInterface> CreateThirdPartyVpnAdaptor( ThirdPartyVpnDriver* driver) override; #endif const std::string& NullRPCIdentifier() override; // The caller retains ownership of 'delegate'. It must not be deleted before // the proxy. std::unique_ptr<PowerManagerProxyInterface> CreatePowerManagerProxy( PowerManagerProxyDelegate* delegate, const base::Closure& service_appeared_callback, const base::Closure& service_vanished_callback) override; #if !defined(DISABLE_WIFI) || !defined(DISABLE_WIRED_8021X) std::unique_ptr<SupplicantProcessProxyInterface> CreateSupplicantProcessProxy( const base::Closure& service_appeared_callback, const base::Closure& service_vanished_callback) override; std::unique_ptr<SupplicantInterfaceProxyInterface> CreateSupplicantInterfaceProxy(SupplicantEventDelegateInterface* delegate, const std::string& object_path) override; std::unique_ptr<SupplicantNetworkProxyInterface> CreateSupplicantNetworkProxy( const std::string& object_path) override; #endif // DISABLE_WIFI || DISABLE_WIRED_8021X #if !defined(DISABLE_WIFI) // See comment in supplicant_bss_proxy.h, about bare pointer. std::unique_ptr<SupplicantBSSProxyInterface> CreateSupplicantBSSProxy( WiFiEndpoint* wifi_endpoint, const std::string& object_path) override; #endif // DISABLE_WIFI std::unique_ptr<UpstartProxyInterface> CreateUpstartProxy() override; std::unique_ptr<DHCPCDListenerInterface> CreateDHCPCDListener( DHCPProvider* provider) override; std::unique_ptr<DHCPProxyInterface> CreateDHCPProxy( const std::string& service) override; #if !defined(DISABLE_CELLULAR) std::unique_ptr<DBusPropertiesProxyInterface> CreateDBusPropertiesProxy( const std::string& path, const std::string& service) override; std::unique_ptr<DBusObjectManagerProxyInterface> CreateDBusObjectManagerProxy( const std::string& path, const std::string& service, const base::Closure& service_appeared_callback, const base::Closure& service_vanished_callback) override; std::unique_ptr<ModemManagerProxyInterface> CreateModemManagerProxy( ModemManagerClassic* manager, const std::string& path, const std::string& service, const base::Closure& service_appeared_callback, const base::Closure& service_vanished_callback) override; std::unique_ptr<ModemProxyInterface> CreateModemProxy( const std::string& path, const std::string& service) override; std::unique_ptr<ModemSimpleProxyInterface> CreateModemSimpleProxy( const std::string& path, const std::string& service) override; std::unique_ptr<ModemCdmaProxyInterface> CreateModemCdmaProxy( const std::string& path, const std::string& service) override; std::unique_ptr<ModemGsmCardProxyInterface> CreateModemGsmCardProxy( const std::string& path, const std::string& service) override; std::unique_ptr<ModemGsmNetworkProxyInterface> CreateModemGsmNetworkProxy( const std::string& path, const std::string& service) override; std::unique_ptr<ModemGobiProxyInterface> CreateModemGobiProxy( const std::string& path, const std::string& service) override; // Proxies for ModemManager1 interfaces std::unique_ptr<mm1::ModemLocationProxyInterface> CreateMM1ModemLocationProxy( const std::string& path, const std::string& service) override; std::unique_ptr<mm1::ModemModem3gppProxyInterface> CreateMM1ModemModem3gppProxy(const std::string& path, const std::string& service) override; std::unique_ptr<mm1::ModemModemCdmaProxyInterface> CreateMM1ModemModemCdmaProxy(const std::string& path, const std::string& service) override; std::unique_ptr<mm1::ModemProxyInterface> CreateMM1ModemProxy( const std::string& path, const std::string& service) override; std::unique_ptr<mm1::ModemSimpleProxyInterface> CreateMM1ModemSimpleProxy( const std::string& path, const std::string& service) override; std::unique_ptr<mm1::SimProxyInterface> CreateMM1SimProxy( const std::string& path, const std::string& service) override; #endif // DISABLE_CELLULAR #if !defined(DISABLE_WIMAX) std::unique_ptr<WiMaxDeviceProxyInterface> CreateWiMaxDeviceProxy( const std::string& path) override; std::unique_ptr<WiMaxManagerProxyInterface> CreateWiMaxManagerProxy( const base::Closure& service_appeared_callback, const base::Closure& service_vanished_callback) override; std::unique_ptr<WiMaxNetworkProxyInterface> CreateWiMaxNetworkProxy( const std::string& path) override; #endif // DISABLE_WIMAX private: void OnDBusServiceRegistered( const base::Callback<void(bool)>& completion_action, bool success); void TakeServiceOwnership(bool success); static const char kNullPath[]; // Use separate bus connection for adaptors and proxies. This allows the // proxy to receive all broadcast signal messages that it is interested in. // Refer to crbug.com/446837 for more info. scoped_refptr<dbus::Bus> adaptor_bus_; scoped_refptr<dbus::Bus> proxy_bus_; EventDispatcher* dispatcher_; std::string null_identifier_; base::Closure registration_done_callback_; }; } // namespace shill #endif // SHILL_DBUS_CHROMEOS_DBUS_CONTROL_H_
<reponame>afatom/core-program<gh_stars>0 #ifndef __SERVER_H__ #define __SERVER_H__ #include <sys/types.h> //setandbind function #include <sys/socket.h> //setandbind function #include <arpa/inet.h> #include <vector> #include "wtqueue.h" #include "nevent.h" #include <cstdint> typedef struct Arguments Arguments; class Server{ public: explicit Server(uint16_t port = 5000); ~Server(); void Run(); void Send(int clientSock, void* msg, size_t msgsize); WtQueue_t<Event_ShPointer>& GetQueue(); private: int m_master; std::vector<int> m_clients; WtQueue_t<Event_ShPointer> m_queue; struct sockaddr_in address; fd_set primarySet; fd_set tempSet; Server(const Server&); Server& operator= (const Server&); void swap(int* lhs, int* rhs); void SetSocketToNonBlockMode(const int& socket); void CloseClientSocket(size_t clientIndex); void SendToSocket(const int& socket, void* msg, size_t msgsize); void SetAndBind(struct sockaddr_in* address, socklen_t structSize); static void* ReadThread(void* args); void ReadAndSendOnAllSockets(Arguments* ptr); }; #endif //__MC_SERVER_H__
#include <stdio.h> #include <math.h> #include <stdlib.h> #include "export.h" #include "evilmath.h" IDL_LONG trace_fweight (int argc, void * argv[]) { IDL_LONG nx; IDL_LONG ny; float ** fimage; float ** invvar; float radius; IDL_LONG ncen; float * xcen; IDL_LONG * ycen; float * xerr; long iy; long icen; IDL_LONG retval = 1; /* Allocate pointers from IDL */ nx = *((IDL_LONG *)argv[0]); ny = *((IDL_LONG *)argv[1]); fimage = (float **)malloc(ny * sizeof(float *)); /* build pointers only */ invvar = (float **)malloc(ny * sizeof(float *)); /* build pointers only */ for (iy=0; iy < ny; iy++) { fimage[iy] = (float *)argv[2] + iy*nx; invvar[iy] = (float *)argv[3] + iy*nx; } radius = *((float *)argv[4]); ncen = *((IDL_LONG *)argv[5]); xcen = ((float *)argv[6]); ycen = ((IDL_LONG *)argv[7]); xerr = ((float *)argv[8]); /* Loop through each center value */ for (icen=0; icen < ncen; icen ++) { recenter_fweight(nx, fimage[ycen[icen]], invvar[ycen[icen]], radius, xcen[icen], &xcen[icen], &xerr[icen]); } /* Free temporary memory */ free(fimage); free(invvar); return retval; }
// Copyright (c) 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_STYLE_SELF_ALIGNMENT_DATA_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_STYLE_SELF_ALIGNMENT_DATA_H_ #include "third_party/blink/renderer/core/style/computed_style_constants.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" namespace blink { class StyleSelfAlignmentData { DISALLOW_NEW(); public: // Style data for Self-Aligment and Default-Alignment properties: align-{self, // items}, justify-{self, items}. // [ <self-position> && <overflow-position>? ] | [ legacy && [ left | right | // center ] ] StyleSelfAlignmentData( ItemPosition position, OverflowAlignment overflow, ItemPositionType position_type = ItemPositionType::kNonLegacy) : position_(static_cast<unsigned>(position)), position_type_(static_cast<unsigned>(position_type)), overflow_(static_cast<unsigned>(overflow)) {} void SetPosition(ItemPosition position) { position_ = static_cast<unsigned>(position); } void SetPositionType(ItemPositionType position_type) { position_type_ = static_cast<unsigned>(position_type); } void SetOverflow(OverflowAlignment overflow) { overflow_ = static_cast<unsigned>(overflow); } ItemPosition GetPosition() const { return static_cast<ItemPosition>(position_); } ItemPositionType PositionType() const { return static_cast<ItemPositionType>(position_type_); } OverflowAlignment Overflow() const { return static_cast<OverflowAlignment>(overflow_); } bool operator==(const StyleSelfAlignmentData& o) const { return position_ == o.position_ && position_type_ == o.position_type_ && overflow_ == o.overflow_; } bool operator!=(const StyleSelfAlignmentData& o) const { return !(*this == o); } private: unsigned position_ : 4; // ItemPosition unsigned position_type_ : 1; // Whether or not alignment uses the 'legacy' // keyword. unsigned overflow_ : 2; // OverflowAlignment }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_STYLE_SELF_ALIGNMENT_DATA_H_
const unsigned char metasprite[]={ 0, 0,0x01,0, 0, 8,0x11,0, 8, 0,0x01,0|OAM_FLIP_H, 8, 8,0x11,0|OAM_FLIP_H, 128 }; const unsigned char metasprite2[]={ 8, 0,0x03,0, 0, 8,0x12,0, 8, 8,0x13,0, 16, 8,0x12,0|OAM_FLIP_H, 0, 16,0x22,0, 8, 16,0x23,0, 16, 16,0x22,0|OAM_FLIP_H, 128 };
<reponame>Flone-dnb/BloodyPlayer // This file is part of the Bloody Player. // Copyright Aleksandr "Flone" Tretyakov (github.com/Flone-dnb). // Licensed under the ZLib license. // Refer to the LICENSE file included. #pragma once #include <QWidget> class QMouseEvent; class QMenu; class QAction; namespace Ui { class TrackWidget; } class TrackWidget : public QWidget { Q_OBJECT signals: // Context menu signals void signalDelete(); void signalMoveUp(); void signalMoveDown(); void signalDoubleClick(size_t trackIndex); void signalSetPlaying(); void signalDisablePlaying(); void signalSelected(size_t iTrackIndex); void signalUpdateTrackInfo(size_t iTrackIndex); public: explicit TrackWidget(QString TrackName, QString TrackInfo, QString TrackTime, QWidget *parent = nullptr); void setPlaying(); void setBitrate(QString sBitrate); void setNumber(size_t iNumber); void enableSelected(); void disablePlaying(); void disableSelected(); ~TrackWidget(); QString trackName; QString trackInfo; QString trackTime; size_t trackIndex; protected: void mouseDoubleClickEvent(QMouseEvent* ev); void mousePressEvent(QMouseEvent* ev); private slots: // Context menu void slotMoveUp(); void slotMoveDown(); void slotDelete(); void slotSetPlaying(); void slotDisablePlaying(); void on_TrackWidget_customContextMenuRequested(const QPoint &pos); private: Ui::TrackWidget *ui; // Context menu QMenu* pMenuContextMenu; QAction* pActionMoveUp; QAction* pActionMoveDown; QAction* pActionDelete; QString styleDefault; QString styleSelected; QString stylePlaying; bool bPlaying; bool bSelected; };
/* * Copyright 2017, Data61 * Commonwealth Scientific and Industrial Research Organisation (CSIRO) * ABN 41 687 119 230. * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(DATA61_BSD) */ /* * seL4 tutorial part 2: create and run a new thread */ /* Include Kconfig variables. */ #include <autoconf.h> #include <stdio.h> #include <assert.h> #include <sel4/sel4.h> #include <simple/simple.h> #include <simple-default/simple-default.h> #include <vka/object.h> #include <allocman/allocman.h> #include <allocman/bootstrap.h> #include <allocman/vka.h> #include <utils/arith.h> #include <utils/zf_log.h> #include <sel4utils/sel4_zf_logif.h> #include <sel4platsupport/bootinfo.h> /* global environment variables */ /* seL4_BootInfo defined in bootinfo.h * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#Globals_links: */ seL4_BootInfo *info; /* simple_t defined in simple.h * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#Globals_links: */ simple_t simple; /* vka_t defined in vka.h * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#Globals_links: */ vka_t vka; /* allocman_t defined in allocman.h * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#Globals_links: */ allocman_t *allocman; /* static memory for the allocator to bootstrap with */ #define ALLOCATOR_STATIC_POOL_SIZE (BIT(seL4_PageBits) * 10) UNUSED static char allocator_mem_pool[ALLOCATOR_STATIC_POOL_SIZE]; /* stack for the new thread */ #define THREAD_2_STACK_SIZE 512 static uint64_t thread_2_stack[THREAD_2_STACK_SIZE]; /* name_thread(): convenience function in util.c: * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#Globals_links: */ extern void name_thread(seL4_CPtr tcb, char *name); /* function to run in the new thread */ void thread_2(void) { /* TASK 15: print something */ /* hint: printf() */ /*- if solution -*/ printf("thread_2: hallo wereld\n"); /*- endif -*/ /* never exit */ while (1); } int main(void) { UNUSED int error = 0; /* TASK 1: get boot info */ /* hint: platsupport_get_bootinfo() * seL4_BootInfo* platsupport_get_bootinfo(void); * @return Pointer to the bootinfo, NULL on failure * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_1: */ /*- if solution -*/ info = platsupport_get_bootinfo(); ZF_LOGF_IF(info == NULL, "Failed to get bootinfo."); /*- endif -*/ /* Set up logging and give us a name: useful for debugging if the thread faults */ /* seL4_CapInitThreadTCB is a cap pointer to the root task's initial TCB. * It is part of the root task's boot environment and defined in bootinfo.h from libsel4: * https://wiki.sel4.systems/seL4%20Tutorial%202#Globals_links: */ zf_log_set_tag_prefix("hello-2:"); name_thread(seL4_CapInitThreadTCB, "hello-2"); /* TASK 2: init simple */ /* hint: simple_default_init_bootinfo() * void simple_default_init_bootinfo(simple_t *simple, seL4_BootInfo *bi); * @param simple Structure for the simple interface object. This gets initialised. * @param bi Pointer to the bootinfo describing what resources are available * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_2: */ /*- if solution -*/ simple_default_init_bootinfo(&simple, info); /*- endif -*/ /* TASK 3: print out bootinfo and other info about simple */ /* hint: simple_print() * void simple_print(simple_t *simple); * @param simple Pointer to simple interface. * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_3: */ /*- if solution -*/ simple_print(&simple); /*- endif -*/ /* TASK 4: create an allocator */ /* hint: bootstrap_use_current_simple() * allocman_t *bootstrap_use_current_simple(simple_t *simple, uint32_t pool_size, char *pool); * @param simple Pointer to simple interface. * @param pool_size Size of the initial memory pool. * @param pool Initial memory pool. * @return returns NULL on error * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_4: */ /*- if solution -*/ allocman = bootstrap_use_current_simple(&simple, ALLOCATOR_STATIC_POOL_SIZE, allocator_mem_pool); /*- endif -*/ ZF_LOGF_IF(allocman == NULL, "Failed to initialize alloc manager.\n" "\tMemory pool sufficiently sized?\n" "\tMemory pool pointer valid?\n"); /* TASK 5: create a vka (interface for interacting with the underlying allocator) */ /* hint: allocman_make_vka() * void allocman_make_vka(vka_t *vka, allocman_t *alloc); * @param vka Structure for the vka interface object. This gets initialised. * @param alloc allocator to be used with this vka * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_5: */ /*- if solution -*/ allocman_make_vka(&vka, allocman); /*- endif -*/ /* TASK 6: get our cspace root cnode */ /* hint: simple_get_cnode() * seL4_CPtr simple_get_cnode(simple_t *simple); * @param simple Pointer to simple interface. * @return The cnode backing the simple interface. no failure. * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_6: */ /*- if solution -*/ seL4_CPtr cspace_cap; cspace_cap = simple_get_cnode(&simple); /*- endif -*/ /* TASK 7: get our vspace root page diretory */ /* hint: simple_get_pd() * seL4_CPtr simple_get_pd(simple_t *simple); * @param simple Pointer to simple interface. * @return The vspace (PD) backing the simple interface. no failure. * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_7: */ /*- if solution -*/ seL4_CPtr pd_cap; pd_cap = simple_get_pd(&simple); /*- endif -*/ /* TASK 8: create a new TCB */ /* hint: vka_alloc_tcb() * int vka_alloc_tcb(vka_t *vka, vka_object_t *result); * @param vka Pointer to vka interface. * @param result Structure for the TCB object. This gets initialised. * @return 0 on success * https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_8: */ /*- if solution -*/ vka_object_t tcb_object = {0}; error = vka_alloc_tcb(&vka, &tcb_object); /*- endif -*/ ZF_LOGF_IFERR(error, "Failed to allocate new TCB.\n" "\tVKA given sufficient bootstrap memory?"); /* TASK 9: initialise the new TCB */ /* hint 1: seL4_TCB_Configure() * int seL4_TCB_Configure(seL4_TCB service, seL4_Word fault_ep, seL4_Uint8 priority, seL4_CNode cspace_root, seL4_CapData_t cspace_root_data, seL4_CNode vspace_root, seL4_CapData_t vspace_root_data, seL4_Word buffer, seL4_CPtr bufferFrame) * @param service Capability to the TCB which is being operated on. * @param fault_ep Endpoint which receives IPCs when this thread faults (must be in TCB's cspace). * @param cspace_root The new CSpace root. * @param cspace_root_data Optionally set the guard and guard size of the new root CNode. If set to zero, this parameter has no effect. * @param vspace_root The new VSpace root. * @param vspace_root_data Has no effect on IA-32 or ARM processors. * @param buffer Address of the thread's IPC buffer. Must be 512-byte aligned. The IPC buffer may not cross a page boundary. * @param bufferFrame Capability to a page containing the thread?s IPC buffer. * @return 0 on success. * Note: this function is generated during build. It is generated from the following definition: * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_9: * You can find out more about it in the API manual: http://sel4.systems/Info/Docs/seL4-manual-3.0.0.pdf * * hint 2: use seL4_CapNull for the fault endpoint * hint 3: use seL4_NilData for cspace and vspace data * hint 4: we don't need an IPC buffer frame or address yet * hint 5: set the priority of the new thread to seL4_MaxPrio */ /*- if solution -*/ error = seL4_TCB_Configure(tcb_object.cptr, seL4_CapNull, cspace_cap, seL4_NilData, pd_cap, seL4_NilData, 0, 0); /*- endif -*/ ZF_LOGF_IFERR(error, "Failed to configure the new TCB object.\n" "\tWe're running the new thread with the root thread's CSpace.\n" "\tWe're running the new thread in the root thread's VSpace.\n" "\tWe will not be executing any IPC in this app.\n"); /* TASK 10: give the new thread a name */ /* hint: we've done thread naming before */ /*- if solution -*/ name_thread(tcb_object.cptr, "hello-2: thread_2"); /*- endif -*/ /* * set start up registers for the new thread: */ UNUSED seL4_UserContext regs = {0}; /* TASK 11: set instruction pointer where the thread shoud start running */ /* hint 1: sel4utils_set_instruction_pointer() * void sel4utils_set_instruction_pointer(seL4_UserContext *regs, seL4_Word value); * @param regs Data structure in which to set the instruction pointer value * @param value New instruction pointer value * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_11: * * hint 2: we want the new thread to run the function "thread_2" */ /*- if solution -*/ sel4utils_set_instruction_pointer(&regs, (seL4_Word)thread_2); /*- endif -*/ /* check that stack is aligned correctly */ const int stack_alignment_requirement = sizeof(seL4_Word) * 2; uintptr_t thread_2_stack_top = (uintptr_t)thread_2_stack + sizeof(thread_2_stack); ZF_LOGF_IF(thread_2_stack_top % (stack_alignment_requirement) != 0, "Stack top isn't aligned correctly to a %dB boundary.\n" "\tDouble check to ensure you're not trampling.", stack_alignment_requirement); /* TASK 12: set stack pointer for the new thread */ /* hint 1: sel4utils_set_stack_pointer() * void sel4utils_set_stack_pointer(seL4_UserContext *regs, seL4_Word value); * @param regs Data structure in which to set the stack pointer value * @param value New stack pointer value * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_12: * * hint 2: remember the stack grows down! */ /*- if solution -*/ sel4utils_set_stack_pointer(&regs, thread_2_stack_top); /*- endif -*/ /* TASK 13: actually write the TCB registers. We write 2 registers: * instruction pointer is first, stack pointer is second. */ /* hint: seL4_TCB_WriteRegisters() * int seL4_TCB_WriteRegisters(seL4_TCB service, seL4_Bool resume_target, seL4_Uint8 arch_flags, seL4_Word count, seL4_UserContext *regs) * @param service Capability to the TCB which is being operated on. * @param resume_target The invocation should also resume the destination thread. * @param arch_flags Architecture dependent flags. These have no meaning on either IA-32 or ARM. * @param count The number of registers to be set. * @param regs Data structure containing the new register values. * @return 0 on success * * Note: this function is generated during build. It is generated from the following definition: * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_13: * You can find out more about it in the API manual: http://sel4.systems/Info/Docs/seL4-manual-3.0.0.pdf */ /*- if solution -*/ error = seL4_TCB_WriteRegisters(tcb_object.cptr, 0, 0, 2, &regs); /*- endif -*/ ZF_LOGF_IFERR(error, "Failed to write the new thread's register set.\n" "\tDid you write the correct number of registers? See arg4.\n"); /* TASK 14: start the new thread running */ /* hint: seL4_TCB_Resume() * int seL4_TCB_Resume(seL4_TCB service) * @param service Capability to the TCB which is being operated on. * @return 0 on success * * Note: this function is generated during build. It is generated from the following definition: * Links to source: https://wiki.sel4.systems/seL4%20Tutorial%202#TASK_14: * You can find out more about it in the API manual: http://sel4.systems/Info/Docs/seL4-manual-3.0.0.pdf */ /*- if solution -*/ error = seL4_TCB_Resume(tcb_object.cptr); /*- endif -*/ ZF_LOGF_IFERR(error, "Failed to start new thread.\n"); /* we are done, say hello */ printf("main: hello world\n"); return 0; }
<gh_stars>10-100 // Read an INI file into easy-to-access name/value pairs. // inih and INIReader are released under the New BSD license (see LICENSE.txt). // Go to the project home page for more info: // // https://github.com/benhoyt/inih /* inih -- simple .INI file parser inih is released under the New BSD license (see LICENSE.txt). Go to the project home page for more info: https://github.com/benhoyt/inih */ #ifndef __INI_H__ #define __INI_H__ /* Make this header file easier to include in C++ code */ #ifdef __cplusplus extern "C" { #endif #include <stdio.h> /* Typedef for prototype of handler function. */ typedef int (*ini_handler)(void* user, const char* section, const char* name, const char* value); /* Typedef for prototype of fgets-style reader function. */ typedef char* (*ini_reader)(char* str, int num, void* stream); /* Parse given INI-style file. May have [section]s, name=value pairs (whitespace stripped), and comments starting with ';' (semicolon). Section is "" if name=value pair parsed before any section heading. name:value pairs are also supported as a concession to Python's configparser. For each name=value pair parsed, call handler function with given user pointer as well as section, name, and value (data only valid for duration of handler call). Handler should return nonzero on success, zero on error. Returns 0 on success, line number of first error on parse error (doesn't stop on first error), -1 on file open error, or -2 on memory allocation error (only when INI_USE_STACK is zero). */ int ini_parse(const char* filename, ini_handler handler, void* user); /* Same as ini_parse(), but takes a FILE* instead of filename. This doesn't close the file when it's finished -- the caller must do that. */ int ini_parse_file(FILE* file, ini_handler handler, void* user); /* Same as ini_parse(), but takes an ini_reader function pointer instead of filename. Used for implementing custom or string-based I/O. */ int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler, void* user); /* Nonzero to allow multi-line value parsing, in the style of Python's configparser. If allowed, ini_parse() will call the handler with the same name for each subsequent line parsed. */ #ifndef INI_ALLOW_MULTILINE #define INI_ALLOW_MULTILINE 1 #endif /* Nonzero to allow a UTF-8 BOM sequence (0xEF 0xBB 0xBF) at the start of the file. See http://code.google.com/p/inih/issues/detail?id=21 */ #ifndef INI_ALLOW_BOM #define INI_ALLOW_BOM 1 #endif /* Nonzero to allow inline comments (with valid inline comment characters specified by INI_INLINE_COMMENT_PREFIXES). Set to 0 to turn off and match Python 3.2+ configparser behaviour. */ #ifndef INI_ALLOW_INLINE_COMMENTS #define INI_ALLOW_INLINE_COMMENTS 1 #endif #ifndef INI_INLINE_COMMENT_PREFIXES #define INI_INLINE_COMMENT_PREFIXES ";" #endif /* Nonzero to use stack, zero to use heap (malloc/free). */ #ifndef INI_USE_STACK #define INI_USE_STACK 1 #endif /* Stop parsing on first error (default is to keep parsing). */ #ifndef INI_STOP_ON_FIRST_ERROR #define INI_STOP_ON_FIRST_ERROR 0 #endif /* Maximum line length for any line in INI file. */ #ifndef INI_MAX_LINE #define INI_MAX_LINE 200 #endif #ifdef __cplusplus } #endif /* inih -- simple .INI file parser inih is released under the New BSD license (see LICENSE.txt). Go to the project home page for more info: https://github.com/benhoyt/inih */ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include <stdio.h> #include <ctype.h> #include <string.h> #if !INI_USE_STACK #include <stdlib.h> #endif #define MAX_SECTION 50 #define MAX_NAME 50 /* Strip whitespace chars off end of given string, in place. Return s. */ inline static char* rstrip(char* s) { char* p = s + strlen(s); while (p > s && isspace((unsigned char)(*--p))) *p = '\0'; return s; } /* Return pointer to first non-whitespace char in given string. */ inline static char* lskip(const char* s) { while (*s && isspace((unsigned char)(*s))) s++; return (char*)s; } /* Return pointer to first char (of chars) or inline comment in given string, or pointer to null at end of string if neither found. Inline comment must be prefixed by a whitespace character to register as a comment. */ inline static char* find_chars_or_comment(const char* s, const char* chars) { #if INI_ALLOW_INLINE_COMMENTS int was_space = 0; while (*s && (!chars || !strchr(chars, *s)) && !(was_space && strchr(INI_INLINE_COMMENT_PREFIXES, *s))) { was_space = isspace((unsigned char)(*s)); s++; } #else while (*s && (!chars || !strchr(chars, *s))) { s++; } #endif return (char*)s; } /* Version of strncpy that ensures dest (size bytes) is null-terminated. */ inline static char* strncpy0(char* dest, const char* src, size_t size) { strncpy(dest, src, size); dest[size - 1] = '\0'; return dest; } /* See documentation in header file. */ inline int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler, void* user) { /* Uses a fair bit of stack (use heap instead if you need to) */ #if INI_USE_STACK char line[INI_MAX_LINE]; #else char* line; #endif char section[MAX_SECTION] = ""; char prev_name[MAX_NAME] = ""; char* start; char* end; char* name; char* value; int lineno = 0; int error = 0; #if !INI_USE_STACK line = (char*)malloc(INI_MAX_LINE); if (!line) { return -2; } #endif /* Scan through stream line by line */ while (reader(line, INI_MAX_LINE, stream) != NULL) { lineno++; start = line; #if INI_ALLOW_BOM if (lineno == 1 && (unsigned char)start[0] == 0xEF && (unsigned char)start[1] == 0xBB && (unsigned char)start[2] == 0xBF) { start += 3; } #endif start = lskip(rstrip(start)); if (*start == ';' || *start == '#') { /* Per Python configparser, allow both ; and # comments at the start of a line */ } #if INI_ALLOW_MULTILINE else if (*prev_name && *start && start > line) { #if INI_ALLOW_INLINE_COMMENTS end = find_chars_or_comment(start, NULL); if (*end) *end = '\0'; rstrip(start); #endif /* Non-blank line with leading whitespace, treat as continuation of previous name's value (as per Python configparser). */ if (!handler(user, section, prev_name, start) && !error) error = lineno; } #endif else if (*start == '[') { /* A "[section]" line */ end = find_chars_or_comment(start + 1, "]"); if (*end == ']') { *end = '\0'; strncpy0(section, start + 1, sizeof(section)); *prev_name = '\0'; } else if (!error) { /* No ']' found on section line */ error = lineno; } } else if (*start) { /* Not a comment, must be a name[=:]value pair */ end = find_chars_or_comment(start, "=:"); if (*end == '=' || *end == ':') { *end = '\0'; name = rstrip(start); value = lskip(end + 1); #if INI_ALLOW_INLINE_COMMENTS end = find_chars_or_comment(value, NULL); if (*end) *end = '\0'; #endif rstrip(value); /* Valid name[=:]value pair found, call handler */ strncpy0(prev_name, name, sizeof(prev_name)); if (!handler(user, section, name, value) && !error) error = lineno; } else if (!error) { /* No '=' or ':' found on name[=:]value line */ error = lineno; } } #if INI_STOP_ON_FIRST_ERROR if (error) break; #endif } #if !INI_USE_STACK free(line); #endif return error; } /* See documentation in header file. */ inline int ini_parse_file(FILE* file, ini_handler handler, void* user) { return ini_parse_stream((ini_reader)fgets, file, handler, user); } /* See documentation in header file. */ inline int ini_parse(const char* filename, ini_handler handler, void* user) { FILE* file; int error; file = fopen(filename, "r"); if (!file) return -1; error = ini_parse_file(file, handler, user); fclose(file); return error; } #endif /* __INI_H__ */ #ifndef __INIREADER_H__ #define __INIREADER_H__ #include <map> #include <set> #include <string> // Read an INI file into easy-to-access name/value pairs. (Note that I've gone // for simplicity here rather than speed, but it should be pretty decent.) class INIReader { public: // Empty Constructor INIReader() {}; // Construct INIReader and parse given filename. See ini.h for more info // about the parsing. INIReader(std::string filename); // Construct INIReader and parse given file. See ini.h for more info // about the parsing. INIReader(FILE *file); // Return the result of ini_parse(), i.e., 0 on success, line number of // first error on parse error, or -1 on file open error. int ParseError() const; // Return the list of sections found in ini file const std::set<std::string>& Sections() const; // Get a string value from INI file, returning default_value if not found. std::string Get(std::string section, std::string name, std::string default_value) const; // Get an integer (long) value from INI file, returning default_value if // not found or not a valid integer (decimal "1234", "-1234", or hex "0x4d2"). long GetInteger(std::string section, std::string name, long default_value) const; // Get a real (floating point double) value from INI file, returning // default_value if not found or not a valid floating point value // according to strtod(). double GetReal(std::string section, std::string name, double default_value) const; // Get a single precision floating point number value from INI file, returning // default_value if not found or not a valid floating point value // according to strtof(). float GetFloat(std::string section, std::string name, float default_value) const; // Get a boolean value from INI file, returning default_value if not found or if // not a valid true/false value. Valid true values are "true", "yes", "on", "1", // and valid false values are "false", "no", "off", "0" (not case sensitive). bool GetBoolean(std::string section, std::string name, bool default_value) const; protected: int _error; std::map<std::string, std::string> _values; std::set<std::string> _sections; static std::string MakeKey(std::string section, std::string name); static int ValueHandler(void* user, const char* section, const char* name, const char* value); }; #endif // __INIREADER_H__ #ifndef __INIREADER__ #define __INIREADER__ #include <algorithm> #include <cctype> #include <cstdlib> inline INIReader::INIReader(std::string filename) { _error = ini_parse(filename.c_str(), ValueHandler, this); } inline INIReader::INIReader(FILE *file) { _error = ini_parse_file(file, ValueHandler, this); } inline int INIReader::ParseError() const { return _error; } inline const std::set<std::string>& INIReader::Sections() const { return _sections; } inline std::string INIReader::Get(std::string section, std::string name, std::string default_value) const { std::string key = MakeKey(section, name); return _values.count(key) ? _values.at(key) : default_value; } inline long INIReader::GetInteger(std::string section, std::string name, long default_value) const { std::string valstr = Get(section, name, ""); const char* value = valstr.c_str(); char* end; // This parses "1234" (decimal) and also "0x4D2" (hex) long n = strtol(value, &end, 0); return end > value ? n : default_value; } inline double INIReader::GetReal(std::string section, std::string name, double default_value) const { std::string valstr = Get(section, name, ""); const char* value = valstr.c_str(); char* end; double n = strtod(value, &end); return end > value ? n : default_value; } inline float INIReader::GetFloat(std::string section, std::string name, float default_value) const { std::string valstr = Get(section, name, ""); const char* value = valstr.c_str(); char* end; float n = strtof(value, &end); return end > value ? n : default_value; } inline bool INIReader::GetBoolean(std::string section, std::string name, bool default_value) const { std::string valstr = Get(section, name, ""); // Convert to lower case to make string comparisons case-insensitive std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower); if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1") return true; else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0") return false; else return default_value; } inline std::string INIReader::MakeKey(std::string section, std::string name) { std::string key = section + "=" + name; // Convert to lower case to make section/name lookups case-insensitive std::transform(key.begin(), key.end(), key.begin(), ::tolower); return key; } inline int INIReader::ValueHandler(void* user, const char* section, const char* name, const char* value) { INIReader* reader = (INIReader*)user; std::string key = MakeKey(section, name); if (reader->_values[key].size() > 0) reader->_values[key] += "\n"; reader->_values[key] += value; reader->_sections.insert(section); return 1; } #endif // __INIREADER__
#pragma once //------------------------------------------------------------------------------ /** Context handling GPU cluster culling (C) 2019-2020 Individual contributors, see AUTHORS file */ //------------------------------------------------------------------------------ #include "graphics/graphicscontext.h" #include "coregraphics/shaderrwbuffer.h" #include "coregraphics/window.h" #include <array> #include "cluster_generate.h" namespace Clustering { class ClusterContext : public Graphics::GraphicsContext { _DeclarePluginContext(); public: /// constructor ClusterContext(); /// destructor virtual ~ClusterContext(); /// setup light context using CameraSettings static void Create(float ZNear, float ZFar, const CoreGraphics::WindowId window); /// get cluster buffer static const CoreGraphics::ShaderRWBufferId GetClusterBuffer(); /// get number of clusters static const SizeT GetNumClusters(); /// get cluster dimensions static const std::array<SizeT, 3> GetClusterDimensions(); /// get cluster uniforms static const ClusterGenerate::ClusterUniforms& GetUniforms(); /// do light classification for tiled/clustered compute static void OnBeforeView(const Ptr<Graphics::View>& view, const Graphics::FrameContext& ctx); #ifndef PUBLIC_BUILD // static void OnRenderDebug(uint32_t flags); #endif private: /// run light classification compute static void UpdateClusters(); }; } // namespace Clustering
// // ZJJTimeCountDownLabel.h // ZJJCountDown // // Created by xiaozhu on 2017/7/10. // Copyright © 2017年 xiaozhu. All rights reserved. // #import <UIKit/UIKit.h> typedef NS_ENUM(NSInteger ,ZJJTextStlye){ ZJJTextStlyeNormal = 0, ZJJTextStlyeCustom, ZJJTextStlyeDDHHMMSSBox, ZJJTextStlyeHHMMSSBox, ZJJTextStlyeMMSSBox, ZJJTextStlyeSSBox, ZJJTextStlyeDDHHMMSSChineseBox, ZJJTextStlyeHHMMSSChineseBox, ZJJTextStlyeMMSSChineseBox, ZJJTextStlyeSSChineseBox, }; typedef NS_ENUM(NSUInteger, ZJJTextEffectStlye) { ZJJTextEffectStlyeNone = 0, /** 描边效果 配合textHollowWidth和textHollowColor两个属性使用,textHollowWidth默认是4 textHollowColor 默认是字体颜色 注意:⚠️ 如果设置textHollowWidth > 0 时为空心效果,全部字体颜色都为描边颜色 如果设置textHollowWidth < 0 时,描边颜色为textHollowColor,中间的颜色为字体颜色 */ ZJJTextEffectStlyeHollow, }; //文本对齐方式 typedef NS_ENUM(NSInteger ,ZJJTextAlignmentStlye){ ZJJTextAlignmentStlyeLeftCenter = 0, ZJJTextAlignmentStlyeLeftTop, ZJJTextAlignmentStlyeLeftBottom, ZJJTextAlignmentStlyeCenterTop, ZJJTextAlignmentStlyeCenter, ZJJTextAlignmentStlyeCenterBottom, ZJJTextAlignmentStlyeRightTop, ZJJTextAlignmentStlyeCenterRight, ZJJTextAlignmentStlyeRightBottom, //自定义位置,配合textLeftDeviation和textTopDeviation属性值来使用 ZJJTextAlignmentStlyeCustom, //水平居中,配合textLeftDeviation属性值来使用 ZJJTextAlignmentStlyeHorizontalCenter, //垂直居中 配合textTopDeviation属性值来使用 ZJJTextAlignmentStlyeVerticalCenter, }; @interface ZJJTimeCountDownLabel : UILabel /** label显示样式:默认样式:55天05时30分10秒 如果要自定义样式,需要设置样式为ZJJTextStlyeCustom,并实现ZJJTimeCountDownDelegate自定义文本方法 */ @property (nonatomic ,assign) ZJJTextStlye textStyle; /** 单个文本框的对齐方式 */ @property (nonatomic ,assign) ZJJTextAlignmentStlye jj_textAlignment; /** 文字效果 */ @property (nonatomic ,assign) ZJJTextEffectStlye effectStlye; /** 时间过时,显示的文字 */ @property (nonatomic ,strong) NSString *jj_description; /** 对应模型中要显示的倒计时的属性字符串(必须要设置,在初始化视图时设置) */ @property (nonatomic ,strong) NSString *timeKey; /** 对应模型 */ @property (nonatomic ,strong) id model; /** 设置文本所在位置在(动态的UITableViewCell或UICollectionViewCell上使用) */ @property (nonatomic ,strong) NSIndexPath *indexPath; /** 是否将过时的数据进行删除(在动态的UITableViewCell或UICollectionViewCell上使用) */ @property (nonatomic ,assign) BOOL isAutomaticallyDeleted; /** 过时的数据是否保留最后格式 默认为NO,不保留格式,显示jj_description值,如果设置为YES ,那么设置jj_description就会失效 例如显示格式为:8天8时8分8秒 ,过时的时间会一值保留为:0天0时0分0秒 */ @property (nonatomic ,assign) BOOL isRetainFinalValue; /** 保留过时的值,对ZJJTextStlyeNormal和ZJJTextStlyeCustom有效 */ @property (nonatomic ,strong) NSAttributedString *textFinalValue; /** 天数 */ @property (nonatomic ,assign) NSInteger days; /** 小时数 */ @property (nonatomic ,assign) NSInteger hours; /** 分数 */ @property (nonatomic ,assign) NSInteger minutes; /** 秒数 */ @property (nonatomic ,assign) NSInteger seconds; /** 总秒数 */ @property (nonatomic ,assign) NSInteger totalSeconds; /** 天数后面添加的字符串 */ @property (nonatomic ,strong) NSString *dayAddString; /** 针对Box风格 小时后面添加字符串 */ @property (nonatomic ,strong) NSString *hourAddString; /** 针对Box风格 分数后面添加字符串 */ @property (nonatomic ,strong) NSString *minuteAddString; /** 针对Box风格 秒数后面添加字符串 */ @property (nonatomic ,strong) NSString *secondAddString; /** 针对Box风格 单个文本背景图片 */ @property (nonatomic ,strong) UIImage *textBackgroundImage; /** 整体文本背景图片 */ @property (nonatomic ,strong) UIImage *backgroundImage; /** 整体文本背景图片的拉伸参数 */ @property (nonatomic ,assign) UIEdgeInsets resizableBackgroundImageWithCapInsets; /** 最左边单个文本左偏移量 ,对ZJJTextAlignmentStlyeCustom和ZJJTextAlignmentStlyeHorizontalCenter对齐样式有效 */ @property (nonatomic ,assign) CGFloat textLeftDeviation; /** 针对Box风格 单个文本顶部偏移量,对ZJJTextAlignmentStlyeCustom和ZJJTextAlignmentStlyeVerticalCenter对齐样式有效 */ @property (nonatomic ,assign) CGFloat textTopDeviation; /** 针对Box风格 设置单个文本背景图片的拉伸参数 */ @property (nonatomic ,assign) UIEdgeInsets resizableImageWithCapInsets; /** 针对Box风格 单个文本背景色 */ @property (nonatomic ,strong) UIColor *textBackgroundColor; /** 针对Box风格 单个文本背景圆角 */ @property (nonatomic ,assign) CGFloat textBackgroundRadius; /** 针对Box风格 单个文本背景边框颜色 */ @property (nonatomic ,strong) UIColor *textBackgroundBorderColor; /** 针对Box风格 单个文本之间的间隔 */ @property (nonatomic ,assign) CGFloat textBackgroundInterval; /** 针对Box风格 单个文本背景框的宽度 */ @property (nonatomic ,assign) CGFloat textBackgroundBorderWidth; /** 针对Box风格 单个文本间的间隔符 */ @property (nonatomic ,strong) NSString *textIntervalSymbol; /** 针对Box风格 单个文本间隔符字体大小 */ @property (nonatomic ,strong) UIFont *textIntervalSymbolFont; /** 针对Box风格 单个文本间的间隔符颜色 */ @property (nonatomic ,strong) UIColor *textIntervalSymbolColor; /** 针对Box风格 单个文本宽 */ @property (nonatomic ,assign) CGFloat textWidth; /** 针对Box风格 单个文本高 */ @property (nonatomic ,assign) CGFloat textHeight; /** 针对Box风格 是否根据文字大小来自动调节宽度 默认为NO 如果设置为YES,那么textWidth属性值就会失效 ,一般是配合textAdjustsWidthLeftRightSide属性值来使用 */ @property (nonatomic ,assign) BOOL textAdjustsWidthToFitFont; /** 单文本字体距离单个文本背景左右偏距 默认值为5,需要将textAdjustsWidthToFitFont设置为YES该值才会生效 */ @property (nonatomic ,assign) CGFloat textAdjustsWidthLeftRightSide; /** 描边效果的宽度,文字效果设置为ZJJTextEffectStlyeNoneHollow风格才有效 */ @property (nonatomic ,assign) CGFloat textHollowWidth; /** 描边效果的颜色,文字效果设置为ZJJTextEffectStlyeNoneHollow风格才有效 */ @property (nonatomic ,strong) UIColor *textHollowColor; /** 扁平化系数,一般是设置在0~0.5之间 ,默认是0 */ @property (nonatomic ,assign) CGFloat textFlatModulus; /** 设置阴影 */ @property (nonatomic ,strong) NSShadow *textShadow; /** 继承该类后,可重新设置属性值 */ - (void)setupProperty; /** 设置Cell数据 @param model 数据模型 @param indexPath 设置文本所在位置在位置 */ - (void)setupCellWithModel:(id)model indexPath:(NSIndexPath *)indexPath; @end
// vrmfcDlg.h : header file // #pragma once #include "afxwin.h" #include "CameraDS.h" class CAlarmTextDlg; class PkMatToGDI; class CDuiBottomTool; //#define USE_THREAD_TO_CAP_MAT #define PLAYER_NAME "IDC_STATIC_OUTPUT" // CvrmfcDlg dialog class CvrmfcDlg : public CDialogEx { // Construction public: CvrmfcDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_VRMFC_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support class lang_obs : public dp::observer<int> { public: virtual void on_update(const int& lang); CvrmfcDlg* dlg; }; std::shared_ptr<lang_obs> obs_ = {}; void on_update(const int & lang); // Implementation protected: HICON m_hIcon; CStatic m_player; CWnd* pcvwnd_ = nullptr; //std::shared_ptr<PkMatToGDI> drawer_ = {}; //cv::VideoCapture capture_ = {}; CCameraDS dscap_ = {}; CBrush m_bkbrush = {}; std::shared_ptr<CAlarmTextDlg> tip_ = {}; std::shared_ptr<CAlarmTextDlg> rec_tip_ = {}; std::shared_ptr<CDuiBottomTool> dui_bt_ = {}; bool bottom_show_ = false; std::string com_data_ = {}; int brightness_level_ = 0; int temperature_ = 0; bool usb_storage_plugin_ = false; bool running_ = true; //cv::Mat frame_ = {}; std::list<cv::Mat> recorded_frames_ = {}; std::mutex mutex_ = {}; std::thread thread_ = {}; std::condition_variable cv_ = {}; void worker(); #ifdef USE_THREAD_TO_CAP_MAT std::mutex mutex_ = {}; std::thread thread_ = {}; //bool previewing_ = true; //bool sig_received_ = false; void stop_worker(bool close_cam = true); void start_worker(); void worker(); int sleep_ms_ = 10; #else #endif // USE_THREAD_TO_CAP_MAT void draw_mat(); struct _fps { std::chrono::steady_clock::time_point begin = {}; long long frames = 0; std::string prev_fps = {}; int get(); std::string get_string(); } fps_ = {}; struct _record { bool recording = false; std::string file = {}; std::shared_ptr<cv::VideoWriter> writer = {}; std::chrono::steady_clock::time_point begin = {}; std::string prev_time_str = {}; std::string get_time(); int get_minutes(); } record_ = {}; void adjust_player_size(int w, int h); void handle_com(); void process_com(const std::string& cmd); void recalc_fps(); // Public interface public: void do_exit_windows(); // return true for recording, false for stopped bool do_record(); void do_stop_record(); void do_capture(); bool do_file_manager(CRect& rc); void do_update_pic_sel(fv pics, fviters iters); void do_update_video_sel(fv videos, fviters iters); bool do_picview_mode_show_or_hide_tools(bool show); bool do_video_view_mode_show_or_hide_tools(bool show); bool do_video_view_mode_pos_changed(const std::wstring& cur, const std::wstring& total, int pos); bool do_video_view_mode_user_change_pos(int pos); void do_file_manager_over(); void do_settings(); bool do_update_capmode(const std::string& mode); bool do_update_resolution(misz sz); bool do_update_video(VideoProcAmpProperty p, int value); bool do_reset_video(); bool do_update_camera(CameraControlProperty p, int value); bool do_reset_camera(); void do_system_info(); void do_adjust_brightness(); // Generated message map functions public: DECLARE_MESSAGE_MAP() virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnBnClickedOk(); afx_msg void OnBnClickedCancel(); afx_msg void OnTimer(UINT_PTR nIDEvent); afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); afx_msg void OnDestroy(); afx_msg LRESULT OnDeviceChange(WPARAM wParam, LPARAM lParam); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); protected: afx_msg LRESULT OnRefreshMat(WPARAM wParam, LPARAM lParam); public: afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); };
<filename>8051/UART/main.c #include "reg51.h" #include "lcd.h" typedef unsigned int u16; typedef unsigned char u8; void sendData(u8 d){ TMOD = 0x20; TH1 = 0xF3; PCON=0X80; SCON = 0x50; TR1 = 1; SBUF = d; while(!TI); TI = 0; } u8 receiveData(){ u8 d; TMOD = 0x20; TH1 = 0xF3; PCON=0X80; SCON = 0x50; TR1 = 1; while(!RI); d = SBUF; P2 = d; RI = 0; return d; } void main(){ char d; P2 = 0x00; LcdInit(); LcdInit(); while(1){ d = receiveData(); P2 = d; LcdWriteData(d); sendData(d); } }
#include "tmr.h" int TMR_enqueue(TMR_t *tmr, EVT_Event_t *e, unsigned long notify_at) { if (0 == tmr) { return -1; } if (0 == e) { return -1; } for (int i = 0; i < TMR_MAX_TIMERS; i++) { if (tmr->event_notify[i] == 0) { tmr->event_notify[i] = notify_at; tmr->events[i] = e; if ((0 == tmr->wake_millis) || (notify_at < tmr->wake_millis)) { tmr->wake_millis = notify_at; } return 0; } } return -1; } int TMR_clear(TMR_t *tmr, EVT_Event_t *e) { if (0 == tmr) { return -1; } if (0 == e) { return -1; } for (int i = 0; i < TMR_MAX_TIMERS; i++) { if (e == tmr->events[i]) { tmr->event_notify[i] = 0; tmr->events[i] = 0; } } return 0; } int TMR_handle(TMR_t *tmr, unsigned long now) { EVT_Event_t *notify_event; if (0 == tmr || 0 == tmr->evt) { return -1; } if (tmr->wake_millis == 0 || tmr->wake_millis > now) { return 0; } tmr->wake_millis = 0; tmr->now_millis = now; for (int i = 0; i < TMR_MAX_TIMERS; i++) { if (tmr->event_notify[i] == 0) { continue; } if (tmr->event_notify[i] < now) { notify_event = tmr->events[i]; tmr->event_notify[i] = 0; tmr->events[i] = 0; EVT_notify(tmr->evt, notify_event); notify_event = 0; } else { if ((0 == tmr->wake_millis) || (tmr->event_notify[i] < tmr->wake_millis)) { tmr->wake_millis = tmr->event_notify[i]; } } } return 0; } unsigned long TMR_now(TMR_t *tmr) { return tmr->now_millis; }
/* * Author: <NAME> * Description: This is teaching material for my university course. Feel free * to use/copy/modify this code. * Source: For more open source projects visit my github profile: * https://github.com/MessineseGianluca * */ #ifndef GRAPH_H #define GRAPH_H #include "../lists/array/array_list.h" #include "../queues/linked/linked_queue.h" //#include "../stacks/linked/linked_stack.h" #include "exceptions.h" #include "gnode.h" template<class W, class N> class Edge_ { public: N node1; N node2; W weight; }; template<class L, class W, class N> class Graph { public: typedef L label; typedef W weight; typedef N node; typedef Edge_<weight, node> Edge; typedef ArrayList<node*> list_of_nodes; typedef typename ArrayList<node*>::position list_of_nodes_pos; typedef ArrayList<Edge> list_of_edges; /*struct Info { int *marks; W path_weight; LinkedStack<node> path; };*/ /* methods */ virtual bool empty() const = 0; virtual void ins_node(node&) = 0; virtual void ins_edge(node, node, weight) = 0; virtual void delete_node(node) = 0; virtual void delete_edge(node, node) = 0; virtual bool exists_node(node) const = 0; virtual bool exists_edge(node, node) const = 0; virtual list_of_nodes adjacent(node) const = 0; virtual list_of_nodes list_nodes() const = 0; virtual label read_label(node) const = 0; virtual void write_label(node, label) = 0; virtual weight read_weight(node, node) const = 0; virtual void write_weight(node, node, weight) = 0; virtual int num_of_nodes() const = 0; virtual int num_of_edges() const = 0; virtual int dim() const = 0; void controller_DFS(node) const; // call it for DFS void BFS(node) const; bool controller_is_connected(node n) const; //call it to know if thegraph is connected //bool is_in_adj(list_of_nodes, node) const; //void controller_path_more_than(node source, W k) const; private: void DFS(node, bool *) const; //bool path_more_than(node source, node e, W k, Info &) const; void is_connected(int &, bool *, node , int) const; }; template<class L, class W, class N> bool Graph<L, W, N>::controller_is_connected(node n) const { int count = 0; int graph_d = dim(); int num = num_of_nodes(); bool marks[graph_d]; for(int i = 0; i < graph_d; i++) { marks[i] = false; } is_connected(count, marks, n, num); if(count == num) { return true; } else { return false; } } template<class L, class W, class N> void Graph<L, W, N>::is_connected(int &count, bool *marks, node n, int num) const { if(!marks[n.getId()]) { count++; marks[n.getId()] = true; } list_of_nodes temp = adjacent(n); list_of_nodes_pos p = temp.begin(); while(!temp.end(p) && count != num) { node c(temp.read(p)->getId()); if(!marks[c.getId()]) { is_connected(count, marks, c, num); } p = temp.next(p); } } template<class L, class W, class N> void Graph<L, W, N>::controller_DFS(node n) const { if(controller_is_connected(n)) { int graph_d = dim(); bool marks[graph_d]; for(int i = 0; i < graph_d; i++) marks[i] = false; std::cout << std::endl; DFS(n, marks); std::cout << std::endl; } else { throw GraphIsNotConnected(); } } template<class L, class W, class N> void Graph<L, W, N>::DFS(node n, bool *marks) const { list_of_nodes_pos p; std::cout << read_label(n) << " "; marks[n.getId()] = true; list_of_nodes ls = adjacent(n); p = ls.begin(); while(!ls.end(p)) { node c(ls.read(p)->getId()); if(marks[c.getId()] == false) { DFS(c, marks); } p = ls.next(p); } } template<class L, class W, class N> void Graph<L, W, N>::BFS(node n) const { if(controller_is_connected(n)) { LinkedQueue<node> q; list_of_nodes list; list_of_nodes_pos p; int graph_d = dim(); bool marks[graph_d]; for(int i = 0; i < graph_d; i++){ marks[i] = false; } std::cout << std::endl; q.queue(n); while(!q.empty()) { node c = q.read(); q.dequeue(); if(!marks[c.getId()]) std::cout << read_label(c) << " "; marks[c.getId()] = true; list = adjacent(c); p = list.begin(); while(!list.end(p)) { node v(list.read(p)->getId()); if(!marks[v.getId()]) { q.queue(v); } p = list.next(p); } } std::cout << std::endl; } else { throw GraphIsNotConnected(); } } /* template<class L, class W, class N> void Graph<L, W, N>::controller_path_more_than(node source, W k) const { int num = num_of_nodes(); list_of_nodes path(num); list_of_nodes adj(adjacent(source)); list_of_nodes_pos p = adj.begin(); list_of_nodes_pos p_path; W path_weight = 0; bool found = false; if(!adj.empty()) { while(!adj.end(p) && !found) { node end(adj.read(p)->getId()); found = path_more_than(source, end, k, path_weight, path); p = adj.next(p); } if(found) { std::cout << "The path is: "; p_path = path.begin(); while(!path.end(p_path)) { std::cout << read_label(path.read(p_path)->getId()); p_path = path.next(p_path); } std::cout << std::endl; } } } template<class L, class W, class N> bool Graph<L, W, N>::path_more_than(node source, node e, W k, W &path_weight, list_of_nodes &path) const { bool found = false; int num = num_of_nodes(); list_of_nodes adj(adjacent(e)); list_of_nodes_pos p = adj.begin(); list_of_nodes_pos p_path; path.insert_last(new GNode(e.getId())); path_weight += read_weight(source, e); std::cout << "reading the node: " << read_label(e) << std::endl; // std::cout << path << " " << path_weight << std::endl; if(adj.size() == 1 && adj.read(p)->getId() == source.getId()) { std::cout << "condition 1" << std::endl; path_weight = 0; p_path = path.begin(); while(!path.end(p_path)) { path.erase(p_path); } return false; } if(!is_in_adj(adj, source) && path_weight > k) { std::cout << "condition 2" << std::endl; return true; } else { std::cout << "condition 3" << std::endl; while(!adj.end(p) && !found) { node end(adj.read(p)->getId()); if(end.getId() != source.getId()) { std::cout << "condition 4" << std::endl; found = path_more_than(source, end, k, path_weight, path); } p = adj.next(p); } } return found; }*/ /* template<class L, class W, class N> bool Graph<L, W, N>::is_in_adj(list_of_nodes adj, node n) const { bool found = false; list_of_nodes_pos p = adj.begin(); while(!adj.end(p) && !found) { if(n.getId() == adj.read(p)->getId()) { found = true; } p = adj.next(p); } return found; } template<class L, class W, class N> void Graph<L, W, N>::controller_path_more_than(node source, W k) const { int graph_d = dim(); int m[graph_d]; Info info; info.marks = m; info.path_weight = 0; for(int i = 0; i < graph_d; i++){ info.marks[i] = 0; } info.marks[source.getId()] = 1; list_of_nodes adj(adjacent(source)); list_of_nodes_pos p = adj.begin(); bool found = false; if(!adj.empty()) { while(!adj.end(p) && !found) { node end(adj.read(p)->getId()); found = path_more_than(source, end, k, info); p = adj.next(p); } if(found) { std::cout << "The path is: "; while(!info.path.empty()) { std::cout << read_label(info.path.read().getId()); info.path.pop(); } } } } template<class L, class W, class N> bool Graph<L, W, N>::path_more_than(node source, node e, W k, Info &info) const { bool found; list_of_nodes adj = adjacent(e); list_of_nodes_pos p = adj.begin(); info.path.push(e); info.path_weight += read_weight(source, e); info.marks[e.getId()] = 1; if(adj.size() == 1 && (adj.read(p)->getId() == source.getId() || info.marks[e.getId()] == -1)) { info.marks[e.getId()] == -1; // black list info.path_weight -= read_weight(source, e); info.path.pop(); return false; } else if(!adj.empty() && (info.path_weight < k || (is_in_adj(adj, source) && info.path_weight > k))) { found = false; while(!adj.end(p) && !found) { node e(adj.read(p)->getId()); // check if the node e is marked or is in black list or if is the source if(e.getId() != source.getId() && (info.marks[e.getId()] != -1 || info.marks[e.getId()] == 1)) { found = path_more_than(source, e, k, info); } p = adj.next(p); } // check if the last node of the path has no adjacencies with a if(is_in_adj(adjacent(info.path.read()), source)) { found = false; } return found; } else if(!adj.empty() && info.path_weight > k) { return true; } else if(adj.empty() && info.path_weight > k) { return true; // end: a path has been found! } else { info.path.pop(); info.marks[e.getId()] = 0; info.path_weight -= read_weight(source, e); return false; } } */ #endif /* GRAPH_H */
/* Matrix.c program files to control the matrix Written by <NAME> && <NAME> */ #include "system.h" // the main gameboard used for the application char* matrix[] ={"eeeeeeeee", "eaaaaaaae", "ebbbbbbbe", "eccc1ccce", "eddddddde", "efffffffe", //screen two starts here "eggggggge", "ehhhhhhhe", "e0001000e", "eiiiiiiie", "ejjjjjjje", "eeeeeeeee"}; /* Duuude function totally resets the game matrix when a new game is started */ void resetMatrix(void){ matrix[0] = "eeeeeeeee"; matrix[1] = "eaaaaaaae"; matrix[2] = "ebbbbbbbe"; matrix[3] = "eccc1ccce"; matrix[4] = "eddddddde"; matrix[5] = "efffffffe"; //screen two starts here matrix[6] = "eggggggge"; matrix[7] = "ehhhhhhhe"; matrix[8] = "e0001000e"; matrix[9] = "eiiiiiiie"; matrix[10] = "ejjjjjjje"; matrix[11] = "eeeeeeeee"; } /* draws frames for an explosion animation x: the x location of where to start the explosion y: the y location of where to start the explosion frame: the frame (1-3) of the animation to be applied */ void showExplosion(int x, int y, int frame){ if(frame == 1){ matrix[x+1][y+1] = 'w'; //frame 1 matrix[x-1][y-1] = 'w'; matrix[x+1][y-1] = 'w'; matrix[x-1][y+1] = 'w'; }else if (frame ==2){ matrix[x+2][y+0] = 'w'; //frame 2 matrix[x-2][y-0] = 'w'; matrix[x+0][y-2] = 'w'; matrix[x-0][y+2] = 'w'; }else{ matrix[x+3][y+3] = 'w'; //frame 3 matrix[x-3][y-3] = 'w'; matrix[x+3][y-3] = 'w'; matrix[x-3][y+3] = 'w'; } }
// Copyright (c) 1997 - 1998 Microsoft Corporation. All Rights Reserved. ///////////////////////////////////////////////////////////////////////////// // CDDSample class ATL_NO_VTABLE CDDSample : public CSample, public IDirectDrawStreamSample { public: CDDSample(); HRESULT InitSample(CStream *pStream, IDirectDrawSurface *pSurface, const RECT *pRect, bool bIsProgressiveRender, bool bIsInternalSample, bool bTemp); // // IStreamSample // STDMETHODIMP GetMediaStream( /* [in] */ IMediaStream **ppMediaStream) { return CSample::GetMediaStream(ppMediaStream); } STDMETHODIMP GetSampleTimes( /* [optional][out] */ STREAM_TIME *pStartTime, /* [optional][out] */ STREAM_TIME *pEndTime, /* [optional][out] */ STREAM_TIME *pCurrentTime) { return CSample::GetSampleTimes( pStartTime, pEndTime, pCurrentTime ); } STDMETHODIMP SetSampleTimes( /* [optional][in] */ const STREAM_TIME *pStartTime, /* [optional][in] */ const STREAM_TIME *pEndTime) { return CSample::SetSampleTimes(pStartTime, pEndTime); } STDMETHODIMP Update( /* [in] */ DWORD dwFlags, /* [optional][in] */ HANDLE hEvent, /* [optional][in] */ PAPCFUNC pfnAPC, /* [optional][in] */ DWORD_PTR dwAPCData) { return CSample::Update(dwFlags, hEvent, pfnAPC, dwAPCData); } STDMETHODIMP CompletionStatus( /* [in] */ DWORD dwFlags, /* [optional][in] */ DWORD dwMilliseconds) { return CSample::CompletionStatus(dwFlags, dwMilliseconds); } // // IDirectDrawStreamSample // STDMETHODIMP GetSurface(IDirectDrawSurface **ppDirectDrawSurface, RECT * pRect); STDMETHODIMP SetRect(const RECT * pRect); // // Overridden virtual function for CSample // void FinalMediaSampleRelease(void); // // Methods forwarded from MediaSample object. // HRESULT MSCallback_GetPointer(BYTE ** ppBuffer); LONG MSCallback_GetSize(void); LONG MSCallback_GetActualDataLength(void); HRESULT MSCallback_SetActualDataLength(LONG lActual); // // Internal methods // long LockAndPrepareMediaSample(long lLastPinPitch); void ReleaseMediaSampleLock(void); HRESULT CopyFrom(CDDSample *pSrcSample); HRESULT CopyFrom(IMediaSample *pSrcMediaSample, const AM_MEDIA_TYPE *pmt); HRESULT LockMediaSamplePointer(); BEGIN_COM_MAP(CDDSample) COM_INTERFACE_ENTRY(IDirectDrawStreamSample) COM_INTERFACE_ENTRY_CHAIN(CSample) END_COM_MAP() public: CComPtr<IDirectDrawSurface> m_pSurface; RECT m_Rect; long m_lLastSurfacePitch; bool m_bProgressiveRender; bool m_bFormatChanged; LONG m_lImageSize; void * m_pvLockedSurfacePtr; }; class CDDInternalSample : public CDDSample { public: CDDInternalSample(); ~CDDInternalSample(); HRESULT InternalInit(void); HRESULT SetCompletionStatus(HRESULT hrStatus); HRESULT Die(void); HRESULT JoinToBuddy(CDDSample *pBuddy); BOOL HasBuddy() const { return m_pBuddySample != NULL; } private: CDDSample *m_pBuddySample; long m_lWaiting; HANDLE m_hWaitFreeSem; bool m_bDead; }; class CDDMediaSample : public CMediaSample, public IDirectDrawMediaSample { public: CDDMediaSample(CSample *pSample) : CMediaSample(pSample) {}; STDMETHODIMP QueryInterface(REFIID riid, void ** ppv); STDMETHODIMP_(ULONG) AddRef() {return CMediaSample::AddRef();} STDMETHODIMP_(ULONG) Release() {return CMediaSample::Release();} STDMETHODIMP GetSurfaceAndReleaseLock(IDirectDrawSurface **ppDirectDrawSurface, RECT * pRect); STDMETHODIMP LockMediaSamplePointer(); };
/* $XFree86: xc/lib/xtrans/Xtransmnx.c,v 3.3 1996/05/10 06:55:50 dawes Exp $ */ /* Xtransmnx.c Created: 11 April 1994 by <NAME> <<EMAIL>> */ #include <stdlib.h> #include <sys/ioctl.h> #include <sys/nbio.h> #include <net/hton.h> #include <net/netlib.h> #include <net/gen/in.h> #include <net/gen/netdb.h> #include <net/gen/tcp.h> #include <net/gen/tcp_io.h> struct private { int nonblocking; int read_inprogress; char *read_buffer; size_t read_bufsize; size_t read_size; size_t read_offset; int write_inprogress; char *write_buffer; size_t write_bufsize; size_t write_size; size_t write_offset; int write_errno; int listen_completed; u16_t listen_port; XtransConnInfo listen_list; }; #define RD_BUFSIZE 1024 #define WR_BUFSIZE 1024 static XtransConnInfo listen_list= NULL; static XtransConnInfo alloc_ConnInfo(Xtransport *thistrans); static void free_ConnInfo(XtransConnInfo ciptr); static struct private *alloc_private(size_t rd_size, size_t wr_size); static void free_private(struct private *priv); static void read_cb(nbio_ref_t ref, int res, int err); static void write_cb(nbio_ref_t ref, int res, int err); static void listen_cb(nbio_ref_t ref, int res, int err); static int restart_listen(XtransConnInfo ciptr); #ifdef TRANS_CLIENT static XtransConnInfo TRANS(MnxTcpOpenCOTSClient) (thistrans, protocol, host, port) Xtransport *thistrans; char *protocol; char *host; char *port; { XtransConnInfo ciptr; char *tcp_device; int s_errno; int fd; nbio_ref_t ref; PRMSG(2, "MnxTcpOpenCOTSClient(%s,%s,%s)\n", protocol, host, port); if ((ciptr= alloc_ConnInfo(thistrans)) == NULL) { PRMSG(1, "MnxTcpOpenCOTSClient: alloc_ConnInfo failed\n", 0, 0, 0); return NULL; } if ((ciptr->priv= (char *)alloc_private(RD_BUFSIZE, WR_BUFSIZE)) == NULL) { PRMSG(1, "MnxTcpOpenCOTSClient: alloc_private() failed\n", 0, 0, 0); s_errno= errno; free_ConnInfo(ciptr); errno= s_errno; return NULL; } if ((tcp_device= getenv("TCP_DEVICE")) == NULL) tcp_device= TCP_DEVICE; PRMSG(4, "MnxTcpOpenCOTSClient: tcp_device= '%s'\n", tcp_device, 0, 0); if ((fd= open(tcp_device, O_RDWR)) == -1) { PRMSG(1, "MnxTcpOpenCOTSClient: open '%s' failed: %s\n", tcp_device, strerror(errno), 0); s_errno= errno; free_ConnInfo(ciptr); errno= s_errno; return NULL; } ciptr->fd= fd; ref.ref_ptr= ciptr; nbio_register(fd); nbio_setcallback(fd, ASIO_READ, read_cb, ref); nbio_setcallback(fd, ASIO_WRITE, write_cb, ref); return ciptr; } #endif /* TRANS_CLIENT */ #ifdef TRANS_SERVER static XtransConnInfo TRANS(MnxTcpOpenCOTSServer) (thistrans, protocol, host, port) Xtransport *thistrans; char *protocol; char *host; char *port; { XtransConnInfo ciptr; char *tcp_device; int s_errno; int fd; nbio_ref_t ref; PRMSG(2, "MnxTcpOpenCOTSServer(%s,%s,%s)\n", protocol, host, port); if ((ciptr= alloc_ConnInfo(thistrans)) == NULL) { PRMSG(1, "MnxTcpOpenCOTSServer: alloc_ConnInfo failed\n", 0, 0, 0); return NULL; } if ((ciptr->priv= (char *)alloc_private(RD_BUFSIZE, WR_BUFSIZE)) == NULL) { PRMSG(1, "MnxTcpOpenCOTSServer: alloc_private() failed\n", 0, 0, 0); s_errno= errno; free_ConnInfo(ciptr); errno= s_errno; return NULL; } if ((tcp_device= getenv("TCP_DEVICE")) == NULL) tcp_device= TCP_DEVICE; PRMSG(4, "MnxTcpOpenCOTSServer: tcp_device= '%s'\n", tcp_device, 0, 0); if ((fd= open(tcp_device, O_RDWR)) == -1) { PRMSG(1, "MnxTcpOpenCOTSServer: open '%s' failed: %s\n", tcp_device, strerror(errno), 0); s_errno= errno; free_ConnInfo(ciptr); errno= s_errno; return NULL; } PRMSG(5, "MnxTcpOpenCOTSServer: fd= '%d'\n", fd, 0, 0); ciptr->fd= fd; ref.ref_ptr= ciptr; nbio_register(fd); nbio_setcallback(fd, ASIO_IOCTL, listen_cb, ref); return ciptr; } #endif /* TRANS_SERVER */ #ifdef TRANS_CLIENT static XtransConnInfo TRANS(MnxTcpOpenCLTSClient) (thistrans, protocol, host, port) Xtransport *thistrans; char *protocol; char *host; char *port; { abort(); } #endif /* TRANS_CLIENT */ #ifdef TRANS_SERVER static XtransConnInfo TRANS(MnxTcpOpenCLTSServer) (thistrans, protocol, host, port) Xtransport *thistrans; char *protocol; char *host; char *port; { abort(); } #endif /* TRANS_SERVER */ #ifdef TRANS_REOPEN static XtransConnInfo TRANS(MnxTcpReopenCOTSServer) (thistrans, fd, port) Xtransport *thistrans; int fd; char *port; { XtransConnInfo ciptr; int i; PRMSG (2, "MnxTcpReopenCOTSServer(%d, %s)\n", fd, port, 0); abort(); } static XtransConnInfo TRANS(MnxTcpReopenCLTSServer) (thistrans, fd, port) Xtransport *thistrans; int fd; char *port; { XtransConnInfo ciptr; int i; PRMSG (2, "MnxTcpReopenCLTSServer(%d, %s)\n", fd, port, 0); abort(); } #endif /* TRANS_REOPEN */ static int TRANS(MnxTcpSetOption) (ciptr, option, arg) XtransConnInfo ciptr; int option; int arg; { int flags; struct private *priv; PRMSG(2, "MnxTcpSetOption(%d,%d,%d)\n", ciptr->fd, option, arg); priv= (struct private *)ciptr->priv; switch(option) { case TRANS_NONBLOCKING: flags= fcntl(ciptr->fd, F_GETFD); if (flags == -1) { PRMSG(1, "MnxTcpSetOption: fcntl F_GETFD failed: %s\n", strerror(errno), 0, 0); return -1; } if (arg == 0) flags &= ~FD_ASYNCHIO; else if (arg == 1) flags |= FD_ASYNCHIO; else { PRMSG(1, "MnxTcpSetOption: bad arg for TRANS_NONBLOCKING: %d\n", arg, 0, 0); return -1; } if (fcntl(ciptr->fd, F_SETFD, flags) == -1) { PRMSG(1, "MnxTcpSetOption: fcntl F_SETFD failed: %s\n", strerror(errno), 0, 0); return -1; } priv->nonblocking= arg; return 0; case TRANS_CLOSEONEXEC: flags= fcntl(ciptr->fd, F_GETFD); if (flags == -1) { PRMSG(1, "MnxTcpSetOption: fcntl F_GETFD failed: %s\n", strerror(errno), 0, 0); return -1; } if (arg == 0) flags &= ~FD_CLOEXEC; else if (arg == 1) flags |= FD_CLOEXEC; else { PRMSG(1, "MnxTcpSetOption: bad arg for TRANS_CLOSEONEXEC: %d\n", arg, 0, 0); return -1; } if (fcntl(ciptr->fd, F_SETFD, flags) == -1) { PRMSG(1, "MnxTcpSetOption: fcntl F_SETFD failed: %s\n", strerror(errno), 0, 0); return -1; } return 0; default: PRMSG(1, "MnxTcpSetOption: unknown option '%d'\n", option, 0, 0); errno= EINVAL; return -1; } } #ifdef TRANS_SERVER static int TRANS(MnxTcpCreateListener) (ciptr, port) XtransConnInfo ciptr; char *port; { struct servent *servp; tcpport_t num_port; char *check; nwio_tcpconf_t tcpconf; nwio_tcpcl_t tcpcl; int r, s_errno, flags; struct private *priv; struct sockaddr_in *addr; PRMSG(2, "MnxTcpCreateListener(%d,%s)\n", ciptr->fd, port, 0); priv= (struct private *)ciptr->priv; if (port == NULL) num_port= 0; else { num_port= strtol(port, &check, 10); num_port= htons(num_port); if (check[0] == '\0') port= NULL; } #ifdef X11_t /* * X has a well known port, that is transport dependent. It is easier * to handle it here, than try and come up with a transport independent * representation that can be passed in and resolved the usual way. * * The port that is passed here is really a string containing the * idisplay from ConnectDisplay(). */ if (port == NULL) num_port= htons(ntohs(num_port) + X_TCP_PORT); #endif if (port != NULL) { if ((servp = getservbyname (port, "tcp")) == NULL) { PRMSG(1, "MnxTcpCreateListener: can't get service for %s\n", port, 0, 0); errno= EINVAL; return TRANS_CREATE_LISTENER_FAILED; } num_port= servp->s_port; } tcpconf.nwtc_flags= NWTC_SHARED | NWTC_UNSET_RA | NWTC_UNSET_RP; if (num_port != 0) { tcpconf.nwtc_locport= num_port; tcpconf.nwtc_flags |= NWTC_LP_SET; } else tcpconf.nwtc_flags |= NWTC_LP_SEL; if (ioctl(ciptr->fd, NWIOSTCPCONF, &tcpconf) == -1) { PRMSG(1, "MnxTcpCreateListener: NWIOSTCPCONF failed: %s\n", strerror(errno),0, 0); return TRANS_CREATE_LISTENER_FAILED; } if (ioctl(ciptr->fd, NWIOGTCPCONF, &tcpconf) == -1) { PRMSG(1, "MnxTcpListen: NWIOGTCPCONF failed: %s\n", strerror(errno),0, 0); return TRANS_CREATE_LISTENER_FAILED; } priv->listen_port= tcpconf.nwtc_locport; if ((addr= (struct sockaddr_in *)xalloc(sizeof(struct sockaddr_in))) == NULL) { PRMSG(1, "MnxTcpAccept: malloc failed\n", 0, 0, 0); return TRANS_CREATE_LISTENER_FAILED; } addr->sin_family= AF_INET; addr->sin_addr.s_addr= tcpconf.nwtc_locaddr; addr->sin_port= tcpconf.nwtc_locport; if (ciptr->addr) xfree(ciptr->addr); ciptr->addr= (char *)addr; ciptr->addrlen= sizeof(struct sockaddr_in); flags= fcntl(ciptr->fd, F_GETFD); if (flags == -1) { PRMSG(1, "MnxTcpCreateListener: fcntl F_GETFD failed: %s\n", strerror(errno), 0, 0); return TRANS_CREATE_LISTENER_FAILED; } if (fcntl(ciptr->fd, F_SETFD, flags | FD_ASYNCHIO) == -1) { PRMSG(1, "MnxTcpCreateListener: fcntl F_SETFD failed: %s\n", strerror(errno), 0, 0); return TRANS_CREATE_LISTENER_FAILED; } tcpcl.nwtcl_flags= 0; r= ioctl(ciptr->fd, NWIOTCPLISTEN, &tcpcl); s_errno= errno; if (fcntl(ciptr->fd, F_SETFD, flags) == -1) { PRMSG(1, "MnxTcpCreateListener: fcntl F_SETFD failed: %s\n", strerror(errno), 0, 0); return TRANS_CREATE_LISTENER_FAILED; } if (r == -1 && s_errno == EINPROGRESS) { nbio_inprogress(ciptr->fd, ASIO_IOCTL, 1 /* read */, 1 /* write */, 0 /* exception */); return 0; } if (r == 0) { priv->listen_completed= 1; return 0; } errno= s_errno; PRMSG(1, "MnxTcpCreateListener: NWIOTCPLISTEN failed: %s\n", strerror(errno), 0, 0); return TRANS_CREATE_LISTENER_FAILED; } #endif /* TRANS_SERVER */ #ifdef TRANS_SERVER static int TRANS(MnxTcpResetListener) (ciptr) XtransConnInfo ciptr; { PRMSG(2, "MnxTcpResetListener(%d)\n", ciptr->fd, 0, 0); return TRANS_RESET_NOOP; } #endif /* TRANS_SERVER */ #ifdef TRANS_SERVER static XtransConnInfo TRANS(MnxTcpAccept) (ciptr_listen, status) XtransConnInfo ciptr_listen; int *status; { XtransConnInfo ciptr; int s_errno; int fd; nbio_ref_t ref; struct private *priv; nwio_tcpconf_t tcpconf; struct sockaddr_in *addr; PRMSG(2, "MnxTcpAccept(%d,%p)\n", ciptr_listen->fd, status, 0); priv= (struct private *)ciptr_listen->priv; *status= TRANS_ACCEPT_MISC_ERROR; if (!priv->listen_completed) { PRMSG(1, "MnxTcpAccept: listen is not completed\n", 0, 0, 0); *status= TRANS_ACCEPT_FAILED; return NULL; } priv->listen_completed= 0; if ((ciptr= alloc_ConnInfo(ciptr_listen->transptr)) == NULL) { PRMSG(1, "MnxTcpAccept: alloc_ConnInfo failed\n", 0, 0, 0); *status= TRANS_ACCEPT_BAD_MALLOC; return NULL; } if ((ciptr->priv= (char *)alloc_private(RD_BUFSIZE, WR_BUFSIZE)) == NULL) { PRMSG(1, "MnxTcpAccept: alloc_private() failed\n", 0, 0, 0); s_errno= errno; free_ConnInfo(ciptr); errno= s_errno; *status= TRANS_ACCEPT_BAD_MALLOC; return NULL; } fd= dup(ciptr_listen->fd); if (fd == -1) { s_errno= errno; PRMSG(1, "MnxTcpAccept: dup failed: %s\n", strerror(errno), 0, 0); free_ConnInfo(ciptr); *status= TRANS_ACCEPT_FAILED; return NULL; } if (restart_listen(ciptr_listen) == -1) { priv->listen_list= listen_list; listen_list= ciptr_listen; PRMSG(1, "MnxTcpAccept: unable to restart listen\n", 0, 0, 0); } ciptr->fd= fd; ref.ref_ptr= ciptr; nbio_register(fd); nbio_setcallback(fd, ASIO_WRITE, write_cb, ref); nbio_setcallback(fd, ASIO_READ, read_cb, ref); if (ioctl(ciptr->fd, NWIOGTCPCONF, &tcpconf) == -1) { PRMSG(1, "MnxTcpAccept: NWIOGTCPCONF failed: %s\n", strerror(errno),0, 0); close(fd); free_ConnInfo(ciptr); *status= TRANS_ACCEPT_MISC_ERROR; return NULL; } if ((addr= (struct sockaddr_in *)xalloc(sizeof(struct sockaddr_in))) == NULL) { PRMSG(1, "MnxTcpAccept: malloc failed\n", 0, 0, 0); close(fd); free_ConnInfo(ciptr); *status= TRANS_ACCEPT_BAD_MALLOC; return NULL; } addr->sin_family= AF_INET; addr->sin_addr.s_addr= tcpconf.nwtc_locaddr; addr->sin_port= tcpconf.nwtc_locport; if (ciptr->addr) xfree(ciptr->addr); ciptr->addr= (char *)addr; ciptr->addrlen= sizeof(struct sockaddr_in); if (*(u8_t *)&tcpconf.nwtc_remaddr == 127) { /* Make ConvertAddress return FamilyLocal */ addr->sin_addr.s_addr= tcpconf.nwtc_remaddr; } if ((addr= (struct sockaddr_in *)xalloc(sizeof(struct sockaddr_in))) == NULL) { PRMSG(1, "MnxTcpConnect: malloc failed\n", 0, 0, 0); close(fd); free_ConnInfo(ciptr); *status= TRANS_ACCEPT_BAD_MALLOC; return NULL; } addr->sin_family= AF_INET; addr->sin_addr.s_addr= tcpconf.nwtc_remaddr; addr->sin_port= tcpconf.nwtc_remport; ciptr->peeraddr= (char *)addr; ciptr->peeraddrlen= sizeof(struct sockaddr_in); *status= 0; return ciptr; } #endif /* TRANS_SERVER */ TRANS(MnxTcpConnect) (ciptr, host, port) XtransConnInfo ciptr; char *host; char *port; { struct hostent *hostp; struct servent *servp; char hostnamebuf[256]; /* tmp space */ tcpport_t num_port; ipaddr_t num_addr; char *check; nwio_tcpconf_t tcpconf; nwio_tcpcl_t tcpcl; struct sockaddr_in *addr; PRMSG(2, "MnxTcpConnect(%d,%s,%s)\n", ciptr->fd, host, port); if (!host) { hostnamebuf[0] = '\0'; (void) TRANS(GetHostname) (hostnamebuf, sizeof hostnamebuf); host = hostnamebuf; } num_port= strtol(port, &check, 10); num_port= htons(num_port); if (check[0] == '\0') port= NULL; #ifdef X11_t /* * X has a well known port, that is transport dependent. It is easier * to handle it here, than try and come up with a transport independent * representation that can be passed in and resolved the usual way. * * The port that is passed here is really a string containing the * idisplay from ConnectDisplay(). */ if (port == NULL) num_port= htons(ntohs(num_port) + X_TCP_PORT); #endif num_addr= inet_addr(host); if (num_addr != -1) host= NULL; if (host != NULL) { if ((hostp = gethostbyname(host)) == NULL) { PRMSG(1, "MnxTcpConnect: can't get address for %s\n", host, 0, 0); errno= EINVAL; return TRANS_CONNECT_FAILED; } if (hostp->h_addrtype != AF_INET) /* is IP host? */ { PRMSG(1, "MnxTcpConnect: %s in not an INET host\n", host, 0, 0); errno= EINVAL; return TRANS_CONNECT_FAILED; } num_addr= *(ipaddr_t *)hostp->h_addr; } if (port != NULL) { if ((servp = getservbyname (port, "tcp")) == NULL) { PRMSG(1, "MnxTcpConnect: can't get service for %s\n", port, 0, 0); errno= EINVAL; return TRANS_CONNECT_FAILED; } num_port= servp->s_port; } tcpconf.nwtc_flags= NWTC_EXCL | NWTC_LP_SEL | NWTC_SET_RA | NWTC_SET_RP; tcpconf.nwtc_remaddr= num_addr; tcpconf.nwtc_remport= num_port; if (ioctl(ciptr->fd, NWIOSTCPCONF, &tcpconf) == -1) { PRMSG(1, "MnxTcpConnect: NWIOSTCPCONF failed: %s\n", strerror(errno),0, 0); return TRANS_CONNECT_FAILED; } tcpcl.nwtcl_flags= 0; if (ioctl(ciptr->fd, NWIOTCPCONN, &tcpcl) == -1) { PRMSG(1, "MnxTcpConnect: connect failed: %s\n", strerror(errno),0, 0); if (errno == ECONNREFUSED || errno == EINTR) return TRANS_TRY_CONNECT_AGAIN; else return TRANS_CONNECT_FAILED; } if (ioctl(ciptr->fd, NWIOGTCPCONF, &tcpconf) == -1) { PRMSG(1, "MnxTcpConnect: NWIOGTCPCONF failed: %s\n", strerror(errno),0, 0); return TRANS_CONNECT_FAILED; } if ((addr= (struct sockaddr_in *)xalloc(sizeof(struct sockaddr_in))) == NULL) { PRMSG(1, "MnxTcpConnect: malloc failed\n", 0, 0, 0); return TRANS_CONNECT_FAILED; } addr->sin_family= AF_INET; addr->sin_addr.s_addr= tcpconf.nwtc_locaddr; addr->sin_port= tcpconf.nwtc_locport; ciptr->addr= (char *)addr; ciptr->addrlen= sizeof(struct sockaddr_in); if (*(u8_t *)&tcpconf.nwtc_remaddr == 127) { /* Make ConvertAddress return FamilyLocal */ addr->sin_addr.s_addr= tcpconf.nwtc_remaddr; } if ((addr= (struct sockaddr_in *)xalloc(sizeof(struct sockaddr_in))) == NULL) { PRMSG(1, "MnxTcpConnect: malloc failed\n", 0, 0, 0); return TRANS_CONNECT_FAILED; } addr->sin_family= AF_INET; addr->sin_addr.s_addr= tcpconf.nwtc_remaddr; addr->sin_port= tcpconf.nwtc_remport; ciptr->peeraddr= (char *)addr; ciptr->peeraddrlen= sizeof(struct sockaddr_in); return 0; } static int TRANS(MnxTcpBytesReadable) (ciptr, pend) XtransConnInfo ciptr; BytesReadable_t *pend; { struct private *priv; int r; PRMSG(2, "MnxTcpBytesReadable(%x,%d,%x)\n", ciptr, ciptr->fd, pend); *pend= 0; priv= (struct private *)ciptr->priv; if (priv->read_inprogress) { PRMSG(5, "MnxTcpBytesReadable: read inprogress, %d\n", *pend, 0, 0); return *pend; } if (priv->read_offset < priv->read_size) { *pend= priv->read_size-priv->read_offset; PRMSG(5, "MnxTcpBytesReadable: %d\n", *pend, 0, 0); return *pend; } priv->read_offset= 0; r= read(ciptr->fd, priv->read_buffer, priv->read_bufsize); if (r >= 0) { if (r == 0) r= 1; /* Signal EOF condition */ priv->read_size= r; PRMSG(5, "MnxTcpBytesReadable: %d\n", *pend, 0, 0); *pend= r; } else if (r == -1 && errno == EINPROGRESS) { priv->read_inprogress= 1; nbio_inprogress(ciptr->fd, ASIO_READ, 1 /* read */, 0 /* write */, 0 /* exception */); } else { PRMSG(1, "MnxTcpBytesReadable: read failed: %s\n", strerror(errno), 0, 0); return -1; } PRMSG(5, "MnxTcpBytesReadable: %d\n", *pend, 0, 0); return *pend; } static int TRANS(MnxTcpRead) (ciptr, buf, size) XtransConnInfo ciptr; char *buf; int size; { int len, r, ret, s_errno; int offset; struct private *priv; asio_fd_set_t fd_set; fwait_t fw; PRMSG(2, "MnxTcpRead(%d,%x,%d)\n", ciptr->fd, buf, size); priv= (struct private *)ciptr->priv; offset= 0; if (priv->read_inprogress) { PRMSG(5, "MnxTcpRead: EAGAIN\n", 0, 0, 0); errno= EAGAIN; return -1; } /* Copy any data left in the buffer */ if (priv->read_offset < priv->read_size) { len= priv->read_size-priv->read_offset; if (len > size-offset) len= size-offset; PRMSG(5, "MnxTcpRead: copying %d bytes\n", len, 0, 0); memcpy(buf+offset, priv->read_buffer + priv->read_offset, len); offset += len; priv->read_offset += len; if (priv->read_offset < priv->read_size) return offset; } /* Try to read directly into the user's buffer. */ ret= 0; s_errno= 0; while(offset < size) { r= read(ciptr->fd, buf+offset, size-offset); if (r == -1 && errno == EINPROGRESS) { r= fcancel(ciptr->fd, ASIO_READ); if (r == -1) abort(); ASIO_FD_ZERO(&fd_set); ASIO_FD_SET(ciptr->fd, ASIO_READ, &fd_set); fw.fw_flags= FWF_NONBLOCK; fw.fw_bits= fd_set.afds_bits; fw.fw_maxfd= ASIO_FD_SETSIZE; r= fwait(&fw); if (r == -1 || fw.fw_fd != ciptr->fd || fw.fw_operation != ASIO_READ) { abort(); } r= fw.fw_result; errno= fw.fw_errno; } if (r > 0) { PRMSG(5, "MnxTcpRead: read %d bytes\n", r, 0, 0); offset += r; continue; } else if (r == 0) { PRMSG(5, "MnxTcpRead: read EOF\n", 0, 0, 0); break; } else { if (errno == EINTR) { PRMSG(5, "MnxTcpRead: EINTR\n", 0, 0, 0); errno= EAGAIN; } else { PRMSG(1, "MnxTcpRead: read error %s\n", strerror(errno), 0, 0); } s_errno= errno; ret= -1; break; } } if (offset != 0) ret= offset; if (priv->read_offset != priv->read_size) abort(); priv->read_offset= 0; priv->read_size= 0; if (priv->nonblocking) { r= read(ciptr->fd, priv->read_buffer, priv->read_bufsize); if (r >= 0) { PRMSG(5, "MnxTcpRead: buffered %d bytes\n", r, 0, 0); priv->read_size= r; } else if (r == -1 && errno == EINPROGRESS) { priv->read_inprogress= 1; nbio_inprogress(ciptr->fd, ASIO_READ, 1 /* read */, 0 /* write */, 0 /* exception */); } else { PRMSG(1, "MnxTcpRead: read failed: %s\n", strerror(errno), 0, 0); } } errno= s_errno; return ret; } static int TRANS(MnxTcpWrite) (ciptr, buf, size) XtransConnInfo ciptr; char *buf; int size; { int len, r, ret, s_errno; int offset; struct private *priv; asio_fd_set_t fd_set; fwait_t fw; PRMSG(2, "MnxTcpWrite(%d,%x,%d)\n", ciptr->fd, buf, size); priv= (struct private *)ciptr->priv; offset= 0; if (priv->write_errno) { PRMSG(5, "MnxTcpWrite: write_errno %d\n", priv->write_errno, 0, 0); errno= priv->write_errno; return -1; } if (priv->write_inprogress) { PRMSG(5, "MnxTcpWrite: EAGAIN\n", 0, 0, 0); errno= EAGAIN; return -1; } /* Try to write directly out of the user's buffer. */ ret= 0; s_errno= 0; while(offset < size) { r= write(ciptr->fd, buf+offset, size-offset); if (r == -1 && errno == EINPROGRESS) { r= fcancel(ciptr->fd, ASIO_WRITE); if (r == -1) abort(); ASIO_FD_ZERO(&fd_set); ASIO_FD_SET(ciptr->fd, ASIO_WRITE, &fd_set); fw.fw_flags= FWF_NONBLOCK; fw.fw_bits= fd_set.afds_bits; fw.fw_maxfd= ASIO_FD_SETSIZE; r= fwait(&fw); if (r == -1 || fw.fw_fd != ciptr->fd || fw.fw_operation != ASIO_WRITE) { abort(); } r= fw.fw_result; errno= fw.fw_errno; } if (r > 0) { PRMSG(5, "MnxTcpWrite: wrote %d bytes\n", r, 0, 0); offset += r; continue; } else if (r == 0) abort(); else { if (errno == EINTR) { PRMSG(5, "MnxTcpWrite: EINTR\n", 0, 0, 0); errno= EAGAIN; } else { PRMSG(1, "MnxTcpWrite: write error: %s\n", strerror(errno), 0, 0); } s_errno= errno; ret= -1; break; } } /* Copy any data to the buffer */ if (offset < size) { len= priv->write_bufsize; if (len > size-offset) len= size-offset; PRMSG(5, "MnxTcpWrite: copying %d bytes\n", len, 0, 0); memcpy(priv->write_buffer, buf+offset, len); offset += len; priv->write_offset= 0; priv->write_size= len; } if (offset != 0) ret= offset; while (priv->write_offset < priv->write_size) { r= write(ciptr->fd, priv->write_buffer+priv->write_offset, priv->write_size-priv->write_offset); if (r > 0) { PRMSG(5, "MnxTcpWrite: wrote %d bytes\n", r, 0, 0); priv->write_offset += r; continue; } else if (r == -1 && errno == EINPROGRESS) { priv->write_inprogress= 1; nbio_inprogress(ciptr->fd, ASIO_WRITE, 0 /* read */, 1 /* write */, 0 /* exception */); } else { PRMSG(1, "MnxTcpWrite: write failed: %s\n", strerror(errno), 0, 0); priv->write_errno= errno; } break; } errno= s_errno; return ret; } static int TRANS(MnxTcpReadv) (ciptr, buf, size) XtransConnInfo ciptr; struct iovec *buf; int size; { int i, offset, total, len, r; PRMSG(2, "MnxTcpReadv(%d,%x,%d)\n", ciptr->fd, buf, size); /* Simply call read a number of times. */ total= 0; offset= 0; i= 0; while(i<size) { PRMSG(5, "MnxTcpReadv: [%d] size %d-%d\n", i, buf[i].iov_len, offset); if (offset >= buf[i].iov_len) { offset= 0; i++; continue; } len= buf[i].iov_len-offset; r= TRANS(MnxTcpRead)(ciptr, buf[i].iov_base+offset, len); if (r == -1) { if (errno == EAGAIN) { PRMSG(5, "MnxTcpReadv: read returned: %s\n", strerror(errno), 0, 0); } else { PRMSG(1, "MnxTcpReadv: read failed: %s\n", strerror(errno), 0, 0); } if (total != 0) return total; else return -1; } if (r == 0) break; if (r > len) abort(); total += r; offset += r; } return total; } static int TRANS(MnxTcpWritev) (ciptr, buf, size) XtransConnInfo ciptr; struct iovec *buf; int size; { int i, offset, total, len, r; PRMSG(2, "MnxTcpWritev(%d,%x,%d)\n", ciptr->fd, buf, size); /* Simply call write a number of times. */ total= 0; offset= 0; i= 0; while(i<size) { if (offset >= buf[i].iov_len) { offset= 0; i++; continue; } len= buf[i].iov_len-offset; r= TRANS(MnxTcpWrite)(ciptr, buf[i].iov_base+offset, len); if (r == -1) { if (errno == EAGAIN) { PRMSG(5, "MnxTcpWritev: AGAIN\n", 0, 0, 0); } else { PRMSG(1, "MnxTcpWritev: write failed: %s\n", strerror(errno), 0, 0); } if (total != 0) return total; else return -1; } if (r == 0 || r > len) abort(); total += r; offset += r; } return total; } static int TRANS(MnxTcpDisconnect) (ciptr) XtransConnInfo ciptr; { PRMSG(2, "MnxTcpDisconnect(%x,%d)\n", ciptr, ciptr->fd, 0); return ioctl(ciptr->fd, NWIOTCPSHUTDOWN, NULL); } static int TRANS(MnxTcpClose) (ciptr) XtransConnInfo ciptr; { XtransConnInfo list, t_ciptr; struct private *priv; PRMSG(2, "MnxTcpClose(%x,%d)\n", ciptr, ciptr->fd, 0); if (listen_list) { list= listen_list; listen_list= NULL; while(list) { t_ciptr= list; priv= (struct private *)t_ciptr->priv; list= priv->listen_list; if (t_ciptr == ciptr) continue; if (restart_listen(t_ciptr) == -1) { priv->listen_list= listen_list; listen_list= t_ciptr; } } } free_private((struct private *)ciptr->priv); nbio_unregister(ciptr->fd); return close (ciptr->fd); } static XtransConnInfo alloc_ConnInfo(thistrans) Xtransport *thistrans; { XtransConnInfo ciptr; PRMSG(2, " alloc_ConnInfo(%p)\n", thistrans, 0, 0); if ((ciptr= (XtransConnInfo) xalloc(sizeof(struct _XtransConnInfo))) == NULL) { PRMSG(1, " alloc_ConnInfo: malloc failed\n", 0, 0, 0); return NULL; } ciptr->transptr= thistrans; ciptr->priv= NULL; ciptr->flags= 0; ciptr->fd= -1; ciptr->port= NULL; ciptr->family= AF_INET; ciptr->addr= NULL; ciptr->addrlen= 0; ciptr->peeraddr= NULL; ciptr->peeraddrlen= 0; return ciptr; } static void free_ConnInfo(ciptr) XtransConnInfo ciptr; { if (ciptr == NULL) return; free_private((struct private *)ciptr->priv); xfree(ciptr); } static struct private * alloc_private(rd_size, wr_size) size_t rd_size; size_t wr_size; { struct private *priv; int s_errno; char *buf; PRMSG(2, ":alloc_private(%d, %d)\n", rd_size, wr_size, 0); if ((priv= (struct private *)xalloc(sizeof(struct private))) == NULL) { PRMSG(1, ":alloc_private: malloc failed\n", 0, 0, 0); return NULL; } priv->nonblocking= 0; priv->read_inprogress= 0; priv->read_buffer= NULL; priv->read_bufsize= rd_size; priv->read_size= 0; priv->read_offset= 0; if (rd_size != 0) { if ((buf= xalloc(rd_size)) == NULL) { PRMSG(1, ":alloc_private: malloc failed\n", 0, 0, 0); s_errno= errno; free_private(priv); errno= s_errno; return NULL; } priv->read_buffer= buf; } priv->write_inprogress= 0; priv->write_buffer= NULL; priv->write_bufsize= rd_size; priv->write_size= 0; priv->write_offset= 0; priv->write_errno= 0; if (wr_size != 0) { if ((buf= xalloc(wr_size)) == NULL) { PRMSG(1, ":alloc_private: malloc failed\n", 0, 0, 0); s_errno= errno; free_private(priv); errno= s_errno; return NULL; } priv->write_buffer= buf; } priv->listen_completed= 0; priv->listen_port= 0; priv->listen_list= NULL; return priv; } static void free_private(priv) struct private *priv; { if (priv == NULL) return; xfree(priv->read_buffer); xfree(priv->write_buffer); xfree(priv); } static void read_cb(ref, res, err) nbio_ref_t ref; int res; int err; { XtransConnInfo ciptr; struct private *priv; PRMSG(2, ":read_cb(%x,%d,%d)\n", ref.ref_ptr, res, err); ciptr= ref.ref_ptr; priv= (struct private *)ciptr->priv; if (res > 0) priv->read_size= res; priv->read_inprogress= 0; } static void write_cb(ref, res, err) nbio_ref_t ref; int res; int err; { XtransConnInfo ciptr; struct private *priv; int r; PRMSG(2, ":write_cb(%x,%d,%d)\n", ref.ref_ptr, res, err); ciptr= ref.ref_ptr; priv= (struct private *)ciptr->priv; if (res > 0) priv->write_offset += res; else if (res == 0) abort(); else { priv->write_errno= err; return; } priv->write_inprogress= 0; while (priv->write_offset < priv->write_size) { r= write(ciptr->fd, priv->write_buffer+priv->write_offset, priv->write_size-priv->write_offset); if (r > 0) { PRMSG(5, "MnxTcpWrite: wrote %d bytes\n", r, 0, 0); priv->write_offset += r; continue; } else if (r == -1 && errno == EINPROGRESS) { priv->write_inprogress= 1; nbio_inprogress(ciptr->fd, ASIO_WRITE, 0 /* read */, 1 /* write */, 0 /* exception */); } else { PRMSG(1, "MnxTcpWrite: write failed: %s\n", strerror(errno), 0, 0); priv->write_errno= errno; } break; } } static void listen_cb(ref, res, err) nbio_ref_t ref; int res; int err; { XtransConnInfo ciptr; struct private *priv; struct sockaddr_in *addr; nwio_tcpconf_t tcpconf; PRMSG(2, ":listen_cb(%x,%d,%d)\n", ref.ref_ptr, res, err); ciptr= ref.ref_ptr; priv= (struct private *)ciptr->priv; if (res == 0) { if (ioctl(ciptr->fd, NWIOGTCPCONF, &tcpconf) == -1) { PRMSG(1, ":listen_cb: NWIOGTCPCONF failed: %s\n", strerror(errno),0, 0); return; } if ((addr= (struct sockaddr_in *)xalloc(sizeof(struct sockaddr_in))) == NULL) { PRMSG(1, ":listen_cb: malloc failed\n", 0, 0, 0); return; } addr->sin_family= AF_INET; addr->sin_addr.s_addr= tcpconf.nwtc_locaddr; addr->sin_port= tcpconf.nwtc_locport; if (ciptr->addr) xfree(ciptr->addr); ciptr->addr= (char *)addr; ciptr->addrlen= sizeof(struct sockaddr_in); priv->listen_completed= 1; return; } PRMSG(2, ":listen_cb: listen failed: %s\n", strerror(err), 0, 0); if (restart_listen(ciptr) == -1) { priv->listen_list= listen_list; listen_list= ciptr; } } static int restart_listen(ciptr) XtransConnInfo ciptr; { char *tcp_device; nwio_tcpconf_t tcpconf; nwio_tcpcl_t tcpcl; int fd, r, s_errno, flags; struct private *priv; nbio_ref_t ref; PRMSG(2, ":restart_listen(%d)\n", ciptr->fd, 0, 0); nbio_unregister(ciptr->fd); if ((tcp_device= getenv("TCP_DEVICE")) == NULL) tcp_device= TCP_DEVICE; if ((fd= open(tcp_device, O_RDWR)) == -1) { PRMSG(1, ":restart_listen: open '%s' failed: %s\n", tcp_device, strerror(errno), 0); return -1; } PRMSG(5, ":restart_listen: fd= '%d'\n", fd, 0, 0); if (fd != ciptr->fd) { if (dup2(fd, ciptr->fd) == -1) abort(); /* no way to recover */ close(fd); } fd= ciptr->fd; ref.ref_ptr= ciptr; nbio_register(fd); nbio_setcallback(fd, ASIO_IOCTL, listen_cb, ref); priv= (struct private *)ciptr->priv; tcpconf.nwtc_flags= NWTC_SHARED | NWTC_UNSET_RA | NWTC_UNSET_RP; tcpconf.nwtc_locport= priv->listen_port; tcpconf.nwtc_flags |= NWTC_LP_SET; if (ioctl(ciptr->fd, NWIOSTCPCONF, &tcpconf) == -1) { PRMSG(1, ":restart_listen: NWIOSTCPCONF failed: %s\n", strerror(errno),0, 0); return -1; } flags= fcntl(ciptr->fd, F_GETFD); if (flags == -1) { PRMSG(1, ":restart_listen: fcntl F_GETFD failed: %s\n", strerror(errno), 0, 0); return -1; } if (fcntl(ciptr->fd, F_SETFD, flags | FD_ASYNCHIO) == -1) { PRMSG(1, ":restart_listen: fcntl F_SETFD failed: %s\n", strerror(errno), 0, 0); return -1; } tcpcl.nwtcl_flags= 0; r= ioctl(ciptr->fd, NWIOTCPLISTEN, &tcpcl); s_errno= errno; if (fcntl(ciptr->fd, F_SETFD, flags) == -1) { PRMSG(1, ":restart_listen: fcntl F_SETFD failed: %s\n", strerror(errno), 0, 0); return -1; } if (r == -1 && s_errno == EINPROGRESS) { nbio_inprogress(ciptr->fd, ASIO_IOCTL, 1 /* read */, 1 /* write */, 0 /* exception */); return 0; } if (r == 0) { priv->listen_completed= 1; return 0; } errno= s_errno; PRMSG(1, ":restart_listen: NWIOTCPLISTEN failed: %s\n", strerror(errno), 0, 0); return -1; } Xtransport TRANS(MnxINETFuncs) = { /* Minix TCP Interface */ "inet", 0, #ifdef TRANS_CLIENT TRANS(MnxTcpOpenCOTSClient), #endif /* TRANS_CLIENT */ #ifdef TRANS_SERVER TRANS(MnxTcpOpenCOTSServer), #endif /* TRANS_SERVER */ #ifdef TRANS_CLIENT TRANS(MnxTcpOpenCLTSClient), #endif /* TRANS_CLIENT */ #ifdef TRANS_SERVER TRANS(MnxTcpOpenCLTSServer), #endif /* TRANS_SERVER */ #ifdef TRANS_REOPEN TRANS(MnxTcpReopenCOTSServer), TRANS(MnxTcpReopenCLTSServer), #endif TRANS(MnxTcpSetOption), #ifdef TRANS_SERVER TRANS(MnxTcpCreateListener), TRANS(MnxTcpResetListener), TRANS(MnxTcpAccept), #endif /* TRANS_SERVER */ #ifdef TRANS_CLIENT TRANS(MnxTcpConnect), #endif /* TRANS_CLIENT */ TRANS(MnxTcpBytesReadable), TRANS(MnxTcpRead), TRANS(MnxTcpWrite), TRANS(MnxTcpReadv), TRANS(MnxTcpWritev), TRANS(MnxTcpDisconnect), TRANS(MnxTcpClose), TRANS(MnxTcpClose), }; Xtransport TRANS(MnxTCPFuncs) = { /* Minix TCP Interface */ "tcp", TRANS_ALIAS, #ifdef TRANS_CLIENT TRANS(MnxTcpOpenCOTSClient), #endif /* TRANS_CLIENT */ #ifdef TRANS_SERVER TRANS(MnxTcpOpenCOTSServer), #endif /* TRANS_SERVER */ #ifdef TRANS_CLIENT TRANS(MnxTcpOpenCLTSClient), #endif /* TRANS_CLIENT */ #ifdef TRANS_SERVER TRANS(MnxTcpOpenCLTSServer), #endif /* TRANS_SERVER */ #ifdef TRANS_REOPEN TRANS(MnxTcpReopenCOTSServer), TRANS(MnxTcpReopenCLTSServer), #endif TRANS(MnxTcpSetOption), #ifdef TRANS_SERVER TRANS(MnxTcpCreateListener), TRANS(MnxTcpResetListener), TRANS(MnxTcpAccept), #endif /* TRANS_SERVER */ #ifdef TRANS_CLIENT TRANS(MnxTcpConnect), #endif /* TRANS_CLIENT */ TRANS(MnxTcpBytesReadable), TRANS(MnxTcpRead), TRANS(MnxTcpWrite), TRANS(MnxTcpReadv), TRANS(MnxTcpWritev), TRANS(MnxTcpDisconnect), TRANS(MnxTcpClose), TRANS(MnxTcpClose), };
///////////////////////////////////////////////////// // AliAnalysisTaskFilterFE: // analysis task to (re)tag RFP and POI of flow event ////////////////////////////////////////////////////// /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id: $ */ #ifndef ALIANALYSISTASKFILTERFE_H #define ALIANALYSISTASKFILTERFE_H #include "AliFlowTrackSimpleCuts.h" #include "AliFlowEventSimple.h" class AliAnalysisTaskSE; class AliAnalysisTaskFilterFE : public AliAnalysisTaskSE { public: AliAnalysisTaskFilterFE(); AliAnalysisTaskFilterFE(const char *name, AliFlowTrackSimpleCuts *cutsRFP, AliFlowTrackSimpleCuts *cutsPOI); virtual ~AliAnalysisTaskFilterFE(); virtual void UserCreateOutputObjects(); virtual void UserExec(Option_t *option); void SetSubeventEtaRange(Double_t minA, Double_t maxA, Double_t minB, Double_t maxB) {this->fMinA = minA; this->fMaxA = maxA; this->fMinB = minB; this->fMaxB = maxB; } private: AliAnalysisTaskFilterFE(const AliAnalysisTaskFilterFE& aAnalysisTask); AliAnalysisTaskFilterFE& operator=(const AliAnalysisTaskFilterFE& aAnalysisTask); AliFlowTrackSimpleCuts* fCutsRFP; //cuts for RFPs AliFlowTrackSimpleCuts* fCutsPOI; //cuts for POIs Double_t fMinA; //minimum of eta range for subevent A Double_t fMaxA; //maximum of eta range for subevent A Double_t fMinB; //minimum of eta range for subevent B Double_t fMaxB; //maximum of eta range for subevent B AliFlowEventSimple* fFlowEvent; //flowevent ClassDef(AliAnalysisTaskFilterFE, 1); // example of analysis }; #endif
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSView.h" @class NSArray, NSMutableString, NSString; @interface RPPINEntryView : NSView { NSMutableString *_text; BOOL _alphaNumeric; BOOL _enabled; NSArray *_fields; CDUnknownBlockType _textChangedHandler; } @property(copy, nonatomic) CDUnknownBlockType textChangedHandler; // @synthesize textChangedHandler=_textChangedHandler; @property(nonatomic) BOOL enabled; // @synthesize enabled=_enabled; @property(retain, nonatomic) NSArray *fields; // @synthesize fields=_fields; @property(nonatomic) BOOL alphaNumeric; // @synthesize alphaNumeric=_alphaNumeric; - (void).cxx_destruct; - (void)viewWillMoveToWindow:(id)arg1; - (void)paste:(id)arg1; - (void)keyDown:(id)arg1; - (void)insertText:(id)arg1; - (BOOL)hasText; - (void)deleteBackward:(id)arg1; - (void)delete:(id)arg1; - (void)cut:(id)arg1; - (void)copy:(id)arg1; - (BOOL)acceptsFirstResponder; - (void)_updateFields; @property(copy, nonatomic) NSString *text; @end
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <functional> #include <new> #include <tuple> #include <type_traits> #include <typeinfo> #include <utility> #include <folly/Traits.h> #include <folly/Utility.h> #include <folly/detail/TypeList.h> #include <folly/functional/Invoke.h> #include <folly/lang/Exception.h> #include <folly/lang/StaticConst.h> #include <folly/PolyException.h> #if defined(__cpp_template_auto) || \ defined(__cpp_nontype_template_parameter_auto) #define FOLLY_POLY_NTTP_AUTO 1 #else #define FOLLY_POLY_NTTP_AUTO 0 #endif namespace folly { /// \cond namespace detail { template <class I> struct PolyRoot; using RRef_ = MetaQuoteTrait<std::add_rvalue_reference>; using LRef_ = MetaQuoteTrait<std::add_lvalue_reference>; template <typename T> struct XRef_ : Type<MetaQuoteTrait<Type>> {}; template <typename T> using XRef = _t<XRef_<T>>; template <typename T> struct XRef_<T&&> : Type<MetaCompose<RRef_, XRef<T>>> {}; template <typename T> struct XRef_<T&> : Type<MetaCompose<LRef_, XRef<T>>> {}; template <typename T> struct XRef_<T const> : Type<MetaQuoteTrait<std::add_const>> {}; template <class A, class B> using AddCvrefOf = MetaApply<XRef<B>, A>; } // namespace detail /// \endcond template <class I> struct Poly; template <class T, class I> detail::AddCvrefOf<T, I>& poly_cast(detail::PolyRoot<I>&); template <class T, class I> detail::AddCvrefOf<T, I> const& poly_cast(detail::PolyRoot<I> const&); #if !FOLLY_POLY_NTTP_AUTO #define FOLLY_AUTO class template <class... Ts> using PolyMembers = detail::TypeList<Ts...>; #else #define FOLLY_AUTO auto template <auto...> struct PolyMembers; #endif /// \cond namespace detail { /* ***************************************************************************** * IMPLEMENTATION NOTES * Building the Interface ---------------------- Here is a high-level description of how Poly works. Users write an interface such as: struct Mine { template <class Base> struct Interface { int Exec() const { return folly::poly_call<0>(*this); } } template <class T> using Members = folly::PolyMembers<&T::Exec>; }; Then they instantiate Poly<Mine>, which will have an Exec member function of the correct signature. The Exec member function comes from Mine::Interface<PolyNode<Mine, PolyRoot<Mine>>>, from which Poly<Mine> inherits. Here's what each piece means: - PolyRoot<I>: stores Data, which is a union of a void* (used when the Poly is storing an object on the heap or a reference) and some aligned storage (used when the Poly is storing an object in-situ). PolyRoot also stores a vtable pointer for interface I, which is a pointer to a struct containing function pointers. The function pointers are bound member functions (e.g., SomeType::Exec). More on the vtable pointer and how it is generated below. - PolyNode: provides the hooks used by folly::poly_call to dispatch to the correctly bound member function for this interface. In the context of an interface I, folly::poly_call<K>(*this, args...) will: 1. Fetch the vtable pointer from PolyRoot, 2. Select the I portion of that vtable (which, in the case of interface extension, may only be a part of the total vtable), 3. Fetch the K-th function pointer from that vtable part, 4. Call through that function pointer, passing Data (from PolyRoot) and any additional arguments in the folly::poly_call<K> invocation. In the case of interface extension -- for instance, if interface Mine extended interface Yours by inheriting from PolyExtends<Yours> -- then interface Mine will have a list of base interfaces in a typelist called "Subsumptions". Poly<Mine> will fold all the subsumed interfaces together, linearly inheriting from them. To take the example of an interface Mine that extends Yours, Poly<Mine> would inherit from this type: Mine::Interface< PolyNode<Mine, Your::Interface< PolyNode<Your, PolyRoot<Mine>>>>> Through linear inheritance, Poly<Mine> ends up with the public member functions of both interfaces, Mine and Yours. VTables ------- As mentioned above, PolyRoot<I> stores a vtable pointer for interface I. The vtable is a struct whose members are function pointers. How are the types of those function pointers computed from the interface? A dummy type is created, Archetype<I>, in much the same way that Poly<I>'s base type is computed. Instead of PolyNode and PolyRoot, there is ArchetypeNode and ArchetypeRoot. These types also provide hooks for folly::poly_call, but they are dummy hooks that do nothing. (Actually, they call std::terminate; they will never be called.) Once Archetype<I> has been constructed, it is a concrete type that has all the member functions of the interface and its subsumed interfaces. That type is passed to Mine::Members, which takes the address of Archetype<I>::Exec and inspects the resulting member function type. This is done for each member in the interface. From a list of [member] function pointers, it is a simple matter of metaprogramming to build a struct of function pointers. std::tuple is used for this. An extra field is added to the tuple for a function that handles all of the "special" operations: destruction, copying, moving, getting the type information, getting the address of the stored object, and fetching a fixed-up vtable pointer for reference conversions (e.g., I -> I&, I& -> I const&, etc). Subsumed interfaces are handled by having VTable<IDerived> inherit from BasePtr<IBase>, where BasePtr<IBase> has only one member of type VTable<IBase> const*. Now that the type of VTable<I> is computed, how are the fields populated? Poly<I> default-constructs to an empty state. Its vtable pointer points to a vtable whose fields are initialized with the addresses of functions that do nothing but throw a BadPolyAccess exception. That way, if you call a member function on an empty Poly, you get an exception. The function pointer corresponding to the "special" operations points to a no-op function; copying, moving and destroying an empty Poly does nothing. On the other hand, when you pass an object of type T satisfying interface I to Poly<I>'s constructor or assignment operator, a vtable for {I,T} is reified by passing type T to I::Members, thereby creating a list of bindings for T's member functions. The address of this vtable gets stored in the PolyRoot<I> subobject, imbuing the Poly object with the behaviors of type T. The T object itself gets stored either on the heap or in the aligned storage within the Poly object itself, depending on the size of T and whether or not it has a noexcept move constructor. */ template <class T, template <class...> class U> struct IsInstanceOf : std::false_type {}; template <class... Ts, template <class...> class U> struct IsInstanceOf<U<Ts...>, U> : std::true_type {}; template <class Then> decltype(auto) if_constexpr(std::true_type, Then then) { return then(Identity{}); } template <class Then> void if_constexpr(std::false_type, Then) {} template <class Then, class Else> decltype(auto) if_constexpr(std::true_type, Then then, Else) { return then(Identity{}); } template <class Then, class Else> decltype(auto) if_constexpr(std::false_type, Then, Else else_) { return else_(Identity{}); } enum class Op : short { eNuke, eMove, eCopy, eType, eAddr, eRefr }; enum class RefType : std::uintptr_t { eRvalue, eLvalue, eConstLvalue }; struct Data; template <class I> struct PolyVal; template <class I> struct PolyRef; struct PolyAccess; template <class T> using IsPoly = IsInstanceOf<remove_cvref_t<T>, Poly>; // Given an interface I and a concrete type T that satisfies the interface // I, create a list of member function bindings from members of T to members // of I. template <class I, class T> using MembersOf = typename I::template Members<remove_cvref_t<T>>; // Given an interface I and a base type T, create a type that implements // the interface I in terms of the capabilities of T. template <class I, class T> using InterfaceOf = typename I::template Interface<T>; #if !FOLLY_POLY_NTTP_AUTO template <class T, T V> using Member = std::integral_constant<T, V>; template <class M> using MemberType = typename M::value_type; template <class M> inline constexpr MemberType<M> memberValue() noexcept { return M::value; } template <class... Ts> struct MakeMembers { template <Ts... Vs> using Members = PolyMembers<Member<Ts, Vs>...>; }; template <class... Ts> MakeMembers<Ts...> deduceMembers(Ts...); template <class Member, class = MemberType<Member>> struct MemberDef; template <class Member, class R, class D, class... As> struct MemberDef<Member, R (D::*)(As...)> { static R value(D& d, As... as) { return folly::invoke(memberValue<Member>(), d, static_cast<As&&>(as)...); } }; template <class Member, class R, class D, class... As> struct MemberDef<Member, R (D::*)(As...) const> { static R value(D const& d, As... as) { return folly::invoke(memberValue<Member>(), d, static_cast<As&&>(as)...); } }; #else template <auto M> using MemberType = decltype(M); template <auto M> inline constexpr MemberType<M> memberValue() noexcept { return M; } #endif struct PolyBase {}; template <class I, class = void> struct SubsumptionsOf_ { using type = TypeList<>; }; template <class I> using InclusiveSubsumptionsOf = TypePushFront<_t<SubsumptionsOf_<I>>, I>; template <class I> struct SubsumptionsOf_<I, void_t<typename I::Subsumptions>> { using type = TypeJoin<TypeTransform< typename I::Subsumptions, MetaQuote<InclusiveSubsumptionsOf>>>; }; template <class I> using SubsumptionsOf = TypeReverseUnique<_t<SubsumptionsOf_<I>>>; struct Bottom { template <class T> [[noreturn]] /* implicit */ operator T &&() const { std::terminate(); } }; using ArchetypeNode = MetaQuote<InterfaceOf>; template <class I> struct ArchetypeRoot; template <class I> using Archetype = TypeFold<InclusiveSubsumptionsOf<I>, ArchetypeRoot<I>, ArchetypeNode>; struct ArchetypeBase : Bottom { ArchetypeBase() = default; template <class T> /* implicit */ ArchetypeBase(T&&); template <std::size_t, class... As> [[noreturn]] Bottom _polyCall_(As&&...) const { std::terminate(); } friend bool operator==(ArchetypeBase const&, ArchetypeBase const&); friend bool operator!=(ArchetypeBase const&, ArchetypeBase const&); friend bool operator<(ArchetypeBase const&, ArchetypeBase const&); friend bool operator<=(ArchetypeBase const&, ArchetypeBase const&); friend bool operator>(ArchetypeBase const&, ArchetypeBase const&); friend bool operator>=(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator++(ArchetypeBase const&); friend Bottom operator++(ArchetypeBase const&, int); friend Bottom operator--(ArchetypeBase const&); friend Bottom operator--(ArchetypeBase const&, int); friend Bottom operator+(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator+=(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator-(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator-=(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator*(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator*=(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator/(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator/=(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator%(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator%=(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator<<(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator<<=(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator>>(ArchetypeBase const&, ArchetypeBase const&); friend Bottom operator>>=(ArchetypeBase const&, ArchetypeBase const&); }; template <class I> struct ArchetypeRoot : ArchetypeBase { template <class Node, class Tfx> using _polySelf_ = Archetype<AddCvrefOf<MetaApply<Tfx, I>, Node>>; using _polyInterface_ = I; }; struct Data { Data() = default; // Suppress compiler-generated copy ops to not copy anything: Data(Data const&) {} Data& operator=(Data const&) { return *this; } union { void* pobj_ = nullptr; std::aligned_storage_t<sizeof(double[2])> buff_; }; }; template <class U, class I> using Arg = If<std::is_same<remove_cvref_t<U>, Archetype<I>>::value, Poly<AddCvrefOf<I, U const&>>, U>; template <class U, class I> using Ret = If<std::is_same<remove_cvref_t<U>, Archetype<I>>::value, AddCvrefOf<Poly<I>, U>, U>; template <class Member, class I> struct SignatureOf_; template <class R, class C, class... As, class I> struct SignatureOf_<R (C::*)(As...), I> { using type = Ret<R, I> (*)(Data&, Arg<As, I>...); }; template <class R, class C, class... As, class I> struct SignatureOf_<R (C::*)(As...) const, I> { using type = Ret<R, I> (*)(Data const&, Arg<As, I>...); }; #ifdef __cpp_noexcept_function_type template <class R, class C, class... As, class I> struct SignatureOf_<R (C::*)(As...) noexcept, I> { using type = std::add_pointer_t<Ret<R, I>(Data&, Arg<As, I>...) noexcept>; }; template <class R, class C, class... As, class I> struct SignatureOf_<R (C::*)(As...) const noexcept, I> { using type = std::add_pointer_t<Ret<R, I>(Data const&, Arg<As, I>...) noexcept>; }; #endif template <class R, class This, class... As, class I> struct SignatureOf_<R (*)(This&, As...), I> { using type = Ret<R, I> (*)(Data&, Arg<As, I>...); }; template <class R, class This, class... As, class I> struct SignatureOf_<R (*)(This const&, As...), I> { using type = Ret<R, I> (*)(Data const&, Arg<As, I>...); }; template <FOLLY_AUTO Arch, class I> using SignatureOf = _t<SignatureOf_<MemberType<Arch>, I>>; template <FOLLY_AUTO User, class I, class Sig = SignatureOf<User, I>> struct ArgTypes_; template <FOLLY_AUTO User, class I, class Ret, class Data, class... Args> struct ArgTypes_<User, I, Ret (*)(Data, Args...)> { using type = TypeList<Args...>; }; #ifdef __cpp_noexcept_function_type template <FOLLY_AUTO User, class I, class Ret, class Data, class... Args> struct ArgTypes_<User, I, Ret (*)(Data, Args...) noexcept> { using type = TypeList<Args...>; }; #endif template <FOLLY_AUTO User, class I> using ArgTypes = _t<ArgTypes_<User, I>>; template <class R, class... Args> using FnPtr = R (*)(Args...); struct ThrowThunk { template <class R, class... Args> constexpr /* implicit */ operator FnPtr<R, Args...>() const noexcept { struct _ { static R call(Args...) { throw_exception<BadPolyAccess>(); } }; return &_::call; } }; inline constexpr ThrowThunk throw_() noexcept { return ThrowThunk{}; } template <class T> inline constexpr bool inSitu() noexcept { return !std::is_reference<T>::value && sizeof(std::decay_t<T>) <= sizeof(Data) && std::is_nothrow_move_constructible<std::decay_t<T>>::value; } template <class T> T& get(Data& d) noexcept { if (inSitu<T>()) { return *(std::add_pointer_t<T>)static_cast<void*>(&d.buff_); } else { return *static_cast<std::add_pointer_t<T>>(d.pobj_); } } template <class T> T const& get(Data const& d) noexcept { if (inSitu<T>()) { return *(std::add_pointer_t<T const>)static_cast<void const*>(&d.buff_); } else { return *static_cast<std::add_pointer_t<T const>>(d.pobj_); } } enum class State : short { eEmpty, eInSitu, eOnHeap }; template <class T> struct IsPolyRef : std::false_type {}; template <class T> struct IsPolyRef<Poly<T&>> : std::true_type {}; template <class Arg, class U> decltype(auto) convert(U&& u) { return detail::if_constexpr( StrictConjunction< IsPolyRef<remove_cvref_t<U>>, Negation<std::is_convertible<U, Arg>>>(), [&](auto id) -> decltype(auto) { return poly_cast<remove_cvref_t<Arg>>(id(u).get()); }, [&](auto id) -> U&& { return static_cast<U&&>(id(u)); }); } template <class Fun> struct IsConstMember : std::false_type {}; template <class R, class C, class... As> struct IsConstMember<R (C::*)(As...) const> : std::true_type {}; template <class R, class C, class... As> struct IsConstMember<R (*)(C const&, As...)> : std::true_type {}; template < class T, FOLLY_AUTO User, class I, class = ArgTypes<User, I>, class = Bool<true>> struct ThunkFn { template <class R, class D, class... As> constexpr /* implicit */ operator FnPtr<R, D&, As...>() const noexcept { return nullptr; } }; template <class T, FOLLY_AUTO User, class I, class... Args> struct ThunkFn< T, User, I, TypeList<Args...>, Bool< !std::is_const<std::remove_reference_t<T>>::value || IsConstMember<MemberType<User>>::value>> { template <class R, class D, class... As> constexpr /* implicit */ operator FnPtr<R, D&, As...>() const noexcept { struct _ { static R call(D& d, As... as) { return folly::invoke( memberValue<User>(), get<T>(d), convert<Args>(static_cast<As&&>(as))...); } }; return &_::call; } }; template < class I, class = MembersOf<I, Archetype<I>>, class = SubsumptionsOf<I>> struct VTable; template <class T, FOLLY_AUTO User, class I> inline constexpr ThunkFn<T, User, I> thunk() noexcept { return ThunkFn<T, User, I>{}; } template <class I> constexpr VTable<I> const* vtable() noexcept { return &StaticConst<VTable<I>>::value; } template <class I, class T> struct VTableFor : VTable<I> { constexpr VTableFor() noexcept : VTable<I>{Type<T>{}} {} }; template <class I, class T> constexpr VTable<I> const* vtableFor() noexcept { return &StaticConst<VTableFor<I, T>>::value; } template <class I, class T> constexpr void* vtableForRef(RefType ref) { switch (ref) { case RefType::eRvalue: return const_cast<VTable<I>*>(vtableFor<I, T&&>()); case RefType::eLvalue: return const_cast<VTable<I>*>(vtableFor<I, T&>()); case RefType::eConstLvalue: return const_cast<VTable<I>*>(vtableFor<I, T const&>()); } return nullptr; } template < class I, class T, std::enable_if_t<std::is_reference<T>::value, int> = 0> void* execOnHeap(Op op, Data* from, void* to) { switch (op) { case Op::eNuke: break; case Op::eMove: case Op::eCopy: static_cast<Data*>(to)->pobj_ = from->pobj_; break; case Op::eType: return const_cast<void*>(static_cast<void const*>(&typeid(T))); case Op::eAddr: if (*static_cast<std::type_info const*>(to) == typeid(T)) { return from->pobj_; } throw_exception<BadPolyCast>(); case Op::eRefr: return vtableForRef<I, remove_cvref_t<T>>( static_cast<RefType>(reinterpret_cast<std::uintptr_t>(to))); } return nullptr; } template < class I, class T, std::enable_if_t<Negation<std::is_reference<T>>::value, int> = 0> void* execOnHeap(Op op, Data* from, void* to) { switch (op) { case Op::eNuke: delete &get<T>(*from); break; case Op::eMove: static_cast<Data*>(to)->pobj_ = std::exchange(from->pobj_, nullptr); break; case Op::eCopy: detail::if_constexpr(std::is_copy_constructible<T>(), [&](auto id) { static_cast<Data*>(to)->pobj_ = new T(id(get<T>(*from))); }); break; case Op::eType: return const_cast<void*>(static_cast<void const*>(&typeid(T))); case Op::eAddr: if (*static_cast<std::type_info const*>(to) == typeid(T)) { return from->pobj_; } throw_exception<BadPolyCast>(); case Op::eRefr: return vtableForRef<I, remove_cvref_t<T>>( static_cast<RefType>(reinterpret_cast<std::uintptr_t>(to))); } return nullptr; } template <class I, class T> void* execInSitu(Op op, Data* from, void* to) { switch (op) { case Op::eNuke: get<T>(*from).~T(); break; case Op::eMove: ::new (static_cast<void*>(&static_cast<Data*>(to)->buff_)) T(std::move(get<T>(*from))); get<T>(*from).~T(); break; case Op::eCopy: detail::if_constexpr(std::is_copy_constructible<T>(), [&](auto id) { ::new (static_cast<void*>(&static_cast<Data*>(to)->buff_)) T(id(get<T>(*from))); }); break; case Op::eType: return const_cast<void*>(static_cast<void const*>(&typeid(T))); case Op::eAddr: if (*static_cast<std::type_info const*>(to) == typeid(T)) { return &from->buff_; } throw_exception<BadPolyCast>(); case Op::eRefr: return vtableForRef<I, remove_cvref_t<T>>( static_cast<RefType>(reinterpret_cast<std::uintptr_t>(to))); } return nullptr; } inline void* noopExec(Op op, Data*, void*) { if (op == Op::eAddr) throw_exception<BadPolyAccess>(); return const_cast<void*>(static_cast<void const*>(&typeid(void))); } template <class I> struct BasePtr { VTable<I> const* vptr_; }; template <class I, class T> constexpr void* (*getOpsImpl(std::true_type) noexcept)(Op, Data*, void*) { return &execInSitu<I, T>; } template <class I, class T> constexpr void* (*getOpsImpl(std::false_type) noexcept)(Op, Data*, void*) { return &execOnHeap<I, T>; } template <class I, class T> constexpr void* (*getOps() noexcept)(Op, Data*, void*) { return getOpsImpl<I, T>(std::integral_constant<bool, inSitu<T>()>{}); } template <class I, FOLLY_AUTO... Arch, class... S> struct VTable<I, PolyMembers<Arch...>, TypeList<S...>> : BasePtr<S>..., std::tuple<SignatureOf<Arch, I>...> { private: template <class T, FOLLY_AUTO... User> constexpr VTable(Type<T>, PolyMembers<User...>) noexcept : BasePtr<S>{vtableFor<S, T>()}..., std::tuple<SignatureOf<Arch, I>...>{thunk<T, User, I>()...}, state_{inSitu<T>() ? State::eInSitu : State::eOnHeap}, ops_{getOps<I, T>()} {} public: constexpr VTable() noexcept : BasePtr<S>{vtable<S>()}..., std::tuple<SignatureOf<Arch, I>...>{ static_cast<SignatureOf<Arch, I>>(throw_())...}, state_{State::eEmpty}, ops_{&noopExec} {} template <class T> explicit constexpr VTable(Type<T>) noexcept : VTable{Type<T>{}, MembersOf<I, T>{}} {} State state_; void* (*ops_)(Op, Data*, void*); }; template <class I> constexpr VTable<I> const& select(VTable<_t<Type<I>>> const& vtbl) noexcept { return vtbl; } template <class I> constexpr VTable<I> const& select(BasePtr<_t<Type<I>>> const& base) noexcept { return *base.vptr_; } struct PolyAccess { template <std::size_t N, typename This, typename... As> static auto call(This&& _this, As&&... args) -> decltype(static_cast<This&&>(_this).template _polyCall_<N>( static_cast<As&&>(args)...)) { static_assert( !IsInstanceOf<std::decay_t<This>, Poly>::value, "When passing a Poly<> object to call(), you must explicitly " "say which Interface to dispatch to, as in " "call<0, MyInterface>(self, args...)"); return static_cast<This&&>(_this).template _polyCall_<N>( static_cast<As&&>(args)...); } template <class Poly> using Iface = typename remove_cvref_t<Poly>::_polyInterface_; template <class Node, class Tfx = MetaIdentity> static typename remove_cvref_t<Node>::template _polySelf_<Node, Tfx> self_(); template <class T, class Poly, class I = Iface<Poly>> static decltype(auto) cast(Poly&& _this) { using Ret = AddCvrefOf<AddCvrefOf<T, I>, Poly&&>; return static_cast<Ret>( *static_cast<std::add_pointer_t<Ret>>(_this.vptr_->ops_( Op::eAddr, const_cast<Data*>(static_cast<Data const*>(&_this)), const_cast<void*>(static_cast<void const*>(&typeid(T)))))); } template <class Poly> static decltype(auto) root(Poly&& _this) noexcept { return static_cast<Poly&&>(_this)._polyRoot_(); } template <class I> static std::type_info const& type(PolyRoot<I> const& _this) noexcept { return *static_cast<std::type_info const*>( _this.vptr_->ops_(Op::eType, nullptr, nullptr)); } template <class I> static VTable<remove_cvref_t<I>> const* vtable( PolyRoot<I> const& _this) noexcept { return _this.vptr_; } template <class I> static Data* data(PolyRoot<I>& _this) noexcept { return &_this; } template <class I> static Data const* data(PolyRoot<I> const& _this) noexcept { return &_this; } template <class I> static Poly<I&&> move(PolyRoot<I&> const& _this) noexcept { return Poly<I&&>{_this, Type<I&>{}}; } template <class I> static Poly<I const&> move(PolyRoot<I const&> const& _this) noexcept { return Poly<I const&>{_this, Type<I const&>{}}; } }; template <class I, class Tail> struct PolyNode : Tail { private: friend PolyAccess; using Tail::Tail; template <std::size_t K, typename... As> decltype(auto) _polyCall_(As&&... as) { return std::get<K>(select<I>(*PolyAccess::vtable(*this)))( *PolyAccess::data(*this), static_cast<As&&>(as)...); } template <std::size_t K, typename... As> decltype(auto) _polyCall_(As&&... as) const { return std::get<K>(select<I>(*PolyAccess::vtable(*this)))( *PolyAccess::data(*this), static_cast<As&&>(as)...); } }; struct MakePolyNode { template <class I, class State> using apply = InterfaceOf<I, PolyNode<I, State>>; }; template <class I> struct PolyRoot : private PolyBase, private Data { friend PolyAccess; friend Poly<I>; friend PolyVal<I>; friend PolyRef<I>; template <class Node, class Tfx> using _polySelf_ = Poly<AddCvrefOf<MetaApply<Tfx, I>, Node>>; using _polyInterface_ = I; private: PolyRoot& _polyRoot_() noexcept { return *this; } PolyRoot const& _polyRoot_() const noexcept { return *this; } VTable<std::decay_t<I>> const* vptr_ = vtable<std::decay_t<I>>(); }; template <class I> using PolyImpl = TypeFold< InclusiveSubsumptionsOf<remove_cvref_t<I>>, PolyRoot<I>, MakePolyNode>; // A const-qualified function type means the user is trying to disambiguate // a member function pointer. template <class Fun> // Fun = R(As...) const struct Sig { template <class T> constexpr Fun T::*operator()(Fun T::*t) const /* nolint */ volatile noexcept { return t; } template <class F, class T> constexpr F T::*operator()(F T::*t) const /* nolint */ volatile noexcept { return t; } }; // A functon type with no arguments means the user is trying to disambiguate // a member function pointer. template <class R> struct Sig<R()> : Sig<R() const> { using Fun = R(); using Sig<R() const>::operator(); template <class T> constexpr Fun T::*operator()(Fun T::*t) const noexcept { return t; } }; template <class R, class... As> struct SigImpl : Sig<R(As...) const> { using Fun = R(As...); using Sig<R(As...) const>::operator(); template <class T> constexpr Fun T::*operator()(Fun T::*t) const noexcept { return t; } constexpr Fun* operator()(Fun* t) const noexcept { return t; } template <class F> constexpr F* operator()(F* t) const noexcept { return t; } }; // The user could be trying to disambiguate either a member or a free function. template <class R, class... As> struct Sig<R(As...)> : SigImpl<R, As...> {}; // This case is like the one above, except we want to add an overload that // handles the case of a free function where the first argument is more // const-qualified than the user explicitly specified. template <class R, class A, class... As> struct Sig<R(A&, As...)> : SigImpl<R, A&, As...> { using CCFun = R(A const&, As...); using SigImpl<R, A&, As...>::operator(); constexpr CCFun* operator()(CCFun* t) const /* nolint */ volatile noexcept { return t; } }; template <class T, class I, class = void> struct ModelsInterface2_ : std::false_type {}; template <class T, class I> struct ModelsInterface2_< T, I, void_t< std::enable_if_t< std::is_constructible<AddCvrefOf<std::decay_t<T>, I>, T>::value>, MembersOf<std::decay_t<I>, std::decay_t<T>>>> : std::true_type {}; template <class T, class I, class = void> struct ModelsInterface_ : std::false_type {}; template <class T, class I> struct ModelsInterface_< T, I, std::enable_if_t< Negation<std::is_base_of<PolyBase, std::decay_t<T>>>::value>> : ModelsInterface2_<T, I> {}; template <class T, class I> struct ModelsInterface : ModelsInterface_<T, I> {}; template <class I1, class I2> struct ValueCompatible : std::is_base_of<I1, I2> {}; // This prevents PolyRef's converting constructors and assignment operators // from being considered as copy constructors and assignment operators: template <class I1> struct ValueCompatible<I1, I1> : std::false_type {}; template <class I1, class I2, class I2Ref> struct ReferenceCompatible : std::is_constructible<I1, I2Ref> {}; // This prevents PolyRef's converting constructors and assignment operators // from being considered as copy constructors and assignment operators: template <class I1, class I2Ref> struct ReferenceCompatible<I1, I1, I2Ref> : std::false_type {}; } // namespace detail /// \endcond } // namespace folly #undef FOLLY_AUTO
#ifndef INCLUDE_H_PKCS11_CORE #define INCLUDE_H_PKCS11_CORE #define GET_BUFFER_SMPL(varName, v8Object) \ char* varName = node::Buffer::Data(v8Object); \ auto varName##Len = node::Buffer::Length(v8Object); #define GET_BUFFER_ARGS(varName, argIndex) \ GET_BUFFER_SMPL(varName, info[argIndex]); #endif // INCLUDE_H_PKCS11_CORE
<gh_stars>10-100 /*++ Copyright (c) 1995 Microsoft Corporation Module Name: topoldat.h Abstract: Include file for cached data class for Automatic recognition of site and CNs Author: <NAME>iov (LiorM) <NAME> (ilanh) 9-July-2000 --*/ #ifndef __TOPOLDAT_H__ #define __TOPOLDAT_H__ #include "dssutil.h" typedef DWORD IPADDRESS; //*********************************************************** // // base class CTopologyData // //*********************************************************** class CTopologyData { public: CTopologyData(); ~CTopologyData(); HRESULT LoadFromRegistry(); const GUID& GetEnterprise() const; const GUID& GetSite() const; BOOL GetAddresses(OUT DWORD * pcbAddress, OUT const unsigned char ** pblobAddress, OUT DWORD * pnCNs, OUT const GUID ** paguidCNs ) const; protected: DWORD m_cbAddress; unsigned char * m_blobAddress; DWORD m_nCNs; GUID * m_aguidCNs; GUID m_guidEnterprise; GUID m_guidSite; }; inline CTopologyData::CTopologyData(): m_cbAddress(0), m_blobAddress(NULL), m_nCNs(0), m_aguidCNs(NULL) { memset(&m_guidEnterprise,0,sizeof(GUID)); memset(&m_guidSite,0,sizeof(GUID)); } inline CTopologyData::~CTopologyData() { delete [] m_blobAddress; delete [] m_aguidCNs; } inline const GUID& CTopologyData::GetEnterprise() const { return(m_guidEnterprise); } inline const GUID& CTopologyData::GetSite() const { return(m_guidSite); } inline BOOL CTopologyData::GetAddresses( OUT DWORD * pcbAddress, OUT const unsigned char ** pblobAddress, OUT DWORD * pnCNs, OUT const GUID ** paguidCNs) const { if (m_cbAddress > 0 && m_blobAddress != NULL && m_nCNs > 0 && m_aguidCNs != NULL) { *pcbAddress = m_cbAddress; *pblobAddress = m_blobAddress; *pnCNs = m_nCNs; *paguidCNs = m_aguidCNs; return(TRUE); } else { return(FALSE); } } //*********************************************************** // // class CServerTopologyData : public CTopologyData // //*********************************************************** class CServerTopologyData : public CTopologyData { public: CServerTopologyData(); ~CServerTopologyData(); HRESULT Load(); HRESULT CompareUpdateServerAddress( IN OUT CAddressList *pIPAddressList, OUT BOOL *pfResolved ) ; bool GetDSServers( OUT unsigned char ** pblobDSServers, OUT DWORD * pcbDSServers ) const; void GetAddressesSorted( OUT IPADDRESS ** paIPAddress, OUT GUID ** paguidIPCN, OUT DWORD * pnIP ) const; private: HRESULT MatchOneAddress( IN CAddressList *pAddressList, IN TA_ADDRESS *pUnfoundAddress, IN DWORD dwAddressLen, IN DWORD dwAddressType, OUT BOOL *pfResolved ) ; HRESULT FindOrphanDsAddress( IN CAddressList *pAddressList, IN DWORD dwAddressLen, IN DWORD dwAddressType, OUT TA_ADDRESS **pUnfoundAddress, OUT BOOL *pfResolved ) ; }; inline CServerTopologyData::CServerTopologyData() { } inline CServerTopologyData::~CServerTopologyData() { } #endif
/* Generated by RuntimeBrowser. */ @protocol SUTabBarControllerDelegate <UITabBarControllerDelegate> @optional - (SUViewController *)tabBarController:(SUTabBarController *)arg1 rootViewControllerForSection:(SUSection *)arg2; - (bool)tabBarController:(SUTabBarController *)arg1 shouldShowSection:(SUSection *)arg2; - (SUViewController *)tabBarController:(SUTabBarController *)arg1 viewControllerForContext:(SUViewControllerContext *)arg2; @end
struct Chubagwonzer : public Chub, public Thread, public Component, public Timer { struct Gwonzero : public Component { signed char vale; Gwonzero(): vale(0) {} void paint(Graphics &g) { g.setColour (Colours::green); int yc = getHeight()/2; int yh = vale * getHeight()/ 256; if (vale > 0) g.fillRect (0,yc-yh, getWidth(), yh); else g.fillRect (0,yc, getWidth(), -yh); } void setVale(signed char v) { vale = v; repaint(); } }; struct Gwonzedo : public Gwonzero { Gwonzedo() : Gwonzero() {} void paint(Graphics &g) { int yc = getHeight()/8; g.setColour (Colours::orange); for (int i =0; i<8; i++) { if (vale&(1<<i)) g.fillRect (0,yc*i, getWidth(), yc); } } }; Gwonzero* gwonzers[8]; virtual void gwonzINIT(int id) { for (int i =0;i<4;i++) { gwonzers[i] = new Gwonzero(); addAndMakeVisible(gwonzers[i]); } for (int i =4;i<8;i++) { if (id==0x7777) gwonzers[i] = new Gwonzedo(); else gwonzers[i] = new Gwonzero(); addAndMakeVisible(gwonzers[i]); } } Chubagwonzer(): Thread("GwonzerThread") { if (chubINIT()) { setSize(400,100); startThread(); startTimer (20); } } ~Chubagwonzer(){ for (int i =0;i<8;i++) delete(gwonzers[i]); //printf("stopt\n"); stopThread(100); wait(100); chubCLOZ(); //delete[8](gwonzers); } void run() { chubRUN(); //printf("stoprunt\n"); } void resized() { for (int i = 0; i < 8; i++) gwonzers[i]->setBounds(getWidth()*i/8,0,getWidth()/8,getHeight()); } void timerCallback () { for (int i = 0; i < 8; i++) gwonzers[i]->setVale(gwonz[i]); } bool chubShouldEnd(){return threadShouldExit();} void chubCALL() {} static void showGwonz() { Chubagwonzer chb; DialogWindow::showModalDialog ("Spit Gwonz", &chb, nullptr, Colours::black, true, true, true); } };
<filename>code/libbluray/src/file/dl.h /* * This file is part of libbluray * Copyright (C) 2009-2010 Obliter0n * Copyright (C) 2009-2010 <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef DL_H_ #define DL_H_ #include "util/attributes.h" #include <stdint.h> /* * function pointer types */ #ifdef __cplusplus typedef void (*fptr_void)(...); typedef int (*fptr_int)(...); typedef int32_t (*fptr_int32)(...); typedef void* (*fptr_p_void)(...); #else typedef void (*fptr_void)(); typedef int (*fptr_int)(); typedef int32_t (*fptr_int32)(); typedef void* (*fptr_p_void)(); #endif /* * Macro to call function without return value */ #define DL_CALL(lib,func,...) \ do { \ fptr_p_void fptr; \ *(void **)(&fptr) = dl_dlsym(lib, #func); \ if (fptr) { \ fptr(__VA_ARGS__); \ } \ } while (0) // We don't bother aliasing dlopen to dlopen_posix, since only one // of the .C files will be compiled and linked, the right one for the // platform. // Note the dlopen takes just the name part. "aacs", internally we // translate to "libaacs.so" "libaacs.dylib" or "aacs.dll". BD_PRIVATE void *dl_dlopen ( const char* path, const char *version ); BD_PRIVATE void *dl_dlsym ( void* handle, const char* symbol ); BD_PRIVATE int dl_dlclose ( void* handle ); /* * Installation path of currently running libbluray.so * returns NULL if unknown. * * This function is used to help finding libbluray.jar if location * is not given in LIBBLURAY_CP environment variable. */ BD_PRIVATE const char *dl_get_path(void); #endif /* DL_H_ */
#ifndef IOPool_Streamer_StreamerFileWriter_h #define IOPool_Streamer_StreamerFileWriter_h #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "IOPool/Streamer/interface/StreamerOutputFile.h" #include "IOPool/Streamer/interface/InitMsgBuilder.h" #include "IOPool/Streamer/interface/EventMsgBuilder.h" #include "FWCore/Utilities/interface/propagate_const.h" #include "IOPool/Streamer/interface/InitMessage.h" #include "IOPool/Streamer/interface/EventMessage.h" #include "IOPool/Streamer/interface/MsgTools.h" #include <iostream> #include <vector> #include <memory> #include <string> namespace edm { class ParameterSetDescription; class StreamerFileWriter { public: explicit StreamerFileWriter(edm::ParameterSet const& ps); explicit StreamerFileWriter(std::string const& fileName); ~StreamerFileWriter(); static void fillDescription(ParameterSetDescription& desc); void doOutputHeader(InitMsgBuilder const& init_message); void doOutputHeader(InitMsgView const& init_message); void doOutputEvent(EventMsgBuilder const& msg); void doOutputEvent(EventMsgView const& msg); void start(){} void stop(){}; uint32 get_adler32() const { return stream_writer_->adler32();} private: edm::propagate_const<std::unique_ptr<StreamerOutputFile>> stream_writer_; }; } #endif
/* Copyright (c) <2003-2019> <<NAME>, Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #ifndef __D_SHAPE_H__ #define __D_SHAPE_H__ #include "ndCollisionStdafx.h" class ndBody; class ndShape; class ndShapeBox; class ndShapeNull; class ndShapeConvex; class ndShapeSphere; class ndShapeCapsule; class ndContactPoint; class ndShapeCompound; class ndRayCastNotify; class ndShapeInstance; class ndShapeStaticMesh; class ndShapeConvexPolygon; class ndShapeDebugCallback; #ifdef _DEBUG // #define DG_DEBUG_AABB #endif enum ndShapeID { // do not change the order of these enum m_sphereCollision = 0, m_capsuleCollision, //m_cylinderCollision, //m_chamferCylinderCollision, m_boxCollision, //m_coneCollision, m_convexHull, // this must be the last convex shape ID // non convex collisions. m_nullCollision, m_boundingBoxHierachy, //m_compoundCollision, //m_heightField, //m_deformableClothPatch, //m_deformableSolidMesh, //m_userMesh, //m_sceneCollision, //m_compoundFracturedCollision, // these are for internal use only //m_contactCloud, m_polygonCollision, //m_lumpedMassCollision }; class ndShapeMaterial { public: ndShapeMaterial() { memset(this, 0, sizeof(ndShapeMaterial)); } dInt64 m_userId; union { void* m_userData; dUnsigned64 m_alignPad; }; union { dUnsigned64 m_intData; dFloat32 m_floatData; } m_userParam[6]; }; D_MSV_NEWTON_ALIGN_32 class ndShapeInfo { public: struct dgBoxData { dFloat32 m_x; dFloat32 m_y; dFloat32 m_z; }; struct dgSphereData { dFloat32 m_radius; }; struct dgCylinderData { dFloat32 m_radio0; dFloat32 m_radio1; dFloat32 m_height; }; struct dgCapsuleData { dFloat32 m_radio0; dFloat32 m_radio1; dFloat32 m_height; }; struct dgConeData { dFloat32 m_r; dFloat32 m_height; }; struct dgChamferCylinderData { dFloat32 m_r; dFloat32 m_height; }; struct dgConvexHullData { dInt32 m_vertexCount; dInt32 m_strideInBytes; dInt32 m_faceCount; dVector* m_vertex; }; struct dgConvexModifierData { ndShape* m_child; }; struct dgCoumpountCollisionData { dInt32 m_chidrenCount; //dgCollision** m_chidren; }; struct dgCollisionBvhData { dInt32 m_vertexCount; dInt32 m_indexCount; }; struct dgDeformableMeshData { dInt32 m_vertexCount; dInt32 m_triangleCount; dInt32 m_vertexStrideInBytes; dUnsigned16* m_indexList; dFloat32* m_vertexList; }; struct dgHeightMapCollisionData { dInt32 m_width; dInt32 m_height; dInt32 m_gridsDiagonals; dInt32 m_elevationDataType; // 0 = 32 bit floats, 1 = unsigned 16 bit intergers dFloat32 m_verticalScale; dFloat32 m_horizonalScale_x; dFloat32 m_horizonalScale_z; void* m_elevation; dInt8* m_atributes; }; struct dgSceneData { dInt32 m_childrenProxyCount; }; dMatrix m_offsetMatrix; ndShapeMaterial m_shapeMaterial; ndShapeID m_collisionType; union { dgBoxData m_box; dgConeData m_cone; dgSphereData m_sphere; dgCapsuleData m_capsule; dgCylinderData m_cylinder; dgChamferCylinderData m_chamferCylinder; dgConvexHullData m_convexHull; dgDeformableMeshData m_deformableMesh; dgConvexModifierData m_convexModifierData; dgCoumpountCollisionData m_compoundCollision; dgCollisionBvhData m_bvhCollision; dgHeightMapCollisionData m_heightFieldCollision; dgSceneData m_sceneCollision; dFloat32 m_paramArray[32]; }; } D_GCC_NEWTON_ALIGN_32; D_MSV_NEWTON_ALIGN_32 class ndShape: public dClassAlloc { public: const ndShape* AddRef() const; dInt32 GetRefCount() const; virtual dInt32 Release() const; virtual ndShapeBox* GetAsShapeBox() { return nullptr; } virtual ndShapeSphere* GetAsShapeSphere() { return nullptr; } virtual ndShapeCapsule* GetAsShapeCapsule() { return nullptr; } virtual ndShapeCompound* GetAsShapeCompound() { return nullptr; } virtual ndShapeNull* GetAsShapeNull() { return nullptr; } virtual ndShapeConvexPolygon* GetAsShapeAsConvexPolygon() { return nullptr; } virtual ndShapeConvex* GetAsShapeConvex() { return nullptr; } virtual ndShapeStaticMesh* GetAsShapeStaticMeshShape() { return nullptr; } virtual dInt32 GetConvexVertexCount() const; dVector GetObbSize() const; dVector GetObbOrigin() const; dFloat32 GetUmbraClipSize() const; D_COLLISION_API virtual void MassProperties(); virtual void DebugShape(const dMatrix& matrix, ndShapeDebugCallback& debugCallback) const = 0; virtual ndShapeInfo GetShapeInfo() const; virtual dFloat32 GetVolume() const = 0; virtual dFloat32 GetBoxMinRadius() const = 0; virtual dFloat32 GetBoxMaxRadius() const = 0; virtual void CalcAABB(const dMatrix& matrix, dVector& p0, dVector& p1) const = 0; virtual dVector SupportVertex(const dVector& dir, dInt32* const vertexIndex) const = 0; virtual dVector SupportVertexSpecialProjectPoint(const dVector& point, const dVector& dir) const = 0; virtual dVector SupportVertexSpecial(const dVector& dir, dFloat32 skinSkinThickness, dInt32* const vertexIndex) const = 0; virtual dInt32 CalculatePlaneIntersection(const dVector& normal, const dVector& point, dVector* const contactsOut) const = 0; virtual dVector CalculateVolumeIntegral(const dMatrix& globalMatrix, const dVector& globalPlane, const ndShapeInstance& parentScale) const = 0; virtual dFloat32 RayCast(ndRayCastNotify& callback, const dVector& localP0, const dVector& localP1, const ndBody* const body, ndContactPoint& contactOut) const = 0; virtual dMatrix CalculateInertiaAndCenterOfMass(const dMatrix& alignMatrix, const dVector& localScale, const dMatrix& matrix) const; virtual dFloat32 CalculateMassProperties(const dMatrix& offset, dVector& inertia, dVector& crossInertia, dVector& centerOfMass) const; D_COLLISION_API virtual void Save(nd::TiXmlElement* const xmlNode, const char* const assetPath, dInt32 nodeid) const; protected: D_COLLISION_API ndShape(ndShapeID id); D_COLLISION_API ndShape (const ndShape& source); D_COLLISION_API virtual ~ndShape(); dVector m_inertia; dVector m_crossInertia; dVector m_centerOfMass; dVector m_boxSize; dVector m_boxOrigin; mutable dAtomic<dInt32> m_refCount; ndShapeID m_collisionId; static dVector m_flushZero; } D_GCC_NEWTON_ALIGN_32; inline dInt32 ndShape::GetConvexVertexCount() const { return 0; } inline const ndShape* ndShape::AddRef() const { m_refCount.fetch_add(1); return this; } inline dInt32 ndShape::Release() const { dInt32 count = m_refCount.fetch_add(-1); dAssert(count >= 1); if (count == 1) { delete this; } return count; } inline dInt32 ndShape::GetRefCount() const { return m_refCount.load(); } inline dFloat32 ndShape::CalculateMassProperties(const dMatrix& offset, dVector& inertia, dVector& crossInertia, dVector& centerOfMass) const { dAssert(0); return 0; } inline dMatrix ndShape::CalculateInertiaAndCenterOfMass(const dMatrix& alignMatrix, const dVector& localScale, const dMatrix& matrix) const { dAssert(0); return dGetZeroMatrix(); } inline dVector ndShape::GetObbOrigin() const { return m_boxOrigin; } inline dVector ndShape::GetObbSize() const { return m_boxSize; } inline dFloat32 ndShape::GetUmbraClipSize() const { return dFloat32(3.0f) * GetBoxMaxRadius(); } inline void ndShape::Save( nd::TiXmlElement* const xmlNode, const char* const assetPath, dInt32 nodeid ) const { dAssert(0); } #endif
#ifndef DMA_HANDLER_INCLUDE #define DMA_HANDLER_INCLUDE #if 0 struct urpc_comm; struct urpc_peer; union urpc_mb; void init_dma_handler(struct urpc_comm *); int64_t dhq_cmd_in(struct urpc_comm *, union urpc_mb *, int); int dhq_cmd_check_done(struct urpc_comm *, int); int dhq_dma_submit(struct urpc_comm *, int); int dhq_cmd_handle(struct urpc_peer *, int); int dhq_in_flight(struct urpc_comm *uc); #else #include <errno.h> #include <signal.h> #include <stdint.h> #include <sys/types.h> #include <unistd.h> #include "urpc_common.h" #include "ve_inst.h" // Flow: // 1. insert decoded cmd // 2. check handles if DMA done // 3. submit to DMA -> link to handle (optimization: coalesce, multiple reqs: same handle) // 4. call handler // // Insert and submit are separate because the submit can fail (EAGAIN). // // slot +--- // 0 | <- out (last submitted) // 1 | <- dma_done (last cmd with payload transfered) // 2 | // 3 | <- dma_submit (last cmd with payload transfer over dma requested) // 4 | <- in (last inserted cmd) // 5 | // +--- // static inline void init_dma_handler(urpc_comm_t *uc) { dma_handler_t *dh = &uc->dhq; dh->in = dh->submit = dh->done = dh->out = -1; dh->in_req = -1; for (int i = 0; i < URPC_LEN_MB; i++) dh->coalesced[i] = 0; } static inline int dhq_in_flight(urpc_comm_t *uc) { int res; res = uc->dhq.in - uc->dhq.out; if (res < 0) res += URPC_LEN_MB; return res; } static inline int64_t dhq_cmd_in(urpc_comm_t *uc, urpc_mb_t *m, int is_recv) { dma_handler_t *dh = &uc->dhq; // incoming slot was free in the mb list, so it must be available here, too dh->in_req++; dh->in = REQ2SLOT(dh->in_req); dh->cmd[dh->in].u64 = m->u64; dprintf("dhq_cmd_in() %s cmd=%d req=%ld in=%d submit=%d done=%d out=%d\n", is_recv ? "recv" : "send", m->c.cmd, dh->in_req, dh->in, dh->submit, dh->done, dh->out); dprintf("dhq_cmd_in cmd=%u offs=%u len=%u\n", dh->cmd[dh->in].c.cmd, dh->cmd[dh->in].c.offs, dh->cmd[dh->in].c.len); return dh->in_req; } static inline void report_exception_and_signal(dma_handler_t *dh, int slot, int exc) { // 0x8000: Memory protection exception // 0x4000: Missing page exception // 0x2000: Missing space exception // 0x1000: Memory access exception // 0x0800: I/O access exception urpc_mb_t *m = &dh->cmd[slot]; pid_t pid = getpid(); eprintf("DMA encountered exception, rc=0x%x" " slot=%d cmd=%d offs=%ld len=%ld\n", exc, slot, m->c.cmd, m->c.offs, m->c.len); if (exc & 0x8000) { eprintf("memory protection exception\n"); kill(pid, SIGBUS); } else if (exc & 0x4000) { eprintf("memory protection exception\n"); kill(pid, SIGBUS); } else if (exc & 0x2000) { eprintf("missing space exception\n"); kill(pid, SIGBUS); } else if (exc & 0x1000) { eprintf("memory access exception\n"); kill(pid, SIGSEGV); } else if (exc & 0x0800) { eprintf("I/O access exception\n"); kill(pid, SIGIOT); } kill(pid, SIGILL); } static inline int dhq_cmd_check_done(urpc_comm_t *uc, int is_recv) { int i, ncheck, rc, slot, start; dma_handler_t *dh = &uc->dhq; // check if any DMA handles have finished in the mean time // ... from dma_done + 1 to dma_submit ncheck = dh->submit - dh->done; if (dh->submit < dh->done) ncheck += URPC_LEN_MB; if (ncheck) dprintf("dhq_cmd_check_done() %s ncheck=%d\n", is_recv ? "recv" : "send", ncheck); for (i = 0, start = dh->done + 1; i < ncheck; i++) { slot = REQ2SLOT(start + i); urpc_mb_t *m = &dh->cmd[slot]; if (m->c.len == 0) { // this one had no DMA, dh->done = slot; continue; } if (dh->coalesced[slot]) { dh->done = slot; continue; } // check DMA handle rc = ve_dma_poll(&dh->handle[slot]); dprintf("dhq_cmd_check_done() %s i=%d ve_dma_poll returned %d\n", is_recv ? "recv" : "send", i, rc); if (rc == -EAGAIN) { dprintf("dhq_cmd_check_done() %s i=%d ve_dma_poll returned %d\n", is_recv ? "recv" : "send", i, rc); break; // not done, yet, no further checking } else if (rc == 0) { // done dh->done = slot; continue; } else { // exception happened! // raise signal and die report_exception_and_signal(dh, slot, rc); break; } } if (ncheck) dprintf("dhq_cmd_check_done() %s in=%d submit=%d done=%d out=%d\n", is_recv ? "recv" : "send", dh->in, dh->submit, dh->done, dh->out); return ncheck; } /** * @brief Submit as many decoded DMA payload transfer requests as possible. * * @param uc urpc communicator * @param is_recv flag, true if reading/receiving from VH */ static inline int dhq_dma_submit(urpc_comm_t *uc, int is_recv) { int i, ncheck, rc, size, slot, start; uint64_t src, dst; uint64_t csrc = 0, cdst = 0; int csize = 0, ncoal = 0, cslot, coal_stop; dma_handler_t *dh = &uc->dhq; // check if any DMA handles have finished in the mean time // ... from submit + 1 to in ncheck = dh->in - dh->submit; if (dh->in < dh->submit) ncheck += URPC_LEN_MB; if (ncheck) dprintf("dhq_dma_submit() %s ncheck=%d\n", is_recv ? "recv" : "send", ncheck); // TODO: implement coalescing transfers! for (i = 0, start = dh->submit + 1; i < ncheck; i++) { slot = REQ2SLOT(start + i); urpc_mb_t *m = &dh->cmd[slot]; if (m->c.len == 0) { // this one has no DMA, move ahead dh->submit = slot; continue; } if (is_recv) { dst = uc->mirr_data_vehva + m->c.offs; src = uc->shm_data_vehva + m->c.offs; } else { src = uc->mirr_data_vehva + m->c.offs; dst = uc->shm_data_vehva + m->c.offs; } size = m->c.len; if (m->c.offs + size > URPC_BUFF_LEN) { eprintf("DMA req out of bounds! offs=%d size=%ld\n", m->c.offs, size); } if (csize == 0) { // this is the first field of possible coalescing csize = size; csrc = src; cdst = dst; dh->coalesced[slot] = 0; coal_stop = 0; cslot = slot; dprintf("coalesce start [%3d] src=%lx dst=%lx len=%u\n", slot, src, dst, size); // // Why is this L1 cache clear needed? Results are wrong if not done! // (actually it doesn't solve the issue, just shifts it for later) // Testing: repeat 'test_callasync 500' ve_inst_fenceC1(); ve_inst_fenceC2(); } else { if (src == csrc + csize && dst == cdst + csize && csize + size <= URPC_MAX_COALESCED_SIZE) { csize += size; dh->coalesced[slot] = 1; ncoal++; cslot = REQ2SLOT(cslot + 1); dprintf("coalesce add [%3d] src=%lx dst=%lx len=%u\n", slot, src, dst, size); ve_inst_fenceC1(); ve_inst_fenceC2(); } else { coal_stop = 1; dh->coalesced[slot] = 0; } } if (ncoal == URPC_MAX_COALESCED_REQS || coal_stop == 1) { // submit! dprintf("coalesce commit [%3d] src=%lx dst=%lx len=%u -> stop\n", slot, csrc, cdst, csize); rc = ve_dma_post(cdst, csrc, csize, &dh->handle[slot]); if (rc != 0) dprintf("dhq_dma_submit() %s i=%d ve_dma_post returned %d\n", is_recv ? "recv" : "send", i, rc); if (rc == -EAGAIN) break; dh->submit = slot; csrc = cdst = 0; csize = 0; if (slot != cslot) { // starting new coalescing csrc = src; cdst = dst; csize = size; coal_stop = 0; cslot = slot; ve_inst_fenceC1(); ve_inst_fenceC2(); } } } if (csize) { dprintf("coalesce commit [%3d] src=%lx dst=%lx len=%u -> end\n", slot, csrc, cdst, csize); rc = ve_dma_post(cdst, csrc, csize, &dh->handle[cslot]); if (rc != 0) dprintf("dhq_dma_submit() %s i=%d ve_dma_post returned %d\n", is_recv ? "recv" : "send", i, rc); if (rc == 0) { dh->submit = cslot; csrc = cdst = 0; csize = 0; } } if (ncheck) dprintf("dhq_dma_submit() %s in=%d submit=%d done=%d out=%d\n", is_recv ? "recv" : "send", dh->in, dh->submit, dh->done, dh->out); return ncheck; } /** * @brief Call handler on commands which have received their payload. * * @param uc urpc communicator * @return number of handled requests * */ static inline int dhq_cmd_handle(urpc_peer_t *up, int is_recv) { int i, ncheck, rc, slot, start; uint64_t src, dst; int64_t req; void *payload; size_t plen; urpc_comm_t *uc; dma_handler_t *dh; transfer_queue_t *tq; if (is_recv) uc = &up->recv; else uc = &up->send; dh = &uc->dhq; tq = uc->tq; // check if any DMA handles have finished in the mean time // ... from out + 1 to done ncheck = dh->done - dh->out; if (dh->done < dh->out) ncheck += URPC_LEN_MB; if (ncheck) dprintf("dhq_cmd_handle() %s ncheck=%d\n", is_recv ? "recv" : "send", ncheck); for (i = 0, start = REQ2SLOT(dh->out + 1); i < ncheck; i++) { slot = REQ2SLOT(start + i); urpc_mb_t *m = &dh->cmd[slot]; req = dh->in_req - ((int64_t)dh->in - (int64_t)slot); if (dh->in < slot) req -= URPC_LEN_MB; if (m->c.len > 0) { payload = (void *)((char *)uc->mirr_data_buff + m->c.offs); plen = m->c.len; } else { payload = NULL; plen = 0; } if (is_recv) { // // call handler // dprintf("dhq_cmd_handle() recv before handler for cmd %d\n", m->c.cmd); urpc_handler_func func = up->handler[m->c.cmd]; if (func) { rc = func(up, m, req, payload, plen); dprintf("dhq_cmd_handle() recv after handler for cmd %d\n", m->c.cmd); if (rc) { eprintf("Warning: RPC handler %d returned %d\n", m->c.cmd, rc); // TODO: more error handling } } dh->out = slot; urpc_slot_done(tq, slot, m); } else { // // submit command to tq // dprintf("dhq_cmd_handle() send submitting to URPC " "cmd=%d offs=%d len=%d\n", m->c.cmd, m->c.offs, m->c.len); dh->out = slot; urpc_put_cmd(up, m); } } if (ncheck) dprintf("dhq_cmd_handle() %s in=%d submit=%d done=%d out=%d\n", is_recv ? "recv" : "send", dh->in, dh->submit, dh->done, dh->out); return ncheck; } #endif #endif
<filename>heekscam-read-only/src/ExtrudedObj.h #pragma once #include "HeeksObj.h" template<typename T> class ExtrudedObj : public T { public: double m_thickness; double m_extrusion_vector[3]; ~ExtrudedObj(void); ExtrudedObj(void) { m_thickness = 0.0; m_extrusion_vector[0] = 0.0; m_extrusion_vector[1] = 0.0; m_extrusion_vector[2] = 0.0; } ExtrudedObj(const ExtrudedObj& e); const ExtrudedObj& operator=(const ExtrudedObj &b); // HeeksObj's virtual functions void ModifyByMatrix(const double* m); void CopyFrom(const HeeksObj* object){ operator=(*((ExtrudedObj*)object)); } HeeksObj* MakeACopyWithID(); bool IsDifferent(HeeksObj* other); void WriteBaseXML(TiXmlElement *element); void ReadBaseXML(TiXmlElement* element); }; template<typename T> ExtrudedObj<T>::ExtrudedObj(const ExtrudedObj& e) { operator=(e); } template < typename T > ExtrudedObj<T>::~ExtrudedObj(){ } template < typename T > const ExtrudedObj<T>& ExtrudedObj<T>::operator=(const ExtrudedObj<T> &b){ T::operator = (b); m_thickness = b.m_thickness; m_extrusion_vector[0] = b.m_extrusion_vector[0]; m_extrusion_vector[1] = b.m_extrusion_vector[1]; m_extrusion_vector[2] = b.m_extrusion_vector[2]; return *this; } template < typename T > HeeksObj* ExtrudedObj<T>::MakeACopyWithID() { ExtrudedObj<T>* pnew = (ExtrudedObj<T>*)T::MakeACopyWithID(); pnew->m_thickness = m_thickness; pnew->m_extrusion_vector[0] = m_extrusion_vector[0]; pnew->m_extrusion_vector[1] = m_extrusion_vector[1]; pnew->m_extrusion_vector[2] = m_extrusion_vector[2]; return (HeeksObj*)pnew; } template < typename T > bool ExtrudedObj<T>::IsDifferent(HeeksObj *other) { ExtrudedObj<T>* eobj = (ExtrudedObj<T>*)other; if (fabs(eobj->m_thickness - m_thickness) > wxGetApp().m_geom_tol) return true; for (int i = 0; i<3; i++) { if (fabs(eobj->m_extrusion_vector[i] - m_extrusion_vector[i]) > 0.000000000001) return true; } return T::IsDifferent(other); } template < typename T > void ExtrudedObj<T>::ModifyByMatrix(const double* m){ gp_Trsf mat = make_matrix(m); gp_Vec v(m_extrusion_vector[0], m_extrusion_vector[1], m_extrusion_vector[2]); v.Transform(mat); extract(v, m_extrusion_vector); } template < typename T > void ExtrudedObj<T>::WriteBaseXML(TiXmlElement *element) { element->SetDoubleAttribute("thickness", m_thickness); element->SetDoubleAttribute("extruX", m_extrusion_vector[0]); element->SetDoubleAttribute("extruY", m_extrusion_vector[1]); element->SetDoubleAttribute("extruZ", m_extrusion_vector[2]); T::WriteBaseXML(element); } template < typename T > void ExtrudedObj<T>::ReadBaseXML(TiXmlElement* pElem) { pElem->Attribute("thickness", &m_thickness); pElem->Attribute("extruX", &m_extrusion_vector[0]); pElem->Attribute("extruY", &m_extrusion_vector[1]); pElem->Attribute("extruZ", &m_extrusion_vector[2]); T::ReadBaseXML(pElem); }
#pragma once #include "TArc/Controls/ControlProxy.h" #include "TArc/Controls/CommonStrings.h" #include "TArc/Utils/QtConnections.h" #include "TArc/Qt/QtString.h" #include <QDoubleSpinBox> #include <QSpinBox> #include <QKeyEvent> #include <QLineEdit> #include <QToolTip> namespace DAVA { template <typename TBase, typename TEditableType> class BaseSpinBox : public ControlProxyImpl<TBase> { public: enum BaseFields : uint32 { Value, IsReadOnly, IsEnabled, IsVisible, Range, ShowSpinArrows, }; using BaseParams = typename ControlProxyImpl<TBase>::BaseParams; BaseSpinBox(const BaseParams& params, const ControlDescriptor& descriptor, DataWrappersProcessor* wrappersProcessor, Reflection model, QWidget* parent); BaseSpinBox(const BaseParams& params, const ControlDescriptor& descriptor, ContextAccessor* accessor, Reflection model, QWidget* parent); protected: bool event(QEvent* e) override; void UpdateControl(const ControlDescriptor& changedFields) override; void SetupSpinBoxBase(); void UpdateRange(); void ValueChanged(TEditableType val); void ToEditingState(); void ToInvalidState(); void ToValidState(); virtual bool FromText(const QString& input, TEditableType& output) const = 0; virtual QString ToText(const TEditableType output) const = 0; virtual bool IsEqualValue(TEditableType v1, TEditableType v2) const = 0; virtual QValidator::State TypeSpecificValidate(const QString& str) const = 0; void fixup(QString& str) const override; QValidator::State validate(QString& input, int& pos) const override; protected: QtConnections connections; QString noValueString = QString(MultipleValuesString); enum class ControlState { ValidValue, InvalidValue, Editing }; Stack<ControlState> stateHistory; QAbstractSpinBox::ButtonSymbols validStateButtonSymbol = QAbstractSpinBox::UpDownArrows; private: QString textFromValue(TEditableType val) const override; TEditableType valueFromText(const QString& text) const override; void focusInEvent(QFocusEvent* event) override; void focusOutEvent(QFocusEvent* event) override; }; } // namespace DAVA
<reponame>dch0ph/libcmatrix<filename>include/lcm_basethreads.h<gh_stars>0 #ifndef lcm_basethreads_h_ #define lcm_basethreads_h_ #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif //Required for Failed #include "basedefs.h" #include "Warnings.h" #include "timer.h" namespace libcmatrix { #ifdef LCM_REENTRANT const bool ThreadingActive=true; #else const bool ThreadingActive=false; #endif template<bool =true> class Mutex { public: void acquire() {} void release() {} }; template<> class Mutex<true> { public: static Warning<> mutexnotfunctional_warning; #ifdef HAVE_PTHREAD_H Mutex() { pthread_mutex_init(&lock_,NULL); } ~Mutex() { pthread_mutex_destroy(&lock_); } void acquire() { pthread_mutex_lock(&lock_); } void release() { pthread_mutex_lock(&lock_); } pthread_mutex_t& operator()() { return lock_; } const pthread_mutex_t& operator()() const { return lock_; } private: pthread_mutex_t lock_; #else Mutex() { mutexnotfunctional_warning.raise(); } void acquire() {} void release() {} #endif }; //automatically acquires lock and releases when destroyed (exception safe) template<bool Active =true> class MutexLock { public: MutexLock(Mutex<Active>& lockv) : lock_(lockv) { lock_.acquire(); } ~MutexLock() { lock_.release(); } private: Mutex<Active>& lock_; }; //empty class when not locking template<> class MutexLock<false> { public: MutexLock(Mutex<false>&) {} }; extern "C" { typedef void (*P_DESTFUNC)(void*); void* worker(void *); } #ifdef LCM_REENTRANT template<class T> class key_holder { pthread_key_t key; public: key_holder(P_DESTFUNC kill_func =0) { if (int errcode=pthread_key_create(&key,kill_func)) throw Failed(strerror(errcode)); } key_holder(P_DESTFUNC kill_func,T* ivalue) { if (int errcode=pthread_key_create(&key,kill_func)) throw Failed(strerror(errcode)); set(ivalue); } void set(T* value) { if (int errcode=pthread_setspecific(key,value)) throw Failed(strerror(errcode)); } T* get() const { return (T*)pthread_getspecific(key); } ~key_holder() { pthread_key_delete(key); } // NB cannot call destructors! Should only be called once }; #else template<class T> class key_holder { T* value; P_DESTFUNC kill_funcp; public: explicit key_holder(P_DESTFUNC kill_func =0,T* ivalue =NULL) : value(ivalue),kill_funcp(kill_func) {} void set(T* ivalue) { value=ivalue; } T* get() const { return value; } ~key_holder() { if (kill_funcp && value) (*kill_funcp)((void*)value); } // NB cannot call destructors! Should only be called once }; #endif typedef void (*P_THREADFUNC)(size_t,size_t,size_t); struct BaseThreadFunction { virtual ~BaseThreadFunction() {} virtual void operator()(size_t,size_t,size_t) const =0; }; class ThreadFunction : public BaseThreadFunction { public: explicit ThreadFunction(P_THREADFUNC func_) : func(func_) { if (!func) throw InvalidParameter("ThreadFunction(): NULL function"); } void operator()(size_t st, size_t en, size_t nthr) const { (*func)(st,en,nthr); } private: P_THREADFUNC func; }; #ifndef LCM_PARALLEL_DEFAULT_VERBOSE #ifdef NDEBUG #define LCM_PARALLEL_DEFAULT_VERBOSE 0 #else #define LCM_PARALLEL_DEFAULT_VERBOSE 1 #endif #endif class base_parallel_controller { public: base_parallel_controller(int verbosev =LCM_PARALLEL_DEFAULT_VERBOSE) : id_(0), verbose_(verbosev), log(NULL) {} ~base_parallel_controller(); int get_thread_num() const { return id_; } bool ammaster() const { return (id_==0); } int get_processors() const { return nprocs_; } //!< get number of processors int get_workers() const { return nworkers_; } //!< get number of actual workers void verbose(int verbosev) { verbose_=verbosev; } static Warning<> logopenfailed_warning; //!< failed to open log file protected: size_t nprocs_; size_t nworkers_; int id_; int verbose_; void error(const char* mess) const { writelog(mess); throw InternalError(mess); } void openlog(const char*); void writelog(const char*) const; void closelog(); double time() const { return timer_(); } private: FILE* log; timer<WallTimer> timer_; }; } //namespace libcmatrix #endif
#ifndef _AICOREDOCUMENTACTION_H_ #define _AICOREDOCUMENTACTION_H_ /* * Name: AICoreDocumentAction.h * $Revision: 1 $ * Author: * Date: * Purpose: Adobe Illustrator Actions defined in the core. * * ADOBE SYSTEMS INCORPORATED * Copyright 1986-2007 Adobe Systems Incorporated. * All rights reserved. * * NOTICE: Adobe permits you to use, modify, and distribute this file * in accordance with the terms of the Adobe license agreement * accompanying it. If you have received this file from a source other * than Adobe, then your use, modification, or distribution of it * requires the prior written permission of Adobe. * */ #ifndef __AIActionManager_h__ #include "AIActionManager.h" #endif /** @ingroup Actions Makes a new document. @param #kAINewDocumentNameKey The document title string. Optional, default is "untitled-n" (with a unique number). @param #kAINewDocumentColorModelKey The color model to use. Allowed values are \c #kDocRGBColor and \c #kDocCMYKColor. @param #kAINewDocumentSettingsFileKey Path to the profile used to create the new document (Unicode string) @param #kAINewDocumentWidthKey The page width in points (real). @param #kAINewDocumentHeightKey The page height in points (real). @param #kAINewDocumentRulerUnitsKey The ruler units, an \c #AIDocumentRulerUnitValue. @param #kAINewDocumentRasterResolutionKey The document raster resolution. (integer) @param #kAINewDocumentPreviewModeKey The preview mode for the document. (integer) @param #kAINewDocumentTransparencyGridKey True to show the transparency grid for the document. */ #define kAINewDocumentAction "adobe_newDocument" /** Parameter to \c #kAINewDocumentAction. The document title string. Optional, default is "untitled-n" (with a unique number).*/ const ActionParamKeyID kAINewDocumentNameKey = 'name'; // string /** Parameter to \c #kAINewDocumentAction. The color model to use. Allowed values are \c #kDocRGBColor and \c #kDocCMYKColor. */ const ActionParamKeyID kAINewDocumentColorModelKey = 'colr'; // integer /** Parameter to \c #kAINewDocumentAction. Unicode string containing the path to the new document profile file to use. These files are found in folders \c #kAIUserWritableStartupFileFolderType and \c #kAIRequiredStartupProfilesFolderType. */ const ActionParamKeyID kAINewDocumentSettingsFileKey = 'setf'; // string /** The page width in points (real). */ const ActionParamKeyID kAINewDocumentWidthKey = 'wdth'; // real /** Parameter to \c #kAINewDocumentAction. The page height in points (real). */ const ActionParamKeyID kAINewDocumentHeightKey = 'heit'; // real /** Parameter to \c #kAINewDocumentAction. The ruler units, an \c #AIDocumentRulerUnitValue. */ const ActionParamKeyID kAINewDocumentRulerUnitsKey = 'rulr'; // integer /** Parameter to \c #kAINewDocumentAction. The document raster resolution, an integer for the PPI value: Screen(72), Medium(150), or High(300). */ const ActionParamKeyID kAINewDocumentRasterResolutionKey= 'rast'; // integer /** Parameter to \c #kAINewDocumentAction. The preview style for the new document, an \c #AIPreviewMode constant. */ const ActionParamKeyID kAINewDocumentPreviewModeKey = 'pxpr'; // integer /** Parameter to \c #kAINewDocumentAction. True to show the transparency grid for the document, false to hide it. */ const ActionParamKeyID kAINewDocumentTransparencyGridKey = 'tran'; // bool /** Parameter to \c #kAINewDocumentAction. If \c #kAINewDocumentTransparencyGridKey is true, the RGB values for the colors of the Transparency Grid */ const ActionParamKeyID kAINewDocumentTransparencyGridColor1RedKey = 'gr1r'; const ActionParamKeyID kAINewDocumentTransparencyGridColor1GreenKey = 'gr1g'; const ActionParamKeyID kAINewDocumentTransparencyGridColor1BlueKey = 'gr1b'; const ActionParamKeyID kAINewDocumentTransparencyGridColor2RedKey = 'gr2r'; const ActionParamKeyID kAINewDocumentTransparencyGridColor2GreenKey = 'gr2g'; const ActionParamKeyID kAINewDocumentTransparencyGridColor2BlueKey = 'gr2b'; // ----------------------------------------------------------------------------- /** @ingroup Actions Opens a document @param #kAIOpenDocumentNameKey The name string of the file to open. @param #kAIOpenDocumentColorModelKey The color model to use. Allowed values are \c #kDocRGBColor and \c #kDocCMYKColor. */ #define kAIOpenDocumentAction "adobe_openDocument" /** Parameter to \c #kAIOpenDocumentAction. The name string of the file to open. */ const ActionParamKeyID kAIOpenDocumentNameKey = 'name'; // string /** Parameter to \c #kAIOpenDocumentAction. The color model to use. Allowed values are \c #kDocRGBColor and \c #kDocCMYKColor. */ const ActionParamKeyID kAIOpenDocumentColorModelKey = 'colr'; // integer // ----------------------------------------------------------------------------- /** @ingroup Actions Saves the current document under its current name, according to its current format. Takes no parameters. */ #define kAISaveDocumentAction "adobe_saveDocument" // ----------------------------------------------------------------------------- /** @ingroup Actions Saves the current document. The parameters allows you to specify the name and format. There can be additional parameters, depending on the file format; see \c AINativeAction.h and\c AISVGAction.h. @param #kAISaveDocumentAsNameKey The name string of the file to save to. Optional. If not specified, shows a dialog to query user for the name. @param #kAISaveDocumentAsFormatKey The format string of the format to save to. Optional. If not specified, uses the current format of the document. Use \c #kAINativeFileFormat to save as a native file, \c #kAIEPSFileFormat to save as an EPS file. @param #kAISaveDocumentAsGetParamsKey When true, shows a dialog to query user for additional parameters required by the format. Optional. Default is false. */ #define kAISaveDocumentAsAction "adobe_saveDocumentAs" /** Parameter to \c #kAISaveDocumentAsAction. The name string of the file to save to. Optional. If not specified, shows a dialog to query user for the name. */ const ActionParamKeyID kAISaveDocumentAsNameKey = 'name'; // string /** Parameter to \c #kAISaveDocumentAsAction. The format string of the format to save to. Optional. If not specified, uses the current format of the document. See \c AINativeAction.h */ const ActionParamKeyID kAISaveDocumentAsFormatKey = 'frmt'; // string /** Parameter to \c #kAISaveDocumentAsAction. When true, shows a dialog to query user for additional parameters required by the format. Optional. Default is false. */ const ActionParamKeyID kAISaveDocumentAsGetParamsKey = 'gprm'; // bool // ----------------------------------------------------------------------------- /** @ingroup Actions Reverts the current document to its state when last saved. Takes no parameters. */ #define kAIRevertDocumentAction "adobe_revertDocument" // ----------------------------------------------------------------------------- /** @ingroup Actions Closes the current document or all open documents. @param #kAICloseAllDocumentsKey When true, close all open document. When false, close only the current document. @param #kAICloseAndSaveDocumentKey When true, saves the document or documents before closing. */ #define kAICloseDocumentAction "adobe_closeDocument" /** Parameter to \c #kAICloseDocumentAction. When true, close all open document. When false, close only the current document. */ const ActionParamKeyID kAICloseAllDocumentsKey = 'all.'; // bool /** Parameter to \c #kAICloseDocumentAction. When true, saves the document or documents before closing. */ const ActionParamKeyID kAICloseAndSaveDocumentKey = 'save'; // bool // ----------------------------------------------------------------------------- /** @ingroup Actions Exports the current document to the file format specified by the format and extension parameters. There may be additional parameters, depending on the file format; see the action information for the individual formats for the definitions. @param #kAIExportDocumentNameKey The name string for the file to export as. @param #kAIExportDocumentFormatKey The format string. Optional. If not specified, shows the Export dialog. See the action information for individual formats for definitions of the format strings. @param #kAIExportDocumentExtensionKey The file extension string. Optional. If not specified, shows the Export dialog. */ #define kAIExportDocumentAction "adobe_exportDocument" /** Parameter to \c #kAIExportDocumentAction. The name string for the file to export as. */ const ActionParamKeyID kAIExportDocumentNameKey = 'name'; // string /** Parameter to \c #kAIExportDocumentAction. The format string. Optional. If not specified, shows the Export dialog. See the action information for individual formats for definitions of the format strings.*/ const ActionParamKeyID kAIExportDocumentFormatKey = 'frmt'; // string /** Parameter to \c #kAIExportDocumentAction. The file extension string. Optional. If not specified, shows the Export dialog. */ const ActionParamKeyID kAIExportDocumentExtensionKey = 'extn'; // string /** Parameter to \c #kAIExportDocumentAction. When true, export multiple artboards specified in \c # kAIExportDocumentSaveAllKey or \c #kAIExportDocumentSaveRangeKey. when false,export the complete artwork */ const ActionParamKeyID kAIExportDocumentSaveMultipleArtboardsKey = 'smab'; // boolean /** Parameter to \c #kAIExportDocumentAction. When true, export all artboards. when false,export the artbaords in \c #kAIExportDocumentSaveRangeKey specified */ const ActionParamKeyID kAIExportDocumentSaveAllKey = 'sall'; // boolean /** Parameter to \c #kAIExportDocumentAction. The artboards range string. Optional when \c # kAIExportDocumentSaveAllKey is true or \c #kAIExportDocumentSaveMultipleArtboardsKey is false*/ const ActionParamKeyID kAIExportDocumentSaveRangeKey = 'sran'; // string const ActionParamKeyID kAIEnableBatchExport = 'ebep'; // string const ActionParamKeyID kAIExportDocumentPreventFileNameUniquifyKey = 'pfnu'; // string // ----------------------------------------------------------------------------- /** @ingroup Actions Prints the current document. Takes no parameters. */ #define kAIPrintDocumentAction "adobe_printDocument" // ----------------------------------------------------------------------------- /** @ingroup Actions Places a file into a document. Additional parameters can be specified for the action depending on the target file format. See the action information for individual formats for definitions of the additional parameters. @param #kAIPlaceDocumentActionNameKey The name string of the file to place. @param #kAIPlaceDocumentActionLinkKey When true, the file is linked. When false, the file is embedded. @param #kAIPlaceDocumentActionReplaceKey When true, the file replaces the current selection in the document. @param #kAIPlaceDocumentActionTemplateKey When true. creates a template layer and places the file in that layer. */ #define kAIPlaceDocumentAction "adobe_placeDocument" /** Parameter to \c #kAIPlaceDocumentAction. The name string of the file to place. */ const ActionParamKeyID kAIPlaceDocumentActionNameKey = 'name'; // string /** Parameter to \c #kAIPlaceDocumentAction. When true, the file is linked. When false, the file is embedded. */ const ActionParamKeyID kAIPlaceDocumentActionLinkKey = 'link'; // bool /** Parameter to \c #kAIPlaceDocumentAction. When true, the file replaces the current selection in the document. */ const ActionParamKeyID kAIPlaceDocumentActionReplaceKey = 'rplc'; // bool /** Parameter to \c #kAIPlaceDocumentAction. When true. creates a template layer and places the file in that layer. */ const ActionParamKeyID kAIPlaceDocumentActionTemplateKey = 'tmpl'; // bool #endif
// // BSYLiveShelfModel.h // BSYLiveSDK // // Created by zddMac on 2020/11/18. // Copyright © 2020 zddMac. All rights reserved. // #import <Foundation/Foundation.h> /** 货架的呈现类型 */ typedef NS_ENUM(NSUInteger, BSYLiveShelfEntranceType) { /** * 无商品信息 */ BSYLiveShelfEntranceType_None = 0, /** * 文字 */ BSYLiveShelfEntranceType_Text = 1, /** * 图片 */ BSYLiveShelfEntranceType_Pic = 2, }; /** 货架的呈现方式 */ typedef NS_ENUM(NSUInteger, BSYLiveShelfShowWay) { /** * 不展示 */ BSYLiveShelfShowWay_None = 0, /** * 悬浮窗 */ BSYLiveShelfShowWay_Pop = 1, /** * 页面 */ BSYLiveShelfShowWay_Page = 2, }; NS_ASSUME_NONNULL_BEGIN /** 直播货架内容 */ @interface BSYLiveShelfModel : NSObject /** * @brief 货架所在群组id */ @property (nonatomic, assign, readonly)uint64_t groupId; /** * @brief 货架id */ @property (nonatomic, strong, readonly)NSString *shelfId; /** * @brief 货架名 */ @property (nonatomic, strong, readonly)NSString *title; /** * @brief 货架链接地址 */ @property (nonatomic, strong, readonly)NSString *actionUrl; /** * @brief 呈现方式 * @see BSYLiveShelfShowWay */ @property (nonatomic, assign, readonly)BSYLiveShelfShowWay showWay; /** * @brief 内容类型 图片或者文字 * @see BSYLiveShelfEntranceType */ @property (nonatomic, assign, readonly)BSYLiveShelfEntranceType entranceStyle; /** * @brief 文字内容或图片链接 */ @property (nonatomic, strong, readonly)NSString *entranceContent; @end NS_ASSUME_NONNULL_END
/* * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") * Copyright (c) 1996,1999 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Imports */ #include "port_before.h" #include <sys/types.h> #include <netinet/in.h> #include <arpa/nameser.h> #include <resolv.h> #include <stdio.h> #include <string.h> #include <netdb.h> #include <ctype.h> #include <stdlib.h> #include <errno.h> #include <isc/memcluster.h> #include <irs.h> #include "port_after.h" #include "irs_p.h" #include "hesiod.h" #include "dns_p.h" /* Types. */ struct pvt { struct dns_p * dns; struct protoent proto; char * prbuf; }; /* Forward. */ static void pr_close(struct irs_pr *); static struct protoent * pr_byname(struct irs_pr *, const char *); static struct protoent * pr_bynumber(struct irs_pr *, int); static struct protoent * pr_next(struct irs_pr *); static void pr_rewind(struct irs_pr *); static void pr_minimize(struct irs_pr *); static struct __res_state * pr_res_get(struct irs_pr *); static void pr_res_set(struct irs_pr *, struct __res_state *, void (*)(void *)); static struct protoent * parse_hes_list(struct irs_pr *, char **); /* Public. */ struct irs_pr * irs_dns_pr(struct irs_acc *this) { struct dns_p *dns = (struct dns_p *)this->private; struct pvt *pvt; struct irs_pr *pr; if (!dns->hes_ctx) { errno = ENODEV; return (NULL); } if (!(pvt = memget(sizeof *pvt))) { errno = ENOMEM; return (NULL); } memset(pvt, 0, sizeof *pvt); if (!(pr = memget(sizeof *pr))) { memput(pvt, sizeof *pvt); errno = ENOMEM; return (NULL); } memset(pr, 0x5e, sizeof *pr); pvt->dns = dns; pr->private = pvt; pr->byname = pr_byname; pr->bynumber = pr_bynumber; pr->next = pr_next; pr->rewind = pr_rewind; pr->close = pr_close; pr->minimize = pr_minimize; pr->res_get = pr_res_get; pr->res_set = pr_res_set; return (pr); } /* Methods. */ static void pr_close(struct irs_pr *this) { struct pvt *pvt = (struct pvt *)this->private; if (pvt->proto.p_aliases) free(pvt->proto.p_aliases); if (pvt->prbuf) free(pvt->prbuf); memput(pvt, sizeof *pvt); memput(this, sizeof *this); } static struct protoent * pr_byname(struct irs_pr *this, const char *name) { struct pvt *pvt = (struct pvt *)this->private; struct dns_p *dns = pvt->dns; struct protoent *proto; char **hes_list; if (!(hes_list = hesiod_resolve(dns->hes_ctx, name, "protocol"))) return (NULL); proto = parse_hes_list(this, hes_list); hesiod_free_list(dns->hes_ctx, hes_list); return (proto); } static struct protoent * pr_bynumber(struct irs_pr *this, int num) { struct pvt *pvt = (struct pvt *)this->private; struct dns_p *dns = pvt->dns; struct protoent *proto; char numstr[16]; char **hes_list; sprintf(numstr, "%d", num); if (!(hes_list = hesiod_resolve(dns->hes_ctx, numstr, "protonum"))) return (NULL); proto = parse_hes_list(this, hes_list); hesiod_free_list(dns->hes_ctx, hes_list); return (proto); } static struct protoent * pr_next(struct irs_pr *this) { UNUSED(this); errno = ENODEV; return (NULL); } static void pr_rewind(struct irs_pr *this) { UNUSED(this); /* NOOP */ } static void pr_minimize(struct irs_pr *this) { UNUSED(this); /* NOOP */ } static struct __res_state * pr_res_get(struct irs_pr *this) { struct pvt *pvt = (struct pvt *)this->private; struct dns_p *dns = pvt->dns; return (__hesiod_res_get(dns->hes_ctx)); } static void pr_res_set(struct irs_pr *this, struct __res_state * res, void (*free_res)(void *)) { struct pvt *pvt = (struct pvt *)this->private; struct dns_p *dns = pvt->dns; __hesiod_res_set(dns->hes_ctx, res, free_res); } /* Private. */ static struct protoent * parse_hes_list(struct irs_pr *this, char **hes_list) { struct pvt *pvt = (struct pvt *)this->private; char *p, *cp, **cpp, **new; int num = 0; int max = 0; for (cpp = hes_list; *cpp; cpp++) { cp = *cpp; /* Strip away comments, if any. */ if ((p = strchr(cp, '#'))) *p = 0; /* Skip blank lines. */ p = cp; while (*p && !isspace((unsigned char)*p)) p++; if (!*p) continue; /* OK, we've got a live one. Let's parse it for real. */ if (pvt->prbuf) free(pvt->prbuf); pvt->prbuf = strdup(cp); p = pvt->prbuf; pvt->proto.p_name = p; while (*p && !isspace((unsigned char)*p)) p++; if (!*p) continue; *p++ = '\0'; pvt->proto.p_proto = atoi(p); while (*p && !isspace((unsigned char)*p)) p++; if (*p) *p++ = '\0'; while (*p) { if ((num + 1) >= max || !pvt->proto.p_aliases) { max += 10; new = realloc(pvt->proto.p_aliases, max * sizeof(char *)); if (!new) { errno = ENOMEM; goto cleanup; } pvt->proto.p_aliases = new; } pvt->proto.p_aliases[num++] = p; while (*p && !isspace((unsigned char)*p)) p++; if (*p) *p++ = '\0'; } if (!pvt->proto.p_aliases) pvt->proto.p_aliases = malloc(sizeof(char *)); if (!pvt->proto.p_aliases) goto cleanup; pvt->proto.p_aliases[num] = NULL; return (&pvt->proto); } cleanup: if (pvt->proto.p_aliases) { free(pvt->proto.p_aliases); pvt->proto.p_aliases = NULL; } if (pvt->prbuf) { free(pvt->prbuf); pvt->prbuf = NULL; } return (NULL); } /*! \file */
<reponame>TheMisterPenguin/ProjetL2 /** * \file personnage.h * \author <NAME> (<EMAIL>) * \author <NAME> (<EMAIL>) * \author <NAME> (<EMAIL>) * \brief Fichier contenant toutes les définitions concernant le personnage * \version 0.2 * \date 28/03/2022 * \copyright Copyright (c) 2022 */ #ifndef __PERSONNAGE_H__ #define __PERSONNAGE_H__ #include "definition_commun.h" #include "listes.h" #include "inventaire.h" #define DUREE_ATTAQUE_OU_CHARGEE 12 #define DUREE_ATTAQUE 4 #define DUREE_ATTAQUE_CHARGEE 10 #define DUREE_BLOQUER 14 #define DUREE_JOUEUR_BLESSE 12 #define DUREE_SOIN 25 /**< Nombre de sprites dans le spritesheet de soin */ #define TAILLE_PERSONNAGE 16 /*La taille du personnage en pixels*/ #define TAILLE_TRIGGER 200 typedef struct s_l_aff t_l_aff; /* Cette définition est la pour éviter une inclusion mutuelle des fichiers personnage.h et affichage.h */ typedef struct inventaire_s inventaire_t; /* Cette définition est la pour éviter une inclusion mutuelle des fichiers \ref personnage.h et \ref inventaire.h */ typedef unsigned char byte; typedef enum { RIEN, /**< Aucune action */ ATTAQUE, /**< Action d'attaque */ ATTAQUE_CHARGEE, /**< Action d'attaque chargée */ CHARGER, /**< Action de charge */ BLOQUER, /**< Action de bloquage */ ATTAQUE_OU_CHARGER, /**< Action d'attaque ou de charge */ J_BLESSE, /**< Action de blessure */ SOIN /**< Action de soin */ }action_t; /**<l'action qu'est en train de faire le personnage*/ /** * \brief Structure contenant les éléments nécéssaires au choix de l'affichage des sprites du personnage * * \authors <NAME> * \authors <NAME> */ typedef struct statut_s { bool en_mouvement; /**<personnage en mouvement*/ t_direction_1 orient_dep;/**<orientation deplacement du personnage*/ t_direction_2 orient_att;/**<orientaiton attaque du personnage*/ bool bouclier_equipe; /**<personnage à un bouclier d'équipé*/ int duree; /**<durée de l'action à réaliser*/ int duree_anim; /**<durée d'une animation éventuelle sur le joueur*/ action_t action; /**<l'action du personnage*/ action_t animation; /**<Animation sur le personnage*/ SDL_Rect zone_colision; /**<zone de colision du personnage*/ SDL_Rect vrai_zone_collision; /**<La vrai zone de collision du J1 sur la carte */ t_aff * texture_prec; /**<la texture precedente du personnage*/ }statut_t; typedef unsigned char byte; /** * \brief Structure non manipulable hors des fonctions du personnage contenant les informations sur le joueur * * \authors <NAME> * \authors <NAME> */ typedef struct joueur_s { char * nom_pers; /**<Le nom du personnage*/ short int niveau; /**<Le niveau du joueur*/ int xp; /**<Le nombre de points d'expérience que possède le joueur */ byte *trigger; /**<Une variable contenant des triggers logiques concernant le personnage */ int maxPdv; /**<Le nombre de Pv max du joueur */ int pdv; /**<Les points de vie actuels du joueur */ int attaque; /**<attaque de base du joueur*/ int defense; /**<defense de base du joueur*/ int vitesse; /**<vitesse de déplacement de base du joueur*/ int attaque_actif; /**<attaque du joueur avec bonus d'equipement*/ int defense_actif; /**<defense du joueur avec bonus d'equipement*/ int vitesse_actif; /**<vitesse du joueur avec bonus d'equipement*/ statut_t *statut; /**<statut du joueur*/ t_l_aff *textures_joueur; /**<Tableau contenant toutes les textures du joueur*/ inventaire_t * inventaire; /**<Inventaire du joueur*/ }joueur_t; /** * \fn void stoper_mouvement_joueurs(joueur_t ** joueurs) * \brief Stop le mouvement des joueurs en jeu * \param joueurs Tableau des joueurs en jeu */ void stoper_mouvement_joueurs(joueur_t ** joueurs); /** * \brief Creer un joueur * \authors <NAME> * \authors <NAME> * \param nom Le nom du joueur * \param niveau Le niveau du joueur * \param xp L'expérience du joueur * \param maxPdv Le nombre maximu de points de vie du joueur * \param pdv Le nombre de points de vie du joueur * \param attaque L'attaque du joueur * \param defense La défense du joueur * \param vitesse La vitesse du joueur * \param trig Le trigger d'information sur le joueur * \param orient L'orientation spatiale du joueur * \param bouclier_equipe La possession d'un bouclier équipé par le joueur * \param num_j La place du joueur dans le tableau des joueurs * \param f_src_obj Le fichier source des objets du jeu * \return Instance nouvellement allouée du type joueur_t contenant les informations du joueur */ extern joueur_t *creer_joueur(const char *nom, const int niveau, const int xp, const int maxPdv, const int pdv, const int attaque, const int defense, const int vitesse, const byte trig[TAILLE_TRIGGER], const t_direction_1 orient, const bool bouclier_equipe, const int num_j, char * f_src_obj); /** * \brief Fonction de création d'un joueur correspondant au modèle standard du jeu * \author <NAME> * * \param nom Le nom du joueur * \param num_j La place du joueur dans le tableau des joueurs * \param f_src_obj Le fichier source des objets du jeu * \return Instance nouvellement allouée du type joueur_t contenant les informations du joueur */ extern joueur_t *new_joueur(const char* nom, int num_j, char * f_src_obj); /** * \brief Fonction qui détruit un joueur * \author <NAME> * * \param j Le joueur à détruire */ extern void detruire_joueur(joueur_t *j); /** * \brief Fonction qui charge une sauvegarde au format JSON. * \author <NAME> * * Cette fonction va récupérer les informations dans la sauvegarde au format JSON. \n * * Il va ensuite detruire les joueurs et la carte, pour ensuite les recrées avec les infomations qui correspondent à la sauvegarde puis téléporter le joueur aux coordonnées voulues. * \param nom_sauv Chemin complet du fichier de sauvegarde * \param f_src_obj Le fichier source contenant les objets du jeu * \param joueurs Les joueurs existants * \param nb_joueurs Le nombre de joueurs existants * \return joueur_t* */ extern joueur_t *charger_sauvegarde_joueur(char * nom_sauv, char *f_src_obj, joueur_t *joueurs[], unsigned short int nb_joueurs); /** * \brief Fonction qui met à jour les statistiques d'un joueur lors d'un passage de niveau * \param perso Le joueur qui passe un niveau */ extern void maj_statistiques(joueur_t* perso); /** * \brief Fonction qui affiche les statistiques d'un joueur dans la console * \author <NAME> * \author <NAME> * \param perso Le joueur sur lequel on se renseigne */ extern void afficher_statistiques(joueur_t* perso); /** * \brief Fonction qui gère le passage de niveau d'un joueur * \param perso Le joueur qui passe un niveau */ extern void levelup(joueur_t* perso); /** * \brief Fonction qui gère les effets d'un gain d'expérience * \param perso Le joueur qui gagne de l'expérience */ extern void gain_xp(joueur_t* perso); /** * \brief Fonction qui créer les sauvegardes du jeu. * \author <NAME> * * Cette fonction va créer une sauvegarde dans le répertoire de sauvegarde au format JSON contenant toutes les informations a conserver sur le joueur. * * \param j Le joueur qui sauvegarde */ extern void creer_sauvegarde_json(joueur_t *j); /** * \brief Fonction gère le répertoire de jeux * \author <NAME> * * Cette fonction vérifie si le répertoire de jeux existe (emplacement différent selon les OS). \n * Puis le créer s'il n'existe pas. * */ void check_repertoire_jeux(); /** * \brief Fonction qui gère les effets de l'environnement sur le joueur * \param liste_monstres La liste des monstres du jeu * \param liste_sorts La liste des sorts du jeu * \param liste_coffres La liste des coffres du jeu * \param joueurs Les joueurs qui interagissent avec l'environnement du jeu * \param nb_joueur Le nombre de joueurs en jeu */ void environnement_joueurs(list * liste_monstres, list * liste_sorts, list * liste_coffres, joueur_t ** joueurs, int nb_joueur); /** * \brief Renvoie la distance séparant le joueur d'une entité définit par sa collision sur l'axe des abscisses * \author <NAME> * \param collision la zone de collision de l'entité * \param joueur le joueur * \return int la distance entre l'entité et le joueur sur l'axe des abscisses */ extern int distance_x_joueur(SDL_Rect collision, joueur_t * joueur); /** * \brief Renvoie la distance séparant le joueur d'une entité définit par sa collision sur l'axe des ordonnées * \author <NAME> * \param collision la zone de collision de l'entité * \param joueur le joueur * \return int la distance entre l'entité et le joueur sur l'axe des ordonnées */ extern int distance_y_joueur(SDL_Rect collision, joueur_t * joueur); /** * \brief Renvoie la distance séparant le joueur d'une entité définit par sa collision * \author <NAME> * \param collision la zone de collision de l'entité * \param joueur le joueur * \return int la distance entre l'entité et le joueur */ extern int distance_joueur(SDL_Rect collision, joueur_t * joueur); SDL_Rect * zone_en_dehors_hitbox(SDL_Rect * hitbox,SDL_Rect * sprite, t_direction_2 orient); #endif
// lm/const-arpa-lm.h // Copyright 2014 <NAME> // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #ifndef KALDI_LM_CONST_ARPA_LM_H_ #define KALDI_LM_CONST_ARPA_LM_H_ #include "base/kaldi-common.h" #include "fstext/deterministic-fst.h" #include "util/common-utils.h" namespace kaldi { // Forward declaration of Auxiliary struct ArpaLine. struct ArpaLine; class ConstArpaLm { public: // Default constructor, will be used if you are going to load the ConstArpaLm // format language model from disk. ConstArpaLm() { lm_states_ = NULL; unigram_states_ = NULL; overflow_buffer_ = NULL; memory_assigned_ = false; initialized_ = false; } // Special constructor, will be used when you initialize ConstArpaLm from // scratch through this constructor. ConstArpaLm(const int32 bos_symbol, const int32 eos_symbol, const int32 unk_symbol, const int32 ngram_order, const int32 num_words, const int32 overflow_buffer_size, const int32 lm_states_size, int32** unigram_states, int32** overflow_buffer, int32* lm_states) : bos_symbol_(bos_symbol), eos_symbol_(eos_symbol), unk_symbol_(unk_symbol), ngram_order_(ngram_order), num_words_(num_words), overflow_buffer_size_(overflow_buffer_size), lm_states_size_(lm_states_size), unigram_states_(unigram_states), overflow_buffer_(overflow_buffer), lm_states_(lm_states) { KALDI_ASSERT(unigram_states_ != NULL); KALDI_ASSERT(overflow_buffer_ != NULL); KALDI_ASSERT(lm_states_ != NULL); KALDI_ASSERT(ngram_order_ > 0); KALDI_ASSERT(bos_symbol_ < num_words_ && bos_symbol_ > 0); KALDI_ASSERT(eos_symbol_ < num_words_ && eos_symbol_ > 0); KALDI_ASSERT(unk_symbol_ < num_words_ && (unk_symbol_ > 0 || unk_symbol_ == -1)); lm_states_end_ = lm_states_ + lm_states_size_ - 1; memory_assigned_ = false; initialized_ = true; } ~ConstArpaLm() { if (memory_assigned_) { delete[] lm_states_; delete[] unigram_states_; delete[] overflow_buffer_; } } // Reads the ConstArpaLm format language model. void Read(std::istream &is, bool binary); // Writes the language model in ConstArpaLm format. void Write(std::ostream &os, bool binary) const; // Creates Arpa format language model from ConstArpaLm format, and writes it // to output stream. This will be useful in testing. void WriteArpa(std::ostream &os) const; // Wrapper of GetNgramLogprobRecurse. It first maps possible out-of-vocabulary // words to <unk>, if <unk> is defined, and then calls GetNgramLogprobRecurse. float GetNgramLogprob(const int32 word, const std::vector<int32>& hist) const; // Returns true if the history word sequence <hist> has successor, which means // <hist> will be a state in the FST format language model. bool HistoryStateExists(const std::vector<int32>& hist) const; int32 BosSymbol() const { return bos_symbol_; } int32 EosSymbol() const { return eos_symbol_; } int32 UnkSymbol() const { return unk_symbol_; } int32 NgramOrder() const { return ngram_order_; } private: // Loops up n-gram probability for given word sequence. Backoff is handled by // recursively calling this function. float GetNgramLogprobRecurse(const int32 word, const std::vector<int32>& hist) const; // Given a word sequence, find the address of the corresponding LmState. // Returns NULL if no corresponding LmState is found. // // If the word sequence exists in n-gram language model, but it is a leaf and // is not an unigram, we still return NULL, since there is no LmState struct // reserved for this sequence. int32* GetLmState(const std::vector<int32>& seq) const; // Given a pointer to the parent, find the child_info that corresponds to // given word. The parent has the following structure: // struct LmState { // float logprob; // float backoff_logprob; // int32 num_children; // std::pair<int32, int32> [] children; // } // It returns false if the child is not found. bool GetChildInfo(const int32 word, int32* parent, int32* child_info) const; // Decodes <child_info> to get log probability and child LmState. In the leaf // case, only <logprob> will be returned, and <child_address> will be NULL. void DecodeChildInfo(const int32 child_info, int32* parent, int32** child_lm_state, float* logprob) const; void WriteArpaRecurse(int32* lm_state, const std::vector<int32>& seq, std::vector<ArpaLine> *output) const; // We assign memory in Read(). If it is called, we have to release memory in // the destructor. bool memory_assigned_; // Makes sure that the language model has been loaded before using it. bool initialized_; // Integer corresponds to <s>. int32 bos_symbol_; // Integer corresponds to </s>. int32 eos_symbol_; // Integer corresponds to unknown-word. -1 if no unknown-word symbol is // provided. int32 unk_symbol_; // N-gram order of the language model. int32 ngram_order_; // Index of largest word-id plus one. It defines the end of <unigram_states_> // array. int32 num_words_; // Number of entries in the overflow buffer for pointers that couldn't be // represented as a 30-bit relative index. int32 overflow_buffer_size_; // Size of the <lm_states_> array, which will be needed by I/O. int32 lm_states_size_; // Points to the end of <lm_states_>. We use this information to check if // there is any illegal visit to the un-reserved memory. int32* lm_states_end_; // Loopup table for pointers of unigrams. The pointer could be NULL, for // example for those words that are in words.txt, but not in the language // model. int32** unigram_states_; // Technically a 32-bit number cannot represent a possibly 64-bit pointer. We // therefore use "relative" address instead of "absolute" address, which will // be a small number most of the time. This buffer is for the case where the // relative address has more than 30-bits. int32** overflow_buffer_; // Memory chunk that contains the actual LmStates. One LmState has the // following structure: // // struct LmState { // float logprob; // float backoff_logprob; // int32 num_children; // std::pair<int32, int32> [] children; // } // // Note that the floating point representation has 4 bytes, int32 also has 4 // bytes, therefore one LmState will occupy the following number of bytes: // // x = 1 + 1 + 1 + 2 * children.size() = 3 + 2 * children.size() int32* lm_states_; }; /** This class wraps a ConstArpaLm format language model with the interface defined in DeterministicOnDemandFst. */ class ConstArpaLmDeterministicFst : public fst::DeterministicOnDemandFst<fst::StdArc> { public: typedef fst::StdArc::Weight Weight; typedef fst::StdArc::StateId StateId; typedef fst::StdArc::Label Label; ConstArpaLmDeterministicFst(const ConstArpaLm& lm); // We cannot use "const" because the pure virtual function in the interface is // not const. virtual StateId Start() { return start_state_; } // We cannot use "const" because the pure virtual function in the interface is // not const. virtual Weight Final(StateId s); virtual bool GetArc(StateId s, Label ilabel, fst::StdArc* oarc); private: typedef unordered_map<std::vector<Label>, StateId, VectorHasher<Label> > MapType; StateId start_state_; MapType wseq_to_state_; std::vector<std::vector<Label> > state_to_wseq_; const ConstArpaLm& lm_; }; // Reads in an Arpa format language model and converts it into ConstArpaLm // format. We assume that the words in the input Arpa format language model have // been converted into integers. bool BuildConstArpaLm(const bool natural_base, const int32 bos_symbol, const int32 eos_symbol, const int32 unk_symbol, const std::string& arpa_rxfilename, const std::string& const_arpa_wxfilename); } // namespace kaldi #endif // KALDI_LM_CONST_ARPA_LM_H_
#pragma once #include "common.h" #include <kernel> #include <string> #include <string_view> #include <vector> #define KTL_TEST(Name, TestBody) \ bool KTLTest_##Name(void) \ { \ __try \ ##TestBody \ __except (EXCEPTION_EXECUTE_HANDLER) \ { \ LOG_ERROR("Exception thrown in test: %#x\n", GetExceptionCode()); \ return false; \ } \ \ LOG_TRACE("[OK] " #Name "!\n"); \ return true; \ } \ #define ASSERT_TRUE(x, fmt, ...) do { if (!(##x)) { LOG_ERROR("[NG] (" #x ") " fmt "\n", __VA_ARGS__); return false; } } while(0) #define ASSERT_FALSE(x, fmt, ...) do { if ((##x)) { LOG_ERROR("[NG] (" #x ") " fmt "\n", __VA_ARGS__); return false; } } while(0) bool test_set(); bool test_vector(); bool test_unicode_string(); bool test_unicode_string_view(); bool test_list(); bool test_memory(); struct timer { timer() : start_{}, end_{}, frequency_{} { } void start() { start_ = KeQueryPerformanceCounter(&frequency_); } void stop() { end_ = KeQueryPerformanceCounter(nullptr); } double elapsed() { double end = static_cast<double>(end_.QuadPart); double start = static_cast<double>(start_.QuadPart); return (end - start) / static_cast<double>(frequency_.QuadPart); } private: LARGE_INTEGER start_; LARGE_INTEGER end_; LARGE_INTEGER frequency_; }; struct complex_copyable_object { complex_copyable_object() = default; complex_copyable_object(const complex_copyable_object& other) : Name(other.Name), Value(other.Value) { } complex_copyable_object(ktl::unicode_string_view name, int value) : Name(name), Value(value) { } complex_copyable_object(ktl::unicode_string_view name) : Name(name) { } ktl::unicode_string<> Name; int Value = 5; ktl::vector<int> Vec; private: int NonStandard = -5; }; struct complex_object { complex_object() = default; complex_object(complex_object&&) = default; complex_object& operator=(complex_object&&) = default; complex_object(ktl::unicode_string_view name, int value) : Name(name), Value(value) { } complex_object(ktl::unicode_string_view name) : Name(name) { } ktl::unicode_string<> Name; int Value = 5; ktl::vector<int> Vec; private: int NonStandard = -5; };
#ifndef STIP_FEATURE #define STIP_FEATURE #include <Eigen/Core> #include <opencv2/core/core.hpp> #include <memory> #include <vector> namespace nuisken { namespace storage { /** * 時空間局所特徴のパッチ * Spatio temporal local feature */ class STIPFeature { private: /** * パッチ内の特徴 */ std::vector<Eigen::MatrixXf> featureVectors; /** * パッチの中心座標 */ cv::Vec3i centerPoint; /** * 重心へのベクトル */ cv::Vec3i displacementVector; /** * 特徴点の空間的なスケール */ double spatialScale; /** * 特徴点の時間的なスケール */ double temporalScale; /** * クラスのラベル */ int classLabel; int viewLabel; int index; public: STIPFeature(const std::vector<Eigen::MatrixXf>& featureVectors, const cv::Vec3i& centerPoint, const cv::Vec3i& displacementVector, const std::pair<double, double>& scales, int classLabel, int viewLabel = 0) : featureVectors(featureVectors), centerPoint(centerPoint), displacementVector(displacementVector), spatialScale(scales.first), temporalScale(scales.second), classLabel(classLabel), viewLabel(viewLabel){}; double getFeatureValue(int index, int featureChannel) const { return featureVectors.at(featureChannel).coeff(0, index); } std::vector<Eigen::MatrixXf> getFeatureVectors() const { auto tempFeatureVectors = this->featureVectors; return tempFeatureVectors; } cv::Vec3i getCenterPoint() const { return centerPoint; } cv::Vec3i getDisplacementVector() const { return displacementVector; } double getSpatialScale() const { return spatialScale; } double getTemporalScale() const { return temporalScale; } int getClassLabel() const { return classLabel; } int getNumberOfFeatureChannels() const { return featureVectors.size(); } int getNumberOfFeatureDimensions(int featureChannel) const { return featureVectors.at(featureChannel).cols(); } int getIndex() const { return index; } int getViewLabel() const { return viewLabel; } void setFeatureVectors(const std::vector<Eigen::MatrixXf>& featureVectors) { this->featureVectors = featureVectors; } void setCenterPoint(const cv::Vec3i& centerPoint) { this->centerPoint = centerPoint; } void setDisplacementVector(const cv::Vec3i& displacementVector) { this->displacementVector = displacementVector; } void setSpatialScale(double spatialScale) { this->spatialScale = spatialScale; } void setTemporalScale(double temporalScale) { this->temporalScale = temporalScale; } void setClassLabel(int classLabel) { this->classLabel = classLabel; } void setIndex(int index) { this->index = index; } // void save(const std::string& filePath) const; // void load(const std::string& filePath); }; } } #endif
/* * Paw.h * * Created on: 28 sept. 2015 * Author: Julien */ #ifndef PAW_H_ #define PAW_H_ #include "paw/Paw_math_model.h" #include "servo/Servo.h" #include "utility/Vector.h" #include "drivers/pca9685/PCA9685.h" /*struct Position_on_hexapode // deprecated, use Vector2f instead { float x_offset; float y_offset; };*/ struct Paw_coords { Vector3f m_prepare_coords; Vector3f m_current_coords; Vector3f m_last_coords; }; /*struct Servos_of_paw { Servo m_coxa; Servo m_femur; Servo m_tibia; int servos_time_table[3]; };*/ class Error_detection; class Paw : public Paw_math_model { public: Paw(Side_enum side, Paw_position_enum paw_position, Error_detection* p_error_detection, float p_x_offset, float p_y_offset, int p_active_sequence_number); void prepare_to_move(float position[3]); void valid_move(); Paw_position_enum get_position() const { return m_position; } Side_enum get_side() const { return m_side; } Vector2f get_position_offset() const { return m_position_offset; } Vector3f get_current_coords() const { return coords.m_current_coords; } Vector3f get_last_position() const { return coords.m_last_coords; } float get_x_center() const { return m_x_center; } int get_servo_time(Servo_position_enum servo_position) const { return servos_time_table[servo_position]; } int get_active_sequence_number() const {return m_active_sequence_number; } int get_side_coef() const { return m_side_coef; } Angles get_servo_angle() const { return m_servo_angles; } const Servo& get_tibia() const { return m_tibia; } const Servo& get_femur() const { return m_femur; } const Servo& get_coxa () const { return m_coxa; } void calibrate(int time[3]); private: Side_enum m_side; Paw_position_enum m_position; int m_side_coef; //Servos_of_paw m_servos; Servo m_coxa; Servo m_femur; Servo m_tibia; int servos_time_table[3]; Paw_coords coords; Angles m_servo_angles; float m_x_center; Vector2f m_position_offset; int m_active_sequence_number; Error_detection* m_error_detection; void determine_servos_paw_time(); }; #endif /* PAW_H_ */
#ifndef rrPendingAssignmentH #define rrPendingAssignmentH #include <vector> #include "rrObject.h" #include "rrTComputeEventAssignmentDelegate.h" #include "rrTPerformEventAssignmentDelegate.h" using std::vector; //--------------------------------------------------------------------------- // <summary> // Initializes a new instance of the PendingAssignment class. // </summary> // <param name="time"></param> namespace rr { class RR_DECLSPEC PendingAssignment : public rrObject { protected: double Time; int Index; bool UseValuesFromTriggerTime; TComputeEventAssignmentDelegate ComputeAssignment; TPerformEventAssignmentDelegate PerformAssignment; int ComputedValuesSize; public: double* ComputedValues; /// <summary> /// Initializes a new instance of the PendingAssignment class. /// </summary> /// <param name="time"></param> PendingAssignment( double time, TComputeEventAssignmentDelegate computeAssignment, TPerformEventAssignmentDelegate performAssignment, bool useValuesFromTriggerTime, int index); int GetIndex(); double GetTime(); void AssignToModel(); }; } #endif //namespace LibRoadRunner //{ // internal class PendingAssignment // { // /// <summary> // /// Initializes a new instance of the PendingAssignment class. // /// </summary> // /// <param name="time"></param> // public PendingAssignment(double time, TComputeEventAssignmentDelegate computeAssignment, // TPerformEventAssignmentDelegate performAssignment, bool useValuesFromTriggerTime, int index) // { // Time = time; // ComputeAssignment = computeAssignment; // PerformAssignment = performAssignment; // Index = index; // UseValuesFromTriggerTime = useValuesFromTriggerTime; // if (useValuesFromTriggerTime) // ComputedValues = computeAssignment(); // } // // public int Index { get; set; } // // public double Time { get; set; } // // public double[] ComputedValues { get; set; } // public TComputeEventAssignmentDelegate ComputeAssignment { get; set; } // public TPerformEventAssignmentDelegate PerformAssignment { get; set; } // public bool UseValuesFromTriggerTime { get; set; } // // public void AssignToModel() // { // if (!UseValuesFromTriggerTime) // ComputedValues = ComputeAssignment(); // PerformAssignment(ComputedValues); // } // } //}
#include "cst.h" #include <SDL.h> SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; SDL_Texture *textureMenu = NULL; SDL_Texture *textureRegles = NULL; SDL_Texture *textureMenuChoixJoueur = NULL; SDL_Texture *textureMenuChoixMode = NULL; SDL_Texture *textureMenuChoixIA = NULL; SDL_Texture *texturePionNoir = NULL; SDL_Texture *textureExAeqo = NULL; SDL_Texture *texturePionBlanc = NULL; SDL_Texture *textureJeu = NULL; SDL_Texture *textureMenuFin = NULL; SDL_Texture *textureRetourMenuFin = NULL; const double rac2 = 1.41213562;
/* LAZYBOX_COMMAND @name echo @descrip Echos a string back @function run_echo @config CMD_ECHO @test nothing @test one "testing" @test many "this is a lot of parameters and some are numbers 1 2 3" @test nonewline_one -n testing @test nonewline_many -n this is a lot of parameters and some are numbers 1 2 3 @test escape_newline1 -e testing\n @test escape_newline2 -e -n testing\n @test escape_newline3 -e testing\n\n\ntesting\ntesting @test escape_newline4 testing\\n @test escape_tab1 -e testing\ttesting @test escape_tab2 -e testing\t\t\ttesting */ #include <stdio.h> #include <string.h> #include "parseArgs.h" #define PARAM_COUNT ( 3U ) typedef struct { bool noNewline; bool interpEscapes; bool dontInterpEscapes; } ECHO_PARAMS; static const ARG_DATA argInfo[ PARAM_COUNT ] = { { 'n', false, ARG_DATA_TYPE_BOOL, offsetof( ECHO_PARAMS, noNewline ) }, { 'e', false, ARG_DATA_TYPE_BOOL, offsetof( ECHO_PARAMS, interpEscapes ) }, { 'E', false, ARG_DATA_TYPE_BOOL, offsetof( ECHO_PARAMS, dontInterpEscapes ) } }; static void handleEscape( bool interpEscapes, char escape ) { if( !interpEscapes ) { printf( "\\%c", escape ); } else { switch( escape ) { case( 'n' ): printf( "\n" ); break; case( 't' ): printf( "\t" ); break; } } } int run_echo( int argc, char* argv[ ] ) { int startIndex; ECHO_PARAMS params = { false, false, false }; if( !parseArgs( argInfo, PARAM_COUNT, &( params ), &( startIndex ), argc, argv ) ) { return 1; } if( params.dontInterpEscapes ) { params.interpEscapes = false; } for( int argidx = startIndex; argidx < argc; argidx++ ) { int length = strlen( argv[ argidx ] ); for( int charIdx = 0; charIdx < length; charIdx++ ) { switch( argv[ argidx ][ charIdx ] ) { case( '\\' ): if( charIdx < length - 1 ) { handleEscape( params.interpEscapes, argv[ argidx ][ charIdx + 1 ] ); charIdx++; } else { printf( "\\" ); } break; default: printf( "%c", argv[ argidx ][ charIdx ] ); break; } } if( argidx < argc - 1 ) { printf( " " ); } } if( !params.noNewline ) { printf( "\n" ); } return 0; }
#include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> typedef int32_t pos; typedef struct{ pos *trace; pos capacity,iter,grow; } n_trace; #define parser_fail(i) __builtin_expect((i)<0,0) static uint64_t read_unsigned_bits_littleendian(NailStream *stream, unsigned count) { uint64_t retval = 0; unsigned int out_idx=0; size_t pos = stream->pos; char bit_offset = stream->bit_offset; const uint8_t *data = stream->data; while(count>0) { if(bit_offset == 0 && (count &7) ==0) { retval|= data[pos] << out_idx; out_idx+=8; pos ++; count-=8; } else { //This can use a lot of performance love //TODO: test this retval |= ((data[pos] >> (bit_offset)) & 1) << out_idx; out_idx++; count--; bit_offset++; if(bit_offset >7) { bit_offset -= 8; pos++; } } } stream->pos = pos; stream->bit_offset = bit_offset; return retval; } static uint64_t read_unsigned_bits(NailStream *stream, unsigned count){ uint64_t retval = 0; unsigned int out_idx=count; size_t pos = stream->pos; char bit_offset = stream->bit_offset; const uint8_t *data = stream->data; //TODO: Implement little endian too //Count LSB to MSB while(count>0) { if(bit_offset == 0 && (count &7) ==0) { out_idx-=8; retval|= data[pos] << out_idx; pos ++; count-=8; } else{ //This can use a lot of performance love //TODO: implement other endianesses out_idx--; retval |= ((data[pos] >> (7-bit_offset)) & 1) << out_idx; count--; bit_offset++; if(bit_offset > 7){ bit_offset -= 8; pos++; } } } stream->pos = pos; stream->bit_offset = bit_offset; return retval; } static int stream_check(const NailStream *stream, unsigned count){ if(stream->size - (count>>3) - ((stream->bit_offset + count & 7)>>3) < stream->pos) return -1; return 0; } static void stream_advance(NailStream *stream, unsigned count){ stream->pos += count >> 3; stream->bit_offset += count &7; if(stream->bit_offset > 7){ stream->pos++; stream->bit_offset-=8; } } static NailStreamPos stream_getpos(NailStream *stream){ return (stream->pos << 3) + stream->bit_offset; //TODO: Overflow potential! } static void stream_backup(NailStream *stream, unsigned count){ stream->pos -= count >> 3; stream->bit_offset -= count & 7; if(stream->bit_offset < 0){ stream->pos--; stream->bit_offset += 8; } } //#define BITSLICE(x, off, len) read_unsigned_bits(x,off,len) /* trace is a minimalistic representation of the AST. Many parsers add a count, choice parsers add * two pos parameters (which choice was taken and where in the trace it begins) * const parsers emit a new input position */ typedef struct{ pos position; pos parser; pos result; } n_hash; typedef struct{ // p_hash *memo; unsigned lg_size; // How large is the hashtable - make it a power of two } n_hashtable; static int n_trace_init(n_trace *out,pos size,pos grow){ if(size <= 1){ return -1; } out->trace = (pos *)malloc(size * sizeof(pos)); if(!out){ return -1; } out->capacity = size -1 ; out->iter = 0; if(grow < 16){ // Grow needs to be at least 2, but small grow makes no sense grow = 16; } out->grow = grow; return 0; } static void n_trace_release(n_trace *out){ free(out->trace); out->trace =NULL; out->capacity = 0; out->iter = 0; out->grow = 0; } static pos n_trace_getpos(n_trace *tr){ return tr->iter; } static void n_tr_setpos(n_trace *tr,pos offset){ assert(offset<tr->capacity); tr->iter = offset; } static int n_trace_grow(n_trace *out, int space){ if(out->capacity - space>= out->iter){ return 0; } pos * new_ptr= (pos *)realloc(out->trace, (out->capacity + out->grow) * sizeof(pos)); if(!new_ptr){ return -1; } out->trace = new_ptr; out->capacity += out->grow; return 0; } static pos n_tr_memo_optional(n_trace *trace){ if(n_trace_grow(trace,1)) return -1; trace->trace[trace->iter] = 0xFFFFFFFD; return trace->iter++; } static void n_tr_optional_succeed(n_trace * trace, pos where){ trace->trace[where] = -1; } static void n_tr_optional_fail(n_trace * trace, pos where){ trace->trace[where] = trace->iter; } static pos n_tr_memo_many(n_trace *trace){ if(parser_fail(n_trace_grow(trace,2))) return -1; trace->trace[trace->iter] = 0xFFFFFFFE; trace->trace[trace->iter+1] = 0xEEEEEEEF; trace->iter +=2; return trace->iter-2; } static void n_tr_write_many(n_trace *trace, pos where, pos count){ trace->trace[where] = count; trace->trace[where+1] = trace->iter; #ifdef NAIL_DEBUG fprintf(stderr,"%d = many %d %d\n", where, count,trace->iter); #endif } static pos n_tr_begin_choice(n_trace *trace){ if(parser_fail(n_trace_grow(trace,2))) return -1; //Debugging values trace->trace[trace->iter] = 0xFFFFFFFF; trace->trace[trace->iter+1] = 0xEEEEEEEE; trace->iter+= 2; return trace->iter - 2; } static int n_tr_stream(n_trace *trace, const NailStream *stream){ assert(sizeof(stream) % sizeof(pos) == 0); if(parser_fail(n_trace_grow(trace,sizeof(*stream)/sizeof(pos)))) return -1; *(NailStream *)(trace->trace + trace->iter) = *stream; #ifdef NAIL_DEBUG fprintf(stderr,"%d = stream\n",trace->iter,stream); #endif trace->iter += sizeof(*stream)/sizeof(pos); return 0; } static pos n_tr_memo_choice(n_trace *trace){ return trace->iter; } static void n_tr_pick_choice(n_trace *trace, pos where, pos which_choice, pos choice_begin){ trace->trace[where] = which_choice; trace->trace[where + 1] = choice_begin; #ifdef NAIL_DEBUG fprintf(stderr,"%d = pick %d %d\n",where, which_choice,choice_begin); #endif } static int n_tr_const(n_trace *trace,NailStream *stream){ if(parser_fail(n_trace_grow(trace,1))) return -1; NailStreamPos newoff = stream_getpos(stream); #ifdef NAIL_DEBUG fprintf(stderr,"%d = const %d \n",trace->iter, newoff); #endif trace->trace[trace->iter++] = newoff; return 0; } #define n_tr_offset n_tr_const
<filename>vainfo/vainfo.c /* * Copyright (c) 2007 Intel Corporation. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdarg.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> #include <va/va_str.h> #include "va_display.h" #ifdef ANDROID /* Macros generated from configure */ #define LIBVA_VERSION_S "2.0.0" #endif #define CHECK_VASTATUS(va_status,func, ret) \ if (va_status != VA_STATUS_SUCCESS) { \ fprintf(stderr,"%s failed with error code %d (%s),exit\n",func, va_status, vaErrorStr(va_status)); \ ret_val = ret; \ goto error; \ } static int show_all_opt = 0; static void usage_exit(const char *program) { fprintf(stdout, "Show information from VA-API driver\n"); fprintf(stdout, "Usage: %s --help\n", program); fprintf(stdout, "\t--help print this message\n\n"); fprintf(stdout, "Usage: %s [options]\n", program); fprintf(stdout, " -a, --all Show all supported attributes\n"); va_print_display_options(stdout); exit(0); } static void parse_args(const char *name, int argc, char **argv) { int c; int option_index = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"all", no_argument, 0, 'a'}, { NULL, 0, NULL, 0 } }; va_init_display_args(&argc, argv); while ((c = getopt_long(argc, argv, "a", long_options, &option_index)) != -1) { switch(c) { case 'a': show_all_opt = 1; break; case 'h': default: usage_exit(name); break; } } } static int show_config_attributes(VADisplay va_dpy, VAProfile profile, VAEntrypoint entrypoint) { struct str_format { int format; char *name; }; VAStatus va_status; int i, n; VAConfigAttrib attrib_list[VAConfigAttribTypeMax]; int max_num_attributes = VAConfigAttribTypeMax; for (i = 0; i < max_num_attributes; i++) { attrib_list[i].type = i; } va_status = vaGetConfigAttributes(va_dpy, profile, entrypoint, attrib_list, max_num_attributes); if (VA_STATUS_ERROR_UNSUPPORTED_PROFILE == va_status || VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT == va_status ) return 0; printf("%s/%s\n", vaProfileStr(profile), vaEntrypointStr(entrypoint)); if (attrib_list[VAConfigAttribRTFormat].value != VA_ATTRIB_NOT_SUPPORTED) { static struct str_format list[] = { {VA_RT_FORMAT_YUV420, "VA_RT_FORMAT_YUV420"}, {VA_RT_FORMAT_YUV422, "VA_RT_FORMAT_YUV422"}, {VA_RT_FORMAT_YUV444, "VA_RT_FORMAT_YUV444"}, {VA_RT_FORMAT_YUV411, "VA_RT_FORMAT_YUV411"}, {VA_RT_FORMAT_YUV400, "VA_RT_FORMAT_YUV400"}, {VA_RT_FORMAT_YUV420_10, "VA_RT_FORMAT_YUV420_10"}, {VA_RT_FORMAT_YUV422_10, "VA_RT_FORMAT_YUV422_10"}, {VA_RT_FORMAT_YUV444_10, "VA_RT_FORMAT_YUV444_10"}, {VA_RT_FORMAT_YUV420_12, "VA_RT_FORMAT_YUV420_12"}, {VA_RT_FORMAT_YUV422_12, "VA_RT_FORMAT_YUV422_12"}, {VA_RT_FORMAT_YUV444_12, "VA_RT_FORMAT_YUV444_12"}, {VA_RT_FORMAT_RGB16, "VA_RT_FORMAT_RGB16"}, {VA_RT_FORMAT_RGB32, "VA_RT_FORMAT_RGB32"}, {VA_RT_FORMAT_RGBP, "VA_RT_FORMAT_RGBP"}, {VA_RT_FORMAT_RGB32_10, "VA_RT_FORMAT_RGB32_10"}, {VA_RT_FORMAT_RGB32_10BPP, "VA_RT_FORMAT_RGB32_10BPP"}, {VA_RT_FORMAT_YUV420_10BPP, "VA_RT_FORMAT_YUV420_10BPP"}, {VA_RT_FORMAT_PROTECTED, "VA_RT_FORMAT_PROTECTED"}, }; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribRTFormat].type)); for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribRTFormat].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } if (attrib_list[VAConfigAttribSpatialResidual].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: %x\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribSpatialResidual].type), attrib_list[VAConfigAttribSpatialResidual].value); } if (attrib_list[VAConfigAttribSpatialClipping].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: %x\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribSpatialClipping].type), attrib_list[VAConfigAttribSpatialClipping].value); } if (attrib_list[VAConfigAttribIntraResidual].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: %x\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribIntraResidual].type), attrib_list[VAConfigAttribIntraResidual].value); } if (attrib_list[VAConfigAttribEncryption].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: %x\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncryption].type), attrib_list[VAConfigAttribEncryption].value); } if (attrib_list[VAConfigAttribRateControl].value != VA_ATTRIB_NOT_SUPPORTED) { static struct str_format list[] = { {VA_RC_NONE, "VA_RC_NONE"}, {VA_RC_CBR, "VA_RC_CBR"}, {VA_RC_VBR, "VA_RC_VBR"}, {VA_RC_VCM, "VA_RC_VCM"}, {VA_RC_CQP, "VA_RC_CQP"}, {VA_RC_VBR_CONSTRAINED, "VA_RC_VBR_CONSTRAINED"}, {VA_RC_ICQ, "VA_RC_ICQ"}, {VA_RC_MB, "VA_RC_MB"}, {VA_RC_CFS, "VA_RC_CFS"}, {VA_RC_PARALLEL, "VA_RC_PARALLEL"}, {VA_RC_QVBR, "VA_RC_QVBR"}, {VA_RC_AVBR, "VA_RC_AVBR"}, {VA_RC_TCBRC, "VA_RC_TCBRC"}, }; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribRateControl].type)); for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribRateControl].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } if (attrib_list[VAConfigAttribDecSliceMode].value != VA_ATTRIB_NOT_SUPPORTED) { static struct str_format list[] = { {VA_DEC_SLICE_MODE_NORMAL, "VA_DEC_SLICE_MODE_NORMAL"}, {VA_DEC_SLICE_MODE_BASE, "VA_DEC_SLICE_MODE_BASE"}, }; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribDecSliceMode].type)); for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribDecSliceMode].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } if (attrib_list[VAConfigAttribDecJPEG].value & (~VA_ATTRIB_NOT_SUPPORTED)) { static struct str_format list[] = { {1 << VA_ROTATION_NONE, "VA_ROTATION_NONE"}, {1 << VA_ROTATION_90, "VA_ROTATION_90"}, {1 << VA_ROTATION_180, "VA_ROTATION_180"}, {1 << VA_ROTATION_270, "VA_ROTATION_270"}, }; VAConfigAttribValDecJPEG *config = (VAConfigAttribValDecJPEG*)&attrib_list[VAConfigAttribDecJPEG].value; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribDecJPEG].type)); for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (config->bits.rotation & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } if (attrib_list[VAConfigAttribDecProcessing].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s:", vaConfigAttribTypeStr(attrib_list[VAConfigAttribDecProcessing].type)); if (VA_DEC_PROCESSING_NONE == attrib_list[VAConfigAttribDecProcessing].value) printf(" VA_DEC_PROCESSING_NONE\n"); else if (VA_DEC_PROCESSING == attrib_list[VAConfigAttribDecProcessing].value) printf(" VA_DEC_PROCESSING\n"); } if (attrib_list[VAConfigAttribEncPackedHeaders].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncPackedHeaders].type)); if (VA_ENC_PACKED_HEADER_NONE == attrib_list[VAConfigAttribEncPackedHeaders].value) printf("VA_ENC_PACKED_HEADER_NONE\n"); else { static struct str_format list[] = { {VA_ENC_PACKED_HEADER_SEQUENCE, "VA_ENC_PACKED_HEADER_SEQUENCE"}, {VA_ENC_PACKED_HEADER_PICTURE, "VA_ENC_PACKED_HEADER_PICTURE"}, {VA_ENC_PACKED_HEADER_SLICE, "VA_ENC_PACKED_HEADER_SLICE"}, {VA_ENC_PACKED_HEADER_MISC, "VA_ENC_PACKED_HEADER_MISC"}, {VA_ENC_PACKED_HEADER_RAW_DATA, "VA_ENC_PACKED_HEADER_RAW_DATA"}, }; for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribEncPackedHeaders].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } } if (attrib_list[VAConfigAttribEncInterlaced].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncInterlaced].type)); if (VA_ENC_INTERLACED_NONE == attrib_list[VAConfigAttribEncInterlaced].value) printf("VA_ENC_INTERLACED_NONE\n"); else { static struct str_format list[] = { {VA_ENC_INTERLACED_FRAME, "VA_ENC_INTERLACED_FRAME"}, {VA_ENC_INTERLACED_FIELD, "VA_ENC_INTERLACED_FIELD"}, {VA_ENC_INTERLACED_MBAFF, "VA_ENC_INTERLACED_MBAFF"}, {VA_ENC_INTERLACED_PAFF, "VA_ENC_INTERLACED_PAFF"}, {VA_ENC_PACKED_HEADER_RAW_DATA, "VA_ENC_PACKED_HEADER_RAW_DATA"}, }; for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribEncInterlaced].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } } if (attrib_list[VAConfigAttribEncMaxRefFrames].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncMaxRefFrames].type)); printf("l0=%d\n", attrib_list[VAConfigAttribEncMaxRefFrames].value & 0xffff); printf("%-*sl1=%d\n", 45, "", (attrib_list[VAConfigAttribEncMaxRefFrames].value >> 16) & 0xffff); } if (attrib_list[VAConfigAttribEncMaxSlices].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: %d\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncMaxSlices].type), attrib_list[VAConfigAttribEncMaxRefFrames].value); } if (attrib_list[VAConfigAttribEncSliceStructure].value != VA_ATTRIB_NOT_SUPPORTED) { static struct str_format list[] = { {VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS, "VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS"}, {VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS, "VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS"}, {VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS, "VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS"}, {VA_ENC_SLICE_STRUCTURE_MAX_SLICE_SIZE, "VA_ENC_SLICE_STRUCTURE_MAX_SLICE_SIZE"}, {VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS, "VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS"}, }; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncSliceStructure].type)); for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribEncSliceStructure].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } if (attrib_list[VAConfigAttribEncMacroblockInfo].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: supported\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncMacroblockInfo].type)); } if (attrib_list[VAConfigAttribMaxPictureWidth].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: %d\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribMaxPictureWidth].type), attrib_list[VAConfigAttribMaxPictureWidth].value); } if (attrib_list[VAConfigAttribMaxPictureHeight].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: %d\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribMaxPictureHeight].type), attrib_list[VAConfigAttribMaxPictureHeight].value); } if (attrib_list[VAConfigAttribEncJPEG].value & (~VA_ATTRIB_NOT_SUPPORTED)) { VAConfigAttribValEncJPEG *config = (VAConfigAttribValEncJPEG*)&attrib_list[VAConfigAttribEncJPEG].value; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncJPEG].type)); printf("rithmatic_coding_mode=%d\n", config->bits.arithmatic_coding_mode); printf("%-*sprogressive_dct_mode=%d\n", 45, "", config->bits.progressive_dct_mode); printf("%-*snon_interleaved_mode=%d\n", 45, "", config->bits.non_interleaved_mode); printf("%-*sdifferential_mode=%d\n", 45, "", config->bits.differential_mode); printf("%-*sdifferential_mode=%d\n", 45, "", config->bits.differential_mode); printf("%-*smax_num_components=%d\n", 45, "", config->bits.max_num_components); printf("%-*smax_num_scans=%d\n", 45, "", config->bits.max_num_scans); printf("%-*smax_num_huffman_tables=%d\n", 45, "", config->bits.max_num_huffman_tables); printf("%-*smax_num_quantization_tables=%d\n", 45, "", config->bits.max_num_quantization_tables); } if (attrib_list[VAConfigAttribEncQualityRange].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: number of supported quality levels is %d\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncQualityRange].type), attrib_list[VAConfigAttribEncQualityRange].value <= 1 ? 1 :attrib_list[VAConfigAttribEncQualityRange].value); } if (attrib_list[VAConfigAttribEncQuantization].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s:", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncQuantization].type)); if (VA_ENC_QUANTIZATION_NONE == attrib_list[VAConfigAttribEncQuantization].value) printf(" VA_ENC_QUANTIZATION_NONE\n"); else if (VA_ENC_QUANTIZATION_TRELLIS_SUPPORTED == attrib_list[VAConfigAttribEncQuantization].value) printf(" VA_ENC_QUANTIZATION_TRELLIS_SUPPORTED\n"); } if (attrib_list[VAConfigAttribEncIntraRefresh].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncIntraRefresh].type)); if (VA_ENC_INTRA_REFRESH_NONE == attrib_list[VAConfigAttribEncIntraRefresh].value) printf("VA_ENC_INTRA_REFRESH_NONE\n"); else { static struct str_format list[] = { {VA_ENC_INTRA_REFRESH_ROLLING_COLUMN, "VA_ENC_INTRA_REFRESH_ROLLING_COLUMN"}, {VA_ENC_INTRA_REFRESH_ROLLING_ROW, "VA_ENC_INTRA_REFRESH_ROLLING_ROW"}, {VA_ENC_INTRA_REFRESH_ADAPTIVE, "VA_ENC_INTRA_REFRESH_ADAPTIVE"}, {VA_ENC_INTRA_REFRESH_CYCLIC, "VA_ENC_INTRA_REFRESH_CYCLIC"}, {VA_ENC_INTRA_REFRESH_P_FRAME, "VA_ENC_INTRA_REFRESH_P_FRAME"}, {VA_ENC_INTRA_REFRESH_B_FRAME, "VA_ENC_INTRA_REFRESH_B_FRAME"}, {VA_ENC_INTRA_REFRESH_MULTI_REF, "VA_ENC_INTRA_REFRESH_MULTI_REF"}, }; for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribEncIntraRefresh].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } } if (attrib_list[VAConfigAttribEncSkipFrame].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: supported\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncSkipFrame].type)); } if (attrib_list[VAConfigAttribEncROI].value & (~VA_ATTRIB_NOT_SUPPORTED)) { VAConfigAttribValEncROI *config = (VAConfigAttribValEncROI*)&attrib_list[VAConfigAttribEncROI].value; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncROI].type)); printf("num_roi_regions=%d\n", config->bits.num_roi_regions); printf("%-*sroi_rc_priority_support=%d\n", 45, "", config->bits.roi_rc_priority_support); printf("%-*sroi_rc_qp_delta_support=%d\n", 45, "", config->bits.roi_rc_qp_delta_support); } if (attrib_list[VAConfigAttribEncRateControlExt].value & (~VA_ATTRIB_NOT_SUPPORTED)) { VAConfigAttribValEncRateControlExt *config = (VAConfigAttribValEncRateControlExt*)&attrib_list[VAConfigAttribEncRateControlExt].value; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncRateControlExt].type)); printf("max_num_temporal_layers_minus1=%d ", config->bits.max_num_temporal_layers_minus1); printf("temporal_layer_bitrate_control_flag=%d\n", config->bits.temporal_layer_bitrate_control_flag); } if (attrib_list[VAConfigAttribProcessingRate].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribProcessingRate].type)); static struct str_format list[] = { {VA_PROCESSING_RATE_ENCODE, "VA_PROCESSING_RATE_ENCODE"}, {VA_PROCESSING_RATE_DECODE, "VA_PROCESSING_RATE_DECODE"}, }; for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribProcessingRate].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } if (attrib_list[VAConfigAttribEncDirtyRect].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: number of supported regions is %d\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncDirtyRect].type), attrib_list[VAConfigAttribEncDirtyRect].value); } if (attrib_list[VAConfigAttribEncParallelRateControl].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: number of supported layers is %d\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncParallelRateControl].type), attrib_list[VAConfigAttribEncParallelRateControl].value); } if (attrib_list[VAConfigAttribEncDynamicScaling].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: supported\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncDynamicScaling].type)); } if (attrib_list[VAConfigAttribFrameSizeToleranceSupport].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: %d\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribFrameSizeToleranceSupport].type), attrib_list[VAConfigAttribFrameSizeToleranceSupport].value); } if (attrib_list[VAConfigAttribFEIFunctionType].value != VA_ATTRIB_NOT_SUPPORTED) { printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribFEIFunctionType].type)); static struct str_format list[] = { {VA_FEI_FUNCTION_ENC, "VA_FEI_FUNCTION_ENC"}, {VA_FEI_FUNCTION_PAK, "VA_FEI_FUNCTION_PAK"}, {VA_FEI_FUNCTION_ENC_PAK, "VA_FEI_FUNCTION_ENC_PAK"}, }; for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribFEIFunctionType].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } if (attrib_list[VAConfigAttribFEIMVPredictors].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: number of supported MV predictors is %d\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribFEIMVPredictors].type), attrib_list[VAConfigAttribFEIMVPredictors].value); } if (attrib_list[VAConfigAttribStats].value & (~VA_ATTRIB_NOT_SUPPORTED)) { VAConfigAttribValStats *config = (VAConfigAttribValStats*)&attrib_list[VAConfigAttribStats].value; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribStats].type)); printf("max_num_past_references=%d\n", config->bits.max_num_past_references); printf("%-*smax_num_future_references=%d\n", 45, "", config->bits.max_num_future_references); printf("%-*snum_outputs=%d\n", 45, "", config->bits.num_outputs); printf("%-*sinterlaced=%d\n", 45, "", config->bits.interlaced); } if (attrib_list[VAConfigAttribEncTileSupport].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: supported\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribEncTileSupport].type)); } if (attrib_list[VAConfigAttribQPBlockSize].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: supported\n", vaConfigAttribTypeStr(attrib_list[VAConfigAttribQPBlockSize].type)); } if (attrib_list[VAConfigAttribMaxFrameSize].value & (~VA_ATTRIB_NOT_SUPPORTED)) { VAConfigAttribValMaxFrameSize *config = (VAConfigAttribValMaxFrameSize*)&attrib_list[VAConfigAttribMaxFrameSize].value; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribMaxFrameSize].type)); printf("max_frame_size=%d\n", config->bits.max_frame_size); printf("%-*smultiple_pass=%d\n", 45, "", config->bits.multiple_pass); } if (attrib_list[VAConfigAttribPredictionDirection].value & (~VA_ATTRIB_NOT_SUPPORTED)) { printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribPredictionDirection].type)); static struct str_format list[] = { {VA_PREDICTION_DIRECTION_PREVIOUS,"VA_PREDICTION_DIRECTION_PREVIOUS"}, {VA_PREDICTION_DIRECTION_FUTURE, "VA_PREDICTION_DIRECTION_FUTURE"}, }; for (i = 0, n = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (attrib_list[VAConfigAttribPredictionDirection].value & list[i].format) { printf("%-*s%s\n", 0 == n ? 0 : 45, "", list[i].name); n++; } } } if (attrib_list[VAConfigAttribMultipleFrame].value & (~VA_ATTRIB_NOT_SUPPORTED)) { VAConfigAttribValMultipleFrame *config = (VAConfigAttribValMultipleFrame*)&attrib_list[VAConfigAttribMultipleFrame].value; printf(" %-39s: ", vaConfigAttribTypeStr(attrib_list[VAConfigAttribMultipleFrame].type)); printf("max_num_concurrent_frames=%d\n", config->bits.max_num_concurrent_frames); printf("%-*smixed_quality_level=%d\n", 45, "", config->bits.mixed_quality_level); } printf("\n"); return 0; } int main(int argc, const char* argv[]) { VADisplay va_dpy; VAStatus va_status; int major_version, minor_version; const char *driver; const char *name = strrchr(argv[0], '/'); VAProfile profile, *profile_list = NULL; int num_profiles, max_num_profiles, i; VAEntrypoint entrypoint, *entrypoints = NULL; int num_entrypoint = 0; int ret_val = 0; if (name) name++; else name = argv[0]; parse_args(name, argc, (char **)argv); va_dpy = va_open_display(); if (NULL == va_dpy) { fprintf(stderr, "%s: vaGetDisplay() failed\n", name); return 2; } va_status = vaInitialize(va_dpy, &major_version, &minor_version); CHECK_VASTATUS(va_status, "vaInitialize", 3); printf("%s: VA-API version: %d.%d (libva %s)\n", name, major_version, minor_version, LIBVA_VERSION_S); driver = vaQueryVendorString(va_dpy); printf("%s: Driver version: %s\n", name, driver ? driver : "<unknown>"); num_entrypoint = vaMaxNumEntrypoints (va_dpy); entrypoints = malloc (num_entrypoint * sizeof (VAEntrypoint)); if (!entrypoints) { printf ("Failed to allocate memory for entrypoint list\n"); ret_val = -1; goto error; } max_num_profiles = vaMaxNumProfiles(va_dpy); profile_list = malloc(max_num_profiles * sizeof(VAProfile)); if (!profile_list) { printf("Failed to allocate memory for profile list\n"); ret_val = 5; goto error; } va_status = vaQueryConfigProfiles(va_dpy, profile_list, &num_profiles); CHECK_VASTATUS(va_status, "vaQueryConfigProfiles", 6); if (show_all_opt) { printf("%s: Supported config attributes per profile/entrypoint pair\n", name); for (i = 0; i < num_profiles; i++) { profile = profile_list[i]; va_status = vaQueryConfigEntrypoints(va_dpy, profile, entrypoints, &num_entrypoint); if (va_status == VA_STATUS_ERROR_UNSUPPORTED_PROFILE) continue; CHECK_VASTATUS(va_status, "vaQueryConfigEntrypoints", 4); for (entrypoint = 0; entrypoint < num_entrypoint; entrypoint++) { ret_val = show_config_attributes(va_dpy, profile_list[i], entrypoints[entrypoint]); if (ret_val) { printf("Failed to get config attributes\n"); goto error; } } } } else { printf("%s: Supported profile and entrypoints\n", name); for (i = 0; i < num_profiles; i++) { profile = profile_list[i]; va_status = vaQueryConfigEntrypoints(va_dpy, profile, entrypoints, &num_entrypoint); if (va_status == VA_STATUS_ERROR_UNSUPPORTED_PROFILE) continue; CHECK_VASTATUS(va_status, "vaQueryConfigEntrypoints", 4); for (entrypoint = 0; entrypoint < num_entrypoint; entrypoint++) { printf(" %-32s: %s\n", vaProfileStr(profile), vaEntrypointStr(entrypoints[entrypoint])); } } } error: free(entrypoints); free(profile_list); vaTerminate(va_dpy); va_close_display(va_dpy); return ret_val; }
<filename>test/litest-device-yubikey.c /* * Copyright © 2014 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #if HAVE_CONFIG_H #include "config.h" #endif #include "litest.h" #include "litest-int.h" static void litest_yubikey_setup(void) { struct litest_device *d = litest_create_device(LITEST_YUBIKEY); litest_set_current_device(d); } static struct input_id input_id = { .bustype = 0x3, .vendor = 0x1050, .product = 0x10, }; static int events[] = { EV_KEY, KEY_ESC, EV_KEY, KEY_1, EV_KEY, KEY_2, EV_KEY, KEY_3, EV_KEY, KEY_4, EV_KEY, KEY_5, EV_KEY, KEY_6, EV_KEY, KEY_7, EV_KEY, KEY_8, EV_KEY, KEY_9, EV_KEY, KEY_0, EV_KEY, KEY_MINUS, EV_KEY, KEY_EQUAL, EV_KEY, KEY_BACKSPACE, EV_KEY, KEY_TAB, EV_KEY, KEY_Q, EV_KEY, KEY_W, EV_KEY, KEY_E, EV_KEY, KEY_R, EV_KEY, KEY_T, EV_KEY, KEY_Y, EV_KEY, KEY_U, EV_KEY, KEY_I, EV_KEY, KEY_O, EV_KEY, KEY_P, EV_KEY, KEY_LEFTBRACE, EV_KEY, KEY_RIGHTBRACE, EV_KEY, KEY_ENTER, EV_KEY, KEY_LEFTCTRL, EV_KEY, KEY_A, EV_KEY, KEY_S, EV_KEY, KEY_D, EV_KEY, KEY_F, EV_KEY, KEY_G, EV_KEY, KEY_H, EV_KEY, KEY_J, EV_KEY, KEY_K, EV_KEY, KEY_L, EV_KEY, KEY_SEMICOLON, EV_KEY, KEY_APOSTROPHE, EV_KEY, KEY_GRAVE, EV_KEY, KEY_LEFTSHIFT, EV_KEY, KEY_BACKSLASH, EV_KEY, KEY_Z, EV_KEY, KEY_X, EV_KEY, KEY_C, EV_KEY, KEY_V, EV_KEY, KEY_B, EV_KEY, KEY_N, EV_KEY, KEY_M, EV_KEY, KEY_COMMA, EV_KEY, KEY_DOT, EV_KEY, KEY_SLASH, EV_KEY, KEY_RIGHTSHIFT, EV_KEY, KEY_KPASTERISK, EV_KEY, KEY_LEFTALT, EV_KEY, KEY_SPACE, EV_KEY, KEY_CAPSLOCK, EV_KEY, KEY_F1, EV_KEY, KEY_F2, EV_KEY, KEY_F3, EV_KEY, KEY_F4, EV_KEY, KEY_F5, EV_KEY, KEY_F6, EV_KEY, KEY_F7, EV_KEY, KEY_F8, EV_KEY, KEY_F9, EV_KEY, KEY_F10, EV_KEY, KEY_NUMLOCK, EV_KEY, KEY_SCROLLLOCK, EV_KEY, KEY_KP7, EV_KEY, KEY_KP8, EV_KEY, KEY_KP9, EV_KEY, KEY_KPMINUS, EV_KEY, KEY_KP4, EV_KEY, KEY_KP5, EV_KEY, KEY_KP6, EV_KEY, KEY_KPPLUS, EV_KEY, KEY_KP1, EV_KEY, KEY_KP2, EV_KEY, KEY_KP3, EV_KEY, KEY_KP0, EV_KEY, KEY_KPDOT, EV_KEY, KEY_102ND, EV_KEY, KEY_F11, EV_KEY, KEY_F12, EV_KEY, KEY_KPENTER, EV_KEY, KEY_RIGHTCTRL, EV_KEY, KEY_KPSLASH, EV_KEY, KEY_SYSRQ, EV_KEY, KEY_RIGHTALT, EV_KEY, KEY_HOME, EV_KEY, KEY_UP, EV_KEY, KEY_PAGEUP, EV_KEY, KEY_LEFT, EV_KEY, KEY_RIGHT, EV_KEY, KEY_END, EV_KEY, KEY_DOWN, EV_KEY, KEY_PAGEDOWN, EV_KEY, KEY_INSERT, EV_KEY, KEY_DELETE, EV_KEY, KEY_PAUSE, EV_KEY, KEY_LEFTMETA, EV_KEY, KEY_RIGHTMETA, EV_KEY, KEY_COMPOSE, EV_LED, LED_NUML, EV_LED, LED_CAPSL, EV_LED, LED_SCROLLL, EV_LED, LED_COMPOSE, EV_LED, LED_KANA, -1, -1, }; struct litest_test_device litest_yubikey_device = { .type = LITEST_YUBIKEY, .features = LITEST_KEYS, .shortname = "yubikey", .setup = litest_yubikey_setup, .interface = NULL, .name = "Yubico Yubico Yubikey II", .id = &input_id, .events = events, .absinfo = NULL, };
<gh_stars>10-100 /* * Copyright 2020-2021, Synopsys, Inc. * All rights reserved. * * This source code is licensed under the BSD-3-Clause license found in * the LICENSE file in the root directory of this source tree. * */ #ifndef _MLI_KRN_L2_NORMALIZE_REF_H_ #define _MLI_KRN_L2_NORMALIZE_REF_H_ #include "mli_check.h" #include "mli_config.h" #include "mli_debug.h" #include "mli_helpers_api.h" #include "mli_math.h" #include "mli_mem_info.h" #include "mli_prv_dsp.h" #include "mli_prv_tensor.h" #include "mli_types.h" #include "mli_prv_activation_lut.h" #include "mli_prv_lut.h" #if defined(__FXAPI__) /* FIXME: Remove this when known problem with dsp mli_math will be solved */ typedef int64_t acc_t; #else typedef mli_acc40_t acc_t; #endif const int kL2NormAsymZeroPoint = 0; const int kL2NormOutputShift = 7; const int kL2NormLutFracBits = 8; namespace mli { namespace krn { namespace ref { static MLI_FORCE_INLINE int16_t normalize_sum( acc_t sum_acc, int *norm_shift) { int norm_shift_val = mli_math_norm_fx<acc_t, int>(sum_acc); /* To Cast acc_t to int16_t */ norm_shift_val = (sizeof(acc_t) - sizeof(int16_t)) * 8 - norm_shift_val; /* Adjust norm_shift to even number because we are going to divide it by 2 */ if ((norm_shift_val & 0x1) == 0x1) { norm_shift_val += 1; } *norm_shift = norm_shift_val; /* Cast Sum_acc to Q7.8 to bring it to LUT input range */ return mli_math_cast_fx<acc_t, int16_t>(sum_acc, norm_shift_val); } template<typename io_T, bool convert, bool one_dim_with_mem_stride> static MLI_FORCE_INLINE int16_t compute_normalized_sum_square_one_dim( const MLI_PTR(io_T) vec_in, int16_t in_zp, int *norm_shift, const int one_dim_shape, const int one_dim_mem_stride) { /* Accumulation through MAC */ acc_t sum_acc = mli_math_mul_fx<int16_t, acc_t>(0, 0); for (int idx = 0; idx < one_dim_shape; idx++) { int16_t input = vec_in[idx * one_dim_mem_stride]; if (convert) { input = mli_math_sub_fx(input, in_zp); } sum_acc = mli_math_mac_fx(sum_acc, input, input); } return normalize_sum(sum_acc, norm_shift); } template<typename io_T, bool convert> static MLI_FORCE_INLINE int16_t compute_normalized_sum_square( struct generic_tensor_private_t<MLI_PTR(io_T)> *in_prv, const MLI_PTR(io_T) vec_in, int16_t in_zp, int *norm_shift) { /* Accumulation through MAC */ acc_t sum_acc = mli_math_mul_fx<int16_t, acc_t>(0, 0); for (int pos0 = 0; pos0 < in_prv->shape[0]; pos0++) { for (int pos1 = 0; pos1 < in_prv->shape[1]; pos1++) { for (int pos2 = 0; pos2 < in_prv->shape[2]; pos2++) { for (int pos3 = 0; pos3 < in_prv->shape[3]; pos3++) { int16_t input = vec_in[POS(in_prv, pos0, pos1, pos2, pos3)]; if (convert) { input = mli_math_sub_fx(input, in_zp); } sum_acc = mli_math_mac_fx(sum_acc, input, input); } } } } return normalize_sum(sum_acc, norm_shift); } template<typename io_T, bool convert> static MLI_FORCE_INLINE io_T normalize_elem( int16_t input, int16_t scale, int16_t in_zp, int shift) { if (convert) { input = mli_math_sub_fx(input, in_zp); } mli_acc32_t tmp_acc = mli_math_mul_fx<int16_t, mli_acc32_t>(scale, input); return mli_math_acc_cast_fx<io_T, mli_acc32_t>(tmp_acc, shift); } template<typename io_T, bool convert, bool one_dim_with_mem_stride> static MLI_FORCE_INLINE void normalize_tensor_one_dim( const MLI_PTR(io_T) vec_in, MLI_PTR(io_T) vec_out, int16_t scale, int16_t in_zp, int shift, const int one_dim_shape, const int one_dim_in_mem_stride, const int one_dim_out_mem_stride) { // final result: normalizing for (int idx = 0; idx < one_dim_shape; idx++) { int16_t input = vec_in[idx * one_dim_in_mem_stride]; vec_out[idx * one_dim_out_mem_stride] = normalize_elem<io_T, convert>(input, scale, in_zp, shift); } } template<typename io_T, bool convert> static MLI_FORCE_INLINE void normalize_tensor( struct generic_tensor_private_t<MLI_PTR(io_T)> *in_prv, struct generic_tensor_private_t<MLI_PTR(io_T)> *out_prv, const MLI_PTR(io_T) vec_in, MLI_PTR(io_T) vec_out, int16_t scale, int16_t in_zp, int shift) { // final result: normalizing for (int pos0 = 0; pos0 < in_prv->shape[0]; pos0++) { for (int pos1 = 0; pos1 < in_prv->shape[1]; pos1++) { for (int pos2 = 0; pos2 < in_prv->shape[2]; pos2++) { for (int pos3 = 0; pos3 < in_prv->shape[3]; pos3++) { int16_t input = vec_in[POS(in_prv, pos0, pos1, pos2, pos3)]; vec_out[POS(out_prv, pos0, pos1, pos2, pos3)] = normalize_elem<io_T, convert>(input, scale, in_zp, shift); } } } } } template <typename io_T, bool convert> static MLI_FORCE_INLINE mli_status mli_krn_l2_normalize_run(const mli_tensor *in, const mli_tensor *epsilon, const mli_l2_normalize_cfg *cfg, mli_tensor *out, const mli_lut *lut) { /* Epsilon Tensor is Unused */ mli_prv_fx_init_dsp_ctrl(); MLI_ASSERT(MLI_MAX_RANK == 4); const MLI_PTR(io_T) vec_in = nullptr; MLI_PTR(io_T) vec_out = nullptr; const MLI_PTR(io_T) in_ptr = mli_prv_tensor_data_ptr<MLI_PTR(io_T)>(in); MLI_PTR(io_T) out_ptr = mli_prv_tensor_data_ptr<MLI_PTR(io_T)>(out); int16_t in_zp = 0; int out_shift = 0; if (convert) { out->el_params.sa.type = MLI_EL_PARAM_SC16_ZP16; out->el_params.sa.dim = -1; in_zp = in->el_params.sa.zero_point.mem.i16; out->el_params.sa.zero_point.mem.i16 = kL2NormAsymZeroPoint; out->el_params.sa.scale.mem.i16 = 1; out->el_params.sa.scale_frac_bits.mem.i8 = kL2NormOutputShift; out_shift = out->el_params.sa.scale_frac_bits.mem.i8; } else { out->el_params.fx.frac_bits = (sizeof(io_T) * 8) - kTransfFuncIntBits - 1; out_shift = out->el_params.fx.frac_bits; } /* Per Tensor Case */ if ( cfg->axis == -1 ) { int shape = mli_prv_squash_tensor_to_one_dim(in, out); if (shape) { int norm_shift; /* inv_sqrt = 1/sqrt(sum_acc) * sum_acc can be approximated to sum_acc = (sum_acc_cast * 2^norm_shift) * inv_sqrt = 1/sqrt(sum_acc * 2^-norm_shift * 2^norm_shift) * = 1/sqrt(sum_acc_cast * 2^norm_shift) * = 1/(2^(norm_shift/2) * sqrt(sum_acc_cast)) * = 2^(-norm_shift/2) * (1/sqrt(sum_acc_cast)) */ const int16_t sum_acc_cast = mli::krn::compute_normalized_sum_square_one_dim<io_T, convert>( in_ptr, in_zp, &norm_shift, shape); /* Activation lookup table of input Q7.8 */ int16_t out_lut = mli::krn::activation_lut_one_elem_interpolate<int16_t, int16_t, /* convert_input */ false, /* convert_output */ false>( sum_acc_cast, lut, kL2NormLutFracBits); /* (Norm_shift + kL2NormLutFracBits) is divided by 2 because of the square root */ int shift = lut->out_frac_bits + ((norm_shift + kL2NormLutFracBits) >> 1) - out_shift; // final result: normalizing mli::krn::normalize_tensor_one_dim<io_T, convert>(in_ptr, out_ptr, out_lut, in_zp, shift, shape); } else { /* Get Generic Private Tensor */ auto in_prv = mli_prv_get_generic_tensor<MLI_PTR(io_T)>(in); auto out_prv = mli_prv_get_generic_tensor<MLI_PTR(io_T)>(out); /* Reordering shapes/mem_stirde to place the inner most dim at last shape */ mli_prv_squash_generic_tensor<MLI_PTR(io_T)>(&in_prv, &out_prv); int norm_shift; const int16_t sum_acc_cast = mli::krn::compute_normalized_sum_square<io_T, convert>(&in_prv, in_ptr, in_zp, &norm_shift); int16_t out_lut = mli::krn::activation_lut_one_elem_interpolate<int16_t, int16_t, /* convert_input */ false, /* convert_output */ false>( sum_acc_cast, lut, kL2NormLutFracBits); int shift = lut->out_frac_bits + ((norm_shift + kL2NormLutFracBits) >> 1) - out_shift; mli::krn::normalize_tensor<io_T, convert>(&in_prv, &out_prv, in_ptr, out_ptr, out_lut, in_zp, shift); } } else { /* Get Generic Private Tensor */ auto in_prv = mli_prv_get_generic_tensor<MLI_PTR(io_T)>(in); auto out_prv = mli_prv_get_generic_tensor<MLI_PTR(io_T)>(out); /* Get Non Axis Tensor */ auto in_non_axis_prv = mli_prv_get_non_axis_tensor<MLI_PTR(io_T)>(&in_prv, cfg->axis); auto out_non_axis_prv = mli_prv_get_non_axis_tensor<MLI_PTR(io_T)>(&out_prv, cfg->axis); /* Get Axis Params */ int axis_shape = in_prv.shape[cfg->axis]; if (cfg->axis == ((int)in->rank - 1)) { for (int dim0 = 0; dim0 < in_non_axis_prv.shape[0]; dim0++) { for (int dim1 = 0; dim1 < in_non_axis_prv.shape[1]; dim1++) { for (int dim2 = 0; dim2 < in_non_axis_prv.shape[2]; dim2++) { vec_in = &in_ptr[dim0 * in_non_axis_prv.mem_stride[0] + dim1 * in_non_axis_prv.mem_stride[1] + dim2 * in_non_axis_prv.mem_stride[2]]; vec_out = &out_ptr[dim0 * out_non_axis_prv.mem_stride[0] + dim1 * out_non_axis_prv.mem_stride[1] + dim2 * out_non_axis_prv.mem_stride[2]]; int norm_shift; const int16_t sum_acc_cast = mli::krn::compute_normalized_sum_square_one_dim <io_T, convert>( vec_in, in_zp, &norm_shift, axis_shape); int16_t out_lut = mli::krn::activation_lut_one_elem_interpolate<int16_t, int16_t, /* convert_input */ false, /* convert_output */ false>( sum_acc_cast, lut, kL2NormLutFracBits); int shift = lut->out_frac_bits + ((norm_shift + kL2NormLutFracBits) >> 1) - out_shift; mli::krn::normalize_tensor_one_dim<io_T, convert>(vec_in, vec_out, out_lut, in_zp, shift, axis_shape); } } } } else { /* Get Axis Strides */ int axis_in_mem_stride = in_prv.mem_stride[cfg->axis]; int axis_out_mem_stride = out_prv.mem_stride[cfg->axis]; for (int dim0 = 0; dim0 < in_non_axis_prv.shape[0]; dim0++) { for (int dim1 = 0; dim1 < in_non_axis_prv.shape[1]; dim1++) { for (int dim2 = 0; dim2 < in_non_axis_prv.shape[2]; dim2++) { vec_in = &in_ptr[dim0 * in_non_axis_prv.mem_stride[0] + dim1 * in_non_axis_prv.mem_stride[1] + dim2 * in_non_axis_prv.mem_stride[2]]; vec_out = &out_ptr[dim0 * out_non_axis_prv.mem_stride[0] + dim1 * out_non_axis_prv.mem_stride[1] + dim2 * out_non_axis_prv.mem_stride[2]]; int norm_shift; const int16_t sum_acc_cast = mli::krn::compute_normalized_sum_square_one_dim <io_T, convert, /* one_dim_with_mem_stride */ true>( vec_in, in_zp, &norm_shift, axis_shape, axis_in_mem_stride); int16_t out_lut = mli::krn::activation_lut_one_elem_interpolate<int16_t, int16_t, /* convert_input */ false, /* convert_output */ false>( sum_acc_cast, lut, kL2NormLutFracBits); int shift = lut->out_frac_bits + ((norm_shift + kL2NormLutFracBits) >> 1) - out_shift; mli::krn::normalize_tensor_one_dim<io_T, convert, /* one_dim_with_mem_stride */ true>( vec_in, vec_out, out_lut, in_zp, shift, axis_shape, axis_in_mem_stride, axis_out_mem_stride); } } } } } return MLI_STATUS_OK; } } // namespace ref } // namespace krn } // namespace mli #endif // _MLI_KRN_L2_NORMALIZE_REF_H_
#ifndef YANDEXDISK_H #define YANDEXDISK_H #include "yandex-disk-name-and-version.h" #include "status-parser.h" #include <QObject> #include <QTimer> class YandexDisk: public QObject { Q_OBJECT public: explicit YandexDisk(QObject* parent = nullptr); void showStatus() const; void start() const; void stop() const; const YandexDiskNameAndVersion& getNameAndVersion() const; QString getHelp() const; signals: void syncStatusChanged(const SyncStatus status); private: struct Output { bool finished = false; QString stdOutput; QString stdError; }; Output run(const QString& arguments, const int timeout_ms) const; void runAndShowOutput(const QString& command, const int timeout_ms) const; const char* processName{"yandex-disk"}; class YandexDiskNameAndVersionImpl: public YandexDiskNameAndVersion { public: explicit YandexDiskNameAndVersionImpl(const YandexDisk& yandexDisk); operator QString() const override; private: const YandexDisk& m_yandexDisk; }; YandexDiskNameAndVersionImpl m_yandexDiskNameAndVersionImpl; SyncStatus m_syncStatus = SyncStatus::Unknown; void updateSyncStatus(); }; #endif // YANDEXDISK_H
<reponame>AutoDB/autoDB<filename>AutoDBTests/ConcurrencyModel.h<gh_stars>1-10 // // ConcurrencyModel.h // AutoDB // // Created by <NAME> on 2016-12-15. // Copyright © 2016 Aggressive Development AB. All rights reserved. // #import <UIKit/UIKit.h> #import "AutoModel.h" @interface ConcurrencyModel : AutoModel {} @property (nonatomic) NSString *name; @property (nonatomic) NSDate *last_update; @property (nonatomic) NSData *lots_of_data; @property (nonatomic) double double_number; @property (nonatomic) int int_number; @property (nonatomic) int int_number_change_for_each_test_12312312312312312312312312312312312323; + (instancetype) newSpecialModel; @end
/* File: linked_list.c * * Purpose: Implement an unsorted linked list with ops insert (at head), * print, member, delete, free_list. * * Input: Single character lower case letters to indicate operators, * followed by arguments needed by operators. * Output: Results of operations. * * Compile: gcc -g -Wall -o linked_list linked_list.c * Run: ./linked_list * * Notes: * 1. Repeated values are allowed in the list * 2. delete only deletes the first occurrence of a value * 3. Program assumes an int will be entered when prompted * for one. */ #include <stdio.h> #include <stdlib.h> struct list_node_s { int data; struct list_node_s* next_p; }; int Member(struct list_node_s* head_p, int val); struct list_node_s* Insert(struct list_node_s* head_p, int val); struct list_node_s* Delete(struct list_node_s* head_p, int val); void Print(struct list_node_s* head_p); struct list_node_s* Free_list(struct list_node_s* head_p); char Get_command(void); int Get_value(void); /*-----------------------------------------------------------------*/ int main(void) { char command; int value; struct list_node_s* head_p = NULL; /* start with empty list */ command = Get_command(); while (command != 'q' && command != 'Q') { switch (command) { case 'i': case 'I': value = Get_value(); head_p = Insert(head_p, value); break; case 'p': case 'P': Print(head_p); break; case 'm': case 'M': value = Get_value(); if (Member(head_p, value)) printf("%d is in the list\n", value); else printf("%d is not in the list\n", value); break; case 'd': case 'D': value = Get_value(); head_p = Delete(head_p, value); break; case 'f': case 'F': head_p = Free_list(head_p); break; default: printf("There is no %c command\n", command); printf("Please try again\n"); } command = Get_command(); } head_p = Free_list(head_p); return 0; } /* main */ /*----------------------------------------------------------------- * Function: Member * Purpose: search list for val * Input args: head_p: pointer to head of list * val: value to search for * Return val: 1 if val is in list, 0 otherwise */ int Member(struct list_node_s* head_p, int val) { struct list_node_s* curr_p = head_p; while (curr_p != NULL) { if (curr_p->data == val) return 1; else curr_p = curr_p->next_p; } return 0; } /* Member */ /*----------------------------------------------------------------- * Function: Delete * Purpose: Delete the first occurrence of val from list * Input args: head_p: pointer to the head of the list * val: value to be deleted * Return val: Possibly updated pointer to head of list */ struct list_node_s* Delete(struct list_node_s* head_p, int val) { struct list_node_s* curr_p = head_p; struct list_node_s* pred_p = NULL; /* Points to predecessor of curr_p or * NULL when curr_p is first node */ /* Find node containing val and predecessor of this node */ while (curr_p != NULL) { if (curr_p->data == val) { if (pred_p == NULL) // head case { printf("\n removing from head! "); head_p = curr_p->next_p; // update head to next. free(curr_p); curr_p = head_p; Print(head_p); } else // middle case { printf("\n removing from middle! "); pred_p->next_p = curr_p->next_p; free(curr_p); curr_p = pred_p->next_p; Print(head_p); } } else { // curr_p->data != val pred_p = curr_p; curr_p = curr_p->next_p; } } return head_p; } /* Delete */ /*----------------------------------------------------------------- * Function: Insert * Purpose: Insert val at head of list * Input args: head_p: pointer to head of list * val: new value to be inserted * Return val: Pointer to head of list */ struct list_node_s* Insert(struct list_node_s* head_p, int val) { struct list_node_s* temp_p; temp_p = malloc(sizeof(struct list_node_s)); temp_p->data = val; temp_p->next_p = head_p; head_p = temp_p; return head_p; } /* Insert */ /*----------------------------------------------------------------- * Function: Print * Purpose: Print list on a single line of stdout * Input arg: head_p */ void Print(struct list_node_s* head_p) { struct list_node_s* curr_p = head_p; printf("list = "); while (curr_p != NULL) { printf("%d ", curr_p->data); curr_p = curr_p->next_p; } printf("\n"); } /* Print */ /*----------------------------------------------------------------- * Function: Free_list * Purpose: free each node in the list * Input arg: head_p: pointer to head of list * Return val: NULL pointer * Note: head_p is set to NULL on completion, indicating * list is empty. */ struct list_node_s* Free_list(struct list_node_s* head_p) { struct list_node_s* curr_p; struct list_node_s* temp_p; curr_p = head_p; while (curr_p != NULL) { temp_p = curr_p; curr_p = curr_p->next_p; free(temp_p); } head_p = NULL; return head_p; } /* Free_list */ /*----------------------------------------------------------------- * Function: Get_command * Purpose: Get a single character command from stdin * Return value: the first non-whitespace character from stdin */ char Get_command(void) { char c; printf("Please enter a command (i, p, m, d, f, q): "); /* Put the space before the %c so scanf will skip white space */ scanf(" %c", &c); return c; } /* Get_command */ /*----------------------------------------------------------------- * Function: Get_value * Purpose: Get an int from stdin * Return value: the next int in stdin * Note: Behavior unpredictable if an int isn't entered */ int Get_value(void) { int val; printf("Please enter a value: "); scanf("%d", &val); return val; } /* Get_value */
<filename>simd/avx512.h #ifndef __AVX512_H #define __AVX512_H /* * Compiler and architecture specific settings */ #include "arch.h" /* * Include supporting header files based on compiler and architecture */ #if defined(__INTEL_COMPILER) #include <zmmintrin.h> #else #include <x86intrin.h> #endif #include <stdint.h> // xx_t types /* * AVX512 512-bit wide vector units * Define constants required for SIMD module to function properly. */ #define SIMD_INT __m512i #define SIMD_FLT __m512 #define SIMD_DBL __m512d #define SIMD_WIDTH_BYTES 64 #define SIMD_STREAMS_32 16 #define SIMD_STREAMS_64 8 #define __VSPRNG_REQUIRED__ // identifies SIMD functions required for VSPRNG #define __SIMD_FUN_ATTR__ ARCH_ATTR_INLINE // force inline when no optimizations #define __SIMD_FUN_PREFIX__ inline static /* * Interface Legend * * simd_*_iXX = signed XX-bit integers * simd_*_uXX = unsigned XX-bit integers * simd_*_fXX = floating-point XX-bit elements * simd_*_XX = unsigned/signed XX-bit integers * simd_*_XX = (set functions) specifies width to consider for integer types * simd_* = datatype obtained from function overloading and parameters */ /************************** * Arithmetic intrinsics **************************/ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_add_i32(const SIMD_INT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { return _mm512_add_epi32(va, vb); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_add_i64(const SIMD_INT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { return _mm512_add_epi64(va, vb); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_add(const SIMD_FLT va, const SIMD_FLT vb) __VSPRNG_REQUIRED__ { return _mm512_add_ps(va, vb); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_add(const SIMD_DBL va, const SIMD_DBL vb) __VSPRNG_REQUIRED__ { return _mm512_add_pd(va, vb); } /*! * Fused multiply-add for 32/64-bit floating-point elements */ #if defined(__FMA__) __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_fmadd(const SIMD_FLT va, const SIMD_FLT vb, const SIMD_FLT vc) { return _mm512_fmadd_ps(va, vb, vc); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_fmadd(const SIMD_DBL va, const SIMD_DBL vb, const SIMD_DBL vc) { return _mm512_fmadd_pd(va, vb, vc); } #else __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_fmadd(const SIMD_FLT va, const SIMD_FLT vb, const SIMD_FLT vc) { const SIMD_FLT vab = _mm512_mul_ps(va, vb); return _mm512_add_ps(vab, vc); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_fmadd(const SIMD_DBL va, const SIMD_DBL vb, const SIMD_DBL vc) { const SIMD_DBL vab = _mm512_mul_pd(va, vb); return _mm512_add_pd(vab, vc); } #endif /*! * Multiply low unsigned 32-bit integers from each packed 64-bit elements * and store the unsigned 64-bit results */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_mul_u32(const SIMD_INT va, const SIMD_INT vb) { return _mm512_mul_epu32(va, vb); } /*! * Multiply low signed 32-bit integers from each packed 64-bit elements * and store the signed 64-bit results */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_mul_i32(const SIMD_INT va, const SIMD_INT vb) { return _mm512_mul_epi32(va, vb); } /*! * Perform 64-bit integer multiplication * NOTE: requires at least AVX512DQ for _mm512_mullo_epi64() */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ //SIMD_INT simd_mul_i64(const SIMD_INT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ SIMD_INT simd_mul_u64(const SIMD_INT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { return _mm512_mullo_epi64(va, vb); } /*! * Multiply packed 32-bit integers, produce intermediate 64-bit integers, * and store the low 32-bit results */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_mullo_i32(const SIMD_INT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { return _mm512_mullo_epi32(va, vb); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_mul(const SIMD_FLT va, const SIMD_FLT vb) __VSPRNG_REQUIRED__ { return _mm512_mul_ps(va, vb); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_mul(const SIMD_DBL va, const SIMD_DBL vb) __VSPRNG_REQUIRED__ { return _mm512_mul_pd(va, vb); } /******************************** * Integral logical intrinsics ********************************/ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_or(const SIMD_INT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { return _mm512_or_si512(va, vb); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_xor(const SIMD_INT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { return _mm512_xor_si512(va, vb); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_and(const SIMD_INT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { return _mm512_and_si512(va, vb); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_and(const SIMD_FLT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { return _mm512_and_ps(va, vb); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_and(const SIMD_DBL va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { return _mm512_and_pd(va, vb); } /***************************** * Shift/Shuffle intrinsics *****************************/ /* * Shift left (logical) packed 32/64-bit integers */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_sll_32(const SIMD_INT va, const int shft) __VSPRNG_REQUIRED__ { return _mm512_slli_epi32(va, (unsigned int)shft); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_srl_32(const SIMD_INT va, const int shft) __VSPRNG_REQUIRED__ { return _mm512_srli_epi32(va, (unsigned int)shft); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_sll_64(const SIMD_INT va, const int shft) __VSPRNG_REQUIRED__ { return _mm512_slli_epi64(va, (unsigned int)shft); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_srl_64(const SIMD_INT va, const int shft) __VSPRNG_REQUIRED__ { return _mm512_srli_epi64(va, (unsigned int)shft); } /* * Shuffle 32-bit elements using control value */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_shuffle_i32(const SIMD_INT va, const int ctrl) __VSPRNG_REQUIRED__ { return _mm512_shuffle_epi32(va, ctrl); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_shuffle_f32(const SIMD_FLT va, const SIMD_FLT vb, const int ctrl) __VSPRNG_REQUIRED__ { return _mm512_shuffle_ps(va, vb, ctrl); } /* * Merge either low/high parts from pair of registers * into a single register */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_merge_lo(const SIMD_INT va, const SIMD_INT vb) { const __m256i vb_lo = _mm512_castsi512_si256(vb); return _mm512_inserti64x4(va, vb_lo, 0x1); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_merge_lo(const SIMD_FLT va, const SIMD_FLT vb) __VSPRNG_REQUIRED__ { const __m256d vb_lo = _mm512_castpd512_pd256(vb); const SIMD_DBL vc = _mm512_insertf64x4(va, vb_lo, 0x1); return _mm512_castpd_ps(vc); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_merge_lo(const SIMD_DBL va, const SIMD_DBL vb) { const __m256d vb_lo = _mm512_castpd512_pd256(vb); return _mm512_insertf64x4(va, vb_lo, 0x1); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_merge_hi(const SIMD_INT va, const SIMD_INT vb) { const __m256i va_hi = _mm512_extracti64x4_epi64(va, 0x1); return _mm512_inserti64x4(vb, va_hi, 0x0); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_merge_hi(const SIMD_FLT va, const SIMD_FLT vb) { const __m256d va_hi = _mm512_extractf64x4_pd(va, 0x1); const SIMD_DBL vc = _mm512_insertf64x4(vb, va_hi, 0x0); return _mm512_castpd_ps(vc); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_merge_hi(const SIMD_DBL va, const SIMD_DBL vb) { const __m256d va_hi = _mm512_extractf64x4_pd(va, 0x1); return _mm512_insertf64x4(vb, va_hi, 0x0); } /*! * Pack and merge a pair of registers */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_packmerge_i32(const SIMD_INT va, const SIMD_INT vb) __VSPRNG_REQUIRED__ { // Pack va const int SIMD_INT va_pk = _mm512_maskz_compress_epi32(0x5555U, va); // Pack vb const int SIMD_INT vb_pk = _mm512_maskz_compress_epi32(0x5555U, vb); // Merge const __m256i vb_pk_lo = _mm512_castsi512_si256(vb_pk); return _mm512_inserti64x4(va_pk, vb_pk_lo, 0x1); } /******************* * Set intrinsics *******************/ /* * Set vector to zero. */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_set_zero(SIMD_INT * const va) __VSPRNG_REQUIRED__ { *va = _mm512_setzero_si512(); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_set_zero(SIMD_FLT * const va) __VSPRNG_REQUIRED__ { *va = _mm512_setzero_ps(); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_set_zero(SIMD_DBL * const va) __VSPRNG_REQUIRED__ { *va = _mm512_setzero_pd(); } /* * Set 32-bit integers to either 32/64 slots. */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set(const int sa) __VSPRNG_REQUIRED__ { return _mm512_set1_epi32(sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set_64(const int sa) __VSPRNG_REQUIRED__ { return _mm512_set1_epi64((long int)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set(const unsigned int sa) __VSPRNG_REQUIRED__ { return _mm512_set1_epi32((int)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set_64(const unsigned int sa) __VSPRNG_REQUIRED__ { return _mm512_set1_epi64((long int)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set(const long int sa) __VSPRNG_REQUIRED__ { return _mm512_set1_epi64(sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set(const unsigned long int sa) __VSPRNG_REQUIRED__ { return _mm512_set1_epi64((long int)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_set(const float sa) __VSPRNG_REQUIRED__ { return _mm512_set1_ps(sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_set(const double sa) __VSPRNG_REQUIRED__ { return _mm512_set1_pd(sa); } /*! * Set vector given an array. * Only required for non-contiguous 32-bit elements due to in-between padding, * 64-bit elements can use load instructions. */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set(const int * const sa, const int n) __VSPRNG_REQUIRED__ { if (n == SIMD_STREAMS_64) return _mm512_set_epi64((long int)sa[7], (long int)sa[6], (long int)sa[5], (long int)sa[4], (long int)sa[3], (long int)sa[2], (long int)sa[1], (long int)sa[0]); else if (n == SIMD_STREAMS_32) return _mm512_load_si512((SIMD_INT *)sa); else return _mm512_setzero_si512(); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set(const unsigned int * const sa, const int n) __VSPRNG_REQUIRED__ { if (n == SIMD_STREAMS_64) return _mm512_set_epi64((long int)sa[7], (long int)sa[6], (long int)sa[5], (long int)sa[4], (long int)sa[3], (long int)sa[2], (long int)sa[1], (long int)sa[0]); else if (n == SIMD_STREAMS_32) return _mm512_load_si512((SIMD_INT *)sa); else return _mm512_setzero_si512(); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set(const long int * const sa, const int n) __VSPRNG_REQUIRED__ { if (n == SIMD_STREAMS_64) return _mm512_set_epi64(sa[7], sa[6], sa[5], sa[4], sa[3], sa[2], sa[1], sa[0]); else return _mm512_setzero_si512(); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_set(const unsigned long int * const sa, const int n) __VSPRNG_REQUIRED__ { if (n == SIMD_STREAMS_64) return _mm512_set_epi64((long int)sa[7], (long int)sa[6], (long int)sa[5], (long int)sa[4], (long int)sa[3], (long int)sa[2], (long int)sa[1], (long int)sa[0]); else return _mm512_setzero_si512(); } /*********************** * Convert intrinsics ***********************/ /*! * Convert packed 32-bit integer elements * to packed single-precision floating-point elements. */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_cvt_i32_f32(const SIMD_INT va) __VSPRNG_REQUIRED__ { return _mm512_cvtepi32_ps(va); } /*! * Convert packed 32-bit integer elements * to packed double-precision floating-point elements. */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_cvt_i32_f64(const SIMD_INT va) __VSPRNG_REQUIRED__ { return _mm512_cvtepi32lo_pd(va); } /*! * Convert packed unsigned 64-bit integer elements * to packed 32-bit floating-point elements, the high half of the register is set to 0.0. */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_cvt_u64_f32(const SIMD_INT va) __VSPRNG_REQUIRED__ { /* const __m256 fa = _mm512_cvtepu64_ps(va); return _mm512_castps256_ps512(fa); // upper half is undefined */ /* const __m256 fa = _mm512_cvtepu64_ps(va); const SIMD_FLT zero = _mm512_setzero_ps(); return _mm512_mask_mov_ps(fa, 0xFF00U, zero); */ const __m256 va_flt = _mm512_cvtepu64_ps(va); return _mm512_mask_xor_ps(va_flt, 0xFF00U, va_flt); } /*! * Convert unsigned 64-bit integers to 64-bit floating-point elements. */ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_cvt_u64_f64(const SIMD_INT va) __VSPRNG_REQUIRED__ { return _mm512_cvtepu64_pd(va); } /******************** * Load intrinsics ********************/ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_load(const int * const sa) __VSPRNG_REQUIRED__ { return _mm512_load_si512((SIMD_INT *)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_loadu(const int * const sa) { return _mm512_loadu_si512((SIMD_INT *)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_load(const unsigned int * const sa) __VSPRNG_REQUIRED__ { return _mm512_load_si512((SIMD_INT *)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_loadu(const unsigned int * const sa) { return _mm512_loadu_si512((SIMD_INT *)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_load(const long int * const sa) __VSPRNG_REQUIRED__ { return _mm512_load_si512((SIMD_INT *)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_loadu(const long int * const sa) { return _mm512_loadu_si512((SIMD_INT *)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_load(const unsigned long int * const sa) __VSPRNG_REQUIRED__ { return _mm512_load_si512((SIMD_INT *)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_INT simd_loadu(const unsigned long int * const sa) { return _mm512_loadu_si512((SIMD_INT *)sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_load(const float * const sa) __VSPRNG_REQUIRED__ { return _mm512_load_ps(sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_FLT simd_loadu(const float * const sa) { return _mm512_loadu_ps(sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_load(const double * const sa) __VSPRNG_REQUIRED__ { return _mm512_load_pd(sa); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ SIMD_DBL simd_loadu(const double * const sa) { return _mm512_loadu_pd(sa); } /******************************* * Store intrinsics *******************************/ __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_store(int * const sa, const SIMD_INT va) __VSPRNG_REQUIRED__ { _mm512_store_si512((SIMD_INT *)sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_storeu(int * const sa, const SIMD_INT va) { _mm512_storeu_si512((SIMD_INT *)sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_store(unsigned int * const sa, const SIMD_INT va) __VSPRNG_REQUIRED__ { _mm512_store_si512((SIMD_INT *)sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_storeu(unsigned int * const sa, const SIMD_INT va) { _mm512_storeu_si512((SIMD_INT *)sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_store(long int * const sa, const SIMD_INT va) __VSPRNG_REQUIRED__ { _mm512_store_si512((SIMD_INT *)sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_storeu(long int * const sa, const SIMD_INT va) { _mm512_storeu_si512((SIMD_INT *)sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_store(unsigned long int * const sa, const SIMD_INT va) __VSPRNG_REQUIRED__ { _mm512_store_si512((SIMD_INT *)sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_storeu(unsigned long int * const sa, const SIMD_INT va) { _mm512_storeu_si512((SIMD_INT *)sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_store(float * const sa, const SIMD_FLT va) __VSPRNG_REQUIRED__ { _mm512_store_ps(sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_storeu(float * const sa, const SIMD_FLT va) { _mm512_storeu_ps(sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_store(double * const sa, const SIMD_DBL va) __VSPRNG_REQUIRED__ { _mm512_store_pd(sa, va); } __SIMD_FUN_ATTR__ __SIMD_FUN_PREFIX__ void simd_storeu(double * const sa, const SIMD_DBL va) { _mm512_storeu_pd(sa, va); } #endif // __AVX512_H
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2019, <NAME> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- //! //! @file //! Transport stream scrambling using multiple algorithms. //! //---------------------------------------------------------------------------- #pragma once #include "tsArgs.h" #include "tsCerrReport.h" #include "tsTSPacket.h" #include "tsDVBCSA2.h" #include "tsDVBCISSA.h" #include "tsIDSA.h" #include "tsMPEG.h" namespace ts { //! //! Transport stream scrambling using multiple algorithms. //! @ingroup mpeg //! //! Include command line arguments processing. //! //! The scrambling type is indicated by a constant as present in a scrambling_descriptor. //! Currently, only SCRAMBLING_DVB_CSA2, SCRAMBLING_DVB_CISSA1 and SCRAMBLING_ATIS_IIF_IDSA //! are supported. //! //! With fixed control words from the command line: //! - For encryption, the next key is used each time setEncryptParity() is called //! with a new parity. //! - For decryption, the next key is used each time a new scrambling_control //! value is found in a TS header. //! class TSDUCKDLL TSScrambling { public: //! //! Default constructor. //! @param [in,out] report Where to report error and information. //! @param [in] scrambling Scrambling type. //! TSScrambling(Report& report = CERR, uint8_t scrambling = SCRAMBLING_DVB_CSA2); //! //! Copy constructor. //! @param [in] other Other instance to copy. Only the configuration parameters, typically //! from the command line, are copied. The state of @a other is not copied. //! TSScrambling(const TSScrambling& other); //! //! Define command line options in an Args. //! @param [in,out] args Command line arguments to update. //! void defineOptions(Args& args) const; //! //! Load arguments from command line. //! @param [in,out] args Command line arguments. //! @return True on success, false on error. //! Args error indicator is also set in case of incorrect arguments. //! bool loadArgs(Args& args); //! //! Check if fixed control words were loaded from the command line. //! @return True if this object uses fixed control words. //! bool hasFixedCW() const { return !_cw_list.empty(); } //! //! Get the number of fixed control words from the command line. //! @return Number of fixed control words from the command line. //! size_t fixedCWCount() const { return _cw_list.size(); } //! //! Restart the list of fixed control words from the beginning. //! Ignored if no control words were loaded from the command line. //! void rewindFixedCW(); //! //! Get the scrambling algorithm name. //! @return The scrambling algorithm name. //! UString algoName() const { return _scrambler[0]->name(); } //! //! Get the required control word size in bytes. //! @return The required control word size in bytes. //! size_t cwSize() const { return _scrambler[0]->minKeySize(); } //! //! Force the usage of a given algorithm. //! @param [in] scrambling Scrambling type. //! @param [in] overrideExplicit If true, always set the scrambling type. //! If false, ignore it if an explicit type was set on the command line. //! @return True on success, false on unsupported type. //! bool setScramblingType(uint8_t scrambling, bool overrideExplicit = true); //! //! Get the current scrambling algorithm. //! @return The scrambling type. //! uint8_t scramblingType() { return _scrambling_type; } //! //! Check if a scrambling algorithm was specified on the command line. //! @return Tue if a scrambling algorithm was specified on the command line. //! bool explicitScramblingType() const { return _explicit_type; } //! //! Force the entropy mode of DVB-CSA2. //! By default, use settings from the command line. //! @param [in] mode DVB-CSA2 entropy mode. //! void setEntropyMode(DVBCSA2::EntropyMode mode); //! //! Set the control word for encrypt and decrypt. //! @param [in] cw The control word to use. //! @param [in] parity Use the parity of this integer value (odd or even). //! @return True on success, false on error. //! bool setCW(const ByteBlock& cw, int parity); //! //! Set the parity of all subsequent encryptions. //! @param [in] parity Use the parity of this integer value (odd or even). //! @return True on success, false on error (error setting next fixed CW, if any). //! bool setEncryptParity(int parity); //! //! Encrypt a TS packet with the current parity and corresponding CW. //! @param [in,out] pkt The packet to encrypt. //! @return True on success, false on error. An already encrypted packet is an error. //! bool encrypt(TSPacket& pkt); //! //! Decrypt a TS packet with the CW corresponding to the parity in the packet. //! @param [in,out] pkt The packet to decrypt. //! @return True on success, false on error. A clear packet is not an error. //! bool decrypt(TSPacket& pkt); private: // List of control words typedef std::list<ByteBlock> CWList; Report& _report; uint8_t _scrambling_type; bool _explicit_type; CWList _cw_list; CWList::iterator _next_cw; uint8_t _encrypt_scv; // Encryption: key to use (SC_EVEN_KEY or SC_ODD_KEY). uint8_t _decrypt_scv; // Decryption: previous scrambling_control value. DVBCSA2 _dvbcsa[2]; // Index 0 = even key, 1 = odd key. DVBCISSA _dvbcissa[2]; IDSA _idsa[2]; CipherChaining* _scrambler[2]; // Set the next fixed control word as scrambling key. bool setNextFixedCW(int parity); // Inaccessible operations. TSScrambling& operator=(const TSScrambling&) = delete; }; }
<filename>baseboard/grunt/baseboard.h /* Copyright 2018 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* Grunt family-specific configuration */ #ifndef __CROS_EC_BASEBOARD_H #define __CROS_EC_BASEBOARD_H #if (defined(VARIANT_GRUNT_TCPC_0_ANX3429) \ + defined(VARIANT_GRUNT_TCPC_0_ANX3447)) != 1 #error Must choose VARIANT_GRUNT_TCPC_0_ANX3429 or VARIANT_GRUNT_TCPC_0_ANX3447 #endif /* NPCX7 config */ #define NPCX_UART_MODULE2 1 /* GPIO64/65 are used as UART pins. */ #define NPCX_TACH_SEL2 0 /* No tach. */ #define NPCX7_PWM1_SEL 0 /* GPIO C2 is not used as PWM1. */ /* Internal SPI flash on NPCX7 */ /* Flash is 1MB but reserve half for future use. */ #define CONFIG_FLASH_SIZE (512 * 1024) #define CONFIG_SPI_FLASH_REGS #define CONFIG_SPI_FLASH_W25Q80 /* Internal SPI flash type. */ /* * Enable 1 slot of secure temporary storage to support * suspend/resume with read/write memory training. */ #define CONFIG_VSTORE #define CONFIG_VSTORE_SLOT_COUNT 1 #define CONFIG_ADC #define CONFIG_BACKLIGHT_LID #define CONFIG_BACKLIGHT_LID_ACTIVE_LOW #define CONFIG_BOARD_VERSION_CUSTOM #define CONFIG_CMD_AP_RESET_LOG #define CONFIG_HIBERNATE_PSL #define CONFIG_HOSTCMD_LPC #define CONFIG_HOSTCMD_SKUID #define CONFIG_I2C #define CONFIG_I2C_BUS_MAY_BE_UNPOWERED #define CONFIG_I2C_CONTROLLER #define CONFIG_LOW_POWER_IDLE #define CONFIG_LOW_POWER_S0 #define CONFIG_LTO #define CONFIG_PWM #define CONFIG_PWM_KBLIGHT #define CONFIG_TEMP_SENSOR #define CONFIG_THERMISTOR_NCP15WB #define CONFIG_VBOOT_HASH #define CONFIG_VOLUME_BUTTONS #define CONFIG_BATTERY_CUT_OFF #define CONFIG_BATTERY_FUEL_GAUGE #define CONFIG_BATTERY_PRESENT_GPIO GPIO_EC_BATT_PRES_L #define CONFIG_BATTERY_REVIVE_DISCONNECT #define CONFIG_BATTERY_SMART #define CONFIG_BC12_DETECT_MAX14637 #define CONFIG_CHARGER #define CONFIG_CHARGE_MANAGER #define CONFIG_CHARGER_DISCHARGE_ON_AC /* * This limit impairs compatibility with BC1.2 chargers that are not actually * capable of supplying 500 mA of current. When the charger is paralleled with * the battery, raising this limit allows the power system to draw more current * from the charger during startup. This improves compatibility with system * batteries that may become excessively imbalanced after extended periods of * rest. * * See also b/111214767 */ #define CONFIG_CHARGER_INPUT_CURRENT 512 #define CONFIG_CHARGER_ISL9238 #define CONFIG_CHARGER_SENSE_RESISTOR 10 #define CONFIG_CHARGER_SENSE_RESISTOR_AC 20 #define CONFIG_CHARGE_RAMP_HW #define CONFIG_USB_CHARGER #define CONFIG_CHIPSET_STONEY #define CONFIG_CHIPSET_RESET_HOOK /* * ACOK from ISL9238 sometimes has a negative pulse after connecting * USB-C power. We want to ignore it. b/77455171 */ #undef CONFIG_EXTPOWER_DEBOUNCE_MS #define CONFIG_EXTPOWER_DEBOUNCE_MS 200 #define CONFIG_EXTPOWER_GPIO #define CONFIG_POWER_COMMON #define CONFIG_POWER_SHUTDOWN_PAUSE_IN_S5 #define CONFIG_POWER_BUTTON #define CONFIG_POWER_BUTTON_X86 /* * On power-on, H1 releases the EC from reset but then quickly asserts and * releases the reset a second time. This means the EC sees 2 resets: * (1) power-on reset, (2) reset-pin reset. This config will * allow the second reset to be treated as a power-on. */ #define CONFIG_BOARD_RESET_AFTER_POWER_ON #define CONFIG_KEYBOARD_BOARD_CONFIG #define CONFIG_KEYBOARD_COL2_INVERTED #define CONFIG_KEYBOARD_PROTOCOL_8042 #define CONFIG_USB_POWER_DELIVERY #define CONFIG_USB_PD_TCPMV1 #define CONFIG_HOSTCMD_PD_CONTROL #define CONFIG_USB_PD_ALT_MODE #define CONFIG_USB_PD_ALT_MODE_DFP #define CONFIG_USB_PD_COMM_LOCKED #define CONFIG_USB_PD_DISCHARGE_PPC #define CONFIG_USB_PD_DP_HPD_GPIO #define CONFIG_USB_PD_DUAL_ROLE #define CONFIG_USB_PD_DUAL_ROLE_AUTO_TOGGLE #define CONFIG_USB_PD_LOGGING #define CONFIG_USB_PD_PORT_MAX_COUNT 2 #define CONFIG_USB_PD_TCPC_LOW_POWER #ifdef VARIANT_GRUNT_TCPC_0_ANX3429 #define CONFIG_USB_PD_TCPM_ANX3429 #elif defined(VARIANT_GRUNT_TCPC_0_ANX3447) #define CONFIG_USB_PD_TCPM_ANX7447 #endif #define CONFIG_USB_PD_TCPM_MUX #define CONFIG_USB_PD_TCPM_PS8751 #define CONFIG_USB_PD_TCPM_TCPCI #define CONFIG_USB_PD_TRY_SRC #define CONFIG_USB_PD_VBUS_DETECT_PPC #define CONFIG_USBC_PPC_SN5S330 #define CONFIG_USBC_PPC_DEDICATED_INT #define CONFIG_USBC_SS_MUX #define CONFIG_USBC_SS_MUX_DFP_ONLY #define CONFIG_USBC_VCONN #define CONFIG_USBC_VCONN_SWAP /* USB-A config */ #define CONFIG_USB_PORT_POWER_DUMB #define USB_PORT_COUNT 2 #define PD_POWER_SUPPLY_TURN_ON_DELAY 30000 /* us */ #define PD_POWER_SUPPLY_TURN_OFF_DELAY 30000 /* us */ #define PD_VCONN_SWAP_DELAY 5000 /* us */ #define PD_OPERATING_POWER_MW 15000 #define PD_MAX_POWER_MW 45000 #define PD_MAX_CURRENT_MA 3000 #define PD_MAX_VOLTAGE_MV 20000 /* * Minimum conditions to start AP and perform swsync. Note that when the * charger is connected via USB-PD analog signaling, the boot will proceed * regardless. */ #define CONFIG_CHARGER_MIN_BAT_PCT_FOR_POWER_ON 3 /* * Require PD negotiation to be complete when we are in a low-battery condition * prior to releasing depthcharge to the kernel. */ #define CONFIG_CHARGER_LIMIT_POWER_THRESH_CHG_MW 15001 #define CONFIG_CHARGER_LIMIT_POWER_THRESH_BAT_PCT 3 /* Increase length of history buffer for port80 messages. */ #undef CONFIG_PORT80_HISTORY_LEN #define CONFIG_PORT80_HISTORY_LEN 256 #define I2C_PORT_BATTERY I2C_PORT_POWER #define I2C_PORT_CHARGER I2C_PORT_POWER #define I2C_PORT_POWER NPCX_I2C_PORT0_0 #define I2C_PORT_TCPC0 NPCX_I2C_PORT1_0 #define I2C_PORT_TCPC1 NPCX_I2C_PORT2_0 #define I2C_PORT_THERMAL_AP NPCX_I2C_PORT3_0 #define I2C_PORT_SENSOR NPCX_I2C_PORT7_0 /* Accelerometer and Gyroscope are the same device. */ #define I2C_PORT_ACCEL I2C_PORT_SENSOR /* Sensors */ #define CONFIG_MKBP_EVENT #define CONFIG_DYNAMIC_MOTION_SENSOR_COUNT /* Thermal */ #define CONFIG_TEMP_SENSOR_SB_TSI #ifndef VARIANT_GRUNT_NO_SENSORS /* Enable sensor fifo, must also define the _SIZE and _THRES */ #define CONFIG_ACCEL_FIFO /* FIFO size is a power of 2. */ #define CONFIG_ACCEL_FIFO_SIZE 256 /* Depends on how fast the AP boots and typical ODRs. */ #define CONFIG_ACCEL_FIFO_THRES (CONFIG_ACCEL_FIFO_SIZE / 3) #endif /* VARIANT_GRUNT_NO_SENSORS */ #define USB_PD_PORT_ANX74XX 0 #define USB_PD_PORT_PS8751 1 #ifndef __ASSEMBLER__ #include "gpio_signal.h" #include "math_util.h" #include "registers.h" enum adc_channel { ADC_TEMP_SENSOR_CHARGER, ADC_TEMP_SENSOR_SOC, ADC_VBUS, ADC_SKU_ID1, ADC_SKU_ID2, ADC_CH_COUNT }; enum power_signal { X86_SLP_S3_N, X86_SLP_S5_N, X86_S0_PGOOD, X86_S5_PGOOD, POWER_SIGNAL_COUNT }; enum temp_sensor_id { TEMP_SENSOR_CHARGER = 0, TEMP_SENSOR_SOC, TEMP_SENSOR_CPU, TEMP_SENSOR_COUNT }; enum sensor_id { LID_ACCEL, BASE_ACCEL, BASE_GYRO, SENSOR_COUNT, }; /* * Matrix to rotate accelerators into the standard reference frame. The default * is the identity which is correct for the reference design. Variations of * Grunt may need to change it for manufacturability. * For the lid: * +x to the right * +y up * +z out of the page * * The principle axes of the body are aligned with the lid when the lid is in * the 180 degree position (open, flat). * * Boards within the Grunt family may need to modify this definition at * board_init() time. */ extern mat33_fp_t grunt_base_standard_ref; /* Sensors without hardware FIFO are in forced mode */ #define CONFIG_ACCEL_FORCE_MODE_MASK (1 << LID_ACCEL) void board_reset_pd_mcu(void); /* Common definition for the USB PD interrupt handlers. */ void tcpc_alert_event(enum gpio_signal signal); void ppc_interrupt(enum gpio_signal signal); void anx74xx_cable_det_interrupt(enum gpio_signal signal); int board_get_version(void); int board_is_convertible(void); void board_update_sensor_config_from_sku(void); #endif /* !__ASSEMBLER__ */ #endif /* __CROS_EC_BASEBOARD_H */
<reponame>kilobyte/critnib #include <stdint.h> #include <stdio.h> #include "hmproto.h" struct hm hms[] = { // HM_ARR(critbit, 2), // HM_ARR(tcradix, 2), HM_ARR(critnib, 0), // HM_ARR(critnib_tag, 0), }; void hm_select(int i) { hm_new = hms[i].hm_new; hm_delete = hms[i].hm_delete; hm_insert = hms[i].hm_insert; hm_remove = hms[i].hm_remove; hm_get = hms[i].hm_get; hm_find_le = hms[i].hm_find_le; hm_find = hms[i].hm_find; hm_name = hms[i].hm_name; hm_immutable= hms[i].hm_immutable; }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <crypto_utils/android_pubkey.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <openssl/bn.h> // Better safe than sorry. #if (ANDROID_PUBKEY_MODULUS_SIZE % 4) != 0 #error RSA modulus size must be multiple of the word size! #endif // Size of the RSA modulus in words. #define ANDROID_PUBKEY_MODULUS_SIZE_WORDS (ANDROID_PUBKEY_MODULUS_SIZE / 4) // This file implements encoding and decoding logic for Android's custom RSA // public key binary format. Public keys are stored as a sequence of // little-endian 32 bit words. Note that Android only supports little-endian // processors, so we don't do any byte order conversions when parsing the binary // struct. typedef struct RSAPublicKey { // Modulus length. This must be ANDROID_PUBKEY_MODULUS_SIZE. uint32_t modulus_size_words; // Precomputed montgomery parameter: -1 / n[0] mod 2^32 uint32_t n0inv; // RSA modulus as a little-endian array. uint8_t modulus[ANDROID_PUBKEY_MODULUS_SIZE]; // Montgomery parameter R^2 as a little-endian array of little-endian words. uint8_t rr[ANDROID_PUBKEY_MODULUS_SIZE]; // RSA modulus: 3 or 65537 uint32_t exponent; } RSAPublicKey; // Reverses byte order in |buffer|. static void reverse_bytes(uint8_t* buffer, size_t size) { for (size_t i = 0; i < (size + 1) / 2; ++i) { uint8_t tmp = buffer[i]; buffer[i] = buffer[size - i - 1]; buffer[size - i - 1] = tmp; } } bool android_pubkey_decode(const uint8_t* key_buffer, size_t size, RSA** key) { const RSAPublicKey* key_struct = (RSAPublicKey*)key_buffer; bool ret = false; uint8_t modulus_buffer[ANDROID_PUBKEY_MODULUS_SIZE]; RSA* new_key = RSA_new(); if (!new_key) { goto cleanup; } // Check |size| is large enough and the modulus size is correct. if (size < sizeof(RSAPublicKey)) { goto cleanup; } if (key_struct->modulus_size_words != ANDROID_PUBKEY_MODULUS_SIZE_WORDS) { goto cleanup; } // Convert the modulus to big-endian byte order as expected by BN_bin2bn. memcpy(modulus_buffer, key_struct->modulus, sizeof(modulus_buffer)); reverse_bytes(modulus_buffer, sizeof(modulus_buffer)); new_key->n = BN_bin2bn(modulus_buffer, sizeof(modulus_buffer), NULL); if (!new_key->n) { goto cleanup; } // Read the exponent. new_key->e = BN_new(); if (!new_key->e || !BN_set_word(new_key->e, key_struct->exponent)) { goto cleanup; } // Note that we don't extract the montgomery parameters n0inv and rr from // the RSAPublicKey structure. They assume a word size of 32 bits, but // BoringSSL may use a word size of 64 bits internally, so we're lacking the // top 32 bits of n0inv in general. For now, we just ignore the parameters // and have BoringSSL recompute them internally. More sophisticated logic can // be added here if/when we want the additional speedup from using the // pre-computed montgomery parameters. *key = new_key; ret = true; cleanup: if (!ret && new_key) { RSA_free(new_key); } return ret; } static bool android_pubkey_encode_bignum(const BIGNUM* num, uint8_t* buffer) { if (!BN_bn2bin_padded(buffer, ANDROID_PUBKEY_MODULUS_SIZE, num)) { return false; } reverse_bytes(buffer, ANDROID_PUBKEY_MODULUS_SIZE); return true; } bool android_pubkey_encode(const RSA* key, uint8_t* key_buffer, size_t size) { RSAPublicKey* key_struct = (RSAPublicKey*)key_buffer; bool ret = false; BN_CTX* ctx = BN_CTX_new(); BIGNUM* r32 = BN_new(); BIGNUM* n0inv = BN_new(); BIGNUM* rr = BN_new(); if (sizeof(RSAPublicKey) > size || RSA_size(key) != ANDROID_PUBKEY_MODULUS_SIZE) { goto cleanup; } // Store the modulus size. key_struct->modulus_size_words = ANDROID_PUBKEY_MODULUS_SIZE_WORDS; // Compute and store n0inv = -1 / N[0] mod 2^32. if (!ctx || !r32 || !n0inv || !BN_set_bit(r32, 32) || !BN_mod(n0inv, key->n, r32, ctx) || !BN_mod_inverse(n0inv, n0inv, r32, ctx) || !BN_sub(n0inv, r32, n0inv)) { goto cleanup; } key_struct->n0inv = (uint32_t)BN_get_word(n0inv); // Store the modulus. if (!android_pubkey_encode_bignum(key->n, key_struct->modulus)) { goto cleanup; } // Compute and store rr = (2^(rsa_size)) ^ 2 mod N. if (!ctx || !rr || !BN_set_bit(rr, ANDROID_PUBKEY_MODULUS_SIZE * 8) || !BN_mod_sqr(rr, rr, key->n, ctx) || !android_pubkey_encode_bignum(rr, key_struct->rr)) { goto cleanup; } // Store the exponent. key_struct->exponent = (uint32_t)BN_get_word(key->e); ret = true; cleanup: BN_free(rr); BN_free(n0inv); BN_free(r32); BN_CTX_free(ctx); return ret; }
#ifndef __PERLCONTACTLISTENER_H__ #define __PERLCONTACTLISTENER_H__ #include <Box2D/Box2D.h> #include <helper.h> class PerlContactListener : public b2ContactListener { public: SV * beginContact; SV * endContact; SV * preSolve; SV * postSolve; PerlContactListener( ): beginContact(NULL), endContact(NULL), preSolve(NULL), postSolve(NULL) {} ~PerlContactListener(){}; void SetBeginContactSub( void * ourSub ) { /* Take a copy of the callback */ if (beginContact == NULL) { /* First time, so create a new SV */ /* fprintf(stderr,"Setting BeginContact!\n"); */ beginContact = newSVsv( (SV*)ourSub ) ; } else { /* Been here before, so overwrite */ SvSetSV(beginContact, (SV*)ourSub ) ; } } void SetEndContactSub( void * s) { /* Take a copy of the callback */ if (endContact == (SV*)NULL) /* First time, so create a new SV */ endContact = newSVsv( (SV*) s) ; else /* Been here before, so overwrite */ SvSetSV(endContact, (SV*) s) ; } void SetPreSolveSub( void * s ) { /* Take a copy of the callback */ if (preSolve == (SV*)NULL) /* First time, so create a new SV */ preSolve = newSVsv( (SV*)s) ; else /* Been here before, so overwrite */ SvSetSV(preSolve, (SV*)s) ; } void SetPostSolveSub( void * s) { if (postSolve == (SV*)NULL) /* First time, so create a new SV */ postSolve = newSVsv((SV*)s) ; else /* Been here before, so overwrite */ SvSetSV(postSolve, (SV*)s) ; } b2Contact * ourContact( b2Contact * c ); b2Manifold * ourManifold( b2Manifold * c ); b2ContactImpulse * ourContactImpulse( b2ContactImpulse * c ); virtual void BeginContact(b2Contact* contact) { if (beginContact) { /* fprintf(stderr,"BeginContact:Going to call our SV!\n"); */ //ST(0) = sv_newmortal(); //sv_setref_pv( ST(0), CLASS, (void*)RETVAL ); dSP; ENTER; SAVETMPS; PUSHMARK(SP); // make a b2Contact and put it there! const char* CLASS = "Box2D::b2Contact"; SV * contactSV = sv_newmortal(); sv_setref_pv( contactSV, CLASS, (void*)contact ); XPUSHs( contactSV ); //sv_2mortal( newSVpv( "Begin",0 ))); PUTBACK; call_sv( (SV*)beginContact, G_DISCARD ); FREETMPS; LEAVE; } else { /* fprintf(stderr,"BeginContact: Didn't call our SV!\n"); */ } } virtual void EndContact(b2Contact* contact) { if (endContact) { dSP; ENTER; SAVETMPS; PUSHMARK(SP); const char* CLASS = "Box2D::b2Contact"; SV * contactSV = sv_newmortal(); sv_setref_pv( contactSV, CLASS, (void*)contact ); XPUSHs( contactSV ); //sv_2mortal( newSVpv( "Begin",0 ))); //XPUSHs( sv_2mortal( newSVpv( "End",0)));//ourContact(contact), 0 ))); PUTBACK; call_sv( (SV*)endContact, G_DISCARD ); FREETMPS; LEAVE; } } virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { if (preSolve) { dSP; ENTER; SAVETMPS; PUSHMARK(SP); const char* CLASS1 = "Box2D::b2Contact"; SV * contactSV = sv_newmortal(); sv_setref_pv( contactSV, CLASS1, (void*)contact ); XPUSHs( contactSV ); //sv_2mortal( newSVpv( "Begin",0 ))); const char* CLASS2 = "Box2D::b2Manifold"; SV * manifoldSV = sv_newmortal(); sv_setref_pv( manifoldSV, CLASS2, (void*) oldManifold ); XPUSHs( manifoldSV ); //sv_2mortal( newSVpv( "Begin",0 ))); XPUSHs( sv_2mortal( newSVpv( "preC",0)));//ourContact(contact), 0 ))); XPUSHs( sv_2mortal( newSVpv( "preM",0)));//ourManifold(oldManifold), 0 ))); PUTBACK; call_sv( (SV*)preSolve, G_DISCARD ); FREETMPS; LEAVE; } } virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { if (postSolve) { dSP; ENTER; SAVETMPS; PUSHMARK(SP); //XPUSHs( sv_2mortal( newSVpv( "postC",0)));//ourContact(contact), 0 ))); //XPUSHs( sv_2mortal( newSVsv(ourContact(contact)))); //XPUSHs( sv_2mortal( newSVpv( "postM",0)));//ourManifold(oldManifold), 0 ))); //XPUSHs( sv_2mortal( newSVsv(oldManifold))); const char* CLASS1 = "Box2D::b2Contact"; SV * contactSV = sv_newmortal(); sv_setref_pv( contactSV, CLASS1, (void*)contact ); XPUSHs( contactSV ); //sv_2mortal( newSVpv( "Begin",0 ))); const char* CLASS2 = "Box2D::b2ContactImpulse"; SV * impulseSV = sv_newmortal(); sv_setref_pv( impulseSV, CLASS2, (void*) impulse ); XPUSHs( impulseSV ); //sv_2mortal( newSVpv( "Begin",0 ))); PUTBACK; call_sv( (SV*)postSolve, G_DISCARD ); FREETMPS; LEAVE; } else { //fprintf(stderr,"PostSolve: Didn't call our SV!\n"); } } }; // void // PerlContactListener::setEndContactSub(name) // SV * name // CODE: // THIS->setEndContactSub( name ); // // if (THIS->endContact == (SV*)NULL) // /* First time, so create a new SV */ // THIS->endContact = (void*)newSVsv(name); // else // /* Been here before, so overwrite */ // SvSetSV((SV*)(THIS->endContact), name); // // // void // PerlContactListener::setPreSolveSub(name) // SV * name // CODE: // if (THIS->preSolve == (SV*)NULL) // /* First time, so create a new SV */ // THIS->preSolve = (void*)newSVsv(name); // else // /* Been here before, so overwrite */ // SvSetSV((SV*)(THIS->preSolve), name); // // void // PerlContactListener::setPostSolveSub(name) // SV * name // CODE: // if (THIS->postSolve == (SV*)NULL) // /* First time, so create a new SV */ // THIS->postSolve = (void*)newSVsv(name); // else // /* Been here before, so overwrite */ // SvSetSV((SV*)(THIS->postSolve), name); // // #endif