max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
407
<gh_stars>100-1000 /* * Copyright (c) 2017-2019, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use 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 NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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. */ #ifndef NVDLA_PRIV_DLA_INTERFACE_H #define NVDLA_PRIV_DLA_INTERFACE_H #include <string> #include "priv/Type.h" namespace nvdla { namespace priv { // // struct dla_network_desc // class DLANetworkDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual size_t op_BDMA() const = 0; virtual size_t op_CONV() const = 0; virtual size_t op_SDP() const = 0; virtual size_t op_PDP() const = 0; virtual size_t op_CDP() const = 0; virtual size_t op_RUBIK() const = 0; virtual size_t numOpHeads() const = 0; virtual int16_t * operationDescIndex(NvU8 *base) const = 0; virtual int16_t * surfaceDescIndex(NvU8 *base) const = 0; virtual int16_t * dependencyGraphIndex(NvU8 *base) const = 0; virtual int16_t * LUTDataIndex(NvU8 *base) const = 0; virtual int16_t * ROIArrayIndex(NvU8 *base) const = 0; virtual int16_t * surfaceIndex(NvU8 *base) const = 0; virtual int16_t * statListIndex(NvU8 *base) const = 0; virtual int16_t * reserved1(NvU8* base) const = 0; virtual int16_t * opHead(NvU8 *base, size_t h) const = 0; virtual uint16_t * numROIs(NvU8 *base) const = 0; virtual uint16_t * numOperations(NvU8 *base) const = 0; virtual uint16_t * numLUTs(NvU8 *base) const = 0; virtual uint16_t * numAddresses(NvU8 *base) const = 0; virtual int16_t * inputLayer(NvU8 *base) const = 0; virtual uint8_t * dynamicROI(NvU8 *base) const = 0; virtual uint8_t * reserved0(NvU8 *base) const = 0; protected: DLANetworkDesc() { } virtual ~DLANetworkDesc() { } }; class DLANetworkDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; size_t op_BDMA() const; size_t op_CONV() const; size_t op_SDP() const; size_t op_PDP() const; size_t op_CDP() const; size_t op_RUBIK() const; size_t numOpHeads() const; int16_t * operationDescIndex() const; int16_t * surfaceDescIndex() const; int16_t * dependencyGraphIndex() const; int16_t * LUTDataIndex() const; int16_t * ROIArrayIndex() const; int16_t * surfaceIndex() const; int16_t * statListIndex() const; int16_t * reserved1() const; int16_t * opHead(size_t h) const; uint16_t * numROIs() const; uint16_t * numOperations() const; uint16_t * numLUTs() const; uint16_t * numAddresses() const; int16_t * inputLayer() const; uint8_t * dynamicROI() const; uint8_t * reserved0() const; DLANetworkDescAccessor(NvU8 *base, const DLANetworkDesc &); protected: NvU8 *_base; const DLANetworkDesc &_n; }; // // struct dla_consumer // class DLAConsumer { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual int16_t * index(NvU8 *base) const = 0; virtual uint8_t * event(NvU8 *base) const = 0; virtual uint8_t event_OpCompleted() const = 0; virtual uint8_t event_OpProgrammed() const = 0; virtual uint8_t event_OpEnabled() const = 0; virtual uint8_t event_OpCDMAWeightDone() const = 0; virtual uint8_t event_OpCDMADataDone() const = 0; virtual uint8_t * res (NvU8 *base) const = 0; protected: DLAConsumer() { } virtual ~DLAConsumer() { } }; class DLAConsumerAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; int16_t * index() const; uint8_t * event() const; uint8_t event_OpCompleted() const; uint8_t event_OpProgrammed() const; uint8_t event_OpEnabled() const; uint8_t event_OpCDMAWeightDone() const; uint8_t event_OpCDMADataDone() const; uint8_t * res() const; DLAConsumerAccessor(NvU8 *base, const DLAConsumer &); protected: NvU8 *_base; const DLAConsumer &_c; }; // // struct dla_common_op_desc // class DLACommonOpDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual int16_t * index(NvU8 *base) const = 0; virtual int8_t * roiIndex(NvU8 *base) const = 0; virtual uint8_t * opType(NvU8 *base) const = 0; virtual uint8_t opType_BDMA() const = 0; virtual uint8_t opType_CONV() const = 0; virtual uint8_t opType_SDP() const = 0; virtual uint8_t opType_PDP() const = 0; virtual uint8_t opType_CDP() const = 0; virtual uint8_t opType_RUBIK() const = 0; virtual uint8_t * dependencyCount(NvU8 *base) const = 0; virtual uint8_t * reserved_xxx(NvU8 *base) const = 0; virtual uint8_t * reserved0(NvU8 *base, size_t i) const = 0; virtual size_t numConsumers() const = 0; virtual DLAConsumerAccessor consumerAccessor(NvU8 *base, size_t c) const = 0; virtual DLAConsumerAccessor fusedParentAccessor(NvU8 *base) const = 0; protected: DLACommonOpDesc() { } virtual ~DLACommonOpDesc() { } }; class DLACommonOpDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; int16_t * index() const; int8_t * roiIndex() const; uint8_t * opType() const; uint8_t opType_BDMA() const; uint8_t opType_CONV() const; uint8_t opType_SDP() const; uint8_t opType_PDP() const; uint8_t opType_CDP() const; uint8_t opType_RUBIK() const; uint8_t * dependencyCount() const; uint8_t * reserved_xxx() const; uint8_t * reserved0(size_t i) const; size_t numConsumers() const; DLAConsumerAccessor consumerAccessor(size_t c) const; DLAConsumerAccessor fusedParentAccessor() const; DLACommonOpDescAccessor(NvU8 *base, const DLACommonOpDesc &); protected: NvU8 *_base; const DLACommonOpDesc &_c; }; // // struct dla_bdma_transfer_desc // class DLABDMATransferDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual int16_t * srcAddress(NvU8 *base) const = 0; virtual int16_t * dstAddress(NvU8 *base) const = 0; virtual uint32_t * lineSize(NvU8 *base) const = 0; virtual uint32_t * lineRepeat(NvU8 *base) const = 0; virtual uint32_t * srcLine(NvU8 *base) const = 0; virtual uint32_t * dstLine(NvU8 *base) const = 0; virtual uint32_t * surfaceRepeat(NvU8 *base) const = 0; virtual uint32_t * srcSurface(NvU8 *base) const = 0; virtual uint32_t * dstSurface(NvU8 *base) const = 0; protected: DLABDMATransferDesc() { } virtual ~DLABDMATransferDesc() { } }; class DLABDMATransferDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; int16_t * srcAddress() const; int16_t * dstAddress() const; uint32_t * lineSize() const; uint32_t * lineRepeat() const; uint32_t * srcLine() const; uint32_t * dstLine() const; uint32_t * surfaceRepeat() const; uint32_t * srcSurface() const; uint32_t * dstSurface() const; DLABDMATransferDescAccessor(NvU8 *base, const DLABDMATransferDesc &); protected: NvU8 *_base; const DLABDMATransferDesc &_t; }; // // struct dla_bdma_surface_desc // class DLABDMASurfaceDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint8_t * srcType(NvU8 *base) const = 0; virtual uint8_t * dstType(NvU8 *base) const = 0; virtual uint8_t type_MC() const = 0; virtual uint8_t type_CV() const = 0; virtual uint8_t type_HW() const = 0; virtual uint16_t * numTransfers(NvU8 *base) const = 0; virtual uint16_t maxNumTransfers() const = 0; virtual DLABDMATransferDescAccessor transferAccessor(NvU8 *base, size_t c) const = 0; protected: DLABDMASurfaceDesc() { } virtual ~DLABDMASurfaceDesc() { } }; class DLABDMASurfaceDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint8_t type_MC() const; uint8_t type_CV() const; uint8_t type_HW() const; uint16_t maxNumTransfers() const; uint8_t * srcType() const; uint8_t * dstType() const; uint16_t * numTransfers() const; DLABDMATransferDescAccessor transferAccessor(size_t c) const; DLABDMASurfaceDescAccessor(NvU8 *base, const DLABDMASurfaceDesc &); protected: NvU8 *_base; const DLABDMASurfaceDesc &_s; }; // // struct dla_bdma_op_desc // class DLABDMAOpDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint16_t * numTransfers(NvU8 *base) const = 0; virtual uint16_t * reserved0(NvU8 *base) const = 0; protected: DLABDMAOpDesc() { } virtual ~DLABDMAOpDesc() { } }; class DLABDMAOpDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint16_t * numTransfers() const; uint16_t * reserved0() const; DLABDMAOpDescAccessor(NvU8 *base, const DLABDMAOpDesc &); protected: NvU8 *_base; const DLABDMAOpDesc &_s; }; // // struct dla_bdma_stat_desc // class DLABDMAStatDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint32_t * readStall(NvU8 *base) const = 0; virtual uint32_t * writeStall(NvU8 *base) const = 0; virtual uint32_t * runtime(NvU8 *base) const = 0; protected: DLABDMAStatDesc() { } virtual ~DLABDMAStatDesc() { } }; class DLABDMAStatDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint32_t * readStall() const; uint32_t * writeStall() const; uint32_t * runtime() const; DLABDMAStatDescAccessor(NvU8 *base, const DLABDMAStatDesc &); protected: NvU8 * _base; const DLABDMAStatDesc &_s; }; // // struct dla_cvt_param // class DLACVTParam { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual int16_t * scale(NvU8 *base) const = 0; virtual uint8_t * truncate(NvU8 *base) const = 0; virtual int32_t * offset(NvU8 *base) const = 0; virtual uint8_t * enable(NvU8 *base) const = 0; virtual uint16_t * reserved_xxx(NvU8 *base) const = 0; protected: DLACVTParam() { } virtual ~DLACVTParam() { } }; class DLACVTParamAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; int16_t * scale() const; uint8_t * truncate() const; int32_t * offset() const; uint8_t * enable() const; uint16_t * reserved_xxx() const; DLACVTParamAccessor(NvU8 *base, const DLACVTParam &); protected: NvU8 *_base; const DLACVTParam &_l; }; // // struct dla_data_cube // class DLADataCube { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint8_t * type_xxx(NvU8 *base) const = 0; virtual uint8_t type_MC_xxx() const = 0; virtual uint8_t type_CV_xxx() const = 0; virtual uint8_t type_HW_xxx() const = 0; virtual uint16_t * type(NvU8 *base) const = 0; virtual uint16_t type_MC() const = 0; virtual uint16_t type_CV() const = 0; virtual uint16_t type_HW() const = 0; virtual int16_t * address(NvU8 *base) const = 0; virtual uint32_t * offset(NvU8 *base) const = 0; virtual uint32_t * size(NvU8 *base) const = 0; virtual uint16_t * width(NvU8 *base) const = 0; virtual uint16_t * height(NvU8 *base) const = 0; virtual uint16_t * channel(NvU8 *base) const = 0; virtual uint16_t * reserved0(NvU8 *base) const = 0; virtual uint32_t * lineStride(NvU8 *base) const = 0; virtual uint32_t * surfStride(NvU8 *base) const = 0; virtual uint32_t * planeStride(NvU8 *base) const = 0; protected: DLADataCube() { } virtual ~DLADataCube() { } }; class DLADataCubeAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint8_t * type_xxx() const; uint8_t type_MC_xxx() const; uint8_t type_CV_xxx() const; uint8_t type_HW_xxx() const; uint16_t * type() const; uint16_t type_MC() const; uint16_t type_CV() const; uint16_t type_HW() const; int16_t * address() const; uint32_t * offset() const; uint32_t * size() const; uint16_t * width() const; uint16_t * height() const; uint16_t * channel() const; uint16_t * reserved0() const; uint32_t * lineStride() const; uint32_t * surfStride() const; uint32_t * planeStride() const; DLADataCubeAccessor(NvU8 *base, const DLADataCube &); protected: NvU8 *_base; const DLADataCube &_l; }; // // struct dla_conv_surface_desc // class DLAConvSurfaceDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLADataCubeAccessor weightDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor meanDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor wmbDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor wgsDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor srcDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor dstDataAccessor(NvU8 *base) const = 0; virtual uint64_t * offsetU_xxx(NvU8 *base) const = 0; virtual int64_t * offsetU(NvU8 *base) const = 0; virtual uint32_t * offsetV(NvU8 *base) const = 0; virtual uint32_t * inLineUVStride(NvU8 *base) const = 0; protected: DLAConvSurfaceDesc() { } virtual ~DLAConvSurfaceDesc() { } }; class DLAConvSurfaceDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLADataCubeAccessor weightDataAccessor() const; DLADataCubeAccessor meanDataAccessor() const; DLADataCubeAccessor wmbDataAccessor() const; DLADataCubeAccessor wgsDataAccessor() const; DLADataCubeAccessor srcDataAccessor() const; DLADataCubeAccessor dstDataAccessor() const; uint64_t * offsetU_xxx() const; int64_t * offsetU() const; uint32_t * offsetV() const; uint32_t * inLineUVStride() const; DLAConvSurfaceDescAccessor(NvU8 *base, const DLAConvSurfaceDesc &); protected: NvU8 *_base; const DLAConvSurfaceDesc &_l; }; // // struct dla_conv_op_desc // class DLAConvOpDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint8_t * inPrecision(NvU8 *base) const = 0; virtual uint8_t inPrecision_Int8() const = 0; virtual uint8_t inPrecision_Int16() const = 0; virtual uint8_t inPrecision_FP16() const = 0; virtual uint8_t * outPrecision(NvU8 *base) const = 0; virtual uint8_t outPrecision_Int8() const = 0; virtual uint8_t outPrecision_Int16() const = 0; virtual uint8_t outPrecision_FP16() const = 0; virtual DLACVTParamAccessor inCVTAccessor(NvU8 *base) const = 0; virtual DLACVTParamAccessor outCVTAccessor(NvU8 *base) const = 0; virtual int16_t * padVal(NvU8 *base) const = 0; virtual uint8_t * convMode(NvU8 *base) const = 0; virtual uint8_t convMode_Direct() const = 0; virtual uint8_t convMode_Winograd() const = 0; virtual uint8_t * dataReuse(NvU8 *base) const = 0; virtual uint8_t * weightReuse(NvU8 *base) const = 0; virtual uint8_t * skipDataRls(NvU8 *base) const = 0; virtual uint8_t * skipWeightRls(NvU8 *base) const = 0; virtual uint8_t * reserved0(NvU8 *base) const = 0; virtual uint16_t * entryPerSlice(NvU8 *base) const = 0; virtual uint16_t * fetchGrain(NvU8 *base) const = 0; virtual uint8_t * dataFormat(NvU8 *base) const = 0; virtual uint8_t dataFormat_T_R8() const = 0; virtual uint8_t dataFormat_T_R10() const = 0; virtual uint8_t dataFormat_T_R12() const = 0; virtual uint8_t dataFormat_T_R16() const = 0; virtual uint8_t dataFormat_T_R16_I() const = 0; virtual uint8_t dataFormat_T_R16_F() const = 0; virtual uint8_t dataFormat_T_A16B16G16R16() const = 0; virtual uint8_t dataFormat_T_X16B16G16R16() const = 0; virtual uint8_t dataFormat_T_A16B16G16R16_F() const = 0; virtual uint8_t dataFormat_T_A16Y16U16V16() const = 0; virtual uint8_t dataFormat_T_V16U16Y16A16() const = 0; virtual uint8_t dataFormat_T_A16Y16U16V16_F() const = 0; virtual uint8_t dataFormat_T_A8B8G8R8() const = 0; virtual uint8_t dataFormat_T_A8R8G8B8() const = 0; virtual uint8_t dataFormat_T_B8G8R8A8() const = 0; virtual uint8_t dataFormat_T_R8G8B8A8() const = 0; virtual uint8_t dataFormat_T_X8B8G8R8() const = 0; virtual uint8_t dataFormat_T_X8R8G8B8() const = 0; virtual uint8_t dataFormat_T_B8G8R8X8() const = 0; virtual uint8_t dataFormat_T_R8G8B8X8() const = 0; virtual uint8_t dataFormat_T_A2B10G10R10() const = 0; virtual uint8_t dataFormat_T_A2R10G10B10() const = 0; virtual uint8_t dataFormat_T_B10G10R10A2() const = 0; virtual uint8_t dataFormat_T_R10G10B10A2() const = 0; virtual uint8_t dataFormat_T_Y8___U8V8_N444() const = 0; virtual uint8_t dataFormat_T_Y8___V8U8_N444() const = 0; virtual uint8_t dataFormat_T_Y10___U10V10_N444() const = 0; virtual uint8_t dataFormat_T_Y10___V10U10_N444() const = 0; virtual uint8_t dataFormat_T_Y12___U12V12_N444() const = 0; virtual uint8_t dataFormat_T_Y12___V12U12_N444() const = 0; virtual uint8_t dataFormat_T_Y16___U16V16_N444() const = 0; virtual uint8_t dataFormat_T_Y16___V16U16_N444() const = 0; virtual uint8_t dataFormat_T_Y16___U8V8_N444() const = 0; virtual uint8_t dataFormat_T_Y16___V8U8_N444() const = 0; virtual uint8_t dataFormat_T_Y8___U8___V8_N444() const = 0; virtual uint8_t dataFormat_T_Y10___U10___V10_N444() const = 0; virtual uint8_t dataFormat_T_Y12___U12___V12_N444() const = 0; virtual uint8_t dataFormat_T_Y16___U16___V16_N444() const = 0; virtual uint8_t dataFormat_T_Y16___U8___V8_N444() const = 0; virtual uint8_t dataFormat_T_A2Y10U10V10() const = 0; virtual uint8_t dataFormat_T_V10U10Y10A2() const = 0; virtual uint8_t dataFormat_T_A8Y8U8V8() const = 0; virtual uint8_t dataFormat_T_V8U8Y8A8() const = 0; virtual uint8_t dataFormat_FEATURE() const = 0; virtual uint8_t * pixelMapping(NvU8 *base) const = 0; virtual uint8_t pixelMapping_PitchLinear() const = 0; virtual uint8_t * batch(NvU8 *base) const = 0; virtual uint8_t * weightFormat(NvU8 *base) const = 0; virtual uint8_t weightFormat_Uncompressed() const = 0; virtual uint8_t weightFormat_Compressed() const = 0; virtual uint8_t * dataBank(NvU8 *base) const = 0; virtual uint8_t * weightBank(NvU8 *base) const = 0; virtual uint32_t * batchStride(NvU8 *base) const = 0; virtual uint16_t * release(NvU8 *base) const = 0; virtual uint8_t * postExtension(NvU8 *base) const = 0; virtual uint8_t * reserved1_xxx(NvU8 *base) const = 0; virtual uint8_t * pixelOverride(NvU8 *base) const = 0; virtual uint8_t pixelOverride_UINT() const = 0; virtual uint8_t pixelOverride_INT() const = 0; virtual uint8_t * meanFormat(NvU8 *base) const = 0; virtual uint8_t meanFormat_None() const = 0; virtual uint8_t meanFormat_Global() const = 0; virtual uint8_t meanFormat_PerPixel() const = 0; virtual uint8_t meanFormat_Disable() const = 0; virtual uint8_t meanFormat_Enable() const = 0; virtual int16_t * meanRY(NvU8 *base) const = 0; virtual int16_t * meanGU(NvU8 *base) const = 0; virtual int16_t * meanBV(NvU8 *base) const = 0; virtual int16_t * meanAX(NvU8 *base) const = 0; virtual uint8_t * convStrideX(NvU8 *base) const = 0; virtual uint8_t * convStrideY(NvU8 *base) const = 0; virtual uint8_t * padXLeft(NvU8 *base) const = 0; virtual uint8_t * padXRight(NvU8 *base) const = 0; virtual uint8_t * padYTop(NvU8 *base) const = 0; virtual uint8_t * padYBottom(NvU8 *base) const = 0; virtual uint8_t * dilationX(NvU8 *base) const = 0; virtual uint8_t * dilationY(NvU8 *base) const = 0; virtual uint8_t * reserved2(NvU8 *base, size_t i) const = 0; virtual uint8_t * praTruncate(NvU8 *base) const = 0; virtual uint16_t * inputWidthCSC(NvU8 *base) const = 0; virtual uint16_t * inputHeightCSC(NvU8 *base) const = 0; virtual uint16_t * inputChannelCSC(NvU8 *base) const = 0; virtual uint16_t * kernelWidthCSC(NvU8 *base) const = 0; virtual uint16_t * kernelHeightCSC(NvU8 *base) const = 0; virtual uint16_t * kernelChannelCSC(NvU8 *base) const = 0; virtual uint16_t * inputWidthCMAC(NvU8 *base) const = 0; virtual uint16_t * inputHeightCMAC(NvU8 *base) const = 0; virtual uint32_t * bytesPerKernel(NvU8 *base) const = 0; protected: DLAConvOpDesc() { } virtual ~DLAConvOpDesc() { } }; class DLAConvOpDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint8_t * inPrecision() const; uint8_t inPrecision_Int8() const; uint8_t inPrecision_Int16() const; uint8_t inPrecision_FP16() const; uint8_t * outPrecision() const; uint8_t outPrecision_Int8() const; uint8_t outPrecision_Int16() const; uint8_t outPrecision_FP16() const; DLACVTParamAccessor inCVTAccessor() const; DLACVTParamAccessor outCVTAccessor() const; int16_t * padVal() const; uint8_t * convMode() const; uint8_t convMode_Direct() const; uint8_t convMode_Winograd() const; uint8_t * dataReuse() const; uint8_t * weightReuse() const; uint8_t * skipDataRls() const; uint8_t * skipWeightRls() const; uint8_t * reserved0() const; uint16_t * entryPerSlice() const; uint16_t * fetchGrain() const; uint8_t * dataFormat() const; uint8_t dataFormat_T_R8() const; uint8_t dataFormat_T_R10() const; uint8_t dataFormat_T_R12() const; uint8_t dataFormat_T_R16() const; uint8_t dataFormat_T_R16_I() const; uint8_t dataFormat_T_R16_F() const; uint8_t dataFormat_T_A16B16G16R16() const; uint8_t dataFormat_T_X16B16G16R16() const; uint8_t dataFormat_T_A16B16G16R16_F() const; uint8_t dataFormat_T_A16Y16U16V16() const; uint8_t dataFormat_T_V16U16Y16A16() const; uint8_t dataFormat_T_A16Y16U16V16_F() const; uint8_t dataFormat_T_A8B8G8R8() const; uint8_t dataFormat_T_A8R8G8B8() const; uint8_t dataFormat_T_B8G8R8A8() const; uint8_t dataFormat_T_R8G8B8A8() const; uint8_t dataFormat_T_X8B8G8R8() const; uint8_t dataFormat_T_X8R8G8B8() const; uint8_t dataFormat_T_B8G8R8X8() const; uint8_t dataFormat_T_R8G8B8X8() const; uint8_t dataFormat_T_A2B10G10R10() const; uint8_t dataFormat_T_A2R10G10B10() const; uint8_t dataFormat_T_B10G10R10A2() const; uint8_t dataFormat_T_R10G10B10A2() const; uint8_t dataFormat_T_Y8___U8V8_N444() const; uint8_t dataFormat_T_Y8___V8U8_N444() const; uint8_t dataFormat_T_Y10___U10V10_N444() const; uint8_t dataFormat_T_Y10___V10U10_N444() const; uint8_t dataFormat_T_Y12___U12V12_N444() const; uint8_t dataFormat_T_Y12___V12U12_N444() const; uint8_t dataFormat_T_Y16___U16V16_N444() const; uint8_t dataFormat_T_Y16___V16U16_N444() const; uint8_t dataFormat_T_Y16___U8V8_N444() const; uint8_t dataFormat_T_Y16___V8U8_N444() const; uint8_t dataFormat_T_Y8___U8___V8_N444() const; uint8_t dataFormat_T_Y10___U10___V10_N444() const; uint8_t dataFormat_T_Y12___U12___V12_N444() const; uint8_t dataFormat_T_Y16___U16___V16_N444() const; uint8_t dataFormat_T_Y16___U8___V8_N444() const; uint8_t dataFormat_T_A2Y10U10V10() const; uint8_t dataFormat_T_V10U10Y10A2() const; uint8_t dataFormat_T_A8Y8U8V8() const; uint8_t dataFormat_T_V8U8Y8A8() const; uint8_t dataFormat_FEATURE() const; uint8_t * pixelMapping() const; uint8_t pixelMapping_PitchLinear() const; uint8_t * batch() const; uint8_t * weightFormat() const; uint8_t weightFormat_Uncompressed() const; uint8_t weightFormat_Compressed() const; uint8_t * dataBank() const; uint8_t * weightBank() const; uint32_t * batchStride() const; uint16_t * release() const; uint8_t * postExtension() const; uint8_t * reserved1_xxx() const; uint8_t * pixelOverride() const; uint8_t pixelOverride_UINT() const; uint8_t pixelOverride_INT() const; uint8_t * meanFormat() const; uint8_t meanFormat_None() const; uint8_t meanFormat_Global() const; uint8_t meanFormat_PerPixel() const; uint8_t meanFormat_Disable() const; uint8_t meanFormat_Enable() const; int16_t * meanRY() const; int16_t * meanGU() const; int16_t * meanBV() const; int16_t * meanAX() const; uint8_t * convStrideX() const; uint8_t * convStrideY() const; uint8_t * padXLeft() const; uint8_t * padXRight() const; uint8_t * padYTop() const; uint8_t * padYBottom() const; uint8_t * dilationX() const; uint8_t * dilationY() const; uint8_t * reserved2(size_t) const; uint8_t * praTruncate() const; uint16_t * inputWidthCSC() const; uint16_t * inputHeightCSC() const; uint16_t * inputChannelCSC() const; uint16_t * kernelWidthCSC() const; uint16_t * kernelHeightCSC() const; uint16_t * kernelChannelCSC() const; uint16_t * inputWidthCMAC() const; uint16_t * inputHeightCMAC() const; uint32_t * bytesPerKernel() const; DLAConvOpDescAccessor(NvU8 *base, const DLAConvOpDesc &); protected: NvU8 *_base; const DLAConvOpDesc &_l; }; // // struct dla_conv_stat_desc // class DLAConvStatDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint32_t * dataReadStall(NvU8 *base) const = 0; virtual uint32_t * weightReadStall(NvU8 *base) const = 0; virtual uint32_t * dataReadLatency(NvU8 *base) const = 0; virtual uint32_t * weightReadLatency(NvU8 *base) const = 0; virtual uint32_t * saturationCount(NvU8 *base) const = 0; virtual uint32_t * nanDataNum(NvU8 *base) const = 0; virtual uint32_t * nanWeightNum(NvU8 *base) const = 0; virtual uint32_t * infDataNum(NvU8 *base) const = 0; virtual uint32_t * infWeightNum(NvU8 *base) const = 0; virtual uint32_t * runtime(NvU8 *base) const = 0; protected: DLAConvStatDesc() { } virtual ~DLAConvStatDesc() { } }; class DLAConvStatDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint32_t * dataReadStall() const; uint32_t * weightReadStall() const; uint32_t * dataReadLatency() const; uint32_t * weightReadLatency() const; uint32_t * saturationCount() const; uint32_t * nanDataNum() const; uint32_t * nanWeightNum() const; uint32_t * infDataNum() const; uint32_t * infWeightNum() const; uint32_t * runtime() const; DLAConvStatDescAccessor(NvU8 *base, const DLAConvStatDesc &); protected: NvU8 *_base; const DLAConvStatDesc &_l; }; // // union dla_lut_offset // class DLALUTOffset { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint8_t * expOffset_xxx(NvU8 *base) const = 0; virtual int8_t * expOffset(NvU8 *base) const = 0; virtual uint8_t * fracBits_xxx(NvU8 *base) const = 0; virtual int8_t * fracBits(NvU8 *base) const = 0; virtual uint16_t * reserved0(NvU8 *base) const = 0; protected: DLALUTOffset() { } virtual ~DLALUTOffset() { } }; class DLALUTOffsetAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint8_t * expOffset_xxx() const; int8_t * expOffset() const; uint8_t * fracBits_xxx() const; int8_t * fracBits() const; uint16_t * reserved0() const; DLALUTOffsetAccessor(NvU8 *base, const DLALUTOffset &); protected: NvU8 *_base; const DLALUTOffset &_l; }; // // struct dla_float_data // class DLAFloatData { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual int16_t * scale(NvU8 *base) const = 0; virtual uint8_t * shifter_xxx(NvU8 *base) const = 0; virtual int8_t * shifter(NvU8 *base) const = 0; virtual uint8_t * reserved0(NvU8 *base) const = 0; protected: DLAFloatData() { } virtual ~DLAFloatData() { } }; class DLAFloatDataAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; int16_t * scale() const; uint8_t * shifter_xxx() const; int8_t * shifter() const; uint8_t * reserved0() const; DLAFloatDataAccessor(NvU8 *base, const DLAFloatData &); protected: NvU8 *_base; const DLAFloatData &_l; }; // // struct dla_slope // class DLASlope { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLAFloatDataAccessor dataIAccessor(NvU8 *base) const = 0; virtual uint16_t * dataF(NvU8 *base) const = 0; protected: DLASlope() { } virtual ~DLASlope() { } }; class DLASlopeAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLAFloatDataAccessor dataIAccessor() const; uint16_t * dataF() const; DLASlopeAccessor(NvU8 *base, const DLASlope &); protected: NvU8 *_base; const DLASlope &_l; }; // // struct dla_lut_param // class DLALUTParam { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual int16_t * linearExpTable(NvU8 *base, size_t i) const = 0; virtual size_t numLinearExpTable() const = 0; virtual int16_t * linearOnlyTable(NvU8 *base, size_t i) const = 0; virtual size_t numLinearOnlyTable() const = 0; virtual uint8_t * method(NvU8 *base) const = 0; virtual uint8_t method_Exponential() const = 0; virtual uint8_t method_Linear() const = 0; virtual DLALUTOffsetAccessor linearExpOffsetAccessor(NvU8 *base) const = 0; virtual DLALUTOffsetAccessor linearOnlyOffsetAccessor(NvU8 *base) const = 0; virtual uint64_t * linearExpStart(NvU8 *base) const = 0; virtual uint64_t * linearExpEnd(NvU8 *base) const = 0; virtual uint64_t * linearOnlyStart(NvU8 *base) const = 0; virtual uint64_t * linearOnlyEnd(NvU8 *base) const = 0; virtual DLASlopeAccessor linearExpUnderflowSlopeAccessor(NvU8 *base) const = 0; virtual DLASlopeAccessor linearExpOverflowSlopeAccessor(NvU8 *base) const = 0; virtual DLASlopeAccessor linearOnlyUnderflowSlopeAccessor(NvU8 *base) const = 0; virtual DLASlopeAccessor linearOnlyOverflowSlopeAccessor(NvU8 *base) const = 0; virtual uint8_t * hybridPriority(NvU8 *base) const = 0; virtual uint8_t * underflowPriority(NvU8 *base) const = 0; virtual uint8_t * overflowPriority(NvU8 *base) const = 0; virtual uint8_t priority_LinearExp() const = 0; virtual uint8_t priority_LinearOnly() const = 0; virtual int8_t * inputScaleLog2(NvU8 *base) const = 0; protected: DLALUTParam() { } virtual ~DLALUTParam() { } }; class DLALUTParamAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; int16_t * linearExpTable(size_t i) const; size_t numLinearExpTable() const; int16_t * linearOnlyTable(size_t i) const; size_t numLinearOnlyTable() const; uint8_t * method() const; uint8_t method_Exponential() const; uint8_t method_Linear() const; DLALUTOffsetAccessor linearExpOffsetAccessor() const; DLALUTOffsetAccessor linearOnlyOffsetAccessor() const; uint64_t * linearExpStart() const; uint64_t * linearExpEnd() const; uint64_t * linearOnlyStart() const; uint64_t * linearOnlyEnd() const; DLASlopeAccessor linearExpUnderflowSlopeAccessor() const; DLASlopeAccessor linearExpOverflowSlopeAccessor() const; DLASlopeAccessor linearOnlyUnderflowSlopeAccessor() const; DLASlopeAccessor linearOnlyOverflowSlopeAccessor() const; uint8_t * hybridPriority() const; uint8_t * underflowPriority() const; uint8_t * overflowPriority() const; uint8_t priority_LinearExp() const; uint8_t priority_LinearOnly() const; int8_t * inputScaleLog2() const; DLALUTParamAccessor(NvU8 *base, const DLALUTParam &); protected: NvU8 *_base; const DLALUTParam &_l; }; // // struct dla_sdp_surface_desc // class DLASDPSurfaceDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLADataCubeAccessor srcDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor x1DataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor x2DataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor yDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor dstDataAccessor(NvU8 *base) const = 0; protected: DLASDPSurfaceDesc() { } virtual ~DLASDPSurfaceDesc() { } }; class DLASDPSurfaceDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLADataCubeAccessor srcDataAccessor() const; DLADataCubeAccessor x1DataAccessor() const; DLADataCubeAccessor x2DataAccessor() const; DLADataCubeAccessor yDataAccessor() const; DLADataCubeAccessor dstDataAccessor() const; DLASDPSurfaceDescAccessor(NvU8 *base, const DLASDPSurfaceDesc &); protected: NvU8 *_base; const DLASDPSurfaceDesc &_l; }; class DLASDPCVT { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLACVTParamAccessor aluCVTAccessor(NvU8 *base) const = 0; virtual DLACVTParamAccessor mulCVTAccessor(NvU8 *base) const = 0; protected: DLASDPCVT() { } virtual ~DLASDPCVT() { } }; class DLASDPCVTAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLACVTParamAccessor aluCVTAccessor() const; DLACVTParamAccessor mulCVTAccessor() const; DLASDPCVTAccessor(NvU8 *base, const DLASDPCVT &); protected: NvU8 * _base; const DLASDPCVT &_l; }; // // dla_sdp_op // class DLASDPOp { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint8_t * enable(NvU8 *base) const = 0; virtual uint8_t * ALUType(NvU8 *base) const = 0; virtual uint8_t ALUType_Max() const = 0; virtual uint8_t ALUType_Min() const = 0; virtual uint8_t ALUType_Sum() const = 0; virtual uint8_t ALUType_Eql() const = 0; virtual uint8_t * type(NvU8 *base) const = 0; virtual uint8_t type_None() const = 0; virtual uint8_t type_Mul() const = 0; virtual uint8_t type_Add() const = 0; virtual uint8_t type_Both() const = 0; virtual uint8_t * mode(NvU8 *base) const = 0; virtual uint8_t mode_PerLayer() const = 0; virtual uint8_t mode_PerKernel() const = 0; virtual uint8_t mode_PerPoint() const = 0; virtual uint8_t * act(NvU8 *base) const = 0; virtual uint8_t act_None() const = 0; virtual uint8_t act_RelU() const = 0; virtual uint8_t act_LUT() const = 0; virtual uint8_t * shiftValue(NvU8 *base) const = 0; virtual int16_t * ALUOperand_xxx(NvU8 *base) const = 0; virtual int16_t * MulOperand_xxx(NvU8 *base) const = 0; virtual int32_t * ALUOperand(NvU8 *base) const = 0; virtual int32_t * MulOperand(NvU8 *base) const = 0; virtual uint8_t * truncate(NvU8 *base) const = 0; virtual uint8_t * precision(NvU8 *base) const = 0; virtual DLASDPCVTAccessor cvt(NvU8 *base) const = 0; protected: DLASDPOp() { } virtual ~DLASDPOp() { } }; class DLASDPOpAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint8_t * enable() const; uint8_t * ALUType() const; uint8_t ALUType_Max() const; uint8_t ALUType_Min() const; uint8_t ALUType_Sum() const; uint8_t ALUType_Eql() const; uint8_t * type() const; uint8_t type_None() const; uint8_t type_Mul() const; uint8_t type_Add() const; uint8_t type_Both() const; uint8_t * mode() const; uint8_t mode_PerLayer() const; uint8_t mode_PerKernel() const; uint8_t mode_PerPoint() const; uint8_t * act() const; uint8_t act_None() const; uint8_t act_RelU() const; uint8_t act_LUT() const; uint8_t * shiftValue() const; int16_t * ALUOperand_xxx() const; int16_t * MulOperand_xxx() const; int32_t * ALUOperand() const; int32_t * MulOperand() const; uint8_t * truncate() const; uint8_t * precision() const; DLASDPCVTAccessor cvt() const; DLASDPOpAccessor(NvU8 *base, const DLASDPOp &); protected: NvU8 *_base; const DLASDPOp &_l; }; // // struct dla_sdp_op_desc // class DLASDPOpDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint8_t * srcPrecision(NvU8 *base) const = 0; virtual uint8_t srcPrecision_Int8() const = 0; virtual uint8_t srcPrecision_Int16() const = 0; virtual uint8_t srcPrecision_FP16() const = 0; virtual uint8_t * dstPrecision(NvU8 *base) const = 0; virtual uint8_t dstPrecision_Int8() const = 0; virtual uint8_t dstPrecision_Int16() const = 0; virtual uint8_t dstPrecision_FP16() const = 0; virtual int16_t * LUTIndex(NvU8 *base) const = 0; virtual DLACVTParamAccessor outCVTAccessor(NvU8 *base) const = 0; virtual uint8_t * convMode(NvU8 *base) const = 0; virtual uint8_t convMode_Direct() const = 0; virtual uint8_t convMode_Winograd() const = 0; virtual uint8_t * batchNum(NvU8 *base) const = 0; virtual uint16_t * reserved0(NvU8 *base) const = 0; virtual uint32_t * batchStride(NvU8 *base) const = 0; virtual DLASDPOpAccessor x1OpAccessor(NvU8 *base) const = 0; virtual DLASDPOpAccessor x2OpAccessor(NvU8 *base) const = 0; virtual DLASDPOpAccessor yOpAccessor(NvU8 *base) const = 0; protected: DLASDPOpDesc() { } virtual ~DLASDPOpDesc() { } }; class DLASDPOpDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint8_t * srcPrecision() const; uint8_t srcPrecision_Int8() const; uint8_t srcPrecision_Int16() const; uint8_t srcPrecision_FP16() const; uint8_t * dstPrecision() const; uint8_t dstPrecision_Int8() const; uint8_t dstPrecision_Int16() const; uint8_t dstPrecision_FP16() const; int16_t * LUTIndex() const; DLACVTParamAccessor outCVTAccessor() const; uint8_t * convMode() const; uint8_t convMode_Direct() const; uint8_t convMode_Winograd() const; uint8_t * batchNum() const; uint16_t * reserved0() const; uint32_t * batchStride() const; DLASDPOpAccessor x1OpAccessor() const; DLASDPOpAccessor x2OpAccessor() const; DLASDPOpAccessor yOpAccessor() const; DLASDPOpDescAccessor(NvU8 *base, const DLASDPOpDesc &); protected: NvU8 *_base; const DLASDPOpDesc &_l; }; // // struct dla_sdp_stat_desc // class DLASDPStatDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint32_t * nanInputNum(NvU8* base) const = 0; virtual uint32_t * infInputNum(NvU8* base) const = 0; virtual uint32_t * nanOutputNum(NvU8* base) const = 0; virtual uint32_t * wdmaWriteStall(NvU8* base) const = 0; virtual uint32_t * lutUnderflow(NvU8* base) const = 0; virtual uint32_t * lutOverflow(NvU8* base) const = 0; virtual uint32_t * lutHybrid(NvU8* base) const = 0; virtual uint32_t * lutLEHit(NvU8* base) const = 0; virtual uint32_t * lutLOHit(NvU8* base) const = 0; virtual uint32_t * saturationCount(NvU8* base) const = 0; virtual uint32_t * runtime(NvU8* base) const = 0; protected: DLASDPStatDesc() { } virtual ~DLASDPStatDesc() { } }; class DLASDPStatDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint32_t * nanInputNum() const; uint32_t * infInputNum() const; uint32_t * nanOutputNum() const; uint32_t * wdmaWriteStall() const; uint32_t * lutUnderflow() const; uint32_t * lutOverflow() const; uint32_t * lutHybrid() const; uint32_t * lutLEHit() const; uint32_t * lutLOHit() const; uint32_t * saturationCount() const; uint32_t * runtime() const; DLASDPStatDescAccessor(NvU8 *base, const DLASDPStatDesc &); protected: NvU8 *_base; const DLASDPStatDesc &_l; }; // // struct dla_pdp_surface_desc // class DLAPDPSurfaceDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLADataCubeAccessor srcDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor dstDataAccessor(NvU8 *base) const = 0; protected: DLAPDPSurfaceDesc() { } virtual ~DLAPDPSurfaceDesc() { } }; class DLAPDPSurfaceDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLADataCubeAccessor srcDataAccessor() const; DLADataCubeAccessor dstDataAccessor() const; DLAPDPSurfaceDescAccessor(NvU8 *base, const DLAPDPSurfaceDesc &); protected: NvU8 *_base; const DLAPDPSurfaceDesc &_l; }; // // dla_pdp_op_desc // class DLAPDPOpDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint8_t *precision(NvU8 *base) const = 0; virtual uint8_t precision_Int8() const = 0; virtual uint8_t precision_Int16() const = 0; virtual uint8_t precision_FP16() const = 0; virtual uint8_t *reserved0_xxx(NvU8 *base, size_t i) const = 0; virtual uint8_t *reserved0(NvU8 *base) const = 0; virtual int16_t *paddingValue_xxx(NvU8 *base, size_t i) const = 0; virtual int32_t *paddingValue(NvU8 *base, size_t i) const = 0; virtual uint8_t *splitNum(NvU8 *base) const = 0; virtual uint8_t *reserved1_xxx(NvU8 *base, size_t i) const = 0; virtual uint16_t *partialInWidthFirst(NvU8 *base) const = 0; virtual uint16_t *partialInWidthMid(NvU8 *base) const = 0; virtual uint16_t *partialInWidthLast(NvU8 *base) const = 0; virtual uint16_t *partialWidthFirst(NvU8 *base) const = 0; virtual uint16_t *partialWidthMid(NvU8 *base) const = 0; virtual uint16_t *partialWidthLast(NvU8 *base) const = 0; virtual uint8_t *poolMode(NvU8 *base) const = 0; virtual uint8_t poolMode_AVG() const = 0; virtual uint8_t poolMode_MAX() const = 0; virtual uint8_t poolMode_MIN() const = 0; virtual uint8_t *poolWidth(NvU8 *base) const = 0; virtual uint8_t *poolHeight(NvU8 *base) const = 0; virtual uint8_t *reserved2_xxx(NvU8 *base) const = 0; virtual uint8_t *strideX(NvU8 *base) const = 0; virtual uint8_t *strideY(NvU8 *base) const = 0; virtual uint16_t *strideX_xxx(NvU8 *base) const = 0; virtual uint16_t *strideY_xxx(NvU8 *base) const = 0; virtual uint16_t *reserved3_xxx(NvU8 *base) const = 0; virtual uint8_t *padLeft(NvU8 *base) const = 0; virtual uint8_t *padRight(NvU8 *base) const = 0; virtual uint8_t *padTop(NvU8 *base) const = 0; virtual uint8_t *padBottom(NvU8 *base) const = 0; protected: DLAPDPOpDesc() { } virtual ~DLAPDPOpDesc() { } }; class DLAPDPOpDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint8_t *precision() const; uint8_t precision_Int8() const; uint8_t precision_Int16() const; uint8_t precision_FP16() const; uint8_t *reserved0_xxx(size_t i) const; uint8_t *reserved0() const; int16_t *paddingValue_xxx(size_t i) const; int32_t *paddingValue(size_t i) const; uint8_t *splitNum() const; uint8_t *reserved1_xxx(size_t i) const; uint16_t *partialInWidthFirst() const; uint16_t *partialInWidthMid() const; uint16_t *partialInWidthLast() const; uint16_t *partialWidthFirst() const; uint16_t *partialWidthMid() const; uint16_t *partialWidthLast() const; uint8_t *poolMode() const; uint8_t poolMode_AVG() const; uint8_t poolMode_MAX() const; uint8_t poolMode_MIN() const; uint8_t *poolWidth() const; uint8_t *poolHeight() const; uint8_t *reserved2_xxx() const; uint8_t *strideX() const; uint8_t *strideY() const; uint16_t *strideX_xxx() const; uint16_t *strideY_xxx() const; uint16_t *reserved3_xxx() const; uint8_t *padLeft() const; uint8_t *padRight() const; uint8_t *padTop() const; uint8_t *padBottom() const; DLAPDPOpDescAccessor(NvU8 *base, const DLAPDPOpDesc &); protected: NvU8 *_base; const DLAPDPOpDesc &_l; }; // // struct dla_pdp_stat_desc // class DLAPDPStatDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint32_t * infInputNum(NvU8* base) const = 0; virtual uint32_t * nanInputNum(NvU8* base) const = 0; virtual uint32_t * nanOutputNum(NvU8* base) const = 0; virtual uint32_t * writeStall(NvU8* base) const = 0; virtual uint32_t * runtime(NvU8* base) const = 0; protected: DLAPDPStatDesc() { } virtual ~DLAPDPStatDesc() { } }; class DLAPDPStatDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint32_t * infInputNum() const; uint32_t * nanInputNum() const; uint32_t * nanOutputNum() const; uint32_t * writeStall() const; uint32_t * runtime() const; DLAPDPStatDescAccessor(NvU8 *base, const DLAPDPStatDesc &); protected: NvU8 *_base; const DLAPDPStatDesc &_l; }; // // dla_cdp_surface_desc // class DLACDPSurfaceDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLADataCubeAccessor srcDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor dstDataAccessor(NvU8 *base) const = 0; protected: DLACDPSurfaceDesc() { } virtual ~DLACDPSurfaceDesc() { } }; class DLACDPSurfaceDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLADataCubeAccessor srcDataAccessor() const; DLADataCubeAccessor dstDataAccessor() const; DLACDPSurfaceDescAccessor(NvU8 *base, const DLACDPSurfaceDesc &); protected: NvU8 *_base; const DLACDPSurfaceDesc &_l; }; // // dla_cdp_op_desc // class DLACDPOpDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint8_t *inPrecision(NvU8 *base) const = 0; virtual uint8_t inPrecision_Int8() const = 0; virtual uint8_t inPrecision_Int16() const = 0; virtual uint8_t inPrecision_FP16() const = 0; virtual uint8_t *outPrecision(NvU8 *base) const = 0; virtual uint8_t outPrecision_Int8() const = 0; virtual uint8_t outPrecision_Int16() const = 0; virtual uint8_t outPrecision_FP16() const = 0; virtual int16_t *LUTIndex(NvU8 *base) const = 0; virtual DLACVTParamAccessor inCVTAccessor(NvU8 *base) const = 0; virtual DLACVTParamAccessor outCVTAccessor(NvU8 *base) const = 0; virtual uint8_t *localSize(NvU8 *base) const = 0; virtual uint8_t *bypassSquareSum(NvU8 *base) const = 0; virtual uint8_t *bypassOutMul(NvU8 *base) const = 0; virtual uint8_t *reserved0(NvU8 *base) const = 0; protected: DLACDPOpDesc() { } virtual ~DLACDPOpDesc() { } }; class DLACDPOpDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint8_t *inPrecision() const; uint8_t inPrecision_Int8() const; uint8_t inPrecision_Int16() const; uint8_t inPrecision_FP16() const; uint8_t *outPrecision() const; uint8_t outPrecision_Int8() const; uint8_t outPrecision_Int16() const; uint8_t outPrecision_FP16() const; int16_t *LUTIndex() const; DLACVTParamAccessor inCVTAccessor() const; DLACVTParamAccessor outCVTAccessor() const; uint8_t *localSize() const; uint8_t *bypassSquareSum() const; uint8_t *bypassOutMul() const; uint8_t *reserved0() const; DLACDPOpDescAccessor(NvU8 *base, const DLACDPOpDesc &); protected: NvU8 *_base; const DLACDPOpDesc &_l; }; // // struct dla_cdp_stat_desc // class DLACDPStatDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint32_t * nanInputNum(NvU8* base) const = 0; virtual uint32_t * infInputNum(NvU8* base) const = 0; virtual uint32_t * nanOutputNum(NvU8* base) const = 0; virtual uint32_t * writeStall(NvU8* base) const = 0; virtual uint32_t * lutUflow(NvU8* base) const = 0; virtual uint32_t * lutOflow(NvU8* base) const = 0; virtual uint32_t * lutHybrid(NvU8* base) const = 0; virtual uint32_t * lutLEHit(NvU8* base) const = 0; virtual uint32_t * lutLOHit(NvU8* base) const = 0; virtual uint32_t * saturationCount(NvU8* base) const = 0; virtual uint32_t * runtime(NvU8* base) const = 0; protected: DLACDPStatDesc() { } virtual ~DLACDPStatDesc() { } }; class DLACDPStatDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint32_t * nanInputNum() const; uint32_t * infInputNum() const; uint32_t * nanOutputNum() const; uint32_t * writeStall() const; uint32_t * lutUflow() const; uint32_t * lutOflow() const; uint32_t * lutHybrid() const; uint32_t * lutLEHit() const; uint32_t * lutLOHit() const; uint32_t * saturationCount() const; uint32_t * runtime() const; DLACDPStatDescAccessor(NvU8 *base, const DLACDPStatDesc &); protected: NvU8 *_base; const DLACDPStatDesc &_l; }; // // struct dla_rubik_surface_desc // class DLARubikSurfaceDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLADataCubeAccessor srcDataAccessor(NvU8 *base) const = 0; virtual DLADataCubeAccessor dstDataAccessor(NvU8 *base) const = 0; protected: DLARubikSurfaceDesc() { } virtual ~DLARubikSurfaceDesc() { } }; class DLARubikSurfaceDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLADataCubeAccessor srcDataAccessor() const; DLADataCubeAccessor dstDataAccessor() const; DLARubikSurfaceDescAccessor(NvU8 *base, const DLARubikSurfaceDesc &); protected: NvU8 *_base; const DLARubikSurfaceDesc &_l; }; // // dla_rubik_op_desc // class DLARubikOpDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint8_t *mode(NvU8 *base) const =0; virtual uint8_t mode_Contract() const = 0; virtual uint8_t mode_Split() const = 0; virtual uint8_t mode_Merge() const = 0; virtual uint8_t *precision(NvU8 *base) const = 0; virtual uint8_t precision_Int8() const = 0; virtual uint8_t precision_Int16() const = 0; virtual uint8_t precision_FP16() const = 0; virtual uint8_t *strideX(NvU8 *base) const = 0; virtual uint8_t *strideY(NvU8 *base) const = 0; protected: DLARubikOpDesc() { } virtual ~DLARubikOpDesc() { } }; class DLARubikOpDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint8_t *mode() const; uint8_t mode_Contract() const; uint8_t mode_Split() const; uint8_t mode_Merge() const; uint8_t *precision() const; uint8_t precision_Int8() const; uint8_t precision_Int16() const; uint8_t precision_FP16() const; uint8_t *strideX() const; uint8_t *strideY() const; DLARubikOpDescAccessor(NvU8 *base, const DLARubikOpDesc &); protected: NvU8 *_base; const DLARubikOpDesc &_l; }; // // struct dla_rubik_stat_desc // class DLARubikStatDesc { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual uint32_t * readStall(NvU8* base) const = 0; virtual uint32_t * writeStall(NvU8* base) const = 0; virtual uint32_t * runtime(NvU8* base) const = 0; protected: DLARubikStatDesc() { } virtual ~DLARubikStatDesc() { } }; class DLARubikStatDescAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; uint32_t * readStall() const; uint32_t * writeStall() const; uint32_t * runtime() const; DLARubikStatDescAccessor(NvU8 *base, const DLARubikStatDesc &); protected: NvU8 *_base; const DLARubikStatDesc &_l; }; // // union dla_surface_container // class DLASurfaceContainer { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLABDMASurfaceDescAccessor bdmaSurfaceDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLAConvSurfaceDescAccessor convSurfaceDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLASDPSurfaceDescAccessor sdpSurfaceDescAccessor (NvU8 *b, size_t c) const = 0; virtual DLAPDPSurfaceDescAccessor pdpSurfaceDescAccessor (NvU8 *b, size_t c) const = 0; virtual DLACDPSurfaceDescAccessor cdpSurfaceDescAccessor (NvU8 *b, size_t c) const = 0; virtual DLARubikSurfaceDescAccessor rubikSurfaceDescAccessor(NvU8 *b, size_t c) const = 0; protected: DLASurfaceContainer() { } virtual ~DLASurfaceContainer() { } }; class DLASurfaceContainerAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLABDMASurfaceDescAccessor bdmaSurfaceDescAccessor(size_t c) const; DLAConvSurfaceDescAccessor convSurfaceDescAccessor(size_t c) const; DLASDPSurfaceDescAccessor sdpSurfaceDescAccessor(size_t c) const; DLAPDPSurfaceDescAccessor pdpSurfaceDescAccessor(size_t c) const; DLACDPSurfaceDescAccessor cdpSurfaceDescAccessor(size_t c) const; DLARubikSurfaceDescAccessor rubikSurfaceDescAccessor(size_t c) const; DLASurfaceContainerAccessor(NvU8 *base, const DLASurfaceContainer &); protected: NvU8 *_base; const DLASurfaceContainer &_l; }; // // union dla_operation_container // class DLAOperationContainer { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLABDMAOpDescAccessor bdmaOpDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLAConvOpDescAccessor convOpDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLASDPOpDescAccessor sdpOpDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLAPDPOpDescAccessor pdpOpDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLACDPOpDescAccessor cdpOpDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLARubikOpDescAccessor rubikOpDescAccessor(NvU8 *b, size_t c) const = 0; protected: DLAOperationContainer() { } virtual ~DLAOperationContainer() { } }; class DLAOperationContainerAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLABDMAOpDescAccessor bdmaOpDescAccessor(size_t c) const; DLAConvOpDescAccessor convOpDescAccessor(size_t c) const; DLASDPOpDescAccessor sdpOpDescAccessor(size_t c) const; DLAPDPOpDescAccessor pdpOpDescAccessor(size_t c) const; DLACDPOpDescAccessor cdpOpDescAccessor(size_t c) const; DLARubikOpDescAccessor rubikOpDescAccessor(size_t c) const; DLAOperationContainerAccessor(NvU8 *base, const DLAOperationContainer &); protected: NvU8 *_base; const DLAOperationContainer &_l; }; // // union dla_stat_container // class DLAStatContainer { public: virtual size_t struct_size() const = 0; virtual size_t struct_align() const = 0; virtual DLABDMAStatDescAccessor bdmaStatDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLAConvStatDescAccessor convStatDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLASDPStatDescAccessor sdpStatDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLAPDPStatDescAccessor pdpStatDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLACDPStatDescAccessor cdpStatDescAccessor(NvU8 *b, size_t c) const = 0; virtual DLARubikStatDescAccessor rubikStatDescAccessor(NvU8 *b, size_t c) const = 0; protected: DLAStatContainer() { } virtual ~DLAStatContainer() { } }; class DLAStatContainerAccessor { public: NvU8 * struct_base() const; size_t struct_size() const; size_t struct_align() const; DLABDMAStatDescAccessor bdmaStatDescAccessor(size_t c) const; DLAConvStatDescAccessor convStatDescAccessor(size_t c) const; DLASDPStatDescAccessor sdpStatDescAccessor(size_t c) const; DLAPDPStatDescAccessor pdpStatDescAccessor(size_t c) const; DLACDPStatDescAccessor cdpStatDescAccessor(size_t c) const; DLARubikStatDescAccessor rubikStatDescAccessor(size_t c) const; DLAStatContainerAccessor(NvU8 *base, const DLAStatContainer &l); protected: NvU8 * _base; const DLAStatContainer &_l; }; class DLAInterface { public: virtual ~DLAInterface() { } // these are the targetted versions virtual NvU8 firmwareTargetVersionMajor() const = 0; virtual NvU8 firmwareTargetVersionMinor() const = 0; virtual NvU8 firmwareTargetVersionSubminor() const = 0; virtual NvU32 firmwareTargetVersion() const = 0; virtual NvU8 firmwareVersionMajor() const = 0; virtual NvU8 firmwareVersionMinor() const = 0; virtual NvU8 firmwareVersionSubminor() const = 0; virtual NvU32 firmwareVersion() const = 0; DLANetworkDescAccessor networkDescAccessor(NvU8 *b) const; DLAConsumerAccessor consumerAccessor(NvU8 *b) const; DLACommonOpDescAccessor commonOpDescAccessor(NvU8 *b) const; DLACVTParamAccessor cvtParamAccessor(NvU8 *b) const; DLADataCubeAccessor dataCubeAccessor(NvU8 *b) const; DLAConvSurfaceDescAccessor convSurfaceDescAccessor(NvU8 *b) const; DLAConvOpDescAccessor convOpDescAccessor(NvU8 *b) const; DLALUTOffsetAccessor lutOffsetAccessor(NvU8 *b) const; DLAFloatDataAccessor floatDataAccessor(NvU8 *b) const; DLASlopeAccessor slopeAccessor(NvU8 *b) const; DLALUTParamAccessor lutParamAccessor(NvU8 *b) const; DLASDPSurfaceDescAccessor sdpSurfaceDescAccessor(NvU8 *b) const; DLASDPOpAccessor sdpOpAccessor(NvU8 *b) const; DLASDPOpDescAccessor sdpOpDescAccessor(NvU8 *b) const; DLASDPCVTAccessor sdpCVTAccessor(NvU8 *b) const; DLAPDPSurfaceDescAccessor pdpSurfaceDescAccessor(NvU8 *b) const; DLAPDPOpDescAccessor pdpOpDescAccessor(NvU8 *b) const; DLACDPSurfaceDescAccessor cdpSurfaceDescAccessor(NvU8 *b) const; DLACDPOpDescAccessor cdpOpDescAccessor(NvU8 *b) const; DLARubikSurfaceDescAccessor rubikSurfaceDescAccessor(NvU8 *b) const; DLARubikOpDescAccessor rubikOpDescAccessor(NvU8 *b) const; DLASurfaceContainerAccessor surfaceContainerAccessor(NvU8 *b) const; DLAOperationContainerAccessor operationContainerAccessor(NvU8 *b) const; protected: virtual const DLANetworkDesc & networkDesc() const = 0; virtual const DLAConsumer & consumer() const = 0; virtual const DLACommonOpDesc & commonOpDesc() const = 0; virtual const DLACVTParam & cvtParam() const = 0; virtual const DLADataCube & dataCube() const = 0; virtual const DLAConvSurfaceDesc & convSurfaceDesc() const = 0; virtual const DLAConvOpDesc & convOpDesc()const = 0; virtual const DLALUTOffset & lutOffset() const = 0; virtual const DLAFloatData & floatData() const = 0; virtual const DLASlope & slope() const = 0; virtual const DLALUTParam & lutParam() const = 0; virtual const DLASDPSurfaceDesc & sdpSurfaceDesc() const = 0; virtual const DLASDPOp & sdpOp() const = 0; virtual const DLASDPOpDesc & sdpOpDesc() const = 0; virtual const DLASDPCVT & sdpCVT() const = 0; virtual const DLAPDPSurfaceDesc & pdpSurfaceDesc() const = 0; virtual const DLAPDPOpDesc & pdpOpDesc() const = 0; virtual const DLACDPSurfaceDesc & cdpSurfaceDesc() const = 0; virtual const DLACDPOpDesc & cdpOpDesc() const = 0; virtual const DLARubikSurfaceDesc & rubikSurfaceDesc() const = 0; virtual const DLARubikOpDesc & rubikOpDesc() const = 0; virtual const DLASurfaceContainer & surfaceContainer() const = 0; virtual const DLAOperationContainer & operationContainer() const = 0; }; class DLAInterfaceA : public DLAInterface { public: virtual ~DLAInterfaceA() { } virtual NvU8 firmwareTargetVersionMajor() const; virtual NvU8 firmwareTargetVersionMinor() const; virtual NvU8 firmwareTargetVersionSubminor() const; virtual NvU32 firmwareTargetVersion() const; virtual NvU8 firmwareVersionMajor() const; virtual NvU8 firmwareVersionMinor() const; virtual NvU8 firmwareVersionSubminor() const; virtual NvU32 firmwareVersion() const; DLANetworkDescAccessor networkDescAccessor(NvU8 *b) const; DLAConsumerAccessor consumerAccessor(NvU8 *b) const; DLACommonOpDescAccessor commonOpDescAccessor(NvU8 *b) const; DLACVTParamAccessor cvtParamAccessor(NvU8 *b) const; DLADataCubeAccessor dataCubeAccessor(NvU8 *b) const; DLAConvSurfaceDescAccessor convSurfaceDescAccessor(NvU8 *b) const; DLAConvOpDescAccessor convOpDescAccessor(NvU8 *b) const; DLALUTOffsetAccessor lutOffsetAccessor(NvU8 *b) const; DLAFloatDataAccessor floatDataAccessor(NvU8 *b) const; DLASlopeAccessor slopeAccessor(NvU8 *b) const; DLALUTParamAccessor lutParamAccessor(NvU8 *b) const; DLASDPSurfaceDescAccessor sdpSurfaceDescAccessor(NvU8 *b) const; DLASDPOpAccessor sdpOpAccessor(NvU8 *b) const; DLASDPOpDescAccessor sdpOpDescAccessor(NvU8 *b) const; DLAPDPSurfaceDescAccessor pdpSurfaceDescAccessor(NvU8 *b) const; DLAPDPOpDescAccessor pdpOpDescAccessor(NvU8 *b) const; DLACDPSurfaceDescAccessor cdpSurfaceDescAccessor(NvU8 *b) const; DLACDPOpDescAccessor cdpOpDescAccessor(NvU8 *b) const; DLARubikSurfaceDescAccessor rubikSurfaceDescAccessor(NvU8 *b) const; DLARubikOpDescAccessor rubikOpDescAccessor(NvU8 *b) const; DLASurfaceContainerAccessor surfaceContainerAccessor(NvU8 *b) const; DLAOperationContainerAccessor operationContainerAccessor(NvU8 *b) const; protected: virtual const DLANetworkDesc & networkDesc() const; virtual const DLAConsumer & consumer() const; virtual const DLACommonOpDesc & commonOpDesc() const; virtual const DLACVTParam & cvtParam() const; virtual const DLADataCube & dataCube() const; virtual const DLAConvSurfaceDesc & convSurfaceDesc() const; virtual const DLAConvOpDesc & convOpDesc() const; virtual const DLALUTOffset & lutOffset() const; virtual const DLAFloatData & floatData() const; virtual const DLASlope & slope() const; virtual const DLALUTParam & lutParam() const; virtual const DLASDPSurfaceDesc & sdpSurfaceDesc() const; virtual const DLASDPOp & sdpOp() const; virtual const DLASDPOpDesc & sdpOpDesc() const; virtual const DLASDPCVT & sdpCVT() const; virtual const DLAPDPSurfaceDesc & pdpSurfaceDesc() const; virtual const DLAPDPOpDesc & pdpOpDesc() const; virtual const DLACDPSurfaceDesc & cdpSurfaceDesc() const; virtual const DLACDPOpDesc & cdpOpDesc() const; virtual const DLARubikSurfaceDesc & rubikSurfaceDesc() const; virtual const DLARubikOpDesc & rubikOpDesc() const; virtual const DLASurfaceContainer & surfaceContainer() const; virtual const DLAOperationContainer & operationContainer() const; // virtual const & () const; // virtual const & () const; }; class DLAInterfaceB : public DLAInterface { public: virtual ~DLAInterfaceB() { } virtual NvU8 firmwareTargetVersionMajor() const; virtual NvU8 firmwareTargetVersionMinor() const; virtual NvU8 firmwareTargetVersionSubminor() const; virtual NvU32 firmwareTargetVersion() const; virtual NvU8 firmwareVersionMajor() const; virtual NvU8 firmwareVersionMinor() const; virtual NvU8 firmwareVersionSubminor() const; virtual NvU32 firmwareVersion() const; DLANetworkDescAccessor networkDescAccessor(NvU8 *b) const; DLAConsumerAccessor consumerAccessor(NvU8 *b) const; DLACommonOpDescAccessor commonOpDescAccessor(NvU8 *b) const; DLACVTParamAccessor cvtParamAccessor(NvU8 *b) const; DLADataCubeAccessor dataCubeAccessor(NvU8 *b) const; DLAConvSurfaceDescAccessor convSurfaceDescAccessor(NvU8 *b) const; DLAConvOpDescAccessor convOpDescAccessor(NvU8 *b) const; DLALUTOffsetAccessor lutOffsetAccessor(NvU8 *b) const; DLAFloatDataAccessor floatDataAccessor(NvU8 *b) const; DLASlopeAccessor slopeAccessor(NvU8 *b) const; DLALUTParamAccessor lutParamAccessor(NvU8 *b) const; DLASDPSurfaceDescAccessor sdpSurfaceDescAccessor(NvU8 *b) const; DLASDPOpAccessor sdpOpAccessor(NvU8 *b) const; DLASDPOpDescAccessor sdpOpDescAccessor(NvU8 *b) const; DLAPDPSurfaceDescAccessor pdpSurfaceDescAccessor(NvU8 *b) const; DLAPDPOpDescAccessor pdpOpDescAccessor(NvU8 *b) const; DLACDPSurfaceDescAccessor cdpSurfaceDescAccessor(NvU8 *b) const; DLACDPOpDescAccessor cdpOpDescAccessor(NvU8 *b) const; DLARubikSurfaceDescAccessor rubikSurfaceDescAccessor(NvU8 *b) const; DLARubikOpDescAccessor rubikOpDescAccessor(NvU8 *b) const; DLASurfaceContainerAccessor surfaceContainerAccessor(NvU8 *b) const; DLAOperationContainerAccessor operationContainerAccessor(NvU8 *b) const; protected: virtual const DLANetworkDesc & networkDesc() const; virtual const DLAConsumer & consumer() const; virtual const DLACommonOpDesc & commonOpDesc() const; virtual const DLACVTParam & cvtParam() const; virtual const DLADataCube & dataCube() const; virtual const DLAConvSurfaceDesc & convSurfaceDesc() const; virtual const DLAConvOpDesc & convOpDesc() const; virtual const DLALUTOffset & lutOffset() const; virtual const DLAFloatData & floatData() const; virtual const DLASlope & slope() const; virtual const DLALUTParam & lutParam() const; virtual const DLASDPSurfaceDesc & sdpSurfaceDesc() const; virtual const DLASDPOp & sdpOp() const; virtual const DLASDPOpDesc & sdpOpDesc() const; virtual const DLASDPCVT & sdpCVT() const; virtual const DLAPDPSurfaceDesc & pdpSurfaceDesc() const; virtual const DLAPDPOpDesc & pdpOpDesc() const; virtual const DLACDPSurfaceDesc & cdpSurfaceDesc() const; virtual const DLACDPOpDesc & cdpOpDesc() const; virtual const DLARubikSurfaceDesc & rubikSurfaceDesc() const; virtual const DLARubikOpDesc & rubikOpDesc() const; virtual const DLASurfaceContainer & surfaceContainer() const; virtual const DLAOperationContainer & operationContainer() const; // virtual const & () const; // virtual const & () const; }; class DLAInterfaceC : public DLAInterface { public: virtual ~DLAInterfaceC() { } virtual NvU8 firmwareTargetVersionMajor() const; virtual NvU8 firmwareTargetVersionMinor() const; virtual NvU8 firmwareTargetVersionSubminor() const; virtual NvU32 firmwareTargetVersion() const; virtual NvU8 firmwareVersionMajor() const; virtual NvU8 firmwareVersionMinor() const; virtual NvU8 firmwareVersionSubminor() const; virtual NvU32 firmwareVersion() const; DLANetworkDescAccessor networkDescAccessor(NvU8 *b) const; DLAConsumerAccessor consumerAccessor(NvU8 *b) const; DLACommonOpDescAccessor commonOpDescAccessor(NvU8 *b) const; DLACVTParamAccessor cvtParamAccessor(NvU8 *b) const; DLADataCubeAccessor dataCubeAccessor(NvU8 *b) const; DLAConvSurfaceDescAccessor convSurfaceDescAccessor(NvU8 *b) const; DLAConvOpDescAccessor convOpDescAccessor(NvU8 *b) const; DLALUTOffsetAccessor lutOffsetAccessor(NvU8 *b) const; DLAFloatDataAccessor floatDataAccessor(NvU8 *b) const; DLASlopeAccessor slopeAccessor(NvU8 *b) const; DLALUTParamAccessor lutParamAccessor(NvU8 *b) const; DLASDPSurfaceDescAccessor sdpSurfaceDescAccessor(NvU8 *b) const; DLASDPOpAccessor sdpOpAccessor(NvU8 *b) const; DLASDPOpDescAccessor sdpOpDescAccessor(NvU8 *b) const; DLAPDPSurfaceDescAccessor pdpSurfaceDescAccessor(NvU8 *b) const; DLAPDPOpDescAccessor pdpOpDescAccessor(NvU8 *b) const; DLACDPSurfaceDescAccessor cdpSurfaceDescAccessor(NvU8 *b) const; DLACDPOpDescAccessor cdpOpDescAccessor(NvU8 *b) const; DLARubikSurfaceDescAccessor rubikSurfaceDescAccessor(NvU8 *b) const; DLARubikOpDescAccessor rubikOpDescAccessor(NvU8 *b) const; DLASurfaceContainerAccessor surfaceContainerAccessor(NvU8 *b) const; DLAOperationContainerAccessor operationContainerAccessor(NvU8 *b) const; protected: virtual const DLANetworkDesc & networkDesc() const; virtual const DLAConsumer & consumer() const; virtual const DLACommonOpDesc & commonOpDesc() const; virtual const DLACVTParam & cvtParam() const; virtual const DLADataCube & dataCube() const; virtual const DLAConvSurfaceDesc & convSurfaceDesc() const; virtual const DLAConvOpDesc & convOpDesc() const; virtual const DLALUTOffset & lutOffset() const; virtual const DLAFloatData & floatData() const; virtual const DLASlope & slope() const; virtual const DLALUTParam & lutParam() const; virtual const DLASDPSurfaceDesc & sdpSurfaceDesc() const; virtual const DLASDPOp & sdpOp() const; virtual const DLASDPOpDesc & sdpOpDesc() const; virtual const DLASDPCVT & sdpCVT() const; virtual const DLAPDPSurfaceDesc & pdpSurfaceDesc() const; virtual const DLAPDPOpDesc & pdpOpDesc() const; virtual const DLACDPSurfaceDesc & cdpSurfaceDesc() const; virtual const DLACDPOpDesc & cdpOpDesc() const; virtual const DLARubikSurfaceDesc & rubikSurfaceDesc() const; virtual const DLARubikOpDesc & rubikOpDesc() const; virtual const DLASurfaceContainer & surfaceContainer() const; virtual const DLAOperationContainer & operationContainer() const; // virtual const & () const; // virtual const & () const; }; class DLAInterfaceD : public DLAInterface { public: virtual ~DLAInterfaceD() { } virtual NvU8 firmwareTargetVersionMajor() const; virtual NvU8 firmwareTargetVersionMinor() const; virtual NvU8 firmwareTargetVersionSubminor() const; virtual NvU32 firmwareTargetVersion() const; virtual NvU8 firmwareVersionMajor() const; virtual NvU8 firmwareVersionMinor() const; virtual NvU8 firmwareVersionSubminor() const; virtual NvU32 firmwareVersion() const; DLANetworkDescAccessor networkDescAccessor(NvU8 *b) const; DLAConsumerAccessor consumerAccessor(NvU8 *b) const; DLACommonOpDescAccessor commonOpDescAccessor(NvU8 *b) const; DLACVTParamAccessor cvtParamAccessor(NvU8 *b) const; DLADataCubeAccessor dataCubeAccessor(NvU8 *b) const; DLAConvSurfaceDescAccessor convSurfaceDescAccessor(NvU8 *b) const; DLAConvOpDescAccessor convOpDescAccessor(NvU8 *b) const; DLALUTOffsetAccessor lutOffsetAccessor(NvU8 *b) const; DLAFloatDataAccessor floatDataAccessor(NvU8 *b) const; DLASlopeAccessor slopeAccessor(NvU8 *b) const; DLALUTParamAccessor lutParamAccessor(NvU8 *b) const; DLASDPSurfaceDescAccessor sdpSurfaceDescAccessor(NvU8 *b) const; DLASDPOpAccessor sdpOpAccessor(NvU8 *b) const; DLASDPOpDescAccessor sdpOpDescAccessor(NvU8 *b) const; DLAPDPSurfaceDescAccessor pdpSurfaceDescAccessor(NvU8 *b) const; DLAPDPOpDescAccessor pdpOpDescAccessor(NvU8 *b) const; DLACDPSurfaceDescAccessor cdpSurfaceDescAccessor(NvU8 *b) const; DLACDPOpDescAccessor cdpOpDescAccessor(NvU8 *b) const; DLARubikSurfaceDescAccessor rubikSurfaceDescAccessor(NvU8 *b) const; DLARubikOpDescAccessor rubikOpDescAccessor(NvU8 *b) const; DLASurfaceContainerAccessor surfaceContainerAccessor(NvU8 *b) const; DLAOperationContainerAccessor operationContainerAccessor(NvU8 *b) const; protected: virtual const DLANetworkDesc & networkDesc() const; virtual const DLAConsumer & consumer() const; virtual const DLACommonOpDesc & commonOpDesc() const; virtual const DLACVTParam & cvtParam() const; virtual const DLADataCube & dataCube() const; virtual const DLAConvSurfaceDesc & convSurfaceDesc() const; virtual const DLAConvOpDesc & convOpDesc() const; virtual const DLALUTOffset & lutOffset() const; virtual const DLAFloatData & floatData() const; virtual const DLASlope & slope() const; virtual const DLALUTParam & lutParam() const; virtual const DLASDPSurfaceDesc & sdpSurfaceDesc() const; virtual const DLASDPOp & sdpOp() const; virtual const DLASDPOpDesc & sdpOpDesc() const; virtual const DLASDPCVT & sdpCVT() const; virtual const DLAPDPSurfaceDesc & pdpSurfaceDesc() const; virtual const DLAPDPOpDesc & pdpOpDesc() const; virtual const DLACDPSurfaceDesc & cdpSurfaceDesc() const; virtual const DLACDPOpDesc & cdpOpDesc() const; virtual const DLARubikSurfaceDesc & rubikSurfaceDesc() const; virtual const DLARubikOpDesc & rubikOpDesc() const; virtual const DLASurfaceContainer & surfaceContainer() const; virtual const DLAOperationContainer & operationContainer() const; // virtual const & () const; // virtual const & () const; }; class DLAInterfaceE : public DLAInterface { public: virtual ~DLAInterfaceE() { } virtual NvU8 firmwareTargetVersionMajor() const; virtual NvU8 firmwareTargetVersionMinor() const; virtual NvU8 firmwareTargetVersionSubminor() const; virtual NvU32 firmwareTargetVersion() const; virtual NvU8 firmwareVersionMajor() const; virtual NvU8 firmwareVersionMinor() const; virtual NvU8 firmwareVersionSubminor() const; virtual NvU32 firmwareVersion() const; DLANetworkDescAccessor networkDescAccessor(NvU8 *b) const; DLAConsumerAccessor consumerAccessor(NvU8 *b) const; DLACommonOpDescAccessor commonOpDescAccessor(NvU8 *b) const; DLACVTParamAccessor cvtParamAccessor(NvU8 *b) const; DLADataCubeAccessor dataCubeAccessor(NvU8 *b) const; DLAConvSurfaceDescAccessor convSurfaceDescAccessor(NvU8 *b) const; DLAConvOpDescAccessor convOpDescAccessor(NvU8 *b) const; DLALUTOffsetAccessor lutOffsetAccessor(NvU8 *b) const; DLAFloatDataAccessor floatDataAccessor(NvU8 *b) const; DLASlopeAccessor slopeAccessor(NvU8 *b) const; DLALUTParamAccessor lutParamAccessor(NvU8 *b) const; DLASDPSurfaceDescAccessor sdpSurfaceDescAccessor(NvU8 *b) const; DLASDPOpAccessor sdpOpAccessor(NvU8 *b) const; DLASDPOpDescAccessor sdpOpDescAccessor(NvU8 *b) const; DLAPDPSurfaceDescAccessor pdpSurfaceDescAccessor(NvU8 *b) const; DLAPDPOpDescAccessor pdpOpDescAccessor(NvU8 *b) const; DLACDPSurfaceDescAccessor cdpSurfaceDescAccessor(NvU8 *b) const; DLACDPOpDescAccessor cdpOpDescAccessor(NvU8 *b) const; DLARubikSurfaceDescAccessor rubikSurfaceDescAccessor(NvU8 *b) const; DLARubikOpDescAccessor rubikOpDescAccessor(NvU8 *b) const; DLASurfaceContainerAccessor surfaceContainerAccessor(NvU8 *b) const; DLAOperationContainerAccessor operationContainerAccessor(NvU8 *b) const; protected: virtual const DLANetworkDesc & networkDesc() const; virtual const DLAConsumer & consumer() const; virtual const DLACommonOpDesc & commonOpDesc() const; virtual const DLACVTParam & cvtParam() const; virtual const DLADataCube & dataCube() const; virtual const DLAConvSurfaceDesc & convSurfaceDesc() const; virtual const DLAConvOpDesc & convOpDesc() const; virtual const DLALUTOffset & lutOffset() const; virtual const DLAFloatData & floatData() const; virtual const DLASlope & slope() const; virtual const DLALUTParam & lutParam() const; virtual const DLASDPSurfaceDesc & sdpSurfaceDesc() const; virtual const DLASDPOp & sdpOp() const; virtual const DLASDPOpDesc & sdpOpDesc() const; virtual const DLASDPCVT & sdpCVT() const; virtual const DLAPDPSurfaceDesc & pdpSurfaceDesc() const; virtual const DLAPDPOpDesc & pdpOpDesc() const; virtual const DLACDPSurfaceDesc & cdpSurfaceDesc() const; virtual const DLACDPOpDesc & cdpOpDesc() const; virtual const DLARubikSurfaceDesc & rubikSurfaceDesc() const; virtual const DLARubikOpDesc & rubikOpDesc() const; virtual const DLASurfaceContainer & surfaceContainer() const; virtual const DLAOperationContainer & operationContainer() const; // virtual const & () const; // virtual const & () const; }; } // nvdla::priv } // nvdla #endif // NVDLA_PRIV_DLA_INTERFACE_H
37,598
1,338
/* version.h 1.118 2003/12/20 07:16:36 (<NAME>) */ #define CS_PKG_RELEASE "3.2.8" #define CS_PKG_RELEASE_CODE 0x3208 #define VERSION(v,p,s) (((v)<<16)+(p<<8)+s) #ifdef CONFIG_PCMCIA #include_next <pcmcia/version.h> #else #define CS_RELEASE CS_PKG_RELEASE #define CS_RELEASE_CODE CS_PKG_RELEASE_CODE #endif
157
1,208
// // TLRecorderIndicatorView.h // TLChat // // Created by 李伯坤 on 16/7/12. // Copyright © 2016年 李伯坤. All rights reserved. // #import <UIKit/UIKit.h> typedef NS_ENUM(NSInteger, TLRecorderStatus) { TLRecorderStatusRecording, TLRecorderStatusWillCancel, TLRecorderStatusTooShort, }; @interface TLRecorderIndicatorView : UIView @property (nonatomic, assign) TLRecorderStatus status; /** * 音量大小,取值(0-1) */ @property (nonatomic, assign) CGFloat volume; @end
213
2,151
// Copyright (c) 2013 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. #include "ui/aura/client/window_parenting_client.h" #include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/base/class_property.h" DEFINE_UI_CLASS_PROPERTY_TYPE(aura::client::WindowParentingClient*) namespace aura { namespace client { DEFINE_UI_CLASS_PROPERTY_KEY(WindowParentingClient*, kRootWindowWindowParentingClientKey, NULL); void SetWindowParentingClient(Window* window, WindowParentingClient* window_tree_client) { DCHECK(window); Window* root_window = window->GetRootWindow(); DCHECK(root_window); root_window->SetProperty(kRootWindowWindowParentingClientKey, window_tree_client); } WindowParentingClient* GetWindowParentingClient(Window* window) { DCHECK(window); Window* root_window = window->GetRootWindow(); DCHECK(root_window); WindowParentingClient* client = root_window->GetProperty(kRootWindowWindowParentingClientKey); DCHECK(client); return client; } void ParentWindowWithContext(Window* window, Window* context, const gfx::Rect& screen_bounds) { DCHECK(context); // |context| must be attached to a hierarchy with a WindowParentingClient. WindowParentingClient* client = GetWindowParentingClient(context); DCHECK(client); Window* default_parent = client->GetDefaultParent(window, screen_bounds); default_parent->AddChild(window); } } // namespace client } // namespace aura
653
2,151
<filename>src/dawn_native/BindGroupLayout.cpp // Copyright 2017 The Dawn 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 // // 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 "dawn_native/BindGroupLayout.h" #include "common/BitSetIterator.h" #include "common/HashUtils.h" #include "dawn_native/Device.h" #include "dawn_native/PerStage.h" #include "dawn_native/ValidationUtils_autogen.h" #include <algorithm> #include <functional> #include <set> namespace dawn_native { MaybeError ValidateBindingTypeWithShaderStageVisibility( wgpu::BindingType bindingType, wgpu::ShaderStage shaderStageVisibility) { // TODO(<EMAIL>): support read-write storage textures. switch (bindingType) { case wgpu::BindingType::StorageBuffer: { if ((shaderStageVisibility & wgpu::ShaderStage::Vertex) != 0) { return DAWN_VALIDATION_ERROR( "storage buffer binding is not supported in vertex shader"); } break; } case wgpu::BindingType::WriteonlyStorageTexture: { if ((shaderStageVisibility & wgpu::ShaderStage::Vertex) != 0) { return DAWN_VALIDATION_ERROR( "write-only storage texture binding is not supported in vertex shader"); } break; } case wgpu::BindingType::StorageTexture: { return DAWN_VALIDATION_ERROR("Read-write storage texture binding is not supported"); } case wgpu::BindingType::UniformBuffer: case wgpu::BindingType::ReadonlyStorageBuffer: case wgpu::BindingType::Sampler: case wgpu::BindingType::ComparisonSampler: case wgpu::BindingType::SampledTexture: case wgpu::BindingType::ReadonlyStorageTexture: break; } return {}; } MaybeError ValidateStorageTextureFormat(DeviceBase* device, wgpu::BindingType bindingType, wgpu::TextureFormat storageTextureFormat) { switch (bindingType) { case wgpu::BindingType::ReadonlyStorageTexture: case wgpu::BindingType::WriteonlyStorageTexture: { if (storageTextureFormat == wgpu::TextureFormat::Undefined) { return DAWN_VALIDATION_ERROR("Storage texture format is missing"); } DAWN_TRY(ValidateTextureFormat(storageTextureFormat)); const Format* format = nullptr; DAWN_TRY_ASSIGN(format, device->GetInternalFormat(storageTextureFormat)); ASSERT(format != nullptr); if (!format->supportsStorageUsage) { return DAWN_VALIDATION_ERROR("The storage texture format is not supported"); } break; } case wgpu::BindingType::StorageBuffer: case wgpu::BindingType::UniformBuffer: case wgpu::BindingType::ReadonlyStorageBuffer: case wgpu::BindingType::Sampler: case wgpu::BindingType::ComparisonSampler: case wgpu::BindingType::SampledTexture: break; default: UNREACHABLE(); break; } return {}; } MaybeError ValidateStorageTextureViewDimension(wgpu::BindingType bindingType, wgpu::TextureViewDimension dimension) { switch (bindingType) { case wgpu::BindingType::ReadonlyStorageTexture: case wgpu::BindingType::WriteonlyStorageTexture: { break; } case wgpu::BindingType::StorageBuffer: case wgpu::BindingType::UniformBuffer: case wgpu::BindingType::ReadonlyStorageBuffer: case wgpu::BindingType::Sampler: case wgpu::BindingType::ComparisonSampler: case wgpu::BindingType::SampledTexture: return {}; case wgpu::BindingType::StorageTexture: default: UNREACHABLE(); return {}; } switch (dimension) { case wgpu::TextureViewDimension::Cube: case wgpu::TextureViewDimension::CubeArray: return DAWN_VALIDATION_ERROR( "Cube map and cube map texture views cannot be used as storage textures"); case wgpu::TextureViewDimension::e1D: case wgpu::TextureViewDimension::e2D: case wgpu::TextureViewDimension::e2DArray: case wgpu::TextureViewDimension::e3D: return {}; case wgpu::TextureViewDimension::Undefined: default: UNREACHABLE(); return {}; } } MaybeError ValidateBindingCanBeMultisampled(wgpu::BindingType bindingType, wgpu::TextureViewDimension viewDimension) { switch (bindingType) { case wgpu::BindingType::SampledTexture: break; case wgpu::BindingType::ReadonlyStorageTexture: case wgpu::BindingType::WriteonlyStorageTexture: return DAWN_VALIDATION_ERROR("Storage texture bindings may not be multisampled"); case wgpu::BindingType::StorageBuffer: case wgpu::BindingType::UniformBuffer: case wgpu::BindingType::ReadonlyStorageBuffer: return DAWN_VALIDATION_ERROR("Buffer bindings may not be multisampled"); case wgpu::BindingType::Sampler: case wgpu::BindingType::ComparisonSampler: return DAWN_VALIDATION_ERROR("Sampler bindings may not be multisampled"); case wgpu::BindingType::StorageTexture: default: UNREACHABLE(); return {}; } switch (viewDimension) { case wgpu::TextureViewDimension::e2D: break; case wgpu::TextureViewDimension::e2DArray: return DAWN_VALIDATION_ERROR("2D array texture bindings may not be multisampled"); case wgpu::TextureViewDimension::Cube: case wgpu::TextureViewDimension::CubeArray: return DAWN_VALIDATION_ERROR("Cube texture bindings may not be multisampled"); case wgpu::TextureViewDimension::e3D: return DAWN_VALIDATION_ERROR("3D texture bindings may not be multisampled"); case wgpu::TextureViewDimension::e1D: return DAWN_VALIDATION_ERROR("1D texture bindings may not be multisampled"); case wgpu::TextureViewDimension::Undefined: default: UNREACHABLE(); return {}; } return {}; } MaybeError ValidateBindGroupLayoutDescriptor(DeviceBase* device, const BindGroupLayoutDescriptor* descriptor) { if (descriptor->nextInChain != nullptr) { return DAWN_VALIDATION_ERROR("nextInChain must be nullptr"); } std::set<BindingNumber> bindingsSet; BindingCounts bindingCounts = {}; for (uint32_t i = 0; i < descriptor->entryCount; ++i) { const BindGroupLayoutEntry& entry = descriptor->entries[i]; BindingNumber bindingNumber = BindingNumber(entry.binding); DAWN_TRY(ValidateShaderStage(entry.visibility)); DAWN_TRY(ValidateBindingType(entry.type)); DAWN_TRY(ValidateTextureComponentType(entry.textureComponentType)); wgpu::TextureViewDimension viewDimension = wgpu::TextureViewDimension::e2D; if (entry.viewDimension != wgpu::TextureViewDimension::Undefined) { DAWN_TRY(ValidateTextureViewDimension(entry.viewDimension)); viewDimension = entry.viewDimension; } if (bindingsSet.count(bindingNumber) != 0) { return DAWN_VALIDATION_ERROR("some binding index was specified more than once"); } DAWN_TRY(ValidateBindingTypeWithShaderStageVisibility(entry.type, entry.visibility)); DAWN_TRY(ValidateStorageTextureFormat(device, entry.type, entry.storageTextureFormat)); DAWN_TRY(ValidateStorageTextureViewDimension(entry.type, viewDimension)); if (entry.multisampled) { DAWN_TRY(ValidateBindingCanBeMultisampled(entry.type, viewDimension)); } switch (entry.type) { case wgpu::BindingType::UniformBuffer: case wgpu::BindingType::StorageBuffer: case wgpu::BindingType::ReadonlyStorageBuffer: break; case wgpu::BindingType::SampledTexture: if (entry.hasDynamicOffset) { return DAWN_VALIDATION_ERROR("Sampled textures cannot be dynamic"); } break; case wgpu::BindingType::Sampler: case wgpu::BindingType::ComparisonSampler: if (entry.hasDynamicOffset) { return DAWN_VALIDATION_ERROR("Samplers cannot be dynamic"); } break; case wgpu::BindingType::ReadonlyStorageTexture: case wgpu::BindingType::WriteonlyStorageTexture: if (entry.hasDynamicOffset) { return DAWN_VALIDATION_ERROR("Storage textures cannot be dynamic"); } break; case wgpu::BindingType::StorageTexture: return DAWN_VALIDATION_ERROR("storage textures aren't supported (yet)"); default: UNREACHABLE(); break; } IncrementBindingCounts(&bindingCounts, entry); bindingsSet.insert(bindingNumber); } DAWN_TRY(ValidateBindingCounts(bindingCounts)); return {}; } namespace { void HashCombineBindingInfo(size_t* hash, const BindingInfo& info) { HashCombine(hash, info.hasDynamicOffset, info.multisampled, info.visibility, info.type, info.textureComponentType, info.viewDimension, info.storageTextureFormat, info.minBufferBindingSize); } bool operator!=(const BindingInfo& a, const BindingInfo& b) { return a.hasDynamicOffset != b.hasDynamicOffset || // a.multisampled != b.multisampled || // a.visibility != b.visibility || // a.type != b.type || // a.textureComponentType != b.textureComponentType || // a.viewDimension != b.viewDimension || // a.storageTextureFormat != b.storageTextureFormat || // a.minBufferBindingSize != b.minBufferBindingSize; } bool IsBufferBinding(wgpu::BindingType bindingType) { switch (bindingType) { case wgpu::BindingType::UniformBuffer: case wgpu::BindingType::StorageBuffer: case wgpu::BindingType::ReadonlyStorageBuffer: return true; case wgpu::BindingType::SampledTexture: case wgpu::BindingType::Sampler: case wgpu::BindingType::ComparisonSampler: case wgpu::BindingType::StorageTexture: case wgpu::BindingType::ReadonlyStorageTexture: case wgpu::BindingType::WriteonlyStorageTexture: return false; default: UNREACHABLE(); return false; } } bool SortBindingsCompare(const BindGroupLayoutEntry& a, const BindGroupLayoutEntry& b) { const bool aIsBuffer = IsBufferBinding(a.type); const bool bIsBuffer = IsBufferBinding(b.type); if (aIsBuffer != bIsBuffer) { // Always place buffers first. return aIsBuffer; } else { if (aIsBuffer) { ASSERT(bIsBuffer); if (a.hasDynamicOffset != b.hasDynamicOffset) { // Buffers with dynamic offsets should come before those without. // This makes it easy to iterate over the dynamic buffer bindings // [0, dynamicBufferCount) during validation. return a.hasDynamicOffset; } if (a.hasDynamicOffset) { ASSERT(b.hasDynamicOffset); ASSERT(a.binding != b.binding); // Above, we ensured that dynamic buffers are first. Now, ensure that // dynamic buffer bindings are in increasing order. This is because dynamic // buffer offsets are applied in increasing order of binding number. return a.binding < b.binding; } } // Otherwise, sort by type. if (a.type != b.type) { return a.type < b.type; } } if (a.visibility != b.visibility) { return a.visibility < b.visibility; } if (a.multisampled != b.multisampled) { return a.multisampled < b.multisampled; } if (a.viewDimension != b.viewDimension) { return a.viewDimension < b.viewDimension; } if (a.textureComponentType != b.textureComponentType) { return a.textureComponentType < b.textureComponentType; } if (a.storageTextureFormat != b.storageTextureFormat) { return a.storageTextureFormat < b.storageTextureFormat; } if (a.minBufferBindingSize != b.minBufferBindingSize) { return a.minBufferBindingSize < b.minBufferBindingSize; } return false; } // This is a utility function to help ASSERT that the BGL-binding comparator places buffers // first. bool CheckBufferBindingsFirst(ityp::span<BindingIndex, const BindingInfo> bindings) { BindingIndex lastBufferIndex{0}; BindingIndex firstNonBufferIndex = std::numeric_limits<BindingIndex>::max(); for (BindingIndex i{0}; i < bindings.size(); ++i) { if (IsBufferBinding(bindings[i].type)) { lastBufferIndex = std::max(i, lastBufferIndex); } else { firstNonBufferIndex = std::min(i, firstNonBufferIndex); } } // If there are no buffers, then |lastBufferIndex| is initialized to 0 and // |firstNonBufferIndex| gets set to 0. return firstNonBufferIndex >= lastBufferIndex; } } // namespace // BindGroupLayoutBase BindGroupLayoutBase::BindGroupLayoutBase(DeviceBase* device, const BindGroupLayoutDescriptor* descriptor) : CachedObject(device), mBindingInfo(BindingIndex(descriptor->entryCount)) { std::vector<BindGroupLayoutEntry> sortedBindings( descriptor->entries, descriptor->entries + descriptor->entryCount); std::sort(sortedBindings.begin(), sortedBindings.end(), SortBindingsCompare); for (BindingIndex i{0}; i < mBindingInfo.size(); ++i) { const BindGroupLayoutEntry& binding = sortedBindings[static_cast<uint32_t>(i)]; mBindingInfo[i].binding = BindingNumber(binding.binding); mBindingInfo[i].type = binding.type; mBindingInfo[i].visibility = binding.visibility; mBindingInfo[i].textureComponentType = Format::TextureComponentTypeToFormatType(binding.textureComponentType); mBindingInfo[i].storageTextureFormat = binding.storageTextureFormat; mBindingInfo[i].minBufferBindingSize = binding.minBufferBindingSize; if (binding.viewDimension == wgpu::TextureViewDimension::Undefined) { mBindingInfo[i].viewDimension = wgpu::TextureViewDimension::e2D; } else { mBindingInfo[i].viewDimension = binding.viewDimension; } mBindingInfo[i].multisampled = binding.multisampled; mBindingInfo[i].hasDynamicOffset = binding.hasDynamicOffset; if (IsBufferBinding(binding.type)) { // Buffers must be contiguously packed at the start of the binding info. ASSERT(GetBufferCount() == i); } IncrementBindingCounts(&mBindingCounts, binding); const auto& it = mBindingMap.emplace(BindingNumber(binding.binding), i); ASSERT(it.second); } ASSERT(CheckBufferBindingsFirst({mBindingInfo.data(), GetBindingCount()})); ASSERT(mBindingInfo.size() <= kMaxBindingsPerPipelineLayoutTyped); } BindGroupLayoutBase::BindGroupLayoutBase(DeviceBase* device, ObjectBase::ErrorTag tag) : CachedObject(device, tag) { } BindGroupLayoutBase::~BindGroupLayoutBase() { // Do not uncache the actual cached object if we are a blueprint if (IsCachedReference()) { GetDevice()->UncacheBindGroupLayout(this); } } // static BindGroupLayoutBase* BindGroupLayoutBase::MakeError(DeviceBase* device) { return new BindGroupLayoutBase(device, ObjectBase::kError); } const BindGroupLayoutBase::BindingMap& BindGroupLayoutBase::GetBindingMap() const { ASSERT(!IsError()); return mBindingMap; } BindingIndex BindGroupLayoutBase::GetBindingIndex(BindingNumber bindingNumber) const { ASSERT(!IsError()); const auto& it = mBindingMap.find(bindingNumber); ASSERT(it != mBindingMap.end()); return it->second; } size_t BindGroupLayoutBase::HashFunc::operator()(const BindGroupLayoutBase* bgl) const { size_t hash = 0; // std::map is sorted by key, so two BGLs constructed in different orders // will still hash the same. for (const auto& it : bgl->mBindingMap) { HashCombine(&hash, it.first, it.second); HashCombineBindingInfo(&hash, bgl->mBindingInfo[it.second]); } return hash; } bool BindGroupLayoutBase::EqualityFunc::operator()(const BindGroupLayoutBase* a, const BindGroupLayoutBase* b) const { if (a->GetBindingCount() != b->GetBindingCount()) { return false; } for (BindingIndex i{0}; i < a->GetBindingCount(); ++i) { if (a->mBindingInfo[i] != b->mBindingInfo[i]) { return false; } } return a->mBindingMap == b->mBindingMap; } BindingIndex BindGroupLayoutBase::GetBindingCount() const { return mBindingInfo.size(); } BindingIndex BindGroupLayoutBase::GetBufferCount() const { return BindingIndex(mBindingCounts.bufferCount); } BindingIndex BindGroupLayoutBase::GetDynamicBufferCount() const { // This is a binding index because dynamic buffers are packed at the front of the binding // info. return static_cast<BindingIndex>(mBindingCounts.dynamicStorageBufferCount + mBindingCounts.dynamicUniformBufferCount); } uint32_t BindGroupLayoutBase::GetUnverifiedBufferCount() const { return mBindingCounts.unverifiedBufferCount; } const BindingCounts& BindGroupLayoutBase::GetBindingCountInfo() const { return mBindingCounts; } size_t BindGroupLayoutBase::GetBindingDataSize() const { // | ------ buffer-specific ----------| ------------ object pointers -------------| // | --- offsets + sizes -------------| --------------- Ref<ObjectBase> ----------| // Followed by: // |---------buffer size array--------| // |-uint64_t[mUnverifiedBufferCount]-| size_t objectPointerStart = mBindingCounts.bufferCount * sizeof(BufferBindingData); ASSERT(IsAligned(objectPointerStart, alignof(Ref<ObjectBase>))); size_t bufferSizeArrayStart = Align(objectPointerStart + mBindingCounts.totalCount * sizeof(Ref<ObjectBase>), sizeof(uint64_t)); ASSERT(IsAligned(bufferSizeArrayStart, alignof(uint64_t))); return bufferSizeArrayStart + mBindingCounts.unverifiedBufferCount * sizeof(uint64_t); } BindGroupLayoutBase::BindingDataPointers BindGroupLayoutBase::ComputeBindingDataPointers( void* dataStart) const { BufferBindingData* bufferData = reinterpret_cast<BufferBindingData*>(dataStart); auto bindings = reinterpret_cast<Ref<ObjectBase>*>(bufferData + mBindingCounts.bufferCount); uint64_t* unverifiedBufferSizes = AlignPtr( reinterpret_cast<uint64_t*>(bindings + mBindingCounts.totalCount), sizeof(uint64_t)); ASSERT(IsPtrAligned(bufferData, alignof(BufferBindingData))); ASSERT(IsPtrAligned(bindings, alignof(Ref<ObjectBase>))); ASSERT(IsPtrAligned(unverifiedBufferSizes, alignof(uint64_t))); return {{bufferData, GetBufferCount()}, {bindings, GetBindingCount()}, {unverifiedBufferSizes, mBindingCounts.unverifiedBufferCount}}; } } // namespace dawn_native
10,376
5,169
<filename>Specs/7/1/0/JSCoreBridge/0.1.1/JSCoreBridge.podspec.json { "name": "JSCoreBridge", "version": "0.1.1", "summary": "A hybird development framework on iOS platform.", "description": "A hybird development framework modified from Apache Cordova.", "documentation_url": "https://github.com/iPhuan/JSCoreBridge", "homepage": "https://github.com/iPhuan/JSCoreBridge.git", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "iPhuan": "<EMAIL>" }, "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/iPhuan/JSCoreBridge.git", "tag": "0.1.1" }, "requires_arc": true, "subspecs": [ { "name": "Optional", "source_files": "JSCoreBridge/Optional/**/*.{h,m}", "preserve_paths": "JSCoreBridge/Optional/config.xml", "requires_arc": true, "dependencies": { "JSCoreBridge/JSCoreBridgeLite": [ ] } }, { "name": "JSCoreBridgeLite", "source_files": "JSCoreBridge/JSCoreBridgeLite/**/*.{h,m}", "resources": "JSCoreBridge/JSCoreBridgeLite/JS/jscorebridge.js", "requires_arc": true, "frameworks": [ "Foundation", "UIKit", "JavaScriptCore" ] } ] }
576
302
#ifndef MAINHANDLER_H #define MAINHANDLER_H #include "include/cef_client.h" #include "include/cef_urlrequest.h" #include "browserdata.h" #include <functional> #include "curlresourcehandler.h" #include <atomic> #include "settings.h" #include "log.h" #include "refcountpublic.h" #include "handlersmanager.h" #include "postmanager.h" class HandlersManager; class MainHandler : public CefClient, public CefDownloadHandler, public CefDisplayHandler, public CefLifeSpanHandler, public CefLoadHandler, public CefRequestHandler, public CefDialogHandler, public CefKeyboardHandler, public CefRenderHandler, public CefJSDialogHandler { bool NeedQuit; bool WaitForLoadEvent; bool IsPopup; CefRefPtr<CefBrowser> Browser; bool IsVisible; BrowserData * Data; PostManager * _PostManager; settings * Settings; int GetBrowserId(); CefRefPtr<CefJSDialogCallback> ConfirmResult; long long ConfirmResultTime; bool ConfirmResultWait; HandlersManager *_HandlersManager = 0; public: MainHandler(); bool GetIsVisible(); void SetData(BrowserData *Data); void SetPostManager(PostManager *_PostManager); void SetSettings(settings *Settings); void SetIsPopup(); bool GetIsPopup(); void SetHandlersManager(HandlersManager *_HandlersManager); virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() OVERRIDE; virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE; virtual CefRefPtr<CefLoadHandler> GetLoadHandler() OVERRIDE; virtual CefRefPtr<CefRequestHandler> GetRequestHandler() OVERRIDE; virtual CefRefPtr<CefDialogHandler> GetDialogHandler() OVERRIDE; virtual CefRefPtr<CefKeyboardHandler> GetKeyboardHandler() OVERRIDE; virtual CefRefPtr<CefRenderHandler> GetRenderHandler() OVERRIDE; virtual CefRefPtr<CefJSDialogHandler> GetJSDialogHandler() OVERRIDE; virtual CefRefPtr<CefDownloadHandler> GetDownloadHandler() OVERRIDE; //CefDownloadHandler virtual void OnBeforeDownload(CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item, const CefString& suggested_name, CefRefPtr<CefBeforeDownloadCallback> callback) OVERRIDE; virtual void OnDownloadUpdated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item, CefRefPtr<CefDownloadItemCallback> callback) OVERRIDE; // CefJSDialogHandler methods: virtual bool OnJSDialog(CefRefPtr<CefBrowser> browser, const CefString& origin_url, JSDialogType dialog_type, const CefString& message_text, const CefString& default_prompt_text, CefRefPtr<CefJSDialogCallback> callback, bool& suppress_message) OVERRIDE; virtual bool OnBeforeUnloadDialog(CefRefPtr<CefBrowser> browser,const CefString& message_text, bool is_reload, CefRefPtr<CefJSDialogCallback> callback) OVERRIDE; // CefKeyboardHandler methods: virtual bool OnKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event) OVERRIDE; // CefDisplayHandler methods: virtual void OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title) OVERRIDE; // CefLifeSpanHandler methods: virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE; virtual bool DoClose(CefRefPtr<CefBrowser> browser) OVERRIDE; virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE; virtual bool OnBeforePopup(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& target_url, const CefString& target_frame_name, CefLifeSpanHandler::WindowOpenDisposition target_disposition, bool user_gesture, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, CefRefPtr<CefClient>& client, CefBrowserSettings& settings, bool* no_javascript_access) OVERRIDE; // CefLoadHandler methods: virtual void OnLoadError(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, ErrorCode errorCode, const CefString& errorText, const CefString& failedUrl) OVERRIDE; virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) OVERRIDE; //virtual void OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) OVERRIDE; // CefRequestHandler methods: virtual ReturnValue OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, CefRefPtr<CefRequestCallback> callback) OVERRIDE; virtual void OnResourceLoadComplete(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, CefRefPtr<CefResponse> response, CefRequestHandler::URLRequestStatus status, int64 received_content_length) OVERRIDE; virtual CefRefPtr<CefResourceHandler> GetResourceHandler(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request) OVERRIDE; virtual bool GetAuthCredentials(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, bool isProxy, const CefString& host, int port, const CefString& realm, const CefString& scheme, CefRefPtr<CefAuthCallback> callback) OVERRIDE; virtual bool OnCertificateError(CefRefPtr<CefBrowser> browser,cef_errorcode_t cert_error,const CefString& request_url,CefRefPtr<CefSSLInfo> ssl_info,CefRefPtr<CefRequestCallback> callback) OVERRIDE; //CefDialogHandler virtual bool OnFileDialog(CefRefPtr<CefBrowser> browser, FileDialogMode mode, const CefString& title, const CefString& default_file_path, const std::vector<CefString>& accept_filters, int selected_accept_filter, CefRefPtr<CefFileDialogCallback> callback) OVERRIDE; //CefRenderHandler virtual bool GetViewRect(CefRefPtr<CefBrowser> browser, CefRect& rect) OVERRIDE; virtual void OnPaint(CefRefPtr<CefBrowser> browser, PaintElementType type, const RectList& dirtyRects, const void* buffer, int width, int height) OVERRIDE; virtual void OnScrollOffsetChanged(CefRefPtr<CefBrowser> browser,double x,double y) OVERRIDE; virtual bool StartDragging(CefRefPtr<CefBrowser> browser,CefRefPtr<CefDragData> drag_data,DragOperationsMask allowed_ops,int x, int y) OVERRIDE; bool IsNeedQuit(); void Hide(); void Show(); void Timer(); void CloseLastBrowser(); void CleanResourceHandlerList(); int GetResourceListLength(); //Events std::vector<std::function<void(const std::string&, int)> > EventSendTextResponce; std::vector<std::function<void(const std::string&, int, int)> > EventUrlLoaded; std::vector<std::function<void(int)> > EventLoadSuccess; std::vector<std::function<void(char*,int,int,int)> > EventPaint; std::vector<std::function<void(CefRefPtr<MainHandler>,CefRefPtr<CefBrowser>)> > EventPopupCreated; std::vector<std::function<void(int)> > EventPopupClosed; std::vector<std::function<void(int64,int)> > EventOldestRequestTimeChanged; std::vector<CefRefPtr<CurlResourceHandler> > EventOnTimerCurlResources; std::atomic_int CurlResourcesLength; private: void SendTextResponce(const std::string&); private: IMPLEMENT_REFCOUNTING_NONE(); }; #endif // MAINHANDLER_H
2,393
347
<filename>backend/manager/modules/common/src/test/java/org/ovirt/engine/core/common/utils/ConfiguredRangeValidatorTest.java package org.ovirt.engine.core.common.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigCommon; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.config.IConfigUtilsInterface; import org.ovirt.engine.core.common.validation.annotation.ConfiguredRange; public class ConfiguredRangeValidatorTest { private static final int TEST_DEFAULT_MIN_RANGE = 0; private static final int TEST_MIN_RANGE = 5; private static final int TEST_MAX_RANGE = 100; private static final int TEST_IN_RANGE = TEST_MAX_RANGE; private static final int TEST_OUT_OF_UPPER_RANGE = TEST_MAX_RANGE + 1; private static final int TEST_OUT_OF_LOWER_RANGE = TEST_MIN_RANGE - 1; private Validator validator; @AfterEach public void tearDown() { Config.setConfigUtils(null); } @Test public void valueOutOfUpperRange() { initConfiguredRange(); validateAndAssertResult(new ConfiguredRangeContainer(TEST_OUT_OF_UPPER_RANGE), false); } @Test public void valueOutOfDefaultLowerRange() { initConfiguredWithDefaultMinValue(); validateAndAssertResult(new ConfiguredRangeContainerDefaultMin(TEST_DEFAULT_MIN_RANGE - 1), false); } @Test public void valueOutOfLowerRange() { initConfiguredWithDefaultMinValue(); validateAndAssertResult(new ConfiguredRangeContainer(TEST_OUT_OF_LOWER_RANGE), false); } @Test public void valueOutOfConfiguredLowerRange() { initConfiguredWithDefaultMinValue(); validateAndAssertResult(new ConfiguredRangeContainerWithConfMin(TEST_MIN_RANGE - 1), false); } @Test public void valueInConfiguredLowerRange() { initConfiguredWithDefaultMinValue(); validateAndAssertResult(new ConfiguredRangeContainerWithConfMin(TEST_MIN_RANGE), true); } @Test public void valueInRange() { initConfiguredRange(); validateAndAssertResult(new ConfiguredRangeContainer(TEST_IN_RANGE), true); } /** * The test assures the precedence of the configuration value over the min attribute of the annotated value. * * The minimum defined by <code>minConfigValue</code> is <code>TEST_MIN_RANGE</code>.<br/> * The minimum defined by <code>min()</code> is <code>TEST_MIN_RANGE + 2</code>.<br/> * The test verifies the valid values are greater then the min value obtained from <code>minConfigValue</code><br/> */ @Test public void valueLowerLimitSetByConfigValue() { initConfiguredWithDefaultMinValue(); validateAndAssertResult(new ConfiguredRangeContainerWithBothMinAttributes(TEST_MIN_RANGE + 1), true); validateAndAssertResult(new ConfiguredRangeContainerWithBothMinAttributes(TEST_MIN_RANGE - 1), false); } private <T> void validateAndAssertResult(T container, boolean isValid) { Set<ConstraintViolation<T>> validate = validator.validate(container); assertEquals(isValid, validate.isEmpty()); } public void initConfiguredRange() { IConfigUtilsInterface configUtils = initConfigUtils(); Config.setConfigUtils(configUtils); } public void initConfiguredWithDefaultMinValue() { IConfigUtilsInterface configUtils = initConfigUtils(); when(configUtils.getValue(ConfigValues.ConnectToServerTimeoutInSeconds, ConfigCommon.defaultConfigurationVersion)).thenReturn(TEST_MIN_RANGE); Config.setConfigUtils(configUtils); } private IConfigUtilsInterface initConfigUtils() { validator = ValidationUtils.getValidator(); IConfigUtilsInterface configUtils = mock(IConfigUtilsInterface.class); when(configUtils.getValue(ConfigValues.vdsTimeout, ConfigCommon.defaultConfigurationVersion)).thenReturn(TEST_MAX_RANGE); return configUtils; } private static class ConfiguredRangeContainer { @ConfiguredRange(min = TEST_MIN_RANGE, maxConfigValue = ConfigValues.vdsTimeout) private int value; public ConfiguredRangeContainer(int value) { this.value = value; } } private static class ConfiguredRangeContainerDefaultMin { @ConfiguredRange(maxConfigValue = ConfigValues.vdsTimeout) private int value; public ConfiguredRangeContainerDefaultMin(int value) { this.value = value; } } private static class ConfiguredRangeContainerWithConfMin { @ConfiguredRange(minConfigValue = ConfigValues.ConnectToServerTimeoutInSeconds, maxConfigValue = ConfigValues.vdsTimeout) private int value; public ConfiguredRangeContainerWithConfMin(int value) { this.value = value; } } private static class ConfiguredRangeContainerWithBothMinAttributes { @ConfiguredRange(min = TEST_MIN_RANGE + 2, minConfigValue = ConfigValues.ConnectToServerTimeoutInSeconds, maxConfigValue = ConfigValues.vdsTimeout) private int value; public ConfiguredRangeContainerWithBothMinAttributes(int value) { this.value = value; } } }
2,030
7,407
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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 2 of the License, or (at your option) any later version. Quake III Arena source code 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 Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // /***************************************************************************** * name: ai_vcmd.c * * desc: Quake3 bot AI * * $Archive: /MissionPack/code/game/ai_vcmd.c $ * *****************************************************************************/ #include "g_local.h" #include "../botlib/botlib.h" #include "../botlib/be_aas.h" #include "../botlib/be_ea.h" #include "../botlib/be_ai_char.h" #include "../botlib/be_ai_chat.h" #include "../botlib/be_ai_gen.h" #include "../botlib/be_ai_goal.h" #include "../botlib/be_ai_move.h" #include "../botlib/be_ai_weap.h" // #include "ai_main.h" #include "ai_dmq3.h" #include "ai_chat.h" #include "ai_cmd.h" #include "ai_dmnet.h" #include "ai_team.h" #include "ai_vcmd.h" // #include "chars.h" //characteristics #include "inv.h" //indexes into the inventory #include "syn.h" //synonyms #include "match.h" //string matching types and vars // for the voice chats #include "../../ui/menudef.h" typedef struct voiceCommand_s { char *cmd; void (*func)(bot_state_t *bs, int client, int mode); } voiceCommand_t; /* ================== BotVoiceChat_GetFlag ================== */ void BotVoiceChat_GetFlag(bot_state_t *bs, int client, int mode) { // if (gametype == GT_CTF) { if (!ctf_redflag.areanum || !ctf_blueflag.areanum) return; } #ifdef MISSIONPACK else if (gametype == GT_1FCTF) { if (!ctf_neutralflag.areanum || !ctf_redflag.areanum || !ctf_blueflag.areanum) return; } #endif else { return; } // bs->decisionmaker = client; bs->ordered = qtrue; bs->order_time = FloatTime(); //set the time to send a message to the team mates bs->teammessage_time = FloatTime() + 2 * random(); //set the ltg type bs->ltgtype = LTG_GETFLAG; //set the team goal time bs->teamgoal_time = FloatTime() + CTF_GETFLAG_TIME; // get an alternate route in ctf if (gametype == GT_CTF) { //get an alternative route goal towards the enemy base BotGetAlternateRouteGoal(bs, BotOppositeTeam(bs)); } // BotSetTeamStatus(bs); // remember last ordered task BotRememberLastOrderedTask(bs); #ifdef DEBUG BotPrintTeamGoal(bs); #endif //DEBUG } /* ================== BotVoiceChat_Offense ================== */ void BotVoiceChat_Offense(bot_state_t *bs, int client, int mode) { if ( gametype == GT_CTF #ifdef MISSIONPACK || gametype == GT_1FCTF #endif ) { BotVoiceChat_GetFlag(bs, client, mode); return; } #ifdef MISSIONPACK if (gametype == GT_HARVESTER) { // bs->decisionmaker = client; bs->ordered = qtrue; bs->order_time = FloatTime(); //set the time to send a message to the team mates bs->teammessage_time = FloatTime() + 2 * random(); //set the ltg type bs->ltgtype = LTG_HARVEST; //set the team goal time bs->teamgoal_time = FloatTime() + TEAM_HARVEST_TIME; bs->harvestaway_time = 0; // BotSetTeamStatus(bs); // remember last ordered task BotRememberLastOrderedTask(bs); } else #endif { // bs->decisionmaker = client; bs->ordered = qtrue; bs->order_time = FloatTime(); //set the time to send a message to the team mates bs->teammessage_time = FloatTime() + 2 * random(); //set the ltg type bs->ltgtype = LTG_ATTACKENEMYBASE; //set the team goal time bs->teamgoal_time = FloatTime() + TEAM_ATTACKENEMYBASE_TIME; bs->attackaway_time = 0; // BotSetTeamStatus(bs); // remember last ordered task BotRememberLastOrderedTask(bs); } #ifdef DEBUG BotPrintTeamGoal(bs); #endif //DEBUG } /* ================== BotVoiceChat_Defend ================== */ void BotVoiceChat_Defend(bot_state_t *bs, int client, int mode) { #ifdef MISSIONPACK if ( gametype == GT_OBELISK || gametype == GT_HARVESTER) { // switch(BotTeam(bs)) { case TEAM_RED: memcpy(&bs->teamgoal, &redobelisk, sizeof(bot_goal_t)); break; case TEAM_BLUE: memcpy(&bs->teamgoal, &blueobelisk, sizeof(bot_goal_t)); break; default: return; } } else #endif if (gametype == GT_CTF #ifdef MISSIONPACK || gametype == GT_1FCTF #endif ) { // switch(BotTeam(bs)) { case TEAM_RED: memcpy(&bs->teamgoal, &ctf_redflag, sizeof(bot_goal_t)); break; case TEAM_BLUE: memcpy(&bs->teamgoal, &ctf_blueflag, sizeof(bot_goal_t)); break; default: return; } } else { return; } // bs->decisionmaker = client; bs->ordered = qtrue; bs->order_time = FloatTime(); //set the time to send a message to the team mates bs->teammessage_time = FloatTime() + 2 * random(); //set the ltg type bs->ltgtype = LTG_DEFENDKEYAREA; //get the team goal time bs->teamgoal_time = FloatTime() + TEAM_DEFENDKEYAREA_TIME; //away from defending bs->defendaway_time = 0; // BotSetTeamStatus(bs); // remember last ordered task BotRememberLastOrderedTask(bs); #ifdef DEBUG BotPrintTeamGoal(bs); #endif //DEBUG } /* ================== BotVoiceChat_DefendFlag ================== */ void BotVoiceChat_DefendFlag(bot_state_t *bs, int client, int mode) { BotVoiceChat_Defend(bs, client, mode); } /* ================== BotVoiceChat_Patrol ================== */ void BotVoiceChat_Patrol(bot_state_t *bs, int client, int mode) { // bs->decisionmaker = client; // bs->ltgtype = 0; bs->lead_time = 0; bs->lastgoal_ltgtype = 0; // BotAI_BotInitialChat(bs, "dismissed", NULL); trap_BotEnterChat(bs->cs, client, CHAT_TELL); BotVoiceChatOnly(bs, -1, VOICECHAT_ONPATROL); // BotSetTeamStatus(bs); #ifdef DEBUG BotPrintTeamGoal(bs); #endif //DEBUG } /* ================== BotVoiceChat_Camp ================== */ void BotVoiceChat_Camp(bot_state_t *bs, int client, int mode) { int areanum; aas_entityinfo_t entinfo; char netname[MAX_NETNAME]; // bs->teamgoal.entitynum = -1; BotEntityInfo(client, &entinfo); //if info is valid (in PVS) if (entinfo.valid) { areanum = BotPointAreaNum(entinfo.origin); if (areanum) { // && trap_AAS_AreaReachability(areanum)) { //NOTE: just assume the bot knows where the person is //if (BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, client)) { bs->teamgoal.entitynum = client; bs->teamgoal.areanum = areanum; VectorCopy(entinfo.origin, bs->teamgoal.origin); VectorSet(bs->teamgoal.mins, -8, -8, -8); VectorSet(bs->teamgoal.maxs, 8, 8, 8); //} } } //if the other is not visible if (bs->teamgoal.entitynum < 0) { BotAI_BotInitialChat(bs, "whereareyou", EasyClientName(client, netname, sizeof(netname)), NULL); trap_BotEnterChat(bs->cs, client, CHAT_TELL); return; } // bs->decisionmaker = client; bs->ordered = qtrue; bs->order_time = FloatTime(); //set the time to send a message to the team mates bs->teammessage_time = FloatTime() + 2 * random(); //set the ltg type bs->ltgtype = LTG_CAMPORDER; //get the team goal time bs->teamgoal_time = FloatTime() + TEAM_CAMP_TIME; //the teammate that requested the camping bs->teammate = client; //not arrived yet bs->arrive_time = 0; // BotSetTeamStatus(bs); // remember last ordered task BotRememberLastOrderedTask(bs); #ifdef DEBUG BotPrintTeamGoal(bs); #endif //DEBUG } /* ================== BotVoiceChat_FollowMe ================== */ void BotVoiceChat_FollowMe(bot_state_t *bs, int client, int mode) { int areanum; aas_entityinfo_t entinfo; char netname[MAX_NETNAME]; bs->teamgoal.entitynum = -1; BotEntityInfo(client, &entinfo); //if info is valid (in PVS) if (entinfo.valid) { areanum = BotPointAreaNum(entinfo.origin); if (areanum) { // && trap_AAS_AreaReachability(areanum)) { bs->teamgoal.entitynum = client; bs->teamgoal.areanum = areanum; VectorCopy(entinfo.origin, bs->teamgoal.origin); VectorSet(bs->teamgoal.mins, -8, -8, -8); VectorSet(bs->teamgoal.maxs, 8, 8, 8); } } //if the other is not visible if (bs->teamgoal.entitynum < 0) { BotAI_BotInitialChat(bs, "whereareyou", EasyClientName(client, netname, sizeof(netname)), NULL); trap_BotEnterChat(bs->cs, client, CHAT_TELL); return; } // bs->decisionmaker = client; bs->ordered = qtrue; bs->order_time = FloatTime(); //the team mate bs->teammate = client; //last time the team mate was assumed visible bs->teammatevisible_time = FloatTime(); //set the time to send a message to the team mates bs->teammessage_time = FloatTime() + 2 * random(); //get the team goal time bs->teamgoal_time = FloatTime() + TEAM_ACCOMPANY_TIME; //set the ltg type bs->ltgtype = LTG_TEAMACCOMPANY; bs->formation_dist = 3.5 * 32; //3.5 meter bs->arrive_time = 0; // BotSetTeamStatus(bs); // remember last ordered task BotRememberLastOrderedTask(bs); #ifdef DEBUG BotPrintTeamGoal(bs); #endif //DEBUG } /* ================== BotVoiceChat_FollowFlagCarrier ================== */ void BotVoiceChat_FollowFlagCarrier(bot_state_t *bs, int client, int mode) { int carrier; carrier = BotTeamFlagCarrier(bs); if (carrier >= 0) BotVoiceChat_FollowMe(bs, carrier, mode); #ifdef DEBUG BotPrintTeamGoal(bs); #endif //DEBUG } /* ================== BotVoiceChat_ReturnFlag ================== */ void BotVoiceChat_ReturnFlag(bot_state_t *bs, int client, int mode) { //if not in CTF mode if ( gametype != GT_CTF #ifdef MISSIONPACK && gametype != GT_1FCTF #endif ) { return; } // bs->decisionmaker = client; bs->ordered = qtrue; bs->order_time = FloatTime(); //set the time to send a message to the team mates bs->teammessage_time = FloatTime() + 2 * random(); //set the ltg type bs->ltgtype = LTG_RETURNFLAG; //set the team goal time bs->teamgoal_time = FloatTime() + CTF_RETURNFLAG_TIME; bs->rushbaseaway_time = 0; BotSetTeamStatus(bs); #ifdef DEBUG BotPrintTeamGoal(bs); #endif //DEBUG } /* ================== BotVoiceChat_StartLeader ================== */ void BotVoiceChat_StartLeader(bot_state_t *bs, int client, int mode) { ClientName(client, bs->teamleader, sizeof(bs->teamleader)); } /* ================== BotVoiceChat_StopLeader ================== */ void BotVoiceChat_StopLeader(bot_state_t *bs, int client, int mode) { char netname[MAX_MESSAGE_SIZE]; if (!Q_stricmp(bs->teamleader, ClientName(client, netname, sizeof(netname)))) { bs->teamleader[0] = '\0'; notleader[client] = qtrue; } } /* ================== BotVoiceChat_WhoIsLeader ================== */ void BotVoiceChat_WhoIsLeader(bot_state_t *bs, int client, int mode) { char netname[MAX_MESSAGE_SIZE]; if (!TeamPlayIsOn()) return; ClientName(bs->client, netname, sizeof(netname)); //if this bot IS the team leader if (!Q_stricmp(netname, bs->teamleader)) { BotAI_BotInitialChat(bs, "iamteamleader", NULL); trap_BotEnterChat(bs->cs, 0, CHAT_TEAM); BotVoiceChatOnly(bs, -1, VOICECHAT_STARTLEADER); } } /* ================== BotVoiceChat_WantOnDefense ================== */ void BotVoiceChat_WantOnDefense(bot_state_t *bs, int client, int mode) { char netname[MAX_NETNAME]; int preference; preference = BotGetTeamMateTaskPreference(bs, client); preference &= ~TEAMTP_ATTACKER; preference |= TEAMTP_DEFENDER; BotSetTeamMateTaskPreference(bs, client, preference); // EasyClientName(client, netname, sizeof(netname)); BotAI_BotInitialChat(bs, "keepinmind", netname, NULL); trap_BotEnterChat(bs->cs, client, CHAT_TELL); BotVoiceChatOnly(bs, client, VOICECHAT_YES); trap_EA_Action(bs->client, ACTION_AFFIRMATIVE); } /* ================== BotVoiceChat_WantOnOffense ================== */ void BotVoiceChat_WantOnOffense(bot_state_t *bs, int client, int mode) { char netname[MAX_NETNAME]; int preference; preference = BotGetTeamMateTaskPreference(bs, client); preference &= ~TEAMTP_DEFENDER; preference |= TEAMTP_ATTACKER; BotSetTeamMateTaskPreference(bs, client, preference); // EasyClientName(client, netname, sizeof(netname)); BotAI_BotInitialChat(bs, "keepinmind", netname, NULL); trap_BotEnterChat(bs->cs, client, CHAT_TELL); BotVoiceChatOnly(bs, client, VOICECHAT_YES); trap_EA_Action(bs->client, ACTION_AFFIRMATIVE); } void BotVoiceChat_Dummy(bot_state_t *bs, int client, int mode) { } voiceCommand_t voiceCommands[] = { {VOICECHAT_GETFLAG, BotVoiceChat_GetFlag}, {VOICECHAT_OFFENSE, BotVoiceChat_Offense }, {VOICECHAT_DEFEND, BotVoiceChat_Defend }, {VOICECHAT_DEFENDFLAG, BotVoiceChat_DefendFlag }, {VOICECHAT_PATROL, BotVoiceChat_Patrol }, {VOICECHAT_CAMP, BotVoiceChat_Camp }, {VOICECHAT_FOLLOWME, BotVoiceChat_FollowMe }, {VOICECHAT_FOLLOWFLAGCARRIER, BotVoiceChat_FollowFlagCarrier }, {VOICECHAT_RETURNFLAG, BotVoiceChat_ReturnFlag }, {VOICECHAT_STARTLEADER, BotVoiceChat_StartLeader }, {VOICECHAT_STOPLEADER, BotVoiceChat_StopLeader }, {VOICECHAT_WHOISLEADER, BotVoiceChat_WhoIsLeader }, {VOICECHAT_WANTONDEFENSE, BotVoiceChat_WantOnDefense }, {VOICECHAT_WANTONOFFENSE, BotVoiceChat_WantOnOffense }, {NULL, BotVoiceChat_Dummy} }; int BotVoiceChatCommand(bot_state_t *bs, int mode, char *voiceChat) { int i, clientNum; //int voiceOnly, color; char *ptr, buf[MAX_MESSAGE_SIZE], *cmd; if (!TeamPlayIsOn()) { return qfalse; } if ( mode == SAY_ALL ) { return qfalse; // don't do anything with voice chats to everyone } Q_strncpyz(buf, voiceChat, sizeof(buf)); cmd = buf; for (; *cmd && *cmd > ' '; cmd++); while (*cmd && *cmd <= ' ') *cmd++ = '\0'; //voiceOnly = atoi(ptr); for (ptr = cmd; *cmd && *cmd > ' '; cmd++); while (*cmd && *cmd <= ' ') *cmd++ = '\0'; clientNum = atoi(ptr); for (; *cmd && *cmd > ' '; cmd++); while (*cmd && *cmd <= ' ') *cmd++ = '\0'; //color = atoi(ptr); if (!BotSameTeam(bs, clientNum)) { return qfalse; } for (i = 0; voiceCommands[i].cmd; i++) { if (!Q_stricmp(cmd, voiceCommands[i].cmd)) { voiceCommands[i].func(bs, clientNum, mode); return qtrue; } } return qfalse; }
5,481
607
<filename>lib/include/timer/AdvancedControlTimer.h /* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013,2014 <NAME> <www.andybrown.me.uk> * Please see website for licensing terms. */ #pragma once namespace stm32plus { /** * Advanced control timers are TIM1, TIM8 * @tparam TTimer The timer class type (Timer1, Timer2...) * @tparam TPeripheralName the peripheral class for the clocks */ template<class TTimer,PeripheralName TPeripheralName> class AdvancedControlTimer : public TimerPeripheral<TTimer,TPeripheralName> { protected: AdvancedControlTimer(TIM_TypeDef *peripheralAddress); public: void initialiseTimeBaseWithRepeat(uint16_t period,uint16_t prescaler,uint16_t clockDivision,uint16_t counterMode,uint8_t repeatCount); void setTimeBaseByFrequencyWithRepeat(uint32_t frequency,uint16_t arr,uint16_t counterMode,uint8_t repeatCount); }; /** * Constructor */ template<class TTimer,PeripheralName TPeripheralName> inline AdvancedControlTimer<TTimer,TPeripheralName>::AdvancedControlTimer(TIM_TypeDef *peripheralAddress) : TimerPeripheral<TTimer,TPeripheralName>(peripheralAddress) { } /** * Initialise the time base for this timer * @param period Configures the period value to be loaded into the active Auto-Reload Register at the next update event. * @param prescaler Configures the prescaler value used to divide the TIM clock. * @param clockDivision TIM_CKD_DIV1/2/4 * @param counterMode TIM_CounterMode_Up/Down * @param repeatCount The number of times that a counter must repeat its end-to-end cycle before generating Update. */ template<class TTimer,PeripheralName TPeripheralName> inline void AdvancedControlTimer<TTimer,TPeripheralName>::initialiseTimeBaseWithRepeat(uint16_t period,uint16_t prescaler,uint16_t clockDivision,uint16_t counterMode,uint8_t repeatCount) { // repeat count is unique to the advanced control timers. Set the value and call the // base to complete the init. this->_timeBase.TIM_RepetitionCounter=repeatCount; Timer::initialiseTimeBase(period,prescaler,clockDivision,counterMode); } /** * Convenience function to set the timer clock (TIMxCLK) to the desired frequency. The counter will * be an up counter (by default) with a period equal to the arr (auto-reload) value. The lowest * frequency that can be set is TIMxCLK / 65536. For a 72Mhz core clock this is 1098 Hz. * @param frequency The frequency in Hz. * @param arr The auto reload value (0..65535). The timer counter reverses/resets at this value. * @param counterMode TIM_CounterMode_* value * @param repeatCount The number of times that a counter must repeat its end-to-end cycle before generating Update. */ template<class TTimer,PeripheralName TPeripheralName> inline void AdvancedControlTimer<TTimer,TPeripheralName>::setTimeBaseByFrequencyWithRepeat(uint32_t frequency,uint16_t arr,uint16_t counterMode,uint8_t repeatCount) { this->_timeBase.TIM_RepetitionCounter=repeatCount; Timer::initialiseTimeBase(arr,(this->_clock/frequency)-1,0,counterMode); } }
1,012
499
package net.ttddyy.dsproxy; import net.ttddyy.dsproxy.listener.NoOpQueryExecutionListener; import net.ttddyy.dsproxy.listener.QueryExecutionListener; import net.ttddyy.dsproxy.proxy.JdbcProxyFactory; import net.ttddyy.dsproxy.proxy.ProxyConfig; import net.ttddyy.dsproxy.proxy.SimpleResultSetProxyLogicFactory; import net.ttddyy.dsproxy.proxy.jdk.JdkJdbcProxyFactory; import net.ttddyy.dsproxy.proxy.jdk.ResultSetInvocationHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.sql.DataSource; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** * @author <NAME> */ public class StatementQueryTest { private DataSource jdbcDataSource; @Before public void setup() throws Exception { // real datasource jdbcDataSource = TestUtils.getDataSourceWithData(); } @After public void teardown() throws Exception { TestUtils.shutdown(jdbcDataSource); } @Test public void resultSetProxy() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); ProxyConfig proxyConfig = ProxyConfig.Builder.create().resultSetProxyLogicFactory(new SimpleResultSetProxyLogicFactory()).build(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); // verify executeQuery ResultSet result = proxySt.executeQuery("select * from emp;"); assertThat(result).isInstanceOf(ResultSet.class); assertThat(Proxy.isProxyClass(result.getClass())).isTrue(); assertThat(Proxy.getInvocationHandler(result)).isExactlyInstanceOf(ResultSetInvocationHandler.class); // verify getResultSet proxySt.execute("select * from emp;"); result = proxySt.getResultSet(); assertThat(result).isInstanceOf(ResultSet.class); assertThat(Proxy.isProxyClass(result.getClass())).isTrue(); assertThat(Proxy.getInvocationHandler(result)).isExactlyInstanceOf(ResultSetInvocationHandler.class); // verify getGeneratedKeys // generatedKeys have own proxy factory, thus expecting non-proxy to be returned result = proxySt.getGeneratedKeys(); assertThat(result).isInstanceOf(ResultSet.class); assertThat(Proxy.isProxyClass(result.getClass())).isFalse(); } @Test public void generatedKeysProxy() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); ProxyConfig proxyConfig = ProxyConfig.Builder.create().generatedKeysProxyLogicFactory(new SimpleResultSetProxyLogicFactory()).build(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); // verify getGeneratedKeys ResultSet generatedKeys = proxySt.getGeneratedKeys(); assertThat(generatedKeys).isInstanceOf(ResultSet.class); assertThat(Proxy.isProxyClass(generatedKeys.getClass())).isTrue(); assertThat(Proxy.getInvocationHandler(generatedKeys)).isExactlyInstanceOf(ResultSetInvocationHandler.class); // other ResultSet returning methods should not return proxy // verify executeQuery ResultSet result = proxySt.executeQuery("select * from emp;"); assertThat(result).isInstanceOf(ResultSet.class); assertThat(Proxy.isProxyClass(result.getClass())).isFalse(); // generated keys should have empty proxied result set generatedKeys = proxySt.getGeneratedKeys(); assertThat(generatedKeys).isInstanceOf(ResultSet.class); assertThat(Proxy.isProxyClass(generatedKeys.getClass())).isTrue(); assertThat(generatedKeys.next()).isFalse(); // verify getResultSet proxySt.execute("select * from emp;"); result = proxySt.getResultSet(); assertThat(result).isInstanceOf(ResultSet.class); assertThat(Proxy.isProxyClass(result.getClass())).isFalse(); // generated keys should have empty proxied result set generatedKeys = proxySt.getGeneratedKeys(); assertThat(generatedKeys).isInstanceOf(ResultSet.class); assertThat(Proxy.isProxyClass(generatedKeys.getClass())).isTrue(); assertThat(generatedKeys.next()).isFalse(); } @Test public void autoRetrieveGeneratedKeys() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); final AtomicReference<ExecutionInfo> listenerReceivedExecutionInfo = new AtomicReference<ExecutionInfo>(); QueryExecutionListener listener = new NoOpQueryExecutionListener() { @Override public void afterQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { // since generatedKeys will NOT be closed, they can be read afterwards. listenerReceivedExecutionInfo.set(execInfo); } }; // autoRetrieveGeneratedKeys=true ProxyConfig proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(false) .build(); JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); ExecutionInfo info = listenerReceivedExecutionInfo.get(); assertThat(info).isNotNull(); ResultSet generatedKeys = info.getGeneratedKeys(); assertThat(generatedKeys).isInstanceOf(ResultSet.class); assertThat(Proxy.isProxyClass(generatedKeys.getClass())).isFalse(); // calling "statement.getGeneratedKeys()" should return the same object ResultSet directGeneratedKeys = proxySt.getGeneratedKeys(); assertThat(directGeneratedKeys).isSameAs(generatedKeys); // verify generated keys ResultSet generatedKeys.next(); int generatedId = generatedKeys.getInt(1); assertThat(generatedId).as("generated ID").isEqualTo(2); // reset listenerReceivedExecutionInfo.set(null); // autoRetrieveGeneratedKeys=false proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(false) .autoCloseGeneratedKeys(false) .build(); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); info = listenerReceivedExecutionInfo.get(); assertThat(info).isNotNull(); assertThat(info.getGeneratedKeys()).isNull(); } @Test public void autoRetrieveGeneratedKeysWithExecuteQueryMethod() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); final AtomicReference<ExecutionInfo> listenerReceivedExecutionInfo = new AtomicReference<ExecutionInfo>(); QueryExecutionListener listener = new NoOpQueryExecutionListener() { @Override public void afterQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { // since generatedKeys will NOT be closed, they can be read afterwards. listenerReceivedExecutionInfo.set(execInfo); } }; // autoRetrieveGeneratedKeys=true ProxyConfig proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(false) .build(); JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); // it should NOT generate keys for executeQuery method proxySt.executeQuery("insert into emp_with_auto_id ( name ) values ('BAZ');"); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNull(); } @Test public void autoRetrieveGeneratedKeysWithQueryExecutionMethods() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); final AtomicReference<ExecutionInfo> listenerReceivedExecutionInfo = new AtomicReference<ExecutionInfo>(); QueryExecutionListener listener = new NoOpQueryExecutionListener() { @Override public void afterQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { // since generatedKeys will NOT be closed, they can be read afterwards. listenerReceivedExecutionInfo.set(execInfo); } }; // autoRetrieveGeneratedKeys=true ProxyConfig proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(false) .build(); JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); // Test with NOT enabling generated-keys proxySt.execute("insert into emp_with_auto_id ( name ) values ('BAZ');"); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNull(); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');"); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNull(); // Statement#executeLargeUpdate is not implemented in HSQL yet // Specify NO_GENERATED_KEYS proxySt.execute("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.NO_GENERATED_KEYS); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNull(); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.NO_GENERATED_KEYS); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNull(); // Test with enabling generated-keys // with Statement.RETURN_GENERATED_KEYS proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.execute("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNotNull(); listenerReceivedExecutionInfo.set(null); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNotNull(); listenerReceivedExecutionInfo.set(null); // with int[] proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.execute("insert into emp_with_auto_id ( name ) values ('BAZ');", new int[]{1}); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNotNull(); listenerReceivedExecutionInfo.set(null); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", new int[]{1}); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNotNull(); listenerReceivedExecutionInfo.set(null); // with String[] proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.execute("insert into emp_with_auto_id ( name ) values ('BAZ');", new String[]{"id"}); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNotNull(); listenerReceivedExecutionInfo.set(null); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", new String[]{"id"}); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNotNull(); listenerReceivedExecutionInfo.set(null); } @Test public void autoRetrieveGeneratedKeysWithBatchStatement() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); final AtomicReference<ExecutionInfo> listenerReceivedExecutionInfo = new AtomicReference<ExecutionInfo>(); QueryExecutionListener listener = new NoOpQueryExecutionListener() { @Override public void afterQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { // since generatedKeys will NOT be closed, they can be read afterwards. listenerReceivedExecutionInfo.set(execInfo); } }; JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); ProxyConfig proxyConfig; Statement proxySt; // default value (expected to NOT auto-retrieve) proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(false) .build(); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.addBatch("insert into emp_with_auto_id ( name ) values ('BAZ');"); proxySt.addBatch("insert into emp_with_auto_id ( name ) values ('BAZ');"); proxySt.addBatch("insert into emp_with_auto_id ( name ) values ('BAZ');"); proxySt.executeBatch(); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNull(); listenerReceivedExecutionInfo.set(null); // executeLargeBatch is not implemented for HSQLDB // autoRetrieve for batch statement = true proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(false) .retrieveGeneratedKeysForBatchStatement(true) // set true .build(); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.addBatch("insert into emp_with_auto_id ( name ) values ('BAZ');"); proxySt.addBatch("insert into emp_with_auto_id ( name ) values ('BAZ');"); proxySt.addBatch("insert into emp_with_auto_id ( name ) values ('BAZ');"); proxySt.executeBatch(); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNotNull(); listenerReceivedExecutionInfo.set(null); // autoRetrieve for batch statement = false proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(false) .retrieveGeneratedKeysForBatchStatement(false) // set false .build(); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.addBatch("insert into emp_with_auto_id ( name ) values ('BAZ');"); proxySt.addBatch("insert into emp_with_auto_id ( name ) values ('BAZ');"); proxySt.addBatch("insert into emp_with_auto_id ( name ) values ('BAZ');"); proxySt.executeBatch(); assertThat(listenerReceivedExecutionInfo.get().getGeneratedKeys()).isNull(); } @Test public void getGeneratedKeys() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); // when no configuration is specified for generated keys (disabling generated keys related feature) ProxyConfig proxyConfig = ProxyConfig.Builder.create().build(); JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); // calling getGeneratedKeys() multiple time is not defined in JDBC spec // For hsqldb, calling second time closes previously returned ResultSet and returns new ResultSet. ResultSet generatedKeys1 = proxySt.getGeneratedKeys(); assertThat(generatedKeys1.isClosed()).isFalse(); ResultSet generatedKeys2 = proxySt.getGeneratedKeys(); assertThat(generatedKeys2.isClosed()).isFalse(); // everytime it should return a new generatedKeys assertThat(generatedKeys2).isNotSameAs(generatedKeys1); // only specify autoRetrieveGeneratedKeys=true proxyConfig = ProxyConfig.Builder.create() .autoRetrieveGeneratedKeys(true) .build(); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); ResultSet generatedKeys3 = proxySt.getGeneratedKeys(); assertThat(generatedKeys3.isClosed()).isFalse(); ResultSet generatedKeys4 = proxySt.getGeneratedKeys(); assertThat(generatedKeys4.isClosed()).isFalse(); // since first generated-keys is open, second call should return the same one assertThat(generatedKeys4).isSameAs(generatedKeys3); generatedKeys4.close(); ResultSet generatedKeys5 = proxySt.getGeneratedKeys(); assertThat(generatedKeys5.isClosed()).isFalse(); // once it is closed, getGeneratedKeys should return a new ResultSet assertThat(generatedKeys5).isNotSameAs(generatedKeys4); ResultSet generatedKeys6 = proxySt.getGeneratedKeys(); assertThat(generatedKeys6.isClosed()).isFalse(); // again it's not closed, thus same ResultSet should be returned assertThat(generatedKeys6).isSameAs(generatedKeys5); } @Test public void getGeneratedKeysWithAutoRetrievalAndAutoCloseFalse() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); // autoCloseGeneratedKeys=false ProxyConfig proxyConfig = ProxyConfig.Builder.create() .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(false) .build(); JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); // while they are not closed, getGeneratedKeys() should return same object ResultSet generatedKeys1 = proxySt.getGeneratedKeys(); ResultSet generatedKeys2 = proxySt.getGeneratedKeys(); assertThat(generatedKeys2).isSameAs(generatedKeys1); // when generatedKeys is closed, getGeneratedKeys() should return new ResultSet generatedKeys1.close(); ResultSet generatedKeys3 = proxySt.getGeneratedKeys(); assertThat(generatedKeys3).isNotSameAs(generatedKeys1); assertThat(generatedKeys3.isClosed()).isFalse(); // since generatedKeys3 is open, calling getGeneratedKeys() should return the same resultset ResultSet generatedKeys4 = proxySt.getGeneratedKeys(); assertThat(generatedKeys4).isSameAs(generatedKeys3); } @Test public void getGeneratedKeysWithAutoRetrievalAndAutoCloseTrue() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); // autoCloseGeneratedKeys=true ProxyConfig proxyConfig = ProxyConfig.Builder.create() .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(true) .build(); JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); // auto close should not affect the result of "getGeneratedKeys" method. ResultSet generatedKeys1 = proxySt.getGeneratedKeys(); assertThat(generatedKeys1.isClosed()).isFalse(); ResultSet generatedKeys2 = proxySt.getGeneratedKeys(); assertThat(generatedKeys2.isClosed()).isFalse(); // result of "getGeneratedKeys" is still open, thus second call of "getGeneratedKeys" should return the same one assertThat(generatedKeys2).isSameAs(generatedKeys1); assertThat(generatedKeys1.isClosed()).isFalse(); } @Test public void autoCloseGeneratedKeysProxy() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); final AtomicReference<ExecutionInfo> listenerReceivedExecutionInfo = new AtomicReference<ExecutionInfo>(); QueryExecutionListener listener = new NoOpQueryExecutionListener() { @Override public void afterQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { ResultSet generatedKeys = execInfo.getGeneratedKeys(); boolean isClosed = true; try { isClosed = generatedKeys.isClosed(); } catch (SQLException ex) { fail("Failed to call generatedKeys.isClosed() message=" + ex.getMessage()); } assertThat(isClosed).isFalse(); listenerReceivedExecutionInfo.set(execInfo); } }; // autoCloseGeneratedKeys=false JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); ProxyConfig proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(false) .build(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); ExecutionInfo info = listenerReceivedExecutionInfo.get(); ResultSet generatedKeys = info.getGeneratedKeys(); assertThat(generatedKeys.isClosed()).isFalse(); try { generatedKeys.close(); } catch (SQLException ex) { fail("closing non closed ResultSet should success. message=" + ex.getMessage()); } listenerReceivedExecutionInfo.set(null); // autoCloseGeneratedKeys=true proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(true) .autoCloseGeneratedKeys(true) .build(); proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('QUX');", Statement.RETURN_GENERATED_KEYS); info = listenerReceivedExecutionInfo.get(); generatedKeys = info.getGeneratedKeys(); assertThat(generatedKeys.isClosed()).isTrue(); } @Test public void autoRetrieveGeneratedKeysWithGeneratedKeysProxy() throws Throwable { Connection conn = this.jdbcDataSource.getConnection(); Statement st = conn.createStatement(); final AtomicReference<ExecutionInfo> listenerReceivedExecutionInfo = new AtomicReference<ExecutionInfo>(); QueryExecutionListener listener = new NoOpQueryExecutionListener() { @Override public void afterQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { listenerReceivedExecutionInfo.set(execInfo); } }; // specify autoRetrieveGeneratedKeys and proxy factory JdbcProxyFactory proxyFactory = new JdkJdbcProxyFactory(); ProxyConfig proxyConfig = ProxyConfig.Builder.create() .queryListener(listener) .autoRetrieveGeneratedKeys(true) .generatedKeysProxyLogicFactory(new SimpleResultSetProxyLogicFactory()) .autoCloseGeneratedKeys(false) .build(); Statement proxySt = proxyFactory.createStatement(st, new ConnectionInfo(), conn, proxyConfig); proxySt.executeUpdate("insert into emp_with_auto_id ( name ) values ('BAZ');", Statement.RETURN_GENERATED_KEYS); ExecutionInfo info = listenerReceivedExecutionInfo.get(); assertThat(info).isNotNull(); assertThat(info.getGeneratedKeys()).isInstanceOf(ResultSet.class); ResultSet generatedKeys = info.getGeneratedKeys(); assertThat(Proxy.isProxyClass(generatedKeys.getClass())).isTrue(); assertThat(Proxy.getInvocationHandler(generatedKeys)).isExactlyInstanceOf(ResultSetInvocationHandler.class); generatedKeys.next(); int generatedId = generatedKeys.getInt(1); assertThat(generatedId).as("generated ID").isEqualTo(2); } }
9,797
600
<reponame>christianhaitian/openbor /* * OpenBOR - http://www.LavaLit.com * ----------------------------------------------------------------------- * Licensed under the BSD license, see LICENSE in OpenBOR root for details. * * Copyright (c) 2004 - 2011 OpenBOR Team */ int SB_playstart(int bits, int samplerate){ xbox_pause_audio(0); return 1; } void SB_playstop(){ xbox_pause_audio(1); } char SB_getvolume(char dev){ return 0; } char SB_setvolume(char dev, char volume){ return 0; }
167
14,668
<gh_stars>1000+ // Copyright 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. #include "chrome/browser/ui/media_router/query_result_manager.h" #include <unordered_set> #include <utility> #include "base/containers/contains.h" #include "base/memory/raw_ptr.h" #include "components/media_router/browser/media_router.h" #include "components/media_router/browser/media_sinks_observer.h" #include "content/public/browser/browser_thread.h" #include "url/origin.h" namespace media_router { // MediaSinkObserver that propagates results back to |result_manager|. // An instance of this class is associated with each registered MediaSource. class QueryResultManager::MediaSourceMediaSinksObserver : public MediaSinksObserver { public: MediaSourceMediaSinksObserver(MediaCastMode cast_mode, const MediaSource& source, const url::Origin& origin, MediaRouter* router, QueryResultManager* result_manager) : MediaSinksObserver(router, source, origin), cast_mode_(cast_mode), source_(source), result_manager_(result_manager) { DCHECK(result_manager); } ~MediaSourceMediaSinksObserver() override {} // MediaSinksObserver: void OnSinksReceived(const std::vector<MediaSink>& result) override { latest_sink_ids_.clear(); for (const MediaSink& sink : result) latest_sink_ids_.push_back(sink.id()); result_manager_->SetSinksCompatibleWithSource(cast_mode_, source_, result); result_manager_->NotifyOnResultsUpdated(); } // Returns the most recent sink IDs that were passed to |OnSinksReceived()|. void GetLatestSinkIds(std::vector<MediaSink::Id>* sink_ids) const { DCHECK(sink_ids); *sink_ids = latest_sink_ids_; } MediaCastMode cast_mode() const { return cast_mode_; } private: const MediaCastMode cast_mode_; const MediaSource source_; std::vector<MediaSink::Id> latest_sink_ids_; const raw_ptr<QueryResultManager> result_manager_; }; // Observes for all the available sinks. class QueryResultManager::AnyMediaSinksObserver : public MediaSinksObserver { public: AnyMediaSinksObserver(MediaRouter* router, QueryResultManager* result_manager) : MediaSinksObserver(router), result_manager_(result_manager) {} ~AnyMediaSinksObserver() override {} // MediaSinksObserver: void OnSinksReceived(const std::vector<MediaSink>& sinks) override { result_manager_->UpdateSinkList(sinks); result_manager_->NotifyOnResultsUpdated(); } private: const raw_ptr<QueryResultManager> result_manager_; }; QueryResultManager::QueryResultManager(MediaRouter* router) : router_(router) { DCHECK(router_); auto observer = std::make_unique<AnyMediaSinksObserver>(router_, this); observer->Init(); sinks_observers_[MediaSource()] = std::move(observer); } QueryResultManager::~QueryResultManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); } void QueryResultManager::AddObserver(Observer* observer) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(observer); observers_.AddObserver(observer); } void QueryResultManager::RemoveObserver(Observer* observer) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(observer); observers_.RemoveObserver(observer); } void QueryResultManager::SetSourcesForCastMode( MediaCastMode cast_mode, const std::vector<MediaSource>& sources, const url::Origin& origin) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (sources.empty()) { LOG(WARNING) << "SetSourcesForCastMode called with empty sources for " << cast_mode; return; } if (!AreSourcesValidForCastMode(cast_mode, sources)) { LOG(WARNING) << "SetSourcesForCastMode called with invalid sources for " << cast_mode; return; } RemoveOldSourcesForCastMode(cast_mode, sources); AddObserversForCastMode(cast_mode, sources, origin); cast_mode_sources_[cast_mode] = sources; NotifyOnResultsUpdated(); } void QueryResultManager::RemoveSourcesForCastMode(MediaCastMode cast_mode) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); RemoveOldSourcesForCastMode(cast_mode, std::vector<MediaSource>()); cast_mode_sources_.erase(cast_mode); NotifyOnResultsUpdated(); } CastModeSet QueryResultManager::GetSupportedCastModes() const { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); CastModeSet modes; for (const auto& cast_mode_pair : cast_mode_sources_) modes.insert(cast_mode_pair.first); return modes; } std::unique_ptr<MediaSource> QueryResultManager::GetSourceForCastModeAndSink( MediaCastMode cast_mode, MediaSink::Id sink_id) const { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto sink_entry = sinks_with_sources_.find(sink_id); if (sink_entry == sinks_with_sources_.end()) return nullptr; return GetHighestPrioritySourceForCastModeAndSink(cast_mode, sink_entry->second); } std::vector<MediaSource> QueryResultManager::GetSourcesForCastMode( MediaCastMode cast_mode) const { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); const auto& cast_mode_it = cast_mode_sources_.find(cast_mode); return cast_mode_it == cast_mode_sources_.end() ? std::vector<MediaSource>() : cast_mode_it->second; } void QueryResultManager::RemoveOldSourcesForCastMode( MediaCastMode cast_mode, const std::vector<MediaSource>& new_sources) { const auto& cast_mode_it = cast_mode_sources_.find(cast_mode); if (cast_mode_it == cast_mode_sources_.end()) return; for (const MediaSource& source : cast_mode_it->second) { if (!base::Contains(new_sources, source)) { sinks_observers_.erase(source); SetSinksCompatibleWithSource(cast_mode, source, std::vector<MediaSink>()); } } } void QueryResultManager::AddObserversForCastMode( MediaCastMode cast_mode, const std::vector<MediaSource>& sources, const url::Origin& origin) { for (const MediaSource& source : sources) { if (!base::Contains(sinks_observers_, source)) { auto observer = std::make_unique<MediaSourceMediaSinksObserver>( cast_mode, source, origin, router_, this); observer->Init(); sinks_observers_[source] = std::move(observer); } } } void QueryResultManager::SetSinksCompatibleWithSource( MediaCastMode cast_mode, const MediaSource& source, const std::vector<MediaSink>& new_sinks) { std::unordered_set<MediaSink::Id> new_sink_ids; for (const MediaSink& sink : new_sinks) new_sink_ids.insert(sink.id()); // (1) Iterate through current sink set, remove cast mode from those that // do not appear in latest result. for (auto it = sinks_with_sources_.begin(); it != sinks_with_sources_.end(); /* no-op */) { const MediaSink::Id& sink_id = it->first; CastModesWithMediaSources& sources_for_sink = it->second; if (!base::Contains(new_sink_ids, sink_id)) sources_for_sink.RemoveSource(cast_mode, source); if (sources_for_sink.IsEmpty()) { sinks_with_sources_.erase(it++); } else { ++it; } } // (2) Add / update sinks with latest result. for (const MediaSink& sink : new_sinks) { auto sink_it = sinks_with_sources_.find(sink.id()); if (sink_it == sinks_with_sources_.end()) { sink_it = sinks_with_sources_ .emplace(sink.id(), CastModesWithMediaSources(sink)) .first; } else { sink_it->second.set_sink(sink); } sink_it->second.AddSource(cast_mode, source); } } void QueryResultManager::UpdateSinkList(const std::vector<MediaSink>& sinks) { all_sinks_ = sinks; } std::unique_ptr<MediaSource> QueryResultManager::GetHighestPrioritySourceForCastModeAndSink( MediaCastMode cast_mode, const CastModesWithMediaSources& sources_for_sink) const { const auto& cast_mode_it = cast_mode_sources_.find(cast_mode); if (cast_mode_it == cast_mode_sources_.end()) return nullptr; for (const MediaSource& source : cast_mode_it->second) { if (sources_for_sink.HasSource(cast_mode, source)) return std::make_unique<MediaSource>(source.id()); } return nullptr; } bool QueryResultManager::AreSourcesValidForCastMode( MediaCastMode cast_mode, const std::vector<MediaSource>& sources) const { const auto& cast_mode_it = cast_mode_sources_.find(cast_mode); bool has_cast_mode = cast_mode_it != cast_mode_sources_.end(); // If a source has already been registered, then it must be associated with // |cast_mode|. return std::find_if(sources.begin(), sources.end(), [=](const MediaSource& source) { return base::Contains(sinks_observers_, source) && (!has_cast_mode || !base::Contains(cast_mode_it->second, source)); }) == sources.end(); } void QueryResultManager::NotifyOnResultsUpdated() { std::vector<MediaSinkWithCastModes> sinks; for (const auto& sink_pair : sinks_with_sources_) { MediaSinkWithCastModes sink_with_cast_modes(sink_pair.second.sink()); sink_with_cast_modes.cast_modes = sink_pair.second.GetCastModes(); sinks.push_back(sink_with_cast_modes); } for (const auto& sink : all_sinks_) { if (!base::Contains(sinks_with_sources_, sink.id())) sinks.push_back(MediaSinkWithCastModes(sink)); } for (QueryResultManager::Observer& observer : observers_) observer.OnResultsUpdated(sinks); } } // namespace media_router
3,701
777
<reponame>google-ar/chromium<gh_stars>100-1000 // Copyright 2014 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 COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_CLIENT_H_ #define COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_CLIENT_H_ #include "base/callback.h" #include "base/callback_list.h" #include "base/time/time.h" #include "components/keyed_service/core/keyed_service.h" #include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/webdata/token_web_data.h" #include "google_apis/gaia/gaia_auth_fetcher.h" #include "net/cookies/cookie_store.h" #include "url/gurl.h" class PrefService; class TokenWebData; namespace content_settings { class Observer; } namespace net { class URLRequestContextGetter; } // An interface that needs to be supplied to the Signin component by its // embedder. class SigninClient : public KeyedService { public: // The subcription for cookie changed notifications. class CookieChangedSubscription { public: virtual ~CookieChangedSubscription() {} }; ~SigninClient() override {} // If |for_ephemeral| is true, special kind of device ID for ephemeral users // is generated. static std::string GenerateSigninScopedDeviceID(bool for_ephemeral); // Sign out. void SignOut(); // Call when done local initialization and SigninClient can initiate any work // it has to do that may require other components (like ProfileManager) to be // available. virtual void DoFinalInit() = 0; // Gets the preferences associated with the client. virtual PrefService* GetPrefs() = 0; // Gets the TokenWebData instance associated with the client. virtual scoped_refptr<TokenWebData> GetDatabase() = 0; // Returns whether it is possible to revoke credentials. virtual bool CanRevokeCredentials() = 0; // Returns device id that is scoped to single signin. This device id will be // regenerated if user signs out and signs back in. // When refresh token is requested for this user it will be annotated with // this device id. virtual std::string GetSigninScopedDeviceId() = 0; // Returns the URL request context information associated with the client. virtual net::URLRequestContextGetter* GetURLRequestContext() = 0; // Returns whether the user's credentials should be merged into the cookie // jar on signin completion. virtual bool ShouldMergeSigninCredentialsIntoCookieJar() = 0; // Returns a string containing the version info of the product in which the // Signin component is being used. virtual std::string GetProductVersion() = 0; // Adds a callback to be called each time a cookie for |url| with name |name| // changes. // Note that |callback| will always be called on the thread that // |AddCookieChangedCallback| was called on. virtual std::unique_ptr<CookieChangedSubscription> AddCookieChangedCallback( const GURL& url, const std::string& name, const net::CookieStore::CookieChangedCallback& callback) = 0; // Called after Google signin has succeeded. virtual void OnSignedIn(const std::string& account_id, const std::string& gaia_id, const std::string& username, const std::string& password) {} // Called after Google signin has succeeded and GetUserInfo has returned. virtual void PostSignedIn(const std::string& account_id, const std::string& username, const std::string& password) {} // Called before Google signout started, call |sign_out| to start the sign out // process. virtual void PreSignOut(const base::Callback<void()>& sign_out); virtual bool IsFirstRun() const = 0; virtual base::Time GetInstallDate() = 0; // Returns true if GAIA cookies are allowed in the content area. virtual bool AreSigninCookiesAllowed() = 0; // Adds an observer to listen for changes to the state of sign in cookie // settings. virtual void AddContentSettingsObserver( content_settings::Observer* observer) = 0; virtual void RemoveContentSettingsObserver( content_settings::Observer* observer) = 0; // Execute |callback| if and when there is a network connection. virtual void DelayNetworkCall(const base::Closure& callback) = 0; // Creates and returns a new platform-specific GaiaAuthFetcher. It is the // responsability of the caller to delete the returned object. virtual GaiaAuthFetcher* CreateGaiaAuthFetcher( GaiaAuthConsumer* consumer, const std::string& source, net::URLRequestContextGetter* getter) = 0; // Called once the credentials has been copied to another SigninManager. virtual void AfterCredentialsCopied() {} // Used do debug channel id binding problem in chrome. Returns the number of // times the request context changed unexpectedly. virtual int number_of_request_context_pointer_changes() const; protected: // Returns device id that is scoped to single signin. // Stores the ID in the kGoogleServicesSigninScopedDeviceId pref. std::string GetOrCreateScopedDeviceIdPref(PrefService* prefs); private: // Perform Chrome-specific sign out. This happens when user signs out or about // to sign in. // This method should not be called from the outside of SigninClient. External // callers must use SignOut() instead. virtual void OnSignedOut() = 0; }; #endif // COMPONENTS_SIGNIN_CORE_BROWSER_SIGNIN_CLIENT_H_
1,688
14,668
// Copyright 2020 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 COMPONENTS_SYNC_BASE_LEGACY_DIRECTORY_DELETION_H_ #define COMPONENTS_SYNC_BASE_LEGACY_DIRECTORY_DELETION_H_ #include "base/files/file_path.h" namespace syncer { // Delete the directory database files from the sync data folder to cleanup // all files. The main purpose is to delete the legacy Directory files (sqlite) // but it also currently deletes the files corresponding to the modern // NigoriStorageImpl. void DeleteLegacyDirectoryFilesAndNigoriStorage( const base::FilePath& directory_path); } // namespace syncer #endif // COMPONENTS_SYNC_BASE_LEGACY_DIRECTORY_DELETION_H_
240
359
<reponame>roannav/learntools import tensorflow as tf from tensorflow.python.keras.layers import Dense, Flatten, Conv2D, LeakyReLU tfgan = tf.contrib.gan leaky = LeakyReLU(0.2) def basic_discriminator(img, unused_conditioning): """Discriminator network on MNIST digits. Args: img: Real or generated image. Should be in the range [-1, 1]. unused_conditioning: The TFGAN API can help with conditional GANs, which would require extra `condition` information to both the generator and the discriminator. Since this example is not conditional, we do not use this argument. Returns: Logits for the probability that the image is real. """ net = Conv2D(64, kernel_size=4, strides=2)(img) net = leaky(net) net = Conv2D(64, kernel_size=4, strides=2)(net) net = leaky(net) net = Conv2D(64, kernel_size=4)(net) net = leaky(net) net = Flatten()(net) net = Dense(1024)(net) net = leaky(net) net = Dense(1, activation='linear')(net) return net def conditional_discriminator(img, conditioning): """Conditional discriminator network on MNIST digits. Args: img: Real or generated MNIST digits. Should be in the range [-1, 1]. conditioning: A 2-tuple of Tensors representing (noise, one_hot_labels). Returns: Logits for the probability that the image is real. """ _, one_hot_labels = conditioning net = Conv2D(64, kernel_size=4, strides=2)(img) net = leaky(net) net = tfgan.features.condition_tensor_from_onehot(net, one_hot_labels) net = Conv2D(128, kernel_size=4, strides=2)(net) net = leaky(net) net = Flatten()(net) net = Dense(1024)(net) net = leaky(net) net = Dense(1, activation='linear')(net) return net
714
4,047
<reponame>kira78/meson { "stdout": [ { "line": "WARNING: Module unstable-keyval is now stable, please use the keyval module instead." } ] }
65
942
r"""Rank-based cost function (CostRank)""" import numpy as np from numpy.linalg import pinv, LinAlgError from scipy.stats.mstats import rankdata from ruptures.base import BaseCost from ruptures.costs import NotEnoughPoints class CostRank(BaseCost): r""" Rank-based cost function """ model = "rank" def __init__(self): """Initialize the object.""" self.inv_cov = None self.ranks = None self.min_size = 2 def fit(self, signal) -> "CostRank": """Set parameters of the instance. Args: signal (array): signal. Shape (n_samples,) or (n_samples, n_features) Returns: self """ if signal.ndim == 1: signal = signal.reshape(-1, 1) obs, vars = signal.shape # Convert signal data into ranks in the range [1, n] ranks = rankdata(signal, axis=0) # Center the ranks into the range [-(n+1)/2, (n+1)/2] centered_ranks = ranks - ((obs + 1) / 2) # Sigma is the covariance of these ranks. # If it's a scalar, reshape it into a 1x1 matrix cov = np.cov(centered_ranks, rowvar=False, bias=True).reshape(vars, vars) # Use the pseudoinverse to handle linear dependencies # see <NAME>., <NAME>., & <NAME>. (2015) try: self.inv_cov = pinv(cov) except LinAlgError as e: raise LinAlgError( "The covariance matrix of the rank signal is not invertible and the " "pseudo-inverse computation did not converge." ) from e self.ranks = centered_ranks self.signal = signal return self def error(self, start, end): """Return the approximation cost on the segment [start:end]. Args: start (int): start of the segment end (int): end of the segment Returns: float: segment cost Raises: NotEnoughPoints: when the segment is too short (less than `min_size` samples). """ if end - start < self.min_size: raise NotEnoughPoints mean = np.reshape(np.mean(self.ranks[start:end], axis=0), (-1, 1)) return -(end - start) * mean.T @ self.inv_cov @ mean
1,010
437
<reponame>Palem1988/nuls<filename>contract-module/base/contract-vm/src/test/java/testcontract/nrc20/SimpleToken.java<gh_stars>100-1000 package testcontract.nrc20; import io.nuls.contract.sdk.Address; import io.nuls.contract.sdk.Contract; import io.nuls.contract.sdk.Msg; import io.nuls.contract.sdk.annotation.Required; import io.nuls.contract.sdk.annotation.View; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import static io.nuls.contract.sdk.Utils.emit; import static io.nuls.contract.sdk.Utils.require; public class SimpleToken implements Contract, NRC20 { private final String name; private final String symbol; private final int decimals; private BigInteger totalSupply = BigInteger.ZERO; private Map<Address, BigInteger> balances = new HashMap<Address, BigInteger>(); private Map<Address, Map<Address, BigInteger>> allowed = new HashMap<Address, Map<Address, BigInteger>>(); @Override @View public String name() { return name; } @Override @View public String symbol() { return symbol; } @Override @View public int decimals() { return decimals; } @Override @View public BigInteger totalSupply() { return totalSupply; } public SimpleToken(@Required String name, @Required String symbol, @Required BigInteger initialAmount, @Required int decimals) { this.name = name; this.symbol = symbol; this.decimals = decimals; totalSupply = initialAmount.multiply(BigInteger.TEN.pow(decimals));; balances.put(Msg.sender(), totalSupply); emit(new TransferEvent(null, Msg.sender(), totalSupply)); } @Override @View public BigInteger allowance(@Required Address owner, @Required Address spender) { Map<Address, BigInteger> ownerAllowed = allowed.get(owner); if (ownerAllowed == null) { return BigInteger.ZERO; } BigInteger value = ownerAllowed.get(spender); if (value == null) { value = BigInteger.ZERO; } return value; } @Override public boolean transferFrom(@Required Address from, @Required Address to, @Required BigInteger value) { subtractAllowed(from, Msg.sender(), value); subtractBalance(from, value); addBalance(to, value); emit(new TransferEvent(from, to, value)); return true; } @Override @View public BigInteger balanceOf(@Required Address owner) { require(owner != null); BigInteger balance = balances.get(owner); if (balance == null) { balance = BigInteger.ZERO; } return balance; } @Override public boolean transfer(@Required Address to, @Required BigInteger value) { subtractBalance(Msg.sender(), value); addBalance(to, value); emit(new TransferEvent(Msg.sender(), to, value)); return true; } @Override public boolean approve(@Required Address spender, @Required BigInteger value) { setAllowed(Msg.sender(), spender, value); emit(new ApprovalEvent(Msg.sender(), spender, value)); return true; } public boolean increaseApproval(@Required Address spender, @Required BigInteger addedValue) { addAllowed(Msg.sender(), spender, addedValue); emit(new ApprovalEvent(Msg.sender(), spender, allowance(Msg.sender(), spender))); return true; } public boolean decreaseApproval(@Required Address spender, @Required BigInteger subtractedValue) { check(subtractedValue); BigInteger oldValue = allowance(Msg.sender(), spender); if (subtractedValue.compareTo(oldValue) > 0) { setAllowed(Msg.sender(), spender, BigInteger.ZERO); } else { subtractAllowed(Msg.sender(), spender, subtractedValue); } emit(new ApprovalEvent(Msg.sender(), spender, allowance(Msg.sender(), spender))); return true; } private void addAllowed(Address address1, Address address2, BigInteger value) { BigInteger allowance = allowance(address1, address2); check(allowance); check(value); setAllowed(address1, address2, allowance.add(value)); } private void subtractAllowed(Address address1, Address address2, BigInteger value) { BigInteger allowance = allowance(address1, address2); check(allowance, value, "Insufficient approved token"); setAllowed(address1, address2, allowance.subtract(value)); } private void setAllowed(Address address1, Address address2, BigInteger value) { check(value); Map<Address, BigInteger> address1Allowed = allowed.get(address1); if (address1Allowed == null) { address1Allowed = new HashMap<Address, BigInteger>(); allowed.put(address1, address1Allowed); } address1Allowed.put(address2, value); } private void addBalance(Address address, BigInteger value) { BigInteger balance = balanceOf(address); check(value, "The value must be greater than or equal to 0."); check(balance); balances.put(address, balance.add(value)); } private void subtractBalance(Address address, BigInteger value) { BigInteger balance = balanceOf(address); check(balance, value, "Insufficient balance of token."); balances.put(address, balance.subtract(value)); } private void check(BigInteger value) { require(value != null && value.compareTo(BigInteger.ZERO) >= 0); } private void check(BigInteger value1, BigInteger value2) { check(value1); check(value2); require(value1.compareTo(value2) >= 0); } private void check(BigInteger value, String msg) { require(value != null && value.compareTo(BigInteger.ZERO) >= 0, msg); } private void check(BigInteger value1, BigInteger value2, String msg) { check(value1); check(value2); require(value1.compareTo(value2) >= 0, msg); } }
2,356
4,372
<reponame>Trydamere/shardingsphere /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.shardingsphere.authority.provider.natived.builder; import org.apache.shardingsphere.authority.model.PrivilegeType; import org.apache.shardingsphere.authority.provider.natived.model.privilege.NativePrivileges; import org.apache.shardingsphere.authority.provider.natived.model.privilege.database.SchemaPrivileges; import org.apache.shardingsphere.authority.provider.natived.model.privilege.database.TablePrivileges; import org.apache.shardingsphere.infra.metadata.user.ShardingSphereUser; import org.apache.shardingsphere.infra.rule.identifier.type.DataNodeContainedRule; import org.junit.Test; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public final class StoragePrivilegeMergerTest { @Test public void assertPrivilegeMergeResult() { ShardingSphereUser user = new ShardingSphereUser("test", "test", "%"); Map<ShardingSphereUser, Collection<NativePrivileges>> userPrivilegeMap = Collections.singletonMap(user, Collections.singleton(buildPrivileges())); Map<ShardingSphereUser, NativePrivileges> actual = StoragePrivilegeMerger.merge(userPrivilegeMap, "schema", Collections.singleton(buildRule())); assertThat(actual.size(), is(1)); assertTrue(actual.get(user).getAdministrativePrivileges().getPrivileges().isEmpty()); assertTrue(actual.get(user).getDatabasePrivileges().getGlobalPrivileges().isEmpty()); assertThat(actual.get(user).getDatabasePrivileges().getSpecificPrivileges().size(), is(1)); assertTrue(actual.get(user).getDatabasePrivileges().getSpecificPrivileges().get("schema").getGlobalPrivileges().isEmpty()); assertThat(actual.get(user).getDatabasePrivileges().getSpecificPrivileges().get("schema").getSpecificPrivileges().size(), is(1)); assertThat("TableName assert error.", actual.get(user).getDatabasePrivileges().getSpecificPrivileges().get("schema").getSpecificPrivileges().get("tbl").getTableName(), is("tbl")); assertThat(actual.get(user).getDatabasePrivileges().getSpecificPrivileges().get("schema").getSpecificPrivileges().get("tbl").getPrivileges().size(), is(1)); assertTrue(actual.get(user).getDatabasePrivileges().getSpecificPrivileges().get("schema").getSpecificPrivileges().get("tbl").getPrivileges().contains(PrivilegeType.SELECT)); } private NativePrivileges buildPrivileges() { Collection<PrivilegeType> tablePrivileges = Collections.singleton(PrivilegeType.SELECT); SchemaPrivileges schema0Privilege = new SchemaPrivileges("schema_0"); schema0Privilege.getSpecificPrivileges().put("tbl_0", new TablePrivileges("tbl_0", tablePrivileges)); schema0Privilege.getSpecificPrivileges().put("tbl_1", new TablePrivileges("tbl_1", tablePrivileges)); SchemaPrivileges schema1Privilege = new SchemaPrivileges("schema_1"); schema1Privilege.getSpecificPrivileges().put("tbl_2", new TablePrivileges("tbl_2", tablePrivileges)); schema1Privilege.getSpecificPrivileges().put("tbl_3", new TablePrivileges("tbl_3", tablePrivileges)); NativePrivileges result = new NativePrivileges(); result.getDatabasePrivileges().getSpecificPrivileges().put("schema_0", schema0Privilege); result.getDatabasePrivileges().getSpecificPrivileges().put("schema_1", schema1Privilege); return result; } private DataNodeContainedRule buildRule() { DataNodeContainedRule result = mock(DataNodeContainedRule.class); when(result.findLogicTableByActualTable("tbl_0")).thenReturn(Optional.of("tbl")); when(result.findLogicTableByActualTable("tbl_1")).thenReturn(Optional.of("tbl")); when(result.findLogicTableByActualTable("tbl_2")).thenReturn(Optional.of("tbl")); when(result.findLogicTableByActualTable("tbl_3")).thenReturn(Optional.of("tbl")); return result; } }
1,664
14,668
<filename>native_client_sdk/src/build_tools/sdk_tools/command/sources.py # 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. import download from sdk_update_common import Error def AddSource(config, url): try: download.UrlOpen(url) except Exception as e: raise Error('Not adding %s, unable to load URL.\n %s' % (url, e)) config.AddSource(url) def RemoveSource(config, url): if url == 'all': config.RemoveAllSources() else: config.RemoveSource(url) def ListSources(config): if config.sources: print 'Installed sources:' for s in config.sources: print ' ' + s else: print 'No external sources installed.'
264
347
package org.ovirt.engine.core.dao; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import org.ovirt.engine.core.common.businessentities.Tags; import org.ovirt.engine.core.common.businessentities.TagsType; import org.ovirt.engine.core.compat.Guid; /** * The following test checks multi-threading issues with Dao usage. * The test uses the TagsDao, but any other Dao can be used */ public class MultiThreadedDaoTest extends BaseDaoTestCase<TagDao> { private static final Guid[] EXISTING_TAGS_IDS = { new Guid("d3ec3e01-ca89-48e1-8b43-a9b38f873b0c"), new Guid("d3ec3e01-ca89-48e1-8b43-a9b38f873b0d"), new Guid("d3ec3e01-ca89-48e1-8b43-a9b38f873b0e") }; private CountDownLatch latch = null; @Test public void testGetSameID() throws Exception { final Tags existing = dao.get(EXISTING_TAGS_IDS[0]); createAndRunThreadsForRunner(() -> { Tags result = dao.get(existing.getTagId()); assertEquals(existing, result); }, 100); } @Test public void testGetDifferentID() throws Exception { final AtomicInteger counter = new AtomicInteger(); final Tags[] existingTags = new Tags[EXISTING_TAGS_IDS.length]; for (int i = 0; i < EXISTING_TAGS_IDS.length; i++) { existingTags[i] = dao.get(EXISTING_TAGS_IDS[i]); } createAndRunThreadsForRunner(() -> { int val = counter.incrementAndGet(); int index = val % EXISTING_TAGS_IDS.length; Tags result = dao.get(EXISTING_TAGS_IDS[index]); assertEquals(existingTags[index], result); }, 100); } @Test public void testReadWriteDelete() throws Exception { final AtomicInteger counter = new AtomicInteger(); createAndRunThreadsForRunner(() -> { int val = counter.incrementAndGet(); Tags tag = createTag("tag" + val, "desc" + val); dao.save(tag); Tags fromDb = dao.get(tag.getTagId()); assertEquals(tag, fromDb); dao.remove(tag.getTagId()); fromDb = dao.get(tag.getTagId()); assertNull(fromDb); }, 100); } private Tags createTag(String name, String desc) { Tags tag = new Tags(); tag.setChildren(new ArrayList<>()); tag.setDescription(desc); tag.setTagName(name); tag.setIsReadonly(true); tag.setParentId(Guid.Empty); tag.setType(TagsType.GeneralTag); return tag; } private void createAndRunThreadsForRunner(Runnable runnable, int numOfThreads) throws Exception { if (runnable == null) { return; } latch = new CountDownLatch(numOfThreads); ExecutorService threadPool = Executors.newFixedThreadPool(numOfThreads); for (int counter = 0; counter < numOfThreads; counter++) { threadPool.execute(new LatchedRunnableWrapper(runnable, latch)); } latch.await(); } }
1,437
2,519
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. package com.starrocks.sql.optimizer.rule.transformation; import com.google.common.collect.Lists; import com.starrocks.sql.optimizer.OptExpression; import com.starrocks.sql.optimizer.OptimizerContext; import com.starrocks.sql.optimizer.operator.OperatorType; import com.starrocks.sql.optimizer.operator.logical.LogicalCTEConsumeOperator; import com.starrocks.sql.optimizer.operator.pattern.Pattern; import com.starrocks.sql.optimizer.rule.RuleType; import java.util.List; public class PruneCTEConsumePlanRule extends TransformationRule { public PruneCTEConsumePlanRule() { super(RuleType.TF_PRUNE_CTE_CONSUME_PLAN, Pattern.create(OperatorType.LOGICAL_CTE_CONSUME) .addChildren(Pattern.create(OperatorType.PATTERN_LEAF, OperatorType.PATTERN_MULTI_LEAF))); } @Override public boolean check(OptExpression input, OptimizerContext context) { LogicalCTEConsumeOperator consume = (LogicalCTEConsumeOperator) input.getOp(); return !context.getCteContext().needInline(consume.getCteId()); } @Override public List<OptExpression> transform(OptExpression input, OptimizerContext context) { // delete cte consume child plan return Lists.newArrayList(OptExpression.create(input.getOp())); } }
487
2,177
package org.nutz.dao; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * @Author: Haimming * @Date: 2020-01-15 10:58 * @Version 1.0 */ public class SqlNotFoundExceptionTest { @Test public void sqlNotFoundExceptionTest() { try { throw new SqlNotFoundException("key"); } catch (Exception e) { System.out.println(e.getMessage()); assertEquals("fail to find SQL 'key'!", e.getMessage()); } } }
222
1,444
<reponame>amc8391/mage<filename>Mage.Server/src/main/java/mage/server/managers/GameManager.java package mage.server.managers; import mage.cards.decks.DeckCardLists; import mage.constants.ManaType; import mage.constants.PlayerAction; import mage.game.Game; import mage.game.GameOptions; import mage.server.game.GameController; import mage.view.GameView; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public interface GameManager { UUID createGameSession(Game game, ConcurrentHashMap<UUID, UUID> userPlayerMap, UUID tableId, UUID choosingPlayerId, GameOptions gameOptions); void joinGame(UUID gameId, UUID userId); Optional<UUID> getChatId(UUID gameId); void sendPlayerUUID(UUID gameId, UUID userId, UUID data); void sendPlayerString(UUID gameId, UUID userId, String data); void sendPlayerManaType(UUID gameId, UUID playerId, UUID userId, ManaType data); void sendPlayerBoolean(UUID gameId, UUID userId, Boolean data); void sendPlayerInteger(UUID gameId, UUID userId, Integer data); void quitMatch(UUID gameId, UUID userId); void sendPlayerAction(PlayerAction playerAction, UUID gameId, UUID userId, Object data); boolean watchGame(UUID gameId, UUID userId); void stopWatching(UUID gameId, UUID userId); void cheat(UUID gameId, UUID userId, UUID playerId, DeckCardLists deckList); boolean cheat(UUID gameId, UUID userId, UUID playerId, String cardName); void removeGame(UUID gameId); boolean saveGame(UUID gameId); GameView getGameView(UUID gameId, UUID playerId); int getNumberActiveGames(); Map<UUID, GameController> getGameController(); }
579
1,155
<reponame>alexhenrie/poedit /* * * (C) Copyright IBM Corp. 2002-2008 - All Rights Reserved * */ #ifndef __MPREFIXUPS_H #define __MPREFIXUPS_H /** * \file * \internal */ #include "LETypes.h" U_NAMESPACE_BEGIN class LEGlyphStorage; // Might want to make this a private member... struct FixupData; class MPreFixups : public UMemory { public: MPreFixups(le_int32 charCount); ~MPreFixups(); void add(le_int32 baseIndex, le_int32 mpreIndex); void apply(LEGlyphStorage &glyphStorage, LEErrorCode& success); private: FixupData *fFixupData; le_int32 fFixupCount; }; U_NAMESPACE_END #endif
263
3,121
from nlpaug.model.base_model import Model class WordRule(Model): def __init__(self, cache=True): self.cache = cache # pylint: disable=R0201 def predict(self, data): raise NotImplementedError
88
643
<filename>jpa-hibernate-examples/jpa-hibernate-crud-deleting-entity/src/main/java/com/hellokoding/jpa/book/Book.java package com.hellokoding.jpa.book; import lombok.*; import javax.persistence.*; import java.util.Objects; @Data @RequiredArgsConstructor @NoArgsConstructor @ToString(exclude = "category") @Entity public class Book{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private @NonNull String name; @ManyToOne @JoinColumn private Category category; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Book)) return false; Book book = (Book) o; return Objects.equals(name, book.name); } @Override public int hashCode() { return Objects.hash(name); } }
328
477
<filename>biostar/accounts/migrations/0026_userlog.py # Generated by Django 3.1 on 2021-04-01 23:22 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('accounts', '0025_profile_handle'), ] operations = [ migrations.CreateModel( name='UserLog', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ipaddr', models.GenericIPAddressField(blank=True, null=True)), ('action', models.IntegerField(choices=[(1, 'Default'), (2, 'Action')], db_index=True, default=1)), ('text', models.TextField(blank=True, null=True)), ('data', models.TextField(blank=True, null=True)), ('date', models.DateTimeField()), ('subject', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='subject', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
579
735
<gh_stars>100-1000 /** * User: mcxiaoke * Date: 2016/10/25 * Time: 12:28 */ package com.mcxiaoke.next.http; import okhttp3.MediaType; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; import okio.ForwardingSource; import okio.Okio; import okio.Source; import java.io.IOException; public class ProgressResponseBody extends ResponseBody { private final ResponseBody body; private final ProgressListener listener; private BufferedSource buffer; private long totalRead; public ProgressResponseBody(ResponseBody body, ProgressListener listener) { this.body = body; this.listener = listener; totalRead = 0L; } @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return body.contentLength(); } public long totalBytesRead() { return totalRead; } @Override public BufferedSource source() { if (buffer == null) { buffer = Okio.buffer(source(body.source())); } return buffer; } private Source source(Source source) { return new ForwardingSource(source) { @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); // read() returns the number of bytes read, or -1 if this source is exhausted. totalRead += bytesRead != -1 ? bytesRead : 0; if (listener != null) { listener.onProgress( totalRead, body.contentLength(), bytesRead == -1); } return bytesRead; } }; } }
738
1,658
/* * Copyright (C) 2019-2022 Chatopera Inc, <https://www.chatopera.com> * * 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. */ package com.chatopera.cc.interceptor; import com.chatopera.cc.basic.MainContext; import com.chatopera.cc.cache.RedisCommand; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 用户体验计划 */ public class UserExperiencePlanInterceptorHandler extends HandlerInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(UserExperiencePlanInterceptorHandler.class); public final static String FLAG_KEY = "cskefu:global:user-experience-plan"; private static RedisCommand redis; public static final String USER_EXP_PLAN_ON = "on"; public static final String USER_EXP_PLAN_OFF = "off"; private static final String USER_EXP_TELEMETRY = "userExpTelemetry"; @Override public void postHandle( HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView view) { if (!request.getMethod().equals("GET")) { return; } if (view == null) { return; } String flag = getRedis().get(FLAG_KEY); if (StringUtils.isEmpty(flag)) { // flag is empty, add init value flag = USER_EXP_PLAN_ON; getRedis().put(FLAG_KEY, USER_EXP_PLAN_ON); } // logger.info("flag {}", flag); if (StringUtils.equalsIgnoreCase(USER_EXP_PLAN_OFF, flag)) { view.addObject(USER_EXP_TELEMETRY, USER_EXP_PLAN_OFF); } else { view.addObject(USER_EXP_TELEMETRY, USER_EXP_PLAN_ON); } } /** * Get redis bean * * @return */ private static RedisCommand getRedis() { if (redis == null) { redis = MainContext.getContext().getBean(RedisCommand.class); } return redis; } }
1,036
348
{"nom":"Epeigné-les-Bois","circ":"2ème circonscription","dpt":"Indre-et-Loire","inscrits":306,"abs":150,"votants":156,"blancs":1,"nuls":2,"exp":153,"res":[{"nuance":"REM","nom":"<NAME>","voix":57},{"nuance":"LR","nom":"Mme <NAME>","voix":37},{"nuance":"FN","nom":"M. <NAME>","voix":19},{"nuance":"FI","nom":"M. <NAME>","voix":16},{"nuance":"ECO","nom":"M. <NAME>","voix":8},{"nuance":"SOC","nom":"Mme <NAME>","voix":7},{"nuance":"DLF","nom":"Mme <NAME>","voix":3},{"nuance":"COM","nom":"<NAME>","voix":2},{"nuance":"EXG","nom":"Mme <NAME>","voix":2},{"nuance":"DVD","nom":"M. <NAME>","voix":1},{"nuance":"DVD","nom":"M. <NAME>","voix":1},{"nuance":"DVG","nom":"M. <NAME>","voix":0},{"nuance":"RDG","nom":"M. <NAME>","voix":0},{"nuance":"DIV","nom":"Mme <NAME>","voix":0}]}
321
326
<reponame>ryuichi1208/ngx_mruby /* // ngx_stream_mruby_core.h - ngx_mruby mruby module header // // See Copyright Notice in ngx_http_mruby_module.c */ #ifndef NGX_STREAM_MRUBY_CORE_H #define NGX_STREAM_MRUBY_CORE_H #include <ngx_config.h> #include <ngx_stream.h> #include <mruby.h> void ngx_stream_mrb_core_class_init(mrb_state *mrb, struct RClass *class); typedef void (*ngx_stream_mrb_cleanup_pt)(void *data); typedef struct ngx_stream_mruby_ctx_t { mrb_value *fiber_proc; mrb_value *async_handler_result; ngx_stream_mrb_cleanup_pt cleanup; ngx_event_t sleep; } ngx_stream_mruby_ctx_t; ngx_stream_mruby_ctx_t *ngx_stream_mrb_get_module_ctx(mrb_state *mrb, ngx_stream_session_t *s); extern ngx_module_t ngx_stream_mruby_module; #endif // NGX_STREAM_MRUBY_CORE_H
355
3,055
/* Fontname: -gnu-Unifont-Medium-R-Normal-Sans-16-160-75-75-c-80-iso10646-1 Copyright: Copyright (C) 1998-2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, et al. License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html> with the GNU Font Embedding Exception. Glyphs: 531/57086 BBX Build Mode: 0 */ const uint8_t u8g2_font_unifont_t_symbols[8999] U8G2_FONT_SECTION("u8g2_font_unifont_t_symbols") = "\23\0\3\2\5\5\4\5\6\20\20\0\376\12\376\13\377\1\233\3\64\16\244 \6\0\240G\1!\10A" "\61DqH\4\42\10\205(F\221\271\5#\17F%D\325\323\60$Q\313\60D=\1$\22G%" "D\27\16J\24I\341<FRe\20\63\0%\24G%D\243II)\211\224\64N\23)\211\222\222" "\246\0&\22G%D\265\225\262J(&\221\226\210I&M\1'\7\201\60F\61\4(\14\203\355C" "\225DI\324[\224\5)\15\203\351C\221EY\324K\224D\0*\15\347dDW\252\264mIS-" "\3+\14\347dD\27\327\206!\213k\0,\11\202\254C\241$\12\0-\7$(E\61\4.\7B" ",D\61\4/\14F%D[\254\206iXM\1\60\22F%D\245EI\250M\211\22mb\22e" "\22\0\61\13E)D\225II\330\247A\62\17F%D\63$\241\230fZXM\207\1\63\20F%" "D\63$\241\230Fs*\212\311\220\0\64\20F%D\31jIT\311\222,\31\306\264\2\65\17F%" "DqH\253\203\234\246b\62$\0\66\17F%D\65\205i:(\241c\62$\0\67\13F%Dq" "-\246\305\264\11\70\20F%D\63$\241\61\31\222\320\61\31\22\0\71\16F%D\63$\241\61\31\324" "\306h\2:\11\342lD\61\304C\0;\12\42\355C\61\304J\242\0<\11%)D\231u\355\0=" "\11\246\244Dq'\16\3>\11%%D\221v\353\10\77\17F%D\63$\241\230\206\325\34L#\0" "@\22F%D\65eR\242$K\244DJ$-\361\20A\16F%D\245E-\241\70\14\242c\0" "B\16F%D\61(\241qXB\307a\1C\16F%D\63$\241\265\243\230\14\11\0D\16F%" "D\61DY\22\372-\31\42\0E\15F%DqH\253\203\222\266\16\3F\14F%DqH\253\203" "\222v\5G\16F%D\63$\241\265\64\204\66e\11H\13F%D\21:\16\203\350\61I\13E)" "D\61Ha\77\15\2J\16G%D\65\210qOY\224e\33\0K\21F%D\21jIT\311D" "\61\311\242Z\22\6L\11F%D\221\366\327aM\15F%D\21\212\323\20-\36\35\3N\20F%" "D\21n\233\22)\221\224H\211v\14O\14F%D\63$\241\77&C\2P\15F%D\61(\241" "qX\322\256\0Q\27g\345C\63Da\22&a\22&a\22&\211\222H\322\220\3\2R\20F%" "D\61(\241qX\242Z\222%\241\30S\15F%D\63$\241\331QL\206\4T\12G%Dq\310" "\342\376\6U\13F%D\21\372\307dH\0V\21G%D\221Z\223,\312\242\254\22&i\234\1W" "\15F%D\21zq\231\206h\24\3X\17F%D\21\212I\324&jQK(\6Y\16G%D" "\221\252I\26e\225\64\356\6Z\13F%Dq-\366\232\16\3[\12\203\361C\61D\375\323\0\134\14" "F%D\221\306\325\70\215\253\1]\12\203\345C\61\365OC\0^\11fdF\245EI\30_\7'" "\344Cq\10`\7c\250F\221\25a\16\6%D\63$a\232\14\243MY\2b\16f%D\221\266" ",\232\350\270)\13\0c\15\6%D\63$\241\332\61\31\22\0d\14f%D\333\262h\243\67e\11" "e\17\6%D\63$\241\70\14j\61\31\22\0f\14e%D'\205\245A\12{\2g\23f\245C" "\233,Z\222%Y\264\245C\22\212\311\220\0h\14f%D\221\266,\232\350c\0i\13e)D\25" "\346\210\330\247Aj\14\245\245CYG\304>J\221\4k\21f%D\221\266%Q%\23\223,\252%" "a\0l\12e)D#\366O\203\0m\22\7%D\261(Q$ER$ER$ER\1n\13" "\6%D\221,\232\350c\0o\14\6%D\63$\241\217\311\220\0p\16F\245C\221,\232\350\270)" "K\232\2q\14F\245C\263h\243\67eI\13r\13\6%D\221,\232\250v\5s\15\6%D\63" "$\241\354\230\14\11\0t\13E%D\25\226\6)\354*u\12\6%D\21\372MY\2v\14\6%" "D\21\32\223\250\67Q\2w\21\7%D\221J\221\24I\221\24I\221T\261\0x\17\6%D\21\212" "I\224\211Z\224\204b\0y\16F\245C\21zL\42KZ\31\22\0z\12\6%Dq\15{\35\6" "{\16\244\251C\245da\26\25kQ\26\12|\7\301\261C\361A}\17\244\251C!fQ\26\226j" "a\226H\0~\12g$F\243I\221\246\0\177#\20\242\203\221\364;I\347\244\223\16I\66%a\32" "%C\222MI\230NC\62\354\234tN:)\351\7\200$\20\242\203\221\364;I\347\244\223\66i\231" "\222(\211\242C\22\15a\224D\305(YtN:'\235\224\364\3\201%\20\242\203\221\364;I\347\244" "\223J\322\62%Q\22EC\22%\247$J\322(\222\62\235\223\316I'%\375\0\202\42\20\242\203\221" "\364;I\347\244\223N\321\20%Q\22E\17C\224\204Q\64\205\321\316I\347\244\223\222~\203$\20\242" "\203\221\364;I\347\244\223*S\64(\245$\252(\323\60DI\224D-S\264s\322\71\351\244\244\37" "\204%\20\242\203\221\364;I\347\244\223\226(\231\224H)\205Q\242D\211\22U\242l\211\222I\347\244" "s\322II\77\205%\20\242\203\221\364;I\347\244\223*C\222\15I\61M\224!\311\246$L\243d" "H\206\235\223\316I'%\375\0\206\37\20\242\203\221\364;I\347\244\323\246I\31K\231i\330\302$\212" "N\321\316I\347\244\223\222~\207$\20\242\203\221\364;I\347\244\223\206hR\306R\64D\322\60\344@" "\22EC\62E;'\235\223NJ\372\1\210 \20\242\203\221\364;I\347\244\223*\323\62\65\17Q&" "M\325,*M:'\235\223NJ\372\1\211!\20\242\203\221\364;I\347\244\323\242\344\242D\305p\210" "\302D\211\212\245\222\235\223\316I'%\375\0\212!\20\242\203\221\364;I\347\244\223\262dR\266\250\232" "EY\244\324\302\64\214\354\234tN:)\351\7\213\42\20\242\203\221\364;I\347\244\223\246p\231\222\60" "\212\246\60\32\302RqH\26\235\223\316I'%\375\0\214\42\20\242\203\221\364;I\347\244\223\246\60\32" "\242$\214\242)\214\206\260T\34\42E\347\244s\322II\77\215\37\20\242\203\221\364;I\347\244S\267" "P\213\352\320\26jI\226C\215:'\235\223NJ\372\1\216\36\20\242\203\221\364;I\347\244\323\246\345" "\230\3\231\213\26&\351t\330\71\351\234tR\322\17\217\35\20\242\203\221\364;I\347\244\323\246\345\230\3" "\231\213\26\226^tN:'\235\224\364\3\220\42\20\242\203\221\364;I\347\244\223\266i\230\222\60\215\222" "T\231\222\34\210\266e\321\71\351\234tR\322\17\221!\20\242\203\221\364;I\347\244\223\246Z\62%Q" "\244M\265d\214\262\252\66\350\234tN:)\351\7\222!\20\242\203\221\364;I\347\244\223\246\312)\211" "\302h*)c\224\244\251\64\354\234tN:)\351\7\223!\20\242\203\221\364;I\347\244\323\226iY" "\243\34\320\62I\213\322l\213&\235\223\316I'%\375\0\224 \20\242\203\221\364;I\347\244\323\246%" "\32\302R\61\34\206\260\224MK\264s\322\71\351\244\244\37\225!\20\242\203\221\364;I\347\244\323*Y" "\244X\262\64\351I\311\22k\226d\221\316I\347\244\223\222~\226!\20\242\203\221\364;I\347\244\323\226" "M\31\243$\312\244\303\226\204Q\64\205\321\316I\347\244\223\222~\227$\20\242\203\221\364;I\347\244\223" "\206dS\306(\211\242!\231\206!,EC\22F;'\235\223NJ\372\1\230!\20\242\203\221\364;" "I\347\244\323&m\30\243$\226J\212\226Da\264I\213\316I\347\244\223\222~\231#\20\242\203\221\364" ";I\347\244\323\244I\31\262\60+%J\66%Q\222E\332\244\354\234tN:)\351\7\232\37\20\242" "\203\221\364;I\347\244\323\246\345\230\246R\32iI\32n\313\242s\322\71\351\244\244\37\233\37\20\242\203" "\221\364;I\347\244\323\246\345\230\206\251\26\355@\224.\323\242s\322\71\351\244\244\37\234\37\20\242\203\221" "\364;I\347\244S\227A\222\342\34\22C\65\313\221\61\324\71\351\234tR\322\17\235!\20\242\203\221\364" ";I\347\244\323\264i\230\222\60\215\42)\233\302$\226\266A\347\244s\322II\77\236 \20\242\203\221" "\364;I\347\244\23\247,\222*\346))Ia\26\207Y\244s\322\71\351\244\244\37\237#\20\242\203\221" "\364;I\347\244\323\244m\230\222(I\207d\312\246$L\243$\35tN:'\235\224\364\3\240\6\0" "\240G\1\241\11A\61D\241\14C\0\242\22G%D\27\207\203\22ER\26eQe\20\343\14\243\16" "G%D\267\305\305A\214\253\203\42\6\244\20\6eD\21&CT\11\305$\212\206$\14\245\22G%" "D\221&Y%\315\206!\313\206!\213k\0\246\11A\61D\61DC\0\247\22F%D\63$\241<" "$\241\230\14\261\230\14\11\0\250\10D(G\21I\1\251\27H!D\65da\22Y\242D\11\225P" "\211\22IJ\302l\210\0\252\14\345hE\263&\203\226\14\351 \253\15&%D\325%j\211\262\250-" "j\254\7\206$Dqm\255#\20\242\203\221\364;I\247-\221\66\204QR\224\206(\322\222\250\70\65" "\351\234t\206!\325\71\351\244\244\37\256\30H!D\65da\222LJ\224(Q\242LJI\211\222b" "\66D\0\257\6&\344Fq\260\12\204\250E\243DR\242\0\261\16'eD\27\327\206!\213\353\330\60" "\4\262\14\345$E\263da$e\341 \263\14\345$E\263da\262j\311\2\264\10c\254F\225\224" "\0\265\24H\241C\23Fa\24Fa\24FadJ\244$\316\1\266\30g\345C\63\34\222dH\222" "!\211\226\60\11\223\60\11\223\60\11\223\4\267\7B,E\61\4\270\7C\250C\265\0\271\13\345$E" "\225II\330\64\10\272\13\345hE\263d\266d\36\4\273\17&%D\21\265EmQ\22\265DM\0" "\274\22F%D\223mIT\311\222\60\252(\25i\10\3\275\22F%D\223mIT\311\222\60\311\224" "\232\226D\3\276\22F%D\241E\225(\223\224\60\252(\25i\10\3\277\17F%D\225\346`\32V" "C\61\31\22\0\300\20\306%D#\353\24-j\11\305a\20\35\3\301\20\306%D'\351\64-j\11" "\305a\20\35\3\302\21\306%D\245E\71E\213ZBq\30D\307\0\303\20\306%D#\331)Z\324" "\22\212\303 :\6\304\20\306%D\23\265S\264\250%\24\207At\14\305\21\306%D\245E\231\216i" "QK(\16\203\350\30\306\25G%D\65(\265(\213\262a\220\262(\213\262(\213\206\0\307\17\206\245" "C\63$\241\265\243\230\14a\246\1\310\20\306%D#\353\360\60\244\325AI[\207\1\311\20\306%D" "'\351\224aH\253\203\222\266\16\3\312\20\306%D\245E\71<\14iuP\322\326a\313\20\306%D" "\23\265\303\303\220V\7%m\35\6\314\15\305)D\243\352\330 \205\375\64\10\315\15\305)D\245\350\360" " \205\375\64\10\316\15\305)D#\325\301A\12\373i\20\317\17\305)D\21%Q\16\16R\330O\203" "\0\320\25G!D\63d\245\60\11\7)\11\223\60\11\223,\32\42\0\321\23\306%D#\331\341p\333" "\224H\211\244DJ\264c\0\322\17\306%D#\353\204!\11\375\61\31\22\0\323\17\306%D'\351\244" "!\11\375\61\31\22\0\324\17\306%D\245E\71aHB\177L\206\4\325\17\306%D#\331\11C\22" "\372c\62$\0\326\17\306%D\23\265\23\206$\364\307dH\0\327\14\246\244D\21&Q\246EI\30" "\330\25\206\345C\233,Z\222M\211\224(\221\22mI\246,)\0\331\15\306%D#\353p\350\37\223" "!\1\332\15\306%D'\351\224\320\77&C\2\333\16\306%D\245E\71\34\372\307dH\0\334\15\306" "%D\23\265\303\241\177L\206\4\335\20\307%Dg'\246j\222EY%\215\273\1\336\20f%D\221" "\246C\224%\241-\31\242\264\12\337\21F%D\63eI\226D\25)KBKd\1\340\20\206%D" "#\353\204!\11\323d\30m\312\22\341\20\206%D'\351\244!\11\323d\30m\312\22\342\21\206%D" "\245E\71aH\302\64\31F\233\262\4\343\20\206%D#\331\11C\22\246\311\60\332\224%\344\21\206%" "D\23\265\23\206$L\223a\264)K\0\345\22\246%D\245E\231N\31\222\60M\206\321\246,\1\346" "\23\7%D\63(Q-J\206!\312\242,\252\14\12\0\347\16F\245C\63$\241\332\61\31\302L\3" "\350\21\206%D#\353\204!\11\305aP\213\311\220\0\351\21\206%D'\351\244!\11\305aP\213\311" "\220\0\352\22\206%D\245E\71aHBq\30\324b\62$\0\353\21\206%D\23\265\23\206$\24\207" "A-&C\2\354\13\205)D\241\352\250\330\247A\355\14\205)D\245\350\4\261O\203\0\356\14\205)" "D#\325Q\261O\203\0\357\15\205)D\21%Q\216\212}\32\4\360\21\206%D#eZ\22ei" "\62\214\36\223!\1\361\15\206%D#\331\341d\321D\37\3\362\16\206%D#\353\204!\11}L\206" "\4\363\16\206%D'\351\244!\11}L\206\4\364\17\206%D\245E\71aHB\37\223!\1\365\17" "\206%D#\331\11C\22\372\230\14\11\0\366\17\206%D\23\265\23\206$\364\61\31\22\0\367\12\346d" "D\245\23\356\4\11\370\23F\345C\233\14I\66%R\242DJ\264%C\222\2\371\14\206%D#\353" "p\350\67e\11\372\14\206%D'\351\224\320o\312\22\373\15\206%D\245E\71\34\372MY\2\374\14" "\206%D\23\265\303\241\337\224%\375\20\306\245C'\351\224\320c\22Y\322\312\220\0\376\17\246\245C\221" "\266,\232\350\270)K\232\2\377\20\306\245C\23\265\303\241\307$\262\244\225!\1\0\0\0\14#\360\7" "\20%\332\5\314\377\377 \240\22F%D\63$ieP\262$\34\262\64\35\2 \241\23F%D\227" "$\303\224(\275(\221\22M\312\226\1 \242\23F%D\65e\242\232$\213\224dI(E\13\0 " "\243\25H!D\65L\71\220\3\71\60h\71\220\16c\16\244\0 \244\21G%D\267\305\341\260\205\303" "\26\247\203\42\6 \245\25G%D\35\17\211\22)\222\42ER\244HK\264D\1 \246\27G%D" "\223EY$%\303\220\264\14C\22I\221\224EY\2 \247\26G%D\241d\211\226\14\313\244H\225" "R$ER$-\0 \250\26G%D\61FY\224L\322\22%\245$J\242H\212\244\5 \251\27" "GeD\223EY\224%\303\220\264\14CbR\244,\312\22\0 \252\25\7!D\61DZ\242T\224" "\212RQ*J\246\14\11\0 \253\30\247\245C\33\16i\264\324\224\60\11\223\60\11\223LZrdX" "\0 \254\22F%D\247EI\70H\341 \245q\224)\0 \255\24G!D\23&YTKBq" "\30\222b\224\225\302\0 \256\16G%Dq\310\342x\232\247\271\15 \257\26\207\245C\61FY\224E" "Y\224EK\244H\212\264,q\11 \260\24\206\245C\63eI\226dQ\22JIEJ\64\261\11 " "\261\32\210!D\63ha\62\14J\230\14\203\22F\203\226\3\71\220\3\71\20\3 \262\31\306\245C\225" "\206CRR\42%K\262$Y\42%R\22e\211\322\14 \263\27H!D\247Fa\24\15\203\22&" "\303\240\204Q\30\205Q\230\0 \264\27H!D\65da\16\344@\62\14\222\70\14J\16\204\331\20\1" " \265\31\306\245C\225\206CRR\42%K\262$K\262$R\242d\310\322\14 \266\26G%DS" "L\302$\33\246$L\302$L\302$J\42\5 \267\31\207\241C\65Da\22F\71\240\3Q\22)" "\25\245\62\14ISR\2 \270\15\7!Dq\310\201C\26w\3 \271\32\252\255\203\361\20\212\303!" "\325\21y\210w`Gr,\307r,\307\22\0 \272\21g!D\25WBcR\264)YT\233\0" " \273\23G!D\223&\341\260U\302\244e\311\342,\233\0 \274\16\345$D\25fKEI\224D" ") \275\22F%D\63DY\222%\331\60\205\203\224\26\1 \276\25\207!D\225d\203\322\242T\224" "\212\334\16\344@\70\14\1 \277\34\307\241C\225\204I\64La\22&a\62Ha\22&a\22\16C" "\226\204I\4!\3\27\307!D\223&a\222\346\300\20\205I\230\304\35\223\60\32\22\0!\11\22\307!" "D\223&a\222\306\303\22\227\7)\356\12!&\20G%D\63(\251\327$\253\204I\264\14!\220\15" "\247$E\225\246\303\220\344@\10!\221\14\305\251C\225-Ma\377\11!\222\15\247 E\231\3\311\60" "\244%\0!\223\15\305)D\25\366\237\222\312\26\1!\224\17\250 EU\13\223aP\302,\212\0!" "\225\17\205)D\225-MaOIe\213\0!\226\15\306\344D\61Db\222Eq\1!\227\15\306\344" "D\65\204Z\22U\302\24!\230\15\306\344D\21\227\262$\224\206\0!\231\15\306\244D\33&Q%\23" "\207\10!\232\22'\245D\31\207I\26E\303\220Da\22\227\0!\233\21'\241D\25W\302(\31\206" "\250\226\204q\10!\234\21\256h\205\261\203:\60%i\26fi\270\3!\235\21\256`\205\17N;\240" "di\242f\71\66\2!\236\17\250 EU\213\262aP\242\64\212\0!\237\17\305\251C\225-M\331" "\322\24\366\23\0!\240\17\250 EU\215\222a\320\242,\212\0!\241\20\345\351C\25\366\247\244\262E" "Ie\213\0!\242\14\247$E\225%Y\62h\35!\243\16\247 E\221\265\15J\226d\21\0!\244" "\15\246$EU\311\206!\311\242\2!\245\15\205)D\225-Ma\77\15\2!\246\16\246$E\21\325" "\222a\310\222(\2!\247\16\205)D\61Ha\77%\225-\2!\250\20\205)D\225-Ma\247\244" "\262E\203\0!\251\16\307$E\233U\302a\210r \4!\252\15\307$E\223fQ\30\15k\11!" "\253\17\307$E\233%M\311\60D\305$\2!\254\20\307$E\223&\245$\212\206\251\226D\0!\255" "\17\250 EUK\224dZ\302,\212\0!\256\26(\241D\231\3i\242EI\62\14J\224d\211\234" "\3\31\0!\257\21\206%D\221\66U$%\252\326\222\322\30\1!\260\15e\245C\225eC\324\22\366" "\1!\261\16e\251C\225F\203\224\224\302\36\1!\262\15E%E\331SR\32\244\64\2!\263\15E" ")E\21\366\22\225\206\254\4!\264\15\250\240Dq\7\322\244\70G\0!\265\15E%E\331SR\32" "\226\64\2!\266\16\250\240D\67d\241RJ\266(\5!\267\16\250\240D\63daTI\264\71\2!" "\270\16\6\345Dq\36\42\61\311\242\270\0!\271\23f%D\221d\342\60\210I\216&\341\60\210Z\22" "!\272\20\306dD\223\14\221\22%\242\230\14\11\0!\273\16\306dD\261D\226H\24\223!\1!\320" "\14\246$E\25\16\363 e\0!\321\27\205)D\225%\211\245\224DI\224DI\224DI\224DI" "\2!\322\14\246$E\27\15\362\60F\0!\323\27\205)DSJ\242$J\242$J\242$J\242$" "\261\324\42\0!\324\16\250 EU\33\226\70\31\266(\2!\325\25\205)D\225%\211\245\224DI\224" "DI\224$\226Z\4!\326\20\306\344D\61DI\246DI\61\11\23\0!\327\17\306\344D\65dI" "\224(\25%\14\1!\330\17\306\344D\23&aRJ\264$\32\2!\331\16\306\344DYQ*J\224" "dC\4!\346\20\350\340D\27\253\311\60'\311 \351@\10!\347\27\207%D\227&Y\345\224\204I" "\230\204I\230\204I\230\204\23\0!\350\20\350\340D\231\3\322\240\224\207%\225\63\0!\351\27\207%D" "\65&a\22&a\22&a\22&\321\262d\225\64\3#\351\27+)\204\221\206\266\323\20\15\311\240\14" "\247!\331&QKC\0#\352\27+)\204\231f\242\264-C\64\134\6e\210\206h\333D\61\15#" "\353\27i-\204\231\3\353\240\15C\62\334\341\34X\7m\30\222\341\0#\354\27i\355\203\361\62\14\331" "\240\356@\16\17\227a\310\6u\7B\0#\355\30-%\204\221\246\243\70d\7i\210\206eP\6i" "\210\206\354h-#\356\31-%\204\221\246\242\270\35\242!\32\224A\31\246!\32\264C(\256\5#\357" "\31*-\204\221Fc\64d\321 E\303\22\15R\64d\321\30\251Q\0#\360 \313\351\203\33K\221" "\242\14\312\222&\265J\30\212\241\30j\251\24'\71\220\245\341\60d\27\0#\361\35\253)\204\251C:" "\62(R\272d\225\60\24C\61\324!\35Jr K\323A\3#\362\31k)\204\67\250\265\34H\242" "XK\305P\207t(\311\201,M\7\15#\363#\255%\204\361!\312\201\60\7\302(\211R%\321\1" "E\207\222\34Rt \255\25\225\212\230t\32\36\2#\364\22f\61\204\33j\323\220\14\7e\220\206l" "T\3#\365\23f\61\204\221\212\333\20\15\312pP\206h\23S\0#\366\21\313\250\204\233C;\60\250" "\303\220\15\227\341 #\367\21\313\250\204\361\240\14\267aH\7\35\330\241\24#\370\27f\65\204!\15\321" "\20\15\321\20\15\321\20\15\321\20\15\321\20\11#\371\14J-\204\361\377\377\377\77\4#\372\23J-\204" "\65l\303\240\14\377\377/\303\240\15\23\0%\200\13\10\241E\361\377\377C\0%\201\11H\240C\361C" "\0%\202\11\210\240C\361\177\20%\203\11\310\240C\361\377\37%\204\13\10\241C\361\377\377C\0%\205" "\13H\241C\361\377\377\177\20%\206\13\210\241C\361\377\377\377\37%\207\15\310\241C\361\377\377\377\377C" "\0%\210\15\10\242C\361\377\377\377\377\177\20%\211\15\7\242C\361\377\377\377\377C\0%\212\13\6\242" "C\361\377\377\377\37%\213\13\5\242C\361\377\377\177\20%\214\13\4\242C\361\377\377C\0%\215\11\3" "\242C\361\377\37%\216\11\2\242C\361\177\20%\217\11\1\242C\361C\0%\220\13\4\262C\361\377\377" "C\0%\221\31\7\242C\221\205\231\26fZ\230ia\246\205\231\26fZ\230ia\26%\222\42\10\242" "C\221\64%\25\245)\251(MIEiJ*JSRQ\232\222\212\322\224T\224\246\244\1%\223 " "\10\242C\261,\311AY\222\203\262$\7eI\16\312\222\34\224%\71(KrP\226d\21%\224\11" "H G\361C\0%\225\11\1\276C\361C\0%\226\11\4\241C\361\177\20%\227\11\4\261C\361\177" "\20%\230\11\4\241E\361\177\20%\231\27\10\242C\61\204C\70\204C\70\204C\70\204C\70\374\377\177" "\10%\232\37\10\242C\61\204C\70\204C\70\204C\70\204C\216\14\341\20\16\341\20\16\341\20\16\341\20" "%\233\26\10\242C\361\377\377\7q\10\207p\10\207p\10\207p\10\1%\234\27\10\242C\361\377\377C" "\70\204C\70\204C\70\204C\70\204C\0%\235\11\4\261E\361\177\20%\236\37\10\242C\71\204C\70" "\204C\70\204C\70\204\303 \16\341\20\16\341\20\16\341\20\16!\0%\237\26\10\242C\71\204C\70\204" "C\70\204C\70\204\303\377\377\17\2%\240\12\347$D\361\377\37\2%\241\14\347dDqP\275\16\203" "\0%\242\15\347dD\63(\251\327dP\0%\243\20\347dDqP\225EY\224E\35\6\1%\244" "\16\347dDqP\207\353p\35\6\1%\245\22\347dDqP*JE\251(\25\245\62\14\2%\246" "\20\347dDqP*\303\245\62\134*\303 %\247\21\347dDqP\242)\232\22%\232\242a\20%" "\250\21\347dD\361\224H\221\22\15Q\42E\303 %\251\22\347dDqP*K\262T\226d\251\14" "\203\0%\252\11\204\250D\361C\0%\253\12\204(E\61H\322 %\254\11\207$E\361\77\4%\255" "\13\207$EqP\325a\20%\256\11\344\250D\361\77\4%\257\13\344\250D\61H\236\6\1%\260\14" "h E\65,\303\62L\0%\261\14h E\65,a\62L\0%\262\15\306\344D%jC\64$" "\303\3%\263\15\306\344D%jQK\70\14\1%\264\12f\344D\245\15\311\60%\265\12f\344D\245" "E\311\60%\266\15\306\344D!\16\321\360!\22\1%\267\15\306\344D!&Rv\221D\0%\270\12" "\204(E!\15\207\10%\271\12\204(E!%\207\10%\272\15\246\344D!\16\321p\210D\0%\273" "\15\246\344D!&R\266H\42\0%\274\15\306\344D\361e\210\206L\224\0%\275\15\306\344Dq\10" "\223\250M\224\0%\276\12f\344Dq\31\62\11%\277\12f\344Dq\211\62\11%\300\14\306\344D)" "\15\37\242!\24%\301\15\306\344D))\333\26)\241\0%\302\12\204(E\65\34\42\1%\303\12\204" "(E\65$K$%\304\14\246\344D)\15\207h\10\5%\305\14\246\344D))[\244\204\2%\306" "\20\347\244D\227n\203\62\14\311\240\255\31\0%\307\17\347\244D\227&Y%M\262J\232\1%\310\17" "\347\244D\227&Y\322\262tK\322\14%\311\20\347\244D\265U\22IY$\245\226M\0%\312\20F" "eD%jQK(&Q\233(\1%\313\16\347\244D\265URk\222e\23\0%\314\20\347\244D" "\225\344P\232\3i\16%\21\0%\315\20\347\244D\265)J\213RQZl\23\0%\316\20\347\244D" "\265U\242H\251H\225,\233\0%\317\16\347\244D\265\15\312\360\227A\233\0%\320\20\347\244D\265I" "\311\66dC\226H\331\4%\321\20\347\244D\265EJ\66dC\266D\332\4%\322\17\347\244D\265U" "Ru\30\224A\233\0%\323\20\347\244D\265\15\312\60\250j\222e\23\0%\324\20\347\244D\265%K" "\64H\203\232d\331\4%\325\20\347\244D\265EJ\66d\303!\31\264\11%\326\13\344\244D\245\14_" "&\1%\327\13\344\260D!-\303\27\11%\330\21\10\242C\361\377\77\15\342\20\16\322\360\377\37%\331" "\27\10\242C\361\377\207hP\224C\242\14\311\242\14\322\360\377C\0%\332\16\10\241E\361\377\207hP" "\224C\22%\333\20\10\241C\221\14\311\242\14\322\360\377C\0%\334\12\204dE\245DY\6%\335\11" "\204pE!\326\2%\336\12\204\260DWJ$\0%\337\12\204\244D\221\205\241\0%\340\12\207dE" "\265UR\65%\341\14\207\244D\221\252I\226M\0%\342\15\306\344C\33j\323\220\14\7\1%\343\15" "\306\344C\221\212\333\20\15\312\60%\344\15\306\244E\361\240\14\321&\246\0%\345\15\306\244Eq\31\244" "!\33\325\0%\346\13\245\244D\263d\266d\1%\347\16\306\344D\361\64DC\64D\303\20%\350\16" "\306\344Dq\210\206h\210\206h\70%\351\16\306\344D\361\220\14\321&\16C\0%\352\16\306\344Dq" "\10\265iH\206C\0%\353\20\307\344Dq\220\42)\222\42)\32\6\1%\354\17\347\244D\227&a" "\222\225\222\326a\20%\355\16\306\244D%jJ\244$\323\60\4%\356\17\346\244D%j\211\224(\321" "\20\15\7%\357\37\255\351\203\273#\232\232\3Y\16\325\241$\7uP\7\223\34\252CY\16\244\232\216" "\254\0%\360\16\306$DqH\242!\22\305a\10%\361\16\306$Dq\10\305!R\242a\10%\362" "\16\306$Dq\10MC\224\14C\0%\363\16\306$Dq\210\22i\10\305a\10%\364\23\10!D" "\65dI\224D\331\240\311r\22fC\4%\365\23\10!D\65da\22\313\203&eI)\33\42\0" "%\366\23\10!D\65da\22\333\6-J\242$\33\42\0%\367\23\10!D\65dQR\213\264A" "\226\223\60\33\42\0%\370\16\306\244Eq\310\222\250\222\211)\0%\371\15\306\244Eq\311\242Z\22\252" "\1%\372\15\306\344C\221\212I\26\325\222a%\373\13\306\344Cq\10\35\207!%\374\11\306$D\361" "\377\1%\375\12\204(D\61H\322 %\376\11\245dD\361\37\2%\377\15\306\344C\33jIT\311" "\206!&\0\23\207%DW\252d\71v\220\6m\307*Q-\3&\1\15\210\240E\25/\312\60(" "\303\2&\2\16\7\245D\265\15\312\60dqk\10&\3\64\20\242\203\221%C\224CC\216$\303\240" "\245aTK\242$N\342(M\242$\215\42)\311\201\260\222\15;\24\347@\230\205C<\204\265\34\210" "shX\1&\4\26g%D\223EYT\213\262$L\242\64\22\243,\12E\0&\5\17\307\344D" "\27g\303\20m\212\224%\0&\6\20\347\344D\27g\313\222EII\221\262\4&\7\14%)D\231" "u\255d\322\0&\10\20\6%Dq\10\265$\252dQ\242M\3&\11\21\10!D\65da\22K" "\236\223\60\33\42\0&\12\20\310\240D\247Fa\224IJ))&\0&\13\20\310\240D\23&\245$" "\221\264(\214R\15&\14\15\305\244D\231ER%\212$\0&\15\21'%D)FY\24\212\241\30" "eQ(\2&\16\16\307dD\63(\232\216\264h\303\1&\17\21\347dD\63(\251\262$\203\22E" "\352\60\10&\20\30\213)\204\361\35\322!\35\322!\35\322!\35\322!\35\322\241\341\1&\21\33\213)" "\204\361\35\322!\35\30\222PQ\62I\211\64%\21\225U\221uhx&\22\33\214)\204\361!\307t" "L\21\25\311m\310D\333\220I.\242\242c\303C\0&\23\21E)D\221iI)\311\302,\211\222" "\232\26&\24\24\207\245D\231(\71\22\245\321\66(\303\220\305\255!\0&\25 \254)\204\325\30U\243" "rT\215\212Q\235\66\14Q\62\34\22eX\22\35It`\32\206\20&\26\33\253)\204\233CI\16" "di-\7\222\34\322!\35\322!\35\322!\35\32\36&\27\25\253)\204\233C;\60\250\303\220\15\227" "\341\377\377\377C\0&\30#\255\345\203\233\344\320\240#\203*M\312\20EC\62\34\224!\212\206D\313" "\344\34\315\321\34\314\301\34\2&\31\42\215%\204\217\306SmPj\303R\32\206$\31.\322\60(\333" "\60D\341\60\245\203\24o\71\230\0&\32\14\207\244Dq\33\244A[\0&\33\14\207\244D\63\34\244" "A\333\0&\34\13\207\244Dq+I\331\2&\35\15\344\250DW\31\24IJ\24\0&\36\15\207\244" "D\63\14Y\24i\33\0&\37\14\344(D\243D\322\222l\5&T\24g%D\227\256\331\62$\213" "\24I\225\226aP\207A&U\24G%D\27gQ\245)iY:\15R\26\15\12\0&V\22'" "%D\221T\206\253\232dQ\226\244\352\60\10&W\24G%D\227&Y)\213\262(\253D\313\220\16" "\203\0&X\23f%D\33\15I&\212\311\22U\62Q\34\206\0&Y\17\6%D\245EmZ\324" "\22\16C\0&Z\22g%D\227\256\331\62$\213\24I\225\226\341\17&[\24G%D\27gQ\245" ")iY:\15\322 \15\12\0&\134\20'%D\221T\206\77$\203\64(\303\37&]\21G%D" "\227n\212\224E\212\64h\323\360\7&^\22f%D\33\15\211\62<(\203\64$\303\37\4&_\20" "\6%D\245\15\321\220iC\64$\303\3&`\20G%D\27\247\333\240\14\177\31\304t\2&a\20" "'%Dc\211\42\325\232d\225\64\316\0&b\21E)D\25fI\224\324\264\244\224da\4&c" "\20G%D\65^\263\341C\222hq:\1&d\21G%D\27\247IVI\255\311 \246\23\0&" "e\17'%Dc\31\376C\62hk\234\1&f\20E)D\25f\323\62\34\222i\13#\0&g" "\22G%D\65&\341\232-CrI\264\70\235\0&\200\24)m\204\361\220\3:\240\3Z\246\3:" "\240\3\17\1&\201\24)m\204\361\220\3:\240\244:\240&:\240\3\17\1&\202\24)m\204\361\220" "\3J\252\3Z\246\3j\242\3\17\1&\203\25)m\204\361\220\3J\226\350\200\16\350\200\222%:\360" "\20&\204\25)m\204\361\220\3J\226\350\200\226\351\200\222%:\360\20&\205\26)m\204\361\220\3J" "\226\350\200\222%:\240d\211\16<\4'\23\31M\345\203\217\346`\16F\71\222\345@Z\16s$\312" "\241$\7s\10'\24\34o\341\203\17\347\360\222C\313\16L\363x\335v`\331\221a\307\206\34\325!" "\0'\25\31ki\204\223\3\311\272l\227u\320\201\35\30\324e\273\254K\16$\0'\26-\357\341\203" "\227\3\351m\320\6e\30\222aH\206\207l\70\250\303\35\70\344\300\353p\320\206\207d\30\222aH\6" "m\320\326\65\7\62\0'\27\35\254%\204\241#VM[\25\35\331\241\35\261\3\222*Z%\35Pt" "D\311\61\0'\30!\314\345\203\241#\203:iC\266\314\203\216\354\310\240\3\312:\215\342\264.:\60" "\350H\224c\0'O \214m\204\361\20\345H\224#C\216\14\71\62\344\310\220#C\216\14\71\62|" "\32\16\321p\10'P \214m\204\65\34\242\341\17:\62\344\310\220#C\216\14\71\62\344\310\220#C" "\216D\303!\2'Q \214m\204\361\20\345\210\222#C\216\14\71\62\344\310\220#C\216\14\71\62|" "\31\16\322p\10'R \214m\204\65\34\222\341\337\221!G\206\34\31rd\310\221!G\206\34\31r" "D\31\16\21\0\0";
15,219
6,663
# mode: run # tag: global, nameerror try: from heapq import * # just to confuse the compiler except ImportError: pass def f(a): """ Py<=3.3 gives 'global name ...', Py3.4+ only 'name ...' >>> f(1) # doctest: +ELLIPSIS Traceback (most recent call last): NameError: ...name 'definitely_unknown_name' is not defined """ a = f a = definitely_unknown_name
156
1,338
/* * Copyright 2010, Haiku. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ #ifndef TEXT_DATA_BASE_H #define TEXT_DATA_BASE_H #include <Entry.h> class TextWriteDataBase { public: virtual ~TextWriteDataBase() {} virtual status_t InitCheck() = 0; virtual status_t AddDocument(const entry_ref& ref) = 0; virtual status_t RemoveDocument(const entry_ref& ref) = 0; virtual status_t Commit() = 0; }; #endif // TEXT_DATA_BASE_H
194
678
<reponame>bzxy/cydia /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/iPodUI.framework/iPodUI */ #import <iPodUI/XXUnknownSuperclass.h> @class NSArray, NSMutableArray; @interface IUActionRowDataSource : XXUnknownSuperclass { NSMutableArray *_rows; // 4 = 0x4 } @property(readonly, assign, nonatomic) NSArray *actionRows; // G=0x39151; @property(readonly, assign, nonatomic) unsigned count; // G=0x391c9; - (unsigned)removeActionRowWithTag:(int)tag; // 0x393b9 - (void)insertActionRow:(id)row atIndex:(unsigned)index; // 0x392fd - (unsigned)indexOfActionRowWithTag:(int)tag; // 0x39209 - (void)enumerateActionRowsUsingBlock:(id)block; // 0x391e9 // declared property getter: - (unsigned)count; // 0x391c9 - (void)addActionRow:(id)row; // 0x39189 // declared property getter: - (id)actionRows; // 0x39151 - (id)actionRowAtIndex:(unsigned)index; // 0x39131 - (void)dealloc; // 0x390dd @end
365
690
<filename>livelessons-security/edge-service/src/main/java/com/example/EdgeServiceApplication.java package com.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoRestTemplateFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.security.Principal; import java.util.Map; import static org.apache.commons.lang3.BooleanUtils.and; @SpringBootApplication public class EdgeServiceApplication { @Bean OAuth2RestTemplate restTemplate(UserInfoRestTemplateFactory templateFactory) { return templateFactory.getUserInfoRestTemplate(); } public static void main(String[] args) { SpringApplication.run(EdgeServiceApplication.class, args); } } @Configuration @EnableOAuth2Sso class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.antMatcher("/**").authorizeRequests() .antMatchers("/" , "/login**", "/webjars**").permitAll() .anyRequest().authenticated() .and() .logout().logoutSuccessUrl("/").permitAll() .and() .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); } } @Configuration @RestController @EnableResourceServer class PrincipalRestController extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.antMatcher("/hi").authorizeRequests().anyRequest().authenticated(); } @RequestMapping("/user") Principal principal(Principal p) { return p; } } @RestController class GreetingsEdgeServiceRestController { private final RestTemplate restTemplate; @Autowired public GreetingsEdgeServiceRestController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @RequestMapping(method = RequestMethod.GET, value = "/hi") public Map<String, String> greet() { return this.restTemplate.exchange("http://localhost:8080/hi", HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() { }) .getBody(); } }
1,131
384
<reponame>hejamu/gromacs /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2010,2012,2013,2014,2015 by the GROMACS development team. * Copyright (c) 2016,2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \file * \brief * Declares common types used in selections. * * \author <NAME> <<EMAIL>> * \ingroup module_selection */ #ifndef GMX_SELECTION_SELECTIONENUMS_H #define GMX_SELECTION_SELECTIONENUMS_H #include "gromacs/utility/flags.h" /*! \brief * Defines the type of covered fraction. * * \inpublicapi */ typedef enum { CFRAC_NONE, /**< No covered fraction (everything covered). */ CFRAC_SOLIDANGLE /**< Fraction of a solid (3D) angle covered. */ } e_coverfrac_t; namespace gmx { /*! \cond internal */ /*! \brief * Flags for options. * * These flags are not part of the public interface, even though they are in an * installed header. They are needed in the implementation of SelectionOption. */ enum SelectionFlag : uint64_t { efSelection_OnlyStatic = 1 << 0, efSelection_OnlyAtoms = 1 << 1, efSelection_OnlySorted = 1 << 2, //! Whether ::POS_MASKONLY should be used for output position evaluation. efSelection_DynamicMask = 1 << 3, //! If set, unconditionally empty selections result in compilation errors. efSelection_DisallowEmpty = 1 << 4, //! Whether velocities of output positions should be evaluated. efSelection_EvaluateVelocities = 1 << 5, //! Whether forces on output positions should be evaluated. efSelection_EvaluateForces = 1 << 6, }; //! Holds a collection of ::SelectionFlag values. typedef FlagsTemplate<SelectionFlag> SelectionFlags; //! \endcond /*! \brief * Describes topology properties required for selection evaluation. * * See SelectionCollection::requiredTopologyProperties(). * * \inpublicapi * \ingroup module_selection */ struct SelectionTopologyProperties { //! Returns a property object that requires generic topology info. static SelectionTopologyProperties topology() { return SelectionTopologyProperties(true, false); } //! Returns a property object that requires atom masses. static SelectionTopologyProperties masses() { return SelectionTopologyProperties(true, true); } //! Initializes properties that does not require anything. SelectionTopologyProperties() : needsTopology(false), needsMasses(false) {} //! Initializes properties with the given flags. SelectionTopologyProperties(bool needsTopology, bool needsMasses) : needsTopology(needsTopology), needsMasses(needsMasses) { } //! Combines flags from another properties object to this. void merge(const SelectionTopologyProperties& other) { needsTopology = needsTopology || other.needsTopology; needsMasses = needsMasses || other.needsMasses; } //! Whether all flags are `true` (for short-ciruiting logic). bool hasAll() const { return needsTopology && needsMasses; } //! Whether any flag is `true`. bool hasAny() const { return needsTopology || needsMasses; } //! Whether topology information is needed for selection evaluation. bool needsTopology; //! Whether atom masses are needed for selection evaluation. bool needsMasses; }; } // namespace gmx #endif
1,484
1,738
<filename>dev/Code/Framework/GridMate/GridMate/Containers/slist.h<gh_stars>1000+ /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #ifndef GM_CONTAINERS_SLIST_H #define GM_CONTAINERS_SLIST_H #include <GridMate/Memory.h> #include <AzCore/std/containers/forward_list.h> namespace GridMate { template<class T, class Allocator = SysContAlloc> using forward_list = AZStd::forward_list<T, Allocator>; } #endif // GM_CONTAINERS_SLIST_H
296
544
from office365.entity import Entity class ConditionalAccessRoot(Entity): """The conditionalAccessRoot resource is the entry point for the Conditional Access (CA) object model. It doesn't contain any usable properties.""" pass
61
1,656
import os import arrow from jinja2 import Environment, FileSystemLoader, select_autoescape from lemur.plugins.utils import get_plugin_option loader = FileSystemLoader(searchpath=os.path.dirname(os.path.realpath(__file__))) env = Environment( loader=loader, # nosec: potentially dangerous types esc. autoescape=select_autoescape(["html", "xml"]), ) def human_time(time): return arrow.get(time).format("dddd, MMMM D, YYYY") def interval(options): return get_plugin_option("interval", options) def unit(options): return get_plugin_option("unit", options) env.filters["time"] = human_time env.filters["interval"] = interval env.filters["unit"] = unit
227
782
/* * Copyright (c) 2020, <NAME>. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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. */ package boofcv.alg.geo.rectify; import georegression.geometry.GeometryMath_F64; import georegression.struct.point.Vector3D_F64; import georegression.struct.se.Se3_F64; import lombok.Getter; import org.ejml.data.DMatrixRMaj; import org.ejml.simple.SimpleMatrix; /** * <p> * Rectifies a stereo pair with known camera calibration using a simple algorithm described in [1] * such that the epipoles project to infinity along the x-axis. After rectification both images will * have the same intrinsic calibration matrix, same extrinsic rotation matrix, but the optical centers * are not modified. * </p> * * <p> * The calibration matrix is the standard upper triangular matrix used throughout the library. A single * calibration matrix is computed for both images by averaging the two original and setting the skew * to zero. * </p> * * <p> * The rectified view is chosen such that it will be most similar to the first camera. This is done by making * the original z-axis and the rectified z-axis similar. * </p> * * <p> * [1] <NAME>, <NAME>, and <NAME>, "A Compact Algorithm for Rectification of Stereo Pairs" * Machine Vision and Applications, 2000 * </p> * * @author <NAME> */ public class RectifyCalibrated { /** Rectification transform for view-1 camera. Undistored to rectified pixels. */ final @Getter DMatrixRMaj undistToRectPixels1 = new DMatrixRMaj(3, 3); /** Rectification transform for view-2 camera. Undistored to rectified pixels. */ final @Getter DMatrixRMaj undistToRectPixels2 = new DMatrixRMaj(3, 3); // direction of new coordinate system axises final Vector3D_F64 v1 = new Vector3D_F64(); final Vector3D_F64 v2 = new Vector3D_F64(); final Vector3D_F64 v3 = new Vector3D_F64(); // Camera calibration matrix. final SimpleMatrix K = new SimpleMatrix(3, 3); /** * Rotation matrix of rectified coordinate system. To convert back into left camera reference frame multiply * the triangulated point by the transpose of this matrix */ @Getter DMatrixRMaj rectifiedRotation; /** * Computes rectification transforms for both cameras and optionally a single calibration * matrix. * * @param K1 Calibration matrix for first camera. * @param worldToCamera1 Location of the first camera. * @param K2 Calibration matrix for second camera. * @param worldToCamera2 Location of the second camera. */ public void process( DMatrixRMaj K1, Se3_F64 worldToCamera1, DMatrixRMaj K2, Se3_F64 worldToCamera2 ) { SimpleMatrix sK1 = SimpleMatrix.wrap(K1); SimpleMatrix sK2 = SimpleMatrix.wrap(K2); SimpleMatrix R1 = SimpleMatrix.wrap(worldToCamera1.getR()); SimpleMatrix R2 = SimpleMatrix.wrap(worldToCamera2.getR()); SimpleMatrix T1 = new SimpleMatrix(3, 1, true, new double[]{worldToCamera1.getT().x, worldToCamera1.getT().y, worldToCamera1.getT().z}); SimpleMatrix T2 = new SimpleMatrix(3, 1, true, new double[]{worldToCamera2.getT().x, worldToCamera2.getT().y, worldToCamera2.getT().z}); // P = K*[R|T] SimpleMatrix KR1 = sK1.mult(R1); SimpleMatrix KR2 = sK2.mult(R2); // compute optical centers in world reference frame // c = -R'*T SimpleMatrix c1 = R1.transpose().mult(T1.scale(-1)); SimpleMatrix c2 = R2.transpose().mult(T2.scale(-1)); // new coordinate system axises selectAxises(R1, R2, c1, c2); // new extrinsic parameters, rotation matrix with rows of camera 1's coordinate system in // the world frame SimpleMatrix RR = new SimpleMatrix(3, 3, true, new double[]{ v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, v3.x, v3.y, v3.z}); // new calibration matrix that is an average of the original K.setTo(sK1.plus(sK2).scale(0.5)); K.set(0, 1, 0);// set skew to zero // new projection rotation matrices SimpleMatrix KRR = K.mult(RR); // rectification transforms undistToRectPixels1.setTo(KRR.mult(KR1.invert()).getDDRM()); undistToRectPixels2.setTo(KRR.mult(KR2.invert()).getDDRM()); rectifiedRotation = RR.getDDRM(); } /** * Selects axises of new coordinate system */ private void selectAxises( SimpleMatrix R1, SimpleMatrix R2, SimpleMatrix c1, SimpleMatrix c2 ) { // --------- Compute the new x-axis v1.setTo(c2.get(0) - c1.get(0), c2.get(1) - c1.get(1), c2.get(2) - c1.get(2)); v1.normalize(); // --------- Compute the new y-axis // cross product of old z axis and new x axis // According to the paper [1] this choice is arbitrary, however it is not. By selecting // the original axis the similarity with the first view is maximized. The other extreme // would be to make it perpendicular, resulting in an unusable rectification. // extract old z-axis from rotation matrix Vector3D_F64 oldZ = new Vector3D_F64( R1.get(2, 0) + R2.get(2, 0), R1.get(2, 1) + R2.get(2, 1), R1.get(2, 2) + R2.get(2, 2)); GeometryMath_F64.cross(oldZ, v1, v2); v2.normalize(); // ---------- Compute the new z-axis // simply the process product of the first two GeometryMath_F64.cross(v1, v2, v3); v3.normalize(); } /** * If a single calibration matrix was requested then this returns it. * * @return Calibration matrix for both cameras */ public DMatrixRMaj getCalibrationMatrix() { return K.getDDRM(); } }
2,020
5,547
<filename>platform/vendor_bsp/nxp/CH-K-Lib/drivers/K/inc/tsi.h /** ****************************************************************************** * @file tsi.h * @author YANDLD * @version V2.5 * @date 2014.3.26 * @brief www.beyondcore.net http://upcmcu.taobao.com * @note 此文件为芯片TSI模块的底层功能函数 ****************************************************************************** */ #ifndef __CH_LIB_TSI_H__ #define __CH_LIB_TSI_H__ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> /** * \enum TSI_TriggerMode_Type * \brief TSI 触发模式选择 */ typedef enum { kTSI_TriggerSoftware, /**< 软件触发 */ kTSI_TriggerPeriodicalScan, /**< 硬件周期性扫描 */ } TSI_TriggerMode_Type; #define HW_TSI_CH0 (0x00) /* 触控的0通道,以下依次类推 */ #define HW_TSI_CH1 (0x01) #define HW_TSI_CH2 (0x02) #define HW_TSI_CH3 (0x03) #define HW_TSI_CH4 (0x04) #define HW_TSI_CH5 (0x05) #define HW_TSI_CH6 (0x06) #define HW_TSI_CH7 (0x07) #define HW_TSI_CH8 (0x08) #define HW_TSI_CH9 (0x09) #define HW_TSI_CH10 (0x0A) #define HW_TSI_CH11 (0x0B) #define HW_TSI_CH12 (0x0C) #define HW_TSI_CH13 (0x0D) #define HW_TSI_CH14 (0x0E) #define HW_TSI_CH15 (0x0F) /** * \enum TSI_ITDMAConfig_Type * \brief TSI 中断DMA配置 */ typedef enum { kTSI_IT_Disable, /**< 关闭中断 */ kTSI_IT_OutOfRange, /**< 溢出中断 */ kTSI_IT_EndOfScan, /**< 扫描结束中断 */ }TSI_ITDMAConfig_Type; /** * \enum TSI_EletrodeOscPs_Type * \brief TSI Electrode Oscillator 分频 */ typedef enum { kTSI_EletrodeOscDiv_1, kTSI_EletrodeOscDiv_2, kTSI_EletrodeOscDiv_4, kTSI_EletrodeOscDiv_8, kTSI_EletrodeOscDiv_16, kTSI_EletrodeOscDiv_32, kTSI_EletrodeOscDiv_64, kTSI_EletrodeOscDiv_128, }TSI_EletrodeOscPs_Type; /** * \enum TSI_ChargeCurrent_Type * \brief TSI charge current */ typedef enum { kTSI_ChargeCurrent_2uA, kTSI_ChargeCurrent_4uA, kTSI_ChargeCurrent_6uA, kTSI_ChargeCurrent_8uA, kTSI_ChargeCurrent_10uA, kTSI_ChargeCurrent_12uA, kTSI_ChargeCurrent_14uA, kTSI_ChargeCurrent_16uA, kTSI_ChargeCurrent_18uA, kTSI_ChargeCurrent_20uA, kTSI_ChargeCurrent_22uA, kTSI_ChargeCurrent_24uA, kTSI_ChargeCurrent_26uA, kTSI_ChargeCurrent_28uA, kTSI_ChargeCurrent_30uA, kTSI_ChargeCurrent_32uA, }TSI_ChargeCurrent_Type; /** * \struct TSI_InitTypeDef * \brief TSI初始化结构 */ typedef struct { uint32_t chl; /* 通道号1~15 */ TSI_TriggerMode_Type triggerMode; /* 触发模式选择 */ TSI_EletrodeOscPs_Type electrodeOSCPrescaler; uint32_t consecutiveScanTimes; /* number of consecutive scans per electrode */ uint32_t threshld; /* 发生超范围中断时的判断阀值 */ TSI_ChargeCurrent_Type refChargeCurrent; /* 参考 OSC 充电电流 */ TSI_ChargeCurrent_Type extChargeCurrent; /* 外部 OSC 充电电流 */ }TSI_InitTypeDef; /* TSI QuickInit macro */ #define TSI0_CH0_PB00 (0x00004008) /* TSI 0通道的PTB0引脚 以下类推 */ #define TSI0_CH1_PA00 (0x00084000) #define TSI0_CH2_PA01 (0x00104200) #define TSI0_CH3_PA02 (0x00184400) #define TSI0_CH4_PA03 (0x00204600) #define TSI0_CH5_PA04 (0x00284800) #define TSI0_CH6_PB01 (0x00304208) #define TSI0_CH7_PB02 (0x00384408) #define TSI0_CH8_PB03 (0x00404608) #define TSI0_CH9_PB16 (0x00486008) #define TSI0_CH10_PB17 (0x00506208) #define TSI0_CH11_PB18 (0x00586408) #define TSI0_CH12_PB19 (0x00606608) #define TSI0_CH13_PC00 (0x00684010) #define TSI0_CH14_PC01 (0x00704210) #define TSI0_CH15_PC02 (0x00784410) /* TSI CallBack Type */ typedef void (*TSI_CallBackType)(void); /* API functions */ uint32_t TSI_QuickInit(uint32_t MAP); uint32_t TSI_GetCounter(uint32_t chl); void TSI_ITDMAConfig(TSI_ITDMAConfig_Type config); void TSI_Init(TSI_InitTypeDef* TSI_InitStruct); void TSI_CallbackInstall(TSI_CallBackType AppCBFun); #ifdef __cplusplus } #endif #endif
2,335
973
<filename>glsdk/glload/include/glload/_int_gl_1_4.hpp #ifndef OPENGL_GEN_CORE_1_4_HPP #define OPENGL_GEN_CORE_1_4_HPP #include "_int_load_test.hpp" namespace gl { enum { BLEND_DST_ALPHA = 0x80CA, BLEND_DST_RGB = 0x80C8, BLEND_SRC_ALPHA = 0x80CB, BLEND_SRC_RGB = 0x80C9, DECR_WRAP = 0x8508, DEPTH_COMPONENT16 = 0x81A5, DEPTH_COMPONENT24 = 0x81A6, DEPTH_COMPONENT32 = 0x81A7, INCR_WRAP = 0x8507, MAX_TEXTURE_LOD_BIAS = 0x84FD, MIRRORED_REPEAT = 0x8370, POINT_FADE_THRESHOLD_SIZE = 0x8128, TEXTURE_COMPARE_FUNC = 0x884D, TEXTURE_COMPARE_MODE = 0x884C, TEXTURE_DEPTH_SIZE = 0x884A, TEXTURE_LOD_BIAS = 0x8501, }; namespace _detail { typedef void (CODEGEN_FUNCPTR * Proc_glBlendFuncSeparate)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); typedef void (CODEGEN_FUNCPTR * Proc_glMultiDrawArrays)(GLenum mode, const GLint * first, const GLsizei * count, GLsizei drawcount); typedef void (CODEGEN_FUNCPTR * Proc_glMultiDrawElements)(GLenum mode, const GLsizei * count, GLenum type, const GLvoid *const* indices, GLsizei drawcount); typedef void (CODEGEN_FUNCPTR * Proc_glPointParameterf)(GLenum pname, GLfloat param); typedef void (CODEGEN_FUNCPTR * Proc_glPointParameterfv)(GLenum pname, const GLfloat * params); typedef void (CODEGEN_FUNCPTR * Proc_glPointParameteri)(GLenum pname, GLint param); typedef void (CODEGEN_FUNCPTR * Proc_glPointParameteriv)(GLenum pname, const GLint * params); } extern _detail::Proc_glBlendFuncSeparate BlendFuncSeparate; extern _detail::Proc_glMultiDrawArrays MultiDrawArrays; extern _detail::Proc_glMultiDrawElements MultiDrawElements; extern _detail::Proc_glPointParameterf PointParameterf; extern _detail::Proc_glPointParameterfv PointParameterfv; extern _detail::Proc_glPointParameteri PointParameteri; extern _detail::Proc_glPointParameteriv PointParameteriv; } #endif /*OPENGL_GEN_CORE_1_4_HPP*/
1,083
5,535
<filename>src/backend/gporca/libgpopt/include/gpopt/operators/CLogicalLeftOuterCorrelatedApply.h //--------------------------------------------------------------------------- // Greenplum Database // Copyright 2012 EMC Corp. // // @filename: // CLogicalLeftOuterCorrelatedApply.h // // @doc: // Logical Left Outer Correlated Apply operator; // a variant of left outer apply that captures the need to implement a // correlated-execution strategy on the physical side //--------------------------------------------------------------------------- #ifndef GPOPT_CLogicalLeftOuterCorrelatedApply_H #define GPOPT_CLogicalLeftOuterCorrelatedApply_H #include "gpos/base.h" #include "gpopt/operators/CLogicalLeftOuterApply.h" namespace gpopt { //--------------------------------------------------------------------------- // @class: // CLogicalLeftOuterCorrelatedApply // // @doc: // Logical Apply operator used in scalar subquery transformations // //--------------------------------------------------------------------------- class CLogicalLeftOuterCorrelatedApply : public CLogicalLeftOuterApply { private: public: CLogicalLeftOuterCorrelatedApply(const CLogicalLeftOuterCorrelatedApply &) = delete; // ctor CLogicalLeftOuterCorrelatedApply(CMemoryPool *mp, CColRefArray *pdrgpcrInner, EOperatorId eopidOriginSubq); // ctor for patterns explicit CLogicalLeftOuterCorrelatedApply(CMemoryPool *mp); // dtor ~CLogicalLeftOuterCorrelatedApply() override = default; // ident accessors EOperatorId Eopid() const override { return EopLogicalLeftOuterCorrelatedApply; } // return a string for operator name const CHAR * SzId() const override { return "CLogicalLeftOuterCorrelatedApply"; } // match function BOOL Matches(COperator *pop) const override; // return a copy of the operator with remapped columns COperator *PopCopyWithRemappedColumns(CMemoryPool *mp, UlongToColRefMap *colref_mapping, BOOL must_exist) override; // applicable transformations CXformSet *PxfsCandidates(CMemoryPool *mp) const override; // return true if operator is a correlated apply BOOL FCorrelated() const override { return true; } // conversion function static CLogicalLeftOuterCorrelatedApply * PopConvert(COperator *pop) { GPOS_ASSERT(nullptr != pop); GPOS_ASSERT(EopLogicalLeftOuterCorrelatedApply == pop->Eopid()); return dynamic_cast<CLogicalLeftOuterCorrelatedApply *>(pop); } }; // class CLogicalLeftOuterCorrelatedApply } // namespace gpopt #endif // !GPOPT_CLogicalLeftOuterCorrelatedApply_H // EOF
813
1,109
<filename>modules/event/src/main/java/com/intuit/wasabi/events/impl/EventsImpl.java<gh_stars>1000+ /******************************************************************************* * Copyright 2016 Intuit * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. *******************************************************************************/ package com.intuit.wasabi.events.impl; import com.google.inject.Inject; import com.google.inject.name.Named; import com.intuit.wasabi.analyticsobjects.Event; import com.intuit.wasabi.analyticsobjects.EventList; import com.intuit.wasabi.assignment.Assignments; import com.intuit.wasabi.assignmentobjects.Assignment; import com.intuit.wasabi.assignmentobjects.User; import com.intuit.wasabi.database.TransactionFactory; import com.intuit.wasabi.eventobjects.EventEnvelopePayload; import com.intuit.wasabi.events.EventIngestionExecutor; import com.intuit.wasabi.events.Events; import com.intuit.wasabi.events.EventsMBean; import com.intuit.wasabi.experimentobjects.Application; import com.intuit.wasabi.experimentobjects.Context; import com.intuit.wasabi.experimentobjects.Experiment; import org.slf4j.Logger; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import static com.intuit.wasabi.events.EventsAnnotations.EXECUTOR_THREADPOOL_SIZE; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.slf4j.LoggerFactory.getLogger; /** * This class <b>asychronously</b> posts events to the events database (mysql in this implementation). * <br></br> * <b>Note: Since the post to the events database is asynchronous, there is a chance of loosing events if the process is shut down abruptly while the event queue is not empty.</b> * <br></br> * <STRONG>WARNING: This class may loose events data</STRONG> */ public class EventsImpl implements Events, EventsMBean { private static final Logger LOGGER = getLogger(EventsImpl.class); protected static final String MYSQL = "mysql"; private Assignments assignments; private TransactionFactory transactionFactory; private LinkedBlockingQueue mysqlQueue = new LinkedBlockingQueue<>(); private ThreadPoolExecutor mysqlExecutor; /** * Executors to ingest event data to real time ingestion system. */ protected Map<String, EventIngestionExecutor> eventIngestionExecutors; @Inject public EventsImpl(Map<String, EventIngestionExecutor> eventIngestionExecutors, final @Named(EXECUTOR_THREADPOOL_SIZE) Integer threadPoolSize, final Assignments assignments, final TransactionFactory transactionFactory) { super(); this.eventIngestionExecutors = eventIngestionExecutors; this.transactionFactory = transactionFactory; this.assignments = assignments; mysqlExecutor = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 0L, MILLISECONDS, mysqlQueue); } /** * {@inheritDoc} */ @Override public void recordEvents(Application.Name applicationName, Experiment.Label experimentLabel, User.ID userID, EventList events, Set<Context> contextSet) { Map<Context, Assignment> assignmentHashMap = getAssignments(userID, applicationName, experimentLabel, contextSet); for (Event event : events.getEvents()) { Assignment assignment = assignmentHashMap.get(event.getContext()); if (assignment != null) { postEventToMysql(assignment, event); ingestEventToRealTimeSystems(applicationName, experimentLabel, event, assignment); } } } // This method ingests event to real time ingestion systems. private void ingestEventToRealTimeSystems(Application.Name applicationName, Experiment.Label experimentLabel, Event event, Assignment assignment) { for (String name : eventIngestionExecutors.keySet()) { eventIngestionExecutors.get(name).execute(new EventEnvelopePayload(applicationName, experimentLabel, assignment, event)); } } protected Map<Context, Assignment> getAssignments(User.ID userID, Application.Name applicationName, Experiment.Label experimentLabel, Set<Context> contextSet) { Map<Context, Assignment> assignmentHashMap = new HashMap<>(); for (Context context : contextSet) { Assignment assignment = assignments.getExistingAssignment(userID, applicationName, experimentLabel, context); assignmentHashMap.put(context, assignment); } return assignmentHashMap; } private void postEventToMysql(Assignment assignment, Event event) { try { mysqlExecutor.execute(makeEventEnvelope(assignment, event)); } catch (Exception e) { LOGGER.warn("Mysql error: Unable to record event " + event.toString() + " for the user " + assignment.getUserID().toString() + " for context " + assignment.getContext(), e); } } /** * Helper method to instantiate events envelope * * @param assignment * @param event * @return */ protected EventsEnvelope makeEventEnvelope(Assignment assignment, Event event) { return new EventsEnvelope(assignment, event, transactionFactory.newTransaction()); } /** * {@inheritDoc} */ @Override public void shutdown() { mysqlExecutor.shutdown(); } @Override public Map<String, Integer> queuesLength() { Map<String, Integer> queueLengthMap = new HashMap<String, Integer>(); queueLengthMap.put(MYSQL, new Integer(mysqlQueue.size())); for (String name : eventIngestionExecutors.keySet()) { queueLengthMap.put(name.toLowerCase(), new Integer(eventIngestionExecutors.get(name).queueLength())); } return queueLengthMap; } /** * {@inheritDoc} */ @Override public int getQueueSize() { // FIXME: is this MBean method really used?? return mysqlQueue.size(); } }
2,408
347
package com.ruoyi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) @EnableDiscoveryClient @EnableFeignClients(basePackages = "com.ruoyi") public class RuoYiDfsApp { public static void main(String[] args) { SpringApplication.run(RuoYiDfsApp.class, args); } }
220
475
<reponame>csmasters/vedastr<filename>vedastr/models/bodies/sequences/transformer/unit/builder.py from vedastr.utils import build_from_cfg from .registry import TRANSFORMER_ENCODER_LAYERS, TRANSFORMER_DECODER_LAYERS def build_encoder_layer(cfg, default_args=None): encoder_layer = build_from_cfg(cfg, TRANSFORMER_ENCODER_LAYERS, default_args) return encoder_layer def build_decoder_layer(cfg, default_args=None): decoder_layer = build_from_cfg(cfg, TRANSFORMER_DECODER_LAYERS, default_args) return decoder_layer
198
328
<gh_stars>100-1000 /** * @file jamplayer.h * */ /* Copyright (C) 2021 by <NAME> mailto:<EMAIL> * * 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. */ #ifndef JAMSTAPL_H_ #define JAMSTAPL_H_ #include "jbiport.h" extern "C" { #include "../jbi_22/code/jbiexprt.h" } struct JamSTAPLDisplay { virtual ~JamSTAPLDisplay() { } virtual void JamShowInfo(const char *pInfo)=0; virtual void JamShowStatus(const char *pStatus, int nExitCode)=0; }; class JamSTAPL { public: JamSTAPL(PROGRAM_PTR pProgram, long nProgramSize, bool bVerbose = false) : m_pProgram(pProgram), m_nProgramSize(nProgramSize) { PlatformInit(bVerbose); } JBI_RETURN_TYPE CheckCRC(bool bVerbose = false); unsigned short GetCRC() const { return m_nCRC; } JBI_RETURN_TYPE PrintInfo(); void ReadIdCode(); void ReadUsercode(); void CheckIdCode(); void Erase(); void Verify(); void Program(); JBI_RETURN_TYPE GetResult() const { return m_nExecResult; } const char *GetResultString() const; int GetExitCode() const { return m_nExitCode; } const char *GetExitCodeString() const; void SetMessage(const char *pMessage) { if (m_pJamSTAPLDisplay != nullptr) { m_pJamSTAPLDisplay->JamShowInfo(pMessage); } } void SetExportInteger(char *pKey, long nValue) { m_ExportInteger.pKey = pKey; m_ExportInteger.nValue = nValue; } const char *GetExportIntegerKey() const { return m_ExportInteger.pKey; } long GetExportIntegerInt() const { return m_ExportInteger.nValue; } void SetJamSTAPLDisplay(JamSTAPLDisplay *pJamSTAPLDisplay) { m_pJamSTAPLDisplay = pJamSTAPLDisplay; } private: void PlatformInit(bool bVerbose); void Execute(const char *pAction); void DisplayStatus(const char *pAction); private: PROGRAM_PTR m_pProgram; long m_nProgramSize; unsigned short m_nCRC{ 0 }; int m_nResetJtag { 1 }; long m_nErrorAddress; int m_nExitCode { -1 }; int m_FormatVersion { 2 }; JBI_RETURN_TYPE m_nExecResult { JBIC_ACTION_NOT_FOUND }; struct ExportInteger { char *pKey; long nValue; }; ExportInteger m_ExportInteger; JamSTAPLDisplay *m_pJamSTAPLDisplay{ nullptr }; }; #endif /* JAMSTAPL_H_ */
1,100
324
<filename>apis/byon/src/test/java/org/jclouds/byon/config/CacheNodeStoreModuleTest.java<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.jclouds.byon.config; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import java.io.IOException; import java.util.Map; import org.jclouds.byon.Node; import org.jclouds.location.Provider; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.google.common.base.Functions; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.Maps; import com.google.common.io.ByteSource; import com.google.common.util.concurrent.UncheckedExecutionException; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.util.Providers; @Test(groups = "unit", singleThreaded = true, testName = "CacheNodeStoreModuleTest") public class CacheNodeStoreModuleTest { @DataProvider(name = "names") public Object[][] createData() { return new Object[][] { { "instance1", "bear" }, { "instance2", "apple" }, { "instance2", "francis" }, { "instance4", "robot" } }; } public void testProvidedMapWithValue() throws IOException { Map<String, Node> map = Maps.newConcurrentMap(); map.put("test", Node.builder().id("instance1").name("instancename").build()); checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", "instance1", "instancename"); checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", "instance1", "instancename"); remove(map, getStore(createInjectorWithProvidedMap(map)), "test"); } public void testProvidedConsistentAcrossRepeatedWrites() throws IOException { Map<String, Node> map = Maps.newConcurrentMap(); Injector injector = createInjectorWithProvidedMap(map); assertEquals(injector.getInstance(Key.get(new TypeLiteral<LoadingCache<String, Node>>() { })).asMap(), map); LoadingCache<String, Node> store = getStore(injector); for (int i = 0; i < 10; i++) check(map, store, "test" + i, "instance1" + i, "instancename" + i); } public void testProvidedConsistentAcrossMultipleInjectors() throws IOException { Map<String, Node> map = Maps.newConcurrentMap(); put(map, getStore(createInjectorWithProvidedMap(map)), "test", "instance1", "instancename"); checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", "instance1", "instancename"); checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", "instance1", "instancename"); remove(map, getStore(createInjectorWithProvidedMap(map)), "test"); } public void testProvidedCacheConsistentAcrossMultipleInjectors() throws IOException { Map<String, Node> map = Maps.newConcurrentMap(); LoadingCache<String, Node> cache = CacheBuilder.newBuilder().build(CacheLoader.from(Functions.forMap(map))); put(map, getStore(createInjectorWithProvidedCache(cache)), "test", "instance1", "instancename"); checkConsistent(map, getStore(createInjectorWithProvidedCache(cache)), "test", "instance1", "instancename"); checkConsistent(map, getStore(createInjectorWithProvidedCache(cache)), "test", "instance1", "instancename"); remove(map, getStore(createInjectorWithProvidedCache(cache)), "test"); } private LoadingCache<String, Node> getStore(Injector injector) { return injector.getInstance(Key.get(new TypeLiteral<LoadingCache<String, Node>>() { })); } private Injector createInjectorWithProvidedMap(Map<String, Node> map) { return Guice.createInjector(new CacheNodeStoreModule(map), new AbstractModule() { @Override public void configure() { bind(ByteSource.class).annotatedWith(Provider.class).toProvider(Providers.<ByteSource>of(null)); } }); } private Injector createInjectorWithProvidedCache(LoadingCache<String, Node> cache) { return Guice.createInjector(new CacheNodeStoreModule(cache), new AbstractModule() { @Override public void configure() { bind(ByteSource.class).annotatedWith(Provider.class).toProvider(Providers.<ByteSource>of(null)); } }); } private void check(Map<String, Node> map, LoadingCache<String, Node> store, String key, String id, String name) throws IOException { put(map, store, key, id, name); checkConsistent(map, store, key, id, name); remove(map, store, key); } private void remove(Map<String, Node> map, LoadingCache<String, Node> store, String key) { store.invalidate(key); assertEquals(store.size(), 0); map.remove(key); assertEquals(map.size(), 0); try { assertEquals(store.getUnchecked(key), null); fail("should not work as null is invalid"); } catch (UncheckedExecutionException e) { } assertEquals(map.get(key), null); } private void checkConsistent(Map<String, Node> map, LoadingCache<String, Node> store, String key, String id, String name) throws IOException { assertEquals(map.size(), 1); if (store.size() == 0) store.getUnchecked(key); assertEquals(store.size(), 1); // checkRepeatedRead assertEquals(store.getUnchecked(key), Node.builder().id(id).name(name).build()); assertEquals(store.getUnchecked(key), Node.builder().id(id).name(name).build()); } private void put(Map<String, Node> map, LoadingCache<String, Node> store, String key, String id, String name) { assertEquals(store.size(), 0); assertEquals(map.size(), 0); map.put(key, Node.builder().id(id).name(name).build()); store.getUnchecked(key); } }
2,350
61,676
<gh_stars>1000+ from django.test import SimpleTestCase from ..utils import setup class JsonScriptTests(SimpleTestCase): @setup({'json-tag01': '{{ value|json_script:"test_id" }}'}) def test_basic(self): output = self.engine.render_to_string( 'json-tag01', {'value': {'a': 'testing\r\njson \'string" <b>escaping</b>'}} ) self.assertEqual( output, '<script id="test_id" type="application/json">' '{"a": "testing\\r\\njson \'string\\" \\u003Cb\\u003Eescaping\\u003C/b\\u003E"}' '</script>' ) @setup({'json-tag02': '{{ value|json_script }}'}) def test_without_id(self): output = self.engine.render_to_string('json-tag02', {'value': {}}) self.assertEqual(output, '<script type="application/json">{}</script>')
395
332
/* * * Copyright 2020 WeBank * * 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. */ package com.webank.wedatasphere.exchangis.queue; import com.webank.wedatasphere.exchangis.queue.domain.QueueElement; import java.util.*; /** * @author davidhua * 2019/1/7 */ public abstract class AbstractAdapterQueue implements Queue<QueueElement> { @Override public int size() { return 0; } @Override public boolean isEmpty() { return false; } @Override public boolean contains(Object o) { return false; } @Override public Iterator<QueueElement> iterator() { return Collections.singletonList(new QueueElement()).iterator(); } @Override public Object[] toArray() { return new Object[]{}; } @Override public <T> T[] toArray(T[] a) { throw new RuntimeException("Don't supported this method"); } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<? extends QueueElement> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } //TODO lock queue }
634
529
<reponame>PervasiveDigital/netmf-interpreter //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "spot_native_Microsoft_SPOT_Messaging_EndPoint.cpp" #include "spot_native_Microsoft_SPOT_Messaging_Message.cpp" #include "spot_native_Microsoft_SPOT_Messaging_Message__RemotedException.cpp"
121
9,953
<reponame>mathieui/twisted # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Test cases for twisted.words.xish.utility """ from __future__ import absolute_import, division from collections import OrderedDict from twisted.trial import unittest from twisted.words.xish import utility from twisted.words.xish.domish import Element from twisted.words.xish.utility import EventDispatcher class CallbackTracker: """ Test helper for tracking callbacks. Increases a counter on each call to L{call} and stores the object passed in the call. """ def __init__(self): self.called = 0 self.obj = None def call(self, obj): self.called = self.called + 1 self.obj = obj class OrderedCallbackTracker: """ Test helper for tracking callbacks and their order. """ def __init__(self): self.callList = [] def call1(self, object): self.callList.append(self.call1) def call2(self, object): self.callList.append(self.call2) def call3(self, object): self.callList.append(self.call3) class EventDispatcherTests(unittest.TestCase): """ Tests for L{EventDispatcher}. """ def testStuff(self): d = EventDispatcher() cb1 = CallbackTracker() cb2 = CallbackTracker() cb3 = CallbackTracker() d.addObserver("/message/body", cb1.call) d.addObserver("/message", cb1.call) d.addObserver("/presence", cb2.call) d.addObserver("//event/testevent", cb3.call) msg = Element(("ns", "message")) msg.addElement("body") pres = Element(("ns", "presence")) pres.addElement("presence") d.dispatch(msg) self.assertEqual(cb1.called, 2) self.assertEqual(cb1.obj, msg) self.assertEqual(cb2.called, 0) d.dispatch(pres) self.assertEqual(cb1.called, 2) self.assertEqual(cb2.called, 1) self.assertEqual(cb2.obj, pres) self.assertEqual(cb3.called, 0) d.dispatch(d, "//event/testevent") self.assertEqual(cb3.called, 1) self.assertEqual(cb3.obj, d) d.removeObserver("/presence", cb2.call) d.dispatch(pres) self.assertEqual(cb2.called, 1) def test_addObserverTwice(self): """ Test adding two observers for the same query. When the event is dispatched both of the observers need to be called. """ d = EventDispatcher() cb1 = CallbackTracker() cb2 = CallbackTracker() d.addObserver("//event/testevent", cb1.call) d.addObserver("//event/testevent", cb2.call) d.dispatch(d, "//event/testevent") self.assertEqual(cb1.called, 1) self.assertEqual(cb1.obj, d) self.assertEqual(cb2.called, 1) self.assertEqual(cb2.obj, d) def test_addObserverInDispatch(self): """ Test for registration of an observer during dispatch. """ d = EventDispatcher() msg = Element(("ns", "message")) cb = CallbackTracker() def onMessage(_): d.addObserver("/message", cb.call) d.addOnetimeObserver("/message", onMessage) d.dispatch(msg) self.assertEqual(cb.called, 0) d.dispatch(msg) self.assertEqual(cb.called, 1) d.dispatch(msg) self.assertEqual(cb.called, 2) def test_addOnetimeObserverInDispatch(self): """ Test for registration of a onetime observer during dispatch. """ d = EventDispatcher() msg = Element(("ns", "message")) cb = CallbackTracker() def onMessage(msg): d.addOnetimeObserver("/message", cb.call) d.addOnetimeObserver("/message", onMessage) d.dispatch(msg) self.assertEqual(cb.called, 0) d.dispatch(msg) self.assertEqual(cb.called, 1) d.dispatch(msg) self.assertEqual(cb.called, 1) def testOnetimeDispatch(self): d = EventDispatcher() msg = Element(("ns", "message")) cb = CallbackTracker() d.addOnetimeObserver("/message", cb.call) d.dispatch(msg) self.assertEqual(cb.called, 1) d.dispatch(msg) self.assertEqual(cb.called, 1) def testDispatcherResult(self): d = EventDispatcher() msg = Element(("ns", "message")) pres = Element(("ns", "presence")) cb = CallbackTracker() d.addObserver("/presence", cb.call) result = d.dispatch(msg) self.assertEqual(False, result) result = d.dispatch(pres) self.assertEqual(True, result) def testOrderedXPathDispatch(self): d = EventDispatcher() cb = OrderedCallbackTracker() d.addObserver("/message/body", cb.call2) d.addObserver("/message", cb.call3, -1) d.addObserver("/message/body", cb.call1, 1) msg = Element(("ns", "message")) msg.addElement("body") d.dispatch(msg) self.assertEqual(cb.callList, [cb.call1, cb.call2, cb.call3], "Calls out of order: %s" % repr([c.__name__ for c in cb.callList])) # Observers are put into CallbackLists that are then put into dictionaries # keyed by the event trigger. Upon removal of the last observer for a # particular event trigger, the (now empty) CallbackList and corresponding # event trigger should be removed from those dictionaries to prevent # slowdown and memory leakage. def test_cleanUpRemoveEventObserver(self): """ Test observer clean-up after removeObserver for named events. """ d = EventDispatcher() cb = CallbackTracker() d.addObserver('//event/test', cb.call) d.dispatch(None, '//event/test') self.assertEqual(1, cb.called) d.removeObserver('//event/test', cb.call) self.assertEqual(0, len(d._eventObservers.pop(0))) def test_cleanUpRemoveXPathObserver(self): """ Test observer clean-up after removeObserver for XPath events. """ d = EventDispatcher() cb = CallbackTracker() msg = Element((None, "message")) d.addObserver('/message', cb.call) d.dispatch(msg) self.assertEqual(1, cb.called) d.removeObserver('/message', cb.call) self.assertEqual(0, len(d._xpathObservers.pop(0))) def test_cleanUpOnetimeEventObserver(self): """ Test observer clean-up after onetime named events. """ d = EventDispatcher() cb = CallbackTracker() d.addOnetimeObserver('//event/test', cb.call) d.dispatch(None, '//event/test') self.assertEqual(1, cb.called) self.assertEqual(0, len(d._eventObservers.pop(0))) def test_cleanUpOnetimeXPathObserver(self): """ Test observer clean-up after onetime XPath events. """ d = EventDispatcher() cb = CallbackTracker() msg = Element((None, "message")) d.addOnetimeObserver('/message', cb.call) d.dispatch(msg) self.assertEqual(1, cb.called) self.assertEqual(0, len(d._xpathObservers.pop(0))) def test_observerRaisingException(self): """ Test that exceptions in observers do not bubble up to dispatch. The exceptions raised in observers should be logged and other observers should be called as if nothing happened. """ class OrderedCallbackList(utility.CallbackList): def __init__(self): self.callbacks = OrderedDict() class TestError(Exception): pass def raiseError(_): raise TestError() d = EventDispatcher() cb = CallbackTracker() originalCallbackList = utility.CallbackList try: utility.CallbackList = OrderedCallbackList d.addObserver('//event/test', raiseError) d.addObserver('//event/test', cb.call) try: d.dispatch(None, '//event/test') except TestError: self.fail("TestError raised. Should have been logged instead.") self.assertEqual(1, len(self.flushLoggedErrors(TestError))) self.assertEqual(1, cb.called) finally: utility.CallbackList = originalCallbackList class XmlPipeTests(unittest.TestCase): """ Tests for L{twisted.words.xish.utility.XmlPipe}. """ def setUp(self): self.pipe = utility.XmlPipe() def test_sendFromSource(self): """ Send an element from the source and observe it from the sink. """ def cb(obj): called.append(obj) called = [] self.pipe.sink.addObserver('/test[@xmlns="testns"]', cb) element = Element(('testns', 'test')) self.pipe.source.send(element) self.assertEqual([element], called) def test_sendFromSink(self): """ Send an element from the sink and observe it from the source. """ def cb(obj): called.append(obj) called = [] self.pipe.source.addObserver('/test[@xmlns="testns"]', cb) element = Element(('testns', 'test')) self.pipe.sink.send(element) self.assertEqual([element], called)
4,279
525
<reponame>colindean/peru #! /usr/bin/env python3 from collections import namedtuple import os import subprocess import sys import textwrap CACHE_PATH = os.environ['PERU_PLUGIN_CACHE'] URL = os.environ['PERU_MODULE_URL'] REV = os.environ['PERU_MODULE_REV'] or 'default' REUP = os.environ['PERU_MODULE_REUP'] or 'default' Result = namedtuple("Result", ["returncode", "output"]) def hg(*args, hg_dir=None, capture_output=False, checked=True): # Avoid forgetting this arg. assert hg_dir is None or os.path.isdir(hg_dir) command = ['hg'] if hg_dir: command.append('--repository') command.append(hg_dir) command.extend(args) stdout = subprocess.PIPE if capture_output else None # Always let stderr print to the caller. process = subprocess.Popen( command, stdin=subprocess.DEVNULL, stdout=stdout, universal_newlines=True) output, _ = process.communicate() if checked and process.returncode != 0: sys.exit(1) return Result(process.returncode, output) def clone_if_needed(url, verbose=False): if not os.path.exists(os.path.join(CACHE_PATH, '.hg')): if verbose: print('hg clone', url) hg('clone', '--noupdate', url, CACHE_PATH) configure(CACHE_PATH) def configure(repo_path): # Set configs needed for cached repos. hgrc_path = os.path.join(repo_path, '.hg', 'hgrc') with open(hgrc_path, 'a') as f: f.write( textwrap.dedent('''\ [ui] # prevent 'hg archive' from creating '.hg_archival.txt' files. archivemeta = false ''')) def hg_pull(url, repo_path): print('hg pull', url) hg('pull', hg_dir=repo_path) def already_has_rev(repo, rev): res = hg( 'identify', '--debug', '--rev', rev, hg_dir=repo, capture_output=True, checked=False) if res.returncode != 0: return False # Only return True for revs that are absolute hashes. # We could consider treating tags the way, but... # 1) Tags actually can change. # 2) It's not clear at a glance whether something is a branch or a tag. # Keep it simple. return res.output.split()[0] == rev def plugin_sync(): dest = os.environ['PERU_SYNC_DEST'] clone_if_needed(URL, verbose=True) if not already_has_rev(CACHE_PATH, REV): hg_pull(URL, CACHE_PATH) # TODO: Should this handle subrepos? hg('archive', '--type', 'files', '--rev', REV, dest, hg_dir=CACHE_PATH) def plugin_reup(): reup_output = os.environ['PERU_REUP_OUTPUT'] clone_if_needed(URL, CACHE_PATH) hg_pull(URL, CACHE_PATH) output = hg( 'identify', '--debug', '--rev', REUP, hg_dir=CACHE_PATH, capture_output=True).output with open(reup_output, 'w') as output_file: print('rev:', output.split()[0], file=output_file) command = os.environ['PERU_PLUGIN_COMMAND'] if command == 'sync': plugin_sync() elif command == 'reup': plugin_reup() else: raise RuntimeError('Unknown command: ' + repr(command))
1,415
32,544
package com.baeldung.map.hashing; class Member { Integer id; String name; }
35
622
<reponame>Sam-Gao-Xin/Courses-<gh_stars>100-1000 import java.util.ArrayList; public class Variance { // Copy here sum from exercise 63 public static int sum(ArrayList<Integer> list) { int total = 0; for(Integer i: list){total+=i;} return total; } // Copy here average from exercise 64 public static double average(ArrayList<Integer> list) { return (double)sum(list)/(double)list.size(); } public static double variance(ArrayList<Integer> list) { double avg = average(list); //Average of the list double total = 0; for(Integer i:list){ total += Math.pow((i-avg), 2); } return total/(list.size()-1); } public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(3); list.add(2); list.add(7); list.add(2); System.out.println("The variance is: " + variance(list)); } }
441
480
#ifndef _ABIBITS_TERMIOS_H #define _ABIBITS_TERMIOS_H typedef unsigned int cc_t; typedef unsigned int speed_t; typedef unsigned int tcflag_t; // indices for the c_cc array in struct termios #define NCCS 11 #define VEOF 0 #define VEOL 1 #define VERASE 2 #define VINTR 3 #define VKILL 4 #define VMIN 5 #define VQUIT 6 #define VSTART 7 #define VSTOP 8 #define VSUSP 9 #define VTIME 10 struct termios { tcflag_t c_iflag; tcflag_t c_oflag; tcflag_t c_cflag; tcflag_t c_lflag; cc_t c_cc[NCCS]; speed_t ibaud; speed_t obaud; }; #endif
277
892
<filename>advisories/unreviewed/2022/05/GHSA-53rw-gv4m-q3jg/GHSA-53rw-gv4m-q3jg.json<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-53rw-gv4m-q3jg", "modified": "2022-05-13T01:28:31Z", "published": "2022-05-13T01:28:31Z", "aliases": [ "CVE-2014-2909" ], "details": "CRLF injection vulnerability in the integrated web server on Siemens SIMATIC S7-1200 CPU devices 2.x and 3.x allows remote attackers to inject arbitrary HTTP headers via unspecified vectors.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2014-2909" }, { "type": "WEB", "url": "https://cert-portal.siemens.com/productcert/pdf/ssa-892012.pdf" }, { "type": "WEB", "url": "http://ics-cert.us-cert.gov/advisories/ICSA-14-114-02" }, { "type": "WEB", "url": "http://www.siemens.com/innovation/pool/de/forschungsfelder/siemens_security_advisory_ssa-892012.pdf" } ], "database_specific": { "cwe_ids": [ "CWE-94" ], "severity": "MODERATE", "github_reviewed": false } }
546
312
<reponame>yanaspaula/rdf4j /******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ /* Generated By:JJTree: Do not edit this line. ASTBaseDecl.java */ package org.eclipse.rdf4j.query.parser.sparql.ast; public class ASTBaseDecl extends SimpleNode { private String iri; public ASTBaseDecl(int id) { super(id); } public ASTBaseDecl(SyntaxTreeBuilder p, int id) { super(p, id); } @Override public Object jjtAccept(SyntaxTreeBuilderVisitor visitor, Object data) throws VisitorException { return visitor.visit(this, data); } public String getIRI() { return iri; } public void setIRI(String iri) { this.iri = iri; } @Override public String toString() { return super.toString() + " (" + iri + ")"; } }
349
3,068
public final class Def { public static final int x = 3; }
18
14,668
// Copyright 2016 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 CHROME_BROWSER_CHROMEOS_PRINTING_CUPS_PRINT_JOB_H_ #define CHROME_BROWSER_CHROMEOS_PRINTING_CUPS_PRINT_JOB_H_ #include <string> #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/printing/history/print_job_info.pb.h" #include "chrome/browser/chromeos/printing/printer_error_codes.h" #include "chrome/browser/printing/print_job.h" #include "chromeos/printing/printer_configuration.h" namespace chromeos { class CupsPrintJob { public: enum class State { STATE_NONE, STATE_WAITING, STATE_STARTED, STATE_PAGE_DONE, STATE_CANCELLED, STATE_SUSPENDED, STATE_RESUMED, STATE_DOCUMENT_DONE, STATE_FAILED, STATE_ERROR, }; CupsPrintJob(const Printer& printer, int job_id, const std::string& document_title, int total_page_number, ::printing::PrintJob::Source source, const std::string& source_id, const printing::proto::PrintSettings& settings); CupsPrintJob(const CupsPrintJob&) = delete; CupsPrintJob& operator=(const CupsPrintJob&) = delete; ~CupsPrintJob(); // Create a unique id for a print job using the |printer_id| and |job_id|. static std::string CreateUniqueId(const std::string& printer_id, int job_id); // Returns a unique id for the print job. std::string GetUniqueId() const; // Returns weak pointer to |this| CupsPrintJob base::WeakPtr<CupsPrintJob> GetWeakPtr(); // Returns whether this print_job has timed out or not. bool IsExpired() const; // Getters. const Printer& printer() const { return printer_; } int job_id() const { return job_id_; } const std::string& document_title() const { return document_title_; } int total_page_number() const { return total_page_number_; } int printed_page_number() const { return printed_page_number_; } ::printing::PrintJob::Source source() const { return source_; } const std::string& source_id() const { return source_id_; } const printing::proto::PrintSettings& settings() const { return settings_; } base::Time creation_time() const { return creation_time_; } State state() const { return state_; } PrinterErrorCode error_code() const { return error_code_; } // Setters. void set_printed_page_number(int page_number) { printed_page_number_ = page_number; } void set_state(State state) { state_ = state; } void set_error_code(PrinterErrorCode error_code) { error_code_ = error_code; } // Returns true if |state_| represents a terminal state. bool IsJobFinished() const; // Returns true if cups pipeline failed. bool PipelineDead() const; private: const Printer printer_; const int job_id_; std::string document_title_; const int total_page_number_; int printed_page_number_ = 0; const ::printing::PrintJob::Source source_; const std::string source_id_; const printing::proto::PrintSettings settings_; const base::Time creation_time_; State state_ = State::STATE_NONE; PrinterErrorCode error_code_ = PrinterErrorCode::NO_ERROR; base::WeakPtrFactory<CupsPrintJob> weak_factory_{this}; }; } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_PRINTING_CUPS_PRINT_JOB_H_
1,188
13,663
/* * xxHash - Extremely Fast Hash algorithm * Copyright (C) 2020 <NAME> * * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php) * * Redistribution and use 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. * * 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. * * You can contact the author at: * - xxHash homepage: https://www.xxhash.com * - xxHash source repository: https://github.com/Cyan4973/xxHash */ #if defined (__cplusplus) extern "C" { #endif /* * Dispatcher code for XXH3 on x86-based targets. */ #if !(defined(__x86_64__) || defined(__i386__) || defined(_M_IX86) || defined(_M_X64)) # error "Dispatching is currently only supported on x86 and x86_64." #endif #ifndef __GNUC__ # error "Dispatching requires __attribute__((__target__)) capability" #endif #define XXH_DISPATCH_AVX2 /* enable dispatch towards AVX2 */ #define XXH_DISPATCH_AVX512 /* enable dispatch towards AVX512 */ #ifdef XXH_DISPATCH_DEBUG /* debug logging */ # include <stdio.h> # define XXH_debugPrint(str) { fprintf(stderr, "DEBUG: xxHash dispatch: %s \n", str); fflush(NULL); } #else # define XXH_debugPrint(str) ((void)0) # undef NDEBUG /* avoid redefinition */ # define NDEBUG #endif #include <assert.h> #if defined(__GNUC__) # include <immintrin.h> /* sse2 */ # include <emmintrin.h> /* avx2 */ #elif defined(_MSC_VER) # include <intrin.h> #endif #define XXH_INLINE_ALL #define XXH_X86DISPATCH #define XXH_TARGET_AVX512 __attribute__((__target__("avx512f"))) #define XXH_TARGET_AVX2 __attribute__((__target__("avx2"))) #define XXH_TARGET_SSE2 __attribute__((__target__("sse2"))) #include "xxhash.h" /* * Modified version of Intel's guide * https://software.intel.com/en-us/articles/how-to-detect-new-instruction-support-in-the-4th-generation-intel-core-processor-family */ #if defined(_MSC_VER) # include <intrin.h> #endif /* * Support both AT&T and Intel dialects * * GCC doesn't convert AT&T syntax to Intel syntax, and will error out if * compiled with -masm=intel. Instead, it supports dialect switching with * curly braces: { AT&T syntax | Intel syntax } * * Clang's integrated assembler automatically converts AT&T syntax to Intel if * needed, making the dialect switching useless (it isn't even supported). * * Note: Comments are written in the inline assembly itself. */ #ifdef __clang__ # define I_ATT(intel, att) att "\n\t" #else # define I_ATT(intel, att) "{" att "|" intel "}\n\t" #endif static void XXH_cpuid(xxh_u32 eax, xxh_u32 ecx, xxh_u32* abcd) { #if defined(_MSC_VER) __cpuidex(abcd, eax, ecx); #else xxh_u32 ebx, edx; # if defined(__i386__) && defined(__PIC__) __asm__( "# Call CPUID\n\t" "#\n\t" "# On 32-bit x86 with PIC enabled, we are not allowed to overwrite\n\t" "# EBX, so we use EDI instead.\n\t" I_ATT("mov edi, ebx", "movl %%ebx, %%edi") I_ATT("cpuid", "cpuid" ) I_ATT("xchg edi, ebx", "xchgl %%ebx, %%edi") : "=D" (ebx), # else __asm__( "# Call CPUID\n\t" I_ATT("cpuid", "cpuid") : "=b" (ebx), # endif "+a" (eax), "+c" (ecx), "=d" (edx)); abcd[0] = eax; abcd[1] = ebx; abcd[2] = ecx; abcd[3] = edx; #endif } #if defined(XXH_DISPATCH_AVX2) || defined(XXH_DISPATCH_AVX512) /* * While the CPU may support AVX2, the operating system might not properly save * the full YMM/ZMM registers. * * xgetbv is used for detecting this: Any compliant operating system will define * a set of flags in the xcr0 register indicating how it saves the AVX registers. * * You can manually disable this flag on Windows by running, as admin: * * bcdedit.exe /set xsavedisable 1 * * and rebooting. Run the same command with 0 to re-enable it. */ static xxh_u64 XXH_xgetbv(void) { #if defined(_MSC_VER) return _xgetbv(0); /* min VS2010 SP1 compiler is required */ #else xxh_u32 xcr0_lo, xcr0_hi; __asm__( "# Call XGETBV\n\t" "#\n\t" "# Older assemblers (e.g. macOS's ancient GAS version) don't support\n\t" "# the XGETBV opcode, so we encode it by hand instead.\n\t" "# See <https://github.com/asmjit/asmjit/issues/78> for details.\n\t" ".byte 0x0f, 0x01, 0xd0\n\t" : "=a" (xcr0_lo), "=d" (xcr0_hi) : "c" (0)); return xcr0_lo | ((xxh_u64)xcr0_hi << 32); #endif } #endif #define SSE2_CPUID_MASK (1 << 26) #define OSXSAVE_CPUID_MASK ((1 << 26) | (1 << 27)) #define AVX2_CPUID_MASK (1 << 5) #define AVX2_XGETBV_MASK ((1 << 2) | (1 << 1)) #define AVX512F_CPUID_MASK (1 << 16) #define AVX512F_XGETBV_MASK ((7 << 5) | (1 << 2) | (1 << 1)) /* Returns the best XXH3 implementation */ static int XXH_featureTest(void) { xxh_u32 abcd[4]; xxh_u32 max_leaves; int best = XXH_SCALAR; #if defined(XXH_DISPATCH_AVX2) || defined(XXH_DISPATCH_AVX512) xxh_u64 xgetbv_val; #endif #if defined(__GNUC__) && defined(__i386__) xxh_u32 cpuid_supported; __asm__( "# For the sake of ruthless backwards compatibility, check if CPUID\n\t" "# is supported in the EFLAGS on i386.\n\t" "# This is not necessary on x86_64 - CPUID is mandatory.\n\t" "# The ID flag (bit 21) in the EFLAGS register indicates support\n\t" "# for the CPUID instruction. If a software procedure can set and\n\t" "# clear this flag, the processor executing the procedure supports\n\t" "# the CPUID instruction.\n\t" "# <https://c9x.me/x86/html/file_module_x86_id_45.html>\n\t" "#\n\t" "# Routine is from <https://wiki.osdev.org/CPUID>.\n\t" "# Save EFLAGS\n\t" I_ATT("pushfd", "pushfl" ) "# Store EFLAGS\n\t" I_ATT("pushfd", "pushfl" ) "# Invert the ID bit in stored EFLAGS\n\t" I_ATT("xor dword ptr[esp], 0x200000", "xorl $0x200000, (%%esp)") "# Load stored EFLAGS (with ID bit inverted)\n\t" I_ATT("popfd", "popfl" ) "# Store EFLAGS again (ID bit may or not be inverted)\n\t" I_ATT("pushfd", "pushfl" ) "# eax = modified EFLAGS (ID bit may or may not be inverted)\n\t" I_ATT("pop eax", "popl %%eax" ) "# eax = whichever bits were changed\n\t" I_ATT("xor eax, dword ptr[esp]", "xorl (%%esp), %%eax" ) "# Restore original EFLAGS\n\t" I_ATT("popfd", "popfl" ) "# eax = zero if ID bit can't be changed, else non-zero\n\t" I_ATT("and eax, 0x200000", "andl $0x200000, %%eax" ) : "=a" (cpuid_supported) :: "cc"); if (XXH_unlikely(!cpuid_supported)) { XXH_debugPrint("CPUID support is not detected!"); return best; } #endif /* Check how many CPUID pages we have */ XXH_cpuid(0, 0, abcd); max_leaves = abcd[0]; /* Shouldn't happen on hardware, but happens on some QEMU configs. */ if (XXH_unlikely(max_leaves == 0)) { XXH_debugPrint("Max CPUID leaves == 0!"); return best; } /* Check for SSE2, OSXSAVE and xgetbv */ XXH_cpuid(1, 0, abcd); /* * Test for SSE2. The check is redundant on x86_64, but it doesn't hurt. */ if (XXH_unlikely((abcd[3] & SSE2_CPUID_MASK) != SSE2_CPUID_MASK)) return best; XXH_debugPrint("SSE2 support detected."); best = XXH_SSE2; #if defined(XXH_DISPATCH_AVX2) || defined(XXH_DISPATCH_AVX512) /* Make sure we have enough leaves */ if (XXH_unlikely(max_leaves < 7)) return best; /* Test for OSXSAVE and XGETBV */ if ((abcd[2] & OSXSAVE_CPUID_MASK) != OSXSAVE_CPUID_MASK) return best; /* CPUID check for AVX features */ XXH_cpuid(7, 0, abcd); xgetbv_val = XXH_xgetbv(); #if defined(XXH_DISPATCH_AVX2) /* Validate that AVX2 is supported by the CPU */ if ((abcd[1] & AVX2_CPUID_MASK) != AVX2_CPUID_MASK) return best; /* Validate that the OS supports YMM registers */ if ((xgetbv_val & AVX2_XGETBV_MASK) != AVX2_XGETBV_MASK) { XXH_debugPrint("AVX2 supported by the CPU, but not the OS."); return best; } /* AVX2 supported */ XXH_debugPrint("AVX2 support detected."); best = XXH_AVX2; #endif #if defined(XXH_DISPATCH_AVX512) /* Check if AVX512F is supported by the CPU */ if ((abcd[1] & AVX512F_CPUID_MASK) != AVX512F_CPUID_MASK) { XXH_debugPrint("AVX512F not supported by CPU"); return best; } /* Validate that the OS supports ZMM registers */ if ((xgetbv_val & AVX512F_XGETBV_MASK) != AVX512F_XGETBV_MASK) { XXH_debugPrint("AVX512F supported by the CPU, but not the OS."); return best; } /* AVX512F supported */ XXH_debugPrint("AVX512F support detected."); best = XXH_AVX512; #endif #endif return best; } /* === Vector implementations === */ /* === XXH3, default variants === */ XXH_NO_INLINE XXH64_hash_t XXHL64_default_scalar(const void* XXH_RESTRICT input, size_t len) { return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512_scalar, XXH3_scrambleAcc_scalar); } XXH_NO_INLINE XXH_TARGET_SSE2 XXH64_hash_t XXHL64_default_sse2(const void* XXH_RESTRICT input, size_t len) { return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512_sse2, XXH3_scrambleAcc_sse2); } #ifdef XXH_DISPATCH_AVX2 XXH_NO_INLINE XXH_TARGET_AVX2 XXH64_hash_t XXHL64_default_avx2(const void* XXH_RESTRICT input, size_t len) { return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512_avx2, XXH3_scrambleAcc_avx2); } #endif #ifdef XXH_DISPATCH_AVX512 XXH_NO_INLINE XXH_TARGET_AVX512 XXH64_hash_t XXHL64_default_avx512(const void* XXH_RESTRICT input, size_t len) { return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512_avx512, XXH3_scrambleAcc_avx512); } #endif /* === XXH3, Seeded variants === */ XXH_NO_INLINE XXH64_hash_t XXHL64_seed_scalar(const void* XXH_RESTRICT input, size_t len, XXH64_hash_t seed) { return XXH3_hashLong_64b_withSeed_internal(input, len, seed, XXH3_accumulate_512_scalar, XXH3_scrambleAcc_scalar, XXH3_initCustomSecret_scalar); } XXH_NO_INLINE XXH_TARGET_SSE2 XXH64_hash_t XXHL64_seed_sse2(const void* XXH_RESTRICT input, size_t len, XXH64_hash_t seed) { return XXH3_hashLong_64b_withSeed_internal(input, len, seed, XXH3_accumulate_512_sse2, XXH3_scrambleAcc_sse2, XXH3_initCustomSecret_sse2); } #ifdef XXH_DISPATCH_AVX2 XXH_NO_INLINE XXH_TARGET_AVX2 XXH64_hash_t XXHL64_seed_avx2(const void* XXH_RESTRICT input, size_t len, XXH64_hash_t seed) { return XXH3_hashLong_64b_withSeed_internal(input, len, seed, XXH3_accumulate_512_avx2, XXH3_scrambleAcc_avx2, XXH3_initCustomSecret_avx2); } #endif #ifdef XXH_DISPATCH_AVX512 XXH_NO_INLINE XXH_TARGET_AVX512 XXH64_hash_t XXHL64_seed_avx512(const void* XXH_RESTRICT input, size_t len, XXH64_hash_t seed) { return XXH3_hashLong_64b_withSeed_internal(input, len, seed, XXH3_accumulate_512_avx512, XXH3_scrambleAcc_avx512, XXH3_initCustomSecret_avx512); } #endif /* === XXH3, Secret variants === */ XXH_NO_INLINE XXH64_hash_t XXHL64_secret_scalar(const void* XXH_RESTRICT input, size_t len, const void* secret, size_t secretLen) { return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate_512_scalar, XXH3_scrambleAcc_scalar); } XXH_NO_INLINE XXH_TARGET_SSE2 XXH64_hash_t XXHL64_secret_sse2(const void* XXH_RESTRICT input, size_t len, const void* secret, size_t secretLen) { return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate_512_sse2, XXH3_scrambleAcc_sse2); } #ifdef XXH_DISPATCH_AVX2 XXH_NO_INLINE XXH_TARGET_AVX2 XXH64_hash_t XXHL64_secret_avx2(const void* XXH_RESTRICT input, size_t len, const void* secret, size_t secretLen) { return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate_512_avx2, XXH3_scrambleAcc_avx2); } #endif #ifdef XXH_DISPATCH_AVX512 XXH_NO_INLINE XXH_TARGET_AVX512 XXH64_hash_t XXHL64_secret_avx512(const void* XXH_RESTRICT input, size_t len, const void* secret, size_t secretLen) { return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate_512_avx512, XXH3_scrambleAcc_avx512); } #endif /* === XXH3 update variants === */ XXH_NO_INLINE XXH_errorcode XXH3_64bits_update_scalar(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_accumulate_512_scalar, XXH3_scrambleAcc_scalar); } XXH_NO_INLINE XXH_TARGET_SSE2 XXH_errorcode XXH3_64bits_update_sse2(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_accumulate_512_sse2, XXH3_scrambleAcc_sse2); } #ifdef XXH_DISPATCH_AVX2 XXH_NO_INLINE XXH_TARGET_AVX2 XXH_errorcode XXH3_64bits_update_avx2(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_accumulate_512_avx2, XXH3_scrambleAcc_avx2); } #endif #ifdef XXH_DISPATCH_AVX512 XXH_NO_INLINE XXH_TARGET_AVX512 XXH_errorcode XXH3_64bits_update_avx512(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_accumulate_512_avx512, XXH3_scrambleAcc_avx512); } #endif /* === XXH128 default variants === */ XXH_NO_INLINE XXH128_hash_t XXHL128_default_scalar(const void* XXH_RESTRICT input, size_t len) { return XXH3_hashLong_128b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512_scalar, XXH3_scrambleAcc_scalar); } XXH_NO_INLINE XXH_TARGET_SSE2 XXH128_hash_t XXHL128_default_sse2(const void* XXH_RESTRICT input, size_t len) { return XXH3_hashLong_128b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512_sse2, XXH3_scrambleAcc_sse2); } #ifdef XXH_DISPATCH_AVX2 XXH_NO_INLINE XXH_TARGET_AVX2 XXH128_hash_t XXHL128_default_avx2(const void* XXH_RESTRICT input, size_t len) { return XXH3_hashLong_128b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512_avx2, XXH3_scrambleAcc_avx2); } #endif #ifdef XXH_DISPATCH_AVX512 XXH_NO_INLINE XXH_TARGET_AVX512 XXH128_hash_t XXHL128_default_avx512(const void* XXH_RESTRICT input, size_t len) { return XXH3_hashLong_128b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512_avx512, XXH3_scrambleAcc_avx512); } #endif /* === XXH128 Secret variants === */ XXH_NO_INLINE XXH128_hash_t XXHL128_secret_scalar(const void* XXH_RESTRICT input, size_t len, const void* XXH_RESTRICT secret, size_t secretLen) { return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, secretLen, XXH3_accumulate_512_scalar, XXH3_scrambleAcc_scalar); } XXH_NO_INLINE XXH_TARGET_SSE2 XXH128_hash_t XXHL128_secret_sse2(const void* XXH_RESTRICT input, size_t len, const void* XXH_RESTRICT secret, size_t secretLen) { return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, secretLen, XXH3_accumulate_512_sse2, XXH3_scrambleAcc_sse2); } #ifdef XXH_DISPATCH_AVX2 XXH_NO_INLINE XXH_TARGET_AVX2 XXH128_hash_t XXHL128_secret_avx2(const void* XXH_RESTRICT input, size_t len, const void* XXH_RESTRICT secret, size_t secretLen) { return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, secretLen, XXH3_accumulate_512_avx2, XXH3_scrambleAcc_avx2); } #endif #ifdef XXH_DISPATCH_AVX512 XXH_NO_INLINE XXH_TARGET_AVX512 XXH128_hash_t XXHL128_secret_avx512(const void* XXH_RESTRICT input, size_t len, const void* XXH_RESTRICT secret, size_t secretLen) { return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, secretLen, XXH3_accumulate_512_avx512, XXH3_scrambleAcc_avx512); } #endif /* === XXH128 Seeded variants === */ XXH_NO_INLINE XXH128_hash_t XXHL128_seed_scalar(const void* XXH_RESTRICT input, size_t len, XXH64_hash_t seed) { return XXH3_hashLong_128b_withSeed_internal(input, len, seed, XXH3_accumulate_512_scalar, XXH3_scrambleAcc_scalar, XXH3_initCustomSecret_scalar); } XXH_NO_INLINE XXH_TARGET_SSE2 XXH128_hash_t XXHL128_seed_sse2(const void* XXH_RESTRICT input, size_t len, XXH64_hash_t seed) { return XXH3_hashLong_128b_withSeed_internal(input, len, seed, XXH3_accumulate_512_sse2, XXH3_scrambleAcc_sse2, XXH3_initCustomSecret_sse2); } #ifdef XXH_DISPATCH_AVX2 XXH_NO_INLINE XXH_TARGET_AVX2 XXH128_hash_t XXHL128_seed_avx2(const void* XXH_RESTRICT input, size_t len, XXH64_hash_t seed) { return XXH3_hashLong_128b_withSeed_internal(input, len, seed, XXH3_accumulate_512_avx2, XXH3_scrambleAcc_avx2, XXH3_initCustomSecret_avx2); } #endif #ifdef XXH_DISPATCH_AVX512 XXH_NO_INLINE XXH_TARGET_AVX512 XXH128_hash_t XXHL128_seed_avx512(const void* XXH_RESTRICT input, size_t len, XXH64_hash_t seed) { return XXH3_hashLong_128b_withSeed_internal(input, len, seed, XXH3_accumulate_512_avx512, XXH3_scrambleAcc_avx512, XXH3_initCustomSecret_avx512); } #endif /* === XXH128 update variants === */ XXH_NO_INLINE XXH_errorcode XXH3_128bits_update_scalar(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_accumulate_512_scalar, XXH3_scrambleAcc_scalar); } XXH_NO_INLINE XXH_TARGET_SSE2 XXH_errorcode XXH3_128bits_update_sse2(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_accumulate_512_sse2, XXH3_scrambleAcc_sse2); } #ifdef XXH_DISPATCH_AVX2 XXH_NO_INLINE XXH_TARGET_AVX2 XXH_errorcode XXH3_128bits_update_avx2(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_accumulate_512_avx2, XXH3_scrambleAcc_avx2); } #endif #ifdef XXH_DISPATCH_AVX512 XXH_NO_INLINE XXH_TARGET_AVX512 XXH_errorcode XXH3_128bits_update_avx512(XXH3_state_t* state, const void* input, size_t len) { return XXH3_update(state, (const xxh_u8*)input, len, XXH3_accumulate_512_avx512, XXH3_scrambleAcc_avx512); } #endif /* ==== Dispatchers ==== */ typedef XXH64_hash_t (*XXH3_dispatchx86_hashLong64_default)(const void* XXH_RESTRICT, size_t); typedef XXH64_hash_t (*XXH3_dispatchx86_hashLong64_withSeed)(const void* XXH_RESTRICT, size_t, XXH64_hash_t); typedef XXH64_hash_t (*XXH3_dispatchx86_hashLong64_withSecret)(const void* XXH_RESTRICT, size_t, const void* XXH_RESTRICT, size_t); typedef XXH_errorcode (*XXH3_dispatchx86_update)(XXH3_state_t*, const void*, size_t); typedef struct { XXH3_dispatchx86_hashLong64_default hashLong64_default; XXH3_dispatchx86_hashLong64_withSeed hashLong64_seed; XXH3_dispatchx86_hashLong64_withSecret hashLong64_secret; XXH3_dispatchx86_update update; } dispatchFunctions_s; static dispatchFunctions_s g_dispatch = { NULL, NULL, NULL, NULL}; #define NB_DISPATCHES 4 static const dispatchFunctions_s k_dispatch[NB_DISPATCHES] = { /* scalar */ { XXHL64_default_scalar, XXHL64_seed_scalar, XXHL64_secret_scalar, XXH3_64bits_update_scalar }, /* sse2 */ { XXHL64_default_sse2, XXHL64_seed_sse2, XXHL64_secret_sse2, XXH3_64bits_update_sse2 }, #ifdef XXH_DISPATCH_AVX2 /* avx2 */ { XXHL64_default_avx2, XXHL64_seed_avx2, XXHL64_secret_avx2, XXH3_64bits_update_avx2 }, #else /* avx2 */ { NULL, NULL, NULL, NULL }, #endif #ifdef XXH_DISPATCH_AVX512 /* avx512 */ { XXHL64_default_avx512, XXHL64_seed_avx512, XXHL64_secret_avx512, XXH3_64bits_update_avx512 } #else /* avx512 */ { NULL, NULL, NULL, NULL } #endif }; typedef XXH128_hash_t (*XXH3_dispatchx86_hashLong128_default)(const void* XXH_RESTRICT, size_t); typedef XXH128_hash_t (*XXH3_dispatchx86_hashLong128_withSeed)(const void* XXH_RESTRICT, size_t, XXH64_hash_t); typedef XXH128_hash_t (*XXH3_dispatchx86_hashLong128_withSecret)(const void* XXH_RESTRICT, size_t, const void* XXH_RESTRICT, size_t); typedef struct { XXH3_dispatchx86_hashLong128_default hashLong128_default; XXH3_dispatchx86_hashLong128_withSeed hashLong128_seed; XXH3_dispatchx86_hashLong128_withSecret hashLong128_secret; XXH3_dispatchx86_update update; } dispatch128Functions_s; static dispatch128Functions_s g_dispatch128 = { NULL, NULL, NULL, NULL }; static const dispatch128Functions_s k_dispatch128[NB_DISPATCHES] = { /* scalar */ { XXHL128_default_scalar, XXHL128_seed_scalar, XXHL128_secret_scalar, XXH3_128bits_update_scalar }, /* sse2 */ { XXHL128_default_sse2, XXHL128_seed_sse2, XXHL128_secret_sse2, XXH3_128bits_update_sse2 }, #ifdef XXH_DISPATCH_AVX2 /* avx2 */ { XXHL128_default_avx2, XXHL128_seed_avx2, XXHL128_secret_avx2, XXH3_128bits_update_avx2 }, #else /* avx2 */ { NULL, NULL, NULL, NULL }, #endif #ifdef XXH_DISPATCH_AVX512 /* avx512 */ { XXHL128_default_avx512, XXHL128_seed_avx512, XXHL128_secret_avx512, XXH3_128bits_update_avx512 } #else /* avx512 */ { NULL, NULL, NULL, NULL } #endif }; static void setDispatch(void) { int vecID = XXH_featureTest(); XXH_STATIC_ASSERT(XXH_AVX512 == NB_DISPATCHES-1); assert(XXH_SCALAR <= vecID && vecID <= XXH_AVX512); #ifndef XXH_DISPATCH_AVX512 assert(vecID != XXH_AVX512); #endif #ifndef XXH_DISPATCH_AVX2 assert(vecID != XXH_AVX2); #endif g_dispatch = k_dispatch[vecID]; g_dispatch128 = k_dispatch128[vecID]; } /* ==== XXH3 public functions ==== */ static XXH64_hash_t XXH3_hashLong_64b_defaultSecret_selection(const void* input, size_t len, XXH64_hash_t seed64, const xxh_u8* secret, size_t secretLen) { (void)seed64; (void)secret; (void)secretLen; if (g_dispatch.hashLong64_default == NULL) setDispatch(); return g_dispatch.hashLong64_default(input, len); } XXH64_hash_t XXH3_64bits_dispatch(const void* input, size_t len) { return XXH3_64bits_internal(input, len, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_defaultSecret_selection); } static XXH64_hash_t XXH3_hashLong_64b_withSeed_selection(const void* input, size_t len, XXH64_hash_t seed64, const xxh_u8* secret, size_t secretLen) { (void)secret; (void)secretLen; if (g_dispatch.hashLong64_seed == NULL) setDispatch(); return g_dispatch.hashLong64_seed(input, len, seed64); } XXH64_hash_t XXH3_64bits_withSeed_dispatch(const void* input, size_t len, XXH64_hash_t seed) { return XXH3_64bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_withSeed_selection); } static XXH64_hash_t XXH3_hashLong_64b_withSecret_selection(const void* input, size_t len, XXH64_hash_t seed64, const xxh_u8* secret, size_t secretLen) { (void)seed64; if (g_dispatch.hashLong64_secret == NULL) setDispatch(); return g_dispatch.hashLong64_secret(input, len, secret, secretLen); } XXH64_hash_t XXH3_64bits_withSecret_dispatch(const void* input, size_t len, const void* secret, size_t secretLen) { return XXH3_64bits_internal(input, len, 0, secret, secretLen, XXH3_hashLong_64b_withSecret_selection); } XXH_errorcode XXH3_64bits_update_dispatch(XXH3_state_t* state, const void* input, size_t len) { if (g_dispatch.update == NULL) setDispatch(); return g_dispatch.update(state, (const xxh_u8*)input, len); } /* ==== XXH128 public functions ==== */ static XXH128_hash_t XXH3_hashLong_128b_defaultSecret_selection(const void* input, size_t len, XXH64_hash_t seed64, const void* secret, size_t secretLen) { (void)seed64; (void)secret; (void)secretLen; if (g_dispatch128.hashLong128_default == NULL) setDispatch(); return g_dispatch128.hashLong128_default(input, len); } XXH128_hash_t XXH3_128bits_dispatch(const void* input, size_t len) { return XXH3_128bits_internal(input, len, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_128b_defaultSecret_selection); } static XXH128_hash_t XXH3_hashLong_128b_withSeed_selection(const void* input, size_t len, XXH64_hash_t seed64, const void* secret, size_t secretLen) { (void)secret; (void)secretLen; if (g_dispatch128.hashLong128_seed == NULL) setDispatch(); return g_dispatch128.hashLong128_seed(input, len, seed64); } XXH128_hash_t XXH3_128bits_withSeed_dispatch(const void* input, size_t len, XXH64_hash_t seed) { return XXH3_128bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_128b_withSeed_selection); } static XXH128_hash_t XXH3_hashLong_128b_withSecret_selection(const void* input, size_t len, XXH64_hash_t seed64, const void* secret, size_t secretLen) { (void)seed64; if (g_dispatch128.hashLong128_secret == NULL) setDispatch(); return g_dispatch128.hashLong128_secret(input, len, secret, secretLen); } XXH128_hash_t XXH3_128bits_withSecret_dispatch(const void* input, size_t len, const void* secret, size_t secretLen) { return XXH3_128bits_internal(input, len, 0, secret, secretLen, XXH3_hashLong_128b_withSecret_selection); } XXH_errorcode XXH3_128bits_update_dispatch(XXH3_state_t* state, const void* input, size_t len) { if (g_dispatch128.update == NULL) setDispatch(); return g_dispatch128.update(state, (const xxh_u8*)input, len); } #if defined (__cplusplus) } #endif
12,642
2,230
package com.folioreader.util; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.os.Build; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.util.StateSet; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.ColorRes; import androidx.core.content.ContextCompat; import com.folioreader.AppContext; import com.folioreader.R; import com.folioreader.ui.view.UnderlinedTextView; import org.json.JSONException; import org.json.JSONObject; import java.lang.ref.SoftReference; import java.lang.reflect.Field; import java.util.Hashtable; /** * Created by mahavir on 3/30/16. */ public class UiUtil { private static final String LOG_TAG = UiUtil.class.getSimpleName(); public static void setCustomFont(View view, Context ctx, AttributeSet attrs, int[] attributeSet, int fontId) { TypedArray a = ctx.obtainStyledAttributes(attrs, attributeSet); String customFont = a.getString(fontId); setCustomFont(view, ctx, customFont); a.recycle(); } public static boolean setCustomFont(View view, Context ctx, String asset) { if (TextUtils.isEmpty(asset)) return false; Typeface tf = null; try { tf = getFont(ctx, asset); if (view instanceof TextView) { ((TextView) view).setTypeface(tf); } else { ((Button) view).setTypeface(tf); } } catch (Exception e) { Log.e("AppUtil", "Could not get typface " + asset); return false; } return true; } private static final Hashtable<String, SoftReference<Typeface>> fontCache = new Hashtable<String, SoftReference<Typeface>>(); public static Typeface getFont(Context c, String name) { synchronized (fontCache) { if (fontCache.get(name) != null) { SoftReference<Typeface> ref = fontCache.get(name); if (ref.get() != null) { return ref.get(); } } Typeface typeface = Typeface.createFromAsset(c.getAssets(), name); fontCache.put(name, new SoftReference<Typeface>(typeface)); return typeface; } } public static ColorStateList getColorList(@ColorInt int selectedColor, @ColorInt int unselectedColor) { int[][] states = new int[][]{ new int[]{android.R.attr.state_selected}, new int[]{} }; int[] colors = new int[]{ selectedColor, unselectedColor }; ColorStateList list = new ColorStateList(states, colors); return list; } public static void keepScreenAwake(boolean enable, Context context) { if (enable) { ((Activity) context) .getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { ((Activity) context) .getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } public static void setBackColorToTextView(UnderlinedTextView textView, String type) { Context context = textView.getContext(); if (type.equals("highlight_yellow")) { setUnderLineColor(textView, context, R.color.highlight_yellow, R.color.highlight_yellow); } else if (type.equals("highlight_green")) { setUnderLineColor(textView, context, R.color.highlight_green, R.color.highlight_green); } else if (type.equals("highlight_blue")) { setUnderLineColor(textView, context, R.color.highlight_blue, R.color.highlight_blue); } else if (type.equals("highlight_pink")) { setUnderLineColor(textView, context, R.color.highlight_pink, R.color.highlight_pink); } else if (type.equals("highlight_underline")) { setUnderLineColor(textView, context, android.R.color.transparent, android.R.color.holo_red_dark); textView.setUnderlineWidth(2.0f); } } private static void setUnderLineColor(UnderlinedTextView underlinedTextView, Context context, int background, int underlinecolor) { underlinedTextView.setBackgroundColor(ContextCompat.getColor(context, background)); underlinedTextView.setUnderLineColor(ContextCompat.getColor(context, underlinecolor)); } public static float convertDpToPixel(float dp, Context context) { return dp * context.getResources().getDisplayMetrics().density; } public static void copyToClipboard(Context context, String text) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("copy", text); clipboard.setPrimaryClip(clip); } public static void share(Context context, String text) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, text); sendIntent.setType("text/plain"); context.startActivity(Intent.createChooser(sendIntent, context.getResources().getText(R.string.send_to))); } public static void setColorIntToDrawable(@ColorInt int color, Drawable drawable) { drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } public static void setColorResToDrawable(@ColorRes int colorResId, Drawable drawable) { try { int color = ContextCompat.getColor(AppContext.get(), colorResId); drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } catch (Resources.NotFoundException e) { Log.e(LOG_TAG, "-> Exception in setColorResToDrawable -> ", e); } } public static void setEditTextCursorColor(EditText editText, @ColorInt int color) { try { // Get the cursor resource id Field field = TextView.class.getDeclaredField("mCursorDrawableRes"); field.setAccessible(true); int drawableResId = field.getInt(editText); // Get the drawable and set a color filter Drawable drawable = ContextCompat.getDrawable(editText.getContext(), drawableResId); drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN); Drawable[] drawables = {drawable, drawable}; if (Build.VERSION.SDK_INT == 15) { // Get the editor Class<?> drawableFieldClass = TextView.class; // Set the drawables field = drawableFieldClass.getDeclaredField("mCursorDrawable"); field.setAccessible(true); field.set(editText, drawables); } else if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT <= 27) { // Get the editor field = TextView.class.getDeclaredField("mEditor"); field.setAccessible(true); Object editor = field.get(editText); // Set the drawables field = editor.getClass().getDeclaredField("mCursorDrawable"); field.setAccessible(true); field.set(editor, drawables); } else if (Build.VERSION.SDK_INT >= 28) { // TODO -> Not working for 28 // Get the editor field = TextView.class.getDeclaredField("mEditor"); field.setAccessible(true); Object editor = field.get(editText); // Set the drawables field = editor.getClass().getDeclaredField("mDrawableForCursor"); field.setAccessible(true); field.set(editor, drawables[0]); } } catch (Exception e) { Log.e(LOG_TAG, "-> ", e); } } public static void setEditTextHandleColor(EditText editText, @ColorInt int color) { try { // Get the cursor resource id Field fieldLeftRes = TextView.class.getDeclaredField("mTextSelectHandleLeftRes"); fieldLeftRes.setAccessible(true); int leftDrawableResId = fieldLeftRes.getInt(editText); Field fieldRightRes = TextView.class.getDeclaredField("mTextSelectHandleRightRes"); fieldRightRes.setAccessible(true); int rightDrawableResId = fieldRightRes.getInt(editText); Field fieldCenterRes = TextView.class.getDeclaredField("mTextSelectHandleRes"); fieldCenterRes.setAccessible(true); int centerDrawableResId = fieldCenterRes.getInt(editText); // Get the drawable and set a color filter Drawable drawableLeft = ContextCompat.getDrawable(editText.getContext(), leftDrawableResId); drawableLeft.setColorFilter(color, PorterDuff.Mode.SRC_IN); Drawable drawableRight = ContextCompat.getDrawable(editText.getContext(), rightDrawableResId); drawableRight.setColorFilter(color, PorterDuff.Mode.SRC_IN); Drawable drawableCenter = ContextCompat.getDrawable(editText.getContext(), centerDrawableResId); drawableCenter.setColorFilter(color, PorterDuff.Mode.SRC_IN); if (Build.VERSION.SDK_INT == 15) { // Get the editor Class<?> drawableFieldClass = TextView.class; // Set the drawables Field fieldLeft = drawableFieldClass.getDeclaredField("mSelectHandleLeft"); fieldLeft.setAccessible(true); fieldLeft.set(editText, drawableLeft); Field fieldRight = drawableFieldClass.getDeclaredField("mSelectHandleRight"); fieldRight.setAccessible(true); fieldRight.set(editText, drawableRight); Field fieldCenter = drawableFieldClass.getDeclaredField("mSelectHandleCenter"); fieldCenter.setAccessible(true); fieldCenter.set(editText, drawableCenter); } else { // Get the editor Field fieldEditor = TextView.class.getDeclaredField("mEditor"); fieldEditor.setAccessible(true); Object editor = fieldEditor.get(editText); // Set the drawables Field fieldLeft = editor.getClass().getDeclaredField("mSelectHandleLeft"); fieldLeft.setAccessible(true); fieldLeft.set(editor, drawableLeft); Field fieldRight = editor.getClass().getDeclaredField("mSelectHandleRight"); fieldRight.setAccessible(true); fieldRight.set(editor, drawableRight); Field fieldCenter = editor.getClass().getDeclaredField("mSelectHandleCenter"); fieldCenter.setAccessible(true); fieldCenter.set(editor, drawableCenter); } } catch (Exception e) { Log.e(LOG_TAG, "-> ", e); } } public static StateListDrawable createStateDrawable(@ColorInt int colorSelected, @ColorInt int colorNormal) { StateListDrawable stateListDrawable = new StateListDrawable(); stateListDrawable.addState(new int[]{android.R.attr.state_selected}, new ColorDrawable(colorSelected)); stateListDrawable.addState(StateSet.WILD_CARD, new ColorDrawable(colorNormal)); return stateListDrawable; } public static GradientDrawable getShapeDrawable(@ColorInt int color) { GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setShape(GradientDrawable.RECTANGLE); gradientDrawable.setStroke(pxToDp(2), color); gradientDrawable.setColor(color); gradientDrawable.setCornerRadius(pxToDp(3)); return gradientDrawable; } public static void setShapeColor(View view, @ColorInt int color) { ((GradientDrawable) view.getBackground()).setColor(color); } public static int pxToDp(int px) { return (int) (px / Resources.getSystem().getDisplayMetrics().density); } public static void setStatusBarColor(Window window, @ColorInt int color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(color); } } public static String rectToDOMRectJson(Rect rect) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("x", rect.left); jsonObject.put("y", rect.top); jsonObject.put("width", rect.width()); jsonObject.put("height", rect.height()); return jsonObject.toString(); } catch (JSONException e) { Log.e(LOG_TAG, "-> ", e); } return null; } }
5,927
11,396
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from awx.main.migrations import ActivityStreamDisabledMigration from awx.main.migrations import _rbac as rbac from awx.main.migrations import _migration_utils as migration_utils class Migration(ActivityStreamDisabledMigration): dependencies = [ ('main', '0021_v330_declare_new_rbac_roles'), ] operations = [ migrations.RunPython(migration_utils.set_current_apps_for_migrations), migrations.RunPython(rbac.create_roles), ]
208
921
# Copyright 2014-2016 Presslabs SRL # # 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. import getpass import os import socket import tempfile import grp import sys from logging import Formatter, StreamHandler from logging.handlers import TimedRotatingFileHandler, SysLogHandler from collections import OrderedDict from six import iteritems from six.moves.urllib.parse import urlparse from gitfs.log import log from gitfs.cache import lru_cache class Args(object): def __init__(self, parser): self.DEFAULTS = OrderedDict( [ ("repo_path", (self.get_repo_path, "string")), ("user", (self.get_current_user, "string")), ("group", (self.get_current_group, "string")), ("username", ("", "string")), ("password", ("", "string")), ("ssh_key", (self.get_ssh_key, "string")), ("ssh_user", (self.get_ssh_user, "string")), ("foreground", (False, "bool")), ("branch", ("master", "string")), ("allow_other", (False, "bool")), ("allow_root", (True, "bool")), ("commiter_name", (self.get_commiter_user, "string")), ("commiter_email", (self.get_commiter_email, "string")), ("max_size", (10, "float")), ("fetch_timeout", (30, "float")), ("idle_fetch_timeout", (30 * 60, "float")), # 30 min ("merge_timeout", (5, "float")), ("debug", (False, "bool")), ("log", ("syslog", "string")), ("log_level", ("warning", "string")), ("cache_size", (800, "int")), ("sentry_dsn", (self.get_sentry_dsn, "string")), ("ignore_file", ("", "string")), ("hard_ignore", ("", "string")), ("min_idle_times", (10, "float")), ("max_open_files", (-1, "int")), ("history_path", ("history", "string")), ("current_path", ("current", "string")), ] ) self.config = self.build_config(parser.parse_args()) def build_config(self, args): if args.o: for arg in args.o.split(","): if "=" in arg: item, value = arg.split("=") setattr(args, item, value) return self.check_args(self.set_defaults(args)) def check_args(self, args): # check allow_other and allow_root if args.allow_other: args.allow_root = False else: args.allow_root = True # check log_level if args.debug: args.log_level = "debug" # setup logging if args.log != "syslog": if args.log in ("-", "/dev/stdout"): handler = StreamHandler(sys.stdout) else: handler = TimedRotatingFileHandler(args.log, when="midnight") handler.setFormatter( Formatter( fmt="%(asctime)s %(threadName)s: " "%(message)s", datefmt="%B-%d-%Y %H:%M:%S", ) ) else: if sys.platform == "darwin": handler = SysLogHandler(address="/var/run/syslog") else: handler = SysLogHandler(address="/dev/log") logger_fmt = ( "GitFS on {mount_point} [%(process)d]: %(threadName)s: " "%(message)s".format(mount_point=args.mount_point) ) handler.setFormatter(Formatter(fmt=logger_fmt)) if args.sentry_dsn != "": from raven.conf import setup_logging from raven.handlers.logging import SentryHandler sentry_handler = SentryHandler( args.sentry_dsn, tags={ "owner": args.user, "remote": args.remote_url, "mountpoint": args.mount_point, }, ) sentry_handler.setLevel("ERROR") setup_logging(sentry_handler) log.addHandler(sentry_handler) handler.setLevel(args.log_level.upper()) log.setLevel(args.log_level.upper()) log.addHandler(handler) # set cache size lru_cache.maxsize = args.cache_size # return absolute repository's path args.repo_path = os.path.abspath(args.repo_path) return args def __getattr__(self, attr): if attr in self.__dict__: return self.__dict__[attr] else: return getattr(self.__dict__["config"], attr) def set_defaults(self, args): for option, value in iteritems(self.DEFAULTS): new_value = getattr(args, option, None) if not new_value: value = value[0] if callable(value): value = value(args) else: if value[1] == "string": value = new_value elif value[1] == "bool": if new_value.lower() == "true": value = True if new_value.lower() == "false": value = False elif value[1] == "float": value = float(new_value) elif value[1] == "int": value = int(new_value) setattr(args, option, value) return args def get_current_group(self, args): gid = os.getegid() return grp.getgrgid(gid).gr_name def get_current_user(self, args): return getpass.getuser() def get_commiter_user(self, args): return args.user def get_commiter_email(self, args): return <EMAIL>(args.<EMAIL>, socket.gethostname()) def get_repo_path(self, args): return tempfile.mkdtemp(dir="/var/lib/gitfs") def get_ssh_key(self, args): return os.getenv("HOME", "/root/") + "/.ssh/id_rsa" def get_sentry_dsn(self, args): return os.environ["SENTRY_DSN"] if "SENTRY_DSN" in os.environ else "" def get_ssh_user(self, args): url = args.remote_url parse_result = urlparse(url) if not parse_result.scheme: url = "ssh://" + url parse_result = urlparse(url) return parse_result.username if parse_result.username else ""
3,466
1,338
<reponame>Kirishikesan/haiku<filename>headers/os/drivers/usb/USB_hid_page_pid.h /* * Copyright 2004-2010, Haiku Inc. All Rights Reserved. * Distributed under the terms of the MIT License. */ #ifndef _USB_HID_PAGE_PHYSICAL_INTERFACE_DEVICE_H #define _USB_HID_PAGE_PHYSICAL_INTERFACE_DEVICE_H /* Reference: * HID Usage Page 0x0F: PHYSICAL INTERFACE DEVICE * Device Class Definition for Physical Interface Deviced (PID) Ver. 1.0 * http://www.usb.org/developers/devclass_docs/pid1_01.pdf */ // UsageIDs enum { B_HID_UID_PID_PHYSICAL_INTERFACE_DEVICE = 0x01, B_HID_UID_PID_NORMAL = 0x20, B_HID_UID_PID_SET_EFFECT_REPORT, B_HID_UID_PID_EFFECT_BLOCK_INDEX, B_HID_UID_PID_PARAMETER_BLOCK_OFFSET, B_HID_UID_PID_ROM_FLAG, B_HID_UID_PID_EFFECT_TYPE, B_HID_UID_PID_ET_CONSTANT_FORCE_DATA, B_HID_UID_PID_ET_SQUARE = 0x30, B_HID_UID_PID_ET_SINE, B_HID_UID_PID_ET_TRIANGLE, B_HID_UID_PID_ET_SAWTOOTH_UP, B_HID_UID_PID_ET_SAWTOOTH_DOWN, B_HID_UID_PID_ET_SPRING, B_HID_UID_PID_ET_DAMPER, B_HID_UID_PID_ET_INERTIA, B_HID_UID_PID_ET_FRICTION, B_HID_UID_PID_DURATION = 0x50, B_HID_UID_PID_SAMPLE_PERIOD, B_HID_UID_PID_GAIN, B_HID_UID_PID_TRIGGER_BUTTON, B_HID_UID_PID_TRIGGER_REPEAT_INTERVAL, B_HID_UID_PID_AXES_ENABLE, B_HID_UID_PID_DIRECTION_ENABLE, B_HID_UID_PID_DIRECTION, B_HID_UID_PID_TYPE_SPECIFIC_BLOCK_OFFSET, B_HID_UID_PID_BLOCK_TYPE, B_HID_UID_PID_SET_ENVELOPE_REPORT, B_HID_UID_PID_ATTACK_LEVEL, B_HID_UID_PID_ATTACK_TIME, B_HID_UID_PID_FADE_LEVEL, B_HID_UID_PID_FADE_TIME, B_HID_UID_PID_SET_CONDITION_REPORT, B_HID_UID_PID_CP_OFFSET, B_HID_UID_PID_POSITIVE_COEFFICIENT, B_HID_UID_PID_NEGATIVE_COEFFICIENT, B_HID_UID_PID_POSITIVE_SATURATION, B_HID_UID_PID_NEGATIVE_SATURATION, B_HID_UID_PID_DEAD_BAND, B_HID_UID_PID_DOWNLOAD_FORCE_SAMPLE, B_HID_UID_PID_ISOCH_CUSTOM_FORCE_ENABLE, B_HID_UID_PID_CUSTOM_FORCE_DATA_REPORT, B_HID_UID_PID_CUSTOM_FORCE_DATA, B_HID_UID_PID_CUSTOM_FORCE_VENDOR_DEFINED_DATA, B_HID_UID_PID_SET_CUSTOM_FORCE_REPORT, B_HID_UID_PID_CUSTOM_FORCE_DATA_OFFSET, B_HID_UID_PID_SAMPLE_COUNT, B_HID_UID_PID_SET_PERIODIC_REPORT, B_HID_UID_PID_OFFSET, B_HID_UID_PID_MAGNITUDE, B_HID_UID_PID_PHASE, B_HID_UID_PID_PERIOD, B_HID_UID_PID_SET_CONSTANT_FORCE_REPORT, B_HID_UID_PID_SET_RAMP_FORCE_REPORT, B_HID_UID_PID_RAMP_START, B_HID_UID_PID_RAMP_END, B_HID_UID_PID_EFFECT_OPERATION_REPORT, B_HID_UID_PID_EFFECT_OPERATION, B_HID_UID_PID_OP_EFFECT_START, B_HID_UID_PID_OP_EFFECT_START_SOLO, B_HID_UID_PID_OP_EFFECT_STOP, B_HID_UID_PID_LOOP_COUNT, B_HID_UID_PID_DEVICE_GAIN_REPORT, B_HID_UID_PID_DEVICE_GAIN, B_HID_UID_PID_PID_POOL_REPORT, B_HID_UID_PID_RAM_POOL_SIZE, B_HID_UID_PID_ROM_POOL_SIZE, B_HID_UID_PID_ROM_EFFECT_BLOCK_COUNT, B_HID_UID_PID_SIMULTANEOUS_EFFECTS_MAX, B_HID_UID_PID_POOL_ALIGNMENT, B_HID_UID_PID_PID_POOL_MOVE_REPORT, B_HID_UID_PID_MOVE_SOURCE, B_HID_UID_PID_MOVE_DESTINATION, B_HID_UID_PID_MOVE_LENGTH, B_HID_UID_PID_PID_BLOCK_LOAD_REPORT, B_HID_UID_PID_BLOCK_LOAD_STATUS = 0x8b, B_HID_UID_PID_BLOCK_LOAD_SUCCESS, B_HID_UID_PID_BLOCK_LOAD_FULL, B_HID_UID_PID_BLOCK_LOAD_ERROR, B_HID_UID_PID_BLOCK_HANDLE, B_HID_UID_PID_PID_BLOCK_FREE_REPORT, B_HID_UID_PID_TYPE_SPECIFIC_BLOCK_HANDLE, B_HID_UID_PID_PID_STATE_REPORT, B_HID_UID_PID_PID_DEVICE_CONTROL_REPORT = 0x95, B_HID_UID_PID_PID_DEVICE_CONTROL, B_HID_UID_PID_DC_ENABLE_ACTUATORS, B_HID_UID_PID_DC_DISABLE_ACTUATORS, B_HID_UID_PID_DC_STOP_ALL_EFFECTS, B_HID_UID_PID_DC_DEVICE_RESET, B_HID_UID_PID_DC_DEVICE_PAUSE, B_HID_UID_PID_DC_DEVICE_CONTINUE, B_HID_UID_PID_DEVICE_PAUSED = 0x9f, B_HID_UID_PID_ACTUATORS_ENABLED, B_HID_UID_PID_SAFETY_SWITCH = 0xa4, B_HID_UID_PID_ACTUATOR_OVERRIDE_SWITCH, B_HID_UID_PID_ACTUATOR_POWER, B_HID_UID_PID_START_DELAY, B_HID_UID_PID_PARAMETER_BLOCK_SIZE, B_HID_UID_PID_DEVICE_MANAGED_POOL, B_HID_UID_PID_SHARED_PARAMETER_BLOCKS, B_HID_UID_PID_CREATE_NEW_EFFECT_REPORT, B_HID_UID_PID_RAM_POOL_AVAILABLE }; #endif // _USB_HID_PAGE_PHYSICAL_INTERFACE_DEVICE_H
2,328
14,668
<gh_stars>1000+ // Copyright 2021 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. #include "android_webview/browser/component_updater/registration.h" #include "android_webview/browser/component_updater/loader_policies/aw_apps_package_names_allowlist_component_loader_policy.h" #include "android_webview/browser/component_updater/origin_trials_component_loader.h" #include "android_webview/browser/component_updater/trust_token_key_commitments_component_loader.h" namespace android_webview { component_updater::ComponentLoaderPolicyVector GetComponentLoaderPolicies() { component_updater::ComponentLoaderPolicyVector policies; LoadTrustTokenKeyCommitmentsComponent(policies); LoadOriginTrialsComponent(policies); LoadPackageNamesAllowlistComponent(policies); return policies; } } // namespace android_webview
275
835
package ai.verta.modeldb.entities.code; import ai.verta.modeldb.versioning.GitCodeBlob; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "git_code_blob") public class GitCodeBlobEntity { public GitCodeBlobEntity() {} public GitCodeBlobEntity(String blobHash, GitCodeBlob gitCodeBlob) { blob_hash = blobHash; repository = gitCodeBlob.getRepo(); commit_hash = gitCodeBlob.getHash(); branch = gitCodeBlob.getBranch(); tag = gitCodeBlob.getTag(); is_dirty = gitCodeBlob.getIsDirty(); } @Id @Column(name = "blob_hash", nullable = false, columnDefinition = "varchar", length = 64) private String blob_hash; @Column(name = "repo") private String repository; @Column(name = "commit_hash", columnDefinition = "varchar", length = 64) private String commit_hash; @Column(name = "branch", columnDefinition = "varchar", length = 64) private String branch; @Column(name = "tag") private String tag; @Column(name = "is_dirty") private Boolean is_dirty; public String getBlobHash() { return blob_hash; } public GitCodeBlob toProto() { return GitCodeBlob.newBuilder() .setRepo(repository) .setHash(commit_hash) .setBranch(branch) .setTag(tag) .setIsDirty(is_dirty) .build(); } }
535
3,651
<filename>core/src/main/java/com/orientechnologies/orient/core/sql/parser/OExpressionStatement.java /* Generated By:JJTree: Do not edit this line. OExpressionStatement.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package com.orientechnologies.orient.core.sql.parser; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.sql.executor.OInternalResultSet; import com.orientechnologies.orient.core.sql.executor.OResultInternal; import com.orientechnologies.orient.core.sql.executor.OResultSet; import java.util.Map; import java.util.Objects; public class OExpressionStatement extends OSimpleExecStatement { protected OExpression expression; public OExpressionStatement(int id) { super(id); } public OExpressionStatement(OrientSql p, int id) { super(p, id); } @Override public OResultSet executeSimple(OCommandContext ctx) { OInternalResultSet result = new OInternalResultSet(); Object expResult = expression.execute(new OResultInternal(), ctx); OResultInternal item = new OResultInternal(); item.setProperty("result", expResult); result.add(item); return result; } @Override public boolean executinPlanCanBeCached() { return false; } @Override public OStatement copy() { OExpressionStatement result = new OExpressionStatement(-1); result.expression = expression.copy(); return result; } @Override public void toString(Map<Object, Object> params, StringBuilder builder) { expression.toString(params, builder); } @Override public boolean refersToParent() { return expression.refersToParent(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OExpressionStatement that = (OExpressionStatement) o; return Objects.equals(expression, that.expression); } @Override public int hashCode() { return Objects.hash(expression); } } /* JavaCC - OriginalChecksum=c3eda193cdcf863b4ced490ef1f37734 (do not edit this line) */
738
310
<reponame>dreeves/usesthis { "name": "FCB1010", "description": "A MIDI foot controller.", "url": "https://www.sweetwater.com/store/detail/FCB1010--behringer-midi-foot-controller-fcb1010" }
79
2,434
<reponame>Secure-AI-Systems-Group/Hardware-Effects #include <iostream> #include <chrono> #ifndef REPETITIONS #define REPETITIONS 1000000 #endif // taken from https://stackoverflow.com/a/8556436/1107768 #define REP0(X) #define REP1(X) X #define REP2(X) REP1(X) X #define REP3(X) REP2(X) X #define REP4(X) REP3(X) X #define REP5(X) REP4(X) X #define REP6(X) REP5(X) X #define REP7(X) REP6(X) X #define REP8(X) REP7(X) X #define REP9(X) REP8(X) X #define REP10(X) REP9(X) X #define REP(HUNDREDS,TENS,ONES,X) \ REP##HUNDREDS(REP10(REP10(X))) \ REP##TENS(REP10(X)) \ REP##ONES(X) int main() { volatile float sum = 0; using Clock = std::chrono::steady_clock; auto start = Clock::now(); for (int i = 0; i < REPETITIONS; i++) { REP(0, 5, 6, sum = i;) // modify this to change the number of stores REP(5, 0, 0, __asm__ __volatile__("nop");) } std::cerr << std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start).count() << std::endl; return 0; }
493
387
{ "name": "libbar", "dependencies": { "libfoo": {"path": "../libfoo", "version": "*", "optional": true} } }
49
1,936
#ifndef DENSE_RECONSTRUCTION_DENSE_RECONSTRUCTION_PLUGIN_H_ #define DENSE_RECONSTRUCTION_DENSE_RECONSTRUCTION_PLUGIN_H_ #include <string> #include <console-common/console-plugin-base-with-plotter.h> #include <console-common/console.h> namespace dense_reconstruction { class DenseReconstructionPlugin : public common::ConsolePluginBaseWithPlotter { public: explicit DenseReconstructionPlugin( common::Console* console, visualization::ViwlsGraphRvizPlotter* plotter); virtual std::string getPluginId() const override { return "dense_reconstruction"; } }; } // namespace dense_reconstruction #endif // DENSE_RECONSTRUCTION_DENSE_RECONSTRUCTION_PLUGIN_H_
233
460
<reponame>juandesant/astrometry.net #include <stdlib.h> #include <stdio.h> #include <string.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix_double.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_blas.h> int main() { int ret; int i, j; gsl_vector* tau; gsl_matrix *A; gsl_matrix *Q, *R, *RTR; gsl_matrix_view Rtop; int M = 4; int N = 3; /* gsl_matrix A; double data[9]; memset(&A, 0, sizeof(gsl_matrix)); A.size1 = 3; A.size2 = 3; A.tda = 3; A.data = data; gsl_matrix_set(&A, 0, 0, 34.0); gsl_matrix_set(&A, 0, 1, 4.0); gsl_matrix_set(&A, 0, 2, 14.0); gsl_matrix_set(&A, 1, 0, 1.0); gsl_matrix_set(&A, 1, 1, 8.0); gsl_matrix_set(&A, 1, 2, 3.0); gsl_matrix_set(&A, 2, 0, 7.0); gsl_matrix_set(&A, 2, 1, 1.0); gsl_matrix_set(&A, 2, 2, 8.0); */ A = gsl_matrix_alloc(M, N); for (i=0; i<M; i++) for (j=0; j<N; j++) gsl_matrix_set(A, i, j, (double)rand()/(double)RAND_MAX); for (i=0; i<A->size1; i++) { printf((i==0) ? "A = (" : " ("); for (j=0; j<A->size2; j++) { printf(" %12.5g ", gsl_matrix_get(A, i, j)); } printf(")\n"); } printf("\n"); tau = gsl_vector_alloc(N); ret = gsl_linalg_QR_decomp(A, tau); Q = gsl_matrix_alloc(M, M); R = gsl_matrix_alloc(M, N); ret = gsl_linalg_QR_unpack(A, tau, Q, R); for (i=0; i<Q->size1; i++) { printf((i==0) ? "Q = (" : " ("); for (j=0; j<Q->size2; j++) { printf(" %12.5g ", gsl_matrix_get(Q, i, j)); } printf(")\n"); } printf("\n"); for (i=0; i<R->size1; i++) { printf((i==0) ? "R = (" : " ("); for (j=0; j<R->size2; j++) { printf(" %12.5g ", gsl_matrix_get(R, i, j)); } printf(")\n"); } printf("\n"); Rtop = gsl_matrix_submatrix(R, 0, 0, N, N); RTR = gsl_matrix_alloc(N, N); gsl_matrix_memcpy(RTR, &(Rtop.matrix)); ret = gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, RTR, RTR); //(Rtop.matrix), &(Rtop.matrix)); for (i=0; i<RTR->size1; i++) { printf((i==0) ? "RTR = (" : " ("); for (j=0; j<RTR->size2; j++) { printf(" %12.5g ", gsl_matrix_get(RTR, i, j)); } printf(")\n"); } printf("\n"); gsl_matrix_free(RTR); gsl_matrix_free(Q); gsl_matrix_free(R); gsl_vector_free(tau); gsl_matrix_free(A); return 0; }
1,297
764
<gh_stars>100-1000 {"symbol": "AGAR","address": "0xb453f1f2EE776dAF2586501361c457dB70e1ca0F","overview":{"en": ""},"email": "","website": "https://agatoken.com/defi/","state": "NORMAL","links": {"blog": "https://agatoken.medium.com/aga-finance-introducing-agar-570d225bd697","twitter": "https://twitter.com/agatkn","telegram": "","github": ""}}
132
335
<gh_stars>100-1000 { "word": "Timorous", "definitions": [ "full of fear; fearful: The noise made them timorous.", "subject to fear; timid.", "characterized by or indicating fear: a timorous whisper." ], "parts-of-speech": "Adjective" }
112
746
<filename>libs/mrwebrtc/src/media/video_track_source.cpp // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "pch.h" #include "interop/global_factory.h" #include "media/video_track_source.h" namespace Microsoft { namespace MixedReality { namespace WebRTC { VideoSourceAdapter::VideoSourceAdapter( rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source) : source_(std::move(source)), state_(source->state()) {} void VideoSourceAdapter::RegisterObserver(webrtc::ObserverInterface* observer) { observer_ = observer; } void VideoSourceAdapter::UnregisterObserver( webrtc::ObserverInterface* observer) { RTC_DCHECK_EQ(observer_, observer); observer_ = nullptr; } // void VideoSourceAdapter::AddSink(webrtc::AudioTrackSinkInterface* sink) { // sinks_.push_back(sink); //} // // void VideoSourceAdapter::RemoveSink(webrtc::AudioTrackSinkInterface* sink) { // auto it = std::find(sinks_.begin(), sinks_.end(), sink); // if (it != sinks_.end()) { // sinks_.erase(it); // } //} VideoTrackSource::VideoTrackSource( RefPtr<GlobalFactory> global_factory, ObjectType video_track_source_type, rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source) noexcept : TrackedObject(std::move(global_factory), video_track_source_type), source_(std::move(source)) { RTC_CHECK(source_); RTC_CHECK((video_track_source_type == ObjectType::kDeviceVideoTrackSource) || (video_track_source_type == ObjectType::kExternalVideoTrackSource)); } VideoTrackSource::~VideoTrackSource() { if (observer_) { // Track sources need to be manipulated from the worker thread rtc::Thread* const worker_thread = GlobalFactory::InstancePtr()->GetWorkerThread(); worker_thread->Invoke<void>( RTC_FROM_HERE, [&]() { source_->RemoveSink(observer_.get()); }); } } template<class T> void VideoTrackSource::SetCallbackImpl(T callback) noexcept { std::lock_guard<std::mutex> lock(observer_mutex_); if (callback) { // When assigning a new callback, create and register an observer. if (!observer_) { observer_ = std::make_unique<VideoFrameObserver>(); // Track sources need to be manipulated from the worker thread rtc::Thread* const worker_thread = GlobalFactory::InstancePtr()->GetWorkerThread(); worker_thread->Invoke<void>(RTC_FROM_HERE, [&]() { rtc::VideoSinkWants sink_settings{}; sink_settings.rotation_applied = true; source_->AddOrUpdateSink(observer_.get(), sink_settings); }); } observer_->SetCallback(callback); } else { // When clearing the existing callback, unregister and destroy the observer. // This ensures the native source knows when there is no more observer, and // can potentially optimize its behavior. if (observer_) { // Reset the callback. observer_->SetCallback(callback); if (!observer_->HasAnyCallbacks()) { // Detach the observer. // Track sources need to be manipulated from the worker thread rtc::Thread* const worker_thread = GlobalFactory::InstancePtr()->GetWorkerThread(); worker_thread->Invoke<void>( RTC_FROM_HERE, [&]() { source_->RemoveSink(observer_.get()); }); observer_.reset(); } } } } void VideoTrackSource::SetCallback(I420AFrameReadyCallback callback) noexcept { return SetCallbackImpl(callback); } void VideoTrackSource::SetCallback(Argb32FrameReadyCallback callback) noexcept { return SetCallbackImpl(callback); } } // namespace WebRTC } // namespace MixedReality } // namespace Microsoft
1,279
1,346
import logging import os # Setup "TRACE" level TRACE = 5 logging.addLevelName(TRACE, "TRACE") class IntLogger(logging.Logger): ignore = [ r'framework.bundle\contents\resources\versions\2\python\framework\code\sandbox.py', r'trakttv.bundle\contents\code\core\logger.py' ] def findCaller(self): f = logging.currentframe() if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)" while hasattr(f, "f_code"): co = f.f_code path = self.normalize_path(co.co_filename) if not self.valid(path): # Ignore sandbox frame f = f.f_back continue rv = (co.co_filename, f.f_lineno, co.co_name) break return rv @classmethod def valid(cls, path): for suffix in cls.ignore: if path.endswith(suffix): return False return True @staticmethod def normalize_path(path): return os.path.normcase(path) # Setup custom logger class logging.setLoggerClass(IntLogger) class Logger(object): def __init__(self, name=None): name = 'plugin%s' % ( ('.' + name) if name else '' ) self.logger = logging.getLogger(name) def trace(self, message, *args, **kwargs): self.logger.log(TRACE, message, *args, **kwargs) def debug(self, message, *args, **kwargs): self.logger.debug(message, *args, **kwargs) def info(self, message, *args, **kwargs): self.logger.info(message, *args, **kwargs) def warn(self, message, *args, **kwargs): self.logger.warn(message, *args, **kwargs) def error(self, message, *args, **kwargs): self.logger.error(message, *args, **kwargs)
856
2,151
<gh_stars>1000+ // Copyright 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. #include "ios/chrome/browser/sync/sync_setup_service.h" #include <stdio.h> #include "base/metrics/histogram_macros.h" #include "components/prefs/pref_service.h" #include "components/sync/base/stop_source.h" #include "components/sync/base/sync_prefs.h" #include "components/sync/driver/sync_service.h" #include "components/sync/protocol/sync_protocol_error.h" #include "google_apis/gaia/google_service_auth_error.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/pref_names.h" #include "net/base/network_change_notifier.h" namespace { // The set of user-selectable datatypes. This must be in the same order as // |SyncSetupService::SyncableDatatype|. syncer::ModelType kDataTypes[] = { syncer::BOOKMARKS, syncer::TYPED_URLS, syncer::PASSWORDS, syncer::PROXY_TABS, syncer::AUTOFILL, syncer::PREFERENCES, syncer::READING_LIST, }; } // namespace SyncSetupService::SyncSetupService(syncer::SyncService* sync_service, PrefService* prefs) : sync_service_(sync_service), prefs_(prefs) { DCHECK(sync_service_); DCHECK(prefs_); for (unsigned int i = 0; i < arraysize(kDataTypes); ++i) { user_selectable_types_.Put(kDataTypes[i]); } } SyncSetupService::~SyncSetupService() { } syncer::ModelType SyncSetupService::GetModelType(SyncableDatatype datatype) { DCHECK(datatype < arraysize(kDataTypes)); return kDataTypes[datatype]; } syncer::ModelTypeSet SyncSetupService::GetPreferredDataTypes() const { return sync_service_->GetPreferredDataTypes(); } bool SyncSetupService::IsDataTypeActive(syncer::ModelType datatype) const { return sync_service_->GetActiveDataTypes().Has(datatype); } bool SyncSetupService::IsDataTypePreferred(syncer::ModelType datatype) const { return GetPreferredDataTypes().Has(datatype); } void SyncSetupService::SetDataTypeEnabled(syncer::ModelType datatype, bool enabled) { sync_blocker_ = sync_service_->GetSetupInProgressHandle(); syncer::ModelTypeSet types = GetPreferredDataTypes(); if (enabled) types.Put(datatype); else types.Remove(datatype); types.RetainAll(user_selectable_types_); if (enabled && !IsSyncEnabled()) SetSyncEnabledWithoutChangingDatatypes(true); sync_service_->OnUserChoseDatatypes(IsSyncingAllDataTypes(), types); if (GetPreferredDataTypes().Empty()) SetSyncEnabled(false); } bool SyncSetupService::UserActionIsRequiredToHaveSyncWork() { if (!IsSyncEnabled() || !IsDataTypePreferred(syncer::PROXY_TABS)) { return true; } switch (this->GetSyncServiceState()) { // No error. case SyncSetupService::kNoSyncServiceError: // These errors are transient and don't mean that sync is off. case SyncSetupService::kSyncServiceCouldNotConnect: case SyncSetupService::kSyncServiceServiceUnavailable: return false; // These errors effectively amount to disabled sync and require a signin. case SyncSetupService::kSyncServiceSignInNeedsUpdate: case SyncSetupService::kSyncServiceNeedsPassphrase: case SyncSetupService::kSyncServiceUnrecoverableError: return true; default: NOTREACHED() << "Unknown sync service state."; return true; } } bool SyncSetupService::IsSyncingAllDataTypes() const { syncer::SyncPrefs sync_prefs(prefs_); return sync_prefs.HasKeepEverythingSynced(); } void SyncSetupService::SetSyncingAllDataTypes(bool sync_all) { sync_blocker_ = sync_service_->GetSetupInProgressHandle(); if (sync_all && !IsSyncEnabled()) SetSyncEnabled(true); sync_service_->OnUserChoseDatatypes( sync_all, Intersection(GetPreferredDataTypes(), syncer::UserSelectableTypes())); } bool SyncSetupService::IsSyncEnabled() const { return sync_service_->CanSyncStart(); } void SyncSetupService::SetSyncEnabled(bool sync_enabled) { SetSyncEnabledWithoutChangingDatatypes(sync_enabled); if (sync_enabled && GetPreferredDataTypes().Empty()) SetSyncingAllDataTypes(true); } SyncSetupService::SyncServiceState SyncSetupService::GetSyncServiceState() { switch (sync_service_->GetAuthError().state()) { case GoogleServiceAuthError::REQUEST_CANCELED: return kSyncServiceCouldNotConnect; // Based on sync_ui_util::GetStatusLabelsForAuthError, SERVICE_UNAVAILABLE // corresponds to sync having been disabled for the user's domain. case GoogleServiceAuthError::SERVICE_UNAVAILABLE: return kSyncServiceServiceUnavailable; case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: return kSyncServiceSignInNeedsUpdate; // The following errors are not shown to the user. case GoogleServiceAuthError::NONE: // Connection failed is not shown to the user, as this will happen if the // service retuned a 500 error. A more detail error can always be checked // on about:sync. case GoogleServiceAuthError::CONNECTION_FAILED: case GoogleServiceAuthError::USER_NOT_SIGNED_UP: case GoogleServiceAuthError::UNEXPECTED_SERVICE_RESPONSE: break; // The following errors are unexpected on iOS. case GoogleServiceAuthError::CAPTCHA_REQUIRED: case GoogleServiceAuthError::ACCOUNT_DELETED: case GoogleServiceAuthError::ACCOUNT_DISABLED: case GoogleServiceAuthError::TWO_FACTOR: case GoogleServiceAuthError::HOSTED_NOT_ALLOWED_DEPRECATED: case GoogleServiceAuthError::SERVICE_ERROR: case GoogleServiceAuthError::WEB_LOGIN_REQUIRED: // Conventional value for counting the states, never used. case GoogleServiceAuthError::NUM_STATES: NOTREACHED() << "Unexpected Auth error (" << sync_service_->GetAuthError().state() << "): " << sync_service_->GetAuthError().error_message(); break; } if (sync_service_->HasUnrecoverableError()) return kSyncServiceUnrecoverableError; if (sync_service_->IsPassphraseRequiredForDecryption()) return kSyncServiceNeedsPassphrase; return kNoSyncServiceError; } bool SyncSetupService::HasFinishedInitialSetup() { // Sync initial setup is considered to finished iff: // 1. User is signed in with sync enabled and the sync setup was completed. // OR // 2. User is not signed in or has disabled sync. return !sync_service_->CanSyncStart() || sync_service_->IsFirstSetupComplete(); } void SyncSetupService::PrepareForFirstSyncSetup() { // |PrepareForFirstSyncSetup| should always be called while the user is signed // out. At that time, sync setup is not completed. DCHECK(!sync_service_->IsFirstSetupComplete()); sync_blocker_ = sync_service_->GetSetupInProgressHandle(); } void SyncSetupService::CommitChanges() { if (sync_service_->IsFirstSetupInProgress()) { // Turn on the sync setup completed flag only if the user did not turn sync // off. if (sync_service_->CanSyncStart()) { sync_service_->SetFirstSetupComplete(); } } sync_blocker_.reset(); } bool SyncSetupService::HasUncommittedChanges() { return sync_service_->IsSetupInProgress(); } void SyncSetupService::SetSyncEnabledWithoutChangingDatatypes( bool sync_enabled) { sync_blocker_ = sync_service_->GetSetupInProgressHandle(); if (sync_enabled) { sync_service_->RequestStart(); } else { UMA_HISTOGRAM_ENUMERATION("Sync.StopSource", syncer::CHROME_SYNC_SETTINGS, syncer::STOP_SOURCE_LIMIT); sync_service_->RequestStop(syncer::SyncService::KEEP_DATA); } }
2,654
9,682
/* * Copyright 2020 Google LLC * * 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. */ package com.google.auto.value.extension.serializable.serializer.runtime; import java.util.function.Function; /** A utility for lambdas that throw exceptions. */ public final class FunctionWithExceptions { /** Creates a wrapper for lambdas that converts checked exceptions to runtime exceptions. */ public static <I, O> Function<I, O> wrapper(FunctionWithException<I, O> fe) { return arg -> { try { return fe.apply(arg); } catch (Exception e) { throw new RuntimeException(e); } }; } /** A function that can throw an exception. */ @FunctionalInterface public interface FunctionWithException<I, O> { O apply(I i) throws Exception; } private FunctionWithExceptions() {} }
383
5,938
# Copyright 2021 Google LLC # # 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 # # https: // 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. # [START aiplatform_tfkeras_task] """Trains a Keras model to predict number of trips started and ended at Citibike stations. """ # [START aiplatform_tfkeras_task_imports] import argparse import os import tensorflow as tf from trainer import utils from trainer.tfkeras_model import model # [END aiplatform_tfkeras_task_imports] # [START aiplatform_tfkeras_task_args] def get_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument( "--input-path", type=str, required=True, help="path to input data" ) parser.add_argument( "--num-epochs", type=int, help="number of times to go through the data, default=20", ) parser.add_argument( "--batch-size", type=int, help="number of records to read during each training step, default=128", ) parser.add_argument( "--learning-rate", type=float, help="learning rate for gradient descent, default=.01", ) parser.add_argument( "--verbosity", choices=["DEBUG", "ERROR", "FATAL", "INFO", "WARN"], default="INFO", ) parser.add_argument( "--model-dir", type=str, help="Output directory for the model.", default=os.getenv("AIP_MODEL_DIR"), ) return parser.parse_args() # [END aiplatform_tfkeras_task_args] # [START aiplatform_tfkeras_task_train_and_evaluate] # [START aiplatform_tfkeras_task_train_and_evaluate_load] def train_and_evaluate( input_path: str, model_dir: str, num_epochs: int = 5, batch_size: int = 128, learning_rate: float = 0.01 ) -> None: """Trains and evaluates the Keras model. Uses the Keras model defined in model.py. Saves the trained model in TensorFlow SavedModel format to the path defined in part by the --job-dir argument.""" # Split datasets into training and testing train_feature, eval_feature, train_target, eval_target = utils.load_data(input_path) # [END aiplatform_tfkeras_task_train_and_evaluate_load] # [START aiplatform_tfkeras_task_train_and_evaluate_dimensions] # Extract dimensions of the data num_train_examples, input_dim = train_feature.shape num_eval_examples = eval_feature.shape[1] output_dim = train_target.shape[1] # [END aiplatform_tfkeras_task_train_and_evaluate_dimensions] # [START aiplatform_tfkeras_task_train_and_evaluate_model] # Create the Keras Model keras_model = model.create_keras_model( input_dim=input_dim, output_dim=output_dim, learning_rate=learning_rate, ) # [END aiplatform_tfkeras_task_train_and_evaluate_model] # [START aiplatform_tfkeras_task_train_and_evaluate_training_data] # Pass a numpy array by passing DataFrame.values training_dataset = model.input_fn( features=train_feature.values, labels=train_target.values, shuffle=True, num_epochs=num_epochs, batch_size=batch_size, ) # [END aiplatform_tfkeras_task_train_and_evaluate_training_data] # [START aiplatform_tfkeras_task_train_and_evaluate_validation_data] # Pass a numpy array by passing DataFrame.values validation_dataset = model.input_fn( features=eval_feature.values, labels=eval_target.values, shuffle=False, num_epochs=num_epochs, batch_size=num_eval_examples, ) # [END aiplatform_tfkeras_task_train_and_evaluate_validation_data] # [START aiplatform_tfkeras_task_train_and_evaluate_fit_export] # Train model keras_model.fit( training_dataset, steps_per_epoch=int(num_train_examples / batch_size), epochs=num_epochs, validation_data=validation_dataset, validation_steps=1, verbose=1, ) # Export model keras_model.save(model_dir) print(f"Model exported to: {model_dir}") # [END aiplatform_tfkeras_task_train_and_evaluate_fit_export] # [END aiplatform_tfkeras_task_train_and_evaluate] if __name__ == "__main__": args = get_args() kwargs = {} if args.num_epochs: kwargs["num-epochs"] = args.num_epochs if args.batch_size: kwargs["batch-size"] = args.batch_size if args.learning_rate: kwargs["learning-rate"] = args.learning_rate tf.compat.v1.logging.set_verbosity(args.verbosity) train_and_evaluate(args.input_path, args.model_dir, **kwargs) # [END aiplatform_tfkeras_task]
2,018
542
<reponame>icemanaf/pear #include <string.h> #include "gtest/gtest.h" extern "C" { #include "sdp_attribute.h" } TEST(sdp_attribute, sdp_attribute_append) { char attributes[] = "a=12345\\r\\nm=12345\\r\\n"; sdp_attribute_t *sdp_attribute = sdp_attribute_create(); sdp_attribute_append(sdp_attribute, (char*)"a=12345"); sdp_attribute_append(sdp_attribute, (char*)"m=12345"); EXPECT_STREQ(sdp_attribute->attributes, attributes); } TEST(sdp_attribute, sdp_attribute_get_answer) { char answer[] = "{\"type\": \"answer\", \"sdp\": \"a=12345\\r\\nm=12345\\r\\n\"}"; sdp_attribute_t *sdp_attribute = sdp_attribute_create(); sdp_attribute_append(sdp_attribute, (char*)"a=12345"); sdp_attribute_append(sdp_attribute, (char*)"m=12345"); EXPECT_STREQ(sdp_attribute_get_answer(sdp_attribute), answer); } GTEST_API_ int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
381
356
#include <bits/stdc++.h> using namespace std; #define N 5 /* Instead of storing a single element at a node, unrolled linked lists store an array of elements at a node. The below program is a simple unrolled linked list with 5 nodes containing a variable number of elements in each. It also traverses the created list. */ //Unrolled Linked List Class class Unrolled { public: int arr[N]; Unrolled *ptr; int capacity; //it is the capacity of number of elements. }; //Printing all the elements of unrolled linked list. //Print elements in current node and moving to next node. void display(Unrolled *ull) { int i; while(ull != NULL) { for(i=0 ; i < ull->capacity ; i++) cout<< ull->arr[i]<<" "; ull = ull->ptr; } } int main() { Unrolled *ul1; int threshold; threshold = ((N/2)+1); //dynamically allocating the four nodes Unrolled* head = new Unrolled; Unrolled* second = new Unrolled; Unrolled* third = new Unrolled; Unrolled* fourth = new Unrolled; //putting values in the first node head->capacity = threshold; head->arr[0] = 1; head->arr[1] = 2; head->arr[2] = 3; //link first node with the second node head->ptr = second; second->capacity = threshold; //putting values in the second node second->arr[0] = 4; second->arr[1] = 5; second->arr[2] = 6; //link second node with the third node second->ptr = third; third->capacity = threshold; //putting values in the third node third->arr[0] = 7; third->arr[1] = 8; third->arr[2] = 9; //link third node with the fourth node third->ptr = fourth; fourth->capacity = threshold; //putting values in the fourth node fourth->arr[0] = 10; fourth->arr[1] = 11; fourth->arr[2] = 12; //the last or the fourth node will point to null fourth->ptr = NULL; display(head); return 0; } /* Complexity: Time complexity : O(n) Test Case 1- Input: 1 2 3 4 5 6 7 8 9 10 11 12 Output: 1 2 3 4 5 6 7 8 9 10 11 12 Test Case 2- Input: 10 20 30 40 50 60 70 80 90 100 110 120 Output: 10 20 30 40 50 60 70 80 90 100 110 120 */
892
342
package com.alibaba.chaosblade.exec.common.util; import org.junit.Assert; import org.junit.Test; public class StringUtilsTest { @Test public void testHasLength() { Assert.assertTrue(StringUtils.hasLength("foo")); Assert.assertFalse(StringUtils.hasLength("")); } @Test public void testHasText() { Assert.assertFalse(StringUtils.hasText(" ")); Assert.assertFalse(StringUtils.hasText(null)); Assert.assertTrue(StringUtils.hasText("foo")); } @Test public void testContainsWhitespace() { Assert.assertFalse(StringUtils.containsWhitespace(null)); Assert.assertFalse(StringUtils.containsWhitespace("foo")); Assert.assertTrue(StringUtils.containsWhitespace(" ")); } @Test public void testTrimWhitespace() { Assert.assertNull(StringUtils.trimWhitespace(null)); Assert.assertEquals("foo", StringUtils.trimWhitespace(" foo ")); } @Test public void testTrimLeadingWhitespace() { Assert.assertNull(StringUtils.trimLeadingWhitespace(null)); Assert.assertEquals("foo ", StringUtils.trimLeadingWhitespace(" foo ")); } @Test public void testTrimLeadingCharacter() { Assert.assertNull(StringUtils.trimLeadingCharacter(null, 'a')); Assert.assertEquals("oo", StringUtils.trimLeadingCharacter("foo", 'f')); } @Test public void testTrimTrailingWhitespace() { Assert.assertNull(StringUtils.trimTrailingWhitespace(null)); Assert.assertEquals(" foo", StringUtils.trimTrailingWhitespace(" foo ")); } @Test public void testTrimAllWhitespace() { Assert.assertNull(StringUtils.trimAllWhitespace(null)); Assert.assertEquals("foo", StringUtils.trimAllWhitespace(" f oo ")); } @Test public void testStartsWithIgnoreCase() { Assert.assertFalse(StringUtils.startsWithIgnoreCase(null, null)); Assert.assertFalse(StringUtils.startsWithIgnoreCase("foo", "foobar")); Assert.assertFalse(StringUtils.startsWithIgnoreCase("foo", "bar")); Assert.assertTrue(StringUtils.startsWithIgnoreCase("foo", "f")); } @Test public void testEndsWithIgnoreCase() { Assert.assertFalse(StringUtils.endsWithIgnoreCase(null, null)); Assert.assertFalse(StringUtils.endsWithIgnoreCase("foo", "foobar")); Assert.assertFalse(StringUtils.endsWithIgnoreCase("foo", "bar")); Assert.assertTrue(StringUtils.endsWithIgnoreCase("foo", "o")); } @Test public void testCountOccurrencesOf() { Assert.assertEquals(0, StringUtils.countOccurrencesOf(null, null)); Assert.assertEquals(2, StringUtils.countOccurrencesOf("foo", "o")); } @Test public void testReplace() { Assert.assertNull(StringUtils.replace(null, null, null)); Assert.assertEquals("foo", StringUtils.replace("foo", null, null)); } @Test public void testDelete() { Assert.assertEquals("f", StringUtils.delete("foo", "o")); } @Test public void testDeleteAny() { Assert.assertNull(StringUtils.deleteAny(null, null)); Assert.assertEquals("f", StringUtils.deleteAny("foo", "o")); } @Test public void testQuoteIfString() { Assert.assertNull(StringUtils.quoteIfString(null)); Assert.assertEquals("'foo'", StringUtils.quoteIfString("foo")); } @Test public void testUnqualify() { Assert.assertEquals("o", StringUtils.unqualify("fo.o")); } @Test public void testCapitalize() { Assert.assertNull(StringUtils.capitalize(null)); Assert.assertEquals("Foo", StringUtils.capitalize("foo")); } @Test public void testUncapitalize() { Assert.assertNull(StringUtils.uncapitalize(null)); Assert.assertEquals("foo", StringUtils.uncapitalize("Foo")); } @Test public void testGetFilename() { Assert.assertNull(StringUtils.getFilename(null)); Assert.assertEquals("foo.txt", StringUtils.getFilename("bar/foo.txt")); } @Test public void textGetFilenameExtension() { Assert.assertNull(StringUtils.getFilenameExtension(null)); Assert.assertEquals("txt", StringUtils.getFilenameExtension("bar/foo.txt")); } @Test public void testStripFilenameExtension() { Assert.assertNull(StringUtils.stripFilenameExtension(null)); Assert.assertEquals("bar/foo", StringUtils.stripFilenameExtension("bar/foo.txt")); } @Test public void testApplyRelativePath() { Assert.assertEquals("bar", StringUtils.applyRelativePath("foo.txt", "bar")); Assert.assertEquals("bar/baz", StringUtils.applyRelativePath("bar/foo.txt", "baz")); } @Test public void testIsNotBlank() { Assert.assertFalse(StringUtils.isNotBlank(" ")); Assert.assertFalse(StringUtils.isNotBlank(null)); Assert.assertTrue(StringUtils.isNotBlank("foo")); } @Test public void testIsNotEmpty() { Assert.assertFalse(StringUtils.isNotEmpty(null)); Assert.assertTrue(StringUtils.isNotEmpty("foo")); } @Test public void testTrimToEmpty() { Assert.assertEquals(StringUtils.EMPTY, StringUtils.trimToEmpty(null)); Assert.assertEquals("foo", StringUtils.trimToEmpty(" foo ")); } @Test public void testTrimToNull() { Assert.assertNull(StringUtils.trimToNull(null)); Assert.assertEquals("foo", StringUtils.trimToNull(" foo ")); } @Test public void testStripComments() { Assert.assertNull(StringUtils.stripComments(null, "foo", "bar", true, true, true, true)); Assert.assertEquals("\u0000", StringUtils.stripComments("\u0000f/o*\no\r\nbar", "foo", "bar", true, true, true, true)); Assert.assertEquals("", StringUtils.stripComments("/f/oo bar", "foo", "bar", true, true, true, true)); Assert.assertEquals("-102o a", StringUtils.stripComments("--foo bar", "foo", "bar", true, true, true, true)); } @Test public void testStartsWithIgnoreCaseAndWs() { Assert.assertFalse(StringUtils.startsWithIgnoreCaseAndWs(null, "a")); Assert.assertFalse(StringUtils.startsWithIgnoreCaseAndWs("bar", "a")); } @Test public void testIsNumeric() { Assert.assertFalse(StringUtils.isNumeric(null)); Assert.assertFalse(StringUtils.isNumeric("foo")); Assert.assertTrue(StringUtils.isNumeric("123")); } }
2,981
882
<filename>src/main/java/water/api/TypeaheadFileRequest.java package water.api; import java.io.File; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import water.persist.PersistHdfs; import water.persist.PersistS3; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.Bucket; import com.google.common.base.Strings; import dontweave.gson.JsonArray; import dontweave.gson.JsonPrimitive; public class TypeaheadFileRequest extends TypeaheadRequest { public TypeaheadFileRequest() { super("Provides a simple JSON array of filtered local files.",""); } protected JsonArray serveFile(String filter, int limit){ File base = null; String filterPrefix = ""; if( !filter.isEmpty() ) { File file = new File(filter); if( file.isDirectory() ) { base = file; } else { base = file.getParentFile(); filterPrefix = file.getName().toLowerCase(); } } if( base == null ) base = new File("."); JsonArray array = new JsonArray(); File[] files = base.listFiles(); if( files == null ) return array; for( File file : files ) { if( file.isHidden() ) continue; if( file.getName().toLowerCase().startsWith(filterPrefix) ) array.add(new JsonPrimitive(file.getPath())); if( array.size() == limit) break; } return array; } protected JsonArray serveHdfs(String filter, int limit){ JsonArray array = new JsonArray(); Configuration conf = PersistHdfs.CONF; if( conf == null ) return array; try { Path p = new Path(filter); Path expand = p; if( !filter.endsWith("/") ) expand = p.getParent(); FileSystem fs = FileSystem.get(p.toUri(), conf); for( FileStatus file : fs.listStatus(expand) ) { Path fp = file.getPath(); if( fp.toString().startsWith(p.toString()) ) { array.add(new JsonPrimitive(fp.toString())); } if( array.size() == limit) break; } } catch( Throwable xe ) { } return array; } protected JsonArray serveS3(String filter, int limit){ JsonArray array = new JsonArray(); try { AmazonS3 s3 = PersistS3.getClient(); filter = Strings.nullToEmpty(filter); for( Bucket b : s3.listBuckets() ) { if( b.getName().startsWith(filter) ) array.add(new JsonPrimitive(b.getName())); if( array.size() == limit) break; } } catch( IllegalArgumentException xe ) { } return array; } @Override final protected JsonArray serve(String filter, int limit) { final String lcaseFilter = filter.toLowerCase(); if(lcaseFilter.startsWith("hdfs://") || lcaseFilter.startsWith("s3n://"))return serveHdfs(filter, limit); if(lcaseFilter.startsWith("s3://")) return serveS3(filter.substring(5), limit); return serveFile(filter,limit); } }
1,132
317
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "mvdTreeWidgetItem.h" /*****************************************************************************/ /* INCLUDE SECTION */ // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) #include <cassert> // // ITK includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) namespace mvd { /* TRANSLATOR mvd::TreeWidgetItem Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*****************************************************************************/ /* CONSTANTS */ namespace { int count = 0; } /*****************************************************************************/ /* STATIC IMPLEMENTATION SECTION */ /*****************************************************************************/ /* CLASS IMPLEMENTATION SECTION */ /*******************************************************************************/ // MANTIS-947: Workaround for QTreeWidget::itemAt() returning NULL for // last item of view after DatabaseBrowserController::UpdateTree() has // been called subsequent to insert new group. // // This workaround reverts the order of insertion of NODE items so // that the last item is always at first index instead of last one. // // Side effect: This inverts the order for all QTreeWidget using // mvd::TreeWidgetItem, not only those in DatabaseBrowser view. #define BUG_WORKAROUND_MANTIS_947 1 TreeWidgetItem::TreeWidgetItem(QTreeWidgetItem* p, const QString& txt, const QVariant& id, const QStringList& columns, TreeWidgetItem::ItemType itemType) : #if BUG_WORKAROUND_MANTIS_947 QTreeWidgetItem(QStringList(txt) << QString() << columns, itemType) #else // BUG_WORKAROUND_MANTIS_947 QTreeWidgetItem(p, QStringList(txt) << QString() << columns, itemType) #endif // BUG_WORKAROUND_MANTIS_947 { assert(p != NULL); // parent->addChild( this ); SetId(id); switch (itemType) { case TreeWidgetItem::ITEM_TYPE_NODE: setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); setFlags( // Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled); #if BUG_WORKAROUND_MANTIS_947 p->insertChild(0, this); #endif // BUG_WORKAROUND_MANTIS_947 break; case TreeWidgetItem::ITEM_TYPE_LEAF: setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicator); setFlags(Qt::ItemIsDragEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable); #if BUG_WORKAROUND_MANTIS_947 p->addChild(this); #endif // BUG_WORKAROUND_MANTIS_947 break; default: assert(false); break; } /* qDebug() << "NEW Item:" << count << "\n" << "type:" << GetType() << "\n" << "id:" << GetId() << "\n" << "text:" << GetText() << "\n" << "hash:" << this->text( 2 ) << "\n" << "parent:" << this->parent() << "\n" << "text[ 0 ]:" << parent->text( 0 ); */ ++count; qDebug() << "Item count:" << count; } /*******************************************************************************/ TreeWidgetItem::~TreeWidgetItem() { /* qDebug() << "DELETE Item:" << "\n" << "type:" << GetType() << "\n" << "id:" << GetId() << "\n" << "text:" << GetText() << "\n" << "hash:" << text( 2 ) << "\n" << "parent:" << parent() << "\n" << "text[ 0 ]:" << (parent()==NULL ? "" : parent()->text( 0 )); */ --count; qDebug() << "Item count:" << count; } /*******************************************************************************/ QTreeWidgetItem* TreeWidgetItem::clone() const { qDebug() << this << "::clone()"; return new TreeWidgetItem(*this); } } // end namespace 'mvd'
1,643
5,133
<reponame>Saljack/mapstruct<gh_stars>1000+ /* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.value.exception; import org.mapstruct.MapperConfig; import org.mapstruct.ap.test.value.CustomIllegalArgumentException; /** * @author <NAME> */ @MapperConfig(unexpectedValueMappingException = CustomIllegalArgumentException.class) public interface Config { }
152
2,728
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import pytest from azure.core.exceptions import ResourceExistsError from azure.storage.fileshare._shared.constants import X_MS_VERSION from azure.storage.fileshare.aio import ( ShareServiceClient, ShareClient, ShareDirectoryClient, ShareFileClient ) from settings.testcase import FileSharePreparer from devtools_testutils.storage.aio import AsyncStorageTestCase # ------------------------------------------------------------------------------ TEST_FILE_PREFIX = 'file' class AsyncStorageClientTest(AsyncStorageTestCase): def setUp(self): super(AsyncStorageTestCase, self).setUp() self.api_version_1 = "2019-02-02" self.api_version_2 = X_MS_VERSION self.short_byte_data = self.get_random_bytes(1024) # --Helpers----------------------------------------------------------------- def _get_file_reference(self, prefix=TEST_FILE_PREFIX): return self.get_resource_name(prefix) async def _create_share(self, fsc): share_name = self.get_resource_name('utshare') share = fsc.get_share_client(share_name) try: await share.create_share() except ResourceExistsError: pass return share async def _delete_share(self, share): try: await share.delete_share() except: pass return share # --Test Cases-------------------------------------------------------------- def test_service_client_api_version_property(self): service_client = ShareServiceClient( "https://foo.file.core.windows.net/account", credential="fake_key") self.assertEqual(service_client.api_version, self.api_version_2) self.assertEqual(service_client._client._config.version, self.api_version_2) with pytest.raises(AttributeError): service_client.api_version = self.api_version_1 service_client = ShareServiceClient( "https://foo.file.core.windows.net/account", credential="fake_key", api_version=self.api_version_1) self.assertEqual(service_client.api_version, self.api_version_1) self.assertEqual(service_client._client._config.version, self.api_version_1) share_client = service_client.get_share_client("foo") self.assertEqual(share_client.api_version, self.api_version_1) self.assertEqual(share_client._client._config.version, self.api_version_1) def test_share_client_api_version_property(self): share_client = ShareClient( "https://foo.file.core.windows.net/account", "share_name", credential="fake_key") self.assertEqual(share_client.api_version, self.api_version_2) self.assertEqual(share_client._client._config.version, self.api_version_2) share_client = ShareClient( "https://foo.file.core.windows.net/account", "share_name", credential="fake_key", api_version=self.api_version_1) self.assertEqual(share_client.api_version, self.api_version_1) self.assertEqual(share_client._client._config.version, self.api_version_1) dir_client = share_client.get_directory_client("foo") self.assertEqual(dir_client.api_version, self.api_version_1) self.assertEqual(dir_client._client._config.version, self.api_version_1) file_client = share_client.get_file_client("foo") self.assertEqual(file_client.api_version, self.api_version_1) self.assertEqual(file_client._client._config.version, self.api_version_1) def test_directory_client_api_version_property(self): dir_client = ShareDirectoryClient( "https://foo.file.core.windows.net/account", "share_name", "dir_path", credential="fake_key") self.assertEqual(dir_client.api_version, self.api_version_2) self.assertEqual(dir_client._client._config.version, self.api_version_2) dir_client = ShareDirectoryClient( "https://foo.file.core.windows.net/account", "share_name", "dir_path", credential="fake_key", api_version=self.api_version_1) self.assertEqual(dir_client.api_version, self.api_version_1) self.assertEqual(dir_client._client._config.version, self.api_version_1) subdir_client = dir_client.get_subdirectory_client("foo") self.assertEqual(subdir_client.api_version, self.api_version_1) self.assertEqual(subdir_client._client._config.version, self.api_version_1) file_client = dir_client.get_file_client("foo") self.assertEqual(file_client.api_version, self.api_version_1) self.assertEqual(file_client._client._config.version, self.api_version_1) def test_file_client_api_version_property(self): file_client = ShareFileClient( "https://foo.file.core.windows.net/account", "share", self._get_file_reference(), credential="fake_key") self.assertEqual(file_client.api_version, self.api_version_2) self.assertEqual(file_client._client._config.version, self.api_version_2) file_client = ShareFileClient( "https://foo.file.core.windows.net/account", "share", self._get_file_reference(), credential="fake_key", api_version=self.api_version_1) self.assertEqual(file_client.api_version, self.api_version_1) self.assertEqual(file_client._client._config.version, self.api_version_1) def test_invalid_api_version(self): with pytest.raises(ValueError) as error: ShareServiceClient( "https://foo.file.core.windows.net/account", credential="fake_key", api_version="foo") self.assertTrue(str(error.value).startswith("Unsupported API version 'foo'.")) with pytest.raises(ValueError) as error: ShareClient( "https://foo.file.core.windows.net/account", "share_name", credential="fake_key", api_version="foo") self.assertTrue(str(error.value).startswith("Unsupported API version 'foo'.")) with pytest.raises(ValueError) as error: ShareDirectoryClient( "https://foo.file.core.windows.net/account", "share_name", "dir_path", credential="fake_key", api_version="foo") self.assertTrue(str(error.value).startswith("Unsupported API version 'foo'.")) with pytest.raises(ValueError) as error: ShareFileClient( "https://foo.file.core.windows.net/account", "share", self._get_file_reference(), credential="fake_key", api_version="foo") self.assertTrue(str(error.value).startswith("Unsupported API version 'foo'.")) @FileSharePreparer() @AsyncStorageTestCase.await_prepared_test async def test_old_api_copy_file_succeeds_async(self, storage_account_name, storage_account_key): fsc = ShareServiceClient( self.account_url(storage_account_name, "file"), credential=storage_account_key, max_range_size=4 * 1024, api_version=self.api_version_1 ) share = await self._create_share(fsc) file_name = self._get_file_reference() source_client = share.get_file_client(file_name) await source_client.upload_file(self.short_byte_data) source_prop = await source_client.get_file_properties() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=share.share_name, file_path='file1copy', credential=storage_account_key, api_version=self.api_version_1) # Act copy = await file_client.start_copy_from_url(source_client.url) # Assert dest_prop = await file_client.get_file_properties() # to make sure the acl is copied from source self.assertEqual(source_prop['permission_key'], dest_prop['permission_key']) self.assertIsNotNone(copy) self.assertEqual(copy['copy_status'], 'success') self.assertIsNotNone(copy['copy_id']) copy_file = await (await file_client.download_file()).readall() self.assertEqual(copy_file, self.short_byte_data) # ------------------------------------------------------------------------------
3,727
8,629
import os import pytest from helpers.cluster import ClickHouseCluster from helpers.test_tools import TSV cluster = ClickHouseCluster(__file__) node = cluster.add_instance( "node", main_configs=["configs/config.d/disable_access_control_improvements.xml"], user_configs=[ "configs/users.d/row_policy.xml", "configs/users.d/another_user.xml", ], ) def copy_policy_xml(local_file_name): script_dir = os.path.dirname(os.path.realpath(__file__)) node.copy_file_to_container( os.path.join(script_dir, local_file_name), "/etc/clickhouse-server/users.d/row_policy.xml", ) node.query("SYSTEM RELOAD CONFIG") @pytest.fixture(scope="module", autouse=True) def started_cluster(): try: cluster.start() node.query( """ CREATE DATABASE mydb; CREATE TABLE mydb.filtered_table1 (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.filtered_table1 values (0, 0), (0, 1), (1, 0), (1, 1); CREATE TABLE mydb.table (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.table values (0, 0), (0, 1), (1, 0), (1, 1); CREATE TABLE mydb.filtered_table2 (a UInt8, b UInt8, c UInt8, d UInt8) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.filtered_table2 values (0, 0, 0, 0), (1, 2, 3, 4), (4, 3, 2, 1), (0, 0, 6, 0); CREATE TABLE mydb.filtered_table3 (a UInt8, b UInt8, c UInt16 ALIAS a + b) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.filtered_table3 values (0, 0), (0, 1), (1, 0), (1, 1); CREATE TABLE mydb.`.filtered_table4` (a UInt8, b UInt8, c UInt16 ALIAS a + b) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.`.filtered_table4` values (0, 0), (0, 1), (1, 0), (1, 1); CREATE TABLE mydb.local (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a; """ ) node.query("INSERT INTO mydb.local values (2, 0), (2, 1), (1, 0), (1, 1)") yield cluster finally: cluster.shutdown() @pytest.fixture(autouse=True) def reset_policies(): try: yield finally: copy_policy_xml("normal_filters.xml") node.query("DROP POLICY IF EXISTS pA, pB ON mydb.filtered_table1") def test_introspection(): policies = [ [ "another ON mydb.filtered_table1", "another", "mydb", "filtered_table1", "6068883a-0e9d-f802-7e22-0144f8e66d3c", "users.xml", "1", 0, 0, "['another']", "[]", ], [ "another ON mydb.filtered_table2", "another", "mydb", "filtered_table2", "c019e957-c60b-d54e-cc52-7c90dac5fb01", "users.xml", "1", 0, 0, "['another']", "[]", ], [ "another ON mydb.filtered_table3", "another", "mydb", "filtered_table3", "4cb080d0-44e8-dbef-6026-346655143628", "users.xml", "1", 0, 0, "['another']", "[]", ], [ "another ON mydb.local", "another", "mydb", "local", "5b23c389-7e18-06bf-a6bc-dd1afbbc0a97", "users.xml", "a = 1", 0, 0, "['another']", "[]", ], [ "default ON mydb.filtered_table1", "default", "mydb", "filtered_table1", "9e8a8f62-4965-2b5e-8599-57c7b99b3549", "users.xml", "a = 1", 0, 0, "['default']", "[]", ], [ "default ON mydb.filtered_table2", "default", "mydb", "filtered_table2", "cffae79d-b9bf-a2ef-b798-019c18470b25", "users.xml", "a + b < 1 or c - d > 5", 0, 0, "['default']", "[]", ], [ "default ON mydb.filtered_table3", "default", "mydb", "filtered_table3", "12fc5cef-e3da-3940-ec79-d8be3911f42b", "users.xml", "c = 1", 0, 0, "['default']", "[]", ], [ "default ON mydb.local", "default", "mydb", "local", "cdacaeb5-1d97-f99d-2bb0-4574f290629c", "users.xml", "1", 0, 0, "['default']", "[]", ], ] assert node.query( "SELECT * from system.row_policies ORDER BY short_name, database, table" ) == TSV(policies) def test_dcl_introspection(): assert node.query("SHOW POLICIES") == TSV( [ "another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3", "another ON mydb.local", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", "default ON mydb.local", ] ) assert node.query("SHOW POLICIES ON mydb.filtered_table1") == TSV( ["another", "default"] ) assert node.query("SHOW POLICIES ON mydb.local") == TSV(["another", "default"]) assert node.query("SHOW POLICIES ON mydb.*") == TSV( [ "another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3", "another ON mydb.local", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", "default ON mydb.local", ] ) assert node.query("SHOW POLICIES default") == TSV( [ "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", "default ON mydb.local", ] ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.local") == "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default\n" ) assert node.query("SHOW CREATE POLICY default") == TSV( [ "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default", "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default", "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default", "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default", ] ) assert node.query("SHOW CREATE POLICIES ON mydb.filtered_table1") == TSV( [ "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 TO another", "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default", ] ) assert node.query("SHOW CREATE POLICIES ON mydb.*") == TSV( [ "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 TO another", "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default", "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default", "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default", "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default", ] ) assert node.query("SHOW CREATE POLICIES") == TSV( [ "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 TO another", "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default", "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default", "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default", "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default", ] ) expected_access = ( "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 TO another\n" "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 TO another\n" "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 TO another\n" "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 TO another\n" "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default\n" "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default\n" "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default\n" "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default\n" ) assert expected_access in node.query("SHOW ACCESS") copy_policy_xml("all_rows.xml") assert node.query("SHOW POLICIES") == TSV( [ "another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", ] ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING 1 TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING 1 TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING 1 TO default\n" ) copy_policy_xml("no_rows.xml") assert node.query("SHOW POLICIES") == TSV( [ "another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", ] ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING NULL TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING NULL TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING NULL TO default\n" ) copy_policy_xml("no_filters.xml") assert node.query("SHOW POLICIES") == "" def test_dcl_management(): copy_policy_xml("no_filters.xml") assert node.query("SHOW POLICIES") == "" node.query("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a<b") assert node.query("SELECT * FROM mydb.filtered_table1") == "" assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pA\n" node.query("ALTER POLICY pA ON mydb.filtered_table1 TO default") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 1]]) assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pA\n" node.query("ALTER POLICY pA ON mydb.filtered_table1 FOR SELECT USING a>b") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0]]) node.query("ALTER POLICY pA ON mydb.filtered_table1 RENAME TO pB") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0]]) assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pB\n" assert ( node.query("SHOW CREATE POLICY pB ON mydb.filtered_table1") == "CREATE ROW POLICY pB ON mydb.filtered_table1 FOR SELECT USING a > b TO default\n" ) node.query("DROP POLICY pB ON mydb.filtered_table1") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV( [[0, 0], [0, 1], [1, 0], [1, 1]] ) assert node.query("SHOW POLICIES") == "" def test_dcl_users_with_policies_from_users_xml(): node.query("CREATE USER X") node.query("GRANT SELECT ON mydb.filtered_table1 TO X") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]]) assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == "" node.query("DROP USER X") def test_some_users_without_policies(): copy_policy_xml("no_filters.xml") assert node.query("SHOW POLICIES") == "" node.query("CREATE USER X, Y") node.query("GRANT SELECT ON mydb.filtered_table1 TO X, Y") # permissive a >= b for X, none for Y node.query( "CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a >= b AS permissive TO X" ) assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == TSV( [[0, 0], [1, 0], [1, 1]] ) assert node.query("SELECT * FROM mydb.filtered_table1", user="Y") == "" # restrictive a >=b for X, none for Y node.query("ALTER POLICY pA ON mydb.filtered_table1 AS restrictive") assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == "" assert node.query("SELECT * FROM mydb.filtered_table1", user="Y") == "" # permissive a >= b for X, restrictive a <= b for X, none for Y node.query("ALTER POLICY pA ON mydb.filtered_table1 AS permissive") node.query( "CREATE POLICY pB ON mydb.filtered_table1 FOR SELECT USING a <= b AS restrictive TO X" ) assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == TSV( [[0, 0], [1, 1]] ) assert node.query("SELECT * FROM mydb.filtered_table1", user="Y") == "" # permissive a >= b for X, restrictive a <= b for Y node.query("ALTER POLICY pB ON mydb.filtered_table1 TO Y") assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == TSV( [[0, 0], [1, 0], [1, 1]] ) assert node.query("SELECT * FROM mydb.filtered_table1", user="Y") == "" node.query("DROP POLICY pA, pB ON mydb.filtered_table1") node.query("DROP USER X, Y")
7,610
4,054
<reponame>Anlon-Burke/vespa // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "unaryfunctionnode.h" #include "integerresultnode.h" #include "resultvector.h" namespace search { namespace expression { class ZCurveFunctionNode : public UnaryFunctionNode { public: enum Dimension {X=0, Y=1}; DECLARE_EXPRESSIONNODE(ZCurveFunctionNode); DECLARE_NBO_SERIALIZE; ZCurveFunctionNode() : _dim(X) { } ZCurveFunctionNode(ExpressionNode::UP arg, Dimension dim) : UnaryFunctionNode(std::move(arg)), _dim(dim) { } ZCurveFunctionNode(const ZCurveFunctionNode & rhs); ZCurveFunctionNode & operator = (const ZCurveFunctionNode & rhs); ~ZCurveFunctionNode(); Dimension getDim() const { return _dim; } private: class Handler { public: Handler(Dimension dim) : _dim(dim) { } virtual ~Handler() { } virtual void handle(const ResultNode & arg) = 0; protected: void handleOne(const ResultNode & arg, Int64ResultNode & result) const { result.set(getXorY(arg.getInteger())); } private: int32_t getXorY(uint64_t z) const; Dimension _dim; }; class SingleValueHandler : public Handler { public: SingleValueHandler(ZCurveFunctionNode & ts) : Handler(ts.getDim()), _result(static_cast<Int64ResultNode &>(ts.updateResult())) { } void handle(const ResultNode & arg) override; private: Int64ResultNode & _result; }; class MultiValueHandler : public Handler { public: MultiValueHandler(ZCurveFunctionNode & ts) : Handler(ts.getDim()), _result(static_cast<IntegerResultNodeVector &>(ts.updateResult())) { } void handle(const ResultNode & arg) override; private: IntegerResultNodeVector & _result; }; bool onExecute() const override; void onPrepareResult() override; Dimension _dim; std::unique_ptr<Handler> _handler; }; } }
755
852
// -*- C++ -*- // // Package: Forward // Class : TotemNumberMerger // // Implementation: // <Notes on implementation> // // Original Author: <NAME> // Created: Tue May 16 10:14:34 CEST 2006 // // system include files // user include files #include "SimG4CMS/Forward/interface/TotemNumberMerger.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" // // constructors and destructor // TotemNumberMerger ::TotemNumberMerger() { #ifdef SCRIVI LogDebug("ForwardSim") << "Creating TotemNumberMerger"; #endif } TotemNumberMerger ::~TotemNumberMerger() { #ifdef SCRIVI LogDebug("ForwardSim") << "Destruction of TotemNumberMerger"; #endif } // // member functions // unsigned long TotemNumberMerger ::Merge(unsigned long value1, unsigned long value2) const { unsigned long c(value1 + value2); unsigned long result(((c * (c + 1)) >> 1) + value1); #ifdef SCRIVI LogDebug("ForwardSim") << "Merge(value1=" << value1 << ", value2=" << value2 << ")=" << result; unsigned long invValue1, invValue2; Split(result, invValue1, invValue2); assert(invValue1 == value1); assert(invValue2 == value2); #endif return result; } unsigned long TotemNumberMerger ::Merge(unsigned long value1, unsigned long value2, unsigned long value3) const { return Merge(Merge(value1, value2), value3); } unsigned long TotemNumberMerger ::Merge(unsigned long value1, unsigned long value2, unsigned long value3, unsigned long value4) const { return Merge(Merge(value1, value2), Merge(value3, value4)); } void TotemNumberMerger ::Split(unsigned long source, unsigned long &value1, unsigned long &value2) const { unsigned long c(static_cast<unsigned long>(floor(sqrt(1. + 8. * static_cast<float>(source)) * 0.5 - 0.5))); value1 = source - ((c * (c + 1)) >> 1); value2 = c - value1; #ifdef SCRIVI LogDebug("ForwardSim") << "source=" << source << ", c=" << c << ", value1=" << value1 << ", value2=" << value2; #endif } void TotemNumberMerger ::Split(unsigned long source, unsigned long &value1, unsigned long &value2, unsigned long &value3) const { unsigned long mix12; Split(source, mix12, value3); Split(mix12, value1, value2); } void TotemNumberMerger ::Split(unsigned long source, unsigned long &value1, unsigned long &value2, unsigned long &value3, unsigned long &value4) const { unsigned long mix12, mix34; Split(source, mix12, mix34); Split(mix12, value1, value2); Split(mix34, value3, value4); }
1,165
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.netbeans.modules.dbschema.nodes; import java.text.MessageFormat; import org.openide.util.NbBundle; import org.openide.nodes.*; import org.netbeans.modules.dbschema.*; /** Node representing a database table. * @see TableElement */ public class TableElementNode extends DBElementNode { /** Return value of getIconAffectingProperties method. */ private static final String[] ICON_AFFECTING_PROPERTIES = new String[] { PROP_TABLE_OR_VIEW }; /** Create a new class node. * @param element class element to represent * @param children node children * @param writeable <code>true</code> to be writable */ public TableElementNode(TableElement element, Children children, boolean writeable) { super(element, children, writeable); setDisplayName(MessageFormat.format((element.isTable() ? NbBundle.getBundle("org.netbeans.modules.dbschema.nodes.Bundle_noi18n").getString("SHORT_tableElement") : NbBundle.getBundle("org.netbeans.modules.dbschema.nodes.Bundle_noi18n").getString("SHORT_viewElement")), new Object[]{super.getDisplayName()})); //NOI18N } /* Resolve the current icon base. * @return icon base string. */ protected String resolveIconBase() { return ((TableElement)element).isView() ? VIEW : TABLE; } /* This method is used for resolving the names of the properties, * which could affect the icon (such as "modifiers"). * @return the appropriate array. */ protected String[] getIconAffectingProperties() { return ICON_AFFECTING_PROPERTIES; } /* Creates property set for this node */ protected Sheet createSheet () { Sheet sheet = Sheet.createDefault(); Sheet.Set ps = sheet.get(Sheet.PROPERTIES); ps.put(createNameProperty(writeable)); ps.put(createTableOrViewProperty(writeable)); return sheet; } /** Create a node property representing the element's name. * @param canW if <code>false</code>, property will be read-only * @return the property. */ protected Node.Property createNameProperty (boolean canW) { return new ElementProp(Node.PROP_NAME, String.class,canW) { /** Gets the value */ public Object getValue () { String name = ((TableElement) element).getName().getFullName(); int pos; pos = name.lastIndexOf("."); //NOI18N if (pos != -1) name = name.substring(pos + 1); return name; } }; } /** Create a property for the table or view flag. * @param canW <code>false</code> to force property to be read-only * @return the property */ protected Node.Property createTableOrViewProperty (boolean canW) { return new ElementProp(PROP_TABLE_OR_VIEW, String.class, canW) { /** Gets the value */ public Object getValue () { if (((TableElement)element).isTableOrView()) return NbBundle.getMessage(TableElementNode.class, "Table"); //NOI18N else return NbBundle.getMessage(TableElementNode.class, "View"); //NOI18N } }; } }
1,426
1,831
<filename>logdevice/common/SocketSender.h /** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <forward_list> #include <folly/ssl/OpenSSLPtrTypes.h> #include "logdevice/common/ConnectionKind.h" #include "logdevice/common/Priority.h" #include "logdevice/common/ResourceBudget.h" #include "logdevice/common/Sender.h" #include "logdevice/common/Timestamp.h" #include "logdevice/common/WeakRefHolder.h" #include "logdevice/common/configuration/NodeLocation.h" #include "logdevice/common/configuration/TrafficClass.h" #include "logdevice/common/configuration/TrafficShapingConfig.h" struct event; struct event_base; namespace facebook { namespace logdevice { namespace configuration { namespace nodes { class NodesConfiguration; }} // namespace configuration::nodes class BWAvailableCallback; class ClientIdxAllocator; class Connection; class FlowGroup; class FlowGroupsUpdate; class IConnectionFactory; class Processor; class SenderImpl; class ShapingContainer; class Socket; class SocketProxy; class StatsHolder; class Worker; struct Settings; /** * The implementation of Sender API which based on using raw folly::AsyncSocket * for connections. See Connection.h for details. */ class SocketSender : public Sender { public: /** * @param node_count the number of nodes in cluster configuration at the * time this Sender was created */ SocketSender( Worker* worker, Processor* processor, std::shared_ptr<const Settings> settings, struct event_base* base, const configuration::ShapingConfig& tsc, ClientIdxAllocator* client_id_allocator, bool is_gossip_sender, std::shared_ptr<const configuration::nodes::NodesConfiguration> nodes, node_index_t my_node_index, folly::Optional<NodeLocation> my_location, std::unique_ptr<IConnectionFactory> connection_factory, StatsHolder* stats); ~SocketSender() override; explicit SocketSender(const Sender&) = delete; explicit SocketSender(Sender&&) noexcept = delete; SocketSender& operator=(const Sender&) = delete; SocketSender& operator=(Sender&&) = delete; /////////// SenderBase API ////////////// bool canSendToImpl(const Address&, TrafficClass, BWAvailableCallback&) override; int sendMessageImpl(std::unique_ptr<Message>&& msg, const Address& addr, BWAvailableCallback* on_bw_avail, SocketCallback* onclose) override; ///////////// Sender API /////////////////// int connect(node_index_t nid) override; int checkServerConnection(node_index_t node) const override; int checkClientConnection(ClientID, bool check_peer_is_node) const override; int closeConnection(const Address&, Status reason) override; bool isClosed(const Address&) const override; int registerOnConnectionClosed(const Address&, SocketCallback& cb) override; void beginShutdown() override; void forceShutdown() override; bool isShutdownCompleted() const override; void forEachConnection( const std::function<void(const ConnectionInfo&)>& cb) const override; const ConnectionInfo* FOLLY_NULLABLE getConnectionInfo(const Address&) const override; bool setConnectionInfo(const Address&, ConnectionInfo&&) override; std::pair<ExtractPeerIdentityResult, PrincipalIdentity> extractPeerIdentity(const Address& addr) override; void fillDebugInfo(InfoSocketsTable& table) const override; void setPeerShuttingDown(node_index_t) override; void noteConfigurationChanged( std::shared_ptr<const configuration::nodes::NodesConfiguration>) override; void onSettingsUpdated(std::shared_ptr<const Settings> new_settings) override; /////////////// Socket-specific Sender API /////////////// /** * Dispatch any accumulated message completions. Must be called from * a context that can tolerate a completion re-entering Sender. */ void deliverCompletedMessages(); ShapingContainer* getNwShapingContainer() { return nw_shaping_container_.get(); } /** * Creates a new client Connection for a newly accepted client connection and * inserts it into the client_sockets_ map. Must be called on the thread * running this Sender's Worker. * * @param fd TCP socket that we got from accept(2) * @param client_addr sockaddr we got from accept(2) * @param conn_token an object used for accepted connection accounting * @param type type of socket (DATA/GOSSIP) * @param conntype type of connection (PLAIN/SSL) * * @return 0 on success, -1 if we failed to create a Connection, sets err to: * EXISTS a Connection for this ClientID already exists * NOMEM a libevent function could not allocate memory * NOBUFS reached internal limit on the number of client * Connections (TODO: implement) INTERNAL failed to set fd non-blocking * (unlikely) */ int addClient(int fd, const Sockaddr& client_addr, ResourceBudget::Token conn_token, SocketType type, ConnectionType conntype, ConnectionKind connection_kind); /** * Called by a Connection managed by this Sender when bytes are added to one * of Connection's queues. These calls should be matched by * noteBytesDrained() calls, such that for each message_type (including * folly::none) the (queued - drained) value reflects the current in-flight * situation. * @param peer_type CLIENT or NODE. * @param message_type If message bytes are added to a queue, message_type is * the type of that message. If message is passed to a evbuffer, * message_type is folly::none. * * @param nbytes how many bytes were appended */ void noteBytesQueued(size_t nbytes, PeerType peer_type, folly::Optional<MessageType> message_type); /** * Called by a Connection managed by this Sender when some bytes from * the Connection output buffer have been drained into the * underlying TCP socket. * @param peer_type CLIENT or NODE. * @param message_type is treated the same way as in * noteBytesQueued() * * @param nbytes how many bytes were sent */ void noteBytesDrained(size_t nbytes, PeerType peer_type, folly::Optional<MessageType> message_type); /** * @return the current total number of bytes in the output evbuffers of * all Connections of all peer types managed by this Sender. */ size_t getBytesPending() const { return bytes_pending_; } /** * @return true iff the total number of bytes in the output evbuffers of * all Connections managed by this Sender exceeds the limit set * in this Processor's configuration */ bool bytesPendingLimitReached(PeerType peer_type) const; /** * Queue a message for a deferred completion. Used from contexts that * must be protected from re-entrance into Sender. */ void queueMessageCompletion(std::unique_ptr<Message>, const Address&, Status, SteadyTimestamp t); /** * Proxy for Connection::getTcpSendBufSize() for a client Connection. Returns * -1 if Connection not found (should never happen). */ ssize_t getTcpSendBufSizeForClient(ClientID client_id) const; /** * Proxy for Connection::getTcpSendBufOccupancy() for a client Connection. * Returns -1 if Connection not found. */ ssize_t getTcpSendBufOccupancyForClient(ClientID client_id) const; /** * @return if this Sender manages a Connection for the node at configuration * position idx, return that Connection. Otherwise return nullptr. * Deprecated : Do not use this API to get Connection. Use of * Connection outside Sender is deprecated. */ Connection* findServerConnection(node_index_t idx) const; /** * Resets the server Connection's connect throttle. If connection does not * exist does nothing. */ void resetServerSocketConnectThrottle(node_index_t node_id); /** * Add a client id to the list of Connections to be erased from * .client_sockets_ next time this object tries to add a new entry to that * map. * * @param client_name id of client Connection to erase * * @return 0 on success, -1 if client_name is not in .client_sockets_, err is * set to NOTFOUND. */ int noteDisconnectedClient(ClientID client_name); // Dumps a human-readable frequency map of queued messages by type. If // `addr` is valid, only messages queued in that Connection are counted. // Otherwise, messages in all Connections are counted. std::string dumpQueuedMessages(Address addr) const; private: // Worker owning this Sender Worker* worker_; Processor* processor_; std::shared_ptr<const Settings> settings_; std::unique_ptr<IConnectionFactory> connection_factory_; // Network Traffic Shaping std::unique_ptr<ShapingContainer> nw_shaping_container_; // Pimpl friend class SenderImpl; std::unique_ptr<SenderImpl> impl_; bool is_gossip_sender_; std::shared_ptr<const configuration::nodes::NodesConfiguration> nodes_; // ids of disconnected Connections to be erased from .client_sockets_ std::forward_list<ClientID> disconnected_clients_; // To avoid re-entering Sender::sendMessage() when low priority messages // are trimmed from a FlowGroup's priority queue, trimmed messages are // accumulated in a deferred completion queue and then processed from // the event loop. CompletionQueue completed_messages_; std::atomic<bool> delivering_completed_messages_{false}; // current number of bytes in all output buffers. std::atomic<size_t> bytes_pending_{0}; // current number of bytes in all output buffers of logdevice client // connections. std::atomic<size_t> bytes_pending_client_{0}; // current number of bytes in all output buffers of node connections. std::atomic<size_t> bytes_pending_node_{0}; // if true, disallow sending messages and initiating connections bool shutting_down_ = false; // The id of this node. // If running on the client, this will be set to NODE_INDEX_INVALID. const node_index_t my_node_index_; // The location of this node (or client). Used to determine whether to use // SSL when connecting. const folly::Optional<NodeLocation> my_location_; void disconnectFromNodesThatChangedAddressOrGeneration(); /** * Tells all open Connections to flush output and close, asynchronously. * isShutdownCompleted() can be used to find out when this operation * completes. Used during shutdown. */ void flushOutputAndClose(Status reason); /** * Unconditionally close all server and clients Connections. */ void closeAllSockets(); /** * Close the Connection for this server * * @param peer Node index for which to close the Connection. * @param reason Reason for closing the Connection. * * @return 0 on success, or -1 if there is no Connection for address `peer`, * in which case err is set to E::NOTFOUND. */ int closeServerSocket(node_index_t peer, Status reason); /** * Close the Connection for a client. * * @param cid Client for which to close the Connection. * @param reason Reason for closing the Connection. * * @return 0 on success, or -1 if there is no Connection for client `cid`, in * which case err is set to E::NOTFOUND. */ int closeClientSocket(ClientID cid, Status reason); /** * A helper method for sending a message to a connected Connection. * * @param msg message to send. Ownership is not transferred unless the call * succeeds. * @param conn client server Connection to send the message into * @param onclose an optional callback to push onto the list of callbacks * that the Connection through which the message gets sent will * call when that Connection is closed. The callback will NOT * be installed if the call fails. * * @return 0 on success, -1 on failure. err is set to * NOBUFS Connection send queue limit was reached * TOOBIG message is too big (exceeds payload size limit) * NOMEM out of kernel memory for sockets, or malloc() failed * CANCELLED msg.cancelled() requested message to be cancelled * INTERNAL bufferevent unexpectedly failed to initiate connection, * unexpected error from socket(2). */ int sendMessageImpl(std::unique_ptr<Message>&& msg, Connection& conn, BWAvailableCallback* on_bw_avail = nullptr, SocketCallback* onclose = nullptr); /** * Returns a Connection to a given node in the cluster config. If a Connection * doesn't exist yet, it will be created. * * This will rely on ssl_boundary setting and target/own location to determine * whether to use SSL. * * @return a pointer to the valid Connection object; on failure returns * nullptr and sets err to NOTINCONFIG nid is not present in the current * cluster config NOSSLCONFIG Connection to nid must use SSL but SSL is not * configured for nid * INTERNAL internal error (debug builds assert) */ Connection* initServerConnection(NodeID nid, SocketType sock_type); /** * This method gets the Connection associated with a given ClientID. The * connection must already exist for this method to succeed. * * @param cid peer name of a client Connection expected to be under the * management of this Sender. * @return the Connection connected to cid or nullptr if an error occured */ Connection* FOLLY_NULLABLE getConnection(const ClientID& cid); /** * This method gets the Connection associated with a given NodeID. It will * attempt to create the connection if it doesn't already exist. * * @param nid peer name of a client Connection expected to be under the * management of this Sender. * @param msg the Message either being sent or received on the * Connection. * @return the Connection connected to nid or nullptr if an error occured */ Connection* FOLLY_NULLABLE getConnection(const NodeID& nid, const Message& msg); /** * This method gets the Connection associated with a given Address. If addr is * a NodeID, it will attempt to create the connection if it doesn't already * exist. Otherwise, the connection must already exist. * * @param addr peer name of a Connection expected to be under the * management of this Sender. * @param msg the Message either being sent or received on the * Connection. * @return the Connection connected to nid or nullptr if an error occured */ Connection* FOLLY_NULLABLE getConnection(const Address& addr, const Message& msg); /** * This method finds any existing Connection associated with a given Address. * * @param addr peer name of a Connection expected to be under the * management of this Sender. * @return the Connection connected to addr or nullptr, with err set, if * the Connection couldn't be found. */ Connection* FOLLY_NULLABLE findConnection(const Address& addr); /** * @return true iff called on the thread that is running this Sender's * Worker. Used in asserts. */ bool onMyWorker() const; /** * Remove client Connections on the disconnected client list from the client * map. Destroy the Connection objects. */ void eraseDisconnectedClients(); /** * Initializes my_node_id_ and my_location_ from the current config and * settings. */ void initMyLocation(); /** * Returns true if SSL should be used with the specified node. * If cross_boundary_out or authentication_out are given, outputs in them * whether SSL should be used for data encryption or for authentication * accordingly. */ bool useSSLWith(node_index_t node_id, bool* cross_boundary = nullptr, bool* authentication = nullptr) const; /** * Closes all Connections in sockets_to_close_ with the specified error codes * and destroys them */ void processSocketsToClose(); /** * Detects and closes connections that are either slow or idle for prolonged * period of time. */ void cleanupConnections(); static void onCompletedMessagesAvailable(void* self, short); /** * Increment the bytes pending for a given peer type. */ void incrementBytesPending(size_t nbytes, PeerType peer_type) { bytes_pending_ += nbytes; switch (peer_type) { case PeerType::CLIENT: bytes_pending_client_ += nbytes; return; case PeerType::NODE: bytes_pending_node_ += nbytes; return; default: ld_check(false); } } /** * Decrement the bytes pending for a given peer type. */ void decrementBytesPending(size_t nbytes, PeerType peer_type) { ld_check(bytes_pending_ >= nbytes); ld_check(getBytesPending(peer_type) >= nbytes); bytes_pending_ -= nbytes; switch (peer_type) { case PeerType::CLIENT: bytes_pending_client_ -= nbytes; return; case PeerType::NODE: bytes_pending_node_ -= nbytes; return; default: ld_check(false); } } size_t getBytesPending(PeerType peer_type) const { switch (peer_type) { case PeerType::CLIENT: return bytes_pending_client_; case PeerType::NODE: return bytes_pending_node_; default: ld_check(false); } return 0; } Connection* FOLLY_NULLABLE findConnection(const Address& addr) const; Connection* FOLLY_NULLABLE findClientConnection(const ClientID& client_id) const; // Iterates over all connections and invokes a callback for each of them. void forAllConnections(const std::function<void(const Connection&)>& cb) const; }; }} // namespace facebook::logdevice
6,354
1,970
<filename>hudi-utilities/src/test/java/org/apache/hudi/utilities/schema/TestSchemaRegistryProvider.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.hudi.utilities.schema; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.avro.Schema; import org.apache.hudi.common.config.TypedProperties; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; class TestSchemaRegistryProvider { private final String basicAuth = "foo:bar"; private final String json = "{\"schema\":\"{\\\"type\\\": \\\"record\\\", \\\"namespace\\\": \\\"example\\\", " + "\\\"name\\\": \\\"FullName\\\",\\\"fields\\\": [{ \\\"name\\\": \\\"first\\\", \\\"type\\\": " + "\\\"string\\\" }]}\"}"; private TypedProperties getProps() { return new TypedProperties() {{ put("hoodie.deltastreamer.schemaprovider.registry.baseUrl", "http://" + basicAuth + "@localhost"); put("hoodie.deltastreamer.schemaprovider.registry.urlSuffix", "-value"); put("hoodie.deltastreamer.schemaprovider.registry.url", "http://foo:bar@localhost"); put("hoodie.deltastreamer.source.kafka.topic", "foo"); } }; } private Schema getExpectedSchema(String response) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8))); return (new Schema.Parser()).parse(node.get("schema").asText()); } private SchemaRegistryProvider getUnderTest(TypedProperties props) throws IOException { InputStream is = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); SchemaRegistryProvider spyUnderTest = Mockito.spy(new SchemaRegistryProvider(props, null)); Mockito.doReturn(is).when(spyUnderTest).getStream(Mockito.any()); return spyUnderTest; } @Test public void testGetSourceSchemaShouldRequestSchemaWithCreds() throws IOException { SchemaRegistryProvider spyUnderTest = getUnderTest(getProps()); Schema actual = spyUnderTest.getSourceSchema(); assertNotNull(actual); assertEquals(actual, getExpectedSchema(json)); verify(spyUnderTest, times(1)).setAuthorizationHeader(eq(basicAuth), Mockito.any(HttpURLConnection.class)); } @Test public void testGetTargetSchemaShouldRequestSchemaWithCreds() throws IOException { SchemaRegistryProvider spyUnderTest = getUnderTest(getProps()); Schema actual = spyUnderTest.getTargetSchema(); assertNotNull(actual); assertEquals(actual, getExpectedSchema(json)); verify(spyUnderTest, times(1)).setAuthorizationHeader(eq(basicAuth), Mockito.any(HttpURLConnection.class)); } @Test public void testGetSourceSchemaShouldRequestSchemaWithoutCreds() throws IOException { TypedProperties props = getProps(); props.put("hoodie.deltastreamer.schemaprovider.registry.url", "http://localhost"); SchemaRegistryProvider spyUnderTest = getUnderTest(props); Schema actual = spyUnderTest.getSourceSchema(); assertNotNull(actual); assertEquals(actual, getExpectedSchema(json)); verify(spyUnderTest, times(0)).setAuthorizationHeader(Mockito.any(), Mockito.any()); } @Test public void testGetTargetSchemaShouldRequestSchemaWithoutCreds() throws IOException { TypedProperties props = getProps(); props.put("hoodie.deltastreamer.schemaprovider.registry.url", "http://localhost"); SchemaRegistryProvider spyUnderTest = getUnderTest(props); Schema actual = spyUnderTest.getTargetSchema(); assertNotNull(actual); assertEquals(actual, getExpectedSchema(json)); verify(spyUnderTest, times(0)).setAuthorizationHeader(Mockito.any(), Mockito.any()); } }
1,643
6,270
<filename>.changes/2.889.0.json [ { "type": "feature", "category": "CostExplorer", "description": "Adding support for Sagemaker savings plans in GetSavingsPlansPurchaseRecommendation API" }, { "type": "feature", "category": "SavingsPlans", "description": "Added support for Amazon SageMaker in Machine Learning Savings Plans" } ]
151
373
// Windows/FileName.h #ifndef __WINDOWS_FILENAME_H #define __WINDOWS_FILENAME_H #include "../../C/7zTypes.h" #include "../Common/MyString.h" namespace NWindows { namespace NFile { namespace NName { int FindSepar(const wchar_t *s) throw(); #ifndef USE_UNICODE_FSTRING int FindSepar(const FChar *s) throw(); #endif const TCHAR kDirDelimiter = CHAR_PATH_SEPARATOR; const TCHAR kAnyStringWildcard = '*'; void NormalizeDirPathPrefix(CSysString &dirPath); // ensures that it ended with '\\' #ifndef _UNICODE void NormalizeDirPathPrefix(UString &dirPath); // ensures that it ended with '\\' #endif bool IsAbsolutePath(const wchar_t *s) throw(); unsigned GetRootPrefixSize(const wchar_t *s) throw(); bool GetFullPath(CFSTR dirPrefix, CFSTR path, FString &fullPath); bool GetFullPath(CFSTR path, FString &fullPath); }}} #endif
304
369
<reponame>aureliony/MSIRGB #pragma once #include "logic\Lighting.h" using namespace System; using namespace System::Windows::Media; namespace MSIRGB { public ref class Lighting { public: enum class FlashingSpeed : Byte { Disabled = static_cast<Byte>(logic::Lighting::FlashingSpeed::Disabled), Speed1 = static_cast<Byte>(logic::Lighting::FlashingSpeed::Speed1), Speed2 = static_cast<Byte>(logic::Lighting::FlashingSpeed::Speed2), Speed3 = static_cast<Byte>(logic::Lighting::FlashingSpeed::Speed3), Speed4 = static_cast<Byte>(logic::Lighting::FlashingSpeed::Speed4), Speed5 = static_cast<Byte>(logic::Lighting::FlashingSpeed::Speed5), Speed6 = static_cast<Byte>(logic::Lighting::FlashingSpeed::Speed6) }; enum class ErrorCode : int { DriverLoadFailed = static_cast<int>(logic::Lighting::ErrorCode::DriverLoadFailed), MotherboardVendorNotSupported = static_cast<int>(logic::Lighting::ErrorCode::MotherboardVendorNotSupported), MotherboardModelNotSupported = static_cast<int>(logic::Lighting::ErrorCode::MotherboardModelNotSupported), MotherboardModelMayOrMayNotBeSupported = static_cast<int>(logic::Lighting::ErrorCode::MotherboardModelMayOrMayNotBeSupported), LoadFailed = static_cast<int>(logic::Lighting::ErrorCode::LoadFailed), }; ref class Exception : public ::Exception { public: Exception(ErrorCode ec) : ::Exception(""), ec(ec) { } ErrorCode GetErrorCode() { return ec; } private: ErrorCode ec; }; literal UInt16 STEP_DURATION_MAX_VALUE = static_cast<UInt16>(logic::Lighting::STEP_DURATION_MAX_VALUE); Lighting(Boolean ignoreMbCheck) { try { lighting = new logic::Lighting(ignoreMbCheck); } catch (logic::Lighting::Exception &e) { throw gcnew Exception(static_cast<ErrorCode>(e.error_code())); } } ~Lighting() { delete lighting; } bool BatchBegin() { return lighting->batch_begin(); } void SetLedEnabled(bool enable) { lighting->set_led_enabled(enable); } bool SetColour(Byte index, Color colour) { return lighting->set_colour(index, logic::Lighting::Colour{ colour.R, colour.G, colour.B }); } Nullable<Color> GetColour(Byte index) { std::optional<logic::Lighting::Colour> colour = lighting->get_colour(index); if (!colour) { return Nullable<Color>(); } return Nullable<Color>(Color::FromRgb(colour->r, colour->g, colour->b)); } Boolean GetDefaultColourChannelsInvertedSetting() { return lighting->get_default_colour_channels_inverted_setting(); } void SetRChannelInverted(Boolean inverted) { lighting->set_r_channel_inverted(inverted); } void SetGChannelInverted(Boolean inverted) { lighting->set_g_channel_inverted(inverted); } void SetBChannelInverted(Boolean inverted) { lighting->set_b_channel_inverted(inverted); } Boolean IsRChannelInverted() { return lighting->is_r_channel_inverted(); } Boolean IsGChannelInverted() { return lighting->is_g_channel_inverted(); } Boolean IsBChannelInverted() { return lighting->is_b_channel_inverted(); } bool SetBreathingModeEnabled(Boolean enabled) { return lighting->set_breathing_mode_enabled(enabled); } Boolean IsBreathingModeEnabled() { return lighting->is_breathing_mode_enabled(); } Boolean SetStepDuration(UInt16 stepDuration) { return lighting->set_step_duration(stepDuration); } UInt16 GetStepDuration() { return lighting->get_step_duration(); } void SetFlashingSpeed(FlashingSpeed flashSpeed) { lighting->set_flash_speed(static_cast<logic::Lighting::FlashingSpeed>(flashSpeed)); } FlashingSpeed GetFlashingSpeed() { return static_cast<FlashingSpeed>(lighting->get_flash_speed()); } bool BatchEnd() { return lighting->batch_end(); } private: logic::Lighting *lighting; }; }
2,217
597
import re import os from ..anf_util import * class GenerateCompletionListBase(object): """docstring for GenerateCompletionListBase""" def __init__(self, command): super(GenerateCompletionListBase, self).__init__() self.top_level_split_char = ":" self.command = command self.aliases = command.aliases self.settings = command.settings def is_home(self, path): return re.match(r"^~[/\\]", path) def is_alias(self, path): return self.top_level_split_char in path def generate_completion_list(self, path_in): alias_list = [] dir_list = [] file_list = [] if self.is_alias(path_in) or self.is_home(path_in): pass else: directory, filename = os.path.split(path_in) if len(directory) == 0: alias_list += self.generate_alias_auto_complete(filename) alias_list += self.generate_project_auto_complete(filename) base, path = self.command.split_path(path_in) full_path = generate_creation_path(self.settings, base, path) directory, filename = os.path.split(full_path) if os.path.isdir(directory): for d in os.listdir(directory): full_path = os.path.join(directory, d) if os.path.isdir(full_path): is_file = False elif self.settings.get(SHOW_FILES_SETTING): is_file = True else: continue if self.compare_entries(d, filename): if is_file: file_list.append(d) else: dir_list.append(d) completion_list = alias_list + dir_list + file_list return sorted(completion_list), alias_list, dir_list, file_list def generate_project_auto_complete(self, base): folder_data = get_project_folder_data( self.settings.get(USE_FOLDER_NAME_SETTING)) if len(folder_data) > 1: folders = [x[0] for x in folder_data] return self.generate_auto_complete(base, folders) return [] def generate_alias_auto_complete(self, base): return self.generate_auto_complete(base, self.aliases) def generate_auto_complete(self, base, iterable_var): sugg = [] for entry in iterable_var: compare_entry = entry compare_base = base if self.settings.get(IGNORE_CASE_SETTING): compare_entry = compare_entry.lower() compare_base = compare_base.lower() if self.compare_entries(compare_entry, compare_base): if entry not in sugg: sugg.append(entry) return sugg def compare_entries(self, compare_entry, compare_base): if self.settings.get(IGNORE_CASE_SETTING): compare_entry = compare_entry.lower() compare_base = compare_base.lower() return compare_entry.startswith(compare_base)
1,463