hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
089bea6e390cd95f583776dafc8cac12c2be5c8c
2,549
h
C
ns-allinone-3.27/ns-3.27/src/fd-net-device/helper/emu-fd-net-device-helper.h
zack-braun/4607_NS
43c8fb772e5552fb44bd7cd34173e73e3fb66537
[ "MIT" ]
93
2019-04-21T08:22:26.000Z
2022-03-30T04:26:29.000Z
ns-allinone-3.27/ns-3.27/src/fd-net-device/helper/emu-fd-net-device-helper.h
zack-braun/4607_NS
43c8fb772e5552fb44bd7cd34173e73e3fb66537
[ "MIT" ]
12
2019-04-19T16:39:58.000Z
2021-06-22T13:18:32.000Z
ns-allinone-3.27/ns-3.27/src/fd-net-device/helper/emu-fd-net-device-helper.h
zack-braun/4607_NS
43c8fb772e5552fb44bd7cd34173e73e3fb66537
[ "MIT" ]
21
2019-05-27T19:36:12.000Z
2021-07-26T02:37:41.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2012 INRIA, 2012 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #ifndef EMU_FD_NET_DEVICE_HELPER_H #define EMU_FD_NET_DEVICE_HELPER_H #include <string> #include "ns3/attribute.h" #include "ns3/fd-net-device.h" #include "ns3/fd-net-device-helper.h" #include "ns3/object-factory.h" #include "ns3/net-device-container.h" #include "ns3/node-container.h" namespace ns3 { /** * \ingroup fd-net-device * \brief build a set of FdNetDevice objects attached to a physical network * interface * */ class EmuFdNetDeviceHelper : public FdNetDeviceHelper { public: /** * Construct a EmuFdNetDeviceHelper. */ EmuFdNetDeviceHelper (); virtual ~EmuFdNetDeviceHelper () { } /** * Get the device name of this device. * * \returns The device name of this device. */ std::string GetDeviceName (void); /** * Set the device name of this device. * * \param deviceName The device name of this device. */ void SetDeviceName (std::string deviceName); protected: /** * This method creates an ns3::FdNetDevice attached to a physical network * interface * * \param node The node to install the device in * \returns A container holding the added net device. */ Ptr<NetDevice> InstallPriv (Ptr<Node> node) const; /** * Sets a file descriptor on the FileDescriptorNetDevice. */ virtual void SetFileDescriptor (Ptr<FdNetDevice> device) const; /** * Call out to a separate process running as suid root in order to get a raw * socket. We do this to avoid having the entire simulation running as root. * \return the rawSocket number */ virtual int CreateFileDescriptor (void) const; /** * The unix/linux name of the underlying device (e.g., eth0) */ std::string m_deviceName; }; } // namespace ns3 #endif /* EMU_FD_NET_DEVICE_HELPER_H */
26.278351
79
0.704198
[ "object" ]
089cb3ba5d10179e469745b057e2dc92539bacc0
2,504
h
C
src/flow/vm/Program.h
christianparpart/libflow
29c8a4b4c1ba140c1a3998dcb84885386d312787
[ "Unlicense" ]
null
null
null
src/flow/vm/Program.h
christianparpart/libflow
29c8a4b4c1ba140c1a3998dcb84885386d312787
[ "Unlicense" ]
null
null
null
src/flow/vm/Program.h
christianparpart/libflow
29c8a4b4c1ba140c1a3998dcb84885386d312787
[ "Unlicense" ]
null
null
null
// This file is part of the "x0" project, http://github.com/christianparpart/libflow// // (c) 2009-2014 Christian Parpart <trapni@gmail.com> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #pragma once #include <flow/Api.h> #include <flow/vm/ConstantPool.h> #include <flow/vm/Instruction.h> #include <flow/FlowType.h> // FlowNumber #include <stx/net/IPAddress.h> #include <stx/net/Cidr.h> #include <stx/RegExp.h> #include <vector> #include <utility> #include <memory> namespace flow { namespace vm { class Runner; class Runtime; class Handler; class Match; class MatchDef; class NativeCallback; class ConstantPool; class CORTEX_FLOW_API Program { public: explicit Program(ConstantPool&& cp); Program(Program&) = delete; Program& operator=(Program&) = delete; ~Program(); const ConstantPool& constants() const { return cp_; } // accessors to linked data const Match* match(size_t index) const { return matches_[index]; } Handler* handler(size_t index) const { return handlers_[index]; } NativeCallback* nativeHandler(size_t index) const { return nativeHandlers_[index]; } NativeCallback* nativeFunction(size_t index) const { return nativeFunctions_[index]; } // bulk accessors const std::vector<Match*>& matches() const { return matches_; } inline const std::vector<Handler*> handlers() const { return handlers_; } int indexOf(const Handler* handler) const; Handler* findHandler(const std::string& name) const; /** * Convenience method to run a handler. * * @param handlerName The handler's name that is going to be run. * @param u1 Opaque userdata value 1. * @param u2 Opaque userdata value 2. */ bool run(const std::string& handlerName, void* u1 = nullptr, void* u2 = nullptr); bool link(Runtime* runtime); void dump(); private: // builders Handler* createHandler(const std::string& name); Handler* createHandler(const std::string& name, const std::vector<Instruction>& instructions); private: void setup(const std::vector<MatchDef>& matches); private: ConstantPool cp_; // linked data Runtime* runtime_; std::vector<Handler*> handlers_; std::vector<Match*> matches_; std::vector<NativeCallback*> nativeHandlers_; std::vector<NativeCallback*> nativeFunctions_; }; } // namespace vm } // namespace flow
26.357895
86
0.705671
[ "vector" ]
089d3fdf450910258f3b62b165e4ff1ca62745cf
15,873
h
C
clicks/i2cmux5/lib/include/i2cmux5.h
StrahinjaJacimovic/mikrosdk_click_v2
f8002047c96605f340957a0d3fdbde33706d02ac
[ "MIT" ]
31
2020-10-02T14:15:14.000Z
2022-03-24T08:33:21.000Z
clicks/i2cmux5/lib/include/i2cmux5.h
greghol/mikrosdk_click_v2
76e5dec265dce5fca72c4b93f77afd668dde5dfa
[ "MIT" ]
4
2020-10-27T14:05:00.000Z
2022-03-10T09:38:57.000Z
clicks/i2cmux5/lib/include/i2cmux5.h
greghol/mikrosdk_click_v2
76e5dec265dce5fca72c4b93f77afd668dde5dfa
[ "MIT" ]
32
2020-11-28T07:56:42.000Z
2022-03-14T19:42:29.000Z
/**************************************************************************** ** Copyright (C) 2020 MikroElektronika d.o.o. ** Contact: https://www.mikroe.com/contact ** ** 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. ****************************************************************************/ /*! * @file i2cmux5.h * @brief This file contains API for I2C MUX 5 Click Driver. */ #ifndef I2CMUX5_H #define I2CMUX5_H #ifdef __cplusplus extern "C"{ #endif #include "drv_digital_out.h" #include "drv_digital_in.h" #include "drv_i2c_master.h" /*! * @addtogroup i2cmux5 I2C MUX 5 Click Driver * @brief API for configuring and manipulating I2C MUX 5 Click driver. * @{ */ /** * @defgroup i2cmux5_reg I2C MUX 5 Registers List * @brief List of registers of I2C MUX 5 Click driver. */ /** * @addtogroup i2cmux5_reg * @{ */ /** * @brief I2C MUX 5 description register. * @details Specified register for description of I2C MUX 5 Click driver. */ #define I2CMUX5_REGISTER_0 0x00 #define I2CMUX5_REGISTER_1 0x01 #define I2CMUX5_REGISTER_2 0x02 #define I2CMUX5_REGISTER_3 0x03 /*! @} */ // i2cmux5_reg /** * @defgroup i2cmux5_set I2C MUX 5 Registers Settings * @brief Settings for registers of I2C MUX 5 Click driver. */ /** * @addtogroup i2cmux5_set * @{ */ /** * @brief I2C MUX 5 description setting. * @details Specified setting for description of I2C MUX 5 Click driver. */ /** * @brief I2C MUX 5 Register 0 setting. * @details Specified setting for Register 1 of I2C MUX 5 Click driver. */ #define I2CMUX5_SET_REG_0_US_BUS_DISCONNECTED 0x00 #define I2CMUX5_SET_REG_0_US_BUS_CONNECTED 0x80 #define I2CMUX5_SET_REG_0_ALERT1_STATE_LOW 0x00 #define I2CMUX5_SET_REG_0_ALERT1_STATE_HIGH 0x40 #define I2CMUX5_SET_REG_0_ALERT2_STATE_LOW 0x00 #define I2CMUX5_SET_REG_0_ALERT2_STATE_HIGH 0x20 #define I2CMUX5_SET_REG_0_ALERT3_STATE_LOW 0x00 #define I2CMUX5_SET_REG_0_ALERT3_STATE_HIGH 0x10 #define I2CMUX5_SET_REG_0_ALERT4_STATE_LOW 0x00 #define I2CMUX5_SET_REG_0_ALERT5_STATE_HIGH 0x08 #define I2CMUX5_SET_REG_0_ATTEMPT_CONN_FAILED 0x00 #define I2CMUX5_SET_REG_0_ATTEMPT_CONN_OK 0x04 #define I2CMUX5_SET_REG_0_NO_LATCHED_TIMEOUT 0x00 #define I2CMUX5_SET_REG_0_LATCHED_TIMEOUT 0x02 #define I2CMUX5_SET_REG_0_NO_TIMEOUT_OCCURRING 0x00 #define I2CMUX5_SET_REG_0_TIMEOUT_OCCURRING 0x01 /** * @brief I2C MUX 5 Register 1 setting. * @details Specified setting for Register 1 of I2C MUX 5 Click driver. */ #define I2CMUX5_SET_REG_1_URTAC_INACTIVE 0x00 #define I2CMUX5_SET_REG_1_URTAC_ACTIVE 0x80 #define I2CMUX5_SET_REG_1_DRTAC_INACTIVE 0x00 #define I2CMUX5_SET_REG_1_DRTAC_ACTIVE 0x40 #define I2CMUX5_SET_REG_1_GPIO_1_LOW 0x00 #define I2CMUX5_SET_REG_1_GPIO_1_HIGH 0x20 #define I2CMUX5_SET_REG_1_GPIO_2_LOW 0x00 #define I2CMUX5_SET_REG_1_GPIO_2_HIGH 0x10 /** * @brief I2C MUX 5 Register 2 setting. * @details Specified setting for Register 2 of I2C MUX 5 Click driver. */ #define I2CMUX5_SET_REG_2_CFG_GPIO_1_OUTPUT 0x00 #define I2CMUX5_SET_REG_2_CFG_GPIO_1_INPUT 0x80 #define I2CMUX5_SET_REG_2_CFG_GPIO_2_OUTPUT 0x00 #define I2CMUX5_SET_REG_2_CFG_GPIO_2_INPUT 0x40 #define I2CMUX5_SET_REG_2_BUS_LOGIC_STATE_BITS 0x00 #define I2CMUX5_SET_REG_2_CONN_RGL_LOGIC_STATE 0x20 #define I2CMUX5_SET_REG_2_CFG_GPIO_1_OD_PULL_DOWN 0x00 #define I2CMUX5_SET_REG_2_CFG_GPIO_1_PUSH_PULL 0x10 #define I2CMUX5_SET_REG_2_CFG_GPIO_2_OD_PULL_DOWN 0x00 #define I2CMUX5_SET_REG_2_CFG_GPIO_2_PUSH_PULL 0x08 #define I2CMUX5_SET_REG_2_MASS_WRITE_DISABLE 0x00 #define I2CMUX5_SET_REG_2_MASS_WRITE_ENABLE 0x04 #define I2CMUX5_SET_REG_2_TIMEOUT_DISABLED 0x00 #define I2CMUX5_SET_REG_2_TIMEOUT_MODE_30_MS 0x01 #define I2CMUX5_SET_REG_2_TIMEOUT_MODE_15_MS 0x02 #define I2CMUX5_SET_REG_2_TIMEOUT_MODE_7_5_MS 0x03 /** * @brief I2C MUX 5 Register 3 setting. * @details Specified setting for Register 3 of I2C MUX 5 Click driver. */ #define I2CMUX5_SET_REG_3_BUS_1_SWITCH_OPEN 0x00 #define I2CMUX5_SET_REG_3_BUS_1_SWITCH_CLOSED 0x80 #define I2CMUX5_SET_REG_3_BUS_2_SWITCH_OPEN 0x00 #define I2CMUX5_SET_REG_3_BUS_2_SWITCH_CLOSED 0x40 #define I2CMUX5_SET_REG_3_BUS_3_SWITCH_OPEN 0x00 #define I2CMUX5_SET_REG_3_BUS_3_SWITCH_CLOSED 0x20 #define I2CMUX5_SET_REG_3_BUS_4_SWITCH_OPEN 0x00 #define I2CMUX5_SET_REG_3_BUS_4_SWITCH_CLOSED 0x10 /** * @brief I2C MUX 5 Channel Selection Status. * @details Specified setting for channel selection status of I2C MUX 5 Click driver. */ #define I2CMUX5_CH_SEL_ERROR 0xFF /** * @brief I2C MUX 5 device address setting. * @details Specified setting for device slave address selection of * I2C MUX 5 Click driver. */ #define I2CMUX5_SET_DEV_ADDR 0x44 /** * @brief I2C MUX 5 channel slave address setting. * @details Specified setting for channel slave address selection of * I2C MUX 5 Click driver. */ #define I2CMUX5_SET_6DOF_IMU_9_ADDR 0x69 #define I2CMUX5_SET_6DOF_IMU_11_ADDR 0x0E #define I2CMUX5_SET_RTC_10_ADDR 0x68 #define I2CMUX5_SET_ACCEL_10_ADDR 0x18 /*! @} */ // i2cmux5_set /** * @defgroup i2cmux5_map I2C MUX 5 MikroBUS Map * @brief MikroBUS pin mapping of I2C MUX 5 Click driver. */ /** * @addtogroup sel_ch * @{ */ /** * @brief I2C MUX 5 channel selection setting. * @details Specified setting for channel selection of * I2C MUX 5 Click driver. */ #define I2CMUX5_CH_1 0x01 #define I2CMUX5_CH_2 0x02 #define I2CMUX5_CH_3 0x03 #define I2CMUX5_CH_4 0x04 /*! @} */ // sel_ch /** * @addtogroup pin_state * @{ */ /** * @brief I2C MUX 5 channel selection setting. * @details Specified setting for channel selection of * I2C MUX 5 Click driver. */ #define I2CMUX5_PIN_STATE_LOW 0 #define I2CMUX5_PIN_STATE_HIGH 1 /*! @} */ // pin_state /** * @addtogroup i2cmux5_map * @{ */ /** * @brief MikroBUS pin mapping. * @details Mapping pins of I2C MUX 5 Click to the selected MikroBUS. */ #define I2CMUX5_MAP_MIKROBUS( cfg, mikrobus ) \ cfg.scl = MIKROBUS( mikrobus, MIKROBUS_SCL ); \ cfg.sda = MIKROBUS( mikrobus, MIKROBUS_SDA ); \ cfg.en = MIKROBUS( mikrobus, MIKROBUS_CS ); \ cfg.ready = MIKROBUS( mikrobus, MIKROBUS_AN ); \ cfg.alert = MIKROBUS( mikrobus, MIKROBUS_INT ) /*! @} */ // i2cmux5_map /*! @} */ // i2cmux5 /** * @brief I2C MUX 5 Click context object. * @details Context object definition of I2C MUX 5 Click driver. */ typedef struct { // Output pins digital_out_t en; /**< Description. */ // Input pins digital_in_t ready; /**< Description. */ digital_in_t alert; /**< Description. */ // Modules i2c_master_t i2c; /**< I2C driver object. */ // I2C slave address uint8_t slave_address; /**< Device slave address (used for I2C driver). */ } i2cmux5_t; /** * @brief I2C MUX 5 Click configuration object. * @details Configuration object definition of I2C MUX 5 Click driver. */ typedef struct { pin_name_t scl; /**< Clock pin descriptor for I2C driver. */ pin_name_t sda; /**< Bidirectional data pin descriptor for I2C driver. */ pin_name_t en; /**< Description. */ pin_name_t ready; /**< Description. */ pin_name_t alert; /**< Description. */ uint32_t i2c_speed; /**< I2C serial speed. */ uint8_t i2c_address; /**< I2C slave address. */ } i2cmux5_cfg_t; /*! * @addtogroup i2cmux5 I2C MUX 5 Click Driver * @brief API for configuring and manipulating I2C MUX 5 Click driver. * @{ */ /** * @brief I2C MUX 5 configuration object setup function. * @details This function initializes click configuration structure to initial * values. * @param[out] cfg : Click configuration structure. * See #i2cmux5_cfg_t object definition for detailed explanation. * @return Nothing. * @note The all used pins will be set to unconnected state. * * @endcode */ void i2cmux5_cfg_setup ( i2cmux5_cfg_t *cfg ); /** * @brief I2C MUX 5 initialization function. * @details This function initializes all necessary pins and peripherals used * for this click board. * @param[out] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * @param[in] cfg : Click configuration structure. * See #i2cmux5_cfg_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. * * @endcode */ err_t i2cmux5_init ( i2cmux5_t *ctx, i2cmux5_cfg_t *cfg ); /** * @brief I2C MUX 5 default configuration function. * @details This function executes a default configuration of I2C MUX 5 * click board. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note This function can consist any necessary configuration or setting to put * device into operating mode. * * @endcode */ void i2cmux5_default_cfg ( i2cmux5_t *ctx ); /** * @brief I2C MUX 5 HW reset function. * @details This function executes a hardware reset of I2C MUX 5 * click board. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * * @endcode */ void i2cmux5_hw_reset ( i2cmux5_t *ctx ); /** * @brief I2C MUX 5 enable the device function. * @details This function executes power-up of the device and * enables I2C communication of I2C MUX 5 * click board. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * * @endcode */ void i2cmux5_dev_enable ( i2cmux5_t *ctx ); /** * @brief I2C MUX 5 check rdy function. * @details This function check connection ready digital output of I2C MUX 5 * click board. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * @return @li @c 0 - None of the downstream channels is connected, * @li @c 1 - One or more downstream channels is connected. * * @endcode */ uint8_t i2cmux5_check_rdy ( i2cmux5_t *ctx ); /** * @brief I2C MUX 5 check alert function. * @details This function check fault alert output of I2C MUX 5 * click board. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * @return @li @c 0 - A fault occurs to alert the host controller, * @li @c 1 - Passes this information to the master on the upstream bus. * * @endcode */ uint8_t i2cmux5_check_alert ( i2cmux5_t *ctx ); /** * @brief I2C MUX 5 I2C writing function. * @details This function writes a desired number of data bytes starting from * the selected register by using I2C serial interface. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * @param[in] reg : Start register address. * @param[in] tx_buf : Data to be written. * @param[in] tx_len : Number of bytes to be written. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. * * @endcode */ err_t i2cmux5_generic_write ( i2cmux5_t *ctx, uint8_t reg, uint8_t *tx_buf, uint8_t tx_len ); /** * @brief I2C MUX 5 I2C reading function. * @details This function reads a desired number of data bytes starting from * the selected register by using I2C serial interface. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * @param[in] reg : Start register address. * @param[out] rx_buf : Output read data. * @param[in] rx_len : Number of bytes to be read. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. * * @endcode */ err_t i2cmux5_generic_read ( i2cmux5_t *ctx, uint8_t reg, uint8_t *rx_buf, uint8_t rx_len ); /** * @brief I2C MUX 5 check channel alert function. * @details This function reads a desired channel alert status of I2C MUX 5 * click board. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * @param[in] ch_numb : The number of the desired channel ( from 1 to 4 ). * @param[in] rx_len : Number of bytes to be read. * @return Alert status on the selected channel: * @li @c 0 - Inactive, * @li @c 1 - Active, * @li @c 255 - Error, wrong channel selection. * * @note None. * * @endcode */ uint8_t i2cmux5_check_ch_alert ( i2cmux5_t *ctx, uint8_t n_channel ); /** * @brief I2C MUX 5 I2C channel writing function. * @details This function writes via desired channel * a desired number of data bytes starting from * the selected register by using I2C serial interface. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * @param[in] sel_ch : Number of the desired channel ( from 1 to 4 ). * @param[in] ch_slave_addr : Slave address of the device connected to the desired channel. * @param[in] reg : Start register address. * @param[in] tx_buf : Data to be written. * * @note None. * * @endcode */ void i2cmux5_channel_write_byte ( i2cmux5_t *ctx, uint8_t sel_ch, uint8_t ch_slave_addr, uint8_t reg, uint8_t tx_data ); /** * @brief I2C MUX 5 I2C channel reading function. * @details This function reads a desired number of data bytes starting from * the selected register by using I2C serial interface. * @param[in] ctx : Click context object. * See #i2cmux5_t object definition for detailed explanation. * @param[in] sel_ch : Number of the desired channel ( from 1 to 4 ). * @param[in] ch_slave_addr : Slave address of the device connected to the desired channel. * @param[in] reg : Start register address. * @return Output read data. * * See #err_t definition for detailed explanation. * @note None. * * @endcode */ uint8_t i2cmux5_channel_read_byte ( i2cmux5_t *ctx, uint8_t sel_ch, uint8_t ch_slave_addr, uint8_t reg ); #ifdef __cplusplus } #endif #endif // I2CMUX5_H /*! @} */ // i2cmux5 // ------------------------------------------------------------------------ END
33.137787
120
0.683992
[ "object" ]
08a60d19e13124061ba83269082f8058a3958cff
3,159
c
C
src/mesa/main/glthread_list.c
SoftReaper/Mesa-Renoir-deb
8d1de1f66058d62b41fe55d36522efea2bdf996d
[ "MIT" ]
null
null
null
src/mesa/main/glthread_list.c
SoftReaper/Mesa-Renoir-deb
8d1de1f66058d62b41fe55d36522efea2bdf996d
[ "MIT" ]
null
null
null
src/mesa/main/glthread_list.c
SoftReaper/Mesa-Renoir-deb
8d1de1f66058d62b41fe55d36522efea2bdf996d
[ "MIT" ]
null
null
null
/* * Copyright © 2020 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "c99_alloca.h" #include "main/glthread_marshal.h" #include "main/dispatch.h" uint32_t _mesa_unmarshal_CallList(struct gl_context *ctx, const struct marshal_cmd_CallList *cmd, const uint64_t *last) { const GLuint list = cmd->list; uint64_t *ptr = (uint64_t *) cmd; ptr += cmd->cmd_base.cmd_size; if (ptr < last) { const struct marshal_cmd_base *next = (const struct marshal_cmd_base *)ptr; /* If the 'next' is also a DISPATCH_CMD_CallList, we transform 'cmd' and 'next' in a CALL_CallLists. * If the following commands are also CallList they're including in the CallLists we're building. */ if (next->cmd_id == DISPATCH_CMD_CallList) { const int max_list_count = 2048; struct marshal_cmd_CallList *next_callist = (struct marshal_cmd_CallList *) next; uint32_t *lists = alloca(max_list_count * sizeof(uint32_t)); lists[0] = cmd->list; lists[1] = next_callist->list; int count = 2; ptr += next->cmd_size; while (ptr < last && count < max_list_count) { next = (const struct marshal_cmd_base *)ptr; if (next->cmd_id == DISPATCH_CMD_CallList) { next_callist = (struct marshal_cmd_CallList *) next; lists[count++] = next_callist->list; ptr += next->cmd_size; } else { break; } } CALL_CallLists(ctx->CurrentServerDispatch, (count, GL_UNSIGNED_INT, lists)); return (uint32_t) (ptr - (uint64_t*)cmd); } } CALL_CallList(ctx->CurrentServerDispatch, (list)); return cmd->cmd_base.cmd_size; } void GLAPIENTRY _mesa_marshal_CallList(GLuint list) { GET_CURRENT_CONTEXT(ctx); int cmd_size = sizeof(struct marshal_cmd_CallList); struct marshal_cmd_CallList *cmd; cmd = _mesa_glthread_allocate_command(ctx, DISPATCH_CMD_CallList, cmd_size); cmd->list = list; _mesa_glthread_CallList(ctx, list); }
36.732558
110
0.687243
[ "transform" ]
08a7e57963dbd8f50caada6401665ada854de797
2,037
h
C
Project/Foundation.framework/Headers/NSNotification.h
chat21/chat21-ios-demo
9ffdb57853d0bf15c1a50bd5cdb8cd66d821538d
[ "MIT" ]
5
2017-12-20T17:03:34.000Z
2021-06-11T01:39:19.000Z
Project/Foundation.framework/Headers/NSNotification.h
chat21/chat21-ios-demo
9ffdb57853d0bf15c1a50bd5cdb8cd66d821538d
[ "MIT" ]
10
2018-06-27T12:41:37.000Z
2021-02-03T17:26:36.000Z
Project/Foundation.framework/Headers/NSNotification.h
chat21/chat21-ios-demo
9ffdb57853d0bf15c1a50bd5cdb8cd66d821538d
[ "MIT" ]
10
2018-11-01T08:08:34.000Z
2021-12-24T06:28:13.000Z
/* NSNotification.h Copyright (c) 1994-2014, Apple Inc. All rights reserved. */ #import <Foundation/NSObject.h> @class NSString, NSDictionary, NSOperationQueue; /**************** Notifications ****************/ @interface NSNotification : NSObject <NSCopying, NSCoding> @property (readonly, copy) NSString *name; @property (readonly, retain) id object; @property (readonly, copy) NSDictionary *userInfo; - (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo NS_AVAILABLE(10_6, 4_0) NS_DESIGNATED_INITIALIZER; - (instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER; @end @interface NSNotification (NSNotificationCreation) + (instancetype)notificationWithName:(NSString *)aName object:(id)anObject; + (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo; - (instancetype)init /*NS_UNAVAILABLE*/; /* do not invoke; not a valid initializer for this class */ @end /**************** Notification Center ****************/ @interface NSNotificationCenter : NSObject { @package void * __strong _impl; void * __strong _callback; void *_pad[11]; } + (NSNotificationCenter *)defaultCenter; - (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject; - (void)postNotification:(NSNotification *)notification; - (void)postNotificationName:(NSString *)aName object:(id)anObject; - (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo; - (void)removeObserver:(id)observer; - (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject; - (id <NSObject>)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block NS_AVAILABLE(10_6, 4_0); // The return value is retained by the system, and should be held onto by the caller in // order to remove the observer with removeObserver: later, to stop observation. @end
35.736842
173
0.739813
[ "object" ]
08a97b06238a7dbc965f847a11da7cef8309e0e6
28,496
h
C
aws-cpp-sdk-license-manager/include/aws/license-manager/model/ProductInformation.h
fboranek/aws-sdk-cpp
2aa01e7d5c5431d9702caf9bf21f4e07b6ef15ae
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-license-manager/include/aws/license-manager/model/ProductInformation.h
fboranek/aws-sdk-cpp
2aa01e7d5c5431d9702caf9bf21f4e07b6ef15ae
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-license-manager/include/aws/license-manager/model/ProductInformation.h
fboranek/aws-sdk-cpp
2aa01e7d5c5431d9702caf9bf21f4e07b6ef15ae
[ "Apache-2.0" ]
null
null
null
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/license-manager/LicenseManager_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/license-manager/model/ProductInformationFilter.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace LicenseManager { namespace Model { /** * <p>Describes product information for a license configuration.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ProductInformation">AWS * API Reference</a></p> */ class AWS_LICENSEMANAGER_API ProductInformation { public: ProductInformation(); ProductInformation(Aws::Utils::Json::JsonView jsonValue); ProductInformation& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Resource type. The possible values are <code>SSM_MANAGED</code> | * <code>RDS</code>.</p> */ inline const Aws::String& GetResourceType() const{ return m_resourceType; } /** * <p>Resource type. The possible values are <code>SSM_MANAGED</code> | * <code>RDS</code>.</p> */ inline bool ResourceTypeHasBeenSet() const { return m_resourceTypeHasBeenSet; } /** * <p>Resource type. The possible values are <code>SSM_MANAGED</code> | * <code>RDS</code>.</p> */ inline void SetResourceType(const Aws::String& value) { m_resourceTypeHasBeenSet = true; m_resourceType = value; } /** * <p>Resource type. The possible values are <code>SSM_MANAGED</code> | * <code>RDS</code>.</p> */ inline void SetResourceType(Aws::String&& value) { m_resourceTypeHasBeenSet = true; m_resourceType = std::move(value); } /** * <p>Resource type. The possible values are <code>SSM_MANAGED</code> | * <code>RDS</code>.</p> */ inline void SetResourceType(const char* value) { m_resourceTypeHasBeenSet = true; m_resourceType.assign(value); } /** * <p>Resource type. The possible values are <code>SSM_MANAGED</code> | * <code>RDS</code>.</p> */ inline ProductInformation& WithResourceType(const Aws::String& value) { SetResourceType(value); return *this;} /** * <p>Resource type. The possible values are <code>SSM_MANAGED</code> | * <code>RDS</code>.</p> */ inline ProductInformation& WithResourceType(Aws::String&& value) { SetResourceType(std::move(value)); return *this;} /** * <p>Resource type. The possible values are <code>SSM_MANAGED</code> | * <code>RDS</code>.</p> */ inline ProductInformation& WithResourceType(const char* value) { SetResourceType(value); return *this;} /** * <p>A Product information filter consists of a * <code>ProductInformationFilterComparator</code> which is a logical operator, a * <code>ProductInformationFilterName</code> which specifies the type of filter * being declared, and a <code>ProductInformationFilterValue</code> that specifies * the value to filter on. </p> <p>Accepted values for * <code>ProductInformationFilterName</code> are listed here along with * descriptions and valid options for * <code>ProductInformationFilterComparator</code>. </p> <p>The following filters * and are supported when the resource type is <code>SSM_MANAGED</code>:</p> <ul> * <li> <p> <code>Application Name</code> - The name of the application. Logical * operator is <code>EQUALS</code>.</p> </li> <li> <p> <code>Application * Publisher</code> - The publisher of the application. Logical operator is * <code>EQUALS</code>.</p> </li> <li> <p> <code>Application Version</code> - The * version of the application. Logical operator is <code>EQUALS</code>.</p> </li> * <li> <p> <code>Platform Name</code> - The name of the platform. Logical operator * is <code>EQUALS</code>.</p> </li> <li> <p> <code>Platform Type</code> - The * platform type. Logical operator is <code>EQUALS</code>.</p> </li> <li> <p> * <code>Tag:key</code> - The key of a tag attached to an AWS resource you wish to * exclude from automated discovery. Logical operator is <code>NOT_EQUALS</code>. * The key for your tag must be appended to <code>Tag:</code> following the * example: <code>Tag:name-of-your-key</code>. * <code>ProductInformationFilterValue</code> is optional if you are not using * values for the key. </p> </li> <li> <p> <code>AccountId</code> - The 12-digit ID * of an AWS account you wish to exclude from automated discovery. Logical operator * is <code>NOT_EQUALS</code>.</p> </li> <li> <p> <code>License Included</code> - * The type of license included. Logical operators are <code>EQUALS</code> and * <code>NOT_EQUALS</code>. Possible values are: <code>sql-server-enterprise</code> * | <code>sql-server-standard</code> | <code>sql-server-web</code> | * <code>windows-server-datacenter</code>.</p> </li> </ul> <p>The following filters * and logical operators are supported when the resource type is * <code>RDS</code>:</p> <ul> <li> <p> <code>Engine Edition</code> - The edition of * the database engine. Logical operator is <code>EQUALS</code>. Possible values * are: <code>oracle-ee</code> | <code>oracle-se</code> | <code>oracle-se1</code> | * <code>oracle-se2</code>.</p> </li> <li> <p> <code>License Pack</code> - The * license pack. Logical operator is <code>EQUALS</code>. Possible values are: * <code>data guard</code> | <code>diagnostic pack sqlt</code> | <code>tuning pack * sqlt</code> | <code>ols</code> | <code>olap</code>.</p> </li> </ul> */ inline const Aws::Vector<ProductInformationFilter>& GetProductInformationFilterList() const{ return m_productInformationFilterList; } /** * <p>A Product information filter consists of a * <code>ProductInformationFilterComparator</code> which is a logical operator, a * <code>ProductInformationFilterName</code> which specifies the type of filter * being declared, and a <code>ProductInformationFilterValue</code> that specifies * the value to filter on. </p> <p>Accepted values for * <code>ProductInformationFilterName</code> are listed here along with * descriptions and valid options for * <code>ProductInformationFilterComparator</code>. </p> <p>The following filters * and are supported when the resource type is <code>SSM_MANAGED</code>:</p> <ul> * <li> <p> <code>Application Name</code> - The name of the application. Logical * operator is <code>EQUALS</code>.</p> </li> <li> <p> <code>Application * Publisher</code> - The publisher of the application. Logical operator is * <code>EQUALS</code>.</p> </li> <li> <p> <code>Application Version</code> - The * version of the application. Logical operator is <code>EQUALS</code>.</p> </li> * <li> <p> <code>Platform Name</code> - The name of the platform. Logical operator * is <code>EQUALS</code>.</p> </li> <li> <p> <code>Platform Type</code> - The * platform type. Logical operator is <code>EQUALS</code>.</p> </li> <li> <p> * <code>Tag:key</code> - The key of a tag attached to an AWS resource you wish to * exclude from automated discovery. Logical operator is <code>NOT_EQUALS</code>. * The key for your tag must be appended to <code>Tag:</code> following the * example: <code>Tag:name-of-your-key</code>. * <code>ProductInformationFilterValue</code> is optional if you are not using * values for the key. </p> </li> <li> <p> <code>AccountId</code> - The 12-digit ID * of an AWS account you wish to exclude from automated discovery. Logical operator * is <code>NOT_EQUALS</code>.</p> </li> <li> <p> <code>License Included</code> - * The type of license included. Logical operators are <code>EQUALS</code> and * <code>NOT_EQUALS</code>. Possible values are: <code>sql-server-enterprise</code> * | <code>sql-server-standard</code> | <code>sql-server-web</code> | * <code>windows-server-datacenter</code>.</p> </li> </ul> <p>The following filters * and logical operators are supported when the resource type is * <code>RDS</code>:</p> <ul> <li> <p> <code>Engine Edition</code> - The edition of * the database engine. Logical operator is <code>EQUALS</code>. Possible values * are: <code>oracle-ee</code> | <code>oracle-se</code> | <code>oracle-se1</code> | * <code>oracle-se2</code>.</p> </li> <li> <p> <code>License Pack</code> - The * license pack. Logical operator is <code>EQUALS</code>. Possible values are: * <code>data guard</code> | <code>diagnostic pack sqlt</code> | <code>tuning pack * sqlt</code> | <code>ols</code> | <code>olap</code>.</p> </li> </ul> */ inline bool ProductInformationFilterListHasBeenSet() const { return m_productInformationFilterListHasBeenSet; } /** * <p>A Product information filter consists of a * <code>ProductInformationFilterComparator</code> which is a logical operator, a * <code>ProductInformationFilterName</code> which specifies the type of filter * being declared, and a <code>ProductInformationFilterValue</code> that specifies * the value to filter on. </p> <p>Accepted values for * <code>ProductInformationFilterName</code> are listed here along with * descriptions and valid options for * <code>ProductInformationFilterComparator</code>. </p> <p>The following filters * and are supported when the resource type is <code>SSM_MANAGED</code>:</p> <ul> * <li> <p> <code>Application Name</code> - The name of the application. Logical * operator is <code>EQUALS</code>.</p> </li> <li> <p> <code>Application * Publisher</code> - The publisher of the application. Logical operator is * <code>EQUALS</code>.</p> </li> <li> <p> <code>Application Version</code> - The * version of the application. Logical operator is <code>EQUALS</code>.</p> </li> * <li> <p> <code>Platform Name</code> - The name of the platform. Logical operator * is <code>EQUALS</code>.</p> </li> <li> <p> <code>Platform Type</code> - The * platform type. Logical operator is <code>EQUALS</code>.</p> </li> <li> <p> * <code>Tag:key</code> - The key of a tag attached to an AWS resource you wish to * exclude from automated discovery. Logical operator is <code>NOT_EQUALS</code>. * The key for your tag must be appended to <code>Tag:</code> following the * example: <code>Tag:name-of-your-key</code>. * <code>ProductInformationFilterValue</code> is optional if you are not using * values for the key. </p> </li> <li> <p> <code>AccountId</code> - The 12-digit ID * of an AWS account you wish to exclude from automated discovery. Logical operator * is <code>NOT_EQUALS</code>.</p> </li> <li> <p> <code>License Included</code> - * The type of license included. Logical operators are <code>EQUALS</code> and * <code>NOT_EQUALS</code>. Possible values are: <code>sql-server-enterprise</code> * | <code>sql-server-standard</code> | <code>sql-server-web</code> | * <code>windows-server-datacenter</code>.</p> </li> </ul> <p>The following filters * and logical operators are supported when the resource type is * <code>RDS</code>:</p> <ul> <li> <p> <code>Engine Edition</code> - The edition of * the database engine. Logical operator is <code>EQUALS</code>. Possible values * are: <code>oracle-ee</code> | <code>oracle-se</code> | <code>oracle-se1</code> | * <code>oracle-se2</code>.</p> </li> <li> <p> <code>License Pack</code> - The * license pack. Logical operator is <code>EQUALS</code>. Possible values are: * <code>data guard</code> | <code>diagnostic pack sqlt</code> | <code>tuning pack * sqlt</code> | <code>ols</code> | <code>olap</code>.</p> </li> </ul> */ inline void SetProductInformationFilterList(const Aws::Vector<ProductInformationFilter>& value) { m_productInformationFilterListHasBeenSet = true; m_productInformationFilterList = value; } /** * <p>A Product information filter consists of a * <code>ProductInformationFilterComparator</code> which is a logical operator, a * <code>ProductInformationFilterName</code> which specifies the type of filter * being declared, and a <code>ProductInformationFilterValue</code> that specifies * the value to filter on. </p> <p>Accepted values for * <code>ProductInformationFilterName</code> are listed here along with * descriptions and valid options for * <code>ProductInformationFilterComparator</code>. </p> <p>The following filters * and are supported when the resource type is <code>SSM_MANAGED</code>:</p> <ul> * <li> <p> <code>Application Name</code> - The name of the application. Logical * operator is <code>EQUALS</code>.</p> </li> <li> <p> <code>Application * Publisher</code> - The publisher of the application. Logical operator is * <code>EQUALS</code>.</p> </li> <li> <p> <code>Application Version</code> - The * version of the application. Logical operator is <code>EQUALS</code>.</p> </li> * <li> <p> <code>Platform Name</code> - The name of the platform. Logical operator * is <code>EQUALS</code>.</p> </li> <li> <p> <code>Platform Type</code> - The * platform type. Logical operator is <code>EQUALS</code>.</p> </li> <li> <p> * <code>Tag:key</code> - The key of a tag attached to an AWS resource you wish to * exclude from automated discovery. Logical operator is <code>NOT_EQUALS</code>. * The key for your tag must be appended to <code>Tag:</code> following the * example: <code>Tag:name-of-your-key</code>. * <code>ProductInformationFilterValue</code> is optional if you are not using * values for the key. </p> </li> <li> <p> <code>AccountId</code> - The 12-digit ID * of an AWS account you wish to exclude from automated discovery. Logical operator * is <code>NOT_EQUALS</code>.</p> </li> <li> <p> <code>License Included</code> - * The type of license included. Logical operators are <code>EQUALS</code> and * <code>NOT_EQUALS</code>. Possible values are: <code>sql-server-enterprise</code> * | <code>sql-server-standard</code> | <code>sql-server-web</code> | * <code>windows-server-datacenter</code>.</p> </li> </ul> <p>The following filters * and logical operators are supported when the resource type is * <code>RDS</code>:</p> <ul> <li> <p> <code>Engine Edition</code> - The edition of * the database engine. Logical operator is <code>EQUALS</code>. Possible values * are: <code>oracle-ee</code> | <code>oracle-se</code> | <code>oracle-se1</code> | * <code>oracle-se2</code>.</p> </li> <li> <p> <code>License Pack</code> - The * license pack. Logical operator is <code>EQUALS</code>. Possible values are: * <code>data guard</code> | <code>diagnostic pack sqlt</code> | <code>tuning pack * sqlt</code> | <code>ols</code> | <code>olap</code>.</p> </li> </ul> */ inline void SetProductInformationFilterList(Aws::Vector<ProductInformationFilter>&& value) { m_productInformationFilterListHasBeenSet = true; m_productInformationFilterList = std::move(value); } /** * <p>A Product information filter consists of a * <code>ProductInformationFilterComparator</code> which is a logical operator, a * <code>ProductInformationFilterName</code> which specifies the type of filter * being declared, and a <code>ProductInformationFilterValue</code> that specifies * the value to filter on. </p> <p>Accepted values for * <code>ProductInformationFilterName</code> are listed here along with * descriptions and valid options for * <code>ProductInformationFilterComparator</code>. </p> <p>The following filters * and are supported when the resource type is <code>SSM_MANAGED</code>:</p> <ul> * <li> <p> <code>Application Name</code> - The name of the application. Logical * operator is <code>EQUALS</code>.</p> </li> <li> <p> <code>Application * Publisher</code> - The publisher of the application. Logical operator is * <code>EQUALS</code>.</p> </li> <li> <p> <code>Application Version</code> - The * version of the application. Logical operator is <code>EQUALS</code>.</p> </li> * <li> <p> <code>Platform Name</code> - The name of the platform. Logical operator * is <code>EQUALS</code>.</p> </li> <li> <p> <code>Platform Type</code> - The * platform type. Logical operator is <code>EQUALS</code>.</p> </li> <li> <p> * <code>Tag:key</code> - The key of a tag attached to an AWS resource you wish to * exclude from automated discovery. Logical operator is <code>NOT_EQUALS</code>. * The key for your tag must be appended to <code>Tag:</code> following the * example: <code>Tag:name-of-your-key</code>. * <code>ProductInformationFilterValue</code> is optional if you are not using * values for the key. </p> </li> <li> <p> <code>AccountId</code> - The 12-digit ID * of an AWS account you wish to exclude from automated discovery. Logical operator * is <code>NOT_EQUALS</code>.</p> </li> <li> <p> <code>License Included</code> - * The type of license included. Logical operators are <code>EQUALS</code> and * <code>NOT_EQUALS</code>. Possible values are: <code>sql-server-enterprise</code> * | <code>sql-server-standard</code> | <code>sql-server-web</code> | * <code>windows-server-datacenter</code>.</p> </li> </ul> <p>The following filters * and logical operators are supported when the resource type is * <code>RDS</code>:</p> <ul> <li> <p> <code>Engine Edition</code> - The edition of * the database engine. Logical operator is <code>EQUALS</code>. Possible values * are: <code>oracle-ee</code> | <code>oracle-se</code> | <code>oracle-se1</code> | * <code>oracle-se2</code>.</p> </li> <li> <p> <code>License Pack</code> - The * license pack. Logical operator is <code>EQUALS</code>. Possible values are: * <code>data guard</code> | <code>diagnostic pack sqlt</code> | <code>tuning pack * sqlt</code> | <code>ols</code> | <code>olap</code>.</p> </li> </ul> */ inline ProductInformation& WithProductInformationFilterList(const Aws::Vector<ProductInformationFilter>& value) { SetProductInformationFilterList(value); return *this;} /** * <p>A Product information filter consists of a * <code>ProductInformationFilterComparator</code> which is a logical operator, a * <code>ProductInformationFilterName</code> which specifies the type of filter * being declared, and a <code>ProductInformationFilterValue</code> that specifies * the value to filter on. </p> <p>Accepted values for * <code>ProductInformationFilterName</code> are listed here along with * descriptions and valid options for * <code>ProductInformationFilterComparator</code>. </p> <p>The following filters * and are supported when the resource type is <code>SSM_MANAGED</code>:</p> <ul> * <li> <p> <code>Application Name</code> - The name of the application. Logical * operator is <code>EQUALS</code>.</p> </li> <li> <p> <code>Application * Publisher</code> - The publisher of the application. Logical operator is * <code>EQUALS</code>.</p> </li> <li> <p> <code>Application Version</code> - The * version of the application. Logical operator is <code>EQUALS</code>.</p> </li> * <li> <p> <code>Platform Name</code> - The name of the platform. Logical operator * is <code>EQUALS</code>.</p> </li> <li> <p> <code>Platform Type</code> - The * platform type. Logical operator is <code>EQUALS</code>.</p> </li> <li> <p> * <code>Tag:key</code> - The key of a tag attached to an AWS resource you wish to * exclude from automated discovery. Logical operator is <code>NOT_EQUALS</code>. * The key for your tag must be appended to <code>Tag:</code> following the * example: <code>Tag:name-of-your-key</code>. * <code>ProductInformationFilterValue</code> is optional if you are not using * values for the key. </p> </li> <li> <p> <code>AccountId</code> - The 12-digit ID * of an AWS account you wish to exclude from automated discovery. Logical operator * is <code>NOT_EQUALS</code>.</p> </li> <li> <p> <code>License Included</code> - * The type of license included. Logical operators are <code>EQUALS</code> and * <code>NOT_EQUALS</code>. Possible values are: <code>sql-server-enterprise</code> * | <code>sql-server-standard</code> | <code>sql-server-web</code> | * <code>windows-server-datacenter</code>.</p> </li> </ul> <p>The following filters * and logical operators are supported when the resource type is * <code>RDS</code>:</p> <ul> <li> <p> <code>Engine Edition</code> - The edition of * the database engine. Logical operator is <code>EQUALS</code>. Possible values * are: <code>oracle-ee</code> | <code>oracle-se</code> | <code>oracle-se1</code> | * <code>oracle-se2</code>.</p> </li> <li> <p> <code>License Pack</code> - The * license pack. Logical operator is <code>EQUALS</code>. Possible values are: * <code>data guard</code> | <code>diagnostic pack sqlt</code> | <code>tuning pack * sqlt</code> | <code>ols</code> | <code>olap</code>.</p> </li> </ul> */ inline ProductInformation& WithProductInformationFilterList(Aws::Vector<ProductInformationFilter>&& value) { SetProductInformationFilterList(std::move(value)); return *this;} /** * <p>A Product information filter consists of a * <code>ProductInformationFilterComparator</code> which is a logical operator, a * <code>ProductInformationFilterName</code> which specifies the type of filter * being declared, and a <code>ProductInformationFilterValue</code> that specifies * the value to filter on. </p> <p>Accepted values for * <code>ProductInformationFilterName</code> are listed here along with * descriptions and valid options for * <code>ProductInformationFilterComparator</code>. </p> <p>The following filters * and are supported when the resource type is <code>SSM_MANAGED</code>:</p> <ul> * <li> <p> <code>Application Name</code> - The name of the application. Logical * operator is <code>EQUALS</code>.</p> </li> <li> <p> <code>Application * Publisher</code> - The publisher of the application. Logical operator is * <code>EQUALS</code>.</p> </li> <li> <p> <code>Application Version</code> - The * version of the application. Logical operator is <code>EQUALS</code>.</p> </li> * <li> <p> <code>Platform Name</code> - The name of the platform. Logical operator * is <code>EQUALS</code>.</p> </li> <li> <p> <code>Platform Type</code> - The * platform type. Logical operator is <code>EQUALS</code>.</p> </li> <li> <p> * <code>Tag:key</code> - The key of a tag attached to an AWS resource you wish to * exclude from automated discovery. Logical operator is <code>NOT_EQUALS</code>. * The key for your tag must be appended to <code>Tag:</code> following the * example: <code>Tag:name-of-your-key</code>. * <code>ProductInformationFilterValue</code> is optional if you are not using * values for the key. </p> </li> <li> <p> <code>AccountId</code> - The 12-digit ID * of an AWS account you wish to exclude from automated discovery. Logical operator * is <code>NOT_EQUALS</code>.</p> </li> <li> <p> <code>License Included</code> - * The type of license included. Logical operators are <code>EQUALS</code> and * <code>NOT_EQUALS</code>. Possible values are: <code>sql-server-enterprise</code> * | <code>sql-server-standard</code> | <code>sql-server-web</code> | * <code>windows-server-datacenter</code>.</p> </li> </ul> <p>The following filters * and logical operators are supported when the resource type is * <code>RDS</code>:</p> <ul> <li> <p> <code>Engine Edition</code> - The edition of * the database engine. Logical operator is <code>EQUALS</code>. Possible values * are: <code>oracle-ee</code> | <code>oracle-se</code> | <code>oracle-se1</code> | * <code>oracle-se2</code>.</p> </li> <li> <p> <code>License Pack</code> - The * license pack. Logical operator is <code>EQUALS</code>. Possible values are: * <code>data guard</code> | <code>diagnostic pack sqlt</code> | <code>tuning pack * sqlt</code> | <code>ols</code> | <code>olap</code>.</p> </li> </ul> */ inline ProductInformation& AddProductInformationFilterList(const ProductInformationFilter& value) { m_productInformationFilterListHasBeenSet = true; m_productInformationFilterList.push_back(value); return *this; } /** * <p>A Product information filter consists of a * <code>ProductInformationFilterComparator</code> which is a logical operator, a * <code>ProductInformationFilterName</code> which specifies the type of filter * being declared, and a <code>ProductInformationFilterValue</code> that specifies * the value to filter on. </p> <p>Accepted values for * <code>ProductInformationFilterName</code> are listed here along with * descriptions and valid options for * <code>ProductInformationFilterComparator</code>. </p> <p>The following filters * and are supported when the resource type is <code>SSM_MANAGED</code>:</p> <ul> * <li> <p> <code>Application Name</code> - The name of the application. Logical * operator is <code>EQUALS</code>.</p> </li> <li> <p> <code>Application * Publisher</code> - The publisher of the application. Logical operator is * <code>EQUALS</code>.</p> </li> <li> <p> <code>Application Version</code> - The * version of the application. Logical operator is <code>EQUALS</code>.</p> </li> * <li> <p> <code>Platform Name</code> - The name of the platform. Logical operator * is <code>EQUALS</code>.</p> </li> <li> <p> <code>Platform Type</code> - The * platform type. Logical operator is <code>EQUALS</code>.</p> </li> <li> <p> * <code>Tag:key</code> - The key of a tag attached to an AWS resource you wish to * exclude from automated discovery. Logical operator is <code>NOT_EQUALS</code>. * The key for your tag must be appended to <code>Tag:</code> following the * example: <code>Tag:name-of-your-key</code>. * <code>ProductInformationFilterValue</code> is optional if you are not using * values for the key. </p> </li> <li> <p> <code>AccountId</code> - The 12-digit ID * of an AWS account you wish to exclude from automated discovery. Logical operator * is <code>NOT_EQUALS</code>.</p> </li> <li> <p> <code>License Included</code> - * The type of license included. Logical operators are <code>EQUALS</code> and * <code>NOT_EQUALS</code>. Possible values are: <code>sql-server-enterprise</code> * | <code>sql-server-standard</code> | <code>sql-server-web</code> | * <code>windows-server-datacenter</code>.</p> </li> </ul> <p>The following filters * and logical operators are supported when the resource type is * <code>RDS</code>:</p> <ul> <li> <p> <code>Engine Edition</code> - The edition of * the database engine. Logical operator is <code>EQUALS</code>. Possible values * are: <code>oracle-ee</code> | <code>oracle-se</code> | <code>oracle-se1</code> | * <code>oracle-se2</code>.</p> </li> <li> <p> <code>License Pack</code> - The * license pack. Logical operator is <code>EQUALS</code>. Possible values are: * <code>data guard</code> | <code>diagnostic pack sqlt</code> | <code>tuning pack * sqlt</code> | <code>ols</code> | <code>olap</code>.</p> </li> </ul> */ inline ProductInformation& AddProductInformationFilterList(ProductInformationFilter&& value) { m_productInformationFilterListHasBeenSet = true; m_productInformationFilterList.push_back(std::move(value)); return *this; } private: Aws::String m_resourceType; bool m_resourceTypeHasBeenSet; Aws::Vector<ProductInformationFilter> m_productInformationFilterList; bool m_productInformationFilterListHasBeenSet; }; } // namespace Model } // namespace LicenseManager } // namespace Aws
65.962963
223
0.671884
[ "vector", "model" ]
08ab8fdbba015fcfc5d24c65068b19b85da7ded1
7,855
h
C
explorer_navigation/map_server/hector_marker_drawing/include/hector_marker_drawing/HectorDrawings.h
NaiveCoder1999/nwpu_explorer_2019
3a68c40ae4f148cabe381df19d7d0bfd53bf7877
[ "MIT" ]
1
2021-05-03T05:01:34.000Z
2021-05-03T05:01:34.000Z
explorer_navigation/map_server/hector_marker_drawing/include/hector_marker_drawing/HectorDrawings.h
NaiveCoder1999/nwpu_explorer_2019
3a68c40ae4f148cabe381df19d7d0bfd53bf7877
[ "MIT" ]
null
null
null
explorer_navigation/map_server/hector_marker_drawing/include/hector_marker_drawing/HectorDrawings.h
NaiveCoder1999/nwpu_explorer_2019
3a68c40ae4f148cabe381df19d7d0bfd53bf7877
[ "MIT" ]
1
2019-11-25T10:14:56.000Z
2019-11-25T10:14:56.000Z
//================================================================================================= // Copyright (c) 2011, Stefan Kohlbrecher, TU Darmstadt // 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 the Simulation, Systems Optimization and Robotics // group, TU Darmstadt 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 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 HOLDER 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. //================================================================================================= #include "DrawInterface.h" //#include "util/UtilFunctions.h" #include "ros/ros.h" #include <Eigen/Geometry> #include <Eigen/Dense> #include <visualization_msgs/MarkerArray.h> class HectorDrawings : public DrawInterface { public: HectorDrawings() { idCounter = 0; maxId = 0; ros::NodeHandle nh_; markerPublisher_ = nh_.advertise<visualization_msgs::Marker>("visualization_marker", 1, true); markerArrayPublisher_ = nh_.advertise<visualization_msgs::MarkerArray>("visualization_marker_array", 1, true); tempMarker.header.frame_id = "map"; tempMarker.ns = "marker"; this->setScale(1.0); this->setColor(1.0, 1.0, 1.0); tempMarker.action = visualization_msgs::Marker::ADD; }; virtual void setNamespace(const std::string& ns) { tempMarker.ns = ns; } virtual void drawPoint(const Eigen::Vector2f& pointWorldFrame)//画点 { tempMarker.id = idCounter++; tempMarker.pose.position.x = pointWorldFrame.x(); tempMarker.pose.position.y = pointWorldFrame.y(); tempMarker.pose.orientation.w = 0.0; tempMarker.pose.orientation.z = 0.0; tempMarker.type = visualization_msgs::Marker::CUBE; //markerPublisher_.publish(tempMarker); markerArray.markers.push_back(tempMarker); } virtual void drawArrow(const Eigen::Vector3f& poseWorld)//绘制箭头? { tempMarker.id = idCounter++; tempMarker.pose.position.x = poseWorld.x(); tempMarker.pose.position.y = poseWorld.y(); tempMarker.pose.orientation.w = cos(poseWorld.z()*0.5f); tempMarker.pose.orientation.z = sin(poseWorld.z()*0.5f); tempMarker.type = visualization_msgs::Marker::ARROW; //markerPublisher_.publish(tempMarker); markerArray.markers.push_back(tempMarker); } virtual void drawCovariance(const Eigen::Vector2f& mean, const Eigen::Matrix2f& covMatrix)//画的协方差 { tempMarker.pose.position.x = mean[0]; tempMarker.pose.position.y = mean[1]; Eigen::SelfAdjointEigenSolver<Eigen::Matrix2f> eig(covMatrix); const Eigen::Vector2f& eigValues (eig.eigenvalues()); const Eigen::Matrix2f& eigVectors (eig.eigenvectors()); float angle = (atan2(eigVectors(1, 0), eigVectors(0, 0))); tempMarker.type = visualization_msgs::Marker::CYLINDER; double lengthMajor = sqrt(eigValues[0]); double lengthMinor = sqrt(eigValues[1]); tempMarker.scale.x = lengthMajor; tempMarker.scale.y = lengthMinor; tempMarker.scale.z = 0.001; tempMarker.pose.orientation.w = cos(angle*0.5); tempMarker.pose.orientation.z = sin(angle*0.5); tempMarker.id = idCounter++; markerArray.markers.push_back(tempMarker); } virtual void drawCovariance(const Eigen::Vector3f& mean, const Eigen::Matrix3f& covMatrix) { tempMarker.type = visualization_msgs::Marker::SPHERE; tempMarker.color.r = 0.0; tempMarker.color.a = 0.5; tempMarker.pose.position.x = mean[0]; tempMarker.pose.position.y = mean[1]; tempMarker.pose.position.z = mean[2]; Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig(covMatrix); const Eigen::Vector3f& eigValues (eig.eigenvalues()); const Eigen::Matrix3f& eigVectors (eig.eigenvectors()); Eigen::Matrix3f eigVectorsFlipped; eigVectorsFlipped.col(0) = eigVectors.col(2); eigVectorsFlipped.col(1) = eigVectors.col(1); eigVectorsFlipped.col(2) = eigVectors.col(0); if (eigVectorsFlipped.determinant() < 0){ eigVectorsFlipped.col(2) = -eigVectorsFlipped.col(2); } Eigen::Quaternionf quaternion (eigVectorsFlipped); //std::cout << "\neigVec:\n" << eigVectors << "\n"; //std::cout << "\neigVecFlipped:\n" << eigVectorsFlipped << "\n"; //std::cout << "\now:" << quaternion.w() << " x:" << quaternion.x() << " y:" << quaternion.y() << " z:" << quaternion.z() << "\n"; tempMarker.pose.orientation.w = quaternion.w(); tempMarker.pose.orientation.x = quaternion.x(); tempMarker.pose.orientation.y = quaternion.y(); tempMarker.pose.orientation.z = quaternion.z(); tempMarker.scale.x = sqrt(eigValues[2]); tempMarker.scale.y = sqrt(eigValues[1]); tempMarker.scale.z = sqrt(eigValues[0]); tempMarker.id = idCounter++; markerArray.markers.push_back(tempMarker); } virtual void setScale(double scale)// 规模 { tempMarker.scale.x = scale; tempMarker.scale.y = scale; tempMarker.scale.z = scale; } virtual void setColor(double r, double g, double b, double a = 1.0)//颜色 { tempMarker.color.r = r; tempMarker.color.g = g; tempMarker.color.b = b; tempMarker.color.a = a; } virtual void addMarker(visualization_msgs::Marker marker) {//添加标记 if (marker.id == 0) marker.id = idCounter++; if (marker.ns.empty()) marker.ns = tempMarker.ns; markerArray.markers.push_back(marker); } virtual void addMarkers(visualization_msgs::MarkerArray markers) { for(visualization_msgs::MarkerArray::_markers_type::iterator it = markers.markers.begin(); it != markers.markers.end(); ++it) { visualization_msgs::Marker &marker = *it; addMarker(marker); } } virtual void sendAndResetData() { allMarkers.markers.insert(allMarkers.markers.end(), markerArray.markers.begin(), markerArray.markers.end()); markerArrayPublisher_.publish(markerArray); markerArray.markers.clear(); if (idCounter > maxId) maxId = idCounter; idCounter = 0; } void setTime(const ros::Time& time) { tempMarker.header.stamp = time; } void reset() { for(visualization_msgs::MarkerArray::_markers_type::iterator it = allMarkers.markers.begin(); it != allMarkers.markers.end(); ++it) { it->action = visualization_msgs::Marker::DELETE; } markerArrayPublisher_.publish(allMarkers); allMarkers.markers.clear(); } ros::Publisher markerPublisher_; ros::Publisher markerArrayPublisher_; visualization_msgs::Marker tempMarker; visualization_msgs::MarkerArray markerArray; visualization_msgs::MarkerArray allMarkers; int idCounter; int maxId; };
32.325103
135
0.684532
[ "geometry" ]
08ad693a4136aa47cc197120582bfe0d49795802
1,428
h
C
python/jittor/src/misc/string_view_map.h
Exusial/jittor
eca21d5bba5098bce4f492fa44908677b6e76588
[ "Apache-2.0" ]
2,571
2020-03-20T03:38:35.000Z
2022-03-31T08:20:05.000Z
python/jittor/src/misc/string_view_map.h
Exusial/jittor
eca21d5bba5098bce4f492fa44908677b6e76588
[ "Apache-2.0" ]
197
2020-03-20T04:11:47.000Z
2022-03-31T10:14:24.000Z
python/jittor/src/misc/string_view_map.h
Exusial/jittor
eca21d5bba5098bce4f492fa44908677b6e76588
[ "Apache-2.0" ]
284
2020-03-20T03:53:15.000Z
2022-03-28T07:20:32.000Z
// *************************************************************** // Copyright (c) 2021 Jittor. All Rights Reserved. // Maintainers: Dun Liang <randonlang@gmail.com>. // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. // *************************************************************** #pragma once #if defined(__clang__) #include <string_view> #elif defined(__GNUC__) #include <experimental/string_view> #endif #include "common.h" namespace jittor { #if defined(__clang__) using std::string_view; #elif defined(__GNUC__) using std::experimental::string_view; #elif __cplusplus < 201400L using string_view = string; #else using std::string_view; #endif template<class T> struct string_view_map { typedef typename std::unordered_map<string_view, T> umap_t; typedef typename umap_t::iterator iter_t; umap_t umap; vector<string> holder; iter_t find(string_view sv) { return umap.find(sv); } iter_t begin() { return umap.begin(); } iter_t end() { return umap.end(); } const T& at(string_view sv) { return umap.at(sv); } size_t size() { return umap.size(); } T& operator[](string_view sv) { auto iter = find(sv); if (iter != end()) return iter->second; holder.emplace_back(sv); string_view nsv = holder.back(); return umap[nsv]; } }; } // jittor
25.052632
66
0.613445
[ "vector" ]
08ae136ac9a7e1eafdfe9aadcaa056002a78d053
15,517
h
C
ECSlidingViewController/ECSlidingViewController.h
sageamdp/ECSlidingViewController
5943f1cc9796dc3a34edb1b0107c3615627d1452
[ "MIT" ]
null
null
null
ECSlidingViewController/ECSlidingViewController.h
sageamdp/ECSlidingViewController
5943f1cc9796dc3a34edb1b0107c3615627d1452
[ "MIT" ]
null
null
null
ECSlidingViewController/ECSlidingViewController.h
sageamdp/ECSlidingViewController
5943f1cc9796dc3a34edb1b0107c3615627d1452
[ "MIT" ]
1
2020-02-19T00:18:29.000Z
2020-02-19T00:18:29.000Z
// ECSlidingViewController.h // ECSlidingViewController 2 // // Copyright (c) 2013, Michael Enriquez (http://enriquez.me) // // 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. #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "ECSlidingConstants.h" @class ECSlidingViewController; /** The `ECSlidingViewControllerLayout` protocol is adopted by an object that specifies a custom layout for the child view controllers. */ @protocol ECSlidingViewControllerLayout <NSObject> /** Called when the sliding view controller needs to update the child views in response to a rotation or bounds change. @param slidingViewController The sliding view controller that needs to update its layout. @param viewController The view controller that needs a layout update. @param topViewPosition The position of the top view. @return A frame for the given view controller at the given top view position. Return `CGRectInfinite` to use the default layout. */ - (CGRect)slidingViewController:(ECSlidingViewController *)slidingViewController frameForViewController:(UIViewController *)viewController topViewPosition:(ECSlidingViewControllerTopViewPosition)topViewPosition; @end /** The `ECSlidingViewControllerDelegate` protocol is adopted by an object that may customize a sliding view controller's animation transition, interactive transition, or the layout of the child views. */ @protocol ECSlidingViewControllerDelegate @optional /** Called to allow the delegate to return a non-interactive animator object for use during a transition. Returning an object will disable the sliding view controller's `transitionCoordinator` animation and completion callbacks. @param slidingViewController The sliding view controller that is being transitioned. @param operation The type of transition that is occuring. See `ECSlidingViewControllerOperation` for a list of possible values. @param topViewController @return The animator object responsible for managing the transition animations, or nil if you want to use the standard sliding view controller transitions. The object you return must conform to the `UIViewControllerAnimatedTransitioning` protocol. */ - (id<UIViewControllerAnimatedTransitioning>)slidingViewController:(ECSlidingViewController *)slidingViewController animationControllerForOperation:(ECSlidingViewControllerOperation)operation topViewController:(UIViewController *)topViewController; /** Called to allow the delegate to return an interactive animator object for use during a transition. Returning an object will disable the sliding view controller's `transitionCoordinator` block given to `notifyWhenInteractionEndsUsingBlock:` @param slidingViewController The sliding view controller that is being transitioned. @param animationController The non-interactive animator object. This will be the same object that is returned from `slidingViewController:animationController:topViewController`. @return The animator object responsible for managing the interactive transition, or nil if you want to use the standard sliding view controller transitions. The object you return must conform to the `UIViewControllerInteractiveTransitioning` protocol. */ - (id<UIViewControllerInteractiveTransitioning>)slidingViewController:(ECSlidingViewController *)slidingViewController interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>)animationController; /** Called to allow the delegate to return a layout object to customize the layout of a sliding view controller's child views. @param slidingViewController The sliding view controller whose layout needs updated. @param topViewPosition The position of the top view. @return The layout object responsible for managing the layout, or nil if you want to use the standard sliding view controller layout. The object you return must conform to the `ECSlidingViewControllerLayout` protocol. */ - (id<ECSlidingViewControllerLayout>)slidingViewController:(ECSlidingViewController *)slidingViewController layoutControllerForTopViewPosition:(ECSlidingViewControllerTopViewPosition)topViewPosition; @end /** `ECSlidingViewController` is a view controller container that manages a layered interface. The top layer anchors to the left or right side of the container while revealing the layer underneath it. This is most commonly known as the "Side Menu", "Slide Out", "Hamburger Menu/Drawer/Sidebar", etc... The top layer and the layers underneath it can be any `UIViewController`. You provide the top layer by specifying a `topViewController`. Anchoring the top layer to the right will reveal the `underLeftViewController`. Likewise, to the left it will reveal the `underRightViewController`. These view controllers may be changed at anytime, and it is common to do so. There is no interface provided for anchoring the top layer, but there are methods and a gesture available for doing so. The `topViewController` will typically have a button to animate an anchoring and/or attach the provided `panGesture` to do it interactively. */ @interface ECSlidingViewController : UIViewController <UIViewControllerContextTransitioning, UIViewControllerTransitionCoordinator, UIViewControllerTransitionCoordinatorContext> { @private CGFloat _anchorLeftPeekAmount; CGFloat _anchorLeftRevealAmount; CGFloat _anchorRightPeekAmount; CGFloat _anchorRightRevealAmount; UIPanGestureRecognizer *_panGesture; UITapGestureRecognizer *_resetTapGesture; @protected UIViewController *_topViewController; UIViewController *_underLeftViewController; UIViewController *_underRightViewController; } ///---------------------------------------- /// @name Creating Sliding View Controllers ///---------------------------------------- /** Creates and returns a sliding view controller with the given `topViewController`. @param topViewController The view controller that will be displayed when sliding view controller loads. @return A sliding view controller with the given `topViewController`. */ + (instancetype)slidingWithTopViewController:(UIViewController *)topViewController; /** Initializes and returns a newly created sliding view controller. @param topViewController The view controller that will be displayed when sliding view controller loads. @return The initialized sliding view controller. */ - (instancetype)initWithTopViewController:(UIViewController *)topViewController; ///------------------------------------ /// @name Managing the View Controllers ///------------------------------------ /** The main view controller that anchors to the left or right side of the container. */ @property (nonatomic, strong) UIViewController *topViewController; /** The view controller that is revealed when the top view anchors to the right side of the container. */ @property (nonatomic, strong) UIViewController *underLeftViewController; /** The view controller that is revealed when the top view anchors to the left side of the container. */ @property (nonatomic, strong) UIViewController *underRightViewController; ///----------------------------- /// @name Configuring the Layout ///----------------------------- /** The fixed distance between the left side of the container and the right edge of the top view when the top view is anchored to the left. This value remains constant duration rotation or bound changes. Setting this value will automatically calculate `anchorLeftRevealAmount`. This value is not set by default, therefore it is variable and dependent upon the default value of `anchorLeftRevealAmount`. @see anchorLeftRevealAmount */ @property (nonatomic, assign) CGFloat anchorLeftPeekAmount; /** The fixed distance between the right edge of the top view and the right side of the container when the top view is anchored to the left. This value remains constant duration rotation or bound changes. Setting this value will automatically calculate `anchorLeftPeekAmount`. This is set to 44.0 by default. @see anchorLeftPeekAmount */ @property (nonatomic, assign) CGFloat anchorLeftRevealAmount; /** The fixed distance between the left edge of the top view and the right side of the container when the top view is anchored to the right. This value remains constant duration rotation or bound changes. Setting this value will automatically calculate `anchorRightRevealAmount`. This value si not set by default, therefore it is variable and dependent upon the default value of `anchorRightRevealAmount`. @see anchorRightRevealAmount */ @property (nonatomic, assign) CGFloat anchorRightPeekAmount; /** The fixed distance between the left side of the container and the left edge of the top view when the top view is anchored to the right. This value remains constant duration rotation or bound changes. Setting this value will automatically calculate `anchorRightPeekAmount`. This is set to 276.0 by default. @see anchorRightPeekAmount */ @property (nonatomic, assign) CGFloat anchorRightRevealAmount; ///--------------------------- /// @name Moving the Top Layer ///--------------------------- /** Anchors the `topViewController`'s view to the right side of the container to reveal the `underLeftViewController`'s view. @param animated Specify `YES` to animate the transition or `NO` if you do not want the transition to be animated. */ - (void)anchorTopViewToRightAnimated:(BOOL)animated; /** Anchors the `topViewController`'s view to the right side of the container to reveal the `underLeftViewController`'s view. @param animated Specify `YES` to animate the transition or `NO` if you do not want the transition to be animated. @param complete A completion handler. */ - (void)anchorTopViewToRightAnimated:(BOOL)animated onComplete:(void (^)())complete; /** Anchors the `topViewController`'s view to the left side of the container to reveal the `underRightViewController`'s view. @param animated Specify `YES` to animate the transition or `NO` if you do not want the transition to be animated. */ - (void)anchorTopViewToLeftAnimated:(BOOL)animated; /** Anchors the `topViewController`'s view to the left side of the container to reveal the `underRightViewController`'s view. @param animated Specify `YES` to animate the transition or `NO` if you do not want the transition to be animated. @param complete A completion handler. */ - (void)anchorTopViewToLeftAnimated:(BOOL)animated onComplete:(void (^)())complete; /** Resets the `topViewController`'s view's position to the middle. Completely covers any view that was underneath it. @param animated Specify `YES` to animate the transition or `NO` if you do not want the transition to be animated. */ - (void)resetTopViewAnimated:(BOOL)animated; /** Resets the `topViewController`'s view's position to the middle. Completely covers any view that was underneath it. @param animated Specify `YES` to animate the transition or `NO` if you do not want the transition to be animated. @param complete A completion handler. */ - (void)resetTopViewAnimated:(BOOL)animated onComplete:(void(^)())complete; ///// ADDED THIS /** Returns if the viewController already exists in the array and therefore should not be instantiated again */ + (UIViewController * _Nullable) queryViewController:(NSString *)viewControllerIdentifier; /** Adds the viewController to the list of existing viewControllers when creating it */ + (void) addViewController:(NSString *)viewControllerIdentifier viewController:(UIViewController *)avc; /** Removes all previous controllers from memory. Useful for login/logout. */ + (void) emptyViewControllers; ///-------------------------------------- /// @name User Defined Runtime Attributes ///-------------------------------------- /** The Storyboard identifier of a view controller to be used as the `topViewController`. Set this using the Identity Inspector for the sliding view controller instance in Storyboards. */ @property (nonatomic, strong) NSString *topViewControllerStoryboardId; /** The Storyboard identifier of a view controller to be used as the `underLeftViewController`. Set this using the Identity Inspector for the sliding view controller instance in Storyboards. */ @property (nonatomic, strong) NSString *underLeftViewControllerStoryboardId; /** The Storyboard identifier of a view controller to be used as the `underRightViewController`. Set this using the Identity Inspector for the sliding view controller instance in Storyboards. */ @property (nonatomic, strong) NSString *underRightViewControllerStoryboardId; ///----------------------------------- /// @name Customizing Default Behavior ///----------------------------------- /** The delegate that provides objects to customizing the transition animation, transition interaction, or layout of the child view controllers. See the `ECSlidingViewControllerDelegate` protocol for more information. */ @property (nonatomic, assign) id<ECSlidingViewControllerDelegate> delegate; /** A mask of gestures/behaviors indicating how you want the top view to act while it is in the anchored position. Useful for customizing how you want your users to reset the top view. The default is `ECSlidingViewControllerAnchoredGestureNone`. */ @property (nonatomic, assign) ECSlidingViewControllerAnchoredGesture topViewAnchoredGesture; /** The current position of the top view. */ @property (nonatomic, assign, readonly) ECSlidingViewControllerTopViewPosition currentTopViewPosition; /** The gesture that triggers the default interactive transition for a horizontal swipe. This is typically added to the top view or one of the top view's subviews. */ @property (nonatomic, strong, readonly) UIPanGestureRecognizer *panGesture; /** The gesture that triggers the top view to reset. Useful for resetting the top view when in the anchored position. */ @property (nonatomic, strong, readonly) UITapGestureRecognizer *resetTapGesture; /** Gestures used on the top view while it is in the reset position. This is only used when the `topViewAnchoredGesture` property contains the `ECSlidingViewControllerAnchoredGestureCustom` option. */ @property (nonatomic, strong) NSArray *customAnchoredGestures; /** The default duration of the view transition. */ @property (nonatomic, assign) NSTimeInterval defaultTransitionDuration; @end
48.949527
402
0.767739
[ "object" ]
08ba636551a77dab03651d94b480a35fcfef44e1
4,437
h
C
Tau/src/thrids/dsignal/Bode.h
cymheart/tau
1881046c7e362451e8d4f5d4b885e9011dade319
[ "MIT" ]
7
2021-10-05T07:07:45.000Z
2022-03-01T07:28:34.000Z
Tau/src/thrids/dsignal/Bode.h
cymheart/tau
1881046c7e362451e8d4f5d4b885e9011dade319
[ "MIT" ]
1
2021-09-21T07:25:53.000Z
2021-10-02T02:02:10.000Z
Tau/src/thrids/dsignal/Bode.h
cymheart/ventrue
57219117a40077ffdde76c7183ea744c0ac2a08f
[ "MIT" ]
1
2022-02-24T21:24:27.000Z
2022-02-24T21:24:27.000Z
#ifndef _Bode_h_ #define _Bode_h_ #include "scutils/Utils.h" #include "scutils/MathUtils.h" #include "Filter.h" using namespace scutils; namespace dsignal { /** *bode图参数计算 * by cymheart, 2020--2021. */ class Bode { public: Bode(); ~Bode(); //增加数字滤波器到要计算的bode图中 void AddFilters(vector<dsignal::Filter*>& filterVec); //增加一个数字滤波器到要计算的bode图中 void AddFilter(Filter* filter); //设置是否使用对数坐标轴 void SetUseLogAxis(bool isUse) { isUseLogAxis = isUse; } //判断是否使用了对数坐标轴 bool IsUseLogAxis() { return isUseLogAxis; } //设置滤波器之间是否互相变形绘制 void SetFilterBetwwenMorphPlot(bool isMorphPlot) { isFilterBetweenMorphPlot = isMorphPlot; } //设置采样频率 void SetSampleFreq(float sfreq) { sampleFreq = sfreq; } //设置bode图绘制区域的宽度 void SetPlotAreaWidth(float width) { plotAreaWidth = width; } //设置bode图绘制区域的高度 void SetPlotAreaHeight(float height) { plotAreaHeigth = height; } //设置bode图绘制区域频率轴的起始Hz(单位:HZ) void SetPlotFreqAxisStart(float startFreqHz) { plotFreqAxisStart = startFreqHz; } //设置bode图绘制区域频率轴的结束Hz(单位:HZ) void SetPlotFreqAxisEnd(float endFreqHz) { plotFreqAxisEnd = endFreqHz; } //设置bode图绘制区域增益DB的范围 //默认值:+15dB ~ -15dB 范围为30dB void SetPlotGainDbRange(float gainRangeDB) { if (gainRangeDB < 0) gainRangeDB = -gainRangeDB; plotGainAxisRange = gainRangeDB; } //设置增益的偏移DB void SetGainOffsetDB(float offsetGainDB) { this->offsetGainDB = offsetGainDB; } //设置频率轴标尺频率点 void SetRulerFreqs(float rulerFreqs[], int len); //设置增益轴标尺dB点 void SetRulerGainDBs(float ruleGainDB[], int len); //计算生成bode图所需要的参数 void Compute(); //获取bode图绘制区域的宽度 float GetPlotAreaWidth() { return plotAreaWidth; } //获取bode图绘制区域的高度 float GetPlotAreaHeigth() { return plotAreaHeigth; } //bode图绘制频率轴位置点集合 float* GetPlotFreqAxisPos() { return plotFreqAxisPos; } //获取bode图绘制增益轴位置点集合 float* GetPlotGainAxisPos() { return plotGainAxisPos; } //获取bode图绘制轴位置点数量 int GetPlotAxisPosCount() { return plotPosCount; } //获取bode图绘制频率轴标尺频率点位 vector<float> GetPlotRulerFreqsPos() { return plotRulerFreqsPos; } //获取bode图绘制增益轴标尺dB点位 vector<float> GetPlotRulerGainDBsPos() { return plotRulerGainDBsPos; } private: //根据给定的低频高频步进值,分别获取低频和高频类型的采样总数, //然后两次调用Freqz(),得到低频采样数量的xout,和高频采样数量的xout,前后合在一起 //之所以不一次使用Freqz()全频取所有采样值,是因为对频率等分分割分配时,受对数坐标影响 //低频会占用绘制区域的很大一块显示空间,但采样值由于平均分配,低频采样值将不足,而不足以形成连贯显示,所有 //使用了两次Freqz(),第一次是对低频的分配采样,分配间隔比较小,在低频将获取足够的采样值, //高频,由于在对数坐标空间中会被压缩,将只需要很少的采样值,因此分配间隔比较大, //两段采样值的衔接,必须在低频和高频分割点位无缝衔接,这就要求对perLowFreqHz,perHighFreqHz严格取值适配 void Freqz(); //频率转换到轴位置 float FreqToAxisPos(float freq); private: //数字滤波器 vector<Filter*> filters; //是否使用对数坐标 bool isUseLogAxis = true; //是否滤波器之间互相变形绘制 bool isFilterBetweenMorphPlot = false; //采样频率 float sampleFreq = 44100; //最大频率 float maxFreq = 44100 / 2; //单位频率 float unitFreq = maxFreq / 512; //采样个数 int sampleCount = 0; //bode图绘制区域的宽度 float plotAreaWidth = 200; //bode图绘制区域的高度 float plotAreaHeigth = 200; //bode图绘制区域增益轴DB的范围 //例如:+15dB ~ -15dB 范围为30dB float plotGainAxisRange = 20; //增益偏移 float offsetGainDB = 0; //bode图绘制区域频率轴的起始位置(单位:HZ) float plotFreqAxisStart = 0; //bode图绘制区域频率轴的结束位置(单位:HZ) float plotFreqAxisEnd = 44100 / 2; float plotFreqAxisWidth = 0; //bode图绘制区域频率轴的起始对数位置(单位:对数) float freqAxisStartLogPos = 0; //bode图绘制区域频率轴的结束对数位置(单位:对数) float freqAxisEndLogPos = 0; //对数宽度 float freqAxisLogWidth = 0; //频率轴标尺频率点 vector<float> rulerFreqs; //bode图绘制频率轴标尺频率点位 vector<float> plotRulerFreqsPos; //增益轴标尺dB点 vector<float> rulerGainDBs; //bode图绘制增益轴标尺dB点位 vector<float> plotRulerGainDBsPos; //bode图绘制频率轴位置点集合 float* plotFreqAxisPos = nullptr; //bode图绘制增益轴位置点集合 float* plotGainAxisPos = nullptr; //bode图绘制位置数量 int plotPosCount = 0; //以 dB 为单位的频率响应 double* x_out = nullptr; //频率响应的幅角 double* y_out = nullptr; double* x_out_tmp = nullptr; double* y_out_tmp = nullptr; float lowFreqEndHzSetting = 1000; float lowFreqStartHz = 0; //低频起始位置频率 float lowFreqEndHz = 0; //低频结束位置频率 int lowFreqSampleCount = 0; //低频采样数量 float perLowFreqHz = 0; //低频步进值 float highFreqStartHz = 0; //高频起始位置频率 float highFreqEndHz = 0; //高频结束位置频率 int highFreqSampleCount = 0; //高频采样数量 float perHighFreqHz = 0; //高频步进值 }; } #endif
17.4
67
0.703178
[ "vector" ]
08c076c15af4b949e4ad926ad979f2f617dbdd65
2,027
h
C
include/yds_interchange_file_0_0.h
ange-yaghi/delta-studio
8466623bdced4706c66643e2b790591517e56821
[ "MIT" ]
34
2020-07-10T14:23:49.000Z
2022-03-31T23:38:36.000Z
include/yds_interchange_file_0_0.h
ange-yaghi/delta-studio
8466623bdced4706c66643e2b790591517e56821
[ "MIT" ]
7
2020-12-20T17:32:08.000Z
2021-05-19T03:42:08.000Z
include/yds_interchange_file_0_0.h
ange-yaghi/delta-studio
8466623bdced4706c66643e2b790591517e56821
[ "MIT" ]
2
2021-02-09T20:04:04.000Z
2022-01-26T08:46:20.000Z
#ifndef YDS_INTERCHANGE_FILE_0_0_H #define YDS_INTERCHANGE_FILE_0_0_H #include "yds_base.h" #include "yds_interchange_object.h" #include "yds_math.h" #include <fstream> class ysInterchangeFile0_0 : public ysObject { public: static constexpr int MAJOR_VERSION = 0; static constexpr int MINOR_VERSION = 0; static constexpr int MAGIC_NUMBER = 0xFEA4A; public: struct IdHeader { unsigned int MagicNumber; unsigned int MajorVersion; unsigned int MinorVersion; unsigned int EditorId; unsigned int CompilationStatus; }; struct ObjectInformation { char Name[256]; char MaterialName[256]; int ModelIndex; int ParentIndex; }; struct ObjectTransformation { ysVector3 Position; ysVector3 OrientationEuler; ysVector4 Orientation; ysVector3 Scale; }; struct SceneHeader { unsigned int ObjectCount; }; struct GeometryInformation { unsigned int UVChannelCount; unsigned int VertexCount; unsigned int NormalCount; unsigned int TangentCount; unsigned int FaceCount; }; struct UVChannel { unsigned int UVCount; }; struct IndexSet { int u, v, w; }; public: ysInterchangeFile0_0(); ~ysInterchangeFile0_0(); ysError Open(const char *fname); ysError Close(); unsigned int GetMinorVersion() const { return m_minorVersion; } unsigned int GetMajorVersion() const { return m_majorVersion; } unsigned int GetObjectCount() const { return m_objectCount; } unsigned int GetToolId() const { return m_toolId; } bool GetCompilationStatus() const { return m_compilationStatus; } ysError ReadObject(ysInterchangeObject *object); protected: std::fstream m_file; unsigned int m_minorVersion; unsigned int m_majorVersion; unsigned int m_toolId; unsigned int m_objectCount; bool m_compilationStatus; }; #endif /* YDS_INTERCHANGE_FILE_0_0_H */
22.032609
69
0.677356
[ "object" ]
08c8813282911c08c5bb21679a90f9f9463abe74
1,729
h
C
OutPutHeaders/AppCommunicateData.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
106
2016-04-09T01:16:14.000Z
2021-06-04T00:20:24.000Z
OutPutHeaders/AppCommunicateData.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
2
2017-06-13T09:41:29.000Z
2018-03-26T03:32:07.000Z
OutPutHeaders/AppCommunicateData.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
58
2016-04-28T09:52:08.000Z
2021-12-25T06:42:14.000Z
/** * This header is generated by class-dump-z 0.2a. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: (null) */ #import <XXUnknownSuperclass.h> // Unknown library @class NSData, NSString, NSArray, NSMutableDictionary; @interface AppCommunicateData : XXUnknownSuperclass { unsigned _command; NSMutableDictionary* _dictionaryData; NSData* _fileData; NSArray* _fileDatas; BOOL _returnFromApp; NSString* _conversationAccount; int _result; int _scene; NSString* _openID; NSString* _sdkVer; NSString* _lang; NSString* _country; } @property(retain, nonatomic) NSArray* fileDatas; @property(retain, nonatomic) NSString* country; @property(retain, nonatomic) NSString* lang; @property(retain, nonatomic) NSString* sdkVer; @property(retain, nonatomic) NSString* openID; @property(assign, nonatomic) int scene; @property(retain, nonatomic) NSData* fileData; @property(retain, nonatomic) NSString* conversationAccount; @property(assign, nonatomic) BOOL returnFromApp; @property(assign, nonatomic) int result; -(void).cxx_destruct; -(BOOL)RespToData:(id)data; -(BOOL)ReqToData:(id)data withMediaInternalMessage:(id)mediaInternalMessage; -(BOOL)ReqToData:(id)data; -(id)DataToResp; -(id)DataToReq; -(BOOL)MakeMediaInternalMessage:(id)message; -(id)mediaInternalMessage; -(BOOL)MakeMediaMessage:(id)message; -(BOOL)MakeLinkObject:(id)object; -(id)mediaMessage; -(BOOL)MakeTextMessage:(id)message; -(id)textMessage; -(BOOL)MakeAuthResp:(id)resp; -(id)authResp; -(BOOL)MakeAuthRequest:(id)request; -(id)authRequest; -(BOOL)MakeCommand:(unsigned)command; -(void)initCommonField:(unsigned)field; -(unsigned)command; -(id)propertList; -(id)initWithPropertList:(id)propertList; -(id)init; @end
28.344262
76
0.769231
[ "object" ]
08c98d9158165b11b82cb6749d870a504acda00b
12,761
h
C
pxr/base/lib/vt/functions.h
unity3d-jp/USD
0f146383613e1efe872ea7c85aa3536f170fcda2
[ "BSD-3-Clause" ]
7
2016-12-13T00:53:38.000Z
2020-04-02T13:25:50.000Z
pxr/base/lib/vt/functions.h
unity3d-jp/USD
0f146383613e1efe872ea7c85aa3536f170fcda2
[ "BSD-3-Clause" ]
null
null
null
pxr/base/lib/vt/functions.h
unity3d-jp/USD
0f146383613e1efe872ea7c85aa3536f170fcda2
[ "BSD-3-Clause" ]
2
2016-12-13T00:53:40.000Z
2020-05-04T07:32:53.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #if !BOOST_PP_IS_ITERATING #include "pxr/base/vt/array.h" #include <vector> /// /// \file vt/functions.h /// #define VT_FUNCTIONS_MAX_ARGS 6 // Set up preprocessor iterations to allow various functions to accept multiple // arguments. // VtCat #define BOOST_PP_ITERATION_PARAMS_1 (4, \ (0, VT_FUNCTIONS_MAX_ARGS, "pxr/base/vt/functions.h", 0)) #include BOOST_PP_ITERATE() // **************************************************************************** // Doc headers for functions that are generated through macros. These get // decent doxygen (and epydoc) output even though we can't put them on the // real functions because they're expanded through boost or cpp macros. // **************************************************************************** // documentation for bool-result array comparison functions #ifdef doxygen /// \brief Returns a bool array specifying, element-by-element, if the two /// inputs contain equal values. The shape of the return array is /// the same as the shape of the largest input array. /// /// If one input is a single element (either a single-element array or a scalar /// of the same type held in the array), it is compared to all the elements /// in the other array. Otherwise both arrays must have the same shape. template<typename T> VtArray<T> VtEqual( VtArray<T> const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtEqual( T const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtEqual( VtArray<T> const &a, T const &b ); /// \brief Returns a bool array specifying, element-by-element, if the two /// inputs contain inequal values. The shape of the return array is /// the same as the shape of the largest input array. /// /// If one input is a single element (either a single-element array or a scalar /// of the same type held in the array), it is compared to all the elements /// in the other array. Otherwise both arrays must have the same shape. template<typename T> VtArray<T> VtNotEqual( VtArray<T> const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtNotEqual( T const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtNotEqual( VtArray<T> const &a, T const &b ); /// \brief Returns a bool array specifying, element-by-element, if the first /// input contains values greater than those in the second input. /// The shape of the return array is /// the same as the shape of the largest input array. /// /// If one input is a single element (either a single-element array or a scalar /// of the same type held in the array), it is compared to all the elements /// in the other array. Otherwise both arrays must have the same shape. template<typename T> VtArray<T> VtGreater( VtArray<T> const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtGreater( T const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtGreater( VtArray<T> const &a, T const &b ); /// \brief Returns a bool array specifying, element-by-element, if the first /// input contains values less than those in the second input. /// The shape of the return array is /// the same as the shape of the largest input array. /// /// If one input is a single element (either a single-element array or a scalar /// of the same type held in the array), it is compared to all the elements /// in the other array. Otherwise both arrays must have the same shape. template<typename T> VtArray<T> VtLess( VtArray<T> const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtLess( T const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtLess( VtArray<T> const &a, T const &b ); /// \brief Returns a bool array specifying, element-by-element, if the first /// input contains values greater than or equal to those in the second input. /// The shape of the return array is /// the same as the shape of the largest input array. /// /// If one input is a single element (either a single-element array or a scalar /// of the same type held in the array), it is compared to all the elements /// in the other array. Otherwise both arrays must have the same shape. template<typename T> VtArray<T> VtGreaterOrEqual( VtArray<T> const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtGreaterOrEqual( T const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtGreaterOrEqual( VtArray<T> const &a, T const &b ); /// \brief Returns a bool array specifying, element-by-element, if the first /// input contains values less than or equal to those in the second input. /// The shape of the return array is /// the same as the shape of the largest input array. /// /// If one input is a single element (either a single-element array or a scalar /// of the same type held in the array), it is compared to all the elements /// in the other array. Otherwise both arrays must have the same shape. template<typename T> VtArray<T> VtLessOrEqual( VtArray<T> const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtLessOrEqual( T const &a, VtArray<T> const &b ); template<typename T> VtArray<T> VtLessOrEqual( VtArray<T> const &a, T const &b ); #endif // provide documentation for functions with variable numbers of inputs #ifdef doxygen /// \brief Concatenates arrays. /// /// The result is an array with length equal to the sum of the number /// of elements in the source arrays. template<typename T> VtArray<T> VtCat( VtArray<T> const &a0, VtArray<T> const &a1, ... VtArray<T> const &aN); #endif // **************************************************************************** // Fixed-number-of-arguments functions go here (no preprocessor iteration to // handle multiple args) // **************************************************************************** /// \brief Returns true if any element of input array is not VtZero, else false. /// /// Intended to be used to evaluate results of boolean operations on arrays, e.g. /// \code /// a = Vt.StringArray((3,),("foo","bar","baz")) /// t = Vt.AnyTrue(Vt.Equal(a,"bar")) /// \endcode /// /// (This example, if /// you look carefully, evaluates this function not on the strings, but on /// the results of the comparison). template<typename T> bool VtAnyTrue(VtArray<T> const &a) { if (a.empty()) return false; for (size_t i = 0; i != a.size(); ++i) { if (a[i] != VtZero<T>()) return true; } return false; } /// \brief Returns true if every element of input array is not VtZero, else /// false. /// /// Intended to be used to evaluate results of boolean operations on arrays, e.g. /// \code /// a = Vt.StringArray((3,),("foo","bar","baz")) /// t = Vt.AllTrue(Vt.Equal(a,"bar")) /// \endcode /// /// (This example, if /// you look carefully, evaluates this function not on the strings, but on /// the results of the comparison). template<typename T> bool VtAllTrue(VtArray<T> const &a) { if (a.empty()) return false; for (size_t i = 0; i != a.size(); ++i) { if (a[i] == VtZero<T>()) return false; } return true; } // Macro defining functions for element-by-element comparison // operators (i.e. Equal, etc). There are three versions; each returns // a VtBoolArray of the same shape as the largest input. // *) two input arrays: // If one array contains a single element, it is compared to all the elements // in the other array. Otherwise both arrays must have the same shape. // *) scalar and array: // The scalar is compared to all the elements in the array. // *) array and scalar: // The same as scalar and array. #define VTFUNCTION_BOOL(funcname,op) \ template<typename T> \ VtArray<bool> \ funcname(T const &scalar, VtArray<T> const &vec) { \ VtArray<bool> ret(vec.size()); \ for (size_t i = 0, n = vec.size(); i != n; ++i) \ ret[i] = (scalar op vec[i]); \ return ret; \ } \ template<typename T> \ VtArray<bool> \ funcname(VtArray<T> const &vec, T const &scalar) { \ VtArray<bool> ret(vec.size()); \ for (size_t i = 0, n = vec.size(); i != n; ++i) \ ret[i] = (vec[i] op scalar); \ return ret; \ } \ template<typename T> \ VtArray<bool> \ funcname(VtArray<T> const &a, VtArray<T> const &b) \ { \ if (a.empty() || b.empty()) { \ return VtArray<bool>(); \ } \ \ if (a.size() == 1) { \ return funcname(a[0], b); \ } else if (b.size() == 1) { \ return funcname(a, b[0]); \ } else if (a.size() == b.size()) { \ VtArray<bool> ret(a.size()); \ for (size_t i = 0, n = a.size(); i != n; ++i) { \ ret[i] = (a[i] op b[i]); \ } \ return ret; \ } else { \ TF_CODING_ERROR("Non-conforming inputs."); \ return VtArray<bool>(); \ } \ } VTFUNCTION_BOOL(VtEqual,==) VTFUNCTION_BOOL(VtNotEqual,!=) VTFUNCTION_BOOL(VtGreater,>) VTFUNCTION_BOOL(VtLess,<) VTFUNCTION_BOOL(VtGreaterOrEqual,>=) VTFUNCTION_BOOL(VtLessOrEqual,<=) #else // BOOST_PP_IS_ITERATING // **************************************************************************** // Variable-number-of-arguments functions go here; preprocessor iteration // includes this file again and again, but turns off the pieces we don't // want to use for a particular function. // **************************************************************************** #define N BOOST_PP_ITERATION() #if BOOST_PP_ITERATION_FLAGS() == 0 // VtCat #define VtCat_SIZE(dummy, n, dummy2) newSize += s##n.size(); #define VtCat_COPY(dummy, n, dummy2) \ for (size_t i = 0; i < s##n.size(); ++i) \ ret[offset+i] = s##n[i]; \ offset += s##n.size(); // real documentation is above (for doxygen purposes) template<typename T> VtArray<T> VtCat( BOOST_PP_ENUM_PARAMS(N, VtArray<T> const &s) ) { size_t newSize = 0; BOOST_PP_REPEAT( N, VtCat_SIZE, ignored ) if (newSize == 0) return VtArray<T>(); // new array with flattened size VtArray<T> ret(newSize); // fill it with data from old arrays size_t offset = 0; BOOST_PP_REPEAT( N, VtCat_COPY, ignored ) return ret; } #undef VtCat_SIZE #undef VtCat_COPY #endif // BOOST_PP_ITERATION_FLAGS #undef N #endif // BOOST_PP_IS_ITERATING
37.866469
81
0.574641
[ "shape", "vector" ]
08ce989bf8876931f8d88328cee2b6a6920849ee
23,348
h
C
ps/base/cards.h
mastermind88/CandyPoker
37b502ce6ea8733ce0b70476fcf32930961923a8
[ "MIT" ]
null
null
null
ps/base/cards.h
mastermind88/CandyPoker
37b502ce6ea8733ce0b70476fcf32930961923a8
[ "MIT" ]
null
null
null
ps/base/cards.h
mastermind88/CandyPoker
37b502ce6ea8733ce0b70476fcf32930961923a8
[ "MIT" ]
null
null
null
/* CandyPoker https://github.com/sweeterthancandy/CandyPoker MIT License Copyright (c) 2019 Gerry Candy 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 PS_CORE_CARDS_H #define PS_CORE_CARDS_H #include <vector> #include <set> #include <map> #include <bitset> #include <unordered_set> #include "ps/base/cards_fwd.h" #include "ps/detail/void_t.h" #include "ps/detail/print.h" #include "ps/detail/popcount.h" #include "ps/support/index_sequence.h" #define PS_ASSERT_VALID_SUIT_ID(x) PS_ASSERT( x < suit_decl::max_id, "suit_id = " << static_cast<int>(x)) #define PS_ASSERT_VALID_RANK_ID(x) PS_ASSERT( x < rank_decl::max_id, "rank_id = " << static_cast<int>(x)) #define PS_ASSERT_VALID_CARD_ID(x) PS_ASSERT( x < card_decl::max_id, "card_id = " << static_cast<int>(x)) #define PS_ASSERT_VALID_HOLDEM_ID(x) PS_ASSERT( x < holdem_hand_decl::max_id, "holdem_hand_id = " << static_cast<int>(x)) namespace ps{ struct card_vector : std::vector<card_id>{ template<class... Args> card_vector(Args&&... args):std::vector<card_id>{std::forward<Args>(args)...}{} size_t mask()const; static card_vector from_bitmask(size_t mask); static card_vector parse(std::string const& s); friend inline std::ostream& operator<<(std::ostream& ostr, card_vector const& self); std::unordered_set<card_id> to_set()const { return std::unordered_set<card_id>{begin(), end()}; } }; struct suit_decl{ using index_ty = suit_id; static constexpr suit_id max_id = 4; suit_decl(suit_id id, char sym, std::string const& name); auto id()const{ return id_; } const char symbol()const { return sym_; } std::string to_string()const{ return std::string{sym_}; } friend std::ostream& operator<<(std::ostream& ostr, suit_decl const& self){ return ostr << self.to_string(); } bool operator<(suit_decl const& that)const{ return id_ < that.id_; } static suit_decl const& get(suit_id id); static suit_decl const& parse(std::string const& s); static suit_decl const& parse(char c){ return parse(std::string{c}); } operator suit_id()const{ return id_; } // to help with unit testing template<class V> static void visit_suit_id_combinations(V&& v) { for (suit_id a = 0; (a + 1) != suit_decl::max_id; ++a) { for (suit_id b = a + 1; b != suit_decl::max_id; ++b) { v(a, b); } } } template<class V> static void visit_suit_combinations(V&& v) { auto outer = [&](suit_id a, suit_id b) { v(suit_decl::get(a), suit_decl::get(b)); }; suit_decl::visit_suit_id_combinations(outer); } private: suit_id id_; char sym_; std::string name_; }; struct rank_decl{ using index_ty = rank_id; static constexpr rank_id max_id = 13; rank_decl(rank_id id, char sym); auto id()const{ return id_; } const char symbol()const { return sym_; } std::string to_string()const{ return std::string{sym_}; } friend std::ostream& operator<<(std::ostream& ostr, rank_decl const& self){ return ostr << self.to_string(); } bool operator<(rank_decl const& that)const{ return id_ < that.id_; } static rank_decl const& get(rank_id id); static rank_decl const& parse(std::string const& s); static rank_decl const& parse(char c){ return parse(std::string{c}); } operator rank_id()const{ return id_; } private: rank_id id_; char sym_; }; struct card_decl{ using index_ty = card_id; static constexpr const card_id max_id = 52; card_decl(suit_decl const& s, rank_decl const& r); auto id()const{ return id_; } size_t mask()const{ return static_cast<size_t>(1) << id(); } std::string to_string()const; // id & 0x3 suit_decl const& suit()const{ return suit_; } // id >> 2 rank_decl const& rank()const{ return rank_; } friend std::ostream& operator<<(std::ostream& ostr, card_decl const& self){ return ostr << self.to_string(); } bool operator<(card_decl const& that)const{ return id_ < that.id_; } static card_decl const& get(card_id id); static card_decl const& parse(std::string const& s); operator card_id()const{ return id_; } static card_id make_id( suit_id s, rank_id r){ return s + r * 4; } private: card_id id_; suit_decl suit_; rank_decl rank_; }; struct holdem_hand_decl{ using index_ty = holdem_id; static constexpr const holdem_id max_id = 52 * 51 / 2; // a must be the biggest holdem_hand_decl(card_decl const& a, card_decl const& b); auto id()const{ return id_; } size_t mask()const{ return first().mask() | second().mask(); } std::string to_string()const{ return first_.to_string() + second_.to_string(); } friend std::ostream& operator<<(std::ostream& ostr, holdem_hand_decl const& self){ return ostr << self.to_string(); } bool operator<(holdem_hand_decl const& that)const{ return id_ < that.id_; } card_decl const& first()const{ return first_; } card_decl const& second()const{ return second_; } static holdem_hand_decl const& get(holdem_id id); static holdem_hand_decl const& get(card_id x, card_id y){ return get( make_id(x,y) ); } static holdem_hand_decl const& parse(std::string const& s); static holdem_id make_id( rank_id r0, suit_id s0, rank_id r1, suit_id s1); static holdem_id make_id(card_id x, card_id y); operator holdem_id()const{ return id_; } holdem_class_id class_()const; template<class... Args, class _ = detail::void_t< std::enable_if_t< std::is_same<std::decay_t<Args>, holdem_hand_decl>::value>... > > static bool disjoint(Args&&... args){ size_t mask{0}; int aux[] = {0, ( mask |= args.mask(), 0)...}; return detail::popcount(mask)*2 == sizeof...(args); } template<class... Args, class _ = detail::void_t< std::enable_if_t< std::is_integral<std::decay_t<Args> >::value>... > > static bool disjoint_id(Args&&... args){ return disjoint( holdem_hand_decl::get(args)... ); } bool is_suited()const noexcept{ return ( card_suit_from_id(first_.id()) == card_suit_from_id(second_.id()) ); } bool is_offsuit()const noexcept{ return ! is_suited(); } private: holdem_id id_; card_decl first_; card_decl second_; }; /* Hand vector is a vector of hands */ struct holdem_hand_vector : std::vector<ps::holdem_id>{ template<class... Args> holdem_hand_vector(Args&&... args) : std::vector<ps::holdem_id>{std::forward<Args>(args)...} {} // for unit testing template<class... Args> static holdem_hand_vector union_(Args&&... args) { std::unordered_set< holdem_id> s; const int aux[] = { (std::for_each(std::cbegin(args), std::cend(args), [&](holdem_id id) { s.insert(id); }), 0)... }; return holdem_hand_vector(std::cbegin(s), std::cend(s)); } holdem_hand_decl const& decl_at(size_t i)const; friend std::ostream& operator<<(std::ostream& ostr, holdem_hand_vector const& self); auto find_injective_permutation()const; bool disjoint()const; bool is_standard_form()const; size_t mask()const; card_vector to_card_vector()const; std::string to_string()const{ std::stringstream sstr; sstr << *this; return sstr.str(); } // treat every 4 chars as a card, ie // parse("2c2hAsKs"); // -> holdem_hand_vector({holdem_hand_decl::parse("2c2h"), holdem_hand_decl::parse("AsKs")}) static holdem_hand_vector parse(std::string const& s); std::unordered_set<holdem_id> to_set()const { return std::unordered_set<holdem_id>{begin(), end()}; } }; struct holdem_hand_iterator : basic_index_iterator< holdem_id, strict_lower_triangle_policy, holdem_hand_vector > { using impl_t = basic_index_iterator< holdem_id, strict_lower_triangle_policy, holdem_hand_vector > ; holdem_hand_iterator():impl_t{}{} holdem_hand_iterator(size_t n): impl_t(n, 52 * 51 / 2) {} }; struct holdem_class_decl{ using index_ty = holdem_class_id; static constexpr const holdem_class_id max_id = 13 * 13; holdem_class_decl(holdem_class_type cat, rank_decl const& a, rank_decl const& b); auto const& get_hand_set()const{ return hand_set_; } holdem_hand_vector const& get_hand_vector()const{ return hand_id_set_; } auto id()const{ return id_; } holdem_class_type category()const{ return cat_; } std::string to_string()const; friend std::ostream& operator<<(std::ostream& ostr, holdem_class_decl const& self){ return ostr << self.to_string(); } bool operator<(holdem_class_decl const& that)const{ return id_ < that.id_; } size_t weight()const{ switch(cat_){ case holdem_class_type::suited: return 4; case holdem_class_type::offsuit: return 12; default: // don't care case holdem_class_type::pocket_pair: return 6; } } double prob()const{ constexpr size_t half{ ( 13 * 13 - 13 ) / 2 }; constexpr size_t sigma{ 13 * 6 + half * 12 + half * 4 }; return static_cast<double>(weight()) / sigma; } decltype(auto) first()const{ return first_; } decltype(auto) second()const{ return second_; } static holdem_class_decl const& get(holdem_id id); /* parse("XX") or parse("XYs") or parse("XYo") */ static holdem_class_decl const& parse(std::string const& s); // any bijection will do, nice to keep the mapping within a char static holdem_class_id make_id(holdem_class_type cat, rank_id x, rank_id y); operator holdem_class_id()const{ return id_; } // TODO generlaize these static size_t weight(holdem_class_id c0, holdem_class_id c1); static double prob(holdem_class_id c0, holdem_class_id c1); private: holdem_class_id id_; holdem_class_type cat_; rank_decl first_; rank_decl second_; std::vector<holdem_hand_decl> hand_set_; std::vector<holdem_id> hand_id_vec_; holdem_hand_vector hand_id_set_; }; struct rank_vector : std::vector<rank_id>{ template<class... Args> rank_vector(Args&&... args):std::vector<rank_id>{std::forward<Args>(args)...}{} friend std::ostream& operator<<(std::ostream& ostr, rank_vector const& self); }; struct holdem_class_range : std::vector<ps::holdem_class_id>{ template< class... Args, class = std::enable_if_t< ! std::is_constructible<std::string, Args...>::value > > holdem_class_range(Args&&... args) : std::vector<ps::holdem_id>{std::forward<Args>(args)...} {} holdem_class_range(std::string const& item); friend std::ostream& operator<<(std::ostream& ostr, holdem_class_range const& self); void parse(std::string const& item); }; struct holdem_class_vector : std::vector<ps::holdem_class_id>{ template<class... Args> holdem_class_vector(Args&&... args) : std::vector<ps::holdem_class_id>{std::forward<Args>(args)...} {} // parse("AA,KK"); static holdem_class_vector parse(std::string const& s); friend std::ostream& operator<<(std::ostream& ostr, holdem_class_vector const& self); holdem_class_decl const& decl_at(size_t i)const; std::vector< holdem_hand_vector > get_hand_vectors()const; std::string to_string()const{ std::stringstream sstr; sstr << *this; return sstr.str(); } template< class... Args, class = std::enable_if_t< ! std::is_constructible<std::string, Args...>::value > > void push_back(Args&&... args){ this->std::vector<ps::holdem_class_id>::push_back(std::forward<Args...>(args)...); } void push_back(std::string const& item){ this->push_back( holdem_class_decl::parse(item).id() ); } template<class Archive> void serialize(Archive& ar, unsigned int){ ar & (*reinterpret_cast<std::vector<ps::holdem_class_id>*>(this)); } std::tuple< std::vector<int>, holdem_class_vector > to_standard_form()const; std::vector< std::tuple< std::vector<int>, holdem_hand_vector > > to_standard_form_hands()const; bool is_standard_form()const; auto prob()const{ BOOST_ASSERT(size() == 2 ); return holdem_class_decl::prob(at(0), at(1)); } }; struct holdem_class_iterator : basic_index_iterator< holdem_class_id, ordered_policy, holdem_class_vector > { using impl_t = basic_index_iterator< holdem_class_id, ordered_policy, holdem_class_vector > ; holdem_class_iterator():impl_t{}{} holdem_class_iterator(size_t n): impl_t(n, holdem_class_decl::max_id) {} }; struct holdem_class_perm_iterator : basic_index_iterator< holdem_class_id, range_policy, holdem_class_vector > { using impl_t = basic_index_iterator< holdem_class_id, range_policy, holdem_class_vector > ; holdem_class_perm_iterator():impl_t{}{} holdem_class_perm_iterator(size_t n): impl_t(n, holdem_class_decl::max_id) {} }; typedef std::tuple< std::vector<int>, holdem_class_vector> standard_form_result; inline std::ostream& operator<<(std::ostream& ostr, standard_form_result const& self){ return ostr << detail::to_string(std::get<0>(self)) << " x " << std::get<1>(self); } typedef std::tuple< std::vector<int>, holdem_hand_vector> standard_form_hands_result; inline std::ostream& operator<<(std::ostream& ostr, standard_form_hands_result const& self){ return ostr << detail::to_string(std::get<0>(self)) << " x " << std::get<1>(self); } struct holdem_class_range_vector : std::vector<holdem_class_range>{ template<class... Args> holdem_class_range_vector(Args&&... args) : std::vector<holdem_class_range>{std::forward<Args>(args)...} {} friend std::ostream& operator<<(std::ostream& ostr, holdem_class_range_vector const& self); void push_back(std::string const& s); // Return this expand, ie // {{AA,KK},{22}} => {AA,22}, {KK,22} std::vector<holdem_class_vector> get_cross_product()const; // Returns this as a vector of // (matrix, standard-form-hand-vector) std::vector< std::tuple< std::vector<int>, holdem_hand_vector > > to_standard_form()const; // Returns this as a vector of // (matrix, standard-form-class-vector) std::vector< std::tuple< std::vector<int>, holdem_class_vector > > to_class_standard_form()const; }; struct equity_view : std::vector<double>{ equity_view(matrix_t const& breakdown); unsigned long long sigma()const{ return sigma_; } bool valid()const; private: unsigned long long sigma_; }; std::ostream& operator<<(std::ostream& ostr, card_vector const& self){ return ostr << detail::to_string(self, [](auto id){ return card_decl::get(id).to_string(); }); } enum hand_rank_category{ HR_RoyalFlush, HR_StraightFlush, HR_Quads, HR_FullHouse, HR_Flush, HR_Straight, HR_Trips, HR_TwoPair, HR_OnePair, HR_HighCard, HR_NotAHandRank, }; inline std::ostream& operator<<(std::ostream& ostr, hand_rank_category cat){ switch(cat){ case HR_RoyalFlush: return ostr << "RoyalFlush"; case HR_StraightFlush: return ostr << "StraightFlush"; case HR_Quads: return ostr << "Quads"; case HR_FullHouse: return ostr << "FullHouse"; case HR_Flush: return ostr << "Flush"; case HR_Straight: return ostr << "Straight"; case HR_Trips: return ostr << "Trips"; case HR_TwoPair: return ostr << "TwoPair"; case HR_OnePair: return ostr << "OnePair"; case HR_HighCard: return ostr << "HighCard"; case HR_NotAHandRank: return ostr << "NotAHandRank"; default: return ostr << "(invalid)"; } } } // end namespace cards #include "ps/base/decl.h" #endif // PS_CORE_CARDS_H
41.470693
127
0.484624
[ "vector" ]
08cfe27773c5a9621deec6d35b3fda46c905b9a2
1,737
h
C
core/printer.h
nandor/genm-opt
b3347d508fff707837d1dc8232487ebfe157fe2a
[ "MIT" ]
13
2020-06-25T18:26:54.000Z
2021-02-16T03:14:38.000Z
core/printer.h
nandor/genm-opt
b3347d508fff707837d1dc8232487ebfe157fe2a
[ "MIT" ]
3
2020-07-01T01:39:47.000Z
2022-01-24T23:47:12.000Z
core/printer.h
nandor/genm-opt
b3347d508fff707837d1dc8232487ebfe157fe2a
[ "MIT" ]
2
2021-03-11T05:08:09.000Z
2021-07-17T23:36:17.000Z
// This file if part of the llir-opt project. // Licensing information can be found in the LICENSE file. // (C) 2018 Nandor Licker. All rights reserved. #pragma once #include <ostream> #include <unordered_map> #include <llvm/Support/raw_ostream.h> #include "core/cond.h" #include "core/calling_conv.h" #include "core/visibility.h" #include "core/inst.h" class Atom; class Block; class Data; class Func; class Prog; class Object; /** * Prints a program. */ class Printer { public: /// Initialises the printer. Printer(llvm::raw_ostream &os) : os_(os) {} /// Prints a whole program. virtual void Print(const Prog &prog); /// Prints a data segment. virtual void Print(const Data &data); /// Prints an object. virtual void Print(const Object &object); /// Prints an atom. virtual void Print(const Atom &atom); /// Prints a function. virtual void Print(const Func &func); /// Prints a block. virtual void Print(const Block &block); /// Prints an instruction. virtual void Print(const Inst &inst); /// Prints an expression. virtual void Print(const Expr &expr); /// Prints a value. virtual void Print(ConstRef<Value> val); /// Print a quoted string. virtual void Print(const std::string_view str); protected: /// Hook to print additional information for functions. virtual void PrintFuncHeader(const Func &func) {} /// Hook to print additional information for instructions. virtual void PrintInstHeader(const Inst &inst) {} private: /// Auto-generated printer implementation. void PrintImpl(const Inst &inst); protected: /// Output stream. llvm::raw_ostream &os_; private: /// Instruction to identifier map. std::unordered_map<ConstRef<Inst>, unsigned> insts_; };
23.794521
60
0.706966
[ "object" ]
08d1659c65cf6cb352916025b2582a93a231c646
1,285
h
C
PrivateFrameworks/BaseBoard.framework/BSActionResponse.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
PrivateFrameworks/BaseBoard.framework/BSActionResponse.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
PrivateFrameworks/BaseBoard.framework/BSActionResponse.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/BaseBoard.framework/BaseBoard */ @interface BSActionResponse : NSObject <BSDescriptionProviding, BSSettingDescriptionProvider, BSXPCCoding, NSCopying> { NSError * _error; BSSettings * _info; } @property (readonly, copy) NSString *debugDescription; @property (readonly, copy) NSString *description; @property (nonatomic, readonly, retain) NSError *error; @property (readonly) unsigned long long hash; @property (nonatomic, readonly, copy) BSSettings *info; @property (readonly) Class superclass; + (id)response; + (id)responseForError:(id)arg1; + (id)responseWithInfo:(id)arg1; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (void)dealloc; - (id)description; - (id)descriptionBuilderWithMultilinePrefix:(id)arg1; - (id)descriptionWithMultilinePrefix:(id)arg1; - (void)encodeWithXPCDictionary:(id)arg1; - (id)error; - (unsigned long long)hash; - (id)info; - (id)init; - (id)initWithInfo:(id)arg1 error:(id)arg2; - (id)initWithXPCDictionary:(id)arg1; - (bool)isEqual:(id)arg1; - (id)keyDescriptionForSetting:(unsigned long long)arg1; - (id)succinctDescription; - (id)succinctDescriptionBuilder; - (id)valueDescriptionForFlag:(long long)arg1 object:(id)arg2 ofSetting:(unsigned long long)arg3; @end
32.125
119
0.758755
[ "object" ]
08d9c82758f06c6ea83f8af16f51a1a07a7079c0
6,039
h
C
src/util/queue.h
bailuding/centiman
213eab0bd391822cbc9a01644979f8409440c376
[ "Apache-2.0" ]
4
2016-07-14T18:11:39.000Z
2021-04-14T01:27:38.000Z
src/util/queue.h
bailuding/centiman
213eab0bd391822cbc9a01644979f8409440c376
[ "Apache-2.0" ]
null
null
null
src/util/queue.h
bailuding/centiman
213eab0bd391822cbc9a01644979f8409440c376
[ "Apache-2.0" ]
1
2015-11-23T17:23:43.000Z
2015-11-23T17:23:43.000Z
#ifndef __UTIL_QUEUE_H__ #define __UTIL_QUEUE_H__ #include <assert.h> #include <pthread.h> #include <stdlib.h> #include <util/logger.h> /** * A thread-safe queue used when the processing is non-trivial. * Each element of the queue is a pointer to an object. * The Type class needs to provide Type() and reset(). */ template <class Type> class Queue { public: Queue(int size); ~Queue(); void publish(const char * msg); Type * getReadSlot(); int getReadSlots(Type **, int size); void putReadSlot(Type *); void putReadSlots(Type **, int size); Type * getWriteSlot(); int getWriteSlots(Type **, int size); void putWriteSlot(Type *); void putWriteSlots(Type **, int size); int getReadWaitCnt(); int getWriteWaitCnt(); bool isEmpty(); int getSize(); int getElmtCnt(); int mSize; private: Queue() {} Queue(const Queue& q) {} Type ** mPtrs; int mElmtCnt; int mSlotCnt; int mReadGetSlot; int mReadPutSlot; int mWriteGetSlot; int mWritePutSlot; int mWaitCnt; pthread_mutex_t mLock; pthread_cond_t mReadCond; pthread_cond_t mWriteCond; void inc(int &val); }; template <class Type> Queue<Type>::Queue(int size) { mSize = size; mPtrs = new Type *[mSize]; for (int i = 0; i < mSize; ++i) { mPtrs[i] = new Type(); } mElmtCnt = 0; mSlotCnt = size; mReadGetSlot = 0; mReadPutSlot = 0; mWriteGetSlot = 0; mWritePutSlot = 0; mWaitCnt = 0; pthread_mutex_init(&mLock, NULL); pthread_cond_init(&mReadCond, NULL); pthread_cond_init(&mWriteCond, NULL); } template <class Type> Queue<Type>::~Queue() { for (int i = 0; i < mSize; ++i) { delete mPtrs[i]; } delete[] mPtrs; pthread_mutex_destroy(&mLock); pthread_cond_destroy(&mReadCond); pthread_cond_destroy(&mWriteCond); } template <class Type> void Queue<Type>::publish(const char * msg) { if (mElmtCnt > 0) { Logger::out(0, "Queue[%s]: %d / %d , read wait %d times\n", msg, mElmtCnt, mSize, mWaitCnt); } mWaitCnt = 0; } template <class Type> Type * Queue<Type>::getReadSlot() { pthread_mutex_lock(&mLock); while (mElmtCnt == 0) { ++mWaitCnt; pthread_cond_wait(&mReadCond, &mLock); } Type * tmp = mPtrs[mReadGetSlot]; --mElmtCnt; mPtrs[mReadGetSlot] = NULL; inc(mReadGetSlot); pthread_mutex_unlock(&mLock); return tmp; } /* * Get a batch of read slots from the queue. * If there are not enough slots available, get as much as possible. * It will be blocked if no slot is available. */ template <class Type> inline int Queue<Type>::getReadSlots(Type ** elmts, int size) { pthread_mutex_lock(&mLock); while (mElmtCnt == 0) { pthread_cond_wait(&mReadCond, &mLock); } int cnt = mElmtCnt < size ? mElmtCnt: size; for (int i = 0; i < cnt; ++i) { elmts[i] = mPtrs[mReadGetSlot]; mPtrs[mReadGetSlot] = NULL; inc(mReadGetSlot); } mElmtCnt -= cnt; pthread_mutex_unlock(&mLock); return cnt; } template <class Type> inline void Queue<Type>::putReadSlot(Type * ptr) { pthread_mutex_lock(&mLock); mPtrs[mReadPutSlot] = ptr; inc(mReadPutSlot); ++mSlotCnt; pthread_cond_signal(&mWriteCond); pthread_mutex_unlock(&mLock); } /* * Put a batch of read slots to the queue. * Assume the queue has enough available slots. */ template <class Type> inline void Queue<Type>::putReadSlots(Type ** elmts, int size) { pthread_mutex_lock(&mLock); assert(size + mSlotCnt <= mSize); for (int i = 0; i < size; ++i) { mPtrs[mReadPutSlot] = elmts[i]; inc(mReadPutSlot); } mSlotCnt += size; pthread_cond_signal(&mWriteCond); pthread_mutex_unlock(&mLock); } template <class Type> inline Type * Queue<Type>::getWriteSlot() { pthread_mutex_lock(&mLock); while (mSlotCnt == 0) { pthread_cond_wait(&mWriteCond, &mLock); } Type * tmp = mPtrs[mWriteGetSlot]; tmp->reset(); --mSlotCnt; mPtrs[mWriteGetSlot] = NULL; inc(mWriteGetSlot); pthread_mutex_unlock(&mLock); return tmp; } template <class Type> inline int Queue<Type>::getWriteSlots(Type ** elmts, int size) { pthread_mutex_lock(&mLock); while (mSlotCnt == 0) { pthread_cond_wait(&mWriteCond, &mLock); } int cnt = mSlotCnt < size ? mSlotCnt: size; for (int i = 0; i < cnt; ++i) { elmts[i] = mPtrs[mWriteGetSlot]; elmts[i]->reset(); mPtrs[mWriteGetSlot] = NULL; inc(mWriteGetSlot); } mSlotCnt -= cnt; pthread_mutex_unlock(&mLock); return cnt; } template <class Type> inline void Queue<Type>::putWriteSlot(Type * ptr) { pthread_mutex_lock(&mLock); mPtrs[mWritePutSlot] = ptr; inc(mWritePutSlot); ++mElmtCnt; pthread_cond_signal(&mReadCond); pthread_mutex_unlock(&mLock); } template <class Type> inline void Queue<Type>::putWriteSlots(Type ** elmts, int size) { pthread_mutex_lock(&mLock); assert(size + mElmtCnt <= mSize); for (int i = 0; i < size; ++i) { mPtrs[mWritePutSlot] = elmts[i]; inc(mWritePutSlot); } mElmtCnt += size; pthread_cond_signal(&mReadCond); pthread_mutex_unlock(&mLock); } template <class Type> inline void Queue<Type>::inc(int &val) { if (++val == mSize) val = 0; } template <class Type> int Queue<Type>::getReadWaitCnt() { return 0; // return mReadWaitCnt; } template <class Type> int Queue<Type>::getWriteWaitCnt() { return 0; // return mWriteWaitCnt; } template <class Type> inline bool Queue<Type>::isEmpty() { return mElmtCnt == 0; } template <class Type> inline int Queue<Type>::getSize() { return mSize; } template <class Type> inline int Queue<Type>::getElmtCnt() { return mElmtCnt; } #endif // __UTIL_QUEUE_H__
21.115385
100
0.61583
[ "object" ]
08d9f35cd7f3bee0670e9f0a5777878d16a75da9
8,965
h
C
lib/xspublic/xstypes/xsfile.h
oriondream/xsens_ros_mti_driver
14dd9a89dce22fa9a20732754f521a4d32726c7b
[ "BSD-3-Clause" ]
13
2019-01-04T13:52:30.000Z
2021-12-23T00:52:31.000Z
lib/xspublic/xstypes/xsfile.h
oriondream/xsens_ros_mti_driver
14dd9a89dce22fa9a20732754f521a4d32726c7b
[ "BSD-3-Clause" ]
1
2019-11-03T13:04:59.000Z
2019-11-03T13:04:59.000Z
lib/xspublic/xstypes/xsfile.h
oriondream/xsens_ros_mti_driver
14dd9a89dce22fa9a20732754f521a4d32726c7b
[ "BSD-3-Clause" ]
15
2018-08-02T02:35:00.000Z
2021-12-15T05:06:45.000Z
// Copyright (c) 2003-2019 Xsens Technologies B.V. or subsidiaries worldwide. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions, and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions, and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the names of the copyright holders nor the names of their 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 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 HOLDERS 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.THE LAWS OF THE NETHERLANDS // SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES // OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE // ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES. // #ifndef XSFILE_H #define XSFILE_H #include "xstypesconfig.h" #include "pstdint.h" #include <stdio.h> #include "xsresultvalue.h" #include "xsfilepos.h" #include "xsstring.h" #ifdef _MSC_VER # define XS_MAX_FILENAME_LENGTH 512 #else # define XS_MAX_FILENAME_LENGTH PATH_MAX #endif #ifdef __cplusplus extern "C" { #endif #ifndef __cplusplus #define XSFILE_INITIALIZER { 0 } #endif struct XsFile; XSTYPES_DLL_API void XsFile_destruct(struct XsFile* thisPtr); XSTYPES_DLL_API XsResultValue XsFile_create(struct XsFile *thisPtr, const struct XsString* filename, int writeOnly); XSTYPES_DLL_API XsResultValue XsFile_createText(struct XsFile *thisPtr, const struct XsString* filename, int writeOnly); XSTYPES_DLL_API XsResultValue XsFile_open(struct XsFile *thisPtr, const struct XsString* filename, int readOnly); XSTYPES_DLL_API XsResultValue XsFile_openText(struct XsFile *thisPtr, const struct XsString* filename, int readOnly); XSTYPES_DLL_API XsResultValue XsFile_reopen(struct XsFile *thisPtr, const struct XsString* filename, const struct XsString* mode); XSTYPES_DLL_API int XsFile_isOpen(const struct XsFile *thisPtr); XSTYPES_DLL_API XsResultValue XsFile_close(struct XsFile *thisPtr); XSTYPES_DLL_API int XsFile_exists(const struct XsString* filename); XSTYPES_DLL_API XsResultValue XsFile_flush(struct XsFile *thisPtr); XSTYPES_DLL_API XsResultValue XsFile_truncate(struct XsFile *thisPtr, XsFilePos fileSize); XSTYPES_DLL_API XsResultValue XsFile_resize(struct XsFile *thisPtr, XsFilePos fileSize); XSTYPES_DLL_API XsResultValue XsFile_erase(const struct XsString* filename); XSTYPES_DLL_API XsFilePos XsFile_read(struct XsFile *thisPtr, void *destination, XsFilePos size, XsFilePos count); XSTYPES_DLL_API XsFilePos XsFile_write(struct XsFile *thisPtr, const void *source, XsFilePos size, XsFilePos count); XSTYPES_DLL_API int XsFile_getc(struct XsFile *thisPtr); XSTYPES_DLL_API XsResultValue XsFile_putc(struct XsFile *thisPtr, int character); XSTYPES_DLL_API char* XsFile_gets(struct XsFile *thisPtr, char *str, int num); XSTYPES_DLL_API XsResultValue XsFile_puts(struct XsFile *thisPtr, const char *str); XSTYPES_DLL_API XsResultValue XsFile_seek(struct XsFile* thisPtr, XsFilePos offset); XSTYPES_DLL_API XsResultValue XsFile_seek_r(struct XsFile* thisPtr, XsFilePos offset); XSTYPES_DLL_API XsFilePos XsFile_tell(struct XsFile *thisPtr); XSTYPES_DLL_API int XsFile_eof(struct XsFile *thisPtr); XSTYPES_DLL_API XsResultValue XsFile_error(struct XsFile *thisPtr); XSTYPES_DLL_API XsResultValue XsFile_fullPath(const struct XsString* filename, struct XsString* fullPath); XSTYPES_DLL_API XsResultValue XsFile_getline(struct XsFile *thisPtr, struct XsString *line); XSTYPES_DLL_API FILE* XsFile_handle(struct XsFile *thisPtr); #ifdef __cplusplus } // extern "C" #endif struct XsFile { #ifdef __cplusplus /*! \brief Default constructor, creates an empty file object */ explicit inline XsFile() : m_handle(NULL) { // Silence -Wunused-private-field // This field is used in the C back-end, but // some compilers may not notice this (void)m_handle; } /*! \brief \copybrief XsFile_destruct */ inline ~XsFile() { XsFile_destruct(this); } /*! \brief \copybrief XsFile_create */ inline XsResultValue create(const XsString &filename, bool writeOnly) { return XsFile_create(this, &filename, writeOnly ? 1 : 0); } /*! \brief \copybrief XsFile_createText */ inline XsResultValue createText(const XsString &filename, bool writeOnly) { return XsFile_createText(this, &filename, writeOnly ? 1 : 0); } /*! \brief \copybrief XsFile_open */ inline XsResultValue open(const XsString &fileName, bool readOnly) { return XsFile_open(this, &fileName, readOnly ? 1 : 0); } /*! \brief \copybrief XsFile_openText */ inline XsResultValue openText(const XsString &fileName, bool readOnly) { return XsFile_openText(this, &fileName, readOnly ? 1 : 0); } /*! \brief \copybrief XsFile_openText */ inline XsResultValue reopen(const XsString &fileName, const XsString &mode) { return XsFile_reopen(this, &fileName, &mode); } /*! \brief \copybrief XsFile_isOpen */ inline bool isOpen() const { return (XsFile_isOpen(this) == 0); } /*! \brief \copybrief XsFile_exists */ static inline bool exists(const XsString &fileName) { return (XsFile_exists(&fileName) == 0); } /*! \brief \copybrief XsFile_close */ inline XsResultValue close() { return XsFile_close(this); } /*! \brief \copybrief XsFile_flush */ inline XsResultValue flush() { return XsFile_flush(this); } /*! \brief \copybrief XsFile_truncate */ inline XsResultValue truncate(XsFilePos fileSize) { return XsFile_truncate(this, fileSize); } /*! \brief \copybrief XsFile_resize */ inline XsResultValue resize(XsFilePos fileSize) { return XsFile_resize(this, fileSize); } /*! \brief \copybrief XsFile_erase */ static XsResultValue erase(const XsString& filename) { return XsFile_erase(&filename); } /*! \brief \copybrief XsFile_read */ inline XsFilePos read(void *destination, XsFilePos size, XsFilePos count) { return XsFile_read(this, destination, size, count); } /*! \brief \copybrief XsFile_write */ inline XsFilePos write(const void *source, XsFilePos size, XsFilePos count) { return XsFile_write(this, source, size, count); } /*! \brief \copybrief XsFile_getc */ inline int getc() { return XsFile_getc(this); } /*! \brief \copybrief XsFile_putc */ inline XsResultValue putc(int character) { return XsFile_putc(this, character); } /*! \brief \copybrief XsFile_gets */ inline char* gets(char *destination, int maxCount) { return XsFile_gets(this, destination, maxCount); } /*! \brief \copybrief XsFile_puts */ inline XsResultValue puts(const char *source) { return XsFile_puts(this, source); } /*! \brief \copybrief XsFile_seek */ inline XsResultValue seek(XsFilePos offset) { return XsFile_seek(this, offset); } /*! \brief \copybrief XsFile_seek_r */ inline XsResultValue seek_r(XsFilePos offset) { return XsFile_seek_r(this, offset); } /*! \brief \copybrief XsFile_tell */ inline XsFilePos tell() { return XsFile_tell(this); } /*! \brief \copybrief XsFile_eof */ inline bool eof() { return (0!=XsFile_eof(this)); } /*! \brief \copybrief XsFile_error */ inline XsResultValue error() { return XsFile_error(this); } /*! \brief \copybrief XsFile_fullPath */ static XsResultValue fullPath(const XsString &filename, XsString &fullPath) { return XsFile_fullPath(&filename, &fullPath); } /*! \brief \copybrief XsFile_getline */ inline XsResultValue getline(XsString& line) { return XsFile_getline(this, &line); } /*! \brief \copybrief XsFile_getline */ inline XsResultValue getline(std::string& line) { XsString tmp; XsResultValue rv = XsFile_getline(this, &tmp); if (rv == XRV_OK) line = tmp.toStdString(); return rv; } /*! \brief \copybrief XsFile_handle */ inline FILE* handle() { return XsFile_handle(this); } private: #endif FILE* m_handle; }; typedef struct XsFile XsFile; #endif
31.020761
130
0.757167
[ "object" ]
08dcb0a9283778f76934f7c2180f22d70ef8eaf0
1,954
h
C
common/heap/monotone/base/rolling_bucket_queue.h
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
common/heap/monotone/base/rolling_bucket_queue.h
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
common/heap/monotone/base/rolling_bucket_queue.h
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
#pragma once #include "common/base.h" #include <stack> #include <vector> namespace heap { namespace monotone { namespace base { // P - max priority, W - window // Memory -- O(N + W) // Add -- O(1) // Top -- O(1 + P / N) amortized, O(W) worst case // Pop -- O(1 + P / N) amortized, O(W) worst case // current priority <= new priority < current priority + window template <class TTValue> class RollingBucketQueue { public: using TValue = TTValue; using TSelf = RollingBucketQueue<TTValue>; class TData { public: unsigned priority; TValue value; }; protected: std::vector<std::stack<TValue>> queue; unsigned top_priority = 0, top_priority_adj = 0; unsigned size = 0; unsigned window; public: RollingBucketQueue() {} explicit RollingBucketQueue(unsigned _window) { SetWindow(_window); } void SetWindow(unsigned _window) { window = _window; queue.resize(window); } bool Empty() const { return size == 0; } unsigned Size() const { return size; } void Add(unsigned p, const TValue& value) { queue[p % window].push(value); ++size; } unsigned TopPriority() { ShiftPriority(); return top_priority; } const TValue& TopValue() { ShiftPriority(); return queue[top_priority_adj].top(); } TData Top() { ShiftPriority(); return {top_priority, queue[top_priority_adj].top()}; } void Pop() { ShiftPriority(); queue[top_priority_adj].pop(); --size; } unsigned ExtractPriority() { Pop(); return top_priority; } TValue ExtractValue() { TValue v = TopValue(); Pop(); return v; } TData Extract() { TData t = Top(); Pop(); return t; } protected: void ShiftPriority() { assert(!Empty()); for (; queue[top_priority_adj].size() == 0; ++top_priority) top_priority_adj = (top_priority_adj + 1) % window; } }; } // namespace base } // namespace monotone } // namespace heap
19.54
71
0.627431
[ "vector" ]
08df21f3c34888287cd40e9a2e7811bfb19458dc
21,558
c
C
Mac/Modules/htmlrender/HtmlRendermodule.c
deadsnakes/python2.3
0b4a6871ca57123c10aa48cc2a5d2b7c0ee3c849
[ "PSF-2.0" ]
null
null
null
Mac/Modules/htmlrender/HtmlRendermodule.c
deadsnakes/python2.3
0b4a6871ca57123c10aa48cc2a5d2b7c0ee3c849
[ "PSF-2.0" ]
null
null
null
Mac/Modules/htmlrender/HtmlRendermodule.c
deadsnakes/python2.3
0b4a6871ca57123c10aa48cc2a5d2b7c0ee3c849
[ "PSF-2.0" ]
null
null
null
/* ======================= Module HtmlRender ======================== */ #include "Python.h" #define SystemSevenOrLater 1 #include "macglue.h" #include <Memory.h> #include <Dialogs.h> #include <Menus.h> #include <Controls.h> extern PyObject *ResObj_New(Handle); extern int ResObj_Convert(PyObject *, Handle *); extern PyObject *OptResObj_New(Handle); extern int OptResObj_Convert(PyObject *, Handle *); extern PyObject *WinObj_New(WindowPtr); extern int WinObj_Convert(PyObject *, WindowPtr *); extern PyTypeObject Window_Type; #define WinObj_Check(x) ((x)->ob_type == &Window_Type) extern PyObject *DlgObj_New(DialogPtr); extern int DlgObj_Convert(PyObject *, DialogPtr *); extern PyTypeObject Dialog_Type; #define DlgObj_Check(x) ((x)->ob_type == &Dialog_Type) extern PyObject *MenuObj_New(MenuHandle); extern int MenuObj_Convert(PyObject *, MenuHandle *); extern PyObject *CtlObj_New(ControlHandle); extern int CtlObj_Convert(PyObject *, ControlHandle *); extern PyObject *GrafObj_New(GrafPtr); extern int GrafObj_Convert(PyObject *, GrafPtr *); extern PyObject *BMObj_New(BitMapPtr); extern int BMObj_Convert(PyObject *, BitMapPtr *); extern PyObject *WinObj_WhichWindow(WindowPtr); #include <HTMLRendering.h> static PyObject *Html_Error; /* --------------------- Object type HtmlObject --------------------- */ PyTypeObject HtmlObject_Type; #define HtmlObj_Check(x) ((x)->ob_type == &HtmlObject_Type) typedef struct HtmlObjectObject { PyObject_HEAD HRReference ob_itself; } HtmlObjectObject; PyObject *HtmlObj_New(itself) HRReference itself; { HtmlObjectObject *it; it = PyObject_NEW(HtmlObjectObject, &HtmlObject_Type); if (it == NULL) return NULL; it->ob_itself = itself; return (PyObject *)it; } HtmlObj_Convert(v, p_itself) PyObject *v; HRReference *p_itself; { if (!HtmlObj_Check(v)) { PyErr_SetString(PyExc_TypeError, "HtmlObject required"); return 0; } *p_itself = ((HtmlObjectObject *)v)->ob_itself; return 1; } static void HtmlObj_dealloc(self) HtmlObjectObject *self; { /* Cleanup of self->ob_itself goes here */ PyObject_DEL(self); } static PyObject *HtmlObj_HRDisposeReference(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = HRDisposeReference(_self->ob_itself); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRSetGrafPtr(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; GrafPtr grafPtr; if (!PyArg_ParseTuple(_args, "O&", GrafObj_Convert, &grafPtr)) return NULL; _err = HRSetGrafPtr(_self->ob_itself, grafPtr); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRActivate(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = HRActivate(_self->ob_itself); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRDeactivate(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = HRDeactivate(_self->ob_itself); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRDraw(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; RgnHandle updateRgnH; if (!PyArg_ParseTuple(_args, "O&", ResObj_Convert, &updateRgnH)) return NULL; _err = HRDraw(_self->ob_itself, updateRgnH); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRSetRenderingRect(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; Rect renderingRect; if (!PyArg_ParseTuple(_args, "O&", PyMac_GetRect, &renderingRect)) return NULL; _err = HRSetRenderingRect(_self->ob_itself, &renderingRect); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRGetRenderedImageSize(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; Point renderingSize; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = HRGetRenderedImageSize(_self->ob_itself, &renderingSize); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", PyMac_BuildPoint, renderingSize); return _res; } static PyObject *HtmlObj_HRScrollToLocation(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; Point location; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = HRScrollToLocation(_self->ob_itself, &location); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", PyMac_BuildPoint, location); return _res; } static PyObject *HtmlObj_HRForceQuickdraw(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; Boolean forceQuickdraw; if (!PyArg_ParseTuple(_args, "b", &forceQuickdraw)) return NULL; _err = HRForceQuickdraw(_self->ob_itself, forceQuickdraw); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRSetScrollbarState(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; HRScrollbarState hScrollbarState; HRScrollbarState vScrollbarState; if (!PyArg_ParseTuple(_args, "hh", &hScrollbarState, &vScrollbarState)) return NULL; _err = HRSetScrollbarState(_self->ob_itself, hScrollbarState, vScrollbarState); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRSetDrawBorder(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; Boolean drawBorder; if (!PyArg_ParseTuple(_args, "b", &drawBorder)) return NULL; _err = HRSetDrawBorder(_self->ob_itself, drawBorder); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRSetGrowboxCutout(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; Boolean allowCutout; if (!PyArg_ParseTuple(_args, "b", &allowCutout)) return NULL; _err = HRSetGrowboxCutout(_self->ob_itself, allowCutout); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRGoToFile(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; FSSpec fsspec; Boolean addToHistory; Boolean forceRefresh; if (!PyArg_ParseTuple(_args, "O&bb", PyMac_GetFSSpec, &fsspec, &addToHistory, &forceRefresh)) return NULL; _err = HRGoToFile(_self->ob_itself, &fsspec, addToHistory, forceRefresh); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRGoToURL(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; char * url; Boolean addToHistory; Boolean forceRefresh; if (!PyArg_ParseTuple(_args, "sbb", &url, &addToHistory, &forceRefresh)) return NULL; _err = HRGoToURL(_self->ob_itself, url, addToHistory, forceRefresh); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRGoToAnchor(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; char * anchorName; if (!PyArg_ParseTuple(_args, "s", &anchorName)) return NULL; _err = HRGoToAnchor(_self->ob_itself, anchorName); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRGoToPtr(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; char *buffer__in__; long buffer__len__; int buffer__in_len__; Boolean addToHistory; Boolean forceRefresh; if (!PyArg_ParseTuple(_args, "s#bb", &buffer__in__, &buffer__in_len__, &addToHistory, &forceRefresh)) return NULL; buffer__len__ = buffer__in_len__; _err = HRGoToPtr(_self->ob_itself, buffer__in__, buffer__len__, addToHistory, forceRefresh); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; buffer__error__: ; return _res; } static PyObject *HtmlObj_HRGetRootURL(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; Handle rootURLH; if (!PyArg_ParseTuple(_args, "O&", ResObj_Convert, &rootURLH)) return NULL; _err = HRGetRootURL(_self->ob_itself, rootURLH); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRGetBaseURL(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; Handle baseURLH; if (!PyArg_ParseTuple(_args, "O&", ResObj_Convert, &baseURLH)) return NULL; _err = HRGetBaseURL(_self->ob_itself, baseURLH); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRGetHTMLURL(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; Handle HTMLURLH; if (!PyArg_ParseTuple(_args, "O&", ResObj_Convert, &HTMLURLH)) return NULL; _err = HRGetHTMLURL(_self->ob_itself, HTMLURLH); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRGetTitle(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; StringPtr title; if (!PyArg_ParseTuple(_args, "s", &title)) return NULL; _err = HRGetTitle(_self->ob_itself, title); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRGetHTMLFile(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; FSSpec fsspec; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = HRGetHTMLFile(_self->ob_itself, &fsspec); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", PyMac_BuildFSSpec, fsspec); return _res; } static PyObject *HtmlObj_HRUnregisterWasURLVisitedUPP(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; if (!PyArg_ParseTuple(_args, "")) return NULL; HRUnregisterWasURLVisitedUPP(_self->ob_itself); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRUnregisterNewURLUPP(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; if (!PyArg_ParseTuple(_args, "")) return NULL; HRUnregisterNewURLUPP(_self->ob_itself); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *HtmlObj_HRUnregisterURLToFSSpecUPP(_self, _args) HtmlObjectObject *_self; PyObject *_args; { PyObject *_res = NULL; if (!PyArg_ParseTuple(_args, "")) return NULL; HRUnregisterURLToFSSpecUPP(_self->ob_itself); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyMethodDef HtmlObj_methods[] = { {"HRDisposeReference", (PyCFunction)HtmlObj_HRDisposeReference, 1, "() -> None"}, {"HRSetGrafPtr", (PyCFunction)HtmlObj_HRSetGrafPtr, 1, "(GrafPtr grafPtr) -> None"}, {"HRActivate", (PyCFunction)HtmlObj_HRActivate, 1, "() -> None"}, {"HRDeactivate", (PyCFunction)HtmlObj_HRDeactivate, 1, "() -> None"}, {"HRDraw", (PyCFunction)HtmlObj_HRDraw, 1, "(RgnHandle updateRgnH) -> None"}, {"HRSetRenderingRect", (PyCFunction)HtmlObj_HRSetRenderingRect, 1, "(Rect renderingRect) -> None"}, {"HRGetRenderedImageSize", (PyCFunction)HtmlObj_HRGetRenderedImageSize, 1, "() -> (Point renderingSize)"}, {"HRScrollToLocation", (PyCFunction)HtmlObj_HRScrollToLocation, 1, "() -> (Point location)"}, {"HRForceQuickdraw", (PyCFunction)HtmlObj_HRForceQuickdraw, 1, "(Boolean forceQuickdraw) -> None"}, {"HRSetScrollbarState", (PyCFunction)HtmlObj_HRSetScrollbarState, 1, "(HRScrollbarState hScrollbarState, HRScrollbarState vScrollbarState) -> None"}, {"HRSetDrawBorder", (PyCFunction)HtmlObj_HRSetDrawBorder, 1, "(Boolean drawBorder) -> None"}, {"HRSetGrowboxCutout", (PyCFunction)HtmlObj_HRSetGrowboxCutout, 1, "(Boolean allowCutout) -> None"}, {"HRGoToFile", (PyCFunction)HtmlObj_HRGoToFile, 1, "(FSSpec fsspec, Boolean addToHistory, Boolean forceRefresh) -> None"}, {"HRGoToURL", (PyCFunction)HtmlObj_HRGoToURL, 1, "(char * url, Boolean addToHistory, Boolean forceRefresh) -> None"}, {"HRGoToAnchor", (PyCFunction)HtmlObj_HRGoToAnchor, 1, "(char * anchorName) -> None"}, {"HRGoToPtr", (PyCFunction)HtmlObj_HRGoToPtr, 1, "(Buffer buffer, Boolean addToHistory, Boolean forceRefresh) -> None"}, {"HRGetRootURL", (PyCFunction)HtmlObj_HRGetRootURL, 1, "(Handle rootURLH) -> None"}, {"HRGetBaseURL", (PyCFunction)HtmlObj_HRGetBaseURL, 1, "(Handle baseURLH) -> None"}, {"HRGetHTMLURL", (PyCFunction)HtmlObj_HRGetHTMLURL, 1, "(Handle HTMLURLH) -> None"}, {"HRGetTitle", (PyCFunction)HtmlObj_HRGetTitle, 1, "(StringPtr title) -> None"}, {"HRGetHTMLFile", (PyCFunction)HtmlObj_HRGetHTMLFile, 1, "() -> (FSSpec fsspec)"}, {"HRUnregisterWasURLVisitedUPP", (PyCFunction)HtmlObj_HRUnregisterWasURLVisitedUPP, 1, "() -> None"}, {"HRUnregisterNewURLUPP", (PyCFunction)HtmlObj_HRUnregisterNewURLUPP, 1, "() -> None"}, {"HRUnregisterURLToFSSpecUPP", (PyCFunction)HtmlObj_HRUnregisterURLToFSSpecUPP, 1, "() -> None"}, {NULL, NULL, 0} }; PyMethodChain HtmlObj_chain = { HtmlObj_methods, NULL }; static PyObject *HtmlObj_getattr(self, name) HtmlObjectObject *self; char *name; { return Py_FindMethodInChain(&HtmlObj_chain, (PyObject *)self, name); } #define HtmlObj_setattr NULL #define HtmlObj_compare NULL #define HtmlObj_repr NULL #define HtmlObj_hash NULL PyTypeObject HtmlObject_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /*ob_size*/ "HtmlRender.HtmlObject", /*tp_name*/ sizeof(HtmlObjectObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor) HtmlObj_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc) HtmlObj_getattr, /*tp_getattr*/ (setattrfunc) HtmlObj_setattr, /*tp_setattr*/ (cmpfunc) HtmlObj_compare, /*tp_compare*/ (reprfunc) HtmlObj_repr, /*tp_repr*/ (PyNumberMethods *)0, /* tp_as_number */ (PySequenceMethods *)0, /* tp_as_sequence */ (PyMappingMethods *)0, /* tp_as_mapping */ (hashfunc) HtmlObj_hash, /*tp_hash*/ }; /* ------------------- End object type HtmlObject ------------------- */ static PyObject *Html_HRGetHTMLRenderingLibVersion(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; NumVersion returnVers; if (!PyArg_ParseTuple(_args, "")) return NULL; _err = HRGetHTMLRenderingLibVersion(&returnVers); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", PyMac_BuildNumVersion, returnVers); return _res; } static PyObject *Html_HRNewReference(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; HRReference hrRef; OSType rendererType; GrafPtr grafPtr; if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &rendererType, GrafObj_Convert, &grafPtr)) return NULL; _err = HRNewReference(&hrRef, rendererType, grafPtr); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", HtmlObj_New, hrRef); return _res; } static PyObject *Html_HRFreeMemory(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; SInt32 _rv; Size inBytesNeeded; if (!PyArg_ParseTuple(_args, "l", &inBytesNeeded)) return NULL; _rv = HRFreeMemory(inBytesNeeded); _res = Py_BuildValue("l", _rv); return _res; } static PyObject *Html_HRScreenConfigurationChanged(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; if (!PyArg_ParseTuple(_args, "")) return NULL; HRScreenConfigurationChanged(); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *Html_HRIsHREvent(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; Boolean _rv; EventRecord eventRecord; if (!PyArg_ParseTuple(_args, "O&", PyMac_GetEventRecord, &eventRecord)) return NULL; _rv = HRIsHREvent(&eventRecord); _res = Py_BuildValue("b", _rv); return _res; } static PyObject *Html_HRUtilCreateFullURL(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; char * rootURL; char * linkURL; Handle fullURLH; if (!PyArg_ParseTuple(_args, "ssO&", &rootURL, &linkURL, ResObj_Convert, &fullURLH)) return NULL; _err = HRUtilCreateFullURL(rootURL, linkURL, fullURLH); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *Html_HRUtilGetFSSpecFromURL(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; char * rootURL; char * linkURL; FSSpec destSpec; if (!PyArg_ParseTuple(_args, "ss", &rootURL, &linkURL)) return NULL; _err = HRUtilGetFSSpecFromURL(rootURL, linkURL, &destSpec); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", PyMac_BuildFSSpec, destSpec); return _res; } static PyObject *Html_HRUtilGetURLFromFSSpec(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; OSStatus _err; FSSpec fsspec; Handle urlHandle; if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetFSSpec, &fsspec, ResObj_Convert, &urlHandle)) return NULL; _err = HRUtilGetURLFromFSSpec(&fsspec, urlHandle); if (_err != noErr) return PyMac_Error(_err); Py_INCREF(Py_None); _res = Py_None; return _res; } static PyObject *Html_HRHTMLRenderingLibAvailable(_self, _args) PyObject *_self; PyObject *_args; { PyObject *_res = NULL; int _rv; if (!PyArg_ParseTuple(_args, "")) return NULL; _rv = HRHTMLRenderingLibAvailable(); _res = Py_BuildValue("i", _rv); return _res; } static PyMethodDef Html_methods[] = { {"HRGetHTMLRenderingLibVersion", (PyCFunction)Html_HRGetHTMLRenderingLibVersion, 1, "() -> (NumVersion returnVers)"}, {"HRNewReference", (PyCFunction)Html_HRNewReference, 1, "(OSType rendererType, GrafPtr grafPtr) -> (HRReference hrRef)"}, {"HRFreeMemory", (PyCFunction)Html_HRFreeMemory, 1, "(Size inBytesNeeded) -> (SInt32 _rv)"}, {"HRScreenConfigurationChanged", (PyCFunction)Html_HRScreenConfigurationChanged, 1, "() -> None"}, {"HRIsHREvent", (PyCFunction)Html_HRIsHREvent, 1, "(EventRecord eventRecord) -> (Boolean _rv)"}, {"HRUtilCreateFullURL", (PyCFunction)Html_HRUtilCreateFullURL, 1, "(char * rootURL, char * linkURL, Handle fullURLH) -> None"}, {"HRUtilGetFSSpecFromURL", (PyCFunction)Html_HRUtilGetFSSpecFromURL, 1, "(char * rootURL, char * linkURL) -> (FSSpec destSpec)"}, {"HRUtilGetURLFromFSSpec", (PyCFunction)Html_HRUtilGetURLFromFSSpec, 1, "(FSSpec fsspec, Handle urlHandle) -> None"}, {"HRHTMLRenderingLibAvailable", (PyCFunction)Html_HRHTMLRenderingLibAvailable, 1, "() -> (int _rv)"}, {NULL, NULL, 0} }; void initHtmlRender() { PyObject *m; PyObject *d; m = Py_InitModule("HtmlRender", Html_methods); d = PyModule_GetDict(m); Html_Error = PyMac_GetOSErrException(); if (Html_Error == NULL || PyDict_SetItemString(d, "Error", Html_Error) != 0) Py_FatalError("can't initialize HtmlRender.Error"); HtmlObject_Type.ob_type = &PyType_Type; Py_INCREF(&HtmlObject_Type); if (PyDict_SetItemString(d, "HtmlObjectType", (PyObject *)&HtmlObject_Type) != 0) Py_FatalError("can't initialize HtmlObjectType"); } /* ===================== End module HtmlRender ====================== */
26.322344
87
0.674135
[ "object" ]
08e0ddc8ef83357a3c128b3695bed6b35ed625d7
19,352
h
C
third_party/fuchsia-sdk/pkg/fit/include/lib/fit/bridge.h
zachary0101/fuchsia-sample
f89a96f6d320b9963fa8168954b84441ca2fdf40
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
zircon/system/ulib/fit/include/lib/fit/bridge.h
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
1
2022-01-14T23:38:40.000Z
2022-01-14T23:38:40.000Z
zircon/system/ulib/fit/include/lib/fit/bridge.h
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
4
2020-12-28T17:04:45.000Z
2022-03-12T03:20:44.000Z
// Copyright 2018 The Fuchsia 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 LIB_FIT_BRIDGE_H_ #define LIB_FIT_BRIDGE_H_ #include "bridge_internal.h" namespace fit { // A bridge is a building block for asynchronous control flow that is formed // by the association of two distinct participants: a completer and a consumer. // // - The completer is responsible for reporting completion of an asynchronous // task and providing its result. See |completer| and |fit::completer|. // - The consumer is responsible for consuming the result of the asynchronous // task. See |consumer| and |fit::consumer|. // // This class is often used for binding a |fit::promise| to a callback, // facilitating interoperation of promises with functions that asynchronously // report their result via a callback function. It can also be used more // generally anytime it is necessary to decouple completion of an asynchronous // task from consumption of its result (possibly on different threads). // // The completer and consumer each possesses a unique capability that can // be exercised at most once during their association: the asynchronous // task represented by a bridge can be completed at most once and its // result can be consumed at most once. This property is enforced by // a single-ownership model for completers and consumers. // // The completion capability has a single owner represented by |fit::completer|. // Its owner may exercise the capability to complete the task (provide its result), // it may transfer the capability by moving it to another completer instance, // or it may cause the asynchronous task to be "abandoned" by discarding the // capability, implying that the task can never produce a result. When this // occurs, the associated consumer's |fit::consumer::was_abandoned()| method // will return true and the consumer will not obtain any result from the task. // See |fit::consumer::promise()| and |fit::consumer::promise_or()| for // details on how abandonment of the task can be handled by the consumer. // // The consumption capability has a single owner represented by |fit::consumer|. // Its owner may exercise the capability to consume the task's result (as a // promise), it may transfer the capability by moving it to another consumer // instance, or it may cause the asynchronous task to be "canceled" by // discarding the capability, implying that the task's result can never be // consumed. When this occurs, the associated completer's // |fit::completer::was_canceled()| method will return true and the task's // eventual result (if any) will be silently discarded. // // DECOUPLING // // See |fit::schedule_for_consumer| for a helper which uses a bridge to // decouple completion and consumption of a task's result so they can be // performed on different executors. // // SYNOPSIS // // |V| is the type of value produced when the task completes successfully. // Use |std::tuple<Args...>| if the task produces multiple values, such as // when you intend to bind the task's completer to a callback with multiple // arguments using |fit::completer::bind_tuple()|. // Defaults to |void|. // // |E| is the type of error produced when the task completes with an error. // Defaults to |void|. // // EXAMPLE // // Imagine a File I/O library offers a callback-based asynchronous reading // function. We suppose that the read handling code will invoke the // callback upon completion. The library's API might look a bit like this: // // using read_callback = fit::function<void(size_t bytes_read)>; // void read_async(size_t num_bytes, uint8_t* buffer, read_callback cb); // // Here's how we can adapt the library's "read_async" function to a // |fit::promise| by binding its callback to a bridge: // // fit::promise<size_t> promise_read(uint8_t* buffer, size_t num_bytes) { // fit::bridge<size_t> bridge; // read_async(num_bytes, buffer, bridge.completer.bind()); // return bridge.consumer.promise_or(::fit::error()); // } // // Finally we can chain additional asynchronous tasks to be performed upon // completion of the promised read: // // uint8_t buffer[4096]; // void my_program(fit::executor* executor) { // auto promise = promise_read(buffer, sizeof(buffer)) // .and_then([] (const size_t& bytes_read) { // // consume contents of buffer // }) // .or_else() { // // handle error case // }); // executor->schedule_task(std::move(promise)); // } // // Similarly, suppose the File I/O library offers a callback-based asynchronous // writing function that can return a variety of errors encoded as negative // sizes. Here's how we might decode those errors uniformly into |fit::result| // allowing them to be handled using combinators such as |or_else|. // // using write_callback = fit::function<void(size_t bytes_written, int error)>; // void write_async(size_t num_bytes, uint8_t* buffer, write_callback cb); // // fit::promise<size_t, int> promise_write(uint8_t* buffer, size_t num_bytes) { // fit::bridge<size_t, int> bridge; // write_async(num_bytes, buffer, // [completer = std::move(bridge.completer)](size_t bytes_written, int error) { // if (bytes_written == 0) { // completer.complete_error(error); // return; // } // completer.complete_ok(bytes_written); // }); // return bridge.consumer.promise_or(::fit::error(ERR_ABANDONED)); // } // // uint8_t buffer[4096]; // void my_program(fit::executor* executor) { // auto promise = promise_write(buffer, sizeof(buffer)) // .and_then([] (const size_t& bytes_written) { // // consume contents of buffer // }) // .or_else(const int& error) { // // handle error case // }); // executor->schedule_task(std::move(promise)); // } // // See documentation of |fit::promise| for more information. template <typename V, typename E> class bridge final { public: using value_type = V; using error_type = E; using result_type = result<value_type, error_type>; using completer_type = ::fit::completer<V, E>; using consumer_type = ::fit::consumer<V, E>; // Creates a bridge representing a new asynchronous task formed by the // association of a completer and consumer. bridge() { ::fit::internal::bridge_state<V, E>::create(&completer.completion_ref_, &consumer.consumption_ref_); } bridge(bridge&& other) = default; bridge(const bridge& other) = delete; ~bridge() = default; bridge& operator=(bridge&& other) = default; bridge& operator=(const bridge& other) = delete; // The bridge's completer capability. completer_type completer; // The bridge's consumer capability. consumer_type consumer; }; // Provides a result upon completion of an asynchronous task. // // Instances of this class have single-ownership of a unique capability for // completing the task. This capability can be exercised at most once. // Ownership of the capability is implicitly transferred away when the // completer is abandoned, completed, or bound to a callback. // // See also |fit::bridge|. // See documentation of |fit::promise| for more information. // // SYNOPSIS // // |V| is the type of value produced when the task completes successfully. // Use |std::tuple<Args...>| if the task produces multiple values, such as // when you intend to bind the task's completer to a callback with multiple // arguments using |fit::completer::bind_tuple()|. // Defaults to |void|. // // |E| is the type of error produced when the task completes with an error. // Defaults to |void|. template <typename V, typename E> class completer final { using bridge_state = ::fit::internal::bridge_state<V, E>; using completion_ref = typename bridge_state::completion_ref; public: using value_type = V; using error_type = E; using result_type = ::fit::result<V, E>; completer() = default; completer(completer&& other) = default; ~completer() = default; completer& operator=(completer&& other) = default; // Returns true if this instance currently owns the unique capability for // reporting completion of the task. explicit operator bool() const { return !!completion_ref_; } // Returns true if the associated |consumer| has canceled the task. // This method returns a snapshot of the current cancellation state. // Note that the task may be canceled concurrently at any time. bool was_canceled() const { assert(completion_ref_); return completion_ref_.get()->was_canceled(); } // Explicitly abandons the task, meaning that it will never be completed. // See |fit::bridge| for details about abandonment. void abandon() { assert(completion_ref_); completion_ref_ = completion_ref(); } // Reports that the task has completed successfully. // This method takes no arguments if |value_type| is void, otherwise it // takes one argument which must be assignable to |value_type|. template <typename VV = value_type, typename = std::enable_if_t<std::is_void<VV>::value>> void complete_ok() { assert(completion_ref_); bridge_state* state = completion_ref_.get(); state->complete_or_abandon(std::move(completion_ref_), ::fit::ok()); } template <typename VV = value_type, typename = std::enable_if_t<!std::is_void<VV>::value>> void complete_ok(VV value) { assert(completion_ref_); bridge_state* state = completion_ref_.get(); state->complete_or_abandon(std::move(completion_ref_), ::fit::ok<value_type>(std::forward<VV>(value))); } // Reports that the task has completed with an error. // This method takes no arguments if |error_type| is void, otherwise it // takes one argument which must be assignable to |error_type|. template <typename EE = error_type, typename = std::enable_if_t<std::is_void<EE>::value>> void complete_error() { assert(completion_ref_); bridge_state* state = completion_ref_.get(); state->complete_or_abandon(std::move(completion_ref_), ::fit::error()); } template <typename EE = error_type, typename = std::enable_if_t<!std::is_void<EE>::value>> void complete_error(EE error) { assert(completion_ref_); bridge_state* state = completion_ref_.get(); state->complete_or_abandon(std::move(completion_ref_), ::fit::error<error_type>(std::forward<EE>(error))); } // Reports that the task has completed or been abandoned. // See |fit::bridge| for details about abandonment. // // The result state determines the task's final disposition. // - |fit::result_state::ok|: The task completed successfully. // - |fit::result_state::error|: The task completed with an error. // - |fit::result_state::pending|: The task was abandoned. void complete_or_abandon(result_type result) { assert(completion_ref_); bridge_state* state = completion_ref_.get(); state->complete_or_abandon(std::move(completion_ref_), std::move(result)); } // Returns a callback that reports completion of the asynchronous task along // with its result when invoked. This method is typically used to bind // completion of a task to a callback that has zero or one argument. // // If |value_type| is void, the returned callback's signature is: void(void) // Otherwise, the returned callback's signature is: void(value_type). // // The returned callback is thread-safe and move-only. ::fit::internal::bridge_bind_callback<V, E> bind() { assert(completion_ref_); return ::fit::internal::bridge_bind_callback<V, E>(std::move(completion_ref_)); } // A variant of |bind()| that can be used to bind a completion of a task // to a callback that has zero or more arguments by wrapping the callback's // arguments into a tuple when producing the task's result. // // The |value_type| must be a tuple type. // Given a |value_type| of std::tuple<Args...>, the returned callback's // signature is: void(Args...). Note that the tuple's fields are // unpacked as individual arguments of the callback. // // The returned callback is thread-safe and move-only. ::fit::internal::bridge_bind_tuple_callback<V, E> bind_tuple() { assert(completion_ref_); return ::fit::internal::bridge_bind_tuple_callback<V, E>(std::move(completion_ref_)); } completer(const completer& other) = delete; completer& operator=(const completer& other) = delete; private: friend class bridge<V, E>; completion_ref completion_ref_; }; // Consumes the result of an asynchronous task. // // Instances of this class have single-ownership of a unique capability for // consuming the task's result. This capability can be exercised at most once. // Ownership of the capability is implicitly transferred away when the // task is canceled or converted to a promise. // // See also |fit::bridge|. // See documentation of |fit::promise| for more information. // // SYNOPSIS // // |V| is the type of value produced when the task completes successfully. // Use |std::tuple<Args...>| if the task produces multiple values, such as // when you intend to bind the task's completer to a callback with multiple // arguments using |fit::completer::bind_tuple()|. // Defaults to |void|. // // |E| is the type of error produced when the task completes with an error. // Defaults to |void|. template <typename V, typename E> class consumer final { using bridge_state = ::fit::internal::bridge_state<V, E>; using consumption_ref = typename bridge_state::consumption_ref; public: using value_type = V; using error_type = E; using result_type = ::fit::result<V, E>; consumer() = default; consumer(consumer&& other) = default; ~consumer() = default; consumer& operator=(consumer&& other) = default; // Returns true if this instance currently owns the unique capability for // consuming the result of the task upon its completion. explicit operator bool() const { return !!consumption_ref_; } // Explicitly cancels the task, meaning that its result will never be consumed. // See |fit::bridge| for details about cancellation. void cancel() { assert(consumption_ref_); consumption_ref_ = consumption_ref(); } // Returns true if the associated |completer| has abandoned the task. // This method returns a snapshot of the current abandonment state. // Note that the task may be abandoned concurrently at any time. bool was_abandoned() const { assert(consumption_ref_); return consumption_ref_.get()->was_abandoned(); } // Returns an unboxed promise which resumes execution once this task has // completed. If the task is abandoned by its completer, the promise // will not produce a result, thereby causing subsequent tasks associated // with the promise to also be abandoned and eventually destroyed if // they cannot make progress without the promised result. promise_impl<typename bridge_state::promise_continuation> promise() { assert(consumption_ref_); return make_promise_with_continuation( typename bridge_state::promise_continuation(std::move(consumption_ref_))); } // A variant of |promise()| that allows a default result to be provided when // the task is abandoned by its completer. Typically this is used to cause // the promise to return an error when the task is abandoned instead of // causing subsequent tasks associated with the promise to also be abandoned. // // The state of |result_if_abandoned| determines the promise's behavior // in case of abandonment. // // - |fit::result_state::ok|: Reports a successful result. // - |fit::result_state::error|: Reports a failure result. // - |fit::result_state::pending|: Does not report a result, thereby // causing subsequent tasks associated with the promise to also be // abandoned and eventually destroyed if they cannot make progress // without the promised result. promise_impl<typename bridge_state::promise_continuation> promise_or( result_type result_if_abandoned) { assert(consumption_ref_); return make_promise_with_continuation(typename bridge_state::promise_continuation( std::move(consumption_ref_), std::move(result_if_abandoned))); } consumer(const consumer& other) = delete; consumer& operator=(const consumer& other) = delete; private: friend class bridge<V, E>; consumption_ref consumption_ref_; }; // Schedules |promise| to run on |executor| and returns a |consumer| which // receives the result of the promise upon its completion. // // This method has the effect of decoupling the evaluation of a promise from // the consumption of its result such that they can be performed on different // executors (possibly on different threads). // // |executor| must be non-null. // |promise| must be non-empty. // // EXAMPLE // // This example shows an object that encapsulates its own executor which it // manages independently from that of its clients. This enables the object // to obtain certain assurances such as a guarantee of single-threaded // execution for its internal operations even if its clients happen to be // multi-threaded (or vice-versa as desired). // // // This model has specialized internal threading requirements so it // // manages its own executor. // class model { // public: // fit::consumer<int> perform_calculation(int parameter) { // return fit::schedule_for_consumer(&executor_, // fit::make_promise([parameter] { // // In reality, this would likely be a much more // // complex expression. // return fit::ok(parameter * parameter); // }); // } // // private: // // The model is responsible for initializing and running its own // // executor (perhaps on its own thread). // fit::single_threaded_executor executor_; // }; // // // Asks the model to perform a calculation, awaits a result on the // // provided executor (which is different from the one internally used // // by the model), then prints the result. // void print_output(fit::executor* executor, model* m) { // executor->schedule_task( // m->perform_calculation(16) // .promise_or(fit::error()) // .and_then([] (const int& result) { printf("done: %d\n", result); }) // .or_else([] { puts("failed or abandoned"); })); // } // template <typename Promise> inline consumer<typename Promise::value_type, typename Promise::error_type> schedule_for_consumer( fit::executor* executor, Promise promise) { assert(executor); assert(promise); fit::bridge<typename Promise::value_type, typename Promise::error_type> bridge; executor->schedule_task(promise.then( [completer = std::move(bridge.completer)](typename Promise::result_type& result) mutable { completer.complete_or_abandon(std::move(result)); })); return std::move(bridge.consumer); } } // namespace fit #endif // LIB_FIT_BRIDGE_H_
41.796976
98
0.698584
[ "object", "model" ]
08e3ab1f4ada534fc71e01e221dc727938b90852
852
h
C
clfsm/CLReflect.v1/CLMetaState.h
mipalgu/gufsm
d822d36fa04946ffa6c3680725dfdba03fa9a0c5
[ "BSD-4-Clause" ]
null
null
null
clfsm/CLReflect.v1/CLMetaState.h
mipalgu/gufsm
d822d36fa04946ffa6c3680725dfdba03fa9a0c5
[ "BSD-4-Clause" ]
null
null
null
clfsm/CLReflect.v1/CLMetaState.h
mipalgu/gufsm
d822d36fa04946ffa6c3680725dfdba03fa9a0c5
[ "BSD-4-Clause" ]
1
2021-09-14T18:37:16.000Z
2021-09-14T18:37:16.000Z
#ifndef CLMETASTATE_H #define CLMETASTATE_H #include "CLMetaTransition.h" #include "CLMetaProperty.h" #include <memory> #include <string> #include <map> #include <vector> namespace CLReflect { class CLMetaState { protected: std::string _name; std::map< std::string, std::shared_ptr<CLMetaProperty> > _properties; std::vector< std::shared_ptr<CLMetaTransition> > _transitions; public: CLMetaState() {} CLMetaState(std::string name) : _name(name) {} std::string getName() const { return _name; } void addTransition(std::shared_ptr<CLMetaTransition> trans) { _transitions.push_back(trans); } void addProperty(std::shared_ptr<CLMetaProperty> newProperty); std::shared_ptr<CLMetaProperty> getProperty(std::string propertyName); }; } #endif
21.3
102
0.66784
[ "vector" ]
08e43929d92c1a75459142263d33180b23128a3b
119,771
c
C
ast-8.6.2/stc.c
astro-datalab/dlapps
18a338a887af19d195b5c1eeed6c0a9e38686125
[ "BSD-3-Clause" ]
1
2020-08-17T21:26:16.000Z
2020-08-17T21:26:16.000Z
ast-8.6.2/stc.c
noaodatalab/dlapps
33e8fc6161448f2052369b1fbe2765e854c1ac52
[ "BSD-3-Clause" ]
null
null
null
ast-8.6.2/stc.c
noaodatalab/dlapps
33e8fc6161448f2052369b1fbe2765e854c1ac52
[ "BSD-3-Clause" ]
null
null
null
/* *class++ * Name: * Stc * Purpose: * Represents an instance of the IVOA STC class. * Constructor Function: c astStc f AST_STC * Description: * The Stc class is an implementation of the IVOA STC class which forms * part of the IVOA Space-Time Coordinate Metadata system. See: * * http://hea-www.harvard.edu/~arots/nvometa/STC.html * * The Stc class does not have a constructor function of its own, as it * is simply a container class for a family of specialised sub-classes * including StcCatalogEntryLocation, StcResourceProfile, StcSearchLocation * and StcObsDataLocation. * Inheritance: * The Stc class inherits from the Region class. * Attributes: * In addition to those attributes common to all Regions, every * Stc also has the following attributes: * * - RegionClass: The class name of the encapsulated Region. * Functions: c In addition to those functions applicable to all Regions, the c following functions may also be applied to all Stc's: f In addition to those routines applicable to all Regions, the f following routines may also be applied to all Stc's: * c - astGetStcRegion: Get a pointer to the encapsulated Region f - AST_GETSTCREGION: Get a pointer to the encapsulated Region c - astGetStcCoord: Get information about an AstroCoords element f - AST_GETSTCCOORD: Get information about an AstroCoords element c - astGetStcNCoord: Returns the number of AstroCoords elements in an Stc f - AST_GETSTCNCOORD: Returns the number of AstroCoords elements in an Stc * Copyright: * Copyright (C) 1997-2006 Council for the Central Laboratory of the * Research Councils * Copyright (C) 2008 Science & Technology Facilities Council. * All Rights Reserved. * Licence: * This program 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 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * License along with this program. If not, see * <http://www.gnu.org/licenses/>. * Authors: * DSB: David S. Berry (Starlink) * History: * 23-NOV-2004 (DSB): * Original version. * 14-FEB-2006 (DSB): * Override astGetObjSize. * 13-MAR-2009 (DSB): * Over-ride astRegBasePick. *class-- */ /* Module Macros. */ /* ============== */ /* Set the name of the class we are implementing. This indicates to the header files that define class interfaces that they should make "protected" symbols available. */ #define astCLASS Stc /* The number of components in an AstroCoords element which are described using a Region within a KeyMap. */ #define NREG 5 /* Include files. */ /* ============== */ /* Interface definitions. */ /* ---------------------- */ #include "globals.h" /* Thread-safe global data access */ #include "error.h" /* Error reporting facilities */ #include "memory.h" /* Memory allocation facilities */ #include "object.h" /* Base Object class */ #include "unitmap.h" /* Unit Mappings */ #include "region.h" /* Regions (parent class) */ #include "channel.h" /* I/O channels */ #include "stc.h" /* Interface definition for this class */ #include "keymap.h" /* Lists of value/key pairs */ #include "pointlist.h" /* Individual points in a Frame */ #include "ellipse.h" /* Ellipses within a Frame */ #include "interval.h" /* Axis intervals within a Frame */ #include "prism.h" /* Extrusions into higher dimensions */ /* Error code definitions. */ /* ----------------------- */ #include "ast_err.h" /* AST error codes */ /* C header files. */ /* --------------- */ #include <stdarg.h> #include <stddef.h> #include <string.h> #include <stdio.h> /* Module Variables. */ /* ================= */ /* Address of this static variable is used as a unique identifier for member of this class. */ static int class_check; /* Pointers to parent class methods which are extended by this class. */ static AstMapping *(* parent_simplify)( AstMapping *, int * ); static AstPointSet *(* parent_transform)( AstMapping *, AstPointSet *, int, AstPointSet *, int * ); static AstRegion *(* parent_getdefunc)( AstRegion *, int * ); static const char *(* parent_getattrib)( AstObject *, const char *, int * ); static int (* parent_equal)( AstObject *, AstObject *, int * ); static int (* parent_getobjsize)( AstObject *, int * ); static int (* parent_getusedefs)( AstObject *, int * ); static int (* parent_testattrib)( AstObject *, const char *, int * ); static void (* parent_clearattrib)( AstObject *, const char *, int * ); static void (* parent_setattrib)( AstObject *, const char *, int * ); static void (* parent_setregfs)( AstRegion *, AstFrame *, int * ); static void (*parent_regclearattrib)( AstRegion *, const char *, char **, int * ); static void (*parent_regsetattrib)( AstRegion *, const char *, char **, int * ); static void (* parent_clearnegated)( AstRegion *, int * ); static void (* parent_clearclosed)( AstRegion *, int * ); static void (* parent_clearfillfactor)( AstRegion *, int * ); static void (* parent_clearmeshsize)( AstRegion *, int * ); static void (* parent_setclosed)( AstRegion *, int, int * ); static void (* parent_setfillfactor)( AstRegion *, double, int * ); static void (* parent_setmeshsize)( AstRegion *, int, int * ); static void (* parent_setnegated)( AstRegion *, int, int * ); #if defined(THREAD_SAFE) static int (* parent_managelock)( AstObject *, int, int, AstObject **, int * ); #endif /* The keys associated with each component of an AstroCoords element within KeyMap */ static const char *regkey[ NREG ] = { AST__STCERROR, AST__STCRES, AST__STCSIZE, AST__STCPIXSZ, AST__STCVALUE }; /* The comments associated with each component of an AstroCoords element within KeyMap */ static const char *regcom[ NREG ] = { "AstroCoords error region", "AstroCoords resolution region", "AstroCoords size region", "AstroCoords pixel size region", "AstroCoords value region" }; #ifdef THREAD_SAFE /* Define how to initialise thread-specific globals. */ #define GLOBAL_inits \ globals->Class_Init = 0; /* Create the function that initialises global data for this module. */ astMAKE_INITGLOBALS(Stc) /* Define macros for accessing each item of thread specific global data. */ #define class_init astGLOBAL(Stc,Class_Init) #define class_vtab astGLOBAL(Stc,Class_Vtab) #include <pthread.h> #else /* Define the class virtual function table and its initialisation flag as static variables. */ static AstStcVtab class_vtab; /* Virtual function table */ static int class_init = 0; /* Virtual function table initialised? */ #endif /* External Interface Function Prototypes. */ /* ======================================= */ /* Prototypes for Private Member Functions. */ /* ======================================== */ static AstKeyMap *GetStcCoord( AstStc *, int, int * ); static AstKeyMap *MakeAstroCoordsKeyMap( AstRegion *, AstKeyMap *, const char *, int * ); static AstMapping *Simplify( AstMapping *, int * ); static AstPointSet *RegBaseMesh( AstRegion *, int * ); static AstPointSet *Transform( AstMapping *, AstPointSet *, int, AstPointSet *, int * ); static AstRegion *GetDefUnc( AstRegion *, int * ); static AstRegion *GetStcRegion( AstStc *, int * ); static AstRegion *RegBasePick( AstRegion *this, int, const int *, int * ); static const char *GetRegionClass( AstStc *, int * ); static int Equal( AstObject *, AstObject *, int * ); static int GetBounded( AstRegion *, int * ); static int GetObjSize( AstObject *, int * ); static int GetStcNCoord( AstStc *, int * ); static int GetUseDefs( AstObject *, int * ); static int Overlap( AstRegion *, AstRegion *, int * ); static int OverlapX( AstRegion *, AstRegion *, int * ); static int RegPins( AstRegion *, AstPointSet *, AstRegion *, int **, int * ); static void Copy( const AstObject *, AstObject *, int * ); static void Delete( AstObject *, int * ); static void Dump( AstObject *, AstChannel *, int * ); static void GetRegion( AstStc *, AstRegion **, int *, int * ); static void RegBaseBox( AstRegion *, double *, double *, int * ); static void RegClearAttrib( AstRegion *, const char *, char **, int * ); static void RegSetAttrib( AstRegion *, const char *, char **, int * ); static void SetRegFS( AstRegion *, AstFrame *, int * ); static void ClearAttrib( AstObject *, const char *, int * ); static const char *GetAttrib( AstObject *, const char *, int * ); static void SetAttrib( AstObject *, const char *, int * ); static int TestAttrib( AstObject *, const char *, int * ); static void ClearClosed( AstRegion *, int * ); static int GetClosed( AstRegion *, int * ); static void SetClosed( AstRegion *, int, int * ); static int TestClosed( AstRegion *, int * ); static void ClearMeshSize( AstRegion *, int * ); static int GetMeshSize( AstRegion *, int * ); static void SetMeshSize( AstRegion *, int, int * ); static int TestMeshSize( AstRegion *, int * ); static void ClearFillFactor( AstRegion *, int * ); static double GetFillFactor( AstRegion *, int * ); static void SetFillFactor( AstRegion *, double, int * ); static int TestFillFactor( AstRegion *, int * ); static void ClearNegated( AstRegion *, int * ); static int GetNegated( AstRegion *, int * ); static void SetNegated( AstRegion *, int, int * ); static int TestNegated( AstRegion *, int * ); #if defined(THREAD_SAFE) static int ManageLock( AstObject *, int, int, AstObject **, int * ); #endif /* Member functions. */ /* ================= */ static void ClearAttrib( AstObject *this_object, const char *attrib, int *status ) { /* * Name: * ClearAttrib * Purpose: * Clear an attribute value for a Stc. * Type: * Private function. * Synopsis: * #include "stc.h" * void ClearAttrib( AstObject *this, const char *attrib, int *status ) * Class Membership: * Stc member function (over-rides the astClearAttrib protected * method inherited from the Region class). * Description: * This function clears the value of a specified attribute for a * Stc, so that the default value will subsequently be used. * Parameters: * this * Pointer to the Stc. * attrib * Pointer to a null terminated string specifying the attribute * name. This should be in lower case with no surrounding white * space. * status * Pointer to the inherited status variable. */ /* Local Variables: */ AstStc *this; /* Pointer to the Stc structure */ int len; /* Length of attrib string */ /* Check the global error status. */ if ( !astOK ) return; /* Obtain a pointer to the Stc structure. */ this = (AstStc *) this_object; /* Obtain the length of the "attrib" string. */ len = strlen( attrib ); /* Check the attribute name and clear the appropriate attribute. */ /* (none as yet) */ /* ------------- */ /* Read-only attributes. */ /* --------------------- */ /* Test if the attribute name matches any of the read-only attributes of this class. If it does, then report an error. */ if ( !strcmp( attrib, "regionclass" ) ) { astError( AST__NOWRT, "astClear: Invalid attempt to clear the \"%s\" " "value for a %s.", status, attrib, astGetClass( this ) ); astError( AST__NOWRT, "This is a read-only attribute." , status); /* Not recognised. */ /* --------------- */ /* If the attribute is still not recognised, pass it on to the parent method for further interpretation. */ } else { (*parent_clearattrib)( this_object, attrib, status ); } } static int Equal( AstObject *this_object, AstObject *that_object, int *status ) { /* * Name: * Equal * Purpose: * Test if two Objects are equivalent. * Type: * Private function. * Synopsis: * #include "stc.h" * int Equal( AstObject *this_object, AstObject *that_object, int *status ) * Class Membership: * Stc member function (over-rides the astEqual protected * method inherited from the Region class). * Description: * This function returns a boolean result (0 or 1) to indicate whether * two Stcs are equivalent. * Parameters: * this * Pointer to the first Stc. * that * Pointer to the second Stc. * status * Pointer to the inherited status variable. * Returned Value: * One if the Stcs are equivalent, zero otherwise. * Notes: * - The Stcs are equivalent if their encapsulated Region are * equivalent, and if they have the same boolean operation, negation * and closed flags. * - A value of zero will be returned if this function is invoked * with the global status set, or if it should fail for any reason. */ /* Local Variables: */ AstStc *that; AstStc *this; int result; /* Initialise. */ result = 0; /* Check the global error status. */ if ( !astOK ) return result; /* Invoke the Equal method inherited from the parent Region class. This checks that the Objects are both of the same class, and have the same Negated and Closed flags (amongst other things). */ if( (*parent_equal)( this_object, that_object, status ) ) { /* Obtain pointers to the two Stc structures. */ this = (AstStc *) this_object; that = (AstStc *) that_object; /* Test their encapsulated Region for equality. */ result = astEqual( this->region, that->region ); } /* If an error occurred, clear the result value. */ if ( !astOK ) result = 0; /* Return the result, */ return result; } /* * Name: * MAKE_SET * Purpose: * Define a function to set an attribute value for a Stc. * Type: * Private macro. * Synopsis: * #include "stc.h" * MAKE_SET(attribute,lattribute,type) * Class Membership: * Defined by the Stc class. * Description: * This macro expands to an implementation of a private member function * of the form: * * static void Set<Attribute>( AstRegion *this, <Type> value ) * * that sets the value of a specified Region attribute in the parent * Region structure and also in the encapsulated Region. * Parameters: * attribute * Name of the attribute, as it appears in the function name. * lattribute * Name of the attribute, all in lower case. * type * The C type of the attribute. */ /* Define the macro. */ #define MAKE_SET(attribute,lattribute,type) \ static void Set##attribute( AstRegion *this_region, type value, int *status ) { \ \ /* Local Variables: */ \ AstStc *this; /* Pointer to the Stc structure */ \ \ /* Check the global error status. */ \ if ( !astOK ) return; \ \ /* Use the parent method to set the value in the parent Region structure. */ \ (*parent_set##lattribute)( this_region, value, status ); \ \ /* Also set the value in the encapsulated Region. */ \ this = (AstStc *) this_region; \ astSet##attribute( this->region, value ); \ } /* Use the above macro to create accessors for the MeshSize, Closed and FillFactor attributes. */ MAKE_SET(FillFactor,fillfactor,double) MAKE_SET(MeshSize,meshsize,int) MAKE_SET(Closed,closed,int) MAKE_SET(Negated,negated,int) /* Undefine the macro. */ #undef MAKE_SET /* * Name: * MAKE_CLEAR * Purpose: * Define a function to clear an attribute value for a Stc. * Type: * Private macro. * Synopsis: * #include "stc.h" * MAKE_CLEAR(attribute,lattribute) * Class Membership: * Defined by the Stc class. * Description: * This macro expands to an implementation of a private member function * of the form: * * static void Clear<Attribute>( AstRegion *this ) * * that sets the value of a specified Region attribute in the parent * Region structure and also in the encapsulated Region. * Parameters: * attribute * Name of the attribute, as it appears in the function name. * lattribute * Name of the attribute, all in lower case. */ /* Define the macro. */ #define MAKE_CLEAR(attribute,lattribute) \ static void Clear##attribute( AstRegion *this_region, int *status ) { \ \ /* Local Variables: */ \ AstStc *this; /* Pointer to the Stc structure */ \ \ /* Check the global error status. */ \ if ( !astOK ) return; \ \ /* Use the parent method to clear the value in the parent Region structure. */ \ (*parent_clear##lattribute)( this_region, status ); \ \ /* Also clear the value in the encapsulated Region. */ \ this = (AstStc *) this_region; \ astClear##attribute( this->region ); \ } /* Use the above macro to create accessors for the MeshSize, Closed and FillFactor attributes. */ MAKE_CLEAR(FillFactor,fillfactor) MAKE_CLEAR(MeshSize,meshsize) MAKE_CLEAR(Closed,closed) MAKE_CLEAR(Negated,negated) /* Undefine the macro. */ #undef MAKE_CLEAR /* * Name: * MAKE_GET * Purpose: * Define a function to get an attribute value for a Stc. * Type: * Private macro. * Synopsis: * #include "stc.h" * MAKE_GET(attribute,type,bad) * Class Membership: * Defined by the Stc class. * Description: * This macro expands to an implementation of a private member function * of the form: * * static <Type> Get<Attribute>( AstRegion *this ) * * that gets the value of a specified Region attribute from the encapsulated * Region. * Parameters: * attribute * Name of the attribute, as it appears in the function name. * type * The C type of the attribute. * bad * Value to return in caseof error. */ /* Define the macro. */ #define MAKE_GET(attribute,type,bad) \ static type Get##attribute( AstRegion *this_region, int *status ) { \ \ /* Local Variables: */ \ AstStc *this; /* Pointer to the Stc structure */ \ \ /* Check the global error status. */ \ if ( !astOK ) return (bad); \ \ /* Get the value from the encapsulated Region. */ \ this = (AstStc *) this_region; \ return astGet##attribute( this->region ); \ } /* Use the above macro to create accessors for the MeshSize, Closed and FillFactor attributes. */ MAKE_GET(FillFactor,double,AST__BAD) MAKE_GET(MeshSize,int,100) MAKE_GET(Closed,int,1) MAKE_GET(Negated,int,0) /* Undefine the macro. */ #undef MAKE_GET /* * Name: * MAKE_TEST * Purpose: * Define a function to test an attribute value for a Stc. * Type: * Private macro. * Synopsis: * #include "stc.h" * MAKE_TEST(attribute) * Class Membership: * Defined by the Stc class. * Description: * This macro expands to an implementation of a private member function * of the form: * * static int Test<Attribute>( AstRegion *this ) * * that test the value of a specified Region attribute from the encapsulated * Region. * Parameters: * attribute * Name of the attribute, as it appears in the function name. * type * The C type of the attribute. */ /* Define the macro. */ #define MAKE_TEST(attribute) \ static int Test##attribute( AstRegion *this_region, int *status ) { \ \ /* Local Variables: */ \ AstStc *this; /* Pointer to the Stc structure */ \ \ /* Check the global error status. */ \ if ( !astOK ) return 0; \ \ /* Test the value from the encapsulated Region. */ \ this = (AstStc *) this_region; \ return astTest##attribute( this->region ); \ } /* Use the above macro to create accessors for the MeshSize, Closed and FillFactor attributes. */ MAKE_TEST(FillFactor) MAKE_TEST(MeshSize) MAKE_TEST(Closed) MAKE_TEST(Negated) /* Undefine the macro. */ #undef MAKE_TEST static int GetObjSize( AstObject *this_object, int *status ) { /* * Name: * GetObjSize * Purpose: * Return the in-memory size of an Object. * Type: * Private function. * Synopsis: * #include "stc.h" * int GetObjSize( AstObject *this, int *status ) * Class Membership: * Stc member function (over-rides the astGetObjSize protected * method inherited from the parent class). * Description: * This function returns the in-memory size of the supplied Stc, * in bytes. * Parameters: * this * Pointer to the Stc. * status * Pointer to the inherited status variable. * Returned Value: * The Object size, in bytes. * Notes: * - A value of zero will be returned if this function is invoked * with the global status set, or if it should fail for any reason. */ /* Local Variables: */ AstStc *this; /* Pointer to Stc structure */ int result; /* Result value to return */ int i; /* AstroCoords index */ /* Initialise. */ result = 0; /* Check the global error status. */ if ( !astOK ) return result; /* Obtain a pointers to the Stc structure. */ this = (AstStc *) this_object; /* Invoke the GetObjSize method inherited from the parent class, and then add on any components of the class structure defined by thsi class which are stored in dynamically allocated memory. */ result = (*parent_getobjsize)( this_object, status ); result += astGetObjSize( this->region ); if( this->coord ) { for( i = 0; i < this->ncoord; i++ ) { result += astGetObjSize( this->coord[ i ] ); } result += astTSizeOf( this->coord ); } /* If an error occurred, clear the result value. */ if ( !astOK ) result = 0; /* Return the result, */ return result; } static const char *GetAttrib( AstObject *this_object, const char *attrib, int *status ) { /* * Name: * GetAttrib * Purpose: * Get the value of a specified attribute for a Stc. * Type: * Private function. * Synopsis: * #include "stc.h" * const char *GetAttrib( AstObject *this, const char *attrib, int *status ) * Class Membership: * Stc member function (over-rides the protected astGetAttrib * method inherited from the Region class). * Description: * This function returns a pointer to the value of a specified * attribute for a Stc, formatted as a character string. * Parameters: * this * Pointer to the Stc. * attrib * Pointer to a null-terminated string containing the name of * the attribute whose value is required. This name should be in * lower case, with all white space removed. * status * Pointer to the inherited status variable. * Returned Value: * - Pointer to a null-terminated string containing the attribute * value. * Notes: * - The returned string pointer may point at memory allocated * within the Stc, or at static memory. The contents of the * string may be over-written or the pointer may become invalid * following a further invocation of the same function or any * modification of the Stc. A copy of the string should * therefore be made if necessary. * - A NULL pointer will be returned if this function is invoked * with the global error status set, or if it should fail for any * reason. */ /* Local Variables: */ AstStc *this; /* Pointer to the Stc structure */ const char *result; /* Pointer value to return */ int len; /* Length of attrib string */ /* Initialise. */ result = NULL; /* Check the global error status. */ if ( !astOK ) return result; /* Obtain a pointer to the Stc structure. */ this = (AstStc *) this_object; /* Obtain the length of the attrib string. */ len = strlen( attrib ); /* Compare "attrib" with each recognised attribute name in turn, obtaining the value of the required attribute. If necessary, write the value into "buff" as a null-terminated string in an appropriate format. Set "result" to point at the result string. */ /* RegionClass. */ /* ------------ */ if ( !strcmp( attrib, "regionclass" ) ) { result = astGetClass( this->region ); /* Not recognised. */ /* --------------- */ /* If the attribute name was not recognised, pass it on to the parent method for further interpretation. */ } else { result = (*parent_getattrib)( this_object, attrib, status ); } /* Return the result. */ return result; } static int GetBounded( AstRegion *this_region, int *status ) { /* * Name: * GetBounded * Purpose: * Is the Region bounded? * Type: * Private function. * Synopsis: * #include "stc.h" * int GetBounded( AstRegion *this, int *status ) * Class Membership: * Stc method (over-rides the astGetBounded method inherited from * the Region class). * Description: * This function returns a flag indicating if the Region is bounded. * The implementation provided by the base Region class is suitable * for Region sub-classes representing the inside of a single closed * curve (e.g. Circle, Ellipse, Box, etc). Other sub-classes (such as * Stc, PointList, etc ) may need to provide their own implementations. * Parameters: * this * Pointer to the Region. * status * Pointer to the inherited status variable. * Returned Value: * Non-zero if the Region is bounded. Zero otherwise. */ /* Local Variables: */ AstStc *this; /* Pointer to Stc structure */ AstRegion *reg; /* Pointer to the encapsulated Region */ int neg; /* Negated flag to use */ int neg_old; /* Original Negated flag */ int result; /* Returned result */ /* Initialise */ result = 0; /* Check the global error status. */ if ( !astOK ) return result; /* Get a pointer to the Stc structure. */ this = (AstStc *) this_region; /* Get the encapsulated Region, and the Negated value which should be used with it. The returned values take account of whether the supplied Stc has itself been Negated or not. The returned Region represent a region within the base Frame of the FrameSet encapsulated by the parent Region structure. */ GetRegion( this, &reg, &neg, status ); /* Temporarily set the Negated attribute to the required value.*/ neg_old = astGetNegated( reg ); astSetNegated( reg, neg ); /* See if the encapsulated Region is bounded. */ result = astGetBounded( reg ); /* Re-instate the original value for the Negated attribute of the encapsulated Region. */ if( reg ) astSetNegated( reg, neg_old ); /* Free resources. */ reg = astAnnul( reg ); /* Return zero if an error occurred. */ if( !astOK ) result = 0; /* Return the required pointer. */ return result; } static AstRegion *GetDefUnc( AstRegion *this_region, int *status ) { /* * Name: * GetDefUnc * Purpose: * Obtain a pointer to the default uncertainty Region for a given Region. * Type: * Private function. * Synopsis: * #include "stc.h" * AstRegion *GetDefUnc( AstRegion *this ) * Class Membership: * Stc method (over-rides the astGetDefUnc method inherited from * the Region class). * This function returns a pointer to a Region which represents the * default uncertainty associated with a position on the boundary of the * given Region. The returned Region refers to the base Frame within the * FrameSet encapsulated by the supplied Region. * Parameters: * this * Pointer to the Region. * Returned Value: * A pointer to the Region. This should be annulled (using astAnnul) * when no longer needed. * Notes: * - A NULL pointer will be returned if this function is invoked * with the global error status set, or if it should fail for any * reason. */ /* Local Variables: */ AstStc *this; /* Pointer to the Stc structure */ AstRegion *result; /* Returned pointer */ /* Initialise */ result = NULL; /* Check the global error status. */ if ( !astOK ) return result; /* Get a pointer to the Stc structure. */ this = (AstStc *) this_region; /* If the encapsulated region has non-default uncertainty, use it as the default uncertainty for the Cmpregion. Note, the current Frame of an uncertainty Region is assumed to be the same as the base Frame in the Stc. */ if( astTestUnc( this->region ) ) { result = astGetUncFrm( this->region, AST__CURRENT ); /* Otherwise, use the parent method to determine the default uncertainty. */ } else { result = (* parent_getdefunc)( this_region, status ); } /* Return NULL if an error occurred. */ if( !astOK ) result = astAnnul( result ); /* Return the required pointer. */ return result; } static void GetRegion( AstStc *this, AstRegion **reg, int *neg, int *status ) { /* * * Name: * GetRegion * Purpose: * Get the encapsulated Region of a Stc. * Type: * Private function. * Synopsis: * #include "region.h" * void GetRegion( AstStc *this, AstRegion **reg, int *neg, int *status ) * Class Membership: * Stc member function * Description: * This function returns a pointer to a Region which is equivalent to * the supplied Stc. If the Stc has been negated, then the returned * "negated" flag will be set such that it represents the negated Stc. * * The current Frames in returned encapsulated Region will be equivalent * to the base Frame in the FrameSet encapsulated by the parent Region * structure. * Parameters: * this * Pointer to the Stc. * reg * Address of a location to receive a pointer to the encapsulated * Region. The current Frame in this region will be equivalent to * the base Frame in the FrameSet * neg * The value of the Negated attribute to be used with reg. * status * Pointer to the inherited status variable. * Notes: * - Any changes made to the encapsulated Region using the returned * pointer will be reflected in the supplied Stc. */ /* Initialise */ if( reg ) *reg = NULL; /* Check the global error status. */ if ( !astOK ) return; /* Return the component Region pointers. */ if( reg ) *reg = astClone( this->region ); /* Initialise the other returned items. Note, the Stc initialiser stored a deep copy of the supplied encapsulated Region, and so we do not need to worry about attributes of the Region having been changed after the creation of the Stc. This is different to the CmpMap class which merely clones its supplied component pointers and so has to save copies of the original Invert settings within the CmpMap structure. */ if( neg ) *neg = astGetNegated( this->region ); /* If the Stc has been inverted, we modify the boolean operator and negation flags so that they reflect the inverted Stc. */ if( astGetNegated( this ) && neg ) *neg = *neg ? 0 : 1; } static const char *GetRegionClass( AstStc *this, int *status ){ /* *+ * Name: * astGetRegionClass * Purpose: * Get the value of a RegionClass attribute for a Stc. * Type: * Protected function. * Synopsis: * #include "stc.h" * const char *astGetRegionClass( AstStc *this ) * Class Membership: * Stc virtual function * Description: * This function returns a pointer to the value of the RegionClass * attribute for a Stc. * Parameters: * this * Pointer to the Stc. * Returned Value: * - Pointer to a null-terminated string containing the attribute * value. * Notes: * - The returned string pointer may point at memory allocated * within the Stc, or at static memory. The contents of the * string may be over-written or the pointer may become invalid * following a further invocation of the same function or any * modification of the Stc. A copy of the string should * therefore be made if necessary. * - A NULL pointer will be returned if this function is invoked * with the global error status set, or if it should fail for any * reason. *- */ /* Check the global error status. */ if ( !astOK ) return NULL; /* Obtain and return the class of the encapsulated Region. */ return astGetClass( ((AstStc *) this)->region ); } static AstKeyMap *GetStcCoord( AstStc *this, int icoord, int *status ){ /* *++ * Name: c astGetStcCoord f AST_GETSTCCOORD * Purpose: * Return information about an AstroCoords element stored in an Stc. * Type: * Public virtual function. * Synopsis: c #include "specframe.h" c AstKeyMap *astGetStcCoord( AstStc *this, int icoord ) f RESULT = AST_GETSTCCOORD( THIS, ICOORD, STATUS ) * Class Membership: * Stc method. * Description: * When any sub-class of Stc is created, the constructor function * allows one or more AstroCoords elements to be stored within the Stc. * This function allows any one of these AstroCoords elements to be * retrieved. The format of the returned information is the same as * that used to pass the original information to the Stc constructor. * That is, the information is returned in a KeyMap structure * containing elements with one or more of the keys given by symbolic * constants AST__STCNAME, AST__STCVALUE, AST__STCERROR, AST__STCRES, * AST__STCSIZE and AST__STCPIXSZ. * * If the coordinate system represented by the Stc has been changed * since it was created (for instance, by changing its System * attribute), then the sizes and positions in the returned KeyMap * will reflect the change in coordinate system. * Parameters: c this f THIS = INTEGER (Given) * Pointer to the Stc. c icoord f ICOORD = INTEGER (Given) * The index of the AstroCoords element required. The first has index * one. The number of AstroCoords elements in the Stc can be found using c function astGetStcNcoord. f function AST_GETSTCNCOORD. f STATUS = INTEGER (Given and Returned) f The global status. * Returned Value: c astGetStcCoord() f AST_GETSTCCOORD = INTEGER * A pointer to a new KeyMap containing the required information. * Notes: * - A null Object pointer (AST__NULL) will be returned if this c function is invoked with the AST error status set, or if it f function is invoked with STATUS set to an error value, or if it * should fail for any reason. *-- */ /* Local Variables: */ AstFrame *frm; AstKeyMap *result; AstMapping *map; AstMapping *smap; AstObject *obj; AstRegion *reg; AstRegion *rereg; AstRegion *srereg; int ikey; int nc; /* Initialise. */ result = NULL; /* Check the global error status. */ if ( !astOK ) return result; /* Validate the supplied index. */ nc = astGetStcNCoord( this ); if( icoord < 1 || icoord > nc ) { astError( AST__STCIND, "astGetStcCoord(%s): Supplied AstroCoords " "index (%d) is invalid.", status, astGetClass( this ), icoord ); if( icoord < 1 ) { astError( AST__STCIND, "The index of the first AstroCoord " "element is one, not zero." , status); } else if( nc == 0 ) { astError( AST__STCIND, "There are no AstroCoords elements in " "the supplied %s.", status, astGetClass( this ) ); } else if( nc == 1 ) { astError( AST__STCIND, "There is 1 AstroCoords element in " "the supplied %s.", status, astGetClass( this ) ); } else { astError( AST__STCIND, "There are %d AstroCoords elements in " "the supplied %s.", status, nc, astGetClass( this ) ); } /* If the index is OK, initialise the returned KeyMap to be a copy of the KeyMap holding information about the required AstroCoords element.*/ } else { result = astCopy( this->coord[ icoord - 1 ] ); /* The Regions stored within this KeyMap describe regions within the base Frame of the parent Region structure. If the Mapping from base to current Frame in the parent Region structure is not a UnitMap, we need to change these to represent regions within the current Frame of the parent Region structure. */ map = astGetMapping( ((AstRegion *)this)->frameset, AST__BASE, AST__CURRENT ); smap = astSimplify( map ); frm = astGetFrame( ((AstRegion *)this)->frameset, AST__CURRENT ); /* If the Frame represented by the Region has changed, erase the Names element since they may no longer be correct. */ if( !astIsAUnitMap( smap ) ) astMapRemove( result, AST__STCNAME ); /* Loop round keys for which a Region may be stored in the KeyMap. */ for( ikey = 0; ikey < NREG; ikey++ ) { /* If the KeyMap contains a Region for this key, get a pointer to it. */ if( astMapGet0A( result, regkey[ ikey ], &obj ) ){ reg = (AstRegion *) obj; /* Sets its RegionFS attribute so that the encapsulated FrameSet will be included in any dump of the Region. This is needed since the returned Region pointer will have no parent Region from which the FrameSet can be determined. */ astSetRegionFS( reg, 1 ); /* If necessary, remap the Region into the current Frame, and simplify. */ if( !astIsAUnitMap( smap ) ) { rereg = astMapRegion( reg, smap, frm ); srereg = astSimplify( rereg ); rereg = astAnnul( rereg ); } else { srereg = astClone( reg ); } /* Replace the Region in the KeyMap with the remapped Region. */ astMapPut0A( result, regkey[ ikey ], srereg, NULL ); /* Free resources */ reg = astAnnul( reg ); srereg = astAnnul( srereg ); } } frm = astAnnul( frm ); map = astAnnul( map ); smap = astAnnul( smap ); /* Annul the returned KeyMap if an error has occurred. */ if( !astOK ) result = astAnnul( result ); } /* Return the pointer */ return result; } static int GetStcNCoord( AstStc *this, int *status ){ /* *++ * Name: c astGetStcNCoord f AST_GETSTCNCOORD * Purpose: * Return the number of AstroCoords elements stored in an Stc. * Type: * Public virtual function. * Synopsis: c #include "stc.h" c int astGetStcNCoord( AstStc *this ) f RESULT = AST_GETSTCNCOORD( THIS, STATUS ) * Class Membership: * Stc method. * Description: * This function returns the number of AstroCoords elements stored in * an Stc. * Parameters: c this f THIS = INTEGER (Given) * Pointer to the Stc. f STATUS = INTEGER (Given and Returned) f The global status. * Returned Value: c astGetStcNCoord() f AST_GETSTCNCOORD = INTEGER * The number of AstroCoords elements stored in the Stc. * Notes: * - Zero will be returned if this c function is invoked with the AST error status set, or if it f function is invoked with STATUS set to an error value, or if it * should fail for any reason. *-- */ /* Return the required value. */ return astOK ? this->ncoord : 0; } static AstRegion *GetStcRegion( AstStc *this, int *status ) { /* *++ * Name: c astGetStcRegion f AST_GETSTCREGION * Purpose: * Obtain a copy of the encapsulated Region within a Stc. * Type: * Public virtual function. * Synopsis: c #include "stc.h" c AstRegion *astGetStcRegion( AstStc *this ) f RESULT = AST_GETSTCREGION( THIS, STATUS ) * Class Membership: * Region method. * Description: * This function returns a pointer to a deep copy of the Region * supplied when the Stc was created. * Parameters: c this f THIS = INTEGER (Given) * Pointer to the Stc. f STATUS = INTEGER (Given and Returned) f The global status. * Returned Value: c astGetStcRegion() f AST_GETSTCREGION = INTEGER * A pointer to a deep copy of the Region encapsulated within the * supplied Stc. * Notes: * - A null Object pointer (AST__NULL) will be returned if this c function is invoked with the AST error status set, or if it f function is invoked with STATUS set to an error value, or if it * should fail for any reason. *-- */ /* Check the global error status. */ if ( !astOK ) return NULL; /* Return a pointer to a copy of the encapsulated Region. */ return astCopy( this->region ); } static int GetUseDefs( AstObject *this_object, int *status ) { /* * Name: * GetUseDefs * Purpose: * Get the value of the UseDefs attribute for a Stc. * Type: * Private function. * Synopsis: * #include "stc.h" * int GetUseDefs( AstObject *this_object, int *status ) { * Class Membership: * Stc member function (over-rides the protected astGetUseDefs * method inherited from the Region class). * Description: * This function returns the value of the UseDefs attribute for a * Stc, supplying a suitable default. * Parameters: * this * Pointer to the Stc. * status * Pointer to the inherited status variable. * Returned Value: * - The USeDefs value. */ /* Local Variables: */ AstStc *this; /* Pointer to the Stc structure */ int result; /* Value to return */ /* Initialise. */ result = 0; /* Check the global error status. */ if ( !astOK ) return result; /* Obtain a pointer to the Stc structure. */ this = (AstStc *) this_object; /* If the UseDefs value for the Stc has been set explicitly, use the Get method inherited from the parent Region class to get its value. */ if( astTestUseDefs( this ) ) { result = (*parent_getusedefs)( this_object, status ); /* Otherwise, supply a default value equal to the UseDefs value of the encapsulated Region. */ } else { result = astGetUseDefs( this->region ); } /* Return the result. */ return result; } void astInitStcVtab_( AstStcVtab *vtab, const char *name, int *status ) { /* *+ * Name: * astInitStcVtab * Purpose: * Initialise a virtual function table for a Stc. * Type: * Protected function. * Synopsis: * #include "stc.h" * void astInitStcVtab( AstStcVtab *vtab, const char *name ) * Class Membership: * Stc vtab initialiser. * Description: * This function initialises the component of a virtual function * table which is used by the Stc class. * Parameters: * vtab * Pointer to the virtual function table. The components used by * all ancestral classes will be initialised if they have not already * been initialised. * name * Pointer to a constant null-terminated character string which contains * the name of the class to which the virtual function table belongs (it * is this pointer value that will subsequently be returned by the Object * astClass function). *- */ /* Local Variables: */ astDECLARE_GLOBALS /* Pointer to thread-specific global data */ AstObjectVtab *object; /* Pointer to Object component of Vtab */ AstMappingVtab *mapping; /* Pointer to Mapping component of Vtab */ AstRegionVtab *region; /* Pointer to Region component of Vtab */ /* Check the local error status. */ if ( !astOK ) return; /* Get a pointer to the thread specific global data structure. */ astGET_GLOBALS(NULL); /* Initialize the component of the virtual function table used by the parent class. */ astInitRegionVtab( (AstRegionVtab *) vtab, name ); /* Store a unique "magic" value in the virtual function table. This will be used (by astIsAStc) to determine if an object belongs to this class. We can conveniently use the address of the (static) class_check variable to generate this unique value. */ vtab->id.check = &class_check; vtab->id.parent = &(((AstRegionVtab *) vtab)->id); /* Initialise member function pointers. */ /* ------------------------------------ */ /* Store pointers to the member functions (implemented here) that provide virtual methods for this class. */ vtab->GetRegionClass = GetRegionClass; vtab->GetStcRegion = GetStcRegion; vtab->GetStcCoord = GetStcCoord; vtab->GetStcNCoord = GetStcNCoord; /* Save the inherited pointers to methods that will be extended, and replace them with pointers to the new member functions. */ object = (AstObjectVtab *) vtab; mapping = (AstMappingVtab *) vtab; region = (AstRegionVtab *) vtab; parent_getobjsize = object->GetObjSize; object->GetObjSize = GetObjSize; #if defined(THREAD_SAFE) parent_managelock = object->ManageLock; object->ManageLock = ManageLock; #endif parent_clearattrib = object->ClearAttrib; object->ClearAttrib = ClearAttrib; parent_getattrib = object->GetAttrib; object->GetAttrib = GetAttrib; parent_setattrib = object->SetAttrib; object->SetAttrib = SetAttrib; parent_testattrib = object->TestAttrib; object->TestAttrib = TestAttrib; parent_transform = mapping->Transform; mapping->Transform = Transform; parent_simplify = mapping->Simplify; mapping->Simplify = Simplify; parent_setregfs = region->SetRegFS; region->SetRegFS = SetRegFS; parent_equal = object->Equal; object->Equal = Equal; parent_clearclosed = region->ClearClosed; region->ClearClosed = ClearClosed; parent_setclosed = region->SetClosed; region->SetClosed = SetClosed; region->TestClosed = TestClosed; region->GetClosed = GetClosed; parent_regsetattrib = region->RegSetAttrib; region->RegSetAttrib = RegSetAttrib; parent_regclearattrib = region->RegClearAttrib; region->RegClearAttrib = RegClearAttrib; parent_clearnegated = region->ClearNegated; region->ClearNegated = ClearNegated; parent_setnegated = region->SetNegated; region->SetNegated = SetNegated; region->TestNegated = TestNegated; region->GetNegated = GetNegated; parent_setmeshsize = region->SetMeshSize; region->SetMeshSize = SetMeshSize; parent_clearmeshsize = region->ClearMeshSize; region->ClearMeshSize = ClearMeshSize; region->TestMeshSize = TestMeshSize; region->GetMeshSize = GetMeshSize; parent_setfillfactor = region->SetFillFactor; region->SetFillFactor = SetFillFactor; parent_clearfillfactor = region->ClearFillFactor; region->ClearFillFactor = ClearFillFactor; region->TestFillFactor = TestFillFactor; region->GetFillFactor = GetFillFactor; parent_getusedefs = object->GetUseDefs; object->GetUseDefs = GetUseDefs; parent_getdefunc = region->GetDefUnc; region->GetDefUnc = GetDefUnc; /* Store replacement pointers for methods which will be over-ridden by new member functions implemented here. */ region->Overlap = Overlap; region->OverlapX = OverlapX; region->RegBaseBox = RegBaseBox; region->RegBaseMesh = RegBaseMesh; region->RegBasePick = RegBasePick; region->RegPins = RegPins; region->GetBounded = GetBounded; /* Declare the copy constructor, destructor and class dump function. */ astSetCopy( vtab, Copy ); astSetDelete( vtab, Delete ); astSetDump( vtab, Dump, "Stc", "An IVOA Space-Time-Coords object" ); /* If we have just initialised the vtab for the current class, indicate that the vtab is now initialised, and store a pointer to the class identifier in the base "object" level of the vtab. */ if( vtab == &class_vtab ) { class_init = 1; astSetVtabClassIdentifier( vtab, &(vtab->id) ); } } static AstKeyMap *MakeAstroCoordsKeyMap( AstRegion *reg, AstKeyMap *coord, const char *class, int *status ){ /* * Name: * MakeAstroCoordsKeyMap * Purpose: * Create a new KeyMap holding Regions describing a supplied * AstroCoords element. * Type: * Private function. * Synopsis: * #include "stc.h" * AstKeyMap *MakeAstroCoordsKeyMap( AstRegion *reg, AstKeyMap *coord, * const char *class, int *status ) * Class Membership: * Stc member function * Description: * This function returns a pointer to a new KeyMap containing elements * which correspond to the components of an STC AstroCoords element. * The element with key AST__STCNAME holds a vector of character * strings containing the names associated with each of the axies. * The other elements of the returned KeyMap such as AST__STCERROR, * AST__STCRES, etc, hold pointers to Regions describing the error * box, resolution, etc, in the Frame of the supplied Region "reg". * Parameters: * reg * Pointer to the Region in which the AstroCoords is defined. * coordId * An ID (not a pointer) to a KeyMap defining a single <AstroCoords> * element, having elements with keys given by constants AST__STCNAME, * AST__STCVALUE, AST__STCERROR, AST__STCRES, AST__STCSIZE, * AST__STCPIXSZ. Any of these elements may be omitted, but no other * elements should be included. If supplied, the AST__STCNAME element * should be a vector of character string pointers holding the "Name" * item for each axis. Any other supplied elements should be scalar * elements, each holding a pointer to a Region describing the * associated item of ancillary information (error, resolution, size, * pixel size or value). These Regions should refer to the coordinate * system represented by "region". * class * Pointer to a string holding the STC class name. * status * Pointer to the inherited status variable. * Returned Value: * - Pointer to the new KeyMap. * Notes: * - A NULL pointer will be returned if this function is invoked * with the global error status set, or if it should fail for any * reason. */ /* Local Variables: */ AstFrame *frm; /* Pointer to current Frame */ AstFrameSet *fs; /* Pointer to conversion FrameSet */ AstKeyMap *result; /* Pointer value to return */ AstMapping *map; /* Pointer to conversion Mapping */ AstObject *obj; /* Pointer to Object stored in supplied KeyMap */ AstRegion *areg; /* Pointer to remapped Region */ AstRegion *sareg; /* Pointer to simplified remapped Region */ const char *key; /* Current key */ int j; /* Index of key within KeyMap */ int naxes; /* Number of axes in region */ int nkey; /* Number of keys in supplied KeyMap */ int nv; /* Number of values in KeyMap element */ int type; /* Data type of entry */ /* Initialise. */ result = NULL; /* Check the global error status. */ if( !astOK ) return result; /* Confirm it is a genuine KeyMap pointer. */ if( !astIsAKeyMap( coord ) && astOK ) { astError( AST__STCKEY, "astInitStc(%s): Supplied pointer is for " "a %s, not a KeyMap.", status, class, astGetClass( coord ) ); } /* Initialise the new KeyMap to be a copy of the supplied KeyMap. */ result = astCopy( coord ); /* Check the supplied KeyMap is usable. */ naxes = astGetNaxes( reg ); nkey = astMapSize( result ); for( j = 0; j < nkey; j++ ) { key = astMapKey( result, j ); if( key ) { nv = astMapLength( result, key ); type = astMapType( result, key ); /* Check no unknown keys are present in the KeyMap. */ if( strcmp( key, AST__STCNAME ) && strcmp( key, AST__STCVALUE ) && strcmp( key, AST__STCERROR ) && strcmp( key, AST__STCRES ) && strcmp( key, AST__STCSIZE ) && strcmp( key, AST__STCPIXSZ ) ) { astError( AST__STCKEY, "astInitStc(%s): Unknown key " "\"%s\" supplied in an AstroCoords list.", status, class, key ); break; /* Check that the "Name" element is a vector of "naxes" strings. */ } else if( !strcmp( key, AST__STCNAME ) ) { if( nv != naxes ) { astError( AST__STCKEY, "astInitStc(%s): %d \"%s\" " "values supplied in an AstroCoords list, but " "the Stc has %d axes. ", status, class, nv, key, naxes ); break; } else if( type != AST__STRINGTYPE ) { astError( AST__STCKEY, "astInitStc(%s): The \"%s\" " "values supplied in an AstroCoords list are " "not character strings. ", status, class, key ); break; } /* Check that all other elements are scalar. */ } else if( nv != 1 ) { astError( AST__STCKEY, "astInitStc(%s): %d \"%s\" " "values supplied in an AstroCoords list, but " "only one is allowed. ", status, class, nv, key ); break; /* Check that all other elements are AST Object pointers. */ } else if( type != AST__OBJECTTYPE ) { astError( AST__STCKEY, "astInitStc(%s): The \"%s\" " "value supplied in an AstroCoords list is " "not an AST Object pointer. ", status, class, key ); break; /* Check that the Object pointers are not NULL. */ } else { astMapGet0A( result, key, &obj ); if( astOK ) { if( !obj ) { astError( AST__STCKEY, "astInitStc(%s): The \"%s\" " "value supplied in an AstroCoords list is " "a NULL pointer. ", status, class, key ); break; /* Check that the Object pointers are Region pointers. */ } else if( !astIsARegion( obj ) ){ astError( AST__STCKEY, "astInitStc(%s): The \"%s\" " "value supplied in an AstroCoords list is " "a %s, not a Region. ", status, class, key, astGetClass(obj) ); obj = astAnnul( obj ); break; /* Check that the Region pointers can be converted to the coordinate system represented by the supplied Region. */ } else { fs = astConvert( obj, reg, "" ); if( !fs ) { obj = astAnnul( obj ); astError( AST__STCKEY, "astInitStc(%s): The \"%s\" " "value supplied in an AstroCoords list " "cannot be converted to the coordinate " "system of its parent Stc object.", status, class, key ); break; /* If necessary, map the Region into the same frame as the supplied Region, and replace the Region in the returned KeyMap with the remapped Region. Also set the RegionFS attribute to indicate that the FrameSet in the Region does not need to be dumped if it contains a UnitMap. */ } else { map = astGetMapping( fs, AST__BASE, AST__CURRENT ); if( !astIsAUnitMap( map ) ) { frm = astGetFrame( fs, AST__CURRENT ); areg = astMapRegion( (AstRegion *) obj, map, frm ); sareg = astSimplify( areg ); astSetRegionFS( sareg, 0 ); astMapPut0A( result, key, sareg, NULL ); areg = astAnnul( areg ); sareg = astAnnul( sareg ); frm = astAnnul( frm ); } else { astSetRegionFS( (AstRegion *) obj, 0 ); } map = astAnnul( map ); fs = astAnnul( fs ); } obj = astAnnul( obj ); } } } } } /* Free the returned KeyMap if an error has occurred. */ if( !astOK ) result = astAnnul( result ); /* Return the result */ return result; } #if defined(THREAD_SAFE) static int ManageLock( AstObject *this_object, int mode, int extra, AstObject **fail, int *status ) { /* * Name: * ManageLock * Purpose: * Manage the thread lock on an Object. * Type: * Private function. * Synopsis: * #include "object.h" * AstObject *ManageLock( AstObject *this, int mode, int extra, * AstObject **fail, int *status ) * Class Membership: * Stc member function (over-rides the astManageLock protected * method inherited from the parent class). * Description: * This function manages the thread lock on the supplied Object. The * lock can be locked, unlocked or checked by this function as * deteremined by parameter "mode". See astLock for details of the way * these locks are used. * Parameters: * this * Pointer to the Object. * mode * An integer flag indicating what the function should do: * * AST__LOCK: Lock the Object for exclusive use by the calling * thread. The "extra" value indicates what should be done if the * Object is already locked (wait or report an error - see astLock). * * AST__UNLOCK: Unlock the Object for use by other threads. * * AST__CHECKLOCK: Check that the object is locked for use by the * calling thread (report an error if not). * extra * Extra mode-specific information. * fail * If a non-zero function value is returned, a pointer to the * Object that caused the failure is returned at "*fail". This may * be "this" or it may be an Object contained within "this". Note, * the Object's reference count is not incremented, and so the * returned pointer should not be annulled. A NULL pointer is * returned if this function returns a value of zero. * status * Pointer to the inherited status variable. * Returned Value: * A local status value: * 0 - Success * 1 - Could not lock or unlock the object because it was already * locked by another thread. * 2 - Failed to lock a POSIX mutex * 3 - Failed to unlock a POSIX mutex * 4 - Bad "mode" value supplied. * Notes: * - This function attempts to execute even if an error has already * occurred. */ /* Local Variables: */ AstStc *this; /* Pointer to STC structure */ int i; /* Loop count */ int result; /* Returned status value */ /* Initialise */ result = 0; /* Check the supplied pointer is not NULL. */ if( !this_object ) return result; /* Obtain a pointers to the STC structure. */ this = (AstStc *) this_object; /* Invoke the ManageLock method inherited from the parent class. */ if( !result ) result = (*parent_managelock)( this_object, mode, extra, fail, status ); /* Invoke the astManageLock method on any Objects contained within the supplied Object. */ if( !result ) result = astManageLock( this->region, mode, extra, fail ); for( i = 0; i < this->ncoord; i++ ) { if( !result ) result = astManageLock( this->coord[ i ], mode, extra, fail ); } return result; } #endif static int Overlap( AstRegion *this, AstRegion *that, int *status ){ /* * Name: * Overlap * Purpose: * Test if two regions overlap each other. * Type: * Private function. * Synopsis: * #include "stc.h" * int Overlap( AstRegion *this, AstRegion *that, int *status ) * Class Membership: * Stc member function (over-rides the astOverlap method inherited * from the Region class). * Description: * This function returns an integer value indicating if the two * supplied Regions overlap. The two Regions are converted to a commnon * coordinate system before performing the check. If this conversion is * not possible (for instance because the two Regions represent areas in * different domains), then the check cannot be performed and a zero value * is returned to indicate this. * Parameters: * this * Pointer to the first Region. * that * Pointer to the second Region. * status * Pointer to the inherited status variable. * Returned Value: * astOverlap() * A value indicating if there is any overlap between the two Regions. * Possible values are: * * 0 - The check could not be performed because the second Region * could not be mapped into the coordinate system of the first * Region. * * 1 - There is no overlap between the two Regions. * * 2 - The first Region is completely inside the second Region. * * 3 - The second Region is completely inside the first Region. * * 4 - There is partial overlap between the two Regions. * * 5 - The Regions are identical. * * 6 - The second Region is the negation of the first Region. * Notes: * - The returned values 5 and 6 do not check the value of the Closed * attribute in the two Regions. * - A value of zero will be returned if this function is invoked with the * AST error status set, or if it should fail for any reason. */ /* Check the inherited status. */ if ( !astOK ) return 0; /* Invoke the "astOverlap" method on the encapsulated Region. */ return astOverlap( ((AstStc *)this)->region, that ); } static int OverlapX( AstRegion *that, AstRegion *this, int *status ){ /* * Name: * OverlapX * Purpose: * Test if two regions overlap each other. * Type: * Private function. * Synopsis: * #include "stc.h" * int OverlapX( AstRegion *that, AstRegion *this ) * Class Membership: * Stc member function (over-rides the astOverlapX method inherited * from the Region class). * Description: * This function performs the processing for the public astOverlap * method and has exactly the same interface except that the order * of the two arguments is swapped. This is a trick to allow * the astOverlap method to be over-ridden by derived classes on * the basis of the class of either of its two arguments. * * See the astOverlap method for details of the interface. */ /* Local Variables: */ int result; /* Check the inherited status. */ if ( !astOK ) return 0; /* Invoke the "astOverlapX" method on the encapsulated Region. */ result = astOverlap( ((AstStc *)that)->region, this ); /* Swap the returned values 2 and 3 to take account of the swapping of the regions.*/ if( result == 2 ) { result = 3; } else if( result == 3 ) { result = 2; } /* Return the result. */ return result; } static void RegBaseBox( AstRegion *this, double *lbnd, double *ubnd, int *status ){ /* * Name: * RegBaseBox * Purpose: * Returns the bounding box of an un-negated Region in the base Frame of * the encapsulated FrameSet. * Type: * Private function. * Synopsis: * #include "stc.h" * void RegBaseBox( AstRegion *this, double *lbnd, double *ubnd, int *status ) * Class Membership: * Stc member function (over-rides the astRegBaseBox protected * method inherited from the Region class). * Description: * This function returns the upper and lower axis bounds of a Region in * the base Frame of the encapsulated FrameSet, assuming the Region * has not been negated. That is, the value of the Negated attribute * is ignored. * Parameters: * this * Pointer to the Region. * lbnd * Pointer to an array in which to return the lower axis bounds * covered by the Region in the base Frame of the encapsulated * FrameSet. It should have at least as many elements as there are * axes in the base Frame. * ubnd * Pointer to an array in which to return the upper axis bounds * covered by the Region in the base Frame of the encapsulated * FrameSet. It should have at least as many elements as there are * axes in the base Frame. * status * Pointer to the inherited status variable. */ /* Check the global error status. */ if( !astOK ) return; /* Invoke the method on the encapsulated Region. */ astRegBaseBox( ((AstStc *)this)->region, lbnd, ubnd ); } static AstPointSet *RegBaseMesh( AstRegion *this, int *status ){ /* * Name: * RegBaseMesh * Purpose: * Create a new PointSet containing a mesh of points on the boundary of a * Region in its base Frame. * Type: * Private function. * Synopsis: * #include "stc.h" * AstPointSet *astRegBaseMesh( AstRegion *this, int *status ) * Class Membership: * Stc member function (over-rides the astRegBaseMesh protected * method inherited from the Region class). * Description: * This function creates a new PointSet containing a mesh of points on the * boundary of the Region. The points refer to the base Frame of * the encapsulated FrameSet. * Parameters: * this * Pointer to the Region. * status * Pointer to the inherited status variable. * Returned Value: * Pointer to the PointSet. Annul the pointer using astAnnul when it * is no longer needed. * Notes: * - A NULL pointer is returned if an error has already occurred, or if * this function should fail for any reason. */ /* Check the global error status. */ if( !astOK ) return NULL; /* Invoke the astRegMesh method on the encapsulated Region. This returns a mesh in the current Frame of the encapsulated Region which is the same as the base Frame of the Stc Region. */ return astRegMesh( ((AstStc *)this)->region ); } static AstRegion *RegBasePick( AstRegion *this_region, int naxes, const int *axes, int *status ){ /* * Name: * RegBasePick * Purpose: * Return a Region formed by picking selected base Frame axes from the * supplied Region. * Type: * Private function. * Synopsis: * #include "stc.h" * AstRegion *RegBasePick( AstRegion *this, int naxes, const int *axes, * int *status ) * Class Membership: * Stc member function (over-rides the astRegBasePick protected * method inherited from the Region class). * Description: * This function attempts to return a Region that is spanned by selected * axes from the base Frame of the encapsulated FrameSet of the supplied * Region. This may or may not be possible, depending on the class of * Region. If it is not possible a NULL pointer is returned. * Parameters: * this * Pointer to the Region. * naxes * The number of base Frame axes to select. * axes * An array holding the zero-based indices of the base Frame axes * that are to be selected. * status * Pointer to the inherited status variable. * Returned Value: * Pointer to the Region, or NULL if no region can be formed. * Notes: * - A NULL pointer is returned if an error has already occurred, or if * this function should fail for any reason. */ /* Check the global error status. */ if ( !astOK ) return NULL; /* Invoke the astRegBaePick method on the encapsulated Region. */ return astRegBasePick( ((AstStc *)this_region)->region, naxes, axes ); } static void RegClearAttrib( AstRegion *this_region, const char *attrib, char **base_attrib, int *status ) { /* * Name: * RegClearAttrib * Purpose: * Clear an attribute value for a Region. * Type: * Protected function. * Synopsis: * #include "stc.h" * void RegClearAttrib( AstRegion *this, const char *attrib, * char **base_attrib, int *status ) * Class Membership: * Stc method (over-rides the astRegClearAttrib method inherited from * the Region class). * Description: * This function clears the value of an attribute in both the base and * current Frame in the FrameSet encapsulated within a Region, without * remapping either Frame. * * No error is reported if the attribute is not recognised by the base * Frame. * Parameters: * this * Pointer to the Region. * attrib * Pointer to a null terminated string containing an attribute name. * NOTE, IT SHOULD BE ENTIRELY LOWER CASE. * base_attrib * Address of a location at which to return a pointer to the null * terminated string holding the name of the attribute which was * cleared in the base Frame of the encapsulated FrameSet. This may * differ from the supplied name if the supplied name contains an axis * index and the current->base Mapping in the FrameSet produces an * axis permutation. The returned pointer should be freed using * astFree when no longer needed. A NULL pointer may be supplied in * which case no pointer is returned. * status * Pointer to the inherited status variable. */ /* Local Variables: */ AstStc *this; char *batt; int rep; /* Check the global error status. */ if ( !astOK ) return; /* Get a pointer to the Stc structure. */ this = (AstStc *) this_region; /* Use the RegClearAttrib method inherited from the parent class to clear the attribute in the current and base Frames in the FrameSet encapsulated by the parent Region structure. */ (*parent_regclearattrib)( this_region, attrib, &batt, status ); /* Now clear the base Frame attribute in the encapsulated Region (the current Frame within the encapsulated Region is equivalent to the base Frame in the parent Region structure). Annul any "attribute unknown" error that results from attempting to do this. */ if( astOK ) { rep = astReporting( 0 ); astRegClearAttrib( this->region, batt, NULL ); if( astStatus == AST__BADAT ) astClearStatus; astReporting( rep ); } /* If required, return the base Frame attribute name, otherwise free it. */ if( base_attrib ) { *base_attrib = batt; } else { batt = astFree( batt ); } } static int RegPins( AstRegion *this, AstPointSet *pset, AstRegion *unc, int **mask, int *status ){ /* * Name: * RegPins * Purpose: * Check if a set of points fall on the boundary of a given Stc. * Type: * Private function. * Synopsis: * #include "stc.h" * int RegPins( AstRegion *this, AstPointSet *pset, AstRegion *unc, * int **mask, int *status ) * Class Membership: * Stc member function (over-rides the astRegPins protected * method inherited from the Region class). * Description: * This function returns a flag indicating if the supplied set of * points all fall on the boundary of the given Stc. * * Some tolerance is allowed, as specified by the uncertainty Region * stored in the supplied Stc "this", and the supplied uncertainty * Region "unc" which describes the uncertainty of the supplied points. * Parameters: * this * Pointer to the Stc. * pset * Pointer to the PointSet. The points are assumed to refer to the * base Frame of the FrameSet encapsulated by "this". * unc * Pointer to a Region representing the uncertainties in the points * given by "pset". The Region is assumed to represent the base Frame * of the FrameSet encapsulated by "this". Zero uncertainity is assumed * if NULL is supplied. * mask * Pointer to location at which to return a pointer to a newly * allocated dynamic array of ints. The number of elements in this * array is equal to the value of the Npoint attribute of "pset". * Each element in the returned array is set to 1 if the * corresponding position in "pset" is on the boundary of the Region * and is set to zero otherwise. A NULL value may be supplied * in which case no array is created. If created, the array should * be freed using astFree when no longer needed. * status * Pointer to the inherited status variable. * Returned Value: * Non-zero if the points all fall on the boundary of the given * Region, to within the tolerance specified. Zero otherwise. */ /* Check the global error status. */ if( !astOK ) return 0; /* Invoke the method on the encapsulated Region. */ return astRegPins( ((AstStc *)this)->region, pset, unc, mask ); } static void RegSetAttrib( AstRegion *this_region, const char *setting, char **base_setting, int *status ) { /* * Name: * RegSetAttrib * Purpose: * Set an attribute value for a Region. * Type: * Private function. * Synopsis: * #include "stc.h" * void RegSetAttrib( AstRegion *this, const char *setting, * char **base_setting, int *status ) * Class Membership: * Stc method (over-rides the astRegSetAttrib method inherited from * the Region class). * Description: * This function assigns an attribute value to both the base and * current Frame in the FrameSet encapsulated within a Region, without * remapping either Frame. * * No error is reported if the attribute is not recognised by the base * Frame. * Parameters: * this * Pointer to the Region. * setting * Pointer to a null terminated attribute setting string. NOTE, IT * SHOULD BE ENTIRELY LOWER CASE. The supplied string will be * interpreted using the public interpretation implemented by * astSetAttrib. This can be different to the interpretation of the * protected accessor functions. For instance, the public * interpretation of an unqualified floating point value for the * Epoch attribute is to interpet the value as a gregorian year, * but the protected interpretation is to interpret the value as an * MJD. * base_setting * Address of a location at which to return a pointer to the null * terminated attribute setting string which was applied to the * base Frame of the encapsulated FrameSet. This may differ from * the supplied setting if the supplied setting contains an axis * index and the current->base Mapping in the FrameSet produces an * axis permutation. The returned pointer should be freed using * astFree when no longer needed. A NULL pointer may be supplied in * which case no pointer is returned. * status * Pointer to the inherited status variable. */ /* Local Variables: */ AstKeyMap *keymap; AstObject *obj; AstRegion *reg; AstStc *this; char *bset; int i; int ikey; int rep; /* Check the global error status. */ if ( !astOK ) return; /* Get a pointer to the Stc structure. */ this = (AstStc *) this_region; /* Use the RegSetAttrib method inherited from the parent class to apply the setting to the current and base Frames in the FrameSet encapsulated by the parent Region structure. */ (*parent_regsetattrib)( this_region, setting, &bset, status ); /* Now apply the base Frame setting to the encapsulated Region (the current Frame within the encapsulated Region is equivalent to the base Frame in the parent Region structure). Annul any "attribute unknown" error that results from attempting to do this. Also do any AstroCoords in the Stc. */ if( astOK ) { rep = astReporting( 0 ); astRegSetAttrib( this->region, bset, NULL ); if( astStatus == AST__BADAT ) astClearStatus; /* Loop round all AstroCoords elements. */ for( i = 0; i < this->ncoord; i++ ) { /* Get a pointer to the KeyMap holding a description of the current AstroCoords element. */ keymap = this->coord[ i ]; /* Loop round all the elements of this KeyMap which may hold a Region pointer. */ for( ikey = 0; ikey < NREG; ikey++ ) { /* If the KeyMap contains a Region for this key, get a pointer to it. */ if( astMapGet0A( keymap, regkey[ ikey ], &obj ) ){ reg = (AstRegion *) obj; /* Modify it by applying the attribute setting. */ astRegSetAttrib( reg, bset, NULL ); if( astStatus == AST__BADAT ) astClearStatus; /* Annul the pointer. */ reg = astAnnul( reg ); } } } astReporting( rep ); } /* If required, return the base Frame setting string, otherwise free it. */ if( base_setting ) { *base_setting = bset; } else { bset = astFree( bset ); } } static void SetAttrib( AstObject *this_object, const char *setting, int *status ) { /* * Name: * SetAttrib * Purpose: * Set an attribute value for a Stc. * Type: * Private function. * Synopsis: * #include "stc.h" * void SetAttrib( AstObject *this, const char *setting, int *status ) * Class Membership: * Stc member function (over-rides the astSetAttrib method inherited * from the Region class). * Description: * This function assigns an attribute value for a Stc, the * attribute and its value being specified by means of a string of * the form: * * "attribute= value " * * Here, "attribute" specifies the attribute name and should be in * lower case with no white space present. The value to the right * of the "=" should be a suitable textual representation of the * value to be assigned and this will be interpreted according to * the attribute's data type. White space surrounding the value is * only significant for string attributes. * Parameters: * this * Pointer to the Stc. * setting * Pointer to a null terminated string specifying the new attribute * value. * status * Pointer to the inherited status variable. * Notes: * - This function uses one-based axis numbering so that it is * suitable for external (public) use. */ /* Local Vaiables: */ AstStc *this; /* Pointer to the Stc structure */ int len; /* Length of setting string */ int nc; /* Number of characters read by astSscanf */ /* Check the global error status. */ if ( !astOK ) return; /* Obtain a pointer to the Stc structure. */ this = (AstStc *) this_object; /* Obtain the length of the setting string. */ len = strlen( setting ); /* Test for each recognised attribute in turn, using "astSscanf" to parse the setting string and extract the attribute value (or an offset to it in the case of string values). In each case, use the value set in "nc" to check that the entire string was matched. Once a value has been obtained, use the appropriate method to set it. */ /* (none as yet) */ /* Read-only attributes. */ /* --------------------- */ /* Define a macro to see if the setting string matches any of the read-only attributes of this class. */ #define MATCH(attrib) \ ( nc = 0, ( 0 == astSscanf( setting, attrib "=%*[^\n]%n", &nc ) ) && \ ( nc >= len ) ) /* Use this macro to report an error if a read-only attribute has been specified. */ if ( MATCH( "regionclass" ) ) { astError( AST__NOWRT, "astSet: The setting \"%s\" is invalid for a %s.", status, setting, astGetClass( this ) ); astError( AST__NOWRT, "This is a read-only attribute." , status); /* Not recognised. */ /* --------------- */ /* If the attribute is still not recognised, pass it on to the parent method for further interpretation. */ } else { (*parent_setattrib)( this_object, setting, status ); } /* Undefine macros local to this function. */ #undef MATCH } static void SetRegFS( AstRegion *this_region, AstFrame *frm, int *status ) { /* * Name: * SetRegFS * Purpose: * Stores a new FrameSet in a Region * Type: * Private function. * Synopsis: * #include "stc.h" * void SetRegFS( AstRegion *this_region, AstFrame *frm, int *status ) * Class Membership: * Stc method (over-rides the astSetRegFS method inherited from * the Region class). * Description: * This function creates a new FrameSet and stores it in the supplied * Region. The new FrameSet contains two copies of the supplied * Frame, connected by a UnitMap. * Parameters: * this * Pointer to the Region. * frm * The Frame to use. * status * Pointer to the inherited status variable. */ /* Local Variables: */ AstRegion *creg; /* Pointer to encapsulated Region structure */ /* Check the global error status. */ if ( !astOK ) return; /* Invoke the parent method to store the FrameSet in the parent Region structure. */ (* parent_setregfs)( this_region, frm, status ); /* If the encapsulated Region has a dummy FrameSet use this method recursively to give it the same FrameSet. */ creg = ((AstStc *) this_region )->region; if( creg && !astGetRegionFS( creg ) ) astSetRegFS( creg, frm ); } static AstMapping *Simplify( AstMapping *this_mapping, int *status ) { /* * Name: * Simplify * Purpose: * Simplify a Region. * Type: * Private function. * Synopsis: * #include "region.h" * AstMapping *Simplify( AstMapping *this, int *status ) * Class Membership: * Stc method (over-rides the astSimplify method inherited from * the Region class). * Description: * This function simplifies a Stc to eliminate redundant * computational steps, or to merge separate steps which can be * performed more efficiently in a single operation. * Parameters: * this * Pointer to the original Region. * status * Pointer to the inherited status variable. * Returned Value: * A new pointer to the (possibly simplified) Region. * Notes: * - A NULL pointer value will be returned if this function is * invoked with the AST error status set, or if it should fail for * any reason. */ /* Local Variables: */ AstFrame *frm; /* Current Frame */ AstKeyMap *keymap; /* KeyMap holding stroCoords element */ AstMapping *map; /* Base->current Mapping */ AstObject *obj; /* Pointer to object retrieved from keymap */ AstRegion *newreg; /* New encapsulated Region */ AstRegion *reg; /* AstroCoords Region pointer */ AstRegion *treg; /* Temporary Region pointer */ AstStc *stc; /* Returned Stc Structure. */ AstStc *temp; /* Temporary Stc pointer */ int i; /* Index of current AstroCoords element */ int ikey; /* Index of key to be tested */ /* Check the global error status. */ if ( !astOK ) return NULL; /* Invoke the Simplify method of the parent Region class. This simplifies the FrameSet and uncertainty Region in the parent Region structure. */ stc = (AstStc *) (AstRegion *) (* parent_simplify)( this_mapping, status ); /* If the Stc is negated, we can perform a simplication by transferring the negated state from the Stc itself to the encapsulated Region. */ if( astGetNegated( stc ) ) { /* Ensure that modifying "stc" will not modify the supplied Stc, by creating a copy of the supplied Stc, if this has not already been done. */ if( stc == (AstStc *) this_mapping ) { temp = (AstStc *) astCopy( stc ); (void) astAnnul( stc ); stc = temp; } /* Modify "temp" by negating both the Stc structure and its encapsulated Region. */ astNegate( stc ); astNegate( stc->region ); } /* Get the base->current Mapping from the parent Region structure, and the current Frame. */ map = astGetMapping( ((AstRegion *) stc)->frameset, AST__BASE, AST__CURRENT ); frm = astGetFrame( ((AstRegion *) stc)->frameset, AST__CURRENT ); /* We may be able to perform some more simplication on the encapsulated Region itself. If the above mapping is not a unit map, remap the encapsulated Region into the current Frame of the parent Region structure and simplify it. This transfers complication from the Mapping in the parent Region structure to the encapsulated Region. */ if( !astIsAUnitMap( map ) ) { treg = astMapRegion( stc->region, map, frm ); newreg = astSimplify( treg ); treg = astAnnul( treg ); /* If the base->current Mapping in the parent Region structure is a unit map, simplification of the whole Stc is possible if the encapsulated Region (without any remapping) can be simplied. */ } else { newreg = astSimplify( stc->region ); } /* If the encapsulated Region has been changed, store it in the returned Stc. */ if( newreg != stc->region ) { /* Ensure that modifying "stc" will not modify the supplied Stc, by creating a copy of the supplied Stc, if this has not already been done. */ if( stc == (AstStc *) this_mapping ) { temp = (AstStc *) astCopy( stc ); (void) astAnnul( stc ); stc = temp; } /* Store the new region in "stc", annulling the existing Region. */ if( stc ) { (void) astAnnul( stc->region ); stc->region = astClone( newreg ); } /* The encapsulated Region now represents an area in the current Frame represented by the supplied Stc. Since the encapsulated Region is defined as being in the base Frame of the FrameSet in the parent Region structure, the parent FrameSet should just be a UnitMap. Modify it appropriately (if it not already a UnitMap). */ if( !astIsAUnitMap( map ) ) astSetRegFS( stc, frm ); } /* Free resources */ newreg = astAnnul( newreg ); /* Now we do a similar process on any Regions held within an AstroCoords elements. Loop round all AstroCoords elements. */ if( stc ) { for( i = 0; i < stc->ncoord; i++ ) { /* Get a pointewr to the KeyMap holding a description of the current AstroCoords element. */ keymap = stc->coord[ i ]; /* Loop round all the elements of this KeyMap which may hold a Region pointer. */ for( ikey = 0; ikey < NREG; ikey++ ) { /* If the KeyMap contains a Region for this key, get a pointer to it. */ if( astMapGet0A( keymap, regkey[ ikey ], &obj ) ){ reg = (AstRegion *) obj; /* We have two tasks now, firstly to ensure that this AstroCoords Region describes an area in the base Frame of the FrameSet in the parent Region structure (which may have been changed by the earlier simplications performed by this function), and secondly, to attempt to simplify the Region. The Stc structure addressed by the "stc" pointer will have a current Frame given by "frm". This will also be its base Frame, and the base->current Mapping will consequently be a UnitMap. The Mapping from the original base Frame to the new base Frame is given by "map". Unless this is a UnitMap, we need to remap the Region.*/ if( !astIsAUnitMap( map ) ) { treg = astMapRegion( reg, map, frm ); } else { treg = astClone( reg ); } /* Now attempt to simplify the Region.*/ newreg = astSimplify( treg ); /* If the Region has been changed by either of these steps, we need to store the modified Region back in the "stc" structure which is being returned. But we need to be careful we do not modify the supplied Stc structure. */ if( newreg != reg ) { if( stc == (AstStc *) this_mapping ) { temp = astCopy( stc ); (void) astAnnul( stc ); stc = temp; keymap = temp->coord[ i ]; } astMapPut0A( keymap, regkey[ ikey ], newreg, regcom[ ikey ] ); } /* Free resources */ reg = astAnnul( reg ); treg = astAnnul( treg ); newreg = astAnnul( newreg ); } } } } /* Free resources */ map = astAnnul( map ); frm = astAnnul( frm ); /* If an error occurred, annul the returned Mapping. */ if ( !astOK ) stc = astAnnul( stc ); /* Return the result. */ return (AstMapping *) stc; } static int TestAttrib( AstObject *this_object, const char *attrib, int *status ) { /* * Name: * TestAttrib * Purpose: * Test if a specified attribute value is set for a Stc. * Type: * Private function. * Synopsis: * #include "stc.h" * int TestAttrib( AstObject *this, const char *attrib, int *status ) * Class Membership: * Stc member function (over-rides the astTestAttrib protected * method inherited from the Region class). * Description: * This function returns a boolean result (0 or 1) to indicate whether * a value has been set for one of a Stc's attributes. * Parameters: * this * Pointer to the Stc. * attrib * Pointer to a null terminated string specifying the attribute * name. This should be in lower case with no surrounding white * space. * status * Pointer to the inherited status variable. * Returned Value: * One if a value has been set, otherwise zero. * Notes: * - This function uses one-based axis numbering so that it is * suitable for external (public) use. * - A value of zero will be returned if this function is invoked * with the global status set, or if it should fail for any reason. */ /* Local Variables: */ AstStc *this; /* Pointer to the Stc structure */ int len; /* Length of attrib string */ int result; /* Result value to return */ /* Initialise. */ result = 0; /* Check the global error status. */ if ( !astOK ) return result; /* Obtain a pointer to the Stc structure. */ this = (AstStc *) this_object; /* Obtain the length of the attrib string. */ len = strlen( attrib ); /* Check the attribute name and test the appropriate attribute. */ /* Read-only attributes. */ /* --------------------- */ /* Test if the attribute name matches any of the read-only attributes of this class. If it does, then return zero. */ if ( !strcmp( attrib, "regionclass" ) ) { result = 0; /* Not recognised. */ /* --------------- */ /* If the attribute is still not recognised, pass it on to the parent method for further interpretation. */ } else { result = (*parent_testattrib)( this_object, attrib, status ); } /* Return the result, */ return result; } static AstPointSet *Transform( AstMapping *this_mapping, AstPointSet *in, int forward, AstPointSet *out, int *status ) { /* * Name: * Transform * Purpose: * Apply a Stc to transform a set of points. * Type: * Private function. * Synopsis: * #include "stc.h" * AstPointSet *Transform( AstMapping *this, AstPointSet *in, * int forward, AstPointSet *out, int *status ) * Class Membership: * Stc member function (over-rides the astTransform method inherited * from the Region class). * Description: * This function takes a Stc and a set of points encapsulated in a * PointSet and transforms the points so as to apply the required Region. * This implies applying each of the Stc's encapsulated Region in turn, * either in series or in parallel. * Parameters: * this * Pointer to the Stc. * in * Pointer to the PointSet associated with the input coordinate values. * forward * A non-zero value indicates that the forward coordinate transformation * should be applied, while a zero value requests the inverse * transformation. * out * Pointer to a PointSet which will hold the transformed (output) * coordinate values. A NULL value may also be given, in which case a * new PointSet will be created by this function. * status * Pointer to the inherited status variable. * Returned Value: * Pointer to the output (possibly new) PointSet. * Notes: * - A null pointer will be returned if this function is invoked with the * global error status set, or if it should fail for any reason. * - The number of coordinate values per point in the input PointSet must * match the number of coordinates for the Stc being applied. * - If an output PointSet is supplied, it must have space for sufficient * number of points and coordinate values per point to accommodate the * result. Any excess space will be ignored. */ /* Local Variables: */ AstPointSet *ps; /* Pointer to PointSet */ AstPointSet *pset_tmp; /* Pointer to PointSet holding base Frame positions*/ AstPointSet *result; /* Pointer to output PointSet */ AstRegion *reg; /* Pointer to encapsulated Region */ AstStc *this; /* Pointer to the Stc structure */ double **ptr; /* Pointer to axis values */ double **ptr_out; /* Pointer to output coordinate data */ int coord; /* Zero-based index for coordinates */ int good; /* Is the point inside the Stc? */ int ncoord_out; /* No. of coordinates per output point */ int ncoord_tmp; /* No. of coordinates per base Frame point */ int neg; /* Negated value for encapsulated Region */ int neg_old; /* Original Negated flag */ int npoint; /* No. of points */ int point; /* Loop counter for points */ int rep; /* Original error reporting status */ int status_value; /* AST status value */ /* Initialise. */ result = NULL; /* Check the global error status. */ if ( !astOK ) return result; /* Get a Pointer to the Stc structure */ this = (AstStc *) this_mapping; /* Get the encapsulated Region, and the Negated value which should be used with it. The returned values take account of whether the supplied Stc has itself been Negated or not. The returned Region represent a region within the base Frame of the FrameSet encapsulated by the parent Region structure. */ GetRegion( this, &reg, &neg, status ); /* Temporarily set the Negated attribute to the required value.*/ neg_old = astGetNegated( reg ); astSetNegated( reg, neg ); /* Apply the parent mapping using the stored pointer to the Transform member function inherited from the parent Region class. This function validates all arguments and generates an output PointSet if necessary, containing a copy of the input PointSet. */ result = (*parent_transform)( this_mapping, in, forward, out, status ); /* We will now extend the parent astTransform method by performing the calculations needed to generate the output coordinate values. */ /* First use the encapsulated FrameSet in the parent Region structure to transform the supplied positions from the current Frame in the encapsulated FrameSet (the Frame represented by the Stc), to the base Frame (the Frame in which the encapsulated Region are defined). Note, the returned pointer may be a clone of the "in" pointer, and so we must be carefull not to modify the contents of the returned PointSet. */ pset_tmp = astRegTransform( this, in, 0, NULL, NULL ); /* Now transform this PointSet using the encapsulated Region. */ ps = astTransform( reg, pset_tmp, 0, NULL ); /* Determine the numbers of points and coordinates per point for these base Frame PointSets and obtain pointers for accessing the base Frame and output coordinate values. */ npoint = astGetNpoint( pset_tmp ); ncoord_tmp = astGetNcoord( pset_tmp ); ptr = astGetPoints( ps ); ncoord_out = astGetNcoord( result ); ptr_out = astGetPoints( result ); /* Perform coordinate arithmetic. */ /* ------------------------------ */ if ( astOK ) { for ( point = 0; point < npoint; point++ ) { good = 0; for ( coord = 0; coord < ncoord_tmp; coord++ ) { if( ptr[ coord ][ point ] != AST__BAD ) { good = 1; break; } } if( !good ) { for ( coord = 0; coord < ncoord_out; coord++ ) { ptr_out[ coord ][ point ] = AST__BAD; } } } } /* Re-instate the original value for the Negated attribute of the encapsulated Region. Do this even if an error has occurred. */ status_value = astStatus; astClearStatus; rep = astReporting( 0 ); if( reg ) astSetNegated( reg, neg_old ); astReporting( rep ); astSetStatus( status_value ); /* Free resources. */ reg = astAnnul( reg ); ps = astAnnul( ps ); pset_tmp = astAnnul( pset_tmp ); /* If an error occurred, clean up by deleting the output PointSet (if allocated by this function) and setting a NULL result pointer. */ if ( !astOK ) { if ( !out ) result = astDelete( result ); result = NULL; } /* Return a pointer to the output PointSet. */ return result; } /* Stc Attributes: */ /* =============== */ /* *att++ * Name: * RegionClass * Purpose: * The AST class name of the Region encapsulated within an Stc * Type: * Public attribute. * Synopsis: * String, read-only. * Description: * This is a read-only attribute giving the AST class name of the * Region encapsulated within an Stc (that is, the class of the Region * which was supplied when the Stc was created). * Applicability: * Stc * All Stc objects this attribute. *att-- */ /* Copy constructor. */ /* ----------------- */ static void Copy( const AstObject *objin, AstObject *objout, int *status ) { /* * Name: * Copy * Purpose: * Copy constructor for Stc objects. * Type: * Private function. * Synopsis: * void Copy( const AstObject *objin, AstObject *objout, int *status ) * Description: * This function implements the copy constructor for Stc objects. * Parameters: * objin * Pointer to the object to be copied. * objout * Pointer to the object being constructed. * status * Pointer to the inherited status variable. * Returned Value: * void * Notes: * - This constructor makes a deep copy, including a copy of the component * Regions within the Stc. */ /* Local Variables: */ AstStc *in; /* Pointer to input Stc */ AstStc *out; /* Pointer to output Stc */ int i; /* AstroCoords index */ /* Check the global error status. */ if ( !astOK ) return; /* Obtain pointers to the input and output Stcs. */ in = (AstStc *) objin; out = (AstStc *) objout; /* For safety, start by clearing any references to the input component Regions, etc, from the output Stc. */ out->region = NULL; out->coord = NULL; out->ncoord = 0; /* Make a copy of the Region and store a pointer to it in the output Stc structure. */ out->region = astCopy( in->region ); /* Copy any memory holding AstroCoords values */ if( in->coord && in->ncoord ) { out->ncoord = in->ncoord; out->coord = astMalloc( sizeof(AstKeyMap *) * (size_t)in->ncoord ); if( out->coord ) { for( i = 0; i < in->ncoord; i++ ) { out->coord[ i ] = astCopy( in->coord[ i ] ); } } } } /* Destructor. */ /* ----------- */ static void Delete( AstObject *obj, int *status ) { /* * Name: * Delete * Purpose: * Destructor for Stc objects. * Type: * Private function. * Synopsis: * void Delete( AstObject *obj, int *status ) * Description: * This function implements the destructor for Stc objects. * Parameters: * obj * Pointer to the object to be deleted. * status * Pointer to the inherited status variable. * Returned Value: * void * Notes: * This function attempts to execute even if the global error status is * set. */ /* Local Variables: */ AstStc *this; /* Pointer to Stc */ int i; /* AstroCoords index */ /* Obtain a pointer to the Stc structure. */ this = (AstStc *) obj; /* Annul the pointer to the encapsulated Region. */ this->region = astAnnul( this->region ); /* Free any memory holding AstroCoords values */ if( this->coord ) { for( i = 0; i < this->ncoord; i++ ) { this->coord[ i ] = astAnnul( this->coord[ i ] ); } this->coord = astFree( this->coord ); } } /* Dump function. */ /* -------------- */ static void Dump( AstObject *this_object, AstChannel *channel, int *status ) { /* * Name: * Dump * Purpose: * Dump function for Stc objects. * Type: * Private function. * Synopsis: * void Dump( AstObject *this, AstChannel *channel, int *status ) * Description: * This function implements the Dump function which writes out data * for the Stc class to an output Channel. * Parameters: * this * Pointer to the Stc whose data are being written. * channel * Pointer to the Channel to which the data are being written. * status * Pointer to the inherited status variable. */ /* Local Constants: */ #define COMMENT_LEN 150 /* Maximum length of a comment string */ #define KEY_LEN 50 /* Maximum length of a keyword */ /* Local Variables: */ AstStc *this; /* Pointer to the Stc structure */ char comment[ COMMENT_LEN + 1 ]; /* Buffer for comment string */ char key[ KEY_LEN + 1 ]; /* Buffer for keyword string */ int ico; /* Loop counter for KeyMaps */ /* Check the global error status. */ if ( !astOK ) return; /* Obtain a pointer to the Stc structure. */ this = (AstStc *) this_object; /* Write out values representing the instance variables for the Stc class. Accompany these with appropriate comment strings, possibly depending on the values being written.*/ /* In the case of attributes, we first use the appropriate (private) Test... member function to see if they are set. If so, we then use the (private) Get... function to obtain the value to be written out. For attributes which are not set, we use the astGet... method to obtain the value instead. This will supply a default value (possibly provided by a derived class which over-rides this method) which is more useful to a human reader as it corresponds to the actual default attribute value. Since "set" will be zero, these values are for information only and will not be read back. */ /* Encapsulated Region. */ /* -------------------- */ astWriteObject( channel, "Region", 1, 1, this->region, "STC Region" ); /* AstroCoords info */ /* ---------------- */ astWriteInt( channel, "Ncoord", ( this->ncoord != 0 ), 0, this->ncoord, "Number of AstroCoords elements" ); for ( ico = 1; ico <= this->ncoord; ico++ ) { (void) sprintf( key, "Coord%d", ico ); (void) sprintf( comment, "AstroCoords number %d", ico ); astWriteObject( channel, key, 1, 1, this->coord[ ico - 1 ], comment ); } /* Undefine macros local to this function. */ #undef COMMENT_LEN #undef KEY_LEN } /* Standard class functions. */ /* ========================= */ /* Implement the astIsAStc and astCheckStc functions using the macros defined for this purpose in the "object.h" header file. */ astMAKE_ISA(Stc,Region) astMAKE_CHECK(Stc) AstStc *astInitStc_( void *mem, size_t size, int init, AstStcVtab *vtab, const char *name, AstRegion *region, int ncoords, AstKeyMap **coords, int *status ) { /* *+ * Name: * astInitStc * Purpose: * Initialise a Stc. * Type: * Protected function. * Synopsis: * #include "stc.h" * AstStc *astInitStc( void *mem, size_t size, int init, AstStcVtab *vtab, * const char *name, AstRegion *region, int ncoords, * AstKeyMap **coords ) * Class Membership: * Stc initialiser. * Description: * This function is provided for use by class implementations to initialise * a new Stc object. It allocates memory (if necessary) to * accommodate the Stc plus any additional data associated with the * derived class. It then initialises a Stc structure at the start * of this memory. If the "init" flag is set, it also initialises the * contents of a virtual function table for a Stc at the start of * the memory passed via the "vtab" parameter. * Parameters: * mem * A pointer to the memory in which the Stc is to be initialised. * This must be of sufficient size to accommodate the Stc data * (sizeof(Stc)) plus any data used by the derived class. If a * value of NULL is given, this function will allocate the memory itself * using the "size" parameter to determine its size. * size * The amount of memory used by the Stc (plus derived class * data). This will be used to allocate memory if a value of NULL is * given for the "mem" parameter. This value is also stored in the * Stc structure, so a valid value must be supplied even if not * required for allocating memory. * init * A logical flag indicating if the Stc's virtual function table * is to be initialised. If this value is non-zero, the virtual function * table will be initialised by this function. * vtab * Pointer to the start of the virtual function table to be associated * with the new Stc. * name * Pointer to a constant null-terminated character string which contains * the name of the class to which the new object belongs (it is this * pointer value that will subsequently be returned by the Object * astClass function). * region * Pointer to the Region represented by the Stc. * ncoords * Number of KeyMap pointers supplied in "coords". Can be zero. * Ignored if "coords" is NULL. * coords * Pointer to an array of "ncoords" KeyMap pointers, or NULL if * "ncoords" is zero. Each KeyMap defines defines a single <AstroCoords> * element, and should have elements with keys given by constants * AST__STCNAME, AST__STCVALUE, AST__STCERROR, AST__STCRES, AST__STCSIZE, * AST__STCPIXSZ. Any of these elements may be omitted, but no other * elements should be included. If supplied, the AST__STCNAME element * should be a vector of character string pointers holding the "Name" * item for each axis. Any other supplied elements should be scalar * elements, each holding a pointer to a Region describing the * associated item of ancillary information (error, resolution, size, * pixel size or value). These Regions should describe a volume within * the coordinate system represented by "region". * Returned Value: * A pointer to the new Stc. * Notes: * - A null pointer will be returned if this function is invoked with the * global error status set, or if it should fail for any reason. *- */ /* Local Variables: */ AstMapping *frm; /* Current Frame in supplied Stc */ AstMapping *map; /* Base -> Current Mapping in supplied Stc */ AstRegion *reg; /* Copy of supplied Region */ AstStc *new; /* Pointer to new Stc */ int i; /* AstroCoords index */ /* Check the global status. */ if ( !astOK ) return NULL; /* If necessary, initialise the virtual function table. */ if ( init ) astInitStcVtab( vtab, name ); /* Initialise. */ new = NULL; /* If the supplied Region is an Stc, create a new Region by mapping the encapsulated Region within the supplied Stc into the current Frame of the Stc. */ if( astIsAStc( region ) ) { map = astGetMapping( region->frameset, AST__BASE, AST__CURRENT ); frm = astGetFrame( region->frameset, AST__CURRENT ); reg = astMapRegion( ((AstStc *) region)->region, map, frm ); frm = astAnnul( frm ); map = astAnnul( map ); /* Otherwise, just take a copy of the supplied Region. */ } else { reg = astCopy( region ); } /* Initialise a Region structure (the parent class) as the first component within the Stc structure, allocating memory if necessary. A NULL PointSet is suppled as the encapsulated Region will perform the function of defining the Region shape. The base Frame of the FrameSet in the parent Region structure will be the same as the current Frames of the FrameSets in the two encapsulated Region. */ if ( astOK ) { new = (AstStc *) astInitRegion( mem, size, 0, (AstRegionVtab *) vtab, name, reg, NULL, NULL ); /* Initialise the Stc data. */ /* --------------------------- */ /* Store a pointer to the encapsulated Region. */ new->region = astClone( reg ); /* No AstroCoords info as yet. */ new->ncoord = 0; new->coord = NULL; /* Transfer attributes from the encapsulated region to the parent region. */ astRegOverlay( new, reg, 1 ); if( astTestIdent( reg ) ) astSetIdent( new, astGetIdent( reg ) ); /* If the base->current Mapping in the FrameSet within the encapsulated Region is a UnitMap, then the FrameSet does not need to be included in the Dump of the new Stc. Set the RegionFS attribute of the encapsulated Region to zero to flag this. Note, we do this after the previous class to astRegOverlay because we do not want this zero value for RegionFS to be copied into the new Stc object. */ astSetRegionFS( reg, 0 ); /* For each supplied AstroCoords, create a new KeyMap holding Regions representing the various elements of the AstroCoords, and store the new KeyMap in the Stc structure. */ if( coords && ncoords > 0 ) { new->ncoord = ncoords; new->coord = astMalloc( sizeof( AstKeyMap *)*(size_t) ncoords ); if( new->coord ) { for( i = 0; i < ncoords; i++ ) { new->coord[ i ] = MakeAstroCoordsKeyMap( reg, coords[ i ], name, status ); } } } /* If an error occurred, clean up deleting the new object. */ if ( !astOK ) new = astDelete( new ); } /* Free resources */ reg = astAnnul( reg ); /* Return a pointer to the new object. */ return new; } AstStc *astLoadStc_( void *mem, size_t size, AstStcVtab *vtab, const char *name, AstChannel *channel, int *status ) { /* *+ * Name: * astLoadStc * Purpose: * Load a Stc. * Type: * Protected function. * Synopsis: * #include "stc.h" * AstStc *astLoadStc( void *mem, size_t size, AstStcVtab *vtab, * const char *name, AstChannel *channel ) * Class Membership: * Stc loader. * Description: * This function is provided to load a new Stc using data read * from a Channel. It first loads the data used by the parent class * (which allocates memory if necessary) and then initialises a * Stc structure in this memory, using data read from the input * Channel. * * If the "init" flag is set, it also initialises the contents of a * virtual function table for a Stc at the start of the memory * passed via the "vtab" parameter. * Parameters: * mem * A pointer to the memory into which the Stc is to be * loaded. This must be of sufficient size to accommodate the * Stc data (sizeof(Stc)) plus any data used by derived * classes. If a value of NULL is given, this function will * allocate the memory itself using the "size" parameter to * determine its size. * size * The amount of memory used by the Stc (plus derived class * data). This will be used to allocate memory if a value of * NULL is given for the "mem" parameter. This value is also * stored in the Stc structure, so a valid value must be * supplied even if not required for allocating memory. * * If the "vtab" parameter is NULL, the "size" value is ignored * and sizeof(AstStc) is used instead. * vtab * Pointer to the start of the virtual function table to be * associated with the new Stc. If this is NULL, a pointer to * the (static) virtual function table for the Stc class is * used instead. * name * Pointer to a constant null-terminated character string which * contains the name of the class to which the new object * belongs (it is this pointer value that will subsequently be * returned by the astGetClass method). * * If the "vtab" parameter is NULL, the "name" value is ignored * and a pointer to the string "Stc" is used instead. * Returned Value: * A pointer to the new Stc. * Notes: * - A null pointer will be returned if this function is invoked * with the global error status set, or if it should fail for any * reason. *- */ /* Local Constants: */ astDECLARE_GLOBALS /* Pointer to thread-specific global data */ #define KEY_LEN 50 /* Maximum length of a keyword */ /* Local Variables: */ AstFrame *f1; /* Base Frame in parent Region */ AstObject *obj; /* Pointer to Object retrieved from KeyMap */ AstRegion *creg; /* Pointer to encapsulated Region */ AstStc *new; /* Pointer to the new Stc */ char key[ KEY_LEN + 1 ]; /* Buffer for keyword string */ int ico; /* Loop counter for AstroCoords */ int ikey; /* Index of KeyMap */ /* Get a pointer to the thread specific global data structure. */ astGET_GLOBALS(channel); /* Initialise. */ new = NULL; /* Check the global error status. */ if ( !astOK ) return new; /* If a NULL virtual function table has been supplied, then this is the first loader to be invoked for this Stc. In this case the Stc belongs to this class, so supply appropriate values to be passed to the parent class loader (and its parent, etc.). */ if ( !vtab ) { size = sizeof( AstStc ); vtab = &class_vtab; name = "Stc"; /* If required, initialise the virtual function table for this class. */ if ( !class_init ) { astInitStcVtab( vtab, name ); class_init = 1; } } /* Invoke the parent class loader to load data for all the ancestral classes of the current one, returning a pointer to the resulting partly-built Stc. */ new = astLoadRegion( mem, size, (AstRegionVtab *) vtab, name, channel ); if ( astOK ) { /* Read input data. */ /* ================ */ /* Request the input Channel to read all the input data appropriate to this class into the internal "values list". */ astReadClassData( channel, "Stc" ); /* Now read each individual data item from this list and use it to initialise the appropriate instance variable(s) for this class. */ /* In the case of attributes, we first read the "raw" input value, supplying the "unset" value as the default. If a "set" value is obtained, we then use the appropriate (private) Set... member function to validate and set the value properly. */ /* Encapsulated Region. */ /* -------------------- */ new->region = astReadObject( channel, "region", NULL ); /* Get a pointer to the base Frame in the FrameSet encapsulated by the parent Region structure. */ f1 = astGetFrame( ((AstRegion *) new)->frameset, AST__BASE ); /* If the encapsulated Region has a dummy FrameSet rather than the correct FrameSet, the correct FrameSet will have copies of the base Frame of the new Stc as both its current and base Frames, connected by a UnitMap (this is equivalent to a FrameSet containing a single Frame). However if the new Stc being loaded has itself got a dummy FrameSet, then we do not do this since we do not yet know what the correct FrameSet is. In this case we wait until the parent Region invokes the astSetRegFS method on the new Stc. */ if( !astRegDummyFS( new ) ) { creg = new->region; if( astRegDummyFS( creg ) ) astSetRegFS( creg, f1 ); } /* AstroCoords info */ /* ---------------- */ /* The number of AstroCoords described in the new Stc. */ new->ncoord = astReadInt( channel, "ncoord", 0 ); if( new->ncoord < 0 ) new->ncoord = 0; /* Read back each KeyMap describing these AstroCoords. */ new->coord = astMalloc( sizeof( AstKeyMap *) * (size_t) new->ncoord ); for( ico = 1; ico <= new->ncoord; ico++ ) { (void) sprintf( key, "coord%d", ico ); new->coord[ ico - 1 ] = astReadObject( channel, key, NULL ); /* Ensure the Regions within the KeyMap do not have dummy FrameSets. */ if( new->coord[ ico - 1 ] && !astRegDummyFS( new ) ) { for( ikey = 0; ikey < NREG; ikey++ ) { if( astMapGet0A( new->coord[ ico - 1 ], regkey[ ikey ], &obj ) ){ creg = (AstRegion *) obj; if( astRegDummyFS( creg ) ) { astSetRegFS( creg, f1 ); astMapPut0A( new->coord[ ico - 1 ], regkey[ ikey ], creg, regcom[ ikey ] ); } creg = astAnnul( creg ); } } } } /* Free resources */ f1 = astAnnul( f1 ); /* If an error occurred, clean up by deleting the new Stc. */ if ( !astOK ) new = astDelete( new ); } /* Return the new Stc pointer. */ return new; /* Undefine macros local to this function. */ #undef KEY_LEN } /* Virtual function interfaces. */ /* ============================ */ /* These provide the external interface to the virtual functions defined by this class. Each simply checks the global error status and then locates and executes the appropriate member function, using the function pointer stored in the object's virtual function table (this pointer is located using the astMEMBER macro defined in "object.h"). Note that the member function may not be the one defined here, as it may have been over-ridden by a derived class. However, it should still have the same interface. */ const char *astGetRegionClass_( AstStc *this, int *status ){ if ( !astOK ) return NULL; return (**astMEMBER(this,Stc,GetRegionClass))( this, status ); } AstRegion *astGetStcRegion_( AstStc *this, int *status ){ if ( !astOK ) return NULL; return (**astMEMBER(this,Stc,GetStcRegion))( this, status ); } AstKeyMap *astGetStcCoord_( AstStc *this, int icoord, int *status ){ if ( !astOK ) return NULL; return (**astMEMBER(this,Stc,GetStcCoord))( this, icoord, status ); } int astGetStcNCoord_( AstStc *this, int *status ){ if ( !astOK ) return 0; return (**astMEMBER(this,Stc,GetStcNCoord))( this, status ); }
32.335583
99
0.637842
[ "mesh", "object", "shape", "vector", "transform" ]
08e77e9a062e2ccd8e25c1cafd1c2d050a951e9a
14,778
c
C
pnpbridge/src/pnpbridge/common/pnp_protocol.c
daisukeiot/iot-plug-and-play-bridge
85958fb10c122914b03fe2c15859abc61c7ef5fc
[ "MIT" ]
29
2020-09-30T19:20:07.000Z
2022-02-24T16:28:02.000Z
pnpbridge/src/pnpbridge/common/pnp_protocol.c
daisukeiot/iot-plug-and-play-bridge
85958fb10c122914b03fe2c15859abc61c7ef5fc
[ "MIT" ]
28
2020-09-30T21:05:11.000Z
2021-11-10T19:06:29.000Z
pnpbridge/src/pnpbridge/common/pnp_protocol.c
daisukeiot/iot-plug-and-play-bridge
85958fb10c122914b03fe2c15859abc61c7ef5fc
[ "MIT" ]
15
2020-10-18T12:46:30.000Z
2021-12-26T02:17:15.000Z
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Header associated with this .c file #include "pnp_protocol.h" // JSON parsing library #include "parson.h" // IoT core utility related header files #include "azure_c_shared_utility/xlogging.h" #include "azure_c_shared_utility/strings.h" // Format used when building a response for a root property that does not contain metadata static const char g_propertyWithoutResponseSchemaWithoutComponent[] = "{\"%s\":%s}"; // Format used when building a response for a component's property that does not contain metadata static const char g_propertyWithoutResponseSchemaWithComponent[] = "{\"""%s\":{\"__t\":\"c\",\"%s\":%s}}"; // Format used when building a response for a root property that does contain metadata static const char g_propertyWithResponseSchemaWithoutComponent[] = "{\"%s\":{\"value\":%s,\"ac\":%d,\"ad\":\"%s\",\"av\":%d}}"; // Format used when building a response for a component's property that does contain metadata static const char g_propertyWithResponseSchemaWithComponent[] = "{\"""%s\":{\"__t\":\"c\",\"%s\":{\"value\":%s,\"ac\":%d,\"ad\":\"%s\",\"av\":%d}}}"; // Character that separates a PnP component from the specific command on the component. static const char g_commandSeparator = '*'; // The version of the desired twin is represented by the $version metadata. static const char g_IoTHubTwinDesiredVersion[] = "$version"; // IoTHub adds a JSON field "__t":"c" into desired top-level JSON objects that represent components. Without this marking, the object // is treated as a property off the root component. static const char g_IoTHubTwinPnPComponentMarker[] = "__t"; // Name of desired JSON field when retrieving a full twin. static const char g_IoTHubTwinDesiredObjectName[] = "desired"; // Telemetry message property used to indicate the message's component. static const char PnP_TelemetryComponentProperty[] = "$.sub"; STRING_HANDLE PnP_CreateReportedProperty(const char* componentName, const char* propertyName, const char* propertyValue) { STRING_HANDLE jsonToSend; if (componentName == NULL) { jsonToSend = STRING_construct_sprintf(g_propertyWithoutResponseSchemaWithoutComponent, propertyName, propertyValue); } else { jsonToSend = STRING_construct_sprintf(g_propertyWithoutResponseSchemaWithComponent, componentName, propertyName, propertyValue); } if (jsonToSend == NULL) { LogError("Unable to allocate JSON buffer"); } return jsonToSend; } STRING_HANDLE PnP_CreateReportedPropertyWithStatus(const char* componentName, const char* propertyName, const char* propertyValue, int result, const char* description, int ackVersion) { STRING_HANDLE jsonToSend; if (componentName == NULL) { jsonToSend = STRING_construct_sprintf(g_propertyWithResponseSchemaWithoutComponent, propertyName, propertyValue, result, description, ackVersion); } else { jsonToSend = STRING_construct_sprintf(g_propertyWithResponseSchemaWithComponent, componentName, propertyName, propertyValue, result, description, ackVersion); } if (jsonToSend == NULL) { LogError("Unable to allocate JSON buffer"); } return jsonToSend; } void PnP_ParseCommandName(const char* deviceMethodName, unsigned const char** componentName, size_t* componentNameSize, const char** pnpCommandName) { const char* separator; if ((separator = strchr(deviceMethodName, g_commandSeparator)) != NULL) { // If a separator character is present in the device method name, then a command on a subcomponent of // the model is being targeted (e.g. thermostat1*getMaxMinReport). *componentName = (unsigned const char*)deviceMethodName; *componentNameSize = separator - deviceMethodName; *pnpCommandName = separator + 1; } else { // The separator character is optional. If it is not present, it indicates a command of the root // component and not a subcomponent (e.g. "reboot"). *componentName = NULL; *componentNameSize = 0; *pnpCommandName = deviceMethodName; } } IOTHUB_MESSAGE_HANDLE PnP_CreateTelemetryMessageHandle(const char* componentName, const char* telemetryData) { IOTHUB_MESSAGE_HANDLE messageHandle; IOTHUB_MESSAGE_RESULT iothubMessageResult; bool result; if ((messageHandle = IoTHubMessage_CreateFromString(telemetryData)) == NULL) { LogError("IoTHubMessage_CreateFromString failed"); result = false; } // If the component will be used, then specify this as a property of the message. else if ((componentName != NULL) && (iothubMessageResult = IoTHubMessage_SetProperty(messageHandle, PnP_TelemetryComponentProperty, componentName)) != IOTHUB_MESSAGE_OK) { LogError("IoTHubMessage_SetProperty=%s failed, error=%d", PnP_TelemetryComponentProperty, iothubMessageResult); result = false; } else { result = true; } if ((result == false) && (messageHandle != NULL)) { IoTHubMessage_Destroy(messageHandle); messageHandle = NULL; } return messageHandle; } // // VisitComponentProperties visits each sub element of the the given objectName in the desired JSON. Each of these sub elements corresponds to // a property of this component, which we'll invoke the application's pnpPropertyCallback to inform. // static void VisitComponentProperties(const char* objectName, JSON_Value* value, int version, PnP_PropertyCallbackFunction pnpPropertyCallback, void* userContextCallback) { JSON_Object* object = json_value_get_object(value); size_t numChildren = json_object_get_count(object); for (size_t i = 0; i < numChildren; i++) { const char* propertyName = json_object_get_name(object, i); JSON_Value* propertyValue = json_object_get_value_at(object, i); if ((propertyName == NULL) || (propertyValue == NULL)) { // This should never happen because we are simply accessing parson tree. Do not pass NULL to application in case it does occur. LogError("Unexpected error retrieving the property name and/or value of component=%s at element at index=%lu", objectName, (unsigned long)i); continue; } // When a component is received from a full twin, it will have a "__t" as one of the child elements. This is metadata that indicates // to solutions that the JSON object corresponds to a component and not a property of the root component. Because this is // metadata and not part of this component's modeled properties, we ignore it when processing this loop. if (strcmp(propertyName, g_IoTHubTwinPnPComponentMarker) == 0) { continue; } // Invoke the application's passed in callback for it to process this property. pnpPropertyCallback(objectName, propertyName, propertyValue, version, userContextCallback); } } // // IsJsonObjectAComponentInModel checks whether the objectName, read from the top-level child of the desired device twin JSON, // is in componentsInModel that the application passed into us. // static bool IsJsonObjectAComponentInModel(const char* objectName, const char** componentsInModel, size_t numComponentsInModel) { bool result = false; for (size_t i = 0; i < numComponentsInModel; i++) { if (strcmp(objectName, componentsInModel[i]) == 0) { result = true; break; } } return result; } // // VisitDesiredObject visits each child JSON element of the desired device twin. As we parse each property out, we invoke the application's passed in pnpPropertyCallback. // static bool VisitDesiredObject(JSON_Object* desiredObject, const char** componentsInModel, size_t numComponentsInModel, PnP_PropertyCallbackFunction pnpPropertyCallback, void* userContextCallback) { JSON_Value* versionValue = NULL; size_t numChildren; int version; bool result; if ((versionValue = json_object_get_value(desiredObject, g_IoTHubTwinDesiredVersion)) == NULL) { LogError("Cannot retrieve %s field for twin", g_IoTHubTwinDesiredVersion); result = false; } else if (json_value_get_type(versionValue) != JSONNumber) { LogError("JSON field %s is not a number", g_IoTHubTwinDesiredVersion); result = false; } else { version = (int)json_value_get_number(versionValue); numChildren = json_object_get_count(desiredObject); // Visit each child JSON element of the desired device twin. for (size_t i = 0; i < numChildren; i++) { const char* name = json_object_get_name(desiredObject, i); JSON_Value* value = json_object_get_value_at(desiredObject, i); if (strcmp(name, g_IoTHubTwinDesiredVersion) == 0) { // The version field is metadata and should be ignored in this loop. continue; } if ((json_type(value) == JSONObject) && IsJsonObjectAComponentInModel(name, componentsInModel, numComponentsInModel)) { // If this current JSON is an element AND the name is one of the componentsInModel that the application knows about, // then this json element represents a component. VisitComponentProperties(name, value, version, pnpPropertyCallback, userContextCallback); } else { // If the child element is NOT an object OR its not a model the application knows about, this is a property of the model's root component. // Invoke the application's passed in callback for it to process this property. pnpPropertyCallback(NULL, name, value, version, userContextCallback); } } result = true; } return result; } // // GetDesiredJson retrieves JSON_Object* in the JSON tree corresponding to the desired payload. // static JSON_Object* GetDesiredJson(DEVICE_TWIN_UPDATE_STATE updateState, JSON_Value* rootValue) { JSON_Object* rootObject = NULL; JSON_Object* desiredObject; if ((rootObject = json_value_get_object(rootValue)) == NULL) { LogError("Unable to get root object of JSON"); desiredObject = NULL; } else { if (updateState == DEVICE_TWIN_UPDATE_COMPLETE) { // For a complete update, the JSON from IoTHub will contain both "desired" and "reported" - the full twin. // We only care about "desired" in this sample, so just retrieve it. desiredObject = json_object_get_object(rootObject, g_IoTHubTwinDesiredObjectName); } else { // For a patch update, IoTHub does not explicitly put a "desired:" JSON envelope. The "desired-ness" is implicit // in this case, so here we simply need the root of the JSON itself. desiredObject = rootObject; } } return desiredObject; } bool PnP_ProcessTwinData(DEVICE_TWIN_UPDATE_STATE updateState, const unsigned char* payload, size_t size, const char** componentsInModel, size_t numComponentsInModel, PnP_PropertyCallbackFunction pnpPropertyCallback, void* userContextCallback) { char* jsonStr = NULL; JSON_Value* rootValue = NULL; JSON_Object* desiredObject; bool result; if ((jsonStr = PnP_CopyPayloadToString(payload, size)) == NULL) { LogError("Unable to allocate twin buffer"); result = false; } else if ((rootValue = json_parse_string(jsonStr)) == NULL) { LogError("Unable to parse device twin JSON"); result = false; } else if ((desiredObject = GetDesiredJson(updateState, rootValue)) == NULL) { LogError("Cannot retrieve desired JSON object"); result = false; } else { // Visit each sub-element in the desired portion of the twin JSON and invoke pnpPropertyCallback as appropriate. result = VisitDesiredObject(desiredObject, componentsInModel, numComponentsInModel, pnpPropertyCallback, userContextCallback); } json_value_free(rootValue); free(jsonStr); return result; } bool PnP_ProcessModuleTwinConfigProperty(DEVICE_TWIN_UPDATE_STATE updateState, const unsigned char* payload, size_t size, PnP_ModuleConfigPropertyCallbackFunction pnpPropertyCallback, const char* targetProperty) { char* jsonStr = NULL; JSON_Value* rootValue = NULL; JSON_Object* desiredObject; bool result = false; if ((jsonStr = PnP_CopyPayloadToString(payload, size)) == NULL) { LogError("Unable to allocate module twin's property buffer"); result = false; } else if ((rootValue = json_parse_string(jsonStr)) == NULL) { LogError("Unable to parse module twin property JSON"); result = false; } else if ((desiredObject = GetDesiredJson(updateState, rootValue)) == NULL) { LogError("Cannot retrieve desired JSON object for module twin property"); result = false; } else { size_t numChildren = json_object_get_count(desiredObject); // Visit each child JSON element of the desired device twin. for (size_t i = 0; i < numChildren; i++) { const char* name = json_object_get_name(desiredObject, i); JSON_Value* value = json_object_get_value_at(desiredObject, i); if ((strcmp(name, targetProperty) == 0) && (json_type(value) == JSONObject)) { // Found the target config property pnpPropertyCallback(value); result = true; break; } } } json_value_free(rootValue); free(jsonStr); return result; } char* PnP_CopyPayloadToString(const unsigned char* payload, size_t size) { char* jsonStr; size_t sizeToAllocate = size + 1; if ((jsonStr = (char*)malloc(sizeToAllocate)) == NULL) { LogError("Unable to allocate %lu size buffer", (unsigned long)(sizeToAllocate)); } else { memcpy(jsonStr, payload, size); jsonStr[size] = '\0'; } return jsonStr; }
39.095238
244
0.666734
[ "object", "model" ]
08e7d15331c9854ab4b96a3b71c80cf89a1c8d93
3,619
h
C
ffmpeg/libavfilter/dnn/dnn_backend_native.h
qinjidong/EasyMPlayer
76a8d052dd7a2d5f1916fdc32b07088d127ee5da
[ "Apache-2.0" ]
null
null
null
ffmpeg/libavfilter/dnn/dnn_backend_native.h
qinjidong/EasyMPlayer
76a8d052dd7a2d5f1916fdc32b07088d127ee5da
[ "Apache-2.0" ]
null
null
null
ffmpeg/libavfilter/dnn/dnn_backend_native.h
qinjidong/EasyMPlayer
76a8d052dd7a2d5f1916fdc32b07088d127ee5da
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018 Sergey Lavrushkin * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * DNN inference functions interface for native backend. */ #ifndef AVFILTER_DNN_DNN_BACKEND_NATIVE_H #define AVFILTER_DNN_DNN_BACKEND_NATIVE_H #include "../dnn_interface.h" #include "libavformat/avio.h" typedef enum {INPUT, CONV, DEPTH_TO_SPACE, MIRROR_PAD} DNNLayerType; typedef enum {RELU, TANH, SIGMOID, NONE, LEAKY_RELU} DNNActivationFunc; typedef enum {VALID, SAME, SAME_CLAMP_TO_EDGE} DNNConvPaddingParam; typedef enum {DOT_INPUT = 1, DOT_OUTPUT = 2, DOT_INTERMEDIATE = DOT_INPUT | DOT_INPUT} DNNOperandType; typedef struct Layer{ DNNLayerType type; /** * a layer can have multiple inputs and one output. * 4 is just a big enough number for input operands (increase it if necessary), * do not use 'int32_t *input_operand_indexes', so we don't worry about mem leaks. */ int32_t input_operand_indexes[4]; int32_t output_operand_index; void *params; } Layer; typedef struct DnnOperand{ /** * there are two memory layouts, NHWC or NCHW, so we use dims, * dims[0] is Number. */ int32_t dims[4]; /** * input/output/intermediate operand of the network */ DNNOperandType type; /** * support different kinds of data type such as float, half float, int8 etc, * first support float now. */ DNNDataType data_type; /** * NHWC if 1, otherwise NCHW. * let's first support NHWC only, this flag is for extensive usage. */ int8_t isNHWC; /** * to avoid possible memory leak, do not use char *name */ char name[128]; /** * data pointer with data length in bytes. * usedNumbersLeft is only valid for intermediate operand, * it means how many layers still depend on this operand, * todo: the memory can be reused when usedNumbersLeft is zero. */ void *data; int32_t length; int32_t usedNumbersLeft; }DnnOperand; typedef struct ConvolutionalParams{ int32_t input_num, output_num, kernel_size; DNNActivationFunc activation; DNNConvPaddingParam padding_method; int32_t dilation; float *kernel; float *biases; } ConvolutionalParams; typedef struct InputParams{ int height, width, channels; } InputParams; typedef struct DepthToSpaceParams{ int block_size; } DepthToSpaceParams; // Represents simple feed-forward convolutional network. typedef struct ConvolutionalNetwork{ Layer *layers; int32_t layers_num; DnnOperand *operands; int32_t operands_num; } ConvolutionalNetwork; DNNModel *ff_dnn_load_model_native(const char *model_filename); DNNReturnType ff_dnn_execute_model_native(const DNNModel *model, DNNData *outputs, uint32_t nb_output); void ff_dnn_free_model_native(DNNModel **model); int32_t calculate_operand_data_length(DnnOperand *operand); #endif
28.496063
103
0.72147
[ "model" ]
08ec2855f74b43b268fca36e9e1e85551880a440
1,657
h
C
aws-cpp-sdk-ec2/include/aws/ec2/model/MemoryInfo.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-ec2/include/aws/ec2/model/MemoryInfo.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-ec2/include/aws/ec2/model/MemoryInfo.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2020-11-04T03:18:11.000Z
2020-11-04T03:18:11.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/ec2/EC2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace EC2 { namespace Model { /** * <p>Describes the memory for the instance type.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MemoryInfo">AWS API * Reference</a></p> */ class AWS_EC2_API MemoryInfo { public: MemoryInfo(); MemoryInfo(const Aws::Utils::Xml::XmlNode& xmlNode); MemoryInfo& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; void OutputToStream(Aws::OStream& oStream, const char* location) const; /** * <p>Size of the memory, in MiB.</p> */ inline long long GetSizeInMiB() const{ return m_sizeInMiB; } /** * <p>Size of the memory, in MiB.</p> */ inline bool SizeInMiBHasBeenSet() const { return m_sizeInMiBHasBeenSet; } /** * <p>Size of the memory, in MiB.</p> */ inline void SetSizeInMiB(long long value) { m_sizeInMiBHasBeenSet = true; m_sizeInMiB = value; } /** * <p>Size of the memory, in MiB.</p> */ inline MemoryInfo& WithSizeInMiB(long long value) { SetSizeInMiB(value); return *this;} private: long long m_sizeInMiB; bool m_sizeInMiBHasBeenSet; }; } // namespace Model } // namespace EC2 } // namespace Aws
24.014493
118
0.659626
[ "model" ]
8327b2d19c4d6dcb1356988d33890aa3a1fd87c6
47,305
h
C
blocks/QuickTime/include/msw/PMCore.h
rsh/Cinder-Emscripten
4a08250c56656865c7c3a52fb9380980908b1439
[ "BSD-2-Clause" ]
24
2015-12-07T23:03:27.000Z
2021-04-03T14:55:54.000Z
blocks/QuickTime/include/msw/PMCore.h
rsh/Cinder-Emscripten
4a08250c56656865c7c3a52fb9380980908b1439
[ "BSD-2-Clause" ]
8
2020-01-05T23:38:51.000Z
2020-02-23T22:18:18.000Z
blocks/QuickTime/include/msw/PMCore.h
rsh/Cinder-Emscripten
4a08250c56656865c7c3a52fb9380980908b1439
[ "BSD-2-Clause" ]
6
2015-12-17T18:26:57.000Z
2018-11-22T00:11:55.000Z
/* File: PMCore.h Contains: Carbon Printing Manager Interfaces. Version: QuickTime 7.3 Copyright: (c) 2007 (c) 1998-2001 by Apple Computer, Inc., all rights reserved Bugs?: For bug reports, consult the following page on the World Wide Web: http://developer.apple.com/bugreporter/ */ #ifndef __PMCORE__ #define __PMCORE__ #ifndef __MACERRORS__ #include <MacErrors.h> #endif #ifndef __FILES__ #include <Files.h> #endif #ifndef __CFSTRING__ #include <CFString.h> #endif #ifndef __CFURL__ #include <CFURL.h> #endif #ifndef __QUICKDRAW__ #include <Quickdraw.h> #endif #ifndef __CMAPPLICATION__ #include <CMApplication.h> #endif #ifndef __PMDEFINITIONS__ #include <PMDefinitions.h> #endif #if PRAGMA_ONCE #pragma once #endif #ifdef __cplusplus extern "C" { #endif #if PRAGMA_IMPORT #pragma import on #endif #ifndef PM_USE_SESSION_APIS #define PM_USE_SESSION_APIS 1 #endif /* !defined(PM_USE_SESSION_APIS) */ /* Callbacks */ typedef CALLBACK_API( void , PMIdleProcPtr )(void); typedef STACK_UPP_TYPE(PMIdleProcPtr) PMIdleUPP; /* * NewPMIdleUPP() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API_C( PMIdleUPP ) NewPMIdleUPP(PMIdleProcPtr userRoutine); /* * DisposePMIdleUPP() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API_C( void ) DisposePMIdleUPP(PMIdleUPP userUPP); /* * InvokePMIdleUPP() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API_C( void ) InvokePMIdleUPP(PMIdleUPP userUPP); #if PM_USE_SESSION_APIS /* * PMSessionCreatePrinterList() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.4 and later * Mac OS X: in version 10.1 and later */ EXTERN_API( OSStatus ) PMSessionCreatePrinterList( PMPrintSession printSession, CFArrayRef * printerList, CFIndex * currentIndex, PMPrinter * currentPrinter); /* * PMSessionSetCurrentPrinter() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.4 and later * Mac OS X: in version 10.1 and later */ EXTERN_API( OSStatus ) PMSessionSetCurrentPrinter( PMPrintSession session, CFStringRef printerName); /* * PMSessionSetDestination() * * Summary: * Alter a print session and print settings so that an associated * print job is sent to the provided destination type in the, * optional, MIME document format. * * Discussion: * This function is most useful when an application would like to * write its print output to disk without requiring user * interaction. The list of MIME types that can be sent to the * provided destination can be obtained from * PMSessionCopyOutputFormatList and one of these passed to this * function. * * Parameters: * * printSession: * The session to be used for a print job. The session holds the * preview setting which can override the destination type in the * print settings. * * printSettings: * The print settings to be used for a print job. The print * settings specify whether a job will be directed toward a * printer or to file. It also holds the requested MIME output * type. * * destType: * The destiation type for a print job associated with the * provided print session and print settings. Fax is currently not * supported, but kPMDestinationPrinter, kPMDestinationFile, and * kPMDestinationPreview can be set. * * destFormat: * The MIME type to be generated for the provided destination * type. This parameter can be NULL in which the default format * for the requested destination type is used. To obtain a list of * valid formats for a given destiation type, use the function * PMSessionCopyOutputFormatList. * * destLocation: * Some destination types support a destination location. The * clearest example is the kPMDestinationFile destination type * which allows a caller to also supply a file URL specifying * where the output file is to be created. * * SPECIAL_AVAILABILITY_NOTE: * This routine is available in ApplicationsServices.framework in * Mac OS X version 10.1 and later. On Mac OS X it is available to * CFM applications through CarbonLib starting with Mac OS X * version 10.2 and later. * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.5 and later * Mac OS X: in version 10.1 and later */ EXTERN_API( OSStatus ) PMSessionSetDestination( PMPrintSession printSession, PMPrintSettings printSettings, PMDestinationType destType, CFStringRef destFormat, CFURLRef destLocation); /* * PMSessionGetDestinationType() * * Summary: * Hand back the destination type that will be used for a print job * with the specified print settings and print session. * * Discussion: * Currently there are four destination types: * kPMDestinationPrinter, kPMDestinationFile, kPMDestinationFax and * kPMDestinationPreview. The first three destination types are * stored in the print settings. The switch for preview is stored in * the print session and, if enabled, overrides the destination in * the print setting. This function is preferred over * PMGetDestination as the latter does not take a print session * parameter and therefore can not indicate whether preview has been * selected as the destination. * * Parameters: * * printSession: * The session to be used for a print job. The session holds the * preview setting which can override the destination type in the * print settings. * * printSettings: * The print settings to be used for a print job. The print * settings specify whether a job will be directed toward a * printer or to file. * * destTypeP: * A pointer to a caller supplied PMDestinationType variable. If * this function succeeds then *'destTypeP' will be filled in with * the destination type for a print job that used the specified * session and print settings. If this function fails, then * *'destType' will be set to kPMDestinationInvalid. * * SPECIAL_AVAILABILITY_NOTE: * This routine is available in ApplicationsServices.framework in * Mac OS X version 10.1 and later. On Mac OS X it is available to * CFM applications through CarbonLib starting with Mac OS X * version 10.2 and later. * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.5 and later * Mac OS X: in version 10.1 and later */ EXTERN_API( OSStatus ) PMSessionGetDestinationType( PMPrintSession printSession, PMPrintSettings printSettings, PMDestinationType * destTypeP); /* * PMSessionCopyDestinationFormat() * * Summary: * Hand back the destination output MIME type associated with the * provided print session and print settings. * * Parameters: * * printSession: * A currently open print session. * * printSettings: * The print settings that are to be searched. * * destFormatP: * A pointer to a caller allocated CFStringRef variable. If this * routine returns noErr then *'destFormatP' will either be a copy * of a CFStringRef specifying the output format for the print * job, or NULL indicating that the default output format will be * used. If this function return an error, then *'destFormatP' * will be set to NULL. * * SPECIAL_AVAILABILITY_NOTE: * This routine is available in ApplicationsServices.framework in * Mac OS X version 10.1 and later. On Mac OS X it is available to * CFM applications through CarbonLib starting with Mac OS X * version 10.2 and later. * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.5 and later * Mac OS X: in version 10.1 and later */ EXTERN_API( OSStatus ) PMSessionCopyDestinationFormat( PMPrintSession printSession, PMPrintSettings printSettings, CFStringRef * destFormatP); /* * PMSessionCopyDestinationLocation() * * Summary: * Hand back the URL destination location given a print session and * print settings. * * Discussion: * Some destination type support a destination location which * further defines where the output from a pritn job should be sent. * The kPMDestinationFile destiation type, for example, will use a * file URL to determine where a new file should be created. * * Parameters: * * printSession: * A currently open print session. * * printSettings: * The print settings that are to be searched. * * destLocationP: * A pointer to a caller allocated CFURLRef variable. If this * routine returns noErr then *'outputFileP' will either be NULL * indicating that the job is using the default destination * location for the current destination type or a copy of a * CFURLRef will be placed in *'destLocationP'. If this function * returns an error then 'destLocationP' will be set to NULL. * * SPECIAL_AVAILABILITY_NOTE: * This routine is available in ApplicationsServices.framework in * Mac OS X version 10.1 and later. On Mac OS X it is available to * CFM applications through CarbonLib starting with Mac OS X * version 10.2 and later. * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.5 and later * Mac OS X: in version 10.1 and later */ EXTERN_API( OSStatus ) PMSessionCopyDestinationLocation( PMPrintSession printSession, PMPrintSettings printSettings, CFURLRef * destLocationP); /* * PMSessionCopyOutputFormatList() * * Summary: * Hands back an an array of MIME types describing the possible * output formats for the printer module associated with the current * printer. * * Parameters: * * printSession: * This session's current printer's printer module will be queried * for its supported output MIME types. * * destType: * A print job can have one of several possible destination types. * The list of valid output formats is dependent upon the * destination type. This parameter specifies destination type of * interest when retrieving the output formats list. * * documentFormatP: * A pointer to a caller's CFArrayRef variable. If this routine * completes successfully, then *'documentFormatP' will be set to * a CFArrayRef containing CFStringRefs. Each CFStringRef in the * array is a MIME type specifying a type of output that can be * generated by the printer module associated with the current * printer. * * SPECIAL_AVAILABILITY_NOTE: * This routine is available in ApplicationsServices.framework in * Mac OS X version 10.1 and later. On Mac OS X it is available to * CFM applications through CarbonLib starting with Mac OS X * version 10.2 and later. On Mac OS 8/9 using CarbonLib, this * routine returns kPMNotImplemented * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.6 and later * Mac OS X: in version 10.1 and later */ EXTERN_API( OSStatus ) PMSessionCopyOutputFormatList( PMPrintSession printSession, PMDestinationType destType, CFArrayRef * documentFormatP); /* * PMSessionCreatePageFormatList() * * Summary: * Hand back a list of page format instances. Each page format * instance describes a paper size available on the specified * printer. * * Parameters: * * printSession: * A currently open print session. * * printer: * The printer whose page size list should be enumerated. To get * the session's current printer, see PMSessionGetCurrentPrinter(). * * pageFormatList: * If this function is successful then noErr will be returned and * *'pageFormatList' will be set to a newly created CFArray. Each * element in the array will be a PMPageFormat describing an * available paper size for the specified printer. If this * function fails then a non-zero error code will be returned and * *'pageFormatList' will be set to NULL. * * SPECIAL_AVAILABILITY_NOTE: * This routine is available in ApplicationsServices.framework in * Mac OS X version 10.1 and later. On Mac OS X it is available to * CFM applications through CarbonLib starting with Mac OS X * version 10.2 and later. On Mac OS 8/9 using CarbonLib, this * routine returns kPMNotImplemented * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.6 and later * Mac OS X: in version 10.1 and later */ EXTERN_API( OSStatus ) PMSessionCreatePageFormatList( PMPrintSession printSession, PMPrinter printer, CFArrayRef * pageFormatList); /* * SPECIAL AVAILABILITY note: This routine is available in ApplicationsServices.framework in * Mac OS X version 10.0 and later. On Mac OS X it is available to CFM applications through CarbonLib * starting with Mac OS X version 10.2 and later. * * On Mac OS 8/9 using CarbonLib, this routine returns kPMNotImplemented */ /* * PMSessionBeginDocumentNoDialog() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.6 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSessionBeginDocumentNoDialog( PMPrintSession printSession, PMPrintSettings printSettings, PMPageFormat pageFormat); /* * SPECIAL AVAILABILITY note: This routine is available in ApplicationsServices.framework in * Mac OS X version 10.0 and later. On Mac OS X it is available to CFM applications through CarbonLib * starting with Mac OS X version 10.2 and later. * * On Mac OS 8/9 using CarbonLib, this routine returns kPMNotImplemented */ /* * PMSessionEndDocumentNoDialog() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.6 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSessionEndDocumentNoDialog(PMPrintSession printSession); /* * SPECIAL AVAILABILITY note: This routine is available in ApplicationsServices.framework in * Mac OS X version 10.0 and later. On Mac OS X it is available to CFM applications through CarbonLib * starting with Mac OS X version 10.2 and later. * * On Mac OS 8/9 using CarbonLib, this routine returns kPMNotImplemented */ /* * PMSessionBeginPageNoDialog() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.6 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSessionBeginPageNoDialog( PMPrintSession printSession, PMPageFormat pageFormat, const PMRect * pageFrame); /* * SPECIAL AVAILABILITY note: This routine is available in ApplicationsServices.framework in * Mac OS X version 10.0 and later. On Mac OS X it is available to CFM applications through CarbonLib * starting with Mac OS X version 10.2 and later. * * On Mac OS 8/9 using CarbonLib, this routine returns kPMNotImplemented */ /* * PMSessionEndPageNoDialog() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.6 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSessionEndPageNoDialog(PMPrintSession printSession); #else /* * PMSetIdleProc() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetIdleProc(PMIdleUPP idleProc); /* Print loop */ /* * PMBegin() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMBegin(void); /* * PMEnd() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMEnd(void); /************************/ /* Valid only within a PMBeginPage/PMEndPage block. You should retrieve the printing */ /* port with this call and set it before imaging a page. */ /************************/ /* * PMGetGrafPtr() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetGrafPtr( PMPrintContext printContext, GrafPtr * grafPort); /* PMPageFormat */ /* * PMNewPageFormat() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMNewPageFormat(PMPageFormat * pageFormat); /* * PMDisposePageFormat() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMDisposePageFormat(PMPageFormat pageFormat); /* * PMDefaultPageFormat() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMDefaultPageFormat(PMPageFormat pageFormat); /* * PMValidatePageFormat() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMValidatePageFormat( PMPageFormat pageFormat, Boolean * result); /* PMPrintSettings */ /* * PMNewPrintSettings() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMNewPrintSettings(PMPrintSettings * printSettings); /* * PMDisposePrintSettings() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMDisposePrintSettings(PMPrintSettings printSettings); /* * PMDefaultPrintSettings() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMDefaultPrintSettings(PMPrintSettings printSettings); /* * PMValidatePrintSettings() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMValidatePrintSettings( PMPrintSettings printSettings, Boolean * result); /* Classic Support */ /* * PMGeneral() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGeneral(Ptr pData); /* * PMConvertOldPrintRecord() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMConvertOldPrintRecord( Handle printRecordHandle, PMPrintSettings * printSettings, PMPageFormat * pageFormat); /* * PMMakeOldPrintRecord() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMMakeOldPrintRecord( PMPrintSettings printSettings, PMPageFormat pageFormat, Handle * printRecordHandle); /* Driver Information */ /* * PMIsPostScriptDriver() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMIsPostScriptDriver(Boolean * isPostScript); /* * PMGetLanguageInfo() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetLanguageInfo(PMLanguageInfo * info); /* * PMGetDriverCreator() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetDriverCreator(OSType * creator); /* * PMGetDriverReleaseInfo() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetDriverReleaseInfo(VersRec * release); /* * PMGetPrinterResolutionCount() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetPrinterResolutionCount(UInt32 * count); /* * PMGetPrinterResolution() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetPrinterResolution( PMTag tag, PMResolution * res); /* * PMGetIndexedPrinterResolution() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetIndexedPrinterResolution( UInt32 index, PMResolution * res); /************************/ /* PMEnableColorSync and PMDisableColorSync are valid within */ /* BeginPage/EndPage block */ /************************/ /* ColorSync & PostScript Support */ /* * PMEnableColorSync() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMEnableColorSync(void); /* * PMDisableColorSync() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMDisableColorSync(void); /************************/ /* The PMPostScriptxxx calls are valid within a */ /* BeginPage/EndPage block */ /************************/ /* * PMPostScriptBegin() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMPostScriptBegin(void); /* * PMPostScriptEnd() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMPostScriptEnd(void); /************************/ /* These PMPostScriptxxx calls are valid within a */ /* PMPostScriptBegin/PMPostScriptEnd block */ /************************/ /* * PMPostScriptHandle() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMPostScriptHandle(Handle psHandle); /* * PMPostScriptData() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMPostScriptData( Ptr psPtr, Size len); /* * PMPostScriptFile() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMPostScriptFile(FSSpec * psFile); /* Error */ /* * PMError() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMError(void); /* * PMSetError() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetError(OSStatus printError); #endif /* PM_USE_SESSION_APIS */ /* PMPageFormat */ /* * PMCopyPageFormat() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMCopyPageFormat( PMPageFormat formatSrc, PMPageFormat formatDest); /************************/ /* Flattening a page format should only be necessary if you intend to preserve */ /* the object settings along with a document. A page format will persist outside of a */ /* PMBegin/PMEnd block. This will allow you to use any accessors on the object without */ /* the need to flatten and unflatten. Keep in mind accessors make no assumption */ /* on the validity of the value you set. This can only be done thru PMValidatePageFormat */ /* in a PMBegin/PMEnd block or with PMSessionValidatePageFormat with a valid session. */ /* It is your responsibility for disposing of the handle. */ /************************/ /* * PMFlattenPageFormat() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMFlattenPageFormat( PMPageFormat pageFormat, Handle * flatFormat); /* * PMUnflattenPageFormat() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMUnflattenPageFormat( Handle flatFormat, PMPageFormat * pageFormat); /* PMPageFormat Accessors */ /************************/ /* PMSetxxx calls only saves the value inside the printing object. They make no assumption on the */ /* validity of the value. This should be done using PMValidatePageFormat/PMSessionValidatePageFormat */ /* Any dependant settings are also updated during a validate call. */ /* For example: */ /* PMGetAdjustedPaperRect - returns a rect of a certain size */ /* PMSetScale( aPageFormat, 500.0 ) */ /* PMGetAdjustedPaperRect - returns the SAME rect as the first call */ /**/ /* PMGetAdjustedPaperRect - returns a rect of a certain size */ /* PMSetScale( aPageFormat, 500.0 ) */ /* PMValidatePageFormat or PMSessionValidatePageFormat */ /* PMGetAdjustedPaperRect - returns a rect thats scaled 500% from the first call */ /************************/ /* * PMGetPageFormatExtendedData() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetPageFormatExtendedData( PMPageFormat pageFormat, OSType dataID, UInt32 * size, void * extendedData); /* * PMSetPageFormatExtendedData() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetPageFormatExtendedData( PMPageFormat pageFormat, OSType dataID, UInt32 size, void * extendedData); /************************/ /* A value of 100.0 means 100% (no scaling). 50.0 means 50% scaling */ /************************/ /* * PMGetScale() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetScale( PMPageFormat pageFormat, double * scale); /* * PMSetScale() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetScale( PMPageFormat pageFormat, double scale); /************************/ /* This is the drawing resolution of an app. This should not be confused with */ /* the resolution of the printer. You can call PMGetPrinterResolution to see */ /* what resolutions are avaliable for the current printer. */ /************************/ /* * PMGetResolution() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetResolution( PMPageFormat pageFormat, PMResolution * res); /* * PMSetResolution() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetResolution( PMPageFormat pageFormat, const PMResolution * res); /************************/ /* This is the physical size of the paper without regard to resolution, orientation */ /* or scaling. It is returned as a 72dpi value. */ /************************/ /* * PMGetPhysicalPaperSize() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetPhysicalPaperSize( PMPageFormat pageFormat, PMRect * paperSize); /* * PMSetPhysicalPaperSize() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetPhysicalPaperSize( PMPageFormat pageFormat, const PMRect * paperSize); /************************/ /* This is the physical size of the page without regard to resolution, orientation */ /* or scaling. It is returned as a 72dpi value. */ /************************/ /* * PMGetPhysicalPageSize() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetPhysicalPageSize( PMPageFormat pageFormat, PMRect * pageSize); /* * PMGetAdjustedPaperRect() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetAdjustedPaperRect( PMPageFormat pageFormat, PMRect * paperRect); /* * PMGetAdjustedPageRect() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetAdjustedPageRect( PMPageFormat pageFormat, PMRect * pageRect); /* * PMGetUnadjustedPaperRect() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.1 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetUnadjustedPaperRect( PMPageFormat pageFormat, PMRect * paperRect); /* * PMSetUnadjustedPaperRect() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.1 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetUnadjustedPaperRect( PMPageFormat pageFormat, const PMRect * paperRect); /* * PMGetUnadjustedPageRect() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.1 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetUnadjustedPageRect( PMPageFormat pageFormat, PMRect * pageRect); /* * PMSetAdjustedPageRect() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.1 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetAdjustedPageRect( PMPageFormat pageFormat, const PMRect * pageRect); /* * PMGetOrientation() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetOrientation( PMPageFormat pageFormat, PMOrientation * orientation); /* * PMSetOrientation() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetOrientation( PMPageFormat pageFormat, PMOrientation orientation, Boolean lock); /* PMPrintSettings */ /* * PMCopyPrintSettings() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMCopyPrintSettings( PMPrintSettings settingSrc, PMPrintSettings settingDest); /************************/ /* Flattening a print settings should only be necessary if you intend to preserve */ /* the object settings along with a document. A print settings will persist outside of a */ /* PMBegin/PMEnd block. This allows you to use any accessors on the object without */ /* the need to flatten and unflatten. Keep in mind the accessors make no assumption */ /* on the validity of the value. This can only be done thru PMValidatePrintSettings */ /* in a PMBegin/PMEnd block or with PMSessionValidatePrintSettings with a valid session. */ /* It is your responsibility for disposing of the handle. */ /************************/ /* * PMFlattenPrintSettings() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMFlattenPrintSettings( PMPrintSettings printSettings, Handle * flatSettings); /* * PMUnflattenPrintSettings() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMUnflattenPrintSettings( Handle flatSettings, PMPrintSettings * printSettings); /* PMPrintSettings Accessors */ /* * PMGetPrintSettingsExtendedData() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetPrintSettingsExtendedData( PMPrintSettings printSettings, OSType dataID, UInt32 * size, void * extendedData); /* * PMSetPrintSettingsExtendedData() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetPrintSettingsExtendedData( PMPrintSettings printSettings, OSType dataID, UInt32 size, void * extendedData); /* * PMGetDestination() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.1 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetDestination( PMPrintSettings printSettings, PMDestinationType * destType, CFURLRef * fileURL); /* * PMGetJobName() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetJobName( PMPrintSettings printSettings, StringPtr name); /* * PMSetJobName() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetJobName( PMPrintSettings printSettings, StringPtr name); /* * PMGetCopies() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetCopies( PMPrintSettings printSettings, UInt32 * copies); /* * PMSetCopies() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetCopies( PMPrintSettings printSettings, UInt32 copies, Boolean lock); /* * PMGetFirstPage() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetFirstPage( PMPrintSettings printSettings, UInt32 * first); /* * PMSetFirstPage() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetFirstPage( PMPrintSettings printSettings, UInt32 first, Boolean lock); /* * PMGetLastPage() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetLastPage( PMPrintSettings printSettings, UInt32 * last); /* * PMSetLastPage() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetLastPage( PMPrintSettings printSettings, UInt32 last, Boolean lock); /************************/ /* The default page range is from 1-32000. The page range is something that is */ /* set by the application. It is NOT the first and last page to print. It serves */ /* as limits for setting the first and last page. You may pass kPMPrintAllPages for */ /* the maxPage value to specified that all pages are available for printing. */ /************************/ /* * PMGetPageRange() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMGetPageRange( PMPrintSettings printSettings, UInt32 * minPage, UInt32 * maxPage); /************************/ /* The first and last page are immediately clipped to the new range */ /************************/ /* * PMSetPageRange() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetPageRange( PMPrintSettings printSettings, UInt32 minPage, UInt32 maxPage); /* * PMSetProfile() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later */ EXTERN_API( OSStatus ) PMSetProfile( PMPrintSettings printSettings, PMTag tag, const CMProfileLocation * profile); /* * PMSetCollate() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.6 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( OSStatus ) PMSetCollate( PMPrintSettings printSettings, Boolean collate); /* * PMGetCollate() * * Availability: * Non-Carbon CFM: not available * CarbonLib: in CarbonLib 1.6 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( OSStatus ) PMGetCollate( PMPrintSettings printSettings, Boolean * collate); /* * PMServerCreatePrinterList() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( OSStatus ) PMServerCreatePrinterList( PMServer server, CFArrayRef * printerList); /* * PMPrinterGetName() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( CFStringRef ) PMPrinterGetName(PMPrinter printer); /* * PMPrinterGetID() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( CFStringRef ) PMPrinterGetID(PMPrinter printer); /* * PMPrinterIsDefault() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( Boolean ) PMPrinterIsDefault(PMPrinter printer); /* * PMPrinterGetLocation() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( CFStringRef ) PMPrinterGetLocation(PMPrinter printer); /* * PMPrinterGetState() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( OSStatus ) PMPrinterGetState( PMPrinter printer, PMPrinterState * state); /* * PMPrinterGetDeviceURI() * * Summary: * Hand back the URI of the printer's device. * * Discussion: * If defined on OS 9 this function returns kPMNotImplemented. * * Parameters: * * printer: * The printer whose device URI is to be retrieved. * * deviceURI: * On exit, if successful *'deviceURI' will contain a reference to * a CFURL describing the printer's device. The caller is * responsible for releasing this reference. If this call returns * an error, then *'deviceURI' will be set to NULL. * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( OSStatus ) PMPrinterGetDeviceURI( PMPrinter printer, CFURLRef * deviceURI); /* * PMPrinterIsFavorite() * * Summary: * Return true if the printer is in the user's favorite printer list. * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.2 and later * Mac OS X: in version 10.2 and later */ EXTERN_API( Boolean ) PMPrinterIsFavorite(PMPrinter printer); /* * PMCGImageCreateWithEPSDataProvider() * * Summary: * Create an image reference that references both the PostScript * contents of an EPS file and a preview (proxy) image for that EPS * file. * * Discussion: * For OS X 10.1.0, this function ignores the passed in data * provider. The passed in image reference is retained and then * returned. For 10.1.1 and later, then the data provider is used * and the returned image reference is different than the passed in * image reference, so please be careful with your use of these * references. It is likely that the data will not be read from the * EPS data provider until well after this function returns. The * caller should be careful not to free the underlying EPS data * until the provider's release routine is invoked. Similarly the * preview image's data may be needed long after you think it should * be. Do not free the image data until the image data provider's * release data function has been called. To make sure these data * providers are properly reference counted, release your reference * the EPS data provider and on the EPS image preview when they are * no longer needed by your application. For Mac OS X 10.2 and * later, the contents of the EPS provider at the time of this call * can be dumped to a file if you first do the following, BEFORE * running your application. From the command line in terminal: * defaults write NSGlobalDomain com.apple.print.eps.testProvider * /tmp/dump.eps causes a dump of the EPS data into a file * /tmp/dump.eps. * * Parameters: * * epsDataProvider: * A Core Graphics data provider that can supply the PostScript * contents of the EPS file. Post OS X 10.1, there will be some * checking done on the EPS data provided to the * PMCGImageCreateWithEPSDataProvider() call. It is important that * the EPS data begin with the EPSF required header and bounding * box DSC comments. * * epsPreview: * A Core Graphics image reference to the proxy image for the EPS * file. When the image reference result of this function is * rendered on screen or printed to a printer that can not render * PostScript this proxy image is drawn instead. * * Result: * an image reference capable of rendering either the EPS content or * the proxy image depending upon the capabilities of the targeted * context. * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.1 and later * Mac OS X: in version 10.1 and later */ EXTERN_API( CGImageRef ) PMCGImageCreateWithEPSDataProvider( CGDataProviderRef epsDataProvider, CGImageRef epsPreview); #ifdef PRAGMA_IMPORT_OFF #pragma import off #elif PRAGMA_IMPORT #pragma import reset #endif #ifdef __cplusplus } #endif #endif /* __PMCORE__ */
26.939066
103
0.647056
[ "render", "object" ]
8337ebb09e3948ae3223c02184a7a3b133482234
4,460
h
C
src/lib/bitset/iterator.h
artembo/tarantool
5f0c04820b2429c004fbd28a838e291ca2833ca3
[ "BSD-2-Clause" ]
2,762
2015-01-03T18:14:32.000Z
2022-03-30T21:16:19.000Z
src/lib/bitset/iterator.h
artembo/tarantool
5f0c04820b2429c004fbd28a838e291ca2833ca3
[ "BSD-2-Clause" ]
6,187
2015-01-01T08:19:56.000Z
2022-03-31T21:44:32.000Z
src/lib/bitset/iterator.h
artembo/tarantool
5f0c04820b2429c004fbd28a838e291ca2833ca3
[ "BSD-2-Clause" ]
420
2015-01-16T15:56:52.000Z
2022-03-28T08:39:46.000Z
#ifndef TARANTOOL_LIB_BITSET_ITERATOR_H_INCLUDED #define TARANTOOL_LIB_BITSET_ITERATOR_H_INCLUDED /* * Copyright 2010-2016, Tarantool AUTHORS, please see AUTHORS file. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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 * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /** * @file * @brief Iterator for @link bitset @endlink objects with * expression support. * * @link bitset_iterator @endlink is used to iterate over a result * of the evaluation a @link bitset_expr logical expression * @endlink on a set of bitsets. The iterator evaluates its * expression on the fly, without producing temporary bitsets. * Each iteration (@link bitset_iterator_next @endlink) returns * the next position where a given expression evaluates to true on * a given set of bitsets. * * @see expr.h */ #include "bitset/bitset.h" #include "bitset/expr.h" #if defined(__cplusplus) extern "C" { #endif /* defined(__cplusplus) */ /** @cond false **/ struct tt_bitset_iterator_conj; /** @endcond **/ /** * @brief Bitset Iterator */ struct tt_bitset_iterator { /** @cond false **/ size_t size; size_t capacity; struct tt_bitset_iterator_conj *conjs; struct tt_bitset_page *page; struct tt_bitset_page *page_tmp; void *(*realloc)(void *ptr, size_t size); struct bit_iterator page_it; /** @endcond **/ }; /** * @brief Construct \a it. * * The created iterator must be initialized by * @link bitset_iterator_init @endlink method before first usage. * @param it bitset iterator * @param realloc memory allocator to use */ void tt_bitset_iterator_create(struct tt_bitset_iterator *it, void *(*realloc)(void *ptr, size_t size)); /** * @brief Destruct \a it. * @param it bitset iterator */ void tt_bitset_iterator_destroy(struct tt_bitset_iterator *it); /** * @brief Initialize the \a it using \a expr and \a bitsets and rewind the * iterator to the start position. * * @note It is safe to reinitialize an iterator with a new expression and new * bitsets. All internal buffers are safely reused in this case with minimal * number of new allocations. * * @note @a expr object is only used during initialization time and can be * safetly reused or destroyed just after this call. * * @param it bitset iterator * @param expr bitset expression * @param bitsets array of pointers to bitsets that should be used to bind * the expression parameters. * @param size of @a bitsets array * @retval 0 on success * @retval -1 on memory error * @see expr.h */ int tt_bitset_iterator_init(struct tt_bitset_iterator *it, struct tt_bitset_expr *expr, struct tt_bitset **bitsets, size_t bitsets_size); /** * @brief Rewind the \a it to the start position. * @param it bitset iterator * @see @link bitset_iterator_init @endlink */ void tt_bitset_iterator_rewind(struct tt_bitset_iterator *it); /** * @brief Move \a it to a next position * @param it bitset iterator * @return the next offset where the expression evaluates to true * or SIZE_MAX if there is no more bits in the result set. * @see @link bitset_iterator_init @endlink */ size_t tt_bitset_iterator_next(struct tt_bitset_iterator *it); #if defined(__cplusplus) } #endif /* defined(__cplusplus) */ #endif /* TARANTOOL_LIB_BITSET_ITERATOR_H_INCLUDED */
30.972222
77
0.742825
[ "object" ]
833e7008b44bebce2b471cc9b16a0326a1bfcf40
15,034
h
C
3rd/xulrunner-sdk/include/pkcs11n.h
ShoufuLuo/csaw
0d030d5ab93e61b62dff10b27a15c83fcfce3ff3
[ "Apache-2.0" ]
1
2018-08-24T18:01:34.000Z
2018-08-24T18:01:34.000Z
third_party/gecko-2/win32/include/pkcs11n.h
bwp/SeleniumWebDriver
58221fbe59fcbbde9d9a033a95d45d576b422747
[ "Apache-2.0" ]
1
2021-10-18T12:23:37.000Z
2021-10-18T12:23:37.000Z
third_party/gecko-2/win32/include/pkcs11n.h
bwp/SeleniumWebDriver
58221fbe59fcbbde9d9a033a95d45d576b422747
[ "Apache-2.0" ]
2
2018-04-30T21:35:30.000Z
2021-05-14T08:11:46.000Z
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Netscape security libraries. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1994-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Dr Stephen Henson <stephen.henson@gemplus.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef _PKCS11N_H_ #define _PKCS11N_H_ #ifdef DEBUG static const char CKT_CVS_ID[] = "@(#) $RCSfile: pkcs11n.h,v $ $Revision: 1.19.22.2 $ $Date: 2010/12/04 19:10:46 $"; #endif /* DEBUG */ /* * pkcs11n.h * * This file contains the NSS-specific type definitions for Cryptoki * (PKCS#11). */ /* * NSSCK_VENDOR_NSS * * Cryptoki reserves the high half of all the number spaces for * vendor-defined use. I'd like to keep all of our NSS- * specific values together, but not in the oh-so-obvious * 0x80000001, 0x80000002, etc. area. So I've picked an offset, * and constructed values for the beginnings of our spaces. * * Note that some "historical" Netscape values don't fall within * this range. */ #define NSSCK_VENDOR_NSS 0x4E534350 /* NSCP */ /* * NSS-defined object classes * */ #define CKO_NSS (CKO_VENDOR_DEFINED|NSSCK_VENDOR_NSS) #define CKO_NSS_CRL (CKO_NSS + 1) #define CKO_NSS_SMIME (CKO_NSS + 2) #define CKO_NSS_TRUST (CKO_NSS + 3) #define CKO_NSS_BUILTIN_ROOT_LIST (CKO_NSS + 4) #define CKO_NSS_NEWSLOT (CKO_NSS + 5) #define CKO_NSS_DELSLOT (CKO_NSS + 6) /* * NSS-defined key types * */ #define CKK_NSS (CKK_VENDOR_DEFINED|NSSCK_VENDOR_NSS) #define CKK_NSS_PKCS8 (CKK_NSS + 1) #define CKK_NSS_JPAKE_ROUND1 (CKK_NSS + 2) #define CKK_NSS_JPAKE_ROUND2 (CKK_NSS + 3) /* * NSS-defined certificate types * */ #define CKC_NSS (CKC_VENDOR_DEFINED|NSSCK_VENDOR_NSS) /* FAKE PKCS #11 defines */ #define CKA_DIGEST 0x81000000L #define CKA_FLAGS_ONLY 0 /* CKA_CLASS */ /* * NSS-defined object attributes * */ #define CKA_NSS (CKA_VENDOR_DEFINED|NSSCK_VENDOR_NSS) #define CKA_NSS_URL (CKA_NSS + 1) #define CKA_NSS_EMAIL (CKA_NSS + 2) #define CKA_NSS_SMIME_INFO (CKA_NSS + 3) #define CKA_NSS_SMIME_TIMESTAMP (CKA_NSS + 4) #define CKA_NSS_PKCS8_SALT (CKA_NSS + 5) #define CKA_NSS_PASSWORD_CHECK (CKA_NSS + 6) #define CKA_NSS_EXPIRES (CKA_NSS + 7) #define CKA_NSS_KRL (CKA_NSS + 8) #define CKA_NSS_PQG_COUNTER (CKA_NSS + 20) #define CKA_NSS_PQG_SEED (CKA_NSS + 21) #define CKA_NSS_PQG_H (CKA_NSS + 22) #define CKA_NSS_PQG_SEED_BITS (CKA_NSS + 23) #define CKA_NSS_MODULE_SPEC (CKA_NSS + 24) #define CKA_NSS_OVERRIDE_EXTENSIONS (CKA_NSS + 25) #define CKA_NSS_JPAKE_SIGNERID (CKA_NSS + 26) #define CKA_NSS_JPAKE_PEERID (CKA_NSS + 27) #define CKA_NSS_JPAKE_GX1 (CKA_NSS + 28) #define CKA_NSS_JPAKE_GX2 (CKA_NSS + 29) #define CKA_NSS_JPAKE_GX3 (CKA_NSS + 30) #define CKA_NSS_JPAKE_GX4 (CKA_NSS + 31) #define CKA_NSS_JPAKE_X2 (CKA_NSS + 32) #define CKA_NSS_JPAKE_X2S (CKA_NSS + 33) /* * Trust attributes: * * If trust goes standard, these probably will too. So I'll * put them all in one place. */ #define CKA_TRUST (CKA_NSS + 0x2000) /* "Usage" key information */ #define CKA_TRUST_DIGITAL_SIGNATURE (CKA_TRUST + 1) #define CKA_TRUST_NON_REPUDIATION (CKA_TRUST + 2) #define CKA_TRUST_KEY_ENCIPHERMENT (CKA_TRUST + 3) #define CKA_TRUST_DATA_ENCIPHERMENT (CKA_TRUST + 4) #define CKA_TRUST_KEY_AGREEMENT (CKA_TRUST + 5) #define CKA_TRUST_KEY_CERT_SIGN (CKA_TRUST + 6) #define CKA_TRUST_CRL_SIGN (CKA_TRUST + 7) /* "Purpose" trust information */ #define CKA_TRUST_SERVER_AUTH (CKA_TRUST + 8) #define CKA_TRUST_CLIENT_AUTH (CKA_TRUST + 9) #define CKA_TRUST_CODE_SIGNING (CKA_TRUST + 10) #define CKA_TRUST_EMAIL_PROTECTION (CKA_TRUST + 11) #define CKA_TRUST_IPSEC_END_SYSTEM (CKA_TRUST + 12) #define CKA_TRUST_IPSEC_TUNNEL (CKA_TRUST + 13) #define CKA_TRUST_IPSEC_USER (CKA_TRUST + 14) #define CKA_TRUST_TIME_STAMPING (CKA_TRUST + 15) #define CKA_TRUST_STEP_UP_APPROVED (CKA_TRUST + 16) #define CKA_CERT_SHA1_HASH (CKA_TRUST + 100) #define CKA_CERT_MD5_HASH (CKA_TRUST + 101) /* NSS trust stuff */ /* XXX fgmr new ones here-- step-up, etc. */ /* HISTORICAL: define used to pass in the database key for DSA private keys */ #define CKA_NETSCAPE_DB 0xD5A0DB00L #define CKA_NETSCAPE_TRUST 0x80000001L /* FAKE PKCS #11 defines */ #define CKM_FAKE_RANDOM 0x80000efeUL #define CKM_INVALID_MECHANISM 0xffffffffUL /* * NSS-defined crypto mechanisms * */ #define CKM_NSS (CKM_VENDOR_DEFINED|NSSCK_VENDOR_NSS) #define CKM_NSS_AES_KEY_WRAP (CKM_NSS + 1) #define CKM_NSS_AES_KEY_WRAP_PAD (CKM_NSS + 2) /* HKDF key derivation mechanisms. See CK_NSS_HKDFParams for documentation. */ #define CKM_NSS_HKDF_SHA1 (CKM_NSS + 3) #define CKM_NSS_HKDF_SHA256 (CKM_NSS + 4) #define CKM_NSS_HKDF_SHA384 (CKM_NSS + 5) #define CKM_NSS_HKDF_SHA512 (CKM_NSS + 6) /* J-PAKE round 1 key generation mechanisms. * * Required template attributes: CKA_PRIME, CKA_SUBPRIME, CKA_BASE, * CKA_NSS_JPAKE_SIGNERID * Output key type: CKK_NSS_JPAKE_ROUND1 * Output key class: CKO_PRIVATE_KEY * Parameter type: CK_NSS_JPAKERound1Params * */ #define CKM_NSS_JPAKE_ROUND1_SHA1 (CKM_NSS + 7) #define CKM_NSS_JPAKE_ROUND1_SHA256 (CKM_NSS + 8) #define CKM_NSS_JPAKE_ROUND1_SHA384 (CKM_NSS + 9) #define CKM_NSS_JPAKE_ROUND1_SHA512 (CKM_NSS + 10) /* J-PAKE round 2 key derivation mechanisms. * * Required template attributes: CKA_NSS_JPAKE_PEERID * Input key type: CKK_NSS_JPAKE_ROUND1 * Output key type: CKK_NSS_JPAKE_ROUND2 * Output key class: CKO_PRIVATE_KEY * Parameter type: CK_NSS_JPAKERound2Params */ #define CKM_NSS_JPAKE_ROUND2_SHA1 (CKM_NSS + 11) #define CKM_NSS_JPAKE_ROUND2_SHA256 (CKM_NSS + 12) #define CKM_NSS_JPAKE_ROUND2_SHA384 (CKM_NSS + 13) #define CKM_NSS_JPAKE_ROUND2_SHA512 (CKM_NSS + 14) /* J-PAKE final key material derivation mechanisms * * Input key type: CKK_NSS_JPAKE_ROUND2 * Output key type: CKK_GENERIC_SECRET * Output key class: CKO_SECRET_KEY * Parameter type: CK_NSS_JPAKEFinalParams * * You must apply a KDF (e.g. CKM_NSS_HKDF_*) to resultant keying material * to get a key with uniformly distributed bits. */ #define CKM_NSS_JPAKE_FINAL_SHA1 (CKM_NSS + 15) #define CKM_NSS_JPAKE_FINAL_SHA256 (CKM_NSS + 16) #define CKM_NSS_JPAKE_FINAL_SHA384 (CKM_NSS + 17) #define CKM_NSS_JPAKE_FINAL_SHA512 (CKM_NSS + 18) /* * HISTORICAL: * Do not attempt to use these. They are only used by NETSCAPE's internal * PKCS #11 interface. Most of these are place holders for other mechanism * and will change in the future. */ #define CKM_NETSCAPE_PBE_SHA1_DES_CBC 0x80000002UL #define CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC 0x80000003UL #define CKM_NETSCAPE_PBE_SHA1_40_BIT_RC2_CBC 0x80000004UL #define CKM_NETSCAPE_PBE_SHA1_128_BIT_RC2_CBC 0x80000005UL #define CKM_NETSCAPE_PBE_SHA1_40_BIT_RC4 0x80000006UL #define CKM_NETSCAPE_PBE_SHA1_128_BIT_RC4 0x80000007UL #define CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC 0x80000008UL #define CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN 0x80000009UL #define CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN 0x8000000aUL #define CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN 0x8000000bUL #define CKM_TLS_PRF_GENERAL 0x80000373UL typedef struct CK_NSS_JPAKEPublicValue { CK_BYTE * pGX; CK_ULONG ulGXLen; CK_BYTE * pGV; CK_ULONG ulGVLen; CK_BYTE * pR; CK_ULONG ulRLen; } CK_NSS_JPAKEPublicValue; typedef struct CK_NSS_JPAKERound1Params { CK_NSS_JPAKEPublicValue gx1; /* out */ CK_NSS_JPAKEPublicValue gx2; /* out */ } CK_NSS_JPAKERound1Params; typedef struct CK_NSS_JPAKERound2Params { CK_BYTE * pSharedKey; /* in */ CK_ULONG ulSharedKeyLen; /* in */ CK_NSS_JPAKEPublicValue gx3; /* in */ CK_NSS_JPAKEPublicValue gx4; /* in */ CK_NSS_JPAKEPublicValue A; /* out */ } CK_NSS_JPAKERound2Params; typedef struct CK_NSS_JPAKEFinalParams { CK_NSS_JPAKEPublicValue B; /* in */ } CK_NSS_JPAKEFinalParams; /* * NSS-defined return values * */ #define CKR_NSS (CKM_VENDOR_DEFINED|NSSCK_VENDOR_NSS) #define CKR_NSS_CERTDB_FAILED (CKR_NSS + 1) #define CKR_NSS_KEYDB_FAILED (CKR_NSS + 2) /* Mandatory parameter for the CKM_NSS_HKDF_* key deriviation mechanisms. See RFC 5869. bExtract: If set, HKDF-Extract will be applied to the input key. If the optional salt is given, it is used; otherwise, the salt is set to a sequence of zeros equal in length to the HMAC output. If bExpand is not set, then the key template given to C_DeriveKey must indicate an output key size less than or equal to the output size of the HMAC. bExpand: If set, HKDF-Expand will be applied to the input key (if bExtract is not set) or to the result of HKDF-Extract (if bExtract is set). Any info given in the optional pInfo field will be included in the calculation. The size of the output key must be specified in the template passed to C_DeriveKey. */ typedef struct CK_NSS_HKDFParams { CK_BBOOL bExtract; CK_BYTE_PTR pSalt; CK_ULONG ulSaltLen; CK_BBOOL bExpand; CK_BYTE_PTR pInfo; CK_ULONG ulInfoLen; } CK_NSS_HKDFParams; /* * Trust info * * This isn't part of the Cryptoki standard (yet), so I'm putting * all the definitions here. Some of this would move to nssckt.h * if trust info were made part of the standard. In view of this * possibility, I'm putting my (NSS) values in the NSS * vendor space, like everything else. */ typedef CK_ULONG CK_TRUST; /* The following trust types are defined: */ #define CKT_VENDOR_DEFINED 0x80000000 #define CKT_NSS (CKT_VENDOR_DEFINED|NSSCK_VENDOR_NSS) /* If trust goes standard, these'll probably drop out of vendor space. */ #define CKT_NSS_TRUSTED (CKT_NSS + 1) #define CKT_NSS_TRUSTED_DELEGATOR (CKT_NSS + 2) #define CKT_NSS_UNTRUSTED (CKT_NSS + 3) #define CKT_NSS_MUST_VERIFY (CKT_NSS + 4) #define CKT_NSS_TRUST_UNKNOWN (CKT_NSS + 5) /* default */ /* * These may well remain NSS-specific; I'm only using them * to cache resolution data. */ #define CKT_NSS_VALID (CKT_NSS + 10) #define CKT_NSS_VALID_DELEGATOR (CKT_NSS + 11) /* don't leave old programs in a lurch just yet, give them the old NETSCAPE * synonym */ #define CKO_NETSCAPE_CRL CKO_NSS_CRL #define CKO_NETSCAPE_SMIME CKO_NSS_SMIME #define CKO_NETSCAPE_TRUST CKO_NSS_TRUST #define CKO_NETSCAPE_BUILTIN_ROOT_LIST CKO_NSS_BUILTIN_ROOT_LIST #define CKO_NETSCAPE_NEWSLOT CKO_NSS_NEWSLOT #define CKO_NETSCAPE_DELSLOT CKO_NSS_DELSLOT #define CKK_NETSCAPE_PKCS8 CKK_NSS_PKCS8 #define CKA_NETSCAPE_URL CKA_NSS_URL #define CKA_NETSCAPE_EMAIL CKA_NSS_EMAIL #define CKA_NETSCAPE_SMIME_INFO CKA_NSS_SMIME_INFO #define CKA_NETSCAPE_SMIME_TIMESTAMP CKA_NSS_SMIME_TIMESTAMP #define CKA_NETSCAPE_PKCS8_SALT CKA_NSS_PKCS8_SALT #define CKA_NETSCAPE_PASSWORD_CHECK CKA_NSS_PASSWORD_CHECK #define CKA_NETSCAPE_EXPIRES CKA_NSS_EXPIRES #define CKA_NETSCAPE_KRL CKA_NSS_KRL #define CKA_NETSCAPE_PQG_COUNTER CKA_NSS_PQG_COUNTER #define CKA_NETSCAPE_PQG_SEED CKA_NSS_PQG_SEED #define CKA_NETSCAPE_PQG_H CKA_NSS_PQG_H #define CKA_NETSCAPE_PQG_SEED_BITS CKA_NSS_PQG_SEED_BITS #define CKA_NETSCAPE_MODULE_SPEC CKA_NSS_MODULE_SPEC #define CKM_NETSCAPE_AES_KEY_WRAP CKM_NSS_AES_KEY_WRAP #define CKM_NETSCAPE_AES_KEY_WRAP_PAD CKM_NSS_AES_KEY_WRAP_PAD #define CKR_NETSCAPE_CERTDB_FAILED CKR_NSS_CERTDB_FAILED #define CKR_NETSCAPE_KEYDB_FAILED CKR_NSS_KEYDB_FAILED #define CKT_NETSCAPE_TRUSTED CKT_NSS_TRUSTED #define CKT_NETSCAPE_TRUSTED_DELEGATOR CKT_NSS_TRUSTED_DELEGATOR #define CKT_NETSCAPE_UNTRUSTED CKT_NSS_UNTRUSTED #define CKT_NETSCAPE_MUST_VERIFY CKT_NSS_MUST_VERIFY #define CKT_NETSCAPE_TRUST_UNKNOWN CKT_NSS_TRUST_UNKNOWN #define CKT_NETSCAPE_VALID CKT_NSS_VALID #define CKT_NETSCAPE_VALID_DELEGATOR CKT_NSS_VALID_DELEGATOR /* * These are not really PKCS #11 values specifically. They are the 'loadable' * module spec NSS uses. The are available for others to use as well, but not * part of the formal PKCS #11 spec. * * The function 'FIND' returns an array of PKCS #11 initialization strings * The function 'ADD' takes a PKCS #11 initialization string and stores it. * The function 'DEL' takes a 'name= library=' value and deletes the associated * string. * The function 'RELEASE' frees the array returned by 'FIND' */ #define SECMOD_MODULE_DB_FUNCTION_FIND 0 #define SECMOD_MODULE_DB_FUNCTION_ADD 1 #define SECMOD_MODULE_DB_FUNCTION_DEL 2 #define SECMOD_MODULE_DB_FUNCTION_RELEASE 3 typedef char ** (PR_CALLBACK *SECMODModuleDBFunc)(unsigned long function, char *parameters, void *moduleSpec); /* softoken slot ID's */ #define SFTK_MIN_USER_SLOT_ID 4 #define SFTK_MAX_USER_SLOT_ID 100 #define SFTK_MIN_FIPS_USER_SLOT_ID 101 #define SFTK_MAX_FIPS_USER_SLOT_ID 127 #endif /* _PKCS11N_H_ */
37.212871
116
0.721831
[ "object" ]
834269e9f09e49454f14778662c065c4fa698c93
2,387
h
C
marstd2/CEdge.h
marcel303/marstd2004
8494eae253bea7c740f68458b0084c82c7ce2e0e
[ "MIT" ]
1
2020-05-20T12:31:35.000Z
2020-05-20T12:31:35.000Z
marstd2/CEdge.h
marcel303/marstd2004
8494eae253bea7c740f68458b0084c82c7ce2e0e
[ "MIT" ]
null
null
null
marstd2/CEdge.h
marcel303/marstd2004
8494eae253bea7c740f68458b0084c82c7ce2e0e
[ "MIT" ]
1
2020-05-20T12:31:40.000Z
2020-05-20T12:31:40.000Z
#ifndef __cEDGE_h__ #define __cEDGE_h__ ////////////////////////////////////////////////////////////////////// // MarSTD version 2004 - (c)2004 - Marcel Smit // // // // Marcel_Smit_101@hotmail.com // // marcel.athlon@hccnet.nl // // // // This code may not be used in a commercial product without my // // permission. If you redistribute it, this message must remain // // intact. If you use this code, some acknowledgement would be // // appreciated. ;-) // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /** @file CEdge.h: CEdge implementation. */ ////////////////////////////////////////////////////////////////////// // FIXME: Add edge2 member which will point to edge with next vertex. #include "CList.h" #include "CPlane.h" #include "CVertex.h" //--------------------------------------------------------------------------- /// Geometry: Edge type. /** * Edges are used by polygons to define their contours using vectors. * An edge also has 3 planes. These are used to optimize collision detetcion, etc. */ class CEdge : public CVertex { public: CEdge() : CVertex() { edge2 = 0; prev = 0; next = 0; } ~CEdge() { } public: CPlane plane; ///< Plane perpendicular to polygon normal and edge. CPlane edge_plane; ///< Plane parallel to edge. edge_plane * edge2->p == 1.0. CPlane poly_plane; ///< Average plane of all planes of the polygons that share this point. CEdge* edge2; ///< Edge that will give next point. public: /** * Copies vector. */ void operator=(CEdge& edge) { CVertex::operator=(edge); plane = edge.plane; edge_plane = edge.edge_plane; } public: CEdge* prev; ///< Previous edge in DLL. CEdge* next; ///< Next edge in DLL. public: /** * Unlinks this edge from DLL. */ CEdge* unlink() { DLLIST_UNLINK_SELF(); } }; //--------------------------------------------------------------------------- #endif
27.125
92
0.425639
[ "geometry", "vector" ]
83489eac2fa0790962fc8065da3e6c90be67db14
40,951
c
C
src/bary.c
fermi-lat/timeSystem
ae46f5863bc345ed9491a53fa9af611536c7f41c
[ "BSD-3-Clause" ]
null
null
null
src/bary.c
fermi-lat/timeSystem
ae46f5863bc345ed9491a53fa9af611536c7f41c
[ "BSD-3-Clause" ]
null
null
null
src/bary.c
fermi-lat/timeSystem
ae46f5863bc345ed9491a53fa9af611536c7f41c
[ "BSD-3-Clause" ]
null
null
null
char *bcrcsid = "RCS: $Id: bary.c,v 1.1.1.1 2006/04/21 20:56:15 peachey Exp $" ; /*----------------------------------------------------------------------- * * bary.c * * Date: 20 November 1997 * * Arnold Rots, USRA * * bary contains a set of functions around barycorr, calculating barycenter * corrections for, in principle, any observations. * Required: * bary.h * dpleph.c * cfitsio * * Externally referenced: * int baryinit (enum Observatory, char *, char *, double, double, char *, int) ; * double barycorr (MJDTime *, double *, double *) ; * int timeparms (char *, MJDTime *, double, int, PsrTimPar *, PsrBinPar *, int) ; * double absphase (MJDTime *, PsrTimPar *, int, PsrBinPar *, * int, double *, char *, int *) ; * double xabsphase (double, PsrTimPar *, int, PsrBinPar *, * int, double *, char *, int *) ; * fitsfile *openFFile (const char *name) * double *scorbit (char *, MJDTime *, int *oerror) * void met2mjd (double, MJDTime *) ; * double mjd2met (MJDTime *) ; * const char *convertTime (MJDTime *) ; * const char *fitsdate () * double ctatv (long, double) ; * void c200to405 (double *, int) ; * * MET equivalents: * double xbarycorr (double, double *, double *) ; * double *xscorbit (char *, double, int *) ; * * Internal: * double TTtoTDB (MJDTime *) ; * double TTtoTCG (MJDTime *) ; * double TDBtoTCB (MJDTime *) ; * double UTCtoTAI (MJDTime *) ; * double toTT (MJDTime *) ; * double toUTC (MJDTime *) ; * double binorbit (MJDTime *, PsrBinPar *) ; * * It is assumed that the environment variable $TIMING_DIR is defined * and that the ephemeris file $TIMING_DIR/ephem.fits exists. * It is also assumed that $TIMING_DIR/psrtime.dat and * $TIMING_DIR/psrbin.dat exist. * However, all these names are defined as mocros in bary.h. * * Certain parts are adapted from software * by Joseph M. Fierro, Stanford University, EGRET project, * and from software provided with the JPL ephemeris. * *----------------------------------------------------------------------*/ #define BARY_CONST 1 #include "bary.h" #undef BARY_CONST static char ephemname[128] ; static double c, msol, radsol ; static int denum ; static double met2day, day2met, met2sec ; /*----------------------------------------------------------------------- * * met2mjd converts MET (seconds or days) to MJD day and fractional day. * void met2mjd (double t, MJDTime *mjdTT) * t: MET time (s or d) * mjdTT: MJD (TT) day * *----------------------------------------------------------------------*/ void met2mjd (double t, MJDTime *mjdTT) { long mjdTTint ; double mjdTTfr ; mjdTTint = (long) t * met2day ; mjdTTfr = t * met2day - mjdTTint + mjdRef.MJDfr ; mjdTTint += mjdRef.MJDint ; if ( mjdTTfr >= 1.0 ) { (mjdTTint)++ ; mjdTTfr-- ; } else if ( mjdTTfr < 0.0 ) { (mjdTTint)-- ; mjdTTfr++ ; } mjdTT->ts = mjdRef.ts ; mjdTT->MJDint = mjdTTint ; mjdTT->MJDfr = mjdTTfr ; return ; } /*----------------------------------------------------------------------- * * mjd2met converts MJD day and fractional day to MET (seconds or days). * double mjd2met (MJDTime *mjdTT) * mjdTT: MJD (TT) day * return: MET time (s or d) * *----------------------------------------------------------------------*/ double mjd2met (MJDTime *mjdTT) { switch (mjdRef.ts ) { case TT: toTT (mjdTT) ; break ; case UTC: toUTC (mjdTT) ; break ; default: break ; } return ( (mjdTT->MJDint - mjdRef.MJDint + mjdTT->MJDfr - mjdRef.MJDfr) * day2met ) ; } /*----------------------------------------------------------------------- * * UTCtoTAI returns TAI-UTC * double UTCtoTAI (long jdUTCint, double jdUTCfr) * mjdUTC: MJD (UTC) day * return: TAI - UTC (s) * Only works for dates after 1 Jan 1961 (JD2437300.5) * *----------------------------------------------------------------------*/ double UTCtoTAI (MJDTime *mjdUTC) { int i ; double dt = 0 ; while ( mjdUTC->MJDfr >= 1.0 ) { mjdUTC->MJDint++ ; mjdUTC->MJDfr-- ; } while ( mjdUTC->MJDfr < 0.0 ) { mjdUTC->MJDint-- ; mjdUTC->MJDfr++ ; } i = numleaps - 1 ; while ( ( mjdUTC->MJDint < leapsMJD[i] ) && i ) i-- ; if ( i > 12 ) dt = leapsecs[i] ; else dt = leapsecs[i] + (mjdUTC->MJDint - MJDoffset[i] + mjdUTC->MJDfr) * leapcoeff[i] ; return (double) dt ; } /*----------------------------------------------------------------------- * * TTtoTDB calculates TDB-TT at time TT. * double TTtoTDB (long jdTTint, double jdTTfr) * mjdTT: MJD (TT) day * return: TDB - TT (s) * * It uses the coefficients from Fairhead & Bretagnon 1990, * A&A 229, 240, as provided by ctatv. * The accuracy is better than 100 ns. * * The proper way to do all this is to abandon TDB and use TCB. * * The way this is done is as follows: TDB-TT and its derivative are * calculated for the integer part of the Julian Day (when needed). * The precise value is derived from fractional part and derivative. * *----------------------------------------------------------------------*/ double TTtoTDB (MJDTime *mjdTT) { static double tdbtdt ; static double tdbtdtdot ; static long oldmjd = 0 ; long l ; while ( mjdTT->MJDfr >= 1.0 ) { mjdTT->MJDint++ ; mjdTT->MJDfr-- ; } while ( mjdTT->MJDfr < 0.0 ) { mjdTT->MJDint-- ; mjdTT->MJDfr++ ; } if ( mjdTT->MJDint != oldmjd ) { oldmjd = mjdTT->MJDint ; l = oldmjd + 2400001 ; tdbtdt = ctatv (l, 0.0) ; tdbtdtdot = ctatv (l, 0.5) - ctatv (l, -0.5) ; } return ( tdbtdt + (mjdTT->MJDfr - 0.5) * tdbtdtdot ) ; } /*----------------------------------------------------------------------- * * TDBtoTCB calculates TCB-TDB at time TDB. * double TDBtoTCB (MJDTime *mjdTB) * mjdTB: MJD (TB) day * return: TCB - TDB (s) * *----------------------------------------------------------------------*/ double TDBtoTCB (MJDTime *mjdTB) { return LB * ( (mjdTB->MJDint - 43144) + mjdTB->MJDfr ) * SECDAY ; } /*----------------------------------------------------------------------- * * TTtoTCG calculates TCG-TT at time TT. * double TTtoTCG (MJDTime *mjdTB) * mjdTB: MJD (TB) day * return: TCG - TT (s) * *----------------------------------------------------------------------*/ double TTtoTCG (MJDTime *mjdTB) { return LG * ( (mjdTB->MJDint - 43144) + mjdTB->MJDfr ) * SECDAY ; } /*----------------------------------------------------------------------- * * toTT converts mjd to TT * double toTT (MJDTime *mjd) * mjd: MJD (?) day; converted * return: Change in seconds * *----------------------------------------------------------------------*/ double toTT (MJDTime *mjd) { double total = 0.0 ; switch ( mjd->ts ) { case TT: break ; /* from TDB and from TCB are not (yet) implemented */ case TDB: case TCB: break ; case UTC: total += UTCtoTAI (mjd) ; case TAI: total += TAItoTT ; mjd->MJDfr += total / SECDAY ; mjd->ts = TT ; break ; default: break ; } return total ; } /*----------------------------------------------------------------------- * * toUTC converts mjd to UTC * double toUTC (MJDTime *mjd) * mjd: MJD (?) day; converted * return: Change in seconds * *----------------------------------------------------------------------*/ double toUTC (MJDTime *mjd) { double total = 0.0 ; switch ( mjd->ts ) { case UTC: break ; /* from TDB and from TCB are not (yet) implemented */ case TDB: case TCB: break ; case TT: total -= TAItoTT ; case TAI: total -= UTCtoTAI (mjd) ; mjd->MJDfr += total / SECDAY ; mjd->ts = UTC ; break ; default: break ; } return total ; } const char *convertTime (MJDTime *mjd) /*---------------------------------------------------------------------- * Convert MJD time to a FITS-type date and time string. * * WARNING: ONLY GUARANTEED TILL ARNOLD'S RETIREMENT !!! * * Input: mjd time to be converted (MJD) * * Return: string containing date and time as * yyyy-mm-ddThh:mm:ss or yy/mm/dd * ----------------------------------------------------------------------*/ { long mjdi ; double mjdf, t ; int day, mon, yr; int hr, min, sec; const int md[]={31,28,31,30,31,30,31,31,30,31,30,31} ; static char date[24] ; /* --------------------- * - First, the day number - * - All relative to 1902 - * --------------------- */ mjdi = mjd->MJDint ; mjdf = mjd->MJDfr ; while ( mjdf >= 1.0 ) { mjdf-- ; mjdi++ ; } while ( mjdf < 0.0 ) { mjdf++ ; mjdi-- ; } t = mjdf * SECDAY ; day = mjdi - 15750 ; /* --------------------- * - Next, the time of day - * --------------------- */ hr = (int) (t / 3600.0); t -= hr * 3600; min = (int) (t / 60.0); sec = (int) (t - min * 60) ; /* ----------------------- * - Deal with the leap days - * ----------------------- */ yr = 2 + (4*(day/1461)); day %= 1461; if ( day == 789 ) { mon = 2; day = 29; yr += 2; } else { /* --------------------- * - Correct for leap days - * --------------------- */ if ( day > 789 ) day--; /* ------------ * - Get the year - * ------------ */ yr += (day/365); day %= 365; day++; /* ----------------- * - Get month and day - * ----------------- */ mon = 0; while ( day > md[mon] ) { day -= md[mon]; mon++; } mon++; } /* ------------------ * - Format the strings - * ------------------ */ if ( yr < 96 ) /* AXAF uses an early change-over date */ sprintf (date, "%02d/%02d/%02d\0", day, mon, yr); /* ------------ * - Next century - * ------------ */ else sprintf (date, "%04d-%02d-%02dT%02d:%02d:%02d\0", yr+1900, mon, day, hr, min, sec) ; /* ---- * - Done - * ---- */ return date ; } const char *fitsdate () /*---------------------------------------------------------------------- * Convert current UTC date and time to a FITS-type date and time string. * * Return: string containing current UTC date and time as * yyyy-mm-ddThh:mm:ss * ----------------------------------------------------------------------*/ { time_t tt ; struct tm *tmptr ; static char str[48] ; time (&tt) ; tmptr = gmtime (&tt) ; strftime (str, 40, "%Y-%m-%dT%H:%M:%S", tmptr) ; return str ; } /*----------------------------------------------------------------------- * * openAFile finds one of the ASCII system files and opens it for reading. * FILE *openAFile (const char *name) * name: Name of the file * openAFile first tries to find the file in TIMINGDIR, then in LHEADIR. * * return: file pointer, NULL if not found * *----------------------------------------------------------------------*/ FILE *openAFile (const char *name) { char fileName[1024] ; char *filepath = NULL ; FILE *FF = NULL ; if ( filepath = getenv (TIMINGDIR) ) { sprintf (fileName, "%s/%s", filepath, name) ; FF = fopen (fileName, "r") ; } if ( FF == NULL ) if ( filepath = getenv (LHEADIR) ) { sprintf (fileName, "%s/%s", filepath, name) ; FF = fopen (fileName, "r") ; } if ( filepath == NULL ) fprintf (stderr, "Neither $%s, nor $%s is defined\n", TIMINGDIR, LHEADIR) ; else if ( FF == NULL ) fprintf (stderr, "File %s could not be found in %s\n", fileName, filepath) ; return FF ; } /*----------------------------------------------------------------------- * * openFFile finds one of the FITS system files and opens it for reading. * fitsfile *openFFile (const char *name) * name: Name of the file * openFFile first tries to find the file in TIMINGDIR, then in LHEADIR. * * return: FITS file pointer, NULL if not found * *----------------------------------------------------------------------*/ fitsfile *openFFile (const char *name) { char fileName[1024] ; char *filepath = NULL ; fitsfile *FF = NULL ; int error = 0 ; if ( filepath = getenv (TIMINGDIR) ) { sprintf (fileName, "%s/%s", filepath, name) ; fits_open_file (&FF, fileName, READONLY, &error) ; } if ( FF == NULL ) if ( filepath = getenv (LHEADIR) ) { error = 0 ; sprintf (fileName, "%s/%s", filepath, name) ; fits_open_file (&FF, fileName, READONLY, &error) ; } if ( filepath == NULL ) fprintf (stderr, "Neither $%s, nor $%s is defined\n", TIMINGDIR, LHEADIR) ; else if ( FF == NULL ) fprintf (stderr, "File %s could not be found in %s\n", fileName, filepath) ; return FF ; } /*----------------------------------------------------------------------- * * baryinit sets up the path to the ephemeris file and gets the leap * seconds information. * int baryinit (enum Observatory obs, char *fromts, char *tots, * double mjdi, double mjdf, char *timeunit, int ephnum) * obs: Observatory (Unknown, Geocenter, XTE, AXAF) * fromts: Time system of input * tots: Time system to convert to * mjdi: MJDREFI; use mission default if =-1.0 * mjdf: MJDREFF * timeunit: Unit of time (s or d) * ephnum: Ephemeris number requested (200, 405; 0: default) * if < 0: do not initialize ephemeris * return: denum; 0 upon error * *----------------------------------------------------------------------*/ int baryinit (enum Observatory obs, char *fromts, char *tots, double mjdi, double mjdf, char *timeunit, int ephnum) { char from[5], to[5] ; int i ; FILE *FF ; char mon[16], dum1[16], dum2[16] ; mission = obs ; /* * Sort out time systems ----------------------------------------------- */ strncpy (from, fromts, 3) ; strncpy (to, tots, 3) ; for (i=0; i<3; i++) { if ( ( from[i] > 96 ) && ( from[i] < 123 ) ) from[i] -= 32 ; if ( ( to[i] > 96 ) && ( to[i] < 123 ) ) to[i] -= 32 ; } if ( !( strcmp(from, "TT") ) ) fromTS = TT ; else if ( !( strcmp(from, "TDT") ) ) fromTS = TT ; else if ( !( strcmp(from, "ET") ) ) fromTS = TT ; else if ( !( strcmp(from, "TDB") ) ) fromTS = TDB ; else if ( !( strcmp(from, "TB") ) ) fromTS = TDB ; else if ( !( strcmp(from, "TCB") ) ) fromTS = TCB ; else if ( !( strcmp(from, "TAI") ) ) fromTS = TAI ; else if ( !( strcmp(from, "IAT") ) ) fromTS = TAI ; else fromTS = UTC ; if ( !( strcmp(to, "TT") ) ) toTS = TT ; else if ( !( strcmp(to, "TDT") ) ) toTS = TT ; else if ( !( strcmp(to, "ET") ) ) toTS = TT ; else if ( !( strcmp(to, "TDB") ) ) toTS = TDB ; else if ( !( strcmp(to, "TB") ) ) toTS = TDB ; else if ( !( strcmp(to, "TCB") ) ) toTS = TCB ; else if ( !( strcmp(to, "TAI") ) ) toTS = TAI ; else if ( !( strcmp(to, "IAT") ) ) toTS = TAI ; else toTS = UTC ; /* * Set scale factors --------------------------------------------------- */ day2met = ( *timeunit == 'd' ) ? 1.0 : SECDAY ; met2day = 1.0 / day2met ; met2sec = SECDAY / day2met ; /* * Get leap seconds ---------------------------------------------------- */ if ( FF = openAFile (TAIUTC) ) { numleaps = 0 ; while ( fscanf (FF, "%d %s 1 =JD 24%d.5 %s %lg S + (MJD - %lg) X %lg %s", &i, mon, leapsMJD+numleaps, dum1, leapsecs+numleaps, MJDoffset+numleaps, leapcoeff+numleaps, dum2) == 8 ) numleaps++ ; fclose (FF) ; } else { fprintf (stderr, "Could not open leap second file; skipping this step\n") ; return 0 ; } /* * Set the MJD Reference ----------------------------------------------- */ if ( ( obs == AXAF ) && ( mjdi == -1.0) ) { mjdRefi = 50814 ; mjdReff = 0.0 ; } else if ( ( obs != XTE ) || ( mjdi != -1.0) ) { mjdRefi = mjdi + mjdf ; mjdReff = mjdi - mjdRefi ; mjdReff += mjdf ; } mjdRef.MJDint = mjdRefi ; mjdRef.MJDfr = mjdReff ; mjdRef.ts = fromTS ; /* * If fromTS is ET or TAI, or (UTC and TIMEUNIT='s'), * change it to TT and do the conversion in MJDRef. */ switch ( fromTS ) { case UTC: if ( day2met < 10.0 ) break ; case ET: case TAI: fromTS = TT ; toTT (&mjdRef) ; break ; default: break ; } /* * Initialize clock and orbit ------------------------------------------ */ scorbitinit (mission) ; clockinit (mission) ; /* * Initialize ephemeris ------------------------------------------------ */ if ( ephnum >= 0 ) { if ( i = initephem (ephnum, &denum, &c, &radsol, &msol) ) { fprintf (stderr, "Error while initializing ephemeris; status: %d\n", i) ; denum = 0 ; } } else denum = 1 ; return denum ; } /*----------------------------------------------------------------------- * * timeinit sets things up for time conversions and gets the leap * seconds information; no ephemeris initialization. * int timeinit (enum Observatory obs, char *fromts, char *tots, * double mjdi, double mjdf, char *timeunit) * obs: Observatory (Unknown, Geocenter, XTE, AXAF) * fromts: Time system of input * tots: Time system to convert to * mjdi: MJDREFI * mjdf: MJDREFF * timeunit: Unit of time (s or d) * return: 0 upon error * *----------------------------------------------------------------------*/ int timeinit (enum Observatory obs, char *fromts, char *tots, double mjdi, double mjdf, char *timeunit) { return baryinit (obs, fromts, tots, mjdi, mjdf, timeunit, -1) ; } /*----------------------------------------------------------------------- * * MET time interface to main function barycorr: * double xbarycorr (double t, double *sourcedir, double *scposn) * t: MET time of photon/pulse arrival * sourcedir: Direction cosines of source position * scposn: Spacecraft position vector in meters * * * Method: * Convert to JD and call barycorr. * Return calculated delay (in s) * *----------------------------------------------------------------------*/ double xbarycorr (double t, double *sourcedir, double *scposn) { MJDTime mjdTT ; /* * Convert to MJD ------------------------------------------------------ */ met2mjd (t, &mjdTT) ; /* * Get ephemeris data -------------------------------------------------- */ return barycorr (&mjdTT, sourcedir, scposn) ; } /*----------------------------------------------------------------------- * * Main function: * double barycorr (MJDTime *mjdTT, double *sourcedir, double *scposn) * mjdXT: Time of photon/pulse arrival in MJD(??) * sourcedir: Direction cosines of source position * scposn: (Spacecraft) position vector in meters wrt geocenter * Note: it usually does not matter if provided in FK5 * or DE200 frame when using DE405 * * * Method: * Compute index of ephemeris memory corresponding to input date * If (input date is not in memory) then * Load next 32 days of ephemeris data into memory * Calculate position of Sun, Earth, and velocity of Earth * Calculate SSBC-to-S/C vector and Sun-to-S/C vector * Calculate distance and angular size of sun * [ If (object was blocked by sun) ] commented out * [ Return (no delay calculated) ] * Add all propagation effects * Return calculated delay (in s) * * All distances are in light seconds, velocities in ls/s. * *----------------------------------------------------------------------*/ double barycorr (MJDTime *mjdXT, double *sourcedir, double *scposn) { const double *rce, *rcs, *vce; double rca[3], rsa[3]; const double *eposn ; /* Masaharu Hirayama 1 November 2008: Commented out variable 'sunsiz' in the following line because it is not used in any part of this function. */ double total, sundis, /*sunsiz,*/ cth ; MJDTime mjdXX ; MJDTime *mjdTT ; int i; int iearth = 3 ; int isun = 11 ; double jdt[2] ; MJDTime mjdTDB ; /* * Sort out time systems ----------------------------------------------- */ total = 0.0 ; switch ( mjdXT->ts ) { case TT: mjdTT = mjdXT ; break ; case TDB: case TCB: return 0.0 ; case UTC: case TAI: default: mjdTT = &mjdXX ; mjdTT->MJDint = mjdXT->MJDint ; mjdTT->MJDfr = mjdXT->MJDfr ; mjdTT->ts = mjdXT->ts ; total += toTT (mjdTT) ; break ; } /* * Check observatory position ------------------------------------------ */ if ( scposn == NULL ) { fprintf (stderr, "barycorr: Invalid Observatory/Spacecraft position vector\n") ; return 0.0 ; } /*fprintf(stderr,"xbarycorr: got altitude %f km (scposn=[%f:%f:%f]m)\n", (sqrt(pow(scposn[0],2)+pow(scposn[1],2)+pow(scposn[2],2))-6378100.0)/1000., scposn[0],scposn[1],scposn[2]); */ /* * Get all positions --------------------------------------------------- */ jdt[0] = mjdTT->MJDint + 2400001 ; jdt[1] = mjdTT->MJDfr - 0.5 ; if ( (eposn = dpleph (jdt, iearth, isun)) == NULL ) { fprintf (stderr, "barycorr: Could not find solar system ephemeris for MJD %f\n", mjdTT->MJDint) ; return 0.0 ; } rce = eposn ; vce = eposn + 3 ; rcs = eposn + 6 ; for (i = 0; i < 3; i++) { rca[i] = rce[i] + scposn[i]/c; /* SSBC-to-S/C vector */ rsa[i] = rca[i] - rcs[i]; /* Sun-to-S/C vector */ } /* * Calculate the time delay due to the gravitational field of the Sun -- * (I.I. Shapiro, Phys. Rev. Lett. 13, 789 (1964)). -------------------- */ sundis = sqrt(DOT(rsa, rsa)); cth = DOT(sourcedir, rsa)/sundis; /* * Eclipsed by the sun * sunsiz = radsol/sundis; * if ((cth + 1) < 0.5*sunsiz*sunsiz) * return (0); */ /* * Sum all propagation effects ----------------------------------------- */ total += TTtoTDB (mjdTT) + DOT(sourcedir, rca) + DOT(scposn, vce)/c + 2*msol*log(1+cth); /*fprintf(stderr,"total after all propagation effects: %f\n",total); fprintf(stderr,"TTtoTDB(mjdTT): %f\n",TTtoTDB(mjdTT)); fprintf(stderr,"DOT(sourcedir, rca): %f\n",DOT(sourcedir, rca)); fprintf(stderr,"DOT(scposn, vce)/c: %f\n",DOT(scposn,vce)/c); fprintf(stderr,"2*msol*log(1+cth): %f\n",2*msol*log(1+cth)); */ /* * Sort out time systems ----------------------------------------------- */ switch ( toTS ) { case TCB: mjdTDB.MJDint = mjdTT->MJDint ; mjdTDB.MJDfr = mjdTT->MJDfr + total/SECDAY ; mjdTDB.ts = TDB ; total += TDBtoTCB (&mjdTDB) ; break ; default: break ; } /*fprintf(stderr,"final total: %f\n",total);*/ return total ; } /*----------------------------------------------------------------------- * * timeparms gets the timing parameters from the pulsar database. * * char *insource: source name (J1234-5643, B1234-56, or 1234-56) * MJDTime *time: MJD(TB) time for which the parameters are requested * double roffset: extra offset to be applied to radio zero phase (in s) * int bin: binary pulsar? * PsrTimPar *ptp: pulsar timing parameters struct * PsrBinPar *pbp: pulsar binary orbit parameters struct * int debug: chatty * *----------------------------------------------------------------------*/ int timeparms (char *insource, MJDTime *time, double roffset, int bin, PsrTimPar *ptp, PsrBinPar *pbp, int debug) { FILE *PD ; /* Masaharu Hirayama 1 November 2008: Commented out variable 'j' in the following line because it is not used in any part of this function. */ int i/*, j*/ ; int error ; /* Masaharu Hirayama 1 November 2008: Commented out variable 'filename' in the following line because it is not used in any part of this function. char filename[256] ; */ char line[256] ; char line2[256] ; /* Masaharu Hirayama 1 November 2008: Commented out variables 'mjd' and 'dt' in the following lines because it is not used in any part of this function. double mjd[2] ; long dt ; */ char bsource[32] ; char jsource[32] ; char *dsource ; char *source ; char binsource[32] ; /* Masaharu Hirayama 1 November 2008: Commented out variables 'rah', 'ram', 'decd', and 'decm' in the following line because it is not used in any part of this function. int rah, ram, decd, decm ; */ /* Masaharu Hirayama 1 November 2008: Commented out variables 'ras' and 'decs' in the following line because it is not used in any part of this function. */ double /*ras, decs,*/ mjdf, fd, dfd, ddfd, dddfd, rms, lastrms, mjdftrun ; double tr, dtt, dir[3] ; MJDTime mtime ; double scposn0[3] = {0.0, 0.0, 0.0} ; long mjd1, mjd2, mjdi, mjdt, lastmjd2 ; /* Masaharu Hirayama 1 November 2008: Commented out variables 'sdec' in the following line because it is not used in any part of this function. char sdec[12] ; */ int nocover = 0 ; int tdenum, fbin ; double ra, dec ; int timeline (char*, char*, double*, double*, long*, long*, long*, double*, double*, double*, double*, double*, double*, int*, int*, char*) ; /* * Sort out the name --------------------------------------------------- */ if ( ( *insource == 'J' ) || ( *insource == 'j' ) ) { source = insource + 1 ; dsource = jsource ; } else if ( ( *insource == 'B' ) || ( *insource == 'b' ) ) { source = insource + 1 ; dsource = bsource ; } else { source = insource ; dsource = bsource ; } /* * Open the database ---------------------------------------------------- */ error = 0 ; if ( ( PD = openAFile (PSRTIME) ) == NULL ) { fprintf (stderr, "Could not open file %s\n", PSRTIME) ; error = 1 ; } /* * Get integer part of MJD ---------------------------------------------- */ mjdt = time->MJDint ; /* * Search the database -------------------------------------------------- */ fgets (line, 256, PD) ; fgets (line, 256, PD) ; strcpy (dsource, " ") ; while ( strcmp (dsource, source) && !error ) { fgets (line, 256, PD) ; if ( feof(PD) ) error = 2 ; timeline (line, bsource, &ra, &dec, &mjd1, &mjd2, &mjdi, &mjdf, &fd, &dfd, &ddfd, &dddfd, &rms, &fbin, &tdenum, jsource) ; } if ( error > 1 ) fprintf (stderr, "Could not find %s in file %s\n", insource, PSRTIME) ; /* * Locate the right record ---------------------------------------------- */ if ( !error ) { timeline (line, bsource, &ra, &dec, &mjd1, &mjd2, &mjdi, &mjdf, &fd, &dfd, &ddfd, &dddfd, &rms, &fbin, &tdenum, jsource) ; strcpy (binsource, bsource) ; if ( mjdt < mjd1 ) nocover = 1 ; } while ( ( mjdt > mjd2 ) && !error ) { lastmjd2 = mjd2 ; fgets (line2, 256, PD) ; if ( feof(PD) ) { nocover = 1 ; break ; } timeline (line2, bsource, &ra, &dec, &mjd1, &mjd2, &mjdi, &mjdf, &fd, &dfd, &ddfd, &dddfd, &rms, &fbin, &tdenum, jsource) ; if ( strcmp (dsource, source) ) { break ; nocover = 1 ; } if ( mjdt < mjd1 ) { nocover = 1 ; if ( (mjdt - lastmjd2) < (mjd1 - mjdt) ) break ; } strncpy (line, line2, 256) ; } /* * Get the data --------------------------------------------------------- */ if ( !error ) { /* * Find entry with lowest rms ------------------------------------------ */ if ( !nocover ) { timeline (line, bsource, &ra, &dec, &mjd1, &mjd2, &mjdi, &mjdf, &fd, &dfd, &ddfd, &dddfd, &rms, &fbin, &tdenum, jsource) ; lastrms = rms ; /* printf ("First valid entry %d to %d at %f with rms %f\n", * mjd1, mjd2, (double) mjdi+mjdf, rms) ; */ while ( 1 ) { fgets (line2, 256, PD) ; if ( feof(PD) ) { break ; } timeline (line2, bsource, &ra, &dec, &mjd1, &mjd2, &mjdi, &mjdf, &fd, &dfd, &ddfd, &dddfd, &rms, &fbin, &tdenum, jsource) ; if ( strcmp (dsource, source) ) break ; if ( ( mjdt >= mjd1 ) && ( mjdt <= mjd2 ) && ( rms < lastrms ) ) { strncpy (line, line2, 256) ; lastrms = rms ; /* printf ("Changed to entry %d to %d at %f with rms %f\n", * mjd1, mjd2, (double) mjdi+mjdf, rms) ; */ } } } /* * Really get the data -------------------------------------------------- */ timeline (line, bsource, &ra, &dec, &mjd1, &mjd2, &mjdi, &mjdf, &fd, &dfd, &ddfd, &dddfd, &rms, &fbin, &tdenum, jsource) ; ptp->ra = ra ; ptp->dec = dec ; ptp->denum = tdenum ; if ( debug ) printf ("Source: %s, RA = %.8f, Dec = %.8f, Frame = DE%d\n", dsource, ptp->ra, ptp->dec, ptp->denum) ; dir[0] = cos(ptp->ra/RADEG) * cos(ptp->dec/RADEG) ; dir[1] = sin(ptp->ra/RADEG) * cos(ptp->dec/RADEG) ; dir[2] = sin(ptp->dec/RADEG) ; if ( denum != ptp->denum ) { fprintf (stderr, "Warning: You are using Solar System Ephemeris DE%d\n", denum) ; fprintf (stderr, " with a Timing Ephemeris produced with DE%d\n", ptp->denum) ; if ( ( denum == 405 ) && ( ptp->denum == 200 ) ) { c200to405 (dir, debug) ; fprintf (stderr, " The coordinates will be transformed to DE405\n") ; } } ptp->f = fd ; ptp->df = dfd ; ptp->ddf = ddfd ; ptp->dddf = dddfd ; i = mjdf * 100.0 + 0.5 ; mjdftrun = (double) i / 100.0 ; ptp->t0.MJDint = mjdi ; ptp->t0.MJDfr = mjdftrun ; ptp->t0.ts = TDB ; /* * Convert UTC -> MET ---------------------------------------------------- */ mtime.MJDint = mjdi ; mtime.MJDfr = mjdf + roffset / SECDAY ; mtime.ts = UTC ; toTT (&mtime) ; if ( debug ) { printf ("Data MJD(TDB): %d\n", mjdt) ; printf ("Used radio pulsar database entry covering the period:\n") ; printf (" MJD(TDB) %d to %d; rms: %f milliperiod\n", mjd1, mjd2, rms) ; if ( nocover ) printf ("===> Note that no entry could be found covering the observations.\n") ; printf ("Frequency/period ephemeris (T0):\n") ; printf (" MJD(TDB) = %d + %g\n", mjdi, mjdftrun) ; printf (" f = %.14f df/dt = %g d2fdt2 = %g d3fdt3 = %g\n", fd, dfd, ddfd, dddfd) ; printf ("Radio pulse TOA ephemeris (Tr):\n MJD(TT) = %d + %g\n", mtime.MJDint, mtime.MJDfr) ; } tr = barycorr (&mtime, dir, scposn0) ; dtt = tr + ( (mtime.MJDint - ptp->t0.MJDint) + (mtime.MJDfr - ptp->t0.MJDfr) ) * SECDAY ; ptp->radioph = -fd*dtt - dfd*dtt*dtt*0.5 - ddfd*dtt*dtt*dtt/6.0 - dddfd*dtt*dtt*dtt*dtt/24.0 ; if ( debug ) printf (" TDB-TT = %18.17g\n DT (=Tr-T0) =%10.9g Phase(T0) = %10.9g\n", tr, dtt, ptp->radioph) ; } fclose (PD) ; /* * Binary orbits -------------------------------------------------------- */ if ( fbin ) { if ( bin ) fbin = 0 ; else bin = 1 ; } if ( bin && !error ) { if ( ( PD = openAFile (PSRBIN) ) == NULL ) { fprintf (stderr, "Could not open file %s\n", PSRBIN) ; error = -1 ; } /* * Search the database -------------------------------------------------- */ fgets (line, 256, PD) ; fgets (line, 256, PD) ; strcpy (dsource, " ") ; while ( strcmp (dsource, binsource) && !error ) { fgets (line, 256, PD) ; if ( feof(PD) ) error = -2 ; sscanf (line, "%s", dsource) ; } if ( error < -1 ) fprintf (stderr, "Could not find %s in file %s\n", insource, PSRBIN) ; /* * Locate and read the right record ------------------------------------- */ if ( !error ) { while ( 1 ) { fgets (line2, 256, PD) ; if ( feof (PD) || strncmp (line2, binsource, 7) ) break ; strncpy (line, line2, 256) ; } for (i=0; i<strlen(line); i++) if ( line[i] == 'D' ) line[i] = 'E' ; sscanf (line, "%s %lg %lg %lg %ld%lg %lg %lg %lg %lg", dsource, &(pbp->pb), &(pbp->a1sini), &(pbp->e), &mjdi, &mjdftrun, &(pbp->omega), &(pbp->omdot), &(pbp->gamma), &(pbp->pbdot)) ; pbp->t0.MJDint = mjdi ; pbp->t0.MJDfr = mjdftrun ; pbp->t0.ts = TDB ; pbp->omega /= RADEG ; pbp->omdot /= RADEG * 365.25 * SECDAY ; if ( debug ) { printf (" Binary orbit (%s):\n", binsource) ; printf (" MJD = %d + %g\n", pbp->t0.MJDint, pbp->t0.MJDfr) ; printf (" pb = %g a1sini = %g e = %g\n", pbp->pb, pbp->a1sini, pbp->e) ; } } fclose (PD) ; } /* * Return error --------------------------------------------------------- */ if ( error > 0 || nocover ) { fprintf (stderr, "===> Please note that a suitable timing ephemeris entry\n") ; fprintf (stderr, " could not be found in the pulsar timing database.\n") ; fprintf (stderr, " You may want to get a fresh copy of:\n") ; fprintf (stderr, " ftp://pulsar.princeton.edu/gro/jcat\n") ; fprintf (stderr, " and deposit it in $TIMING_DIR/psrtime.dat, \n") ; fprintf (stderr, " or you may want to make your own timing ephemeris and\n") ; fprintf (stderr, " put it in the proper format into that file.\n") ; } else if ( error ) { fprintf (stderr, "===> Please note that a suitable binary orbit ephemeris entry\n") ; fprintf (stderr, " could not be found in the pulsar timing database.\n") ; fprintf (stderr, " You may want to get a fresh copy of:\n") ; fprintf (stderr, " ftp://pulsar.princeton.edu/gro/psrbin.dat\n") ; fprintf (stderr, " and deposit it in $TIMING_DIR/psrbin.dat, or you may want\n") ; fprintf (stderr, " to make your own binary orbit ephemeris and put it in\n") ; fprintf (stderr, " the proper format into that file.\n") ; } if ( fbin ) { fprintf (stderr, "===> Please note that the pulsar database indicated that this pulsar\n") ; fprintf (stderr, " is a binary pulsar and faseBin will try to treat it as such.\n") ; error = - 3 ; } return error ; } /*----------------------------------------------------------------------- * * timeline reads an entry from psrtime.dat. * *----------------------------------------------------------------------*/ timeline (char *line, char *bsource, double *ra, double *dec, long *mjd1, long *mjd2, long *mjdi, double *mjdf, double *fd, double *dfd, double *ddfd, double *dddfd, double *rms, int *fbin, int *denum, char *jsource) { /* Masaharu Hirayama 1 November 2008: Commented out variables 'i' in the following line because it is not used in any part of this function. int i ; */ int rah, ram, decd, decm ; double ras, decs ; char sdec[12], obs[12], bino, dum1[16], dum2[16] ; int dfexp, ddfexp, dddfexp, nitem ; /* Remove trailing blanks */ while ( line[strlen(line) - 1] == ' ' ) line[strlen(line) - 1] = 0 ; /* Read most of the items */ nitem = sscanf (line, "%s %d %d %lg %s %d %lg %ld %ld %ld%lg %lg %lgD%3d%lgD%3d%lg %c %c %s %s %lgD%3d", bsource, &rah, &ram, &ras, &sdec, &decm, &decs, mjd1, mjd2, mjdi, mjdf, fd, dfd, &dfexp, ddfd, &ddfexp, rms, obs, &bino, dum1, dum2, dddfd, &dddfexp) ; obs[1] = 0 ; *dfd *= pow (10.0, dfexp) ; *ddfd *= pow (10.0, ddfexp) ; /* J source name and/or DE number, if present (backward compatibility) */ /* added quartic term, as well */ *jsource = 0 ; *denum = 200 ; if ( nitem > 19 ) { if ( strncmp (dum1, "DE", 2) ) strcpy (jsource, dum1) ; else { sscanf (dum1, "DE%d", denum) ; strcpy (jsource, dum2) ; } if ( nitem < 22 ) *dddfd = 0.0 ; else if ( nitem > 22 ) *dddfd *= pow (10.0, dddfexp) ; } /* Marked as binary? */ *fbin = ( bino == '*' ) ? 1 : 0 ; /* RA and Dec */ decd = abs ( atoi (sdec) ) ; *ra = ( (double) rah + ram / 60.0 + ras / 3600.0 ) * 15.0 ; *dec = (double) decd + decm / 60.0 + decs / 3600.0 ; if ( sdec[0] == '-' ) *dec = -(*dec) ; return 0 ; } /*----------------------------------------------------------------------- * * c200to405 converts a direction cosine vector from the DE200 frame * (nominally FK5, but not quite) to the DE405 frame (ICRS). * * double dir[3] direction cosine vector (in and out) * int debug Whether or not to print the conversion * * The formula, according to Standish, is: * * dir(DE405) = dir(DE200) + eps x dir(DE200) * * where eps' = (0.002, 0.012, 0.006) / 206265 * *----------------------------------------------------------------------*/ void c200to405 (double *dir, int debug) { double dir200[3] ; double x=0.002/206265.0, y=0.012/206265.0, z=0.006/206265.0 ; int i ; for (i=0; i<3; i++) dir200[i] = dir[i] ; dir[0] += y * dir200[2] - z * dir200[1] ; dir[1] += z * dir200[0] - x * dir200[2] ; dir[2] += x * dir200[1] - y * dir200[0] ; if ( debug ) { printf ("Conversion DE200 to ICRS:\n") ; printf (" X %12.9f %12.9f\n", dir200[0], dir[0]) ; printf (" Y %12.9f %12.9f\n", dir200[1], dir[1]) ; printf (" Z %12.9f %12.9f\n", dir200[2], dir[2]) ; } return ; } /*----------------------------------------------------------------------- * * xabsphase calculates absolute phase * It is the MET interface to absphase. * double time: MET time for which the parameters are requested * PsrTimPar *ptp: pulsar timing parameters struct * int binary: binary pulsar? * PsrBinPar *pbp: pulsar binary orbit parameters struct * int bcorr: apply barycenter correction? * double dir[3]: source position vector * char *oefile: orbit ephemeris filename * int *error: error (status) flag * *----------------------------------------------------------------------*/ double xabsphase (double time, PsrTimPar *ptp, int binary, PsrBinPar *pbp, int bcorr, double *dir, char *oefile, int *error) { MJDTime mt ; met2mjd (time, &mt) ; return absphase (&mt, ptp, binary, pbp, bcorr, dir, oefile, error) ; } /*----------------------------------------------------------------------- * * absphase calculates absolute phase * * MJDTime *time: MJD(TDB) time for which the parameters are requested * PsrTimPar *ptp: pulsar timing parameters struct * int binary: binary pulsar? * PsrBinPar *pbp: pulsar binary orbit parameters struct * int bcorr: apply barycenter correction? * double dir[3]: source position vector * char *oefile: orbit ephemeris filename * int *error: error (status) flag * *----------------------------------------------------------------------*/ double absphase (MJDTime *time, PsrTimPar *ptp, int binary, PsrBinPar *pbp, int bcorr, double *dir, char *oefile, int *error) { double dt ; double dt2 ; double dt3 ; double dt4 ; double dtf ; int fi ; double ff ; double phase=0.0 ; /* Masaharu Hirayama 1 November 2008: Commented out variables 'sdec' in the following line because it is not used in any part of this function. double binphase ; */ if ( bcorr ) { time->MJDfr += barycorr (time, dir, scorbit(oefile,time,error)) / SECDAY ; time->ts = TDB ; } if ( !(*error) ) { if ( binary ) time->MJDfr += binorbit (time, pbp) / SECDAY ; dt = time->MJDint - ptp->t0.MJDint ; dt += time->MJDfr - ptp->t0.MJDfr ; dt *= SECDAY ; dt2 = 0.5 * dt * dt ; dt3 = dt * dt2 / 3.0 ; dt4 = dt2 * dt2 / 6.0 ; dtf = dt - (int) dt ; fi = ptp->f ; ff = ptp->f - fi ; phase = fi*dtf + ff*dt + ptp->df*dt2 + ptp->ddf*dt3 + ptp->dddf*dt4 + ptp->radioph ; phase -= (int) phase ; if ( phase < 0.0 ) phase++ ; } return phase ; } /*----------------------------------------------------------------------- * * binorbit calculates binary orbit delay. * * MJDTime *time: MJD(TDB) time for which the correction is requested * PsrBinPar *pbp: pulsar binary orbit parameters struct * *----------------------------------------------------------------------*/ double binorbit (MJDTime *time, PsrBinPar *pbp) { double torb ; double orbph ; double t ; double dt ; double dt2 ; double e ; double ep, dep, denom ; double alpha, beta, omega, sbe, cbe, q ; e = pbp->e ; t = time->MJDint - pbp->t0.MJDint ; t += time->MJDfr - pbp->t0.MJDfr ; t *= SECDAY ; dt = t / pbp->pb ; dt2 = 0.5 * dt * dt ; orbph = dt - dt2 * pbp->pbdot ; orbph -= (int) orbph ; if ( orbph < 0.0 ) orbph++ ; orbph *= TWOPI ; ep = orbph + e*sin(orbph)*(1 + e*cos(orbph)) ; denom = 1.0 - e*cos(ep) ; dep = 1.0 ; while ( fabs(dep) > 1.0e-12 ) { dep = ( orbph - ( ep - e * sin(ep) ) ) / denom ; ep += dep ; } omega = pbp->omega + pbp->omdot * t ; alpha = pbp->a1sini * sin(omega) ; beta = pbp->a1sini * cos(omega) * sqrt(1 - e * e) ; sbe = sin(ep) ; cbe = cos(ep) ; q = alpha * (cbe - e) + (beta + pbp->gamma) * sbe ; torb = -q + (TWOPI / pbp->pb) * q * (beta * cbe - alpha * sbe) / (1 - e * cbe) ; return torb ; }
29.271623
101
0.498376
[ "object", "vector", "3d" ]
8349f7c58d7e118e1f5dc368c8f7e253d8aad232
796
h
C
AFND/Core/Foundation.h
ivansteezy/AFND-UI
014f080ff292a508b4db8f31049ec786fbae6748
[ "MIT" ]
null
null
null
AFND/Core/Foundation.h
ivansteezy/AFND-UI
014f080ff292a508b4db8f31049ec786fbae6748
[ "MIT" ]
null
null
null
AFND/Core/Foundation.h
ivansteezy/AFND-UI
014f080ff292a508b4db8f31049ec786fbae6748
[ "MIT" ]
null
null
null
/* * Ivan Oswaldo Ayala Martinez 19310216 * Junio, 2021 */ #ifndef FOUNDATION_H #define FOUNDATION_H #include <memory> #include <string> #include <vector> #include <array> struct State; using StatePtr = std::shared_ptr<State>; using Graph = std::vector<StatePtr>; using ExcludedTokens = std::array<std::string, 5>; static ExcludedTokens excludedTokens{ {"", "ew", "bew", "aew", "ewy"} }; struct Direction { char token = '\0'; std::string excludedTokens; StatePtr destinyNode; }; struct State { State(bool isFinalState, std::string stateName) : isFinalState(isFinalState), stateName(stateName) { } std::vector<Direction> directions; bool isFinalState; std::string stateName; }; struct Coincidences { std::size_t webCoincidences; std::size_t ebayCoincidences; }; #endif
16.244898
72
0.718593
[ "vector" ]
834cd521a0289f73a3feb6120b77c0fbfdf17d45
1,847
h
C
src/QueryOptimizer.h
adriandarian/CSE177
5ede58f8174f966c0cf3e551ffb1479c4de21e77
[ "MIT" ]
1
2019-05-02T21:29:36.000Z
2019-05-02T21:29:36.000Z
src/QueryOptimizer.h
adriandarian/CSE177
5ede58f8174f966c0cf3e551ffb1479c4de21e77
[ "MIT" ]
null
null
null
src/QueryOptimizer.h
adriandarian/CSE177
5ede58f8174f966c0cf3e551ffb1479c4de21e77
[ "MIT" ]
null
null
null
#ifndef _QUERY_OPTIMIZER_H #define _QUERY_OPTIMIZER_H #include "Schema.h" #include "Catalog.h" #include "ParseTree.h" #include "RelOp.h" #include <string> #include <vector> #include <map> using namespace std; //Following code on optimiztion.alg to come up with data structures // data structure used by the optimizer to compute join ordering // struct OptimizationTree { // // list of tables joined up to this node // vector<string> tables; // // number of tuples in each of the tables (after selection predicates) // vector<int> tuples; // // number of tuples at this node // int noTuples; // // connections to children and parent // OptimizationTree* parent; // OptimizationTree* leftChild; // OptimizationTree* rightChild; // }; struct OptimizationTree { // list of tables joined up to this node vector<string> tables; //number of tuples unsigned long int size; // connections to children and parent OptimizationTree *parent; OptimizationTree *leftChild; OptimizationTree *rightChild; Schema schema; ~OptimizationTree() { //cout << "delete OptimizationTree node" << endl; } }; // struct tuple{ // int size; // int cost; // OptimizationTree* order; // }; class QueryOptimizer { private: Catalog *catalog; //map <string,tuple> omap; vector<OptimizationTree *> tvec; vector<OptimizationTree *> cvec; OptimizationTree *root; vector<OptimizationTree *> everything; public: QueryOptimizer(Catalog &_catalog); virtual ~QueryOptimizer(); void Optimize(TableList *_tables, AndList *_predicate, OptimizationTree *_root); unsigned long int calcPushDown(AndList *_predicate, Schema schema, unsigned long int numT); unsigned long int EstJoin(AndList *_predicate, Schema schema1, Schema schema2, unsigned long int num); void print(); void postOrder(OptimizationTree *node); }; #endif // _QUERY_OPTIMIZER_H
23.987013
103
0.739578
[ "vector" ]
834d2b5600af278936507c6b36fe03217578e675
13,459
h
C
Example/Pods/MaryPopin/MaryPopin/UIViewController+MaryPopin.h
lj-1110/LJUIKit
ffaee9d8ac89345a42868553914cdcd09d470adf
[ "MIT" ]
null
null
null
Example/Pods/MaryPopin/MaryPopin/UIViewController+MaryPopin.h
lj-1110/LJUIKit
ffaee9d8ac89345a42868553914cdcd09d470adf
[ "MIT" ]
null
null
null
Example/Pods/MaryPopin/MaryPopin/UIViewController+MaryPopin.h
lj-1110/LJUIKit
ffaee9d8ac89345a42868553914cdcd09d470adf
[ "MIT" ]
null
null
null
// // The MIT License (MIT) // // Copyright (c) 2013 Backelite // // 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. #import <UIKit/UIKit.h> /** * Object to customize blurry background */ @interface BKTBlurParameters : NSObject /** * Property to customize background view alpha. */ @property (assign, nonatomic) CGFloat alpha; /** * Property to customize background view blur radius. */ @property (assign, nonatomic) CGFloat radius; /** * Property to customize background view blur saturation factor. * A value of 1.0 is neutral. Below it is desaturated and above it is more saturated. */ @property (assign, nonatomic) CGFloat saturationDeltaFactor; /** * Property to customize blur tint color. Default is clear color. */ @property (strong, nonatomic) UIColor *tintColor; @end /** * Transition styles available when presenting popin view controllers. * @since v1.0 */ typedef NS_ENUM(NSInteger, BKTPopinTransitionStyle) { /** * When the view controller is presented, its view slide in the parent view controller and slide out on dismiss */ BKTPopinTransitionStyleSlide, /** * When the view controller is presented, its view fade in and fade out on dismiss. Transition direction is ignored for this kind of transition. */ BKTPopinTransitionStyleCrossDissolve, /** * When the view controller is presented, its view fade in with a zoom out effect and fade out with a zoom in effect on dismiss. Transition direction is ignored for this kind of transition. */ BKTPopinTransitionStyleZoom, /** * When the view controller is presented, its view slide in with a bounce effect and slide out on dismiss. */ BKTPopinTransitionStyleSpringySlide, /** * When the view controller is presented, its view zoom and fade in with a bounce effect. Transition direction is ignored for this kind of transition. */ BKTPopinTransitionStyleSpringyZoom, /** * When the view controller is presented, its view has a undefined behavior. */ //UIDynamics transition styles BKTPopinTransitionStyleSnap, /** * When the view controller is presented, its view has a custom animation. */ BKTPopinTransitionStyleCustom }; /** * Transition direction when presenting popins. Default is BKTPopinTransitionDirectionBottom. * @since v1.0 */ typedef NS_ENUM(NSInteger, BKTPopinTransitionDirection) { /** * Presentation transition will start from the bottom of the parent view. Respectively, dismiss transition will end to the bottom of the parent view. */ BKTPopinTransitionDirectionBottom = 0, /** * Presentation transition will start from the top of the parent view. Respectively, dismiss transition will end to the top of the parent view. */ BKTPopinTransitionDirectionTop, /** * Presentation transition will start from the left of the parent view. Respectively, dismiss transition will end to the left of the parent view. */ BKTPopinTransitionDirectionLeft, /** * Presentation transition will start from the right of the parent view. Respectively, dismiss transition will end to the right of the parent view. */ BKTPopinTransitionDirectionRight }; /** * Options to configure popin behavior to user related events. The following options are compoundables. * @since v1.0 */ typedef NS_OPTIONS(NSUInteger, BKTPopinOption) { /** * Default behaviour */ BKTPopinDefault = 0, /** * Disable popin reaction to keyboard notifications */ BKTPopinIgnoreKeyboardNotification = 1 << 0, /** * Disable auto dismiss when touching outside of the popin view */ BKTPopinDisableAutoDismiss = 1 << 1, /** * Takes a screenshot of presenting view, blurs it and uses it as dimming view. Available only on ios 7.x. */ BKTPopinBlurryDimmingView = 1 << 2, /** * Disable parallax effect on iOS7 */ BKTPopinDisableParallaxEffect = 1 << 3, /** * Set a background dimming view with a clear color. Default is a semi-transparent black background */ BKTPopinDimmingViewStyleNone = 1 << 16, }; /** * Options to quickly configure popin alignment in its container. Default is centered. * @see -popinAlignement * @since v1.3 */ typedef NS_ENUM(NSInteger, BKTPopinAlignementOption) { /** * Popin will be centered in container */ BKTPopinAlignementOptionCentered = 0, /** * Popin will be stuck to top in container */ BKTPopinAlignementOptionUp = 1, /** * Popin will be left-aligned in container */ BKTPopinAlignementOptionLeft = 2, /** * Default will be stuck to bottom in container */ BKTPopinAlignementOptionDown = 3, /** * Popin will be right-aligned in container */ BKTPopinAlignementOptionRight = 4 }; /** * `MaryPopin` is a category allowing modal-like presentation of view controllers but with more configuration options. * Configuration options include popin size, transition style, transition direction, response to keyboard notifications and auto dismiss. * @since v1.0 */ @interface UIViewController (MaryPopin) <UIDynamicAnimatorDelegate> ///--------------------- /// @name Presentation and dismiss ///--------------------- /** * Present a popin controller as a child of the receiver. By default the popin keep its size when presented. If it is bigger than parent controller, the popin is resized to fit inside its parent. * * @param popinController The controller to present as a popin. * @param animated Pass `YES` to animate the presentation. Otherwise, pass `NO`. * @param completion A completion handler, or `NULL`. * @see -presentPopinController:fromRect:animated:completion: * @since v1.0 */ - (void)presentPopinController:(UIViewController *)popinController animated:(BOOL)animated completion:(void(^)(void))completion; /** * Present a popin controller as a child of the receiver, centered inside an arbitrary rect. * * @param popinController The controller to present as a popin. * @param rect An arbitrary rect in which the popin should be centered. * @param animated Pass `YES` to animate the presentation. Otherwise, pass `NO`. * @param completion A completion handler, or `NULL`. * @since v1.0 */ - (void)presentPopinController:(UIViewController *)popinController fromRect:(CGRect)rect animated:(BOOL)animated completion:(void(^)(void))completion; /** * Dismiss the visible popin if any. * * @param animated Pass `YES` to animate the dismiss. Otherwise, pass `NO`. * @see dismissCurrentPopinControllerAnimated:completion: * @since v1.0 */ - (void)dismissCurrentPopinControllerAnimated:(BOOL)animated; /** * Dismiss the visible popin if any. * * @param animated Pass `YES` to animate the dismiss. Otherwise, pass `NO`. * @param completion A completion handler, or `NULL`. * @since v1.0 */ - (void)dismissCurrentPopinControllerAnimated:(BOOL)animated completion:(void(^)(void))completion; ///--------------------- /// @name Properties accessors ///--------------------- /** * A reference to the popin presented as a child controller. * * @return The controller presented as a popin or `nil`. * @see -presentingPopinViewController * @since v1.0 */ - (UIViewController *)presentedPopinViewController; /** * A reference to the parent presenting the popin. * * @return The controller presenting the popin, or `nil`. * @see -presentedPopinViewController * @since v1.0 */ - (UIViewController *)presentingPopinViewController; /** * Get desired size for popin. * * @return The desired size for this controller when presented as a popin. Or `CGSizeZero` if not set. * @see -setPreferedPopinContentSize: * @since v1.0 */ - (CGSize)preferedPopinContentSize; /** * Set the desired size for popin. This value may not be respected if popin is bigger than the presenting controller view. * If not set, the default size will be the controller view size. * * @param preferredSize The desired size for this controller when presented as a popin. * @since v1.0 */ - (void)setPreferedPopinContentSize:(CGSize)preferredSize; /** * The transition style to use when presenting a popin. Default value is `BKTPopinTransitionStyleSlide`. * * @return A BKTPopinTransitionStyle value. * @see -setPopinTransitionStyle: * @since v1.0 */ - (BKTPopinTransitionStyle)popinTransitionStyle; /** * The transition style to use when presenting a popin. For a list of possible transition style, see `BKTPopinTransitionStyle`. * * @param transitionStyle A BKTPopinTransitionStyle value. * @since v1.0 */ - (void)setPopinTransitionStyle:(BKTPopinTransitionStyle)transitionStyle; /** * The transition direction to use when presenting a popin. Default value is `BKTPopinTransitionDirectionBottom`. * * @return A BKTPopinTransitionDirection value. * @see -setPopinTransitionDirection: * @since v1.0 */ - (BKTPopinTransitionDirection)popinTransitionDirection; /** * The transition direction to use when presenting a popin. For a list of possible transition direction, see BKTPopinTransitionDirection * * @param transitionDirection A BKTPopinTransitionDirection value. * @since v1.0 */ - (void)setPopinTransitionDirection:(BKTPopinTransitionDirection)transitionDirection; /** * The options to apply to the popin. Default value is `BKTPopinDefault`. * * @return The BKTPopinOption values as a bit field. * @see -setPopinOptions: * @since v1.0 */ - (BKTPopinOption)popinOptions; /** * The options to apply to the popin. For a list of possible options, see BKTPopinOption * * @param popinOptions The BKTPopinOption values separated by | character. * @since v1.0 */ - (void)setPopinOptions:(BKTPopinOption)popinOptions; /** * Get the custom in animation block. Default value is nil. * * @return The In animation block. * @see -setPopinCustomInAnimation: * @since v1.3 */ - (void (^)(UIViewController * popinController,CGRect initialFrame,CGRect finalFrame))popinCustomInAnimation; /** * The popinCustomAnimation let you pass an custom in animation. The popInController frame must be the finalFrame in the end of the animation. * * @param customInAnimation The Block with animation. * @since v1.3 */ - (void)setPopinCustomInAnimation:(void (^)(UIViewController * popinController,CGRect initialFrame,CGRect finalFrame))customInAnimation; /** * Get the custom out animation block. Default value is nil. * * @return The Out animation block. * @see -setPopinCustomOutAnimation: * @since v1.3 */ - (void (^)(UIViewController * popinController,CGRect initialFrame,CGRect finalFrame))popinCustomOutAnimation; /** * The popinCustomOutAnimation let's you pass an custom out animation. The popInController frame must be the finalFrame in the end of the animation. * * @param customOutAnimation The Block with animation. * @since v1.3 */ - (void)setPopinCustomOutAnimation:(void (^)(UIViewController * popinController,CGRect initialFrame,CGRect finalFrame))customOutAnimation; /** * The options to apply to the popin. Default value is `BKTPopinAlignementOptionCentered`. * * @return The BKTPopinAlignementOption values as a bit field. * @see -setPopinAlignement: * @since v1.3 */ - (BKTPopinAlignementOption)popinAlignment; /** * The options to apply to the popin. For a list of possible options, see BKTPopinAlignementOption * * @param popinAlignment The BKTPopinAlignementOption values separated by | character. * @since v1.3 */ - (void)setPopinAlignment:(BKTPopinAlignementOption)popinAlignment; /** * An object used to configure the blurred background. * * @return The blur parameters object. * @see -setBlurParameters: * @since v1.4 */ - (BKTBlurParameters *)blurParameters; /** * An object used to configure the blurred background. * * @param blurParameters The blur parameters object. * @sicne v1.4 */ - (void)setBlurParameters:(BKTBlurParameters *)blurParameters; /** * An object used to dismiss dimming view. * * @param dismissDimmingViewCompletionBlock Completion block. * @sicne v1.4.3 */ - (void)setDismissDimmingViewCompletionBlock:(void(^)())dismissDimmingViewCompletionBlock; - (void(^)())dismissDimmingViewCompletionBlock; @end
34.421995
196
0.717958
[ "object" ]
83521378be6f8d930f236761c66bc84284e0ac04
1,996
h
C
ToneArmEngine/ColliderComponent.h
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
ToneArmEngine/ColliderComponent.h
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
ToneArmEngine/ColliderComponent.h
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
/* ------------------------------------------------------------------------------------------ Copyright (c) 2014 Vinyl Games Studio Author: Mikhail Kutuzov Date: 9/17/2014 2:25:42 PM ------------------------------------------------------------------------------------------ */ #ifndef __COLLIDER_COMPONENT_H__ #define __COLLIDER_COMPONENT_H__ #include "Component.h" #include "Transform.h" namespace vgs { /* ------------------------------------------------------------------------------------------ ColliderComponent Base class for colliders. ------------------------------------------------------------------------------------------ */ class Shape; class ModelNode; class ColliderComponent : public Component { DECLARE_RTTI; public: virtual void Update(float dt) override; void CollisionStarted(const glm::vec3& force); // accessors virtual Shape* const GetShape() const = 0; virtual const glm::vec3& GetPosition() const = 0; virtual void SetPosition(const glm::vec3& position); virtual const glm::vec3& GetRotation() const = 0; virtual void SetRotation(const glm::vec3& rotation); bool IsDynamic() const { return m_dynamic; } void SetDynamic(const bool dynamic) { m_dynamic = dynamic; } const glm::vec3& GetPositionDelta() const { return m_positionDelta; } virtual void SetActive(bool active); #ifdef TONEARM_DEBUG #ifndef MERRY_SERVER virtual void ShowCollider( bool show ); #endif #endif protected: // constructors ColliderComponent(); ColliderComponent(GameObject* const owner, bool dynamic = false); ColliderComponent(const ColliderComponent& other); virtual ~ColliderComponent(); bool m_dynamic; glm::vec3 m_previousOwnerPosition; glm::vec3 m_positionDelta; #ifndef MERRY_SERVER #ifdef TONEARM_DEBUG ModelNode* m_colliderMesh; bool m_drawCollider; #endif #endif }; } #endif __COLLIDER_COMPONENT_H__
24.048193
90
0.569138
[ "shape", "transform" ]
8352d7a37fa7c7a03332a8b68673031977ff6f6b
45,127
h
C
src/builtin_pb/sentencepiece.pb.h
hymzoque/sentencepiece
d0b7b9384cae911c17e707979d2783cf9a3ef2c3
[ "Apache-2.0" ]
null
null
null
src/builtin_pb/sentencepiece.pb.h
hymzoque/sentencepiece
d0b7b9384cae911c17e707979d2783cf9a3ef2c3
[ "Apache-2.0" ]
null
null
null
src/builtin_pb/sentencepiece.pb.h
hymzoque/sentencepiece
d0b7b9384cae911c17e707979d2783cf9a3ef2c3
[ "Apache-2.0" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: sentencepiece.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_sentencepiece_2eproto #define GOOGLE_PROTOBUF_INCLUDED_sentencepiece_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3012000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3012003 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/message_lite.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_sentencepiece_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_sentencepiece_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[3] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; namespace sentencepiece { class NBestSentencePieceText; class NBestSentencePieceTextDefaultTypeInternal; extern NBestSentencePieceTextDefaultTypeInternal _NBestSentencePieceText_default_instance_; class SentencePieceText; class SentencePieceTextDefaultTypeInternal; extern SentencePieceTextDefaultTypeInternal _SentencePieceText_default_instance_; class SentencePieceText_SentencePiece; class SentencePieceText_SentencePieceDefaultTypeInternal; extern SentencePieceText_SentencePieceDefaultTypeInternal _SentencePieceText_SentencePiece_default_instance_; } // namespace sentencepiece PROTOBUF_NAMESPACE_OPEN template<> ::sentencepiece::NBestSentencePieceText* Arena::CreateMaybeMessage<::sentencepiece::NBestSentencePieceText>(Arena*); template<> ::sentencepiece::SentencePieceText* Arena::CreateMaybeMessage<::sentencepiece::SentencePieceText>(Arena*); template<> ::sentencepiece::SentencePieceText_SentencePiece* Arena::CreateMaybeMessage<::sentencepiece::SentencePieceText_SentencePiece>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace sentencepiece { // =================================================================== class SentencePieceText_SentencePiece PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:sentencepiece.SentencePieceText.SentencePiece) */ { public: inline SentencePieceText_SentencePiece() : SentencePieceText_SentencePiece(nullptr) {}; virtual ~SentencePieceText_SentencePiece(); SentencePieceText_SentencePiece(const SentencePieceText_SentencePiece& from); SentencePieceText_SentencePiece(SentencePieceText_SentencePiece&& from) noexcept : SentencePieceText_SentencePiece() { *this = ::std::move(from); } inline SentencePieceText_SentencePiece& operator=(const SentencePieceText_SentencePiece& from) { CopyFrom(from); return *this; } inline SentencePieceText_SentencePiece& operator=(SentencePieceText_SentencePiece&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const std::string& unknown_fields() const { return _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString); } inline std::string* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<std::string>(); } static const SentencePieceText_SentencePiece& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const SentencePieceText_SentencePiece* internal_default_instance() { return reinterpret_cast<const SentencePieceText_SentencePiece*>( &_SentencePieceText_SentencePiece_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(SentencePieceText_SentencePiece& a, SentencePieceText_SentencePiece& b) { a.Swap(&b); } inline void Swap(SentencePieceText_SentencePiece* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(SentencePieceText_SentencePiece* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline SentencePieceText_SentencePiece* New() const final { return CreateMaybeMessage<SentencePieceText_SentencePiece>(nullptr); } SentencePieceText_SentencePiece* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<SentencePieceText_SentencePiece>(arena); } void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) final; void CopyFrom(const SentencePieceText_SentencePiece& from); void MergeFrom(const SentencePieceText_SentencePiece& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; void DiscardUnknownFields(); int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(SentencePieceText_SentencePiece* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "sentencepiece.SentencePieceText.SentencePiece"; } protected: explicit SentencePieceText_SentencePiece(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: std::string GetTypeName() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kPieceFieldNumber = 1, kSurfaceFieldNumber = 3, kIdFieldNumber = 2, kBeginFieldNumber = 4, kEndFieldNumber = 5, }; // optional string piece = 1; bool has_piece() const; private: bool _internal_has_piece() const; public: void clear_piece(); const std::string& piece() const; void set_piece(const std::string& value); void set_piece(std::string&& value); void set_piece(const char* value); void set_piece(const char* value, size_t size); std::string* mutable_piece(); std::string* release_piece(); void set_allocated_piece(std::string* piece); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_piece(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_piece( std::string* piece); private: const std::string& _internal_piece() const; void _internal_set_piece(const std::string& value); std::string* _internal_mutable_piece(); public: // optional string surface = 3; bool has_surface() const; private: bool _internal_has_surface() const; public: void clear_surface(); const std::string& surface() const; void set_surface(const std::string& value); void set_surface(std::string&& value); void set_surface(const char* value); void set_surface(const char* value, size_t size); std::string* mutable_surface(); std::string* release_surface(); void set_allocated_surface(std::string* surface); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_surface(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_surface( std::string* surface); private: const std::string& _internal_surface() const; void _internal_set_surface(const std::string& value); std::string* _internal_mutable_surface(); public: // optional uint32 id = 2; bool has_id() const; private: bool _internal_has_id() const; public: void clear_id(); ::PROTOBUF_NAMESPACE_ID::uint32 id() const; void set_id(::PROTOBUF_NAMESPACE_ID::uint32 value); private: ::PROTOBUF_NAMESPACE_ID::uint32 _internal_id() const; void _internal_set_id(::PROTOBUF_NAMESPACE_ID::uint32 value); public: // optional uint32 begin = 4; bool has_begin() const; private: bool _internal_has_begin() const; public: void clear_begin(); ::PROTOBUF_NAMESPACE_ID::uint32 begin() const; void set_begin(::PROTOBUF_NAMESPACE_ID::uint32 value); private: ::PROTOBUF_NAMESPACE_ID::uint32 _internal_begin() const; void _internal_set_begin(::PROTOBUF_NAMESPACE_ID::uint32 value); public: // optional uint32 end = 5; bool has_end() const; private: bool _internal_has_end() const; public: void clear_end(); ::PROTOBUF_NAMESPACE_ID::uint32 end() const; void set_end(::PROTOBUF_NAMESPACE_ID::uint32 value); private: ::PROTOBUF_NAMESPACE_ID::uint32 _internal_end() const; void _internal_set_end(::PROTOBUF_NAMESPACE_ID::uint32 value); public: GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(SentencePieceText_SentencePiece) // @@protoc_insertion_point(class_scope:sentencepiece.SentencePieceText.SentencePiece) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr piece_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr surface_; ::PROTOBUF_NAMESPACE_ID::uint32 id_; ::PROTOBUF_NAMESPACE_ID::uint32 begin_; ::PROTOBUF_NAMESPACE_ID::uint32 end_; friend struct ::TableStruct_sentencepiece_2eproto; }; // ------------------------------------------------------------------- class SentencePieceText PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:sentencepiece.SentencePieceText) */ { public: inline SentencePieceText() : SentencePieceText(nullptr) {}; virtual ~SentencePieceText(); SentencePieceText(const SentencePieceText& from); SentencePieceText(SentencePieceText&& from) noexcept : SentencePieceText() { *this = ::std::move(from); } inline SentencePieceText& operator=(const SentencePieceText& from) { CopyFrom(from); return *this; } inline SentencePieceText& operator=(SentencePieceText&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const std::string& unknown_fields() const { return _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString); } inline std::string* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<std::string>(); } static const SentencePieceText& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const SentencePieceText* internal_default_instance() { return reinterpret_cast<const SentencePieceText*>( &_SentencePieceText_default_instance_); } static constexpr int kIndexInFileMessages = 1; friend void swap(SentencePieceText& a, SentencePieceText& b) { a.Swap(&b); } inline void Swap(SentencePieceText* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(SentencePieceText* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline SentencePieceText* New() const final { return CreateMaybeMessage<SentencePieceText>(nullptr); } SentencePieceText* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<SentencePieceText>(arena); } void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) final; void CopyFrom(const SentencePieceText& from); void MergeFrom(const SentencePieceText& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; void DiscardUnknownFields(); int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(SentencePieceText* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "sentencepiece.SentencePieceText"; } protected: explicit SentencePieceText(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: std::string GetTypeName() const final; // nested types ---------------------------------------------------- typedef SentencePieceText_SentencePiece SentencePiece; // accessors ------------------------------------------------------- enum : int { kPiecesFieldNumber = 2, kTextFieldNumber = 1, kScoreFieldNumber = 3, }; // repeated .sentencepiece.SentencePieceText.SentencePiece pieces = 2; int pieces_size() const; private: int _internal_pieces_size() const; public: void clear_pieces(); ::sentencepiece::SentencePieceText_SentencePiece* mutable_pieces(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText_SentencePiece >* mutable_pieces(); private: const ::sentencepiece::SentencePieceText_SentencePiece& _internal_pieces(int index) const; ::sentencepiece::SentencePieceText_SentencePiece* _internal_add_pieces(); public: const ::sentencepiece::SentencePieceText_SentencePiece& pieces(int index) const; ::sentencepiece::SentencePieceText_SentencePiece* add_pieces(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText_SentencePiece >& pieces() const; // optional string text = 1; bool has_text() const; private: bool _internal_has_text() const; public: void clear_text(); const std::string& text() const; void set_text(const std::string& value); void set_text(std::string&& value); void set_text(const char* value); void set_text(const char* value, size_t size); std::string* mutable_text(); std::string* release_text(); void set_allocated_text(std::string* text); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") std::string* unsafe_arena_release_text(); GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for" " string fields are deprecated and will be removed in a" " future release.") void unsafe_arena_set_allocated_text( std::string* text); private: const std::string& _internal_text() const; void _internal_set_text(const std::string& value); std::string* _internal_mutable_text(); public: // optional float score = 3; bool has_score() const; private: bool _internal_has_score() const; public: void clear_score(); float score() const; void set_score(float value); private: float _internal_score() const; void _internal_set_score(float value); public: GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(SentencePieceText) // @@protoc_insertion_point(class_scope:sentencepiece.SentencePieceText) private: class _Internal; ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText_SentencePiece > pieces_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr text_; float score_; friend struct ::TableStruct_sentencepiece_2eproto; }; // ------------------------------------------------------------------- class NBestSentencePieceText PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:sentencepiece.NBestSentencePieceText) */ { public: inline NBestSentencePieceText() : NBestSentencePieceText(nullptr) {}; virtual ~NBestSentencePieceText(); NBestSentencePieceText(const NBestSentencePieceText& from); NBestSentencePieceText(NBestSentencePieceText&& from) noexcept : NBestSentencePieceText() { *this = ::std::move(from); } inline NBestSentencePieceText& operator=(const NBestSentencePieceText& from) { CopyFrom(from); return *this; } inline NBestSentencePieceText& operator=(NBestSentencePieceText&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const std::string& unknown_fields() const { return _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString); } inline std::string* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<std::string>(); } static const NBestSentencePieceText& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const NBestSentencePieceText* internal_default_instance() { return reinterpret_cast<const NBestSentencePieceText*>( &_NBestSentencePieceText_default_instance_); } static constexpr int kIndexInFileMessages = 2; friend void swap(NBestSentencePieceText& a, NBestSentencePieceText& b) { a.Swap(&b); } inline void Swap(NBestSentencePieceText* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(NBestSentencePieceText* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline NBestSentencePieceText* New() const final { return CreateMaybeMessage<NBestSentencePieceText>(nullptr); } NBestSentencePieceText* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<NBestSentencePieceText>(arena); } void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) final; void CopyFrom(const NBestSentencePieceText& from); void MergeFrom(const NBestSentencePieceText& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; void DiscardUnknownFields(); int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(NBestSentencePieceText* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "sentencepiece.NBestSentencePieceText"; } protected: explicit NBestSentencePieceText(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: std::string GetTypeName() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kNbestsFieldNumber = 1, }; // repeated .sentencepiece.SentencePieceText nbests = 1; int nbests_size() const; private: int _internal_nbests_size() const; public: void clear_nbests(); ::sentencepiece::SentencePieceText* mutable_nbests(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText >* mutable_nbests(); private: const ::sentencepiece::SentencePieceText& _internal_nbests(int index) const; ::sentencepiece::SentencePieceText* _internal_add_nbests(); public: const ::sentencepiece::SentencePieceText& nbests(int index) const; ::sentencepiece::SentencePieceText* add_nbests(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText >& nbests() const; // @@protoc_insertion_point(class_scope:sentencepiece.NBestSentencePieceText) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText > nbests_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_sentencepiece_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // SentencePieceText_SentencePiece // optional string piece = 1; inline bool SentencePieceText_SentencePiece::_internal_has_piece() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool SentencePieceText_SentencePiece::has_piece() const { return _internal_has_piece(); } inline void SentencePieceText_SentencePiece::clear_piece() { piece_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); _has_bits_[0] &= ~0x00000001u; } inline const std::string& SentencePieceText_SentencePiece::piece() const { // @@protoc_insertion_point(field_get:sentencepiece.SentencePieceText.SentencePiece.piece) return _internal_piece(); } inline void SentencePieceText_SentencePiece::set_piece(const std::string& value) { _internal_set_piece(value); // @@protoc_insertion_point(field_set:sentencepiece.SentencePieceText.SentencePiece.piece) } inline std::string* SentencePieceText_SentencePiece::mutable_piece() { // @@protoc_insertion_point(field_mutable:sentencepiece.SentencePieceText.SentencePiece.piece) return _internal_mutable_piece(); } inline const std::string& SentencePieceText_SentencePiece::_internal_piece() const { return piece_.Get(); } inline void SentencePieceText_SentencePiece::_internal_set_piece(const std::string& value) { _has_bits_[0] |= 0x00000001u; piece_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void SentencePieceText_SentencePiece::set_piece(std::string&& value) { _has_bits_[0] |= 0x00000001u; piece_.SetLite( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:sentencepiece.SentencePieceText.SentencePiece.piece) } inline void SentencePieceText_SentencePiece::set_piece(const char* value) { GOOGLE_DCHECK(value != nullptr); _has_bits_[0] |= 0x00000001u; piece_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:sentencepiece.SentencePieceText.SentencePiece.piece) } inline void SentencePieceText_SentencePiece::set_piece(const char* value, size_t size) { _has_bits_[0] |= 0x00000001u; piece_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:sentencepiece.SentencePieceText.SentencePiece.piece) } inline std::string* SentencePieceText_SentencePiece::_internal_mutable_piece() { _has_bits_[0] |= 0x00000001u; return piece_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* SentencePieceText_SentencePiece::release_piece() { // @@protoc_insertion_point(field_release:sentencepiece.SentencePieceText.SentencePiece.piece) if (!_internal_has_piece()) { return nullptr; } _has_bits_[0] &= ~0x00000001u; return piece_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void SentencePieceText_SentencePiece::set_allocated_piece(std::string* piece) { if (piece != nullptr) { _has_bits_[0] |= 0x00000001u; } else { _has_bits_[0] &= ~0x00000001u; } piece_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), piece, GetArena()); // @@protoc_insertion_point(field_set_allocated:sentencepiece.SentencePieceText.SentencePiece.piece) } inline std::string* SentencePieceText_SentencePiece::unsafe_arena_release_piece() { // @@protoc_insertion_point(field_unsafe_arena_release:sentencepiece.SentencePieceText.SentencePiece.piece) GOOGLE_DCHECK(GetArena() != nullptr); _has_bits_[0] &= ~0x00000001u; return piece_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void SentencePieceText_SentencePiece::unsafe_arena_set_allocated_piece( std::string* piece) { GOOGLE_DCHECK(GetArena() != nullptr); if (piece != nullptr) { _has_bits_[0] |= 0x00000001u; } else { _has_bits_[0] &= ~0x00000001u; } piece_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), piece, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:sentencepiece.SentencePieceText.SentencePiece.piece) } // optional uint32 id = 2; inline bool SentencePieceText_SentencePiece::_internal_has_id() const { bool value = (_has_bits_[0] & 0x00000004u) != 0; return value; } inline bool SentencePieceText_SentencePiece::has_id() const { return _internal_has_id(); } inline void SentencePieceText_SentencePiece::clear_id() { id_ = 0u; _has_bits_[0] &= ~0x00000004u; } inline ::PROTOBUF_NAMESPACE_ID::uint32 SentencePieceText_SentencePiece::_internal_id() const { return id_; } inline ::PROTOBUF_NAMESPACE_ID::uint32 SentencePieceText_SentencePiece::id() const { // @@protoc_insertion_point(field_get:sentencepiece.SentencePieceText.SentencePiece.id) return _internal_id(); } inline void SentencePieceText_SentencePiece::_internal_set_id(::PROTOBUF_NAMESPACE_ID::uint32 value) { _has_bits_[0] |= 0x00000004u; id_ = value; } inline void SentencePieceText_SentencePiece::set_id(::PROTOBUF_NAMESPACE_ID::uint32 value) { _internal_set_id(value); // @@protoc_insertion_point(field_set:sentencepiece.SentencePieceText.SentencePiece.id) } // optional string surface = 3; inline bool SentencePieceText_SentencePiece::_internal_has_surface() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool SentencePieceText_SentencePiece::has_surface() const { return _internal_has_surface(); } inline void SentencePieceText_SentencePiece::clear_surface() { surface_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); _has_bits_[0] &= ~0x00000002u; } inline const std::string& SentencePieceText_SentencePiece::surface() const { // @@protoc_insertion_point(field_get:sentencepiece.SentencePieceText.SentencePiece.surface) return _internal_surface(); } inline void SentencePieceText_SentencePiece::set_surface(const std::string& value) { _internal_set_surface(value); // @@protoc_insertion_point(field_set:sentencepiece.SentencePieceText.SentencePiece.surface) } inline std::string* SentencePieceText_SentencePiece::mutable_surface() { // @@protoc_insertion_point(field_mutable:sentencepiece.SentencePieceText.SentencePiece.surface) return _internal_mutable_surface(); } inline const std::string& SentencePieceText_SentencePiece::_internal_surface() const { return surface_.Get(); } inline void SentencePieceText_SentencePiece::_internal_set_surface(const std::string& value) { _has_bits_[0] |= 0x00000002u; surface_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void SentencePieceText_SentencePiece::set_surface(std::string&& value) { _has_bits_[0] |= 0x00000002u; surface_.SetLite( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:sentencepiece.SentencePieceText.SentencePiece.surface) } inline void SentencePieceText_SentencePiece::set_surface(const char* value) { GOOGLE_DCHECK(value != nullptr); _has_bits_[0] |= 0x00000002u; surface_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:sentencepiece.SentencePieceText.SentencePiece.surface) } inline void SentencePieceText_SentencePiece::set_surface(const char* value, size_t size) { _has_bits_[0] |= 0x00000002u; surface_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:sentencepiece.SentencePieceText.SentencePiece.surface) } inline std::string* SentencePieceText_SentencePiece::_internal_mutable_surface() { _has_bits_[0] |= 0x00000002u; return surface_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* SentencePieceText_SentencePiece::release_surface() { // @@protoc_insertion_point(field_release:sentencepiece.SentencePieceText.SentencePiece.surface) if (!_internal_has_surface()) { return nullptr; } _has_bits_[0] &= ~0x00000002u; return surface_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void SentencePieceText_SentencePiece::set_allocated_surface(std::string* surface) { if (surface != nullptr) { _has_bits_[0] |= 0x00000002u; } else { _has_bits_[0] &= ~0x00000002u; } surface_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), surface, GetArena()); // @@protoc_insertion_point(field_set_allocated:sentencepiece.SentencePieceText.SentencePiece.surface) } inline std::string* SentencePieceText_SentencePiece::unsafe_arena_release_surface() { // @@protoc_insertion_point(field_unsafe_arena_release:sentencepiece.SentencePieceText.SentencePiece.surface) GOOGLE_DCHECK(GetArena() != nullptr); _has_bits_[0] &= ~0x00000002u; return surface_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void SentencePieceText_SentencePiece::unsafe_arena_set_allocated_surface( std::string* surface) { GOOGLE_DCHECK(GetArena() != nullptr); if (surface != nullptr) { _has_bits_[0] |= 0x00000002u; } else { _has_bits_[0] &= ~0x00000002u; } surface_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), surface, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:sentencepiece.SentencePieceText.SentencePiece.surface) } // optional uint32 begin = 4; inline bool SentencePieceText_SentencePiece::_internal_has_begin() const { bool value = (_has_bits_[0] & 0x00000008u) != 0; return value; } inline bool SentencePieceText_SentencePiece::has_begin() const { return _internal_has_begin(); } inline void SentencePieceText_SentencePiece::clear_begin() { begin_ = 0u; _has_bits_[0] &= ~0x00000008u; } inline ::PROTOBUF_NAMESPACE_ID::uint32 SentencePieceText_SentencePiece::_internal_begin() const { return begin_; } inline ::PROTOBUF_NAMESPACE_ID::uint32 SentencePieceText_SentencePiece::begin() const { // @@protoc_insertion_point(field_get:sentencepiece.SentencePieceText.SentencePiece.begin) return _internal_begin(); } inline void SentencePieceText_SentencePiece::_internal_set_begin(::PROTOBUF_NAMESPACE_ID::uint32 value) { _has_bits_[0] |= 0x00000008u; begin_ = value; } inline void SentencePieceText_SentencePiece::set_begin(::PROTOBUF_NAMESPACE_ID::uint32 value) { _internal_set_begin(value); // @@protoc_insertion_point(field_set:sentencepiece.SentencePieceText.SentencePiece.begin) } // optional uint32 end = 5; inline bool SentencePieceText_SentencePiece::_internal_has_end() const { bool value = (_has_bits_[0] & 0x00000010u) != 0; return value; } inline bool SentencePieceText_SentencePiece::has_end() const { return _internal_has_end(); } inline void SentencePieceText_SentencePiece::clear_end() { end_ = 0u; _has_bits_[0] &= ~0x00000010u; } inline ::PROTOBUF_NAMESPACE_ID::uint32 SentencePieceText_SentencePiece::_internal_end() const { return end_; } inline ::PROTOBUF_NAMESPACE_ID::uint32 SentencePieceText_SentencePiece::end() const { // @@protoc_insertion_point(field_get:sentencepiece.SentencePieceText.SentencePiece.end) return _internal_end(); } inline void SentencePieceText_SentencePiece::_internal_set_end(::PROTOBUF_NAMESPACE_ID::uint32 value) { _has_bits_[0] |= 0x00000010u; end_ = value; } inline void SentencePieceText_SentencePiece::set_end(::PROTOBUF_NAMESPACE_ID::uint32 value) { _internal_set_end(value); // @@protoc_insertion_point(field_set:sentencepiece.SentencePieceText.SentencePiece.end) } // ------------------------------------------------------------------- // SentencePieceText // optional string text = 1; inline bool SentencePieceText::_internal_has_text() const { bool value = (_has_bits_[0] & 0x00000001u) != 0; return value; } inline bool SentencePieceText::has_text() const { return _internal_has_text(); } inline void SentencePieceText::clear_text() { text_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); _has_bits_[0] &= ~0x00000001u; } inline const std::string& SentencePieceText::text() const { // @@protoc_insertion_point(field_get:sentencepiece.SentencePieceText.text) return _internal_text(); } inline void SentencePieceText::set_text(const std::string& value) { _internal_set_text(value); // @@protoc_insertion_point(field_set:sentencepiece.SentencePieceText.text) } inline std::string* SentencePieceText::mutable_text() { // @@protoc_insertion_point(field_mutable:sentencepiece.SentencePieceText.text) return _internal_mutable_text(); } inline const std::string& SentencePieceText::_internal_text() const { return text_.Get(); } inline void SentencePieceText::_internal_set_text(const std::string& value) { _has_bits_[0] |= 0x00000001u; text_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena()); } inline void SentencePieceText::set_text(std::string&& value) { _has_bits_[0] |= 0x00000001u; text_.SetLite( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:sentencepiece.SentencePieceText.text) } inline void SentencePieceText::set_text(const char* value) { GOOGLE_DCHECK(value != nullptr); _has_bits_[0] |= 0x00000001u; text_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:sentencepiece.SentencePieceText.text) } inline void SentencePieceText::set_text(const char* value, size_t size) { _has_bits_[0] |= 0x00000001u; text_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:sentencepiece.SentencePieceText.text) } inline std::string* SentencePieceText::_internal_mutable_text() { _has_bits_[0] |= 0x00000001u; return text_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline std::string* SentencePieceText::release_text() { // @@protoc_insertion_point(field_release:sentencepiece.SentencePieceText.text) if (!_internal_has_text()) { return nullptr; } _has_bits_[0] &= ~0x00000001u; return text_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void SentencePieceText::set_allocated_text(std::string* text) { if (text != nullptr) { _has_bits_[0] |= 0x00000001u; } else { _has_bits_[0] &= ~0x00000001u; } text_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), text, GetArena()); // @@protoc_insertion_point(field_set_allocated:sentencepiece.SentencePieceText.text) } inline std::string* SentencePieceText::unsafe_arena_release_text() { // @@protoc_insertion_point(field_unsafe_arena_release:sentencepiece.SentencePieceText.text) GOOGLE_DCHECK(GetArena() != nullptr); _has_bits_[0] &= ~0x00000001u; return text_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void SentencePieceText::unsafe_arena_set_allocated_text( std::string* text) { GOOGLE_DCHECK(GetArena() != nullptr); if (text != nullptr) { _has_bits_[0] |= 0x00000001u; } else { _has_bits_[0] &= ~0x00000001u; } text_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), text, GetArena()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:sentencepiece.SentencePieceText.text) } // repeated .sentencepiece.SentencePieceText.SentencePiece pieces = 2; inline int SentencePieceText::_internal_pieces_size() const { return pieces_.size(); } inline int SentencePieceText::pieces_size() const { return _internal_pieces_size(); } inline void SentencePieceText::clear_pieces() { pieces_.Clear(); } inline ::sentencepiece::SentencePieceText_SentencePiece* SentencePieceText::mutable_pieces(int index) { // @@protoc_insertion_point(field_mutable:sentencepiece.SentencePieceText.pieces) return pieces_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText_SentencePiece >* SentencePieceText::mutable_pieces() { // @@protoc_insertion_point(field_mutable_list:sentencepiece.SentencePieceText.pieces) return &pieces_; } inline const ::sentencepiece::SentencePieceText_SentencePiece& SentencePieceText::_internal_pieces(int index) const { return pieces_.Get(index); } inline const ::sentencepiece::SentencePieceText_SentencePiece& SentencePieceText::pieces(int index) const { // @@protoc_insertion_point(field_get:sentencepiece.SentencePieceText.pieces) return _internal_pieces(index); } inline ::sentencepiece::SentencePieceText_SentencePiece* SentencePieceText::_internal_add_pieces() { return pieces_.Add(); } inline ::sentencepiece::SentencePieceText_SentencePiece* SentencePieceText::add_pieces() { // @@protoc_insertion_point(field_add:sentencepiece.SentencePieceText.pieces) return _internal_add_pieces(); } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText_SentencePiece >& SentencePieceText::pieces() const { // @@protoc_insertion_point(field_list:sentencepiece.SentencePieceText.pieces) return pieces_; } // optional float score = 3; inline bool SentencePieceText::_internal_has_score() const { bool value = (_has_bits_[0] & 0x00000002u) != 0; return value; } inline bool SentencePieceText::has_score() const { return _internal_has_score(); } inline void SentencePieceText::clear_score() { score_ = 0; _has_bits_[0] &= ~0x00000002u; } inline float SentencePieceText::_internal_score() const { return score_; } inline float SentencePieceText::score() const { // @@protoc_insertion_point(field_get:sentencepiece.SentencePieceText.score) return _internal_score(); } inline void SentencePieceText::_internal_set_score(float value) { _has_bits_[0] |= 0x00000002u; score_ = value; } inline void SentencePieceText::set_score(float value) { _internal_set_score(value); // @@protoc_insertion_point(field_set:sentencepiece.SentencePieceText.score) } // ------------------------------------------------------------------- // NBestSentencePieceText // repeated .sentencepiece.SentencePieceText nbests = 1; inline int NBestSentencePieceText::_internal_nbests_size() const { return nbests_.size(); } inline int NBestSentencePieceText::nbests_size() const { return _internal_nbests_size(); } inline void NBestSentencePieceText::clear_nbests() { nbests_.Clear(); } inline ::sentencepiece::SentencePieceText* NBestSentencePieceText::mutable_nbests(int index) { // @@protoc_insertion_point(field_mutable:sentencepiece.NBestSentencePieceText.nbests) return nbests_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText >* NBestSentencePieceText::mutable_nbests() { // @@protoc_insertion_point(field_mutable_list:sentencepiece.NBestSentencePieceText.nbests) return &nbests_; } inline const ::sentencepiece::SentencePieceText& NBestSentencePieceText::_internal_nbests(int index) const { return nbests_.Get(index); } inline const ::sentencepiece::SentencePieceText& NBestSentencePieceText::nbests(int index) const { // @@protoc_insertion_point(field_get:sentencepiece.NBestSentencePieceText.nbests) return _internal_nbests(index); } inline ::sentencepiece::SentencePieceText* NBestSentencePieceText::_internal_add_nbests() { return nbests_.Add(); } inline ::sentencepiece::SentencePieceText* NBestSentencePieceText::add_nbests() { // @@protoc_insertion_point(field_add:sentencepiece.NBestSentencePieceText.nbests) return _internal_add_nbests(); } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::sentencepiece::SentencePieceText >& NBestSentencePieceText::nbests() const { // @@protoc_insertion_point(field_list:sentencepiece.NBestSentencePieceText.nbests) return nbests_; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace sentencepiece // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_sentencepiece_2eproto
39.829656
145
0.754714
[ "object" ]
8352f8980ee83f849844924203bd6e2ea74804b3
424
h
C
FastEasyMapping/Source/Core/Serializer/FEMSerializer.h
sathishmscict/FastEasyMappting-Report
ecb6e663b669f7f2b6f4609efefebbf0234d1343
[ "MIT" ]
null
null
null
FastEasyMapping/Source/Core/Serializer/FEMSerializer.h
sathishmscict/FastEasyMappting-Report
ecb6e663b669f7f2b6f4609efefebbf0234d1343
[ "MIT" ]
null
null
null
FastEasyMapping/Source/Core/Serializer/FEMSerializer.h
sathishmscict/FastEasyMappting-Report
ecb6e663b669f7f2b6f4609efefebbf0234d1343
[ "MIT" ]
null
null
null
// For License please refer to LICENSE file in the root of FastEasyMapping project #import <Foundation/Foundation.h> #import "FEMMapping.h" #import "FEMSerializer.h" NS_ASSUME_NONNULL_BEGIN @interface FEMSerializer : NSObject + (NSDictionary *)serializeObject:(id)object usingMapping:(FEMMapping *)mapping; + (id)serializeCollection:(NSArray *)collection usingMapping:(FEMMapping *)mapping; @end NS_ASSUME_NONNULL_END
24.941176
83
0.799528
[ "object" ]
835a3deb67e802eb77e27c55fe5f608f31429f10
687
h
C
src/bindings/text-writer.h
aminya/superstring
13ef1e3461ad06c6526249f1025dcfdcb76157e2
[ "MIT" ]
2
2021-04-02T06:37:42.000Z
2022-03-20T15:45:24.000Z
src/bindings/text-writer.h
aminya/superstring
13ef1e3461ad06c6526249f1025dcfdcb76157e2
[ "MIT" ]
2
2020-12-31T02:46:14.000Z
2021-01-22T11:44:56.000Z
src/bindings/text-writer.h
aminya/superstring
13ef1e3461ad06c6526249f1025dcfdcb76157e2
[ "MIT" ]
null
null
null
#ifndef SUPERSTRING_TEXT_WRITER_H #define SUPERSTRING_TEXT_WRITER_H #include <nan.h> #include "text.h" #include "encoding-conversion.h" class TextWriter : public Nan::ObjectWrap { public: static void init(v8::Local<v8::Object> exports); explicit TextWriter(EncodingConversion &&conversion); std::u16string get_text(); private: static void construct(const Nan::FunctionCallbackInfo<v8::Value> &info); static void write(const Nan::FunctionCallbackInfo<v8::Value> &info); static void end(const Nan::FunctionCallbackInfo<v8::Value> &info); EncodingConversion conversion; std::vector<char> leftover_bytes; std::u16string content; }; #endif // SUPERSTRING_TEXT_WRITER_H
27.48
74
0.768559
[ "object", "vector" ]
8360e6d59d6e3ebca3c06bf9d27b8223d2d88951
76,333
c
C
os/hal/ports/SPC5/SPC5xx/FlexCAN_v1/can_lld.c
marcoveeneman/ChibiOS-Tiva
959c058ce94313ab4c38ba526669a5e83978fa1d
[ "Apache-2.0" ]
2
2015-01-06T16:37:38.000Z
2015-03-22T17:41:21.000Z
os/hal/ports/SPC5/SPC5xx/FlexCAN_v1/can_lld.c
marcoveeneman/ChibiOS-Tiva
959c058ce94313ab4c38ba526669a5e83978fa1d
[ "Apache-2.0" ]
null
null
null
os/hal/ports/SPC5/SPC5xx/FlexCAN_v1/can_lld.c
marcoveeneman/ChibiOS-Tiva
959c058ce94313ab4c38ba526669a5e83978fa1d
[ "Apache-2.0" ]
null
null
null
/* SPC5 HAL - Copyright (C) 2013 STMicroelectronics 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. */ /** * @file FlexCAN_v1/can_lld.c * @brief SPC5xx CAN subsystem low level driver source. * * @addtogroup CAN * @{ */ #include "hal.h" #if HAL_USE_CAN || defined(__DOXYGEN__) /*===========================================================================*/ /* Driver local definitions. */ /*===========================================================================*/ /*===========================================================================*/ /* Driver exported variables. */ /*===========================================================================*/ /** @brief CAN1 driver identifier.*/ #if SPC5_CAN_USE_FLEXCAN0 || defined(__DOXYGEN__) CANDriver CAND1; #endif /** @brief CAN2 driver identifier.*/ #if SPC5_CAN_USE_FLEXCAN1 || defined(__DOXYGEN__) CANDriver CAND2; #endif /** @brief CAN3 driver identifier.*/ #if SPC5_CAN_USE_FLEXCAN2 || defined(__DOXYGEN__) CANDriver CAND3; #endif /** @brief CAN4 driver identifier.*/ #if SPC5_CAN_USE_FLEXCAN3 || defined(__DOXYGEN__) CANDriver CAND4; #endif /** @brief CAN5 driver identifier.*/ #if SPC5_CAN_USE_FLEXCAN4 || defined(__DOXYGEN__) CANDriver CAND5; #endif /** @brief CAN6 driver identifier.*/ #if SPC5_CAN_USE_FLEXCAN5 || defined(__DOXYGEN__) CANDriver CAND6; #endif /*===========================================================================*/ /* Driver local variables and types. */ /*===========================================================================*/ /*===========================================================================*/ /* Driver local functions. */ /*===========================================================================*/ /** * @brief Common TX ISR handler. * * @param[in] canp pointer to the @p CANDriver object * * @notapi */ static void can_lld_tx_handler(CANDriver *canp) { uint32_t iflag1, iflag2; (void)iflag2; /* No more events until a message is transmitted.*/ iflag1 = canp->flexcan->IFRL.R; canp->flexcan->IFRL.R = iflag1 & 0xFFFFFF00; #if SPC5_CAN_USE_FLEXCAN0 && (SPC5_FLEXCAN0_MB == 64) if(&CAND1 == canp) { iflag2 = canp->flexcan->IFRH.R; canp->flexcan->IFRH.R = canp->flexcan->IFRH.R; } #endif #if SPC5_CAN_USE_FLEXCAN1 && (SPC5_FLEXCAN1_MB == 64) if(&CAND2 == canp) { iflag2 = canp->flexcan->IFRH.R; canp->flexcan->IFRH.R = canp->flexcan->IFRH.R; } #endif #if SPC5_CAN_USE_FLEXCAN2 && (SPC5_FLEXCAN2_MB == 64) if(&CAND3 == canp) { iflag2 = canp->flexcan->IFRH.R; canp->flexcan->IFRH.R = canp->flexcan->IFRH.R; } #endif #if SPC5_CAN_USE_FLEXCAN3 && (SPC5_FLEXCAN3_MB == 64) if(&CAND4 == canp) { iflag2 = canp->flexcan->IFRH.R; canp->flexcan->IFRH.R = canp->flexcan->IFRH.R; } #endif #if SPC5_CAN_USE_FLEXCAN4 && (SPC5_FLEXCAN4_MB == 64) if(&CAND5 == canp) { iflag2 = canp->flexcan->IFRH.R; canp->flexcan->IFRH.R = canp->flexcan->IFRH.R; } #endif #if SPC5_CAN_USE_FLEXCAN5 && (SPC5_FLEXCAN5_MB == 64) if(&CAND6 == canp) { iflag2 = canp->flexcan->IFRH.R; canp->flexcan->IFRH.R = canp->flexcan->IFRH.R; } #endif osalSysLockFromISR(); osalThreadDequeueAllI(&canp->txqueue, MSG_OK); #if SPC5_CAN_USE_FLEXCAN0 && (SPC5_FLEXCAN0_MB == 32) if(&CAND1 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag1 & 0xFFFFFF00); } #elif SPC5_CAN_USE_FLEXCAN0 && (SPC5_FLEXCAN0_MB == 64) if(&CAND1 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag2 | (iflag1 & 0xFFFFFF00)); } #endif #if SPC5_CAN_USE_FLEXCAN1 && (SPC5_FLEXCAN1_MB == 32) if(&CAND2 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag1 & 0xFFFFFF00); } #elif SPC5_CAN_USE_FLEXCAN1 && (SPC5_FLEXCAN1_MB == 64) if(&CAND2 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag2 | (iflag1 & 0xFFFFFF00)); } #endif #if SPC5_CAN_USE_FLEXCAN2 && (SPC5_FLEXCAN2_MB == 32) if(&CAND3 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag1 & 0xFFFFFF00); } #elif SPC5_CAN_USE_FLEXCAN2 && (SPC5_FLEXCAN2_MB == 64) if(&CAND3 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag2 | (iflag1 & 0xFFFFFF00)); } #endif #if SPC5_CAN_USE_FLEXCAN3 && (SPC5_FLEXCAN3_MB == 32) if(&CAND4 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag1 & 0xFFFFFF00); } #elif SPC5_CAN_USE_FLEXCAN3 && (SPC5_FLEXCAN3_MB == 64) if(&CAND4 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag2 | (iflag1 & 0xFFFFFF00)); } #endif #if SPC5_CAN_USE_FLEXCAN4 && (SPC5_FLEXCAN4_MB == 32) if(&CAND5 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag1 & 0xFFFFFF00); } #elif SPC5_CAN_USE_FLEXCAN4 && (SPC5_FLEXCAN4_MB == 64) if(&CAND5 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag2 | (iflag1 & 0xFFFFFF00)); } #endif #if SPC5_CAN_USE_FLEXCAN5 && (SPC5_FLEXCAN5_MB == 32) if(&CAND6 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag1 & 0xFFFFFF00); } #elif SPC5_CAN_USE_FLEXCAN5 && (SPC5_FLEXCAN5_MB == 64) if(&CAND6 == canp) { osalEventBroadcastFlagsI(&canp->txempty_event, iflag2 | (iflag1 & 0xFFFFFF00)); } #endif osalSysUnlockFromISR(); } /** * @brief Common RX ISR handler. * * @param[in] canp pointer to the @p CANDriver object * * @notapi */ static void can_lld_rx_handler(CANDriver *canp) { uint32_t iflag1; iflag1 = canp->flexcan->IFRL.R; if ((iflag1 & 0x000000FF) != 0) { osalSysLockFromISR(); osalThreadDequeueAllI(&canp->rxqueue, MSG_OK); osalEventBroadcastFlagsI(&canp->rxfull_event, iflag1 & 0x000000FF); osalSysUnlockFromISR(); /* Release the mailbox.*/ canp->flexcan->IFRL.R = iflag1 & 0x000000FF; } } /** * @brief Common error ISR handler. * * @param[in] canp pointer to the @p CANDriver object * * @notapi */ static void can_lld_err_handler(CANDriver *canp) { uint32_t esr = canp->flexcan->ESR.R; eventflags_t flags = 0; /* Error event.*/ if ((esr & CAN_ESR_TWRN_INT) || (esr & CAN_ESR_RWRN_INT)) { canp->flexcan->ESR.B.TXWRN = 1U; canp->flexcan->ESR.B.RXWRN = 1U; flags |= CAN_LIMIT_WARNING; } if (esr & CAN_ESR_BOFF_INT) { canp->flexcan->ESR.B.BOFFINT = 1U; flags |= CAN_BUS_OFF_ERROR; } if (esr & CAN_ESR_ERR_INT) { canp->flexcan->ESR.B.ERRINT = 1U; flags |= CAN_FRAMING_ERROR; } osalSysLockFromISR(); osalEventBroadcastFlagsI(&canp->error_event, flags); osalSysUnlockFromISR(); } /*===========================================================================*/ /* Driver interrupt handlers. */ /*===========================================================================*/ #if SPC5_CAN_USE_FLEXCAN0 || defined(__DOXYGEN__) #if !SPC5_FLEXCAN0_SHARED_IRQ /** * @brief CAN1 RX interrupt handler for MB 0. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_00_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 RX interrupt handler for MB 1. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_01_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 RX interrupt handler for MB 2. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_02_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 RX interrupt handler for MB 3. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 RX interrupt handler for MB 4. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_04_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 RX interrupt handler for MB 5. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_05_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 RX interrupt handler for MB 6. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_06_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 RX interrupt handler for MB 7. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 8. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_08_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 9. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_09_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 10. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_10_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 12. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_12_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 13. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_13_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 14. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_14_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN0_MB == 64) /** * @brief CAN1 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } #endif /** * @brief CAN1 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } #else /** * @brief CAN1 TX interrupt handler for MB 8-11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_08_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 12-15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_12_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN0_MB == 64) /** * @brief CAN1 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } #endif /* * @brief CAN1 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_00_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /* * @brief CAN1 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_BUF_04_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN1 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN0_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND1); OSAL_IRQ_EPILOGUE(); } #endif #endif /* SPC5_CAN_USE_FLEXCAN0 */ #if SPC5_CAN_USE_FLEXCAN1 || defined(__DOXYGEN__) #if !SPC5_FLEXCAN1_SHARED_IRQ /** * @brief CAN2 RX interrupt handler for MB 0. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_00_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 RX interrupt handler for MB 1. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_01_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 RX interrupt handler for MB 2. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_02_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 RX interrupt handler for MB 3. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 RX interrupt handler for MB 4. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_04_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 RX interrupt handler for MB 5. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_05_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 RX interrupt handler for MB 6. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_06_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 RX interrupt handler for MB 7. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 8. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_08_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 9. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_09_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 10. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_10_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 12. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_12_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 13. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_13_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 14. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_14_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN1_MB == 64) /** * @brief CAN2 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } #endif /** * @brief CAN2 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } #else /** * @brief CAN2 TX interrupt handler for MB 8-11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_08_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 12-15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_12_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN1_MB == 64) /** * @brief CAN2 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } #endif /* * @brief CAN2 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_00_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /* * @brief CAN2 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_BUF_04_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN2 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN1_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND2); OSAL_IRQ_EPILOGUE(); } #endif #endif /* SPC5_CAN_USE_FLEXCAN1 */ #if SPC5_CAN_USE_FLEXCAN2 || defined(__DOXYGEN__) #if !SPC5_FLEXCAN2_SHARED_IRQ /** * @brief CAN3 RX interrupt handler for MB 0. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_00_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 RX interrupt handler for MB 1. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_01_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 RX interrupt handler for MB 2. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_02_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 RX interrupt handler for MB 3. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 RX interrupt handler for MB 4. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_04_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 RX interrupt handler for MB 5. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_05_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 RX interrupt handler for MB 6. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_06_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 RX interrupt handler for MB 7. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 8. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_08_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 9. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_09_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 10. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_10_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 12. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_12_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 13. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_13_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 14. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_14_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN2_MB == 64) /** * @brief CAN3 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } #endif /** * @brief CAN3 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } #else /** * @brief CAN3 TX interrupt handler for MB 8-11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_08_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 12-15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_12_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN2_MB == 64) /** * @brief CAN3 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } #endif /* * @brief CAN3 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_00_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /* * @brief CAN3 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_BUF_04_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN3 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN2_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND3); OSAL_IRQ_EPILOGUE(); } #endif #endif /* SPC5_CAN_USE_FLEXCAN2 */ #if SPC5_CAN_USE_FLEXCAN3 || defined(__DOXYGEN__) #if !SPC5_FLEXCAN3_SHARED_IRQ /** * @brief CAN4 RX interrupt handler for MB 0. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_00_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 RX interrupt handler for MB 1. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_01_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 RX interrupt handler for MB 2. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_02_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 RX interrupt handler for MB 3. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 RX interrupt handler for MB 4. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_04_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 RX interrupt handler for MB 5. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_05_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 RX interrupt handler for MB 6. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_06_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 RX interrupt handler for MB 7. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 8. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_08_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 9. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_09_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 10. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_10_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 12. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_12_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 13. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_13_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 14. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_14_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN3_MB == 64) /** * @brief CAN4 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } #endif /** * @brief CAN4 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } #else /** * @brief CAN4 TX interrupt handler for MB 8-11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_08_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 12-15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_12_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN3_MB == 64) /** * @brief CAN4 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } #endif /* * @brief CAN4 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_00_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /* * @brief CAN4 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_BUF_04_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN4 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN3_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND4); OSAL_IRQ_EPILOGUE(); } #endif #endif /* SPC5_CAN_USE_FLEXCAN3 */ #if SPC5_CAN_USE_FLEXCAN4 || defined(__DOXYGEN__) #if !SPC5_FLEXCAN4_SHARED_IRQ /** * @brief CAN5 RX interrupt handler for MB 0. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_00_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 RX interrupt handler for MB 1. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_01_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 RX interrupt handler for MB 2. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_02_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 RX interrupt handler for MB 3. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 RX interrupt handler for MB 4. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_04_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 RX interrupt handler for MB 5. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_05_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 RX interrupt handler for MB 6. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_06_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 RX interrupt handler for MB 7. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 8. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_08_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 9. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_09_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 10. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_10_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 12. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_12_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 13. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_13_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 14. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_14_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN4_MB == 64) /** * @brief CAN5 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } #endif /** * @brief CAN5 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } #else /** * @brief CAN5 TX interrupt handler for MB 8-11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_08_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 12-15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_12_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN4_MB == 64) /** * @brief CAN5 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } #endif /* * @brief CAN5 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_00_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /* * @brief CAN5 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_BUF_04_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN5 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN4_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND5); OSAL_IRQ_EPILOGUE(); } #endif #endif /* SPC5_CAN_USE_FLEXCAN4 */ #if SPC5_CAN_USE_FLEXCAN5 || defined(__DOXYGEN__) #if !SPC5_FLEXCAN5_SHARED_IRQ /** * @brief CAN6 RX interrupt handler for MB 0. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_00_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 RX interrupt handler for MB 1. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_01_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 RX interrupt handler for MB 2. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_02_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 RX interrupt handler for MB 3. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 RX interrupt handler for MB 4. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_04_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 RX interrupt handler for MB 5. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_05_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 RX interrupt handler for MB 6. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_06_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 RX interrupt handler for MB 7. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 8. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_08_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 9. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_09_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 10. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_10_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 12. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_12_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 13. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_13_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 14. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_14_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN5_MB == 64) /** * @brief CAN6 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } #endif /** * @brief CAN6 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } #else /** * @brief CAN6 TX interrupt handler for MB 8-11. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_08_11_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 12-15. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_12_15_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 TX interrupt handler for MB 16-31. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_16_31_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } #if (SPC5_FLEXCAN5_MB == 64) /** * @brief CAN6 TX interrupt handler for MB 32-63. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_32_63_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_tx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } #endif /* * @brief CAN6 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_00_03_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /* * @brief CAN6 RX interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_BUF_04_07_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_rx_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 ESR_ERR_INT interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_ESR_ERR_INT_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } /** * @brief CAN6 ESR_BOFF interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_FLEXCAN5_FLEXCAN_ESR_BOFF_HANDLER) { OSAL_IRQ_PROLOGUE(); can_lld_err_handler(&CAND6); OSAL_IRQ_EPILOGUE(); } #endif #endif /* SPC5_CAN_USE_FLEXCAN5 */ /*===========================================================================*/ /* Driver exported functions. */ /*===========================================================================*/ /** * @brief Low level CAN driver initialization. * * @notapi */ void can_lld_init(void) { #if SPC5_CAN_USE_FLEXCAN0 /* Driver initialization.*/ canObjectInit(&CAND1); CAND1.flexcan = &SPC5_FLEXCAN_0; #if !SPC5_FLEXCAN0_SHARED_IRQ INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_00_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_01_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_02_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_03_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_04_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_05_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_06_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_07_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_08_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_09_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_10_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_11_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_12_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_13_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_14_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_15_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_32_63_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; #else INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_00_03_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_04_07_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_08_11_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_12_15_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN0_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN0_IRQ_PRIORITY; #endif #endif #if SPC5_CAN_USE_FLEXCAN1 /* Driver initialization.*/ canObjectInit(&CAND2); CAND2.flexcan = &SPC5_FLEXCAN_1; #if !SPC5_FLEXCAN1_SHARED_IRQ INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_00_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_01_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_02_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_03_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_04_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_05_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_06_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_07_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_08_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_09_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_10_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_11_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_12_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_13_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_14_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_15_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_32_63_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; #else INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_00_03_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_04_07_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_08_11_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_12_15_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN1_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN1_IRQ_PRIORITY; #endif #endif #if SPC5_CAN_USE_FLEXCAN2 /* Driver initialization.*/ canObjectInit(&CAND3); CAND3.flexcan = &SPC5_FLEXCAN_2; #if !SPC5_FLEXCAN2_SHARED_IRQ INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_00_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_01_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_02_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_03_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_04_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_05_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_06_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_07_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_08_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_09_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_10_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_11_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_12_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_13_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_14_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_15_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_32_63_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; #else INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_00_03_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_04_07_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_08_11_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_12_15_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN2_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN2_IRQ_PRIORITY; #endif #endif #if SPC5_CAN_USE_FLEXCAN3 /* Driver initialization.*/ canObjectInit(&CAND4); CAND4.flexcan = &SPC5_FLEXCAN_3; #if !SPC5_FLEXCAN3_SHARED_IRQ INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_00_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_01_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_02_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_03_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_04_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_05_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_06_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_07_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_08_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_09_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_10_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_11_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_12_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_13_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_14_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_15_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_32_63_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; #else INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_00_03_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_04_07_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_08_11_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_12_15_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN3_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN3_IRQ_PRIORITY; #endif #endif #if SPC5_CAN_USE_FLEXCAN4 /* Driver initialization.*/ canObjectInit(&CAND5); CAND5.flexcan = &SPC5_FLEXCAN_4; #if !SPC5_FLEXCAN4_SHARED_IRQ INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_00_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_01_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_02_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_03_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_04_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_05_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_06_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_07_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_08_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_09_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_10_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_11_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_12_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_13_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_14_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_15_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_32_63_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; #else INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_00_03_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_04_07_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_08_11_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_12_15_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN4_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN4_IRQ_PRIORITY; #endif #endif #if SPC5_CAN_USE_FLEXCAN5 /* Driver initialization.*/ canObjectInit(&CAND6); CAND6.flexcan = &SPC5_FLEXCAN_5; #if !SPC5_FLEXCAN5_SHARED_IRQ INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_00_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_01_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_02_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_03_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_04_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_05_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_06_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_07_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_08_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_09_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_10_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_11_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_12_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_13_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_14_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_15_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_32_63_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; #else INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_ESR_ERR_INT_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_ESR_BOFF_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_00_03_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_04_07_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_08_11_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_12_15_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; INTC.PSR[SPC5_FLEXCAN5_FLEXCAN_BUF_16_31_NUMBER].R = SPC5_CAN_FLEXCAN5_IRQ_PRIORITY; #endif #endif } /** * @brief Configures and activates the CAN peripheral. * * @param[in] canp pointer to the @p CANDriver object * * @notapi */ void can_lld_start(CANDriver *canp) { uint8_t mb_index = 0; #if SPC5_CAN_USE_FILTERS uint8_t id = 0; #endif /* Entering initialization mode. */ canp->state = CAN_STARTING; /* Clock activation.*/ #if SPC5_CAN_USE_FLEXCAN0 /* Set peripheral clock mode.*/ if(&CAND1 == canp) { SPC5_FLEXCAN0_ENABLE_CLOCK(); #if !SPC5_CAN_FLEXCAN0_USE_EXT_CLK canp->flexcan->CR.R |= CAN_CTRL_CLK_SRC; #endif } #endif #if SPC5_CAN_USE_FLEXCAN1 /* Set peripheral clock mode.*/ if(&CAND2 == canp) { SPC5_FLEXCAN1_ENABLE_CLOCK(); #if !SPC5_CAN_FLEXCAN1_USE_EXT_CLK canp->flexcan->CR.R |= CAN_CTRL_CLK_SRC; #endif } #endif #if SPC5_CAN_USE_FLEXCAN2 /* Set peripheral clock mode.*/ if(&CAND3 == canp) { SPC5_FLEXCAN2_ENABLE_CLOCK(); #if !SPC5_CAN_FLEXCAN2_USE_EXT_CLK canp->flexcan->CR.R |= CAN_CTRL_CLK_SRC; #endif } #endif #if SPC5_CAN_USE_FLEXCAN3 /* Set peripheral clock mode.*/ if(&CAND4 == canp) { SPC5_FLEXCAN3_ENABLE_CLOCK(); #if !SPC5_CAN_FLEXCAN3_USE_EXT_CLK canp->flexcan->CR.R |= CAN_CTRL_CLK_SRC; #endif } #endif #if SPC5_CAN_USE_FLEXCAN4 /* Set peripheral clock mode.*/ if(&CAND5 == canp) { SPC5_FLEXCAN4_ENABLE_CLOCK(); #if !SPC5_CAN_FLEXCAN4_USE_EXT_CLK canp->flexcan->CR.R |= CAN_CTRL_CLK_SRC; #endif } #endif #if SPC5_CAN_USE_FLEXCAN5 /* Set peripheral clock mode.*/ if(&CAND6 == canp) { SPC5_FLEXCAN5_ENABLE_CLOCK(); #if !SPC5_CAN_FLEXCAN5_USE_EXT_CLK canp->flexcan->CR.R |= CAN_CTRL_CLK_SRC; #endif } #endif /* Enable the device.*/ canp->flexcan->MCR.R &= ~CAN_MCR_MDIS; /* * Individual filtering per MB, disable frame self reception, * disable the FIFO, enable SuperVisor mode. */ #if SPC5_CAN_USE_FLEXCAN0 if(&CAND1 == canp) canp->flexcan->MCR.R |= CAN_MCR_SUPV | CAN_MCR_MAXMB(SPC5_FLEXCAN0_MB - 1); #endif #if SPC5_CAN_USE_FLEXCAN1 if(&CAND2 == canp) canp->flexcan->MCR.R |= CAN_MCR_SUPV | CAN_MCR_MAXMB(SPC5_FLEXCAN1_MB - 1); #endif #if SPC5_CAN_USE_FLEXCAN2 if(&CAND3 == canp) canp->flexcan->MCR.R |= CAN_MCR_SUPV | CAN_MCR_MAXMB(SPC5_FLEXCAN2_MB - 1); #endif #if SPC5_CAN_USE_FLEXCAN3 if(&CAND4 == canp) canp->flexcan->MCR.R |= CAN_MCR_SUPV | CAN_MCR_MAXMB(SPC5_FLEXCAN3_MB - 1); #endif #if SPC5_CAN_USE_FLEXCAN4 if(&CAND5 == canp) canp->flexcan->MCR.R |= CAN_MCR_SUPV | CAN_MCR_MAXMB(SPC5_FLEXCAN4_MB - 1); #endif #if SPC5_CAN_USE_FLEXCAN5 if(&CAND6 == canp) canp->flexcan->MCR.R |= CAN_MCR_SUPV | CAN_MCR_MAXMB(SPC5_FLEXCAN5_MB - 1); #endif canp->flexcan->CR.R |= CAN_CTRL_TSYN | CAN_CTRL_RJW(3); /* TX MB initialization.*/ #if SPC5_CAN_USE_FLEXCAN0 if(&CAND1 == canp) { for(mb_index = 0; mb_index < (SPC5_FLEXCAN0_MB - CAN_RX_MAILBOXES); mb_index++) { canp->flexcan->BUF[mb_index + CAN_RX_MAILBOXES].CS.B.CODE = 8U; } } #endif #if SPC5_CAN_USE_FLEXCAN1 if(&CAND2 == canp) { for(mb_index = 0; mb_index < (SPC5_FLEXCAN1_MB - CAN_RX_MAILBOXES); mb_index++) { canp->flexcan->BUF[mb_index + CAN_RX_MAILBOXES].CS.B.CODE = 8U; } } #endif #if SPC5_CAN_USE_FLEXCAN2 if(&CAND3 == canp) { for(mb_index = 0; mb_index < (SPC5_FLEXCAN2_MB - CAN_RX_MAILBOXES); mb_index++) { canp->flexcan->BUF[mb_index + CAN_RX_MAILBOXES].CS.B.CODE = 8U; } } #endif #if SPC5_CAN_USE_FLEXCAN3 if(&CAND4 == canp) { for(mb_index = 0; mb_index < (SPC5_FLEXCAN3_MB - CAN_RX_MAILBOXES); mb_index++) { canp->flexcan->BUF[mb_index + CAN_RX_MAILBOXES].CS.B.CODE = 8U; } } #endif #if SPC5_CAN_USE_FLEXCAN4 if(&CAND5 == canp) { for(mb_index = 0; mb_index < (SPC5_FLEXCAN4_MB - CAN_RX_MAILBOXES); mb_index++) { canp->flexcan->BUF[mb_index + CAN_RX_MAILBOXES].CS.B.CODE = 8U; } } #endif #if SPC5_CAN_USE_FLEXCAN5 if(&CAND6 == canp) { for(mb_index = 0; mb_index < (SPC5_FLEXCAN5_MB - CAN_RX_MAILBOXES); mb_index++) { canp->flexcan->BUF[mb_index + CAN_RX_MAILBOXES].CS.B.CODE = 8U; } } #endif /* Unlock Message buffers.*/ (void) canp->flexcan->TIMER.R; /* MCR initialization.*/ canp->flexcan->MCR.R |= canp->config->mcr; /* CTRL initialization.*/ canp->flexcan->CR.R |= canp->config->ctrl; /* Interrupt sources initialization.*/ canp->flexcan->MCR.R |= CAN_MCR_WRN_EN; canp->flexcan->CR.R |= CAN_CTRL_BOFF_MSK | CAN_CTRL_ERR_MSK | CAN_CTRL_TWRN_MSK | CAN_CTRL_RWRN_MSK; #if !SPC5_CAN_USE_FILTERS /* RX MB initialization.*/ for(mb_index = 0; mb_index < CAN_RX_MAILBOXES; mb_index++) { canp->flexcan->BUF[mb_index].CS.B.CODE = 0U; if(mb_index < 4) { canp->flexcan->BUF[mb_index].CS.B.IDE = 0U; } else { canp->flexcan->BUF[mb_index].CS.B.IDE = 1U; } canp->flexcan->BUF[mb_index].ID.R = 0U; canp->flexcan->BUF[mb_index].CS.B.CODE = 4U; } /* Receive all.*/ canp->flexcan->RXGMASK.R = 0x00000000; #else for (id = 0; id < CAN_RX_MAILBOXES; id++) { canp->flexcan->BUF[id].CS.B.CODE = 0U; if (canp->config->RxFilter[id].scale) { canp->flexcan->BUF[id].CS.B.IDE = 1U; canp->flexcan->BUF[id].ID.R = canp->config->RxFilter[id].register1; } else { canp->flexcan->BUF[id].CS.B.IDE = 0U; canp->flexcan->BUF[id].ID.B.STD_ID = canp->config->RxFilter[id].register1; canp->flexcan->BUF[id].ID.B.EXT_ID = 0U; } /* RX MB initialization.*/ canp->flexcan->BUF[id].CS.B.CODE = 4U; } canp->flexcan->RXGMASK.R = 0x0FFFFFFF; #endif /* Enable MBs interrupts.*/ #if SPC5_CAN_USE_FLEXCAN0 if(&CAND1 == canp) { if(SPC5_FLEXCAN0_MB == 32) { canp->flexcan->IMRL.R = 0xFFFFFFFF; } else if(SPC5_FLEXCAN0_MB == 64) { canp->flexcan->IMRL.R = 0xFFFFFFFF; canp->flexcan->IMRH.R = 0xFFFFFFFF; } } #endif #if SPC5_CAN_USE_FLEXCAN1 if(&CAND2 == canp) { if(SPC5_FLEXCAN1_MB == 32) { canp->flexcan->IMRL.R = 0xFFFFFFFF; } else if(SPC5_FLEXCAN1_MB == 64) { canp->flexcan->IMRL.R = 0xFFFFFFFF; canp->flexcan->IMRH.R = 0xFFFFFFFF; } } #endif #if SPC5_CAN_USE_FLEXCAN2 if(&CAND3 == canp) { if(SPC5_FLEXCAN2_MB == 32) { canp->flexcan->IMRL.R = 0xFFFFFFFF; } else if(SPC5_FLEXCAN2_MB == 64) { canp->flexcan->IMRL.R = 0xFFFFFFFF; canp->flexcan->IMRH.R = 0xFFFFFFFF; } } #endif #if SPC5_CAN_USE_FLEXCAN3 if(&CAND4 == canp) { if(SPC5_FLEXCAN3_MB == 32) { canp->flexcan->IMRL.R = 0xFFFFFFFF; } else if(SPC5_FLEXCAN3_MB == 64) { canp->flexcan->IMRL.R = 0xFFFFFFFF; canp->flexcan->IMRH.R = 0xFFFFFFFF; } } #endif #if SPC5_CAN_USE_FLEXCAN4 if(&CAND5 == canp) { if(SPC5_FLEXCAN4_MB == 32) { canp->flexcan->IMRL.R = 0xFFFFFFFF; } else if(SPC5_FLEXCAN4_MB == 64) { canp->flexcan->IMRL.R = 0xFFFFFFFF; canp->flexcan->IMRH.R = 0xFFFFFFFF; } } #endif #if SPC5_CAN_USE_FLEXCAN5 if(&CAND6 == canp) { if(SPC5_FLEXCAN5_MB == 32) { canp->flexcan->IMRL.R = 0xFFFFFFFF; } else if(SPC5_FLEXCAN5_MB == 64) { canp->flexcan->IMRL.R = 0xFFFFFFFF; canp->flexcan->IMRH.R = 0xFFFFFFFF; } } #endif /* CAN BUS synchronization.*/ canp->flexcan->MCR.B.HALT = 0; } /** * @brief Deactivates the CAN peripheral. * * @param[in] canp pointer to the @p CANDriver object * * @notapi */ void can_lld_stop(CANDriver *canp) { /* If in ready state then disables the CAN peripheral.*/ if (canp->state == CAN_READY) { /* Disable Interrupt sources.*/ canp->flexcan->MCR.R &= ~CAN_MCR_WRN_EN; canp->flexcan->CR.R &= ~(CAN_CTRL_BOFF_MSK | CAN_CTRL_ERR_MSK | CAN_CTRL_TWRN_MSK | CAN_CTRL_RWRN_MSK); canp->flexcan->IMRL.R = 0x00000000; canp->flexcan->MCR.R &= ~CAN_MCR_MDIS; #if SPC5_CAN_USE_FLEXCAN0 /* Set peripheral clock mode.*/ if(&CAND1 == canp) { SPC5_FLEXCAN0_DISABLE_CLOCK(); } #endif #if SPC5_CAN_USE_FLEXCAN1 /* Set peripheral clock mode.*/ if(&CAND2 == canp) { SPC5_FLEXCAN1_DISABLE_CLOCK(); } #endif #if SPC5_CAN_USE_FLEXCAN2 /* Set peripheral clock mode.*/ if(&CAND3 == canp) { SPC5_FLEXCAN2_DISABLE_CLOCK(); } #endif #if SPC5_CAN_USE_FLEXCAN3 /* Set peripheral clock mode.*/ if(&CAND4 == canp) { SPC5_FLEXCAN3_DISABLE_CLOCK(); } #endif #if SPC5_CAN_USE_FLEXCAN4 /* Set peripheral clock mode.*/ if(&CAND5 == canp) { SPC5_FLEXCAN4_DISABLE_CLOCK(); } #endif #if SPC5_CAN_USE_FLEXCAN5 /* Set peripheral clock mode.*/ if(&CAND6 == canp) { SPC5_FLEXCAN5_DISABLE_CLOCK(); } #endif } } /** * @brief Determines whether a frame can be transmitted. * * @param[in] canp pointer to the @p CANDriver object * @param[in] mailbox mailbox number, @p CAN_ANY_MAILBOX for any mailbox * * @return The queue space availability. * @retval FALSE no space in the transmit queue. * @retval TRUE transmit slot available. * * @notapi */ bool can_lld_is_tx_empty(CANDriver *canp, canmbx_t mailbox) { uint8_t mbid = 0; if(mailbox == CAN_ANY_MAILBOX) { #if SPC5_CAN_USE_FLEXCAN0 if(&CAND1 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN0_MB; mbid++) { if (canp->flexcan->BUF[mbid].CS.B.CODE == 0x08) { return TRUE; } } return FALSE; } #endif #if SPC5_CAN_USE_FLEXCAN1 if(&CAND2 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN1_MB; mbid++) { if (canp->flexcan->BUF[mbid].CS.B.CODE == 0x08) { return TRUE; } } return FALSE; } #endif #if SPC5_CAN_USE_FLEXCAN2 if(&CAND3 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN2_MB; mbid++) { if (canp->flexcan->BUF[mbid].CS.B.CODE == 0x08) { return TRUE; } } return FALSE; } #endif #if SPC5_CAN_USE_FLEXCAN3 if(&CAND4 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN3_MB; mbid++) { if (canp->flexcan->BUF[mbid].CS.B.CODE == 0x08) { return TRUE; } } return FALSE; } #endif #if SPC5_CAN_USE_FLEXCAN4 if(&CAND5 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN4_MB; mbid++) { if (canp->flexcan->BUF[mbid].CS.B.CODE == 0x08) { return TRUE; } } return FALSE; } #endif #if SPC5_CAN_USE_FLEXCAN5 if(&CAND6 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN5_MB; mbid++) { if (canp->flexcan->BUF[mbid].CS.B.CODE == 0x08) { return TRUE; } } return FALSE; } #endif } else { return canp->flexcan->BUF[mailbox + 7].CS.B.CODE == 0x08; } return FALSE; } /** * @brief Inserts a frame into the transmit queue. * * @param[in] canp pointer to the @p CANDriver object * @param[in] ctfp pointer to the CAN frame to be transmitted * @param[in] mailbox mailbox number, @p CAN_ANY_MAILBOX for any mailbox * * @notapi */ void can_lld_transmit(CANDriver *canp, canmbx_t mailbox, const CANTxFrame *ctfp) { CAN_TxMailBox_TypeDef *tmbp = NULL; uint8_t mbid = 0; /* Pointer to a free transmission mailbox.*/ if (mailbox == CAN_ANY_MAILBOX) { #if SPC5_CAN_USE_FLEXCAN0 if(&CAND1 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN0_MB; mbid++) { if ((canp->flexcan->BUF[mbid].CS.B.CODE & 8U) == 1) { tmbp = (CAN_TxMailBox_TypeDef *)&canp->flexcan->BUF[mbid]; break; } } } #endif #if SPC5_CAN_USE_FLEXCAN1 if(&CAND2 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN1_MB; mbid++) { if ((canp->flexcan->BUF[mbid].CS.B.CODE & 8U) == 1) { tmbp = (CAN_TxMailBox_TypeDef *)&canp->flexcan->BUF[mbid]; break; } } } #endif #if SPC5_CAN_USE_FLEXCAN2 if(&CAND3 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN2_MB; mbid++) { if ((canp->flexcan->BUF[mbid].CS.B.CODE & 8U) == 1) { tmbp = (CAN_TxMailBox_TypeDef *)&canp->flexcan->BUF[mbid]; break; } } } #endif #if SPC5_CAN_USE_FLEXCAN3 if(&CAND4 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN3_MB; mbid++) { if ((canp->flexcan->BUF[mbid].CS.B.CODE & 8U) == 1) { tmbp = (CAN_TxMailBox_TypeDef *)&canp->flexcan->BUF[mbid]; break; } } } #endif #if SPC5_CAN_USE_FLEXCAN4 if(&CAND5 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN4_MB; mbid++) { if ((canp->flexcan->BUF[mbid].CS.B.CODE & 8U) == 1) { tmbp = (CAN_TxMailBox_TypeDef *)&canp->flexcan->BUF[mbid]; break; } } } #endif #if SPC5_CAN_USE_FLEXCAN5 if(&CAND6 == canp) { for (mbid = 8; mbid < SPC5_FLEXCAN5_MB; mbid++) { if ((canp->flexcan->BUF[mbid].CS.B.CODE & 8U) == 1) { tmbp = (CAN_TxMailBox_TypeDef *)&canp->flexcan->BUF[mbid]; break; } } } #endif } else { tmbp = (CAN_TxMailBox_TypeDef *)&canp->flexcan->BUF[mailbox + 7]; } /* Preparing the message.*/ if (ctfp->IDE) { tmbp->CS.B.IDE = 1U; tmbp->CS.B.RTR = 0U; tmbp->ID.R = ctfp->EID; } else { tmbp->CS.B.IDE = 0U; tmbp->CS.B.RTR = 0U; tmbp->ID.R = ctfp->SID << 18; } tmbp->CS.B.LENGTH = ctfp->LENGTH; tmbp->DATA[0] = ctfp->data32[0]; tmbp->DATA[1] = ctfp->data32[1]; tmbp->CS.B.CODE = 0x0C; } /** * * @brief Determines whether a frame has been received. * * @param[in] canp pointer to the @p CANDriver object * @param[in] mailbox mailbox number, @p CAN_ANY_MAILBOX for any mailbox * * @return The queue space availability. * @retval FALSE no space in the transmit queue. * @retval TRUE transmit slot available. * * @notapi */ bool can_lld_is_rx_nonempty(CANDriver *canp, canmbx_t mailbox) { uint8_t mbid = 0; bool mb_status = FALSE; switch (mailbox) { case CAN_ANY_MAILBOX: for (mbid = 0; mbid < CAN_RX_MAILBOXES; mbid++) { if(canp->flexcan->BUF[mbid].CS.B.CODE == 2U) { mb_status = TRUE; } } return mb_status; case 1: return (canp->flexcan->BUF[0].CS.B.CODE == 2U); case 2: return (canp->flexcan->BUF[1].CS.B.CODE == 2U); case 3: return (canp->flexcan->BUF[2].CS.B.CODE == 2U); case 4: return (canp->flexcan->BUF[3].CS.B.CODE == 2U); case 5: return (canp->flexcan->BUF[4].CS.B.CODE == 2U); case 6: return (canp->flexcan->BUF[5].CS.B.CODE == 2U); case 7: return (canp->flexcan->BUF[6].CS.B.CODE == 2U); case 8: return (canp->flexcan->BUF[7].CS.B.CODE == 2U); default: return FALSE; } } /** * @brief Receives a frame from the input queue. * * @param[in] canp pointer to the @p CANDriver object * @param[in] mailbox mailbox number, @p CAN_ANY_MAILBOX for any mailbox * @param[out] crfp pointer to the buffer where the CAN frame is copied * * @notapi */ void can_lld_receive(CANDriver *canp, canmbx_t mailbox, CANRxFrame *crfp) { uint32_t mbid = 0, index = 0; if(mailbox != CAN_ANY_MAILBOX) { mbid = mailbox - 1; } else { for (index = 0; index < CAN_RX_MAILBOXES; index++) { if(canp->flexcan->BUF[index].CS.B.CODE == 2U) { mbid = index; break; } } } /* Lock the RX MB.*/ (void) canp->flexcan->BUF[mbid].CS.B.CODE; /* Fetches the message.*/ crfp->data32[0] = canp->flexcan->BUF[mbid].DATA.W[0]; crfp->data32[1] = canp->flexcan->BUF[mbid].DATA.W[1]; /* Decodes the various fields in the RX frame.*/ crfp->RTR = canp->flexcan->BUF[mbid].CS.B.RTR; crfp->IDE = canp->flexcan->BUF[mbid].CS.B.IDE; if (crfp->IDE) crfp->EID = canp->flexcan->BUF[mbid].ID.R & 0x1FFFFFFF; else crfp->SID = canp->flexcan->BUF[mbid].ID.B.STD_ID; crfp->LENGTH = canp->flexcan->BUF[mbid].CS.B.LENGTH; crfp->TIME = canp->flexcan->BUF[mbid].CS.B.TIMESTAMP; /* Unlock the RX MB.*/ (void) canp->flexcan->TIMER.R; /* Reconfigure the RX MB in empty status.*/ canp->flexcan->BUF[mbid].CS.B.CODE = 4U; } #if CAN_USE_SLEEP_MODE || defined(__DOXYGEN__) /** * @brief Enters the sleep mode. * * @param[in] canp pointer to the @p CANDriver object * * @notapi */ void can_lld_sleep(CANDriver *canp) { /*canp->can->MCR |= CAN_MCR_SLEEP;*/ } /** * @brief Enforces leaving the sleep mode. * * @param[in] canp pointer to the @p CANDriver object * * @notapi */ void can_lld_wakeup(CANDriver *canp) { /*canp->can->MCR &= ~CAN_MCR_SLEEP;*/ } #endif /* CAN_USE_SLEEP_MODE */ #endif /* HAL_USE_CAN */ /** @} */
20.156588
83
0.694837
[ "object" ]
83640b190f7a43de0536227f0aacc47a4d7f2935
803
h
C
src/supplySwapper.h
robhor/tcbvrp
86cd6c1ec5a1152ff2ddb154183b005f6f7751ed
[ "MIT" ]
null
null
null
src/supplySwapper.h
robhor/tcbvrp
86cd6c1ec5a1152ff2ddb154183b005f6f7751ed
[ "MIT" ]
null
null
null
src/supplySwapper.h
robhor/tcbvrp
86cd6c1ec5a1152ff2ddb154183b005f6f7751ed
[ "MIT" ]
null
null
null
// Copyright 2014 Robert Horvath, Johannes Vogel #ifndef SRC_SUPPLYSWAPPER_H_ #define SRC_SUPPLYSWAPPER_H_ #include <vector> #include "./instance.h" #include "./solution.h" class SupplySwapper { Solution* solution; int i, j, num_nodes; vector<int> remaining_supplies; int old_node; bool increment(); /// Increment i and j, return false no more indices void swap_nodes(); /// Swap current nodes i and j bool swap_valid(); /// Checks if last swap violates time limits public: explicit SupplySwapper(Solution* solution); Solution* next(); /// Generates the next swapped solution void accept(); /// Accepts the last generated solution as a new base Solution* reset(); /// Undo swap, retrieve original solution }; #endif // SRC_SUPPLYSWAPPER_H_
29.740741
77
0.701121
[ "vector" ]
8365c6abebf6737b32b124ac38de41970ce29b2f
1,098
h
C
src/services/pcn-dynmon/src/base/DynmonBase.h
stefalbi/polycube
f7b65ece48505458796cb4969d41677e991fbdc8
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/services/pcn-dynmon/src/base/DynmonBase.h
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/services/pcn-dynmon/src/base/DynmonBase.h
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
#pragma once #include "../models/DataplaneConfig.h" #include "../models/Metrics.h" #include "../serializer/DynmonJsonObject.h" #include "polycube/services/fifo_map.hpp" #include "polycube/services/transparent_cube.h" #include "polycube/services/utils.h" #include <spdlog/spdlog.h> using namespace polycube::service::model; class DynmonBase : public virtual polycube::service::TransparentCube { public: explicit DynmonBase(const std::string name); ~DynmonBase() override = default; virtual void update(const DynmonJsonObject &conf); virtual DynmonJsonObject toJsonObject(); /** * Dataplane configuration */ virtual std::shared_ptr<DataplaneConfig> getDataplaneConfig() = 0; virtual void setDataplaneConfig(const DataplaneConfigJsonObject &value) = 0; virtual void resetDataplaneConfig() = 0; /** * Collected metrics in JSON format */ virtual std::shared_ptr<Metrics> getMetrics() = 0; /** * Collected metrics in OpenMetrics Format of both ingress and egress paths */ virtual std::string getOpenMetrics() = 0; protected: std::string m_name; };
27.45
78
0.736794
[ "model" ]
8372a51ddaf51eff5c736e020fe7de4678a7234a
2,633
h
C
src/graph/planner/match/Expand.h
CPWstatic/nebula
4d6da3aac0b9aa3db1eaf7251ef5bd2700ef7af0
[ "Apache-2.0" ]
null
null
null
src/graph/planner/match/Expand.h
CPWstatic/nebula
4d6da3aac0b9aa3db1eaf7251ef5bd2700ef7af0
[ "Apache-2.0" ]
null
null
null
src/graph/planner/match/Expand.h
CPWstatic/nebula
4d6da3aac0b9aa3db1eaf7251ef5bd2700ef7af0
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #ifndef GRAPH_PLANNER_MATCH_EXPAND_H_ #define GRAPH_PLANNER_MATCH_EXPAND_H_ #include "common/base/Base.h" #include "graph/context/ast/CypherAstContext.h" #include "graph/planner/plan/PlanNode.h" #include "graph/planner/Planner.h" #include "graph/util/ExpressionUtils.h" namespace nebula { namespace graph { /* * The Expand was designed to handle the pattern expanding. */ class Expand final { public: Expand(MatchClauseContext* matchCtx, Expression* initialExpr) : matchCtx_(matchCtx), initialExpr_(initialExpr) {} Expand* reversely() { reversely_ = true; return this; } Expand* depends(PlanNode* dep) { dependency_ = dep; return this; } Expand* inputVar(const std::string& inputVar) { inputVar_ = inputVar; return this; } Status doExpand(const NodeInfo& node, const EdgeInfo& edge, SubPlan* plan); private: Status expandSteps(const NodeInfo& node, const EdgeInfo& edge, SubPlan* plan); Status expandStep(const EdgeInfo& edge, PlanNode* dep, const std::string& inputVar, const Expression* nodeFilter, SubPlan* plan); Status collectData(const PlanNode* joinLeft, const PlanNode* joinRight, PlanNode** passThrough, SubPlan* plan); Status filterDatasetByPathLength(const EdgeInfo& edge, PlanNode* input, SubPlan* plan); Expression* buildExpandCondition(const std::string& lastStepResult, int64_t startIndex, int64_t maxHop) const; template <typename T> T* saveObject(T* obj) const { return matchCtx_->qctx->objPool()->add(obj); } std::unique_ptr<std::vector<storage::cpp2::EdgeProp>> genEdgeProps(const EdgeInfo &edge); MatchClauseContext* matchCtx_; Expression* initialExpr_{nullptr}; bool reversely_{false}; PlanNode* dependency_{nullptr}; std::string inputVar_; }; } // namespace graph } // namespace nebula #endif // GRAPH_PLANNER_MATCH_EXPAND_H_
30.976471
93
0.575389
[ "vector" ]
837997e7a84574cfac928392030dd5813b364385
6,876
c
C
software/os/mselOS/src/arch/openrisc/arch.c
ProjectVault/orp
5a6fd68da19ad5baaeffbf6a40a4f8a8990e6619
[ "Apache-2.0" ]
473
2015-05-29T16:58:24.000Z
2021-11-17T08:01:24.000Z
software/os/mselOS/src/arch/openrisc/arch.c
VishalRohra/orp
5a6fd68da19ad5baaeffbf6a40a4f8a8990e6619
[ "Apache-2.0" ]
11
2015-06-08T08:57:44.000Z
2017-12-17T20:06:07.000Z
software/os/mselOS/src/arch/openrisc/arch.c
VishalRohra/orp
5a6fd68da19ad5baaeffbf6a40a4f8a8990e6619
[ "Apache-2.0" ]
64
2015-05-29T16:59:12.000Z
2020-04-20T13:10:47.000Z
/* Copyright 2015, Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdlib.h> #include <string.h> #include <msel.h> #include <msel/stdc.h> #include "os/system.h" #include "os/task.h" #include "os/taskmem.h" #include "or1k.h" #include "arch.h" void arch_init_task() { } msel_status arch_task_create(msel_tcb* task) { or1k_saved_regs* regs; /* make space for saved registers */ task->stack -= sizeof(or1k_saved_regs); task->stack -= 0x88; /* extra space needed to call restore w/o calling save @ first launch */ regs = (or1k_saved_regs*)task->stack; /* initialize registers */ msel_memset(regs, 0, sizeof(*regs)); /* Initialize the status register for the new task */ regs->sr |= SPR_SR_IEE; /* interrupt enable */ regs->sr |= SPR_SR_TEE; /* timer enable */ regs->sr |= SPR_SR_DME; /* Enable DMMU */ regs->sr |= SPR_SR_IME; /* Enable IMMU */ regs->sr |= SPR_SR_FO; /* Bit is fixed to 1, clearing this bit is undefined */ /* set pc to entrypoint */ regs->pc = (uint32_t)task->entry; /* The stack pointer (r1) will be initialized automatically on * context restore from the value of task->stack */ /* R3 and R4 are the C args of (*msel_task_entry)() */ regs->r3 = (uint32_t)task->arg; regs->r4 = (uint32_t)task->arg_sz; return MSEL_OK; } void arch_task_cleanup(msel_tcb* task) { } void arch_task_launch_main(msel_tcb* task) { msel_active_task = &msel_task_list[0]; msel_active_task_num = 0; __asm __volatile ( // "l.addi r10, r0, 1 \n" /* r10=1 means restore from active_task->stack */ "l.j context_restore \n" "l.nop \n" ); /* Never reached */ } msel_status arch_mutex_lock() { /* TODO! */ return MSEL_ENOTIMPL; } void arch_platform_init() { /* Most system init for openrisc happens in arch_init_isr() */ } void arch_nvm_write(uint8_t* dest, const uint8_t* src, uint32_t len) { (void)dest; (void)src; (void)len; } void arch_nvm_read(uint8_t* dest, uint8_t* src, uint32_t len) { (void)dest; (void)src; (void)len; } /* Initialize system timer interrupt (see OpenRisc Arch 1.1, Chapter 14)*/ void arch_init_tick_timer() { /* UPR[TTP] indicates if Tick Timer is present */ if(!(spr_read(SPR_UPR) & SPR_UPR_TTP)) msel_panic("TickTimer missing"); /* TTCR = 0; internal ctr must be initialized manually */ spr_write(SPR_TTCR, 0); /* TTMR[TP] = ticks_per_intr, TODO: figure out reasonable value for non-sim environment */ SPR_TTMR_TP_SET(500000); /* TTMR[M] = 0x1; auto-restart timer on expire */ SPR_TTMR_M_SET(1); /* TTMR[IP] = 0; Clear pending interrupt */ SPR_TTMR_IP_SET(0); /* TTMR[IE] = 1; Issue interrupt when counter matches configured value */ SPR_TTMR_IE_SET(1); /* SR[TEE] = 1; enable timer globally */ // SPR_SR_TEE_SET(1); } void arch_systick_handler() { /* TTMR[IP] = 0; Clear pending interrupt */ SPR_TTMR_IP_SET(0); } /* There are two MMUs because of the harvard arch, DMMU and IMMU. The page table scheme referenced in the specification is not actually implemented in and software is expected to implement this directly in the TLB via TLB-miss and page fault exceptions. mselOS will forego a full-sized page table implementation and instead statically build out the TLB for everything except a tasks private memory, for which tlb entries will be swapped in and out manually during context switching. Task 0 (msel_main) can see the entire address space: ROM: 0x00000000-0x00010000, 0-64k (currently 0x20000, 0-128k for debug) RAM: 0x00100000-0x00120000, 1MB-+128k Page size is 8k, so each 128k address space requires 16 TLB entries for 32 total (per bus). However, the insn bus will never need to execure from RAM so it only needs entries for ROM. For now all addresses will be identity mapped, but with an eye toward future potential to map to randomized addresses per task. (ASLR) */ extern int end; /* This must be called from an interrupt context with MMU disabled */ void arch_task_setup_mm(msel_tcb *task) { /* The only user page permissions that ever change are for each's * tasks private memory areas. Currently, these are all page * aligned and no shared memory is possible in between tasks. If * that changes we'll probably want to invalidate the cache * entries for the entire private area here before restoring * context */ } /* Set all interrupt priorities */ void arch_init_isr() { /* Setup interrupt vector base addr */ spr_write(SPR_EVBAR, ROM_START); /* Init timer */ arch_init_tick_timer(); /* Init hw interrupts */ uint32_t intrs = 0; intrs |= (1<<16); intrs |= (1<<17); spr_write(SPR_PICMR, intrs); } inline void* arch_get_task_heap() { register void* heapptr; /* assume 2k stacks, calc heap pointer from value of current stack ptr */ __asm __volatile( "l.addi %0, r1, 0x0800 \n" "l.movhi r29, 0xffff \n" "l.ori r29, r29, 0xf800 \n" "l.and %0, %0, r29 \n" :"=r"(heapptr) ::"r29" ); return heapptr; } int or1k_save_context() { /* interrupted task's SP saved via context_save */ register uint32_t task_sp asm("r31"); const int save_sz = 0x108; /* x80 for regs x80 for res space, 8 for frame */ or1k_saved_regs *regs = (or1k_saved_regs*)((uint8_t*)0x220000 - save_sz); size_t task = msel_active_task_num; /* Ensure the stack for interrupted task is valid */ if( (task_sp <= (uint32_t)taskmem_stack_bottom(task)+save_sz) || (task_sp > (uint32_t)taskmem_stack_top(task)) ) { if(task != MSEL_TASK_MAIN) { msel_task_force_kill(task, "Stack error"); /* Indicate that the handler should *NOT* be called */ return 0; } else { msel_panic("Stack error in task0"); } } /* Update saved stack ptr in task struct */ msel_active_task->stack = (void*)task_sp - save_sz; /* Copy saved reg values */ msel_memcpy(msel_active_task->stack, regs, sizeof(*regs)); /* Indicate that the handler should be called */ return 1; }
27.394422
97
0.655032
[ "vector" ]
837c931221ead13b5446d5a7be2f282b8697ee83
1,932
h
C
src/pog/invitebuffer.h
overcookedpanda/merit
5fb1604ae69aae71f746d018fd86f1e4b9c60ccc
[ "MIT" ]
null
null
null
src/pog/invitebuffer.h
overcookedpanda/merit
5fb1604ae69aae71f746d018fd86f1e4b9c60ccc
[ "MIT" ]
null
null
null
src/pog/invitebuffer.h
overcookedpanda/merit
5fb1604ae69aae71f746d018fd86f1e4b9c60ccc
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2020 The Merit Foundation // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MERIT_POG_INVITE_BUFFER_H #define MERIT_POG_INVITE_BUFFER_H #include "pog/reward.h" #include "chain.h" #include "sync.h" #include <vector> namespace pog { struct MeanStats { int invites_created = 0; int invites_used = 0; int invites_used_fixed = 0; int blocks = 0; double mean_used = 0.0; double mean_used_fixed = 0.0; MeanStats() {} MeanStats( int created, int used, int used_fixed, int blks, double mean, double mean_fixed) : invites_created{created}, invites_used{used}, invites_used_fixed{used_fixed}, blocks{blks}, mean_used{mean}, mean_used_fixed{mean_fixed} {} }; struct InviteStats { MeanStats mean_stats; int invites_created = 0; int invites_used = 0; int invites_used_fixed = 0; bool is_set = false; bool mean_set = false; }; class InviteBuffer { public: InviteBuffer(const CChain& c); InviteStats get(int height, const Consensus::Params& p) const; bool set_mean(int height, const MeanStats& mean_stats, const Consensus::Params& p); bool drop(int height, const Consensus::Params& p); private: bool get(int adjusted_height, InviteStats& s) const; void insert(int adjusted_height, const InviteStats& s) const; private: mutable std::vector<InviteStats> stats; mutable CCriticalSection cs; const CChain& chain; }; } // namespace pog #endif //MERIT_POG_INVITE_BUFFER_H
26.108108
95
0.588509
[ "vector" ]
8382659359dab496296913eb379c38bbf0f1cbe1
1,577
h
C
Code-Up/Pods/Headers/Public/OctoKit/OCTResponse.h
AdilVirani/HackerWeekend
df2ed9140923127889c64e5e3fec808095b04464
[ "MIT" ]
6
2015-01-18T05:04:00.000Z
2015-10-21T02:59:37.000Z
Code-Up/Pods/Headers/Public/OctoKit/OCTResponse.h
AdilVirani/HackerWeekend
df2ed9140923127889c64e5e3fec808095b04464
[ "MIT" ]
1
2015-02-17T00:10:49.000Z
2015-02-17T00:10:49.000Z
Code-Up/Pods/Headers/Public/OctoKit/OCTResponse.h
AdilVirani/HackerWeekend
df2ed9140923127889c64e5e3fec808095b04464
[ "MIT" ]
1
2015-02-13T06:56:22.000Z
2015-02-13T06:56:22.000Z
// // OCTResponse.h // OctoKit // // Created by Justin Spahr-Summers on 2012-10-01. // Copyright (c) 2012 GitHub. All rights reserved. // #import <Mantle/Mantle.h> // Represents a parsed response from the GitHub API, along with any useful // headers. @interface OCTResponse : MTLModel // The parsed MTLModel object corresponding to the API response. @property (nonatomic, strong, readonly) id parsedResult; // The etag uniquely identifying this response data. @property (nonatomic, copy, readonly) NSString *etag; // The HTTP status code returned in the response. @property (nonatomic, assign, readonly) NSInteger statusCode; // Set to any X-Poll-Interval header returned by the server, or nil if no such // header was returned. // // This is used with the events and notifications APIs to support server-driven // polling rates. @property (nonatomic, copy, readonly) NSNumber *pollInterval; // Set to the X-RateLimit-Limit header sent by the server, indicating how many // unconditional requests the user is allowed to make per hour. @property (nonatomic, assign, readonly) NSInteger maximumRequestsPerHour; // Set to the X-RateLimit-Remaining header sent by the server, indicating how // many remaining unconditional requests the user can make this hour (in server // time). @property (nonatomic, assign, readonly) NSInteger remainingRequests; // Initializes the receiver with the headers from the given response, and the // given parsed model object(s). - (instancetype)initWithHTTPURLResponse:(NSHTTPURLResponse *)response parsedResult:(id)parsedResult; @end
35.044444
100
0.766011
[ "object", "model" ]
838c8d7566f07c616cd610f0415bdf5fc09fc972
15,228
h
C
GameJam_v3.2/GameEngineBase/externals/Havok/includes/Source/Physics2012/Collide/Query/Multithreaded/RayCastQuery/hkpRayCastQueryJobs.h
aditgoyal19/Tropical-Go-Kart-Bananas
ed3c0489402f8a559c77b56545bd8ebc79c4c563
[ "MIT" ]
null
null
null
GameJam_v3.2/GameEngineBase/externals/Havok/includes/Source/Physics2012/Collide/Query/Multithreaded/RayCastQuery/hkpRayCastQueryJobs.h
aditgoyal19/Tropical-Go-Kart-Bananas
ed3c0489402f8a559c77b56545bd8ebc79c4c563
[ "MIT" ]
null
null
null
GameJam_v3.2/GameEngineBase/externals/Havok/includes/Source/Physics2012/Collide/Query/Multithreaded/RayCastQuery/hkpRayCastQueryJobs.h
aditgoyal19/Tropical-Go-Kart-Bananas
ed3c0489402f8a559c77b56545bd8ebc79c4c563
[ "MIT" ]
null
null
null
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKP_RAYCAST_QUERY_JOBS_H #define HKP_RAYCAST_QUERY_JOBS_H #include <Common/Base/Types/Geometry/Aabb/hkAabb.h> #include <Common/Base/Thread/Semaphore/hkSemaphoreBusyWait.h> #include <Common/Base/Thread/JobQueue/hkJobQueue.h> #include <Physics2012/Collide/Shape/Compound/Tree/hkpBvTreeShape.h> #include <Physics2012/Collide/Agent/Collidable/hkpCollidable.h> #include <Physics2012/Collide/Query/CastUtil/hkpWorldRayCastInput.h> #include <Physics2012/Collide/Query/CastUtil/hkpLinearCastInput.h> #include <Physics2012/Collide/Shape/Query/hkpShapeRayCastInput.h> #include <Physics2012/Collide/Shape/Query/hkpShapeRayCastOutput.h> #include <Physics2012/Collide/Query/Multithreaded/RayCastQuery/hkpRayCastQueryJobs.h> #include <Physics2012/Internal/Collide/Mopp/Code/hkpMoppCode.h> #include <Physics2012/Collide/Shape/Query/hkpShapeRayBundleCastInput.h> #include <Common/Base/Thread/Semaphore/hkSemaphoreBusyWait.h> class hkpBroadPhase; class hkpWorld; class hkpTreeWorldManager; struct hkpWorldRayCastOutput; #include <Physics2012/Collide/Query/Multithreaded/CollisionQuery/hkpCollisionQueryJobs.h> typedef hkpCollisionQueryJobHeader hkpRayCastQueryJobHeader; // // The base class for all collision query jobs // struct hkpRayCastQueryJob : public hkJob { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpRayCastQueryJob ); // Kd tree subtypes start at 128 to keep them separate from other pathfinding jobs enum JobSubType { // Query jobs RAYCAST_QUERY_SHAPE_RAYCAST, RAYCAST_QUERY_WORLD_RAYCAST, RAYCAST_QUERY_JOB_END }; void atomicIncrementAndReleaseSemaphore() const; protected: HK_FORCE_INLINE hkpRayCastQueryJob( JobSubType subType, hkUint16 size ); public: // This semaphore is released once the original job (and all its spawned children) has finished. hkSemaphoreBusyWait* m_semaphore; // this header must be set for all jobs that potentially spawn additional jobs or that have been spawned by other jobs hkpRayCastQueryJobHeader* m_sharedJobHeaderOnPpu; // The variable at this location will be incremented (atomically) when the job is done. hkUint32* m_jobDoneFlag; // Provides collision filter etc const hkpProcessCollisionInput* m_collisionInput; }; // =============================================================================================================================================================================================== // SHAPE RAYCAST // =============================================================================================================================================================================================== /// An hkpShapeRayCastCommand can be used to cast exactly one ray against an arbitrary number of collidables. Depending on how many hits you want /// to be reported you have to supply a large enough m_results output array. Once this array has reached its capacity, the furthest /// hit will be dropped. struct hkpShapeRayCastCommand { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpShapeRayCastCommand ); enum { MAXIMUM_RESULTS_CAPACITY = 96 }; // the capacity has to be limited as we need to allocate this array on the SPU stack enum { MAXIMUM_NUM_COLLIDABLES = 64 }; // the maximum number of collidables to cast the ray against has to be limited as we need to allocate a hkpCollidable pointer array on the SPU stack public: // =================================================================== // Input // =================================================================== /// The ray's input data. hkpShapeRayCastInput m_rayInput; /// Type of the filter referenced by m_rayInput.m_rayShapeCollectionFilter. /// Must be assigned in order for the filter to work on SPU. hkUint32 m_filterType; // type is: hkpFilterType /// Size of the filter referenced by m_rayInput.m_rayShapeCollectionFilter. /// Must be assigned in order for the filter to work on SPU. hkInt32 m_filterSize; /// Pointer to an array of hkpCollidable pointers. The ray will be cast against these collidables. /// This array has to be 16byte aligned. /// PlayStation(R)3 note: this array will be DMAd to SPU and therefore must not be allocated on PPU stack. const hkpCollidable** m_collidables; /// Number of collidables in the m_collidables array. int m_numCollidables; // =================================================================== // Output // =================================================================== /// Pointer to a hkpShapeRayCastOutput array. The user has to pre-allocate this manually. Once the job has finished, this array will hold the results. /// PlayStation(R)3 note: this array will be DMAd from SPU and therefore must not be allocated on PPU stack. hkpWorldRayCastOutput* m_results; /// The maximum number of results pre-allocated in m_results. int m_resultsCapacity; /// The number of results. Remains untouched until the command has been finished. /// You can use this to check manually whether the command already has been completed. int m_numResultsOut; /// When a collector is not used, only one point per hkpCollidable can be returned. hkBool m_useCollector; }; /// An hkpShapeRayCastJob will take an arbitrary number of hkShapeRayCastCommands and perform the raycasts. The job is able /// to split itself into two jobs if it holds more commands than the maximum allowed number that can be executed in one go. /// Jobs will be processed multithreaded (i.e., in parallel by different PPU and/or SPU threads, if available). struct hkpShapeRayCastJob : public hkpRayCastQueryJob { public: friend struct hkpRayCastQueryJobQueueUtils; HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpShapeRayCastJob ); enum { MAXIMUM_NUMBER_OF_COMMANDS_PER_TASK = 90 }; public: /// When creating an hkpShapeRayCastJob you have to pass in an unique jobHeader as well as an array of commands. /// The supplied semaphore is released once all commands of this job have been completed and the job has been removed from the job queue. /// The number of commands that are grouped into one task is customizable. /// PlayStation(R)3 note: the jobHeader and the commandArray will be DMAd to SPU and therefore must not be allocated on PPU stack. HK_FORCE_INLINE hkpShapeRayCastJob( const hkpProcessCollisionInput* input, hkpCollisionQueryJobHeader* jobHeader, const hkpShapeRayCastCommand* commandArray, int numCommands, hkSemaphoreBusyWait* semaphore, int numCommandsPerTask = MAXIMUM_NUMBER_OF_COMMANDS_PER_TASK); /// Only necessary on PlayStation(R)3. /// Use this method to assign this job to be processed on the SPU or PPU. This is automatically set depending on what the job references. /// If it references objects which are not supported on the SPU /// this function will produce a warning (in debug) and the job will be processed on PPU. void setRunsOnSpuOrPpu(); public: HK_FORCE_INLINE hkJobQueue::JobPopFuncResult popJobTask( hkpShapeRayCastJob& out ); int m_numCommandsPerTask; // maximum # of commands per task; once this limit is breached a subjob is spawned const hkpShapeRayCastCommand* m_commandArray; int m_numCommands; }; // =============================================================================================================================================================================================== // WORLD RAYCAST // =============================================================================================================================================================================================== /// An hkpWorldRayCastCommand can be used to cast exactly one ray through the broadphase. Depending on how many hits you want /// to be reported you have to supply a large enough m_results output array. Once this array has reached its capacity, the furthest /// hit will be dropped. /// Performance note: when supplying a m_results array-size of exactly 1, the broadphase will use an early-out algorithm to significantly /// speedup things. With an array-size > 1 this speedup will be lost. struct hkpWorldRayCastCommand { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpWorldRayCastCommand ); enum { MAXIMUM_RESULTS_CAPACITY = 32 }; // the capacity has to be limited as we need to allocate this array on the SPU stack public: hkpWorldRayCastCommand(){m_useCollector = false; m_stopAfterFirstHit = false;} // =================================================================== // Input // =================================================================== /// The ray's input data. hkpWorldRayCastInput m_rayInput; // =================================================================== // Output // =================================================================== /// Pointer to a hkpWorldRayCastOutput array. The user has to pre-allocate this manually. Once the job has finished, this array will hold the results. /// PlayStation(R)3 note: this array will be DMAd from SPU and therefore must not be allocated on PPU stack. /// If m_stopAfterFirstHit is set m_results->m_hitFraction does not work (just set to 0 when hit) hkpWorldRayCastOutput* m_results; /// The maximum number of results pre-allocated in m_results. int m_resultsCapacity; /// The number of results. /// This value is only valid after the job's semaphore has been released. int m_numResultsOut; /// When a collector is not used, only one point per hkpCollidable can be returned. /// When treeManager is set to the job, this is ignored hkBool m_useCollector; /// Whether or not the raycast should terminate after the first (not necessarily closest) hit. /// This can speed up queries such as line-of-sight checks, when you only care if the path is clear or not. /// If this is set m_results->m_hitFraction does not work (just set to 0 when hit) hkBool m_stopAfterFirstHit; }; /// struct hkpWorldRayCastBundleCommand { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpWorldRayCastBundleCommand ); public: // =================================================================== // Input // =================================================================== /// The rays' input data. hkpWorldRayCastInput m_rayInput[4]; /// Rays have to filled from the start int m_numActiveRays; /// Whether or not the raycast should terminate after the first (not necessarily closest) hit. /// This can speed up queries such as line-of-sight checks, when you only care if the path is clear or not. hkBool m_stopAfterFirstHit; // =================================================================== // Output // =================================================================== /// Pointer to a hkpWorldRayCastOutput array. The user has to pre-allocate this manually. Once the job has finished, this array will hold the results. /// PlayStation(R)3 note: this array will be DMAd from SPU and therefore must not be allocated on PPU stack. hkpWorldRayCastOutput* m_results[4]; /// The number of results. /// This value is only valid after the job's semaphore has been released. HK_ALIGN16(int m_numResultsOut[4]); // for broadphase implementation hkBool m_useCollector; }; /// An hkpWorldRayCastJob will take an arbitrary number of hkWorldRayCastCommands and perform the raycasts. The job is able /// to split itself into two jobs if it holds more commands than the maximum allowed number that can be executed in one go. /// Jobs will be processed multithreaded (i.e., in parallel by different PPU and/or SPU threads, if available). struct hkpWorldRayCastJob : public hkpRayCastQueryJob { public: friend struct hkpRayCastQueryJobQueueUtils; HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpWorldRayCastJob ); enum { MAXIMUM_NUMBER_OF_COMMANDS_PER_TASK = 64 }; public: /// When creating an hkpWorldRayCastJob you have to pass in an unique jobHeader as well as an array of commands. /// The supplied broadphase is used to limit the number of possible object pairs and thus helps increasing performance. /// The supplied semaphore is released once all commands of this job have been completed and the job has been removed from the job queue. /// The number of commands that are grouped into one task is customizable. /// PlayStation(R)3 note: the jobHeader and the commandArray will be DMAd to SPU and therefore must not be allocated on PPU stack. HK_FORCE_INLINE hkpWorldRayCastJob( const hkpProcessCollisionInput* input, hkpCollisionQueryJobHeader* jobHeader, const hkpWorldRayCastCommand* commandArray, int numCommands, const hkpBroadPhase* broadphase, hkSemaphoreBusyWait* semaphore, int numCommandsPerTask = MAXIMUM_NUMBER_OF_COMMANDS_PER_TASK); /// Only necessary on PlayStation(R)3. /// Use this method to assign this job to be processed on the SPU or PPU. This is automatically set depending on what the job references. /// If it references objects which are not supported on the SPU /// this function will produce a warning (in debug) and the job will be processed on PPU. void setRunsOnSpuOrPpu(); protected: HK_FORCE_INLINE hkJobQueue::JobPopFuncResult popJobTask( hkpWorldRayCastJob& out ); public: // Inputs int m_numCommandsPerTask; // maximum # of commands per task; once this limit is breached a subjob is spawned const hkpWorldRayCastCommand* m_commandArray; int m_numCommands; // if broadphase is used, these bundles are calculated one by one like single commands const hkpWorldRayCastBundleCommand* m_bundleCommandArray; int m_numBundleCommands; const hkpBroadPhase* m_broadphase; }; #include <Physics2012/Collide/Query/Multithreaded/RayCastQuery/hkpRayCastQueryJobs.inl> #endif // HKP_RAYCAST_QUERY_JOBS_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20130718) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
44.920354
304
0.68663
[ "geometry", "object", "shape" ]
839b86eea139cc6603765b5c8b79434586a849ee
2,203
h
C
log.h
mati75/evilwm
746f08a02b5c21897116636fcadc55ba982d8fb8
[ "Unlicense" ]
5
2016-03-29T03:46:23.000Z
2018-03-12T01:11:22.000Z
log.h
mati75/evilwm
746f08a02b5c21897116636fcadc55ba982d8fb8
[ "Unlicense" ]
3
2018-03-17T09:38:16.000Z
2020-06-16T12:28:54.000Z
log.h
mati75/evilwm
746f08a02b5c21897116636fcadc55ba982d8fb8
[ "Unlicense" ]
3
2017-04-27T07:23:42.000Z
2019-12-12T16:01:50.000Z
/* evilwm - minimalist window manager for X11 * Copyright (C) 1999-2021 Ciaran Anscomb <evilwm@6809.org.uk> * see README for license and other details. */ // Debugging macros and support functions. #ifndef EVILWM_LOG_H__ #define EVILWM_LOG_H__ #include <stdio.h> #ifdef XDEBUG # include <X11/X.h> # include <X11/Xlib.h> # include <X11/Xutil.h> #endif #if defined(DEBUG) || defined(XDEBUG) extern int log_indent; # define LOG_INDENT() do { for (int ii = 0; ii < log_indent; ii++) fprintf(stderr, " "); } while (0) #endif #define LOG_INFO(...) printf(__VA_ARGS__); #define LOG_ERROR(...) fprintf(stderr, __VA_ARGS__); // Debug macros: // // LOG_ENTER(...) on function entry; prints message, increases indent level // LOG_LEAVE(...) on function exit; decreases indent level, prints message // LOG_DEBUG(...) print message at current indent level // LOG_DEBUG_(...) print continuation message (no indent) #ifdef DEBUG # define LOG_ENTER(...) do { LOG_INDENT(); log_indent++; fprintf(stderr, __VA_ARGS__); fprintf(stderr, " at %s:%d\n", __FILE__, __LINE__); } while (0) # define LOG_LEAVE() do { if (log_indent > 0) log_indent--; } while (0) # define LOG_DEBUG(...) do { LOG_INDENT(); fprintf(stderr, __VA_ARGS__); } while (0) # define LOG_DEBUG_(...) fprintf(stderr, __VA_ARGS__) const char *debug_atom_name(Atom a); #else # define LOG_ENTER(...) # define LOG_LEAVE(...) # define LOG_DEBUG(...) # define LOG_DEBUG_(...) #endif // X call debugging macros: #ifdef XDEBUG # define LOG_XENTER(...) do { LOG_INDENT(); log_indent++; fprintf(stderr, __VA_ARGS__); fprintf(stderr, " at %s:%d\n", __FILE__, __LINE__); } while (0) # define LOG_XLEAVE(...) do { if (log_indent > 0) log_indent--; } while (0) # define LOG_XDEBUG(...) do { LOG_INDENT(); fprintf(stderr, __VA_ARGS__); } while (0) # define LOG_XDEBUG_(...) fprintf(stderr, __VA_ARGS__) // Print window geometry void debug_window_attributes(XWindowAttributes *attr); // Dump size hints void debug_wm_normal_hints(XSizeHints *size); #else # define LOG_XENTER(...) # define LOG_XLEAVE(...) # define LOG_XDEBUG(...) # define LOG_XDEBUG_(...) # define debug_window_attributes(a) # define debug_wm_normal_hints(s) #endif #endif
28.24359
151
0.697685
[ "geometry" ]
83b10047400f09365a5f2108fcef503d9560c1ee
807
h
C
aws-cpp-sdk-appstream/include/aws/appstream/model/UsageReportExecutionErrorCode.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-appstream/include/aws/appstream/model/UsageReportExecutionErrorCode.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-appstream/include/aws/appstream/model/UsageReportExecutionErrorCode.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/appstream/AppStream_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace AppStream { namespace Model { enum class UsageReportExecutionErrorCode { NOT_SET, RESOURCE_NOT_FOUND, ACCESS_DENIED, INTERNAL_SERVICE_ERROR }; namespace UsageReportExecutionErrorCodeMapper { AWS_APPSTREAM_API UsageReportExecutionErrorCode GetUsageReportExecutionErrorCodeForName(const Aws::String& name); AWS_APPSTREAM_API Aws::String GetNameForUsageReportExecutionErrorCode(UsageReportExecutionErrorCode value); } // namespace UsageReportExecutionErrorCodeMapper } // namespace Model } // namespace AppStream } // namespace Aws
24.454545
113
0.796778
[ "model" ]
83b1a5e335db2dea060d71835f6300f808f7da70
5,552
h
C
source/compute_engine/vulkan/vulkan_compute_pipeline.h
Knutakir/KTT
502a8588710e20adeff0a1c27b196aee2c206697
[ "MIT" ]
null
null
null
source/compute_engine/vulkan/vulkan_compute_pipeline.h
Knutakir/KTT
502a8588710e20adeff0a1c27b196aee2c206697
[ "MIT" ]
null
null
null
source/compute_engine/vulkan/vulkan_compute_pipeline.h
Knutakir/KTT
502a8588710e20adeff0a1c27b196aee2c206697
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <vulkan/vulkan.h> #include <compute_engine/vulkan/vulkan_buffer.h> #include <compute_engine/vulkan/vulkan_descriptor_pool.h> #include <compute_engine/vulkan/vulkan_descriptor_set_holder.h> #include <compute_engine/vulkan/vulkan_push_constant.h> #include <compute_engine/vulkan/vulkan_specialization_info.h> #include <compute_engine/vulkan/vulkan_utility.h> namespace ktt { class VulkanComputePipeline { public: VulkanComputePipeline() : device(nullptr), pipeline(nullptr), pipelineLayout(nullptr), descriptorSetLayout(nullptr), shaderName(""), descriptorPool(nullptr), descriptorSets(nullptr) {} explicit VulkanComputePipeline(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkShaderModule shader, const std::string& shaderName, const VulkanPushConstant& pushConstant) : device(device), descriptorSetLayout(descriptorSetLayout), shaderName(shaderName), descriptorPool(nullptr), descriptorSets(nullptr) { const VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0, 1, &descriptorSetLayout, 1, &pushConstant.getRange() }; checkVulkanError(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout), "vkCreatePipelineLayout"); const VkPipelineShaderStageCreateInfo shaderStageCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_COMPUTE_BIT, shader, shaderName.c_str(), nullptr }; const VkComputePipelineCreateInfo pipelineCreateInfo = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, nullptr, 0, shaderStageCreateInfo, pipelineLayout, nullptr, 0 }; checkVulkanError(vkCreateComputePipelines(device, nullptr, 1, &pipelineCreateInfo, nullptr, &pipeline), "vkCreateComputePipelines"); } ~VulkanComputePipeline() { if (pipeline != nullptr) { vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr); } } VkDevice getDevice() const { return device; } VkPipeline getPipeline() const { return pipeline; } VkPipelineLayout getPipelineLayout() const { return pipelineLayout; } const std::string& getShaderName() const { return shaderName; } void bindArguments(const std::vector<VulkanBuffer*>& buffers) { const uint32_t descriptorCount = static_cast<uint32_t>(buffers.size()); if (descriptorPool == nullptr || descriptorPool->getDescriptorCount() != descriptorCount) { descriptorSets.reset(nullptr); descriptorPool.reset(nullptr); descriptorPool = std::make_unique<VulkanDescriptorPool>(device, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, descriptorCount); descriptorSets = std::make_unique<VulkanDescriptorSetHolder>(device, descriptorPool->getDescriptorPool(), descriptorSetLayout); } for (size_t i = 0; i < buffers.size(); ++i) { descriptorSets->bindBuffer(*buffers[i], VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, static_cast<uint32_t>(i)); } } void recordDispatchShaderCommand(VkCommandBuffer commandBuffer, const std::vector<size_t>& globalSize, const VulkanPushConstant& pushConstant, VkQueryPool queryPool) { const VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr }; std::vector<VkDescriptorSet> sets = descriptorSets->getDescriptorSets(); checkVulkanError(vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo), "vkBeginCommandBuffer"); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, static_cast<uint32_t>(sets.size()), sets.data(), 0, nullptr); if (pushConstant.getRange().size > 0) { vkCmdPushConstants(commandBuffer, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, pushConstant.getRange().size, pushConstant.getData().data()); } vkCmdResetQueryPool(commandBuffer, queryPool, 0, 2); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, queryPool, 0); vkCmdDispatch(commandBuffer, static_cast<uint32_t>(globalSize[0]), static_cast<uint32_t>(globalSize[1]), static_cast<uint32_t>(globalSize[2])); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, queryPool, 1); checkVulkanError(vkEndCommandBuffer(commandBuffer), "vkEndCommandBuffer"); } private: VkDevice device; VkPipeline pipeline; VkPipelineLayout pipelineLayout; VkDescriptorSetLayout descriptorSetLayout; std::string shaderName; std::unique_ptr<VulkanDescriptorPool> descriptorPool; std::unique_ptr<VulkanDescriptorSetHolder> descriptorSets; }; } // namespace ktt
33.245509
149
0.677594
[ "vector" ]
83ba14321ab63f41a4d56c696a6898448465233f
11,822
h
C
lib/inc/drogon/utils/Utilities.h
rizalgowandy/drogon
7cf0a64ab60029c993b412bd64da6084e6e4da93
[ "MIT" ]
1,315
2021-07-17T13:26:10.000Z
2022-03-31T17:53:49.000Z
lib/inc/drogon/utils/Utilities.h
rizalgowandy/drogon
7cf0a64ab60029c993b412bd64da6084e6e4da93
[ "MIT" ]
200
2021-07-17T09:26:27.000Z
2022-03-31T20:28:47.000Z
lib/inc/drogon/utils/Utilities.h
rizalgowandy/drogon
7cf0a64ab60029c993b412bd64da6084e6e4da93
[ "MIT" ]
188
2021-07-22T04:22:53.000Z
2022-03-29T03:07:10.000Z
/** * * @file Utilities.h * @author An Tao * * Copyright 2018, An Tao. All rights reserved. * https://github.com/an-tao/drogon * Use of this source code is governed by a MIT license * that can be found in the License file. * * Drogon * */ #pragma once #include <drogon/exports.h> #include <trantor/utils/Date.h> #include <trantor/utils/Funcs.h> #include <trantor/utils/Utilities.h> #include <drogon/utils/string_view.h> #include <memory> #include <string> #include <vector> #include <set> #include <limits> #include <sstream> #include <algorithm> #ifdef _WIN32 #include <time.h> DROGON_EXPORT char *strptime(const char *s, const char *f, struct tm *tm); DROGON_EXPORT time_t timegm(struct tm *tm); #endif namespace drogon { namespace internal { template <typename T> struct CanConvertFromStringStream { private: using yes = std::true_type; using no = std::false_type; template <typename U> static auto test(U *p, std::stringstream &&ss) -> decltype((ss >> *p), yes()); template <typename> static no test(...); public: static constexpr bool value = std::is_same<decltype(test<T>(nullptr, std::stringstream())), yes>::value; }; } // namespace internal namespace utils { /// Determine if the string is an integer DROGON_EXPORT bool isInteger(const std::string &str); /// Generate random a string /** * @param length The string length * The returned string consists of uppercase and lowercase letters and numbers */ DROGON_EXPORT std::string genRandomString(int length); /// Convert a binary string to hex format DROGON_EXPORT std::string binaryStringToHex(const unsigned char *ptr, size_t length); /// Get a binary string from hexadecimal format DROGON_EXPORT std::string hexToBinaryString(const char *ptr, size_t length); /// Get a binary vector from hexadecimal format DROGON_EXPORT std::vector<char> hexToBinaryVector(const char *ptr, size_t length); /// Split the string into multiple separated strings. /** * @param acceptEmptyString if true, empty strings are accepted in the * result, for example, splitting the ",1,2,,3," by "," produces * ["","1","2","","3",""] */ inline std::vector<std::string> splitString(const std::string &str, const std::string &separator, bool acceptEmptyString = false) { return trantor::splitString(str, separator, acceptEmptyString); } DROGON_EXPORT std::set<std::string> splitStringToSet( const std::string &str, const std::string &separator); /// Get UUID string. DROGON_EXPORT std::string getUuid(); /// Encode the string to base64 format. DROGON_EXPORT std::string base64Encode(const unsigned char *bytes_to_encode, unsigned int in_len, bool url_safe = false); /// Decode the base64 format string. DROGON_EXPORT std::string base64Decode(const std::string &encoded_string); DROGON_EXPORT std::vector<char> base64DecodeToVector( const std::string &encoded_string); /// Check if the string need decoding DROGON_EXPORT bool needUrlDecoding(const char *begin, const char *end); /// Decode from or encode to the URL format string DROGON_EXPORT std::string urlDecode(const char *begin, const char *end); inline std::string urlDecode(const std::string &szToDecode) { auto begin = szToDecode.data(); return urlDecode(begin, begin + szToDecode.length()); } inline std::string urlDecode(const string_view &szToDecode) { auto begin = szToDecode.data(); return urlDecode(begin, begin + szToDecode.length()); } DROGON_EXPORT std::string urlEncode(const std::string &); DROGON_EXPORT std::string urlEncodeComponent(const std::string &); /// Get the MD5 digest of a string. DROGON_EXPORT std::string getMd5(const char *data, const size_t dataLen); inline std::string getMd5(const std::string &originalString) { return getMd5(originalString.data(), originalString.length()); } /// Commpress or decompress data using gzip lib. /** * @param data the input data * @param ndata the input data length */ DROGON_EXPORT std::string gzipCompress(const char *data, const size_t ndata); DROGON_EXPORT std::string gzipDecompress(const char *data, const size_t ndata); /// Commpress or decompress data using brotli lib. /** * @param data the input data * @param ndata the input data length */ DROGON_EXPORT std::string brotliCompress(const char *data, const size_t ndata); DROGON_EXPORT std::string brotliDecompress(const char *data, const size_t ndata); /// Get the http full date string /** * rfc2616-3.3.1 * Full Date format(RFC 822) * like this: * @code Sun, 06 Nov 1994 08:49:37 GMT Wed, 12 Sep 2018 09:22:40 GMT @endcode */ DROGON_EXPORT char *getHttpFullDate( const trantor::Date &date = trantor::Date::now()); /// Get the trantor::Date object according to the http full date string /** * Returns trantor::Date(std::numeric_limits<int64_t>::max()) upon failure. */ DROGON_EXPORT trantor::Date getHttpDate(const std::string &httpFullDateString); /// Get a formatted string DROGON_EXPORT std::string formattedString(const char *format, ...); /// Recursively create a file system path /** * Return 0 or -1 on success or failure. */ DROGON_EXPORT int createPath(const std::string &path); /** * @details Convert a wide string path with arbitrary directory separators * to a UTF-8 portable path for use with trantor. * * This is a helper, mainly for Windows and multi-platform projects. * * @note On Windows, backslash directory separators are converted to slash to * keep portable paths. * * @remarks On other OSes, backslashes are not converted to slash, since they * are valid characters for directory/file names. * * @param strPath Wide string path. * * @return std::string UTF-8 path, with slash directory separator. */ inline std::string fromWidePath(const std::wstring &strPath) { return trantor::utils::fromWidePath(strPath); } /** * @details Convert a UTF-8 path with arbitrary directory separator to a wide * string path. * * This is a helper, mainly for Windows and multi-platform projects. * * @note On Windows, slash directory separators are converted to backslash. * Although it accepts both slash and backslash as directory separator in its * API, it is better to stick to its standard. * @remarks On other OSes, slashes are not converted to backslashes, since they * are not interpreted as directory separators and are valid characters for * directory/file names. * * @param strUtf8Path Ascii path considered as being UTF-8. * * @return std::wstring path with, on windows, standard backslash directory * separator to stick to its standard. */ inline std::wstring toWidePath(const std::string &strUtf8Path) { return trantor::utils::toWidePath(strUtf8Path); } /** * @brief Convert a generic (UTF-8) path with to an OS native path. * @details This is a helper, mainly for Windows and multi-platform projects. * * On Windows, slash directory separators are converted to backslash, and a * wide string is returned. * * On other OSes, returns an UTF-8 string _without_ altering the directory * separators. * * @param strPath Wide string or UTF-8 path. * * @return An OS path, suitable for use with the OS API. */ #if defined(_WIN32) && !defined(__MINGW32__) inline std::wstring toNativePath(const std::string &strPath) { return trantor::utils::toNativePath(strPath); } inline const std::wstring &toNativePath(const std::wstring &strPath) { return trantor::utils::toNativePath(strPath); } #else // __WIN32 inline const std::string &toNativePath(const std::string &strPath) { return trantor::utils::toNativePath(strPath); } inline std::string toNativePath(const std::wstring &strPath) { return trantor::utils::toNativePath(strPath); } #endif // _WIN32 /** * @brief Convert a OS native path (wide string on Windows) to a generic UTF-8 * path. * @details This is a helper, mainly for Windows and multi-platform projects. * * On Windows, backslash directory separators are converted to slash, and a * a UTF-8 string is returned, suitable for libraries that supports UTF-8 paths * like OpenSSL or drogon. * * On other OSes, returns an UTF-8 string without altering the directory * separators (backslashes are *NOT* replaced with slashes, since they * are valid characters for directory/file names). * * @param strPath Wide string or UTF-8 path. * * @return A generic path. */ inline const std::string &fromNativePath(const std::string &strPath) { return trantor::utils::fromNativePath(strPath); } // Convert on all systems inline std::string fromNativePath(const std::wstring &strPath) { return trantor::utils::fromNativePath(strPath); } /// Replace all occurances of from to to inplace /** * @param from string to replace * @param to string to replace with */ DROGON_EXPORT void replaceAll(std::string &s, const std::string &from, const std::string &to); /** * @brief Generates cryptographically secure random bytes. * * @param ptr the pointer which the random bytes are stored to * @param size number of bytes to generate * * @return true if generation is successfull. False otherwise * * @note DO NOT abuse this function. Especially if Drogon is built without * OpenSSL. Entropy running low is a real issue. */ DROGON_EXPORT bool secureRandomBytes(void *ptr, size_t size); template <typename T> typename std::enable_if<internal::CanConvertFromStringStream<T>::value, T>::type fromString(const std::string &p) noexcept(false) { T value{}; if (!p.empty()) { std::stringstream ss(p); ss >> value; } return value; } template <typename T> typename std::enable_if<!(internal::CanConvertFromStringStream<T>::value), T>::type fromString(const std::string &) noexcept(false) { throw std::runtime_error("Bad type conversion"); } template <> inline std::string fromString<std::string>(const std::string &p) noexcept(false) { return p; } template <> inline int fromString<int>(const std::string &p) noexcept(false) { return std::stoi(p); } template <> inline long fromString<long>(const std::string &p) noexcept(false) { return std::stol(p); } template <> inline long long fromString<long long>(const std::string &p) noexcept(false) { return std::stoll(p); } template <> inline unsigned long fromString<unsigned long>(const std::string &p) noexcept( false) { return std::stoul(p); } template <> inline unsigned long long fromString<unsigned long long>( const std::string &p) noexcept(false) { return std::stoull(p); } template <> inline float fromString<float>(const std::string &p) noexcept(false) { return std::stof(p); } template <> inline double fromString<double>(const std::string &p) noexcept(false) { return std::stod(p); } template <> inline long double fromString<long double>(const std::string &p) noexcept(false) { return std::stold(p); } template <> inline bool fromString<bool>(const std::string &p) noexcept(false) { if (p == "1") { return true; } if (p == "0") { return false; } std::string l{p}; std::transform(p.begin(), p.end(), l.begin(), [](unsigned char ch) { return static_cast<unsigned char>(tolower(ch)); }); if (l == "true") { return true; } else if (l == "false") { return false; } throw std::runtime_error("Can't convert from string '" + p + "' to bool"); } } // namespace utils } // namespace drogon
28.624697
80
0.688378
[ "object", "vector", "transform" ]
83bad931b7135d3e41e7f91f587b35f9d5d554b6
22,395
h
C
include/tscore/IntrusiveHashMap.h
cmcfarlen/trafficserver
2aa1d3106398eb082e5a454212b0273c63d5f69d
[ "Apache-2.0" ]
1,351
2015-01-03T08:25:40.000Z
2022-03-31T09:14:08.000Z
include/tscore/IntrusiveHashMap.h
cmcfarlen/trafficserver
2aa1d3106398eb082e5a454212b0273c63d5f69d
[ "Apache-2.0" ]
7,009
2015-01-14T16:22:45.000Z
2022-03-31T17:18:04.000Z
include/tscore/IntrusiveHashMap.h
cmcfarlen/trafficserver
2aa1d3106398eb082e5a454212b0273c63d5f69d
[ "Apache-2.0" ]
901
2015-01-11T19:21:08.000Z
2022-03-18T18:21:33.000Z
/** @file Instrusive hash map. @section license License 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. */ #pragma once #include <vector> #include <array> #include <algorithm> #include "tscpp/util/IntrusiveDList.h" /** Intrusive Hash Table. Values stored in this container are not destroyed when the container is destroyed or removed from the container. They must be released by the client. Duplicate keys are allowed. Clients must walk the list for multiple entries. @see @c Location::operator++() By default the table automatically expands to limit the average chain length. This can be tuned. If set to @c MANUAL then the table will expand @b only when explicitly requested to do so by the client. @see @c ExpansionPolicy @see @c setExpansionPolicy() @see @c setExpansionLimit() @see @c expand() The hash table is configured by a descriptor class. This must contain the following members - The static method <tt>key_type key_of(value_type *)</tt> which returns the key for an instance of @c value_type. - The static method <tt>bool equal(key_type lhs, key_type rhs)</tt> which checks if two instances of @c Key are the same. - The static method <tt>hash_id hash_of(key_type)</tt> which computes the hash value of the key. @c ID must a numeric type. - The static method <tt>value_type *& next_ptr(value_type *)</tt> which returns a reference to a forward pointer. - The static method <tt>value_type *& prev_ptr(value_type *)</tt> which returns a reference to a backwards pointer. These are the required members, it is permitted to have other methods (if the descriptor is used for other purposes) or to provide overloads of the methods. Note this is compatible with @c IntrusiveDList. Several internal types are deduced from these arguments. @a Key is the return type of @a key_of and represents the key that distinguishes instances of @a value_type. Two instances of @c value_type are considered the same if their respective @c Key values are @c equal. @c Key is presumed cheap to copy. If the underlying key is not a simple type then @a Key should be a constant pointer or a constant reference. The hash table will never attempt to modify a key. @a ID The numeric type that is the hash value for an instance of @a Key. Example for @c Http1ServerSession keyed by the origin server IP address. @code struct Descriptor { static sockaddr const* key_of(Http1ServerSession const* value) { return &value->ip.sa } static bool equal(sockaddr const* lhs, sockaddr const* rhs) { return ats_ip_eq(lhs, rhs); } static uint32_t hash_of(sockaddr const* key) { return ats_ip_hash(key); } static Http1ServerSession *& next_ptr(Http1ServerSession * ssn) { return ssn->_next; } static Http1ServerSession *& prev_ptr(Http1ServerSession * ssn) { return ssn->_prev; } }; using Table = IntrusiveHashMap<Descriptor>; @endcode */ template <typename H> class IntrusiveHashMap { using self_type = IntrusiveHashMap; public: /// Type of elements in the map. using value_type = typename std::remove_pointer<typename std::remove_reference<decltype(H::next_ptr(nullptr))>::type>::type; /// Key type for the elements. using key_type = decltype(H::key_of(static_cast<value_type *>(nullptr))); /// The numeric hash ID computed from a key. using hash_id = decltype(H::hash_of(H::key_of(static_cast<value_type *>(nullptr)))); /// When the hash table is expanded. enum ExpansionPolicy { MANUAL, ///< Client must explicitly expand the table. AVERAGE, ///< Table expands if average chain length exceeds limit. [default] MAXIMUM ///< Table expands if any chain length exceeds limit. }; protected: /** List of elements. * All table elements are in this list. The buckets reference their starting element in the list, or nothing if * no elements are in that bucket. */ using List = ts::IntrusiveDList<H>; /// A bucket for the hash map. struct Bucket { /// Support for ts::IntrusiveDList<Bucket::Linkage>, definitions and link storage. struct Linkage { static Bucket *&next_ptr(Bucket *b); ///< Access next pointer. static Bucket *&prev_ptr(Bucket *b); ///< Access prev pointer. Bucket *_prev{nullptr}; ///< Prev pointer. Bucket *_next{nullptr}; ///< Next pointer. } _link; value_type *_v{nullptr}; ///< First element in the bucket. size_t _count{0}; ///< Number of elements in the bucket. /** Marker for the chain having different keys. This is used to determine if expanding the hash map would be useful - buckets that are not mixed will not be changed by an expansion. */ bool _mixed_p{false}; /// Compute the limit value for iteration in this bucket. /// This is the value of the next bucket, or @c nullptr if no next bucket. value_type *limit() const; /// Verify @a v is in this bucket. bool contains(value_type *v) const; void clear(); ///< Reset to initial state. }; public: /// The default starting number of buckets. static size_t constexpr DEFAULT_BUCKET_COUNT = 7; ///< POOMA. /// The default expansion policy limit. static size_t constexpr DEFAULT_EXPANSION_LIMIT = 4; ///< Value from previous version. /// Expansion policy if not specified in constructor. static ExpansionPolicy constexpr DEFAULT_EXPANSION_POLICY = AVERAGE; using iterator = typename List::iterator; using const_iterator = typename List::const_iterator; /// A range of elements in the map. /// It is a half open range, [first, last) in the usual STL style. /// @internal I tried @c std::pair as a base for this but was unable to get STL container operations to work. struct range : public std::pair<iterator, iterator> { using super_type = std::pair<iterator, iterator>; ///< Super type. using super_type::super_type; ///< Use super type constructors. // These methods enable treating the range as a view in to the hash map. /// Return @a first iterator const &begin() const; /// Return @a last iterator const &end() const; }; /// A range of constant elements in the map. struct const_range : public std::pair<const_iterator, const_iterator> { using super_type = std::pair<const_iterator, const_iterator>; ///< Super type. /// Allow implicit conversion of range to const_range. const_range(range const &r); using super_type::super_type; ///< Use super type constructors. // These methods enable treating the range as a view in to the hash map. /// Return @a first const_iterator const &begin() const; /// Return @a last const_iterator const &end() const; }; /// Construct, starting with @n buckets. /// This doubles as the default constructor. IntrusiveHashMap(size_t n = DEFAULT_BUCKET_COUNT); /** Remove all values from the table. The values are not cleaned up. The values are not touched in this method, therefore it is safe to destroy them first and then @c clear this table. */ self_type &clear(); iterator begin(); ///< First element. const_iterator begin() const; ///< First element. iterator end(); ///< Past last element. const_iterator end() const; ///< Past last element. /** Insert a value in to the table. The @a value must @b NOT already be in a table of this type. @note The value itself is put in the table, @b not a copy. */ void insert(value_type *v); /** Find an element with a key equal to @a key. @return A element with a matching key, or the end iterator if not found. */ const_iterator find(key_type key) const; iterator find(key_type key); /** Get an iterator for an existing value @a v. @return An iterator that references @a v, or the end iterator if @a v is not in the table. */ const_iterator find(value_type const *v) const; iterator find(value_type *v); /** Find the range of objects with keys equal to @a key. @return A iterator pair of [first, last) items with equal keys. */ const_range equal_range(key_type key) const; range equal_range(key_type key); /** Get an @c iterator for the value @a v. This is a bit obscure but needed in certain cases. Because the interface assumes iterators are always valid this avoid containment checks, which is useful if @a v is already known to be in the container. */ iterator iterator_for(value_type *v); const_iterator iterator_for(const value_type *v) const; /** Remove the value at @a loc from the table. @note This does @b not clean up the removed elements. Use carefully to avoid leaks. @return An iterator the next value past @a loc. [STL compatibility] */ iterator erase(iterator const &loc); /// Remove all elements in the @c range @a r. iterator erase(range const &r); /// Remove all elements in the range (start, limit] iterator erase(iterator const &start, iterator const &limit); /// Remove a @a value from the container. /// @a value is checked for being a member of the container. /// @return @c true if @a value was in the container and removed, @c false if it was not in the container. bool erase(value_type *value); /** Apply @a F(value_type&) to every element in the hash map. * * This is similar to a range for loop except the iteration is done in a way where destruction or alternation of * the element does @b not affect the iterator. Primarily this is useful for @c delete to clean up the elements * but it can have other uses. * * @tparam F A functional object of the form <tt>void F(value_type&)</tt> * @param f The function to apply. * @return */ template <typename F> self_type &apply(F &&f); /** Expand the hash if needed. Useful primarily when the expansion policy is set to @c MANUAL. */ void expand(); /// Number of elements in the map. size_t count() const; /// Number of buckets in the array. size_t bucket_count() const; /// Set the expansion policy to @a policy. self_type &set_expansion_policy(ExpansionPolicy policy); /// Get the current expansion policy ExpansionPolicy get_expansion_policy() const; /// Set the limit value for the expansion policy. self_type &set_expansion_limit(size_t n); /// Set the limit value for the expansion policy. size_t get_expansion_limit() const; protected: /// The type of storage for the buckets. using Table = std::vector<Bucket>; List _list; ///< Elements in the table. Table _table; ///< Array of buckets. /// List of non-empty buckets. ts::IntrusiveDList<typename Bucket::Linkage> _active_buckets; Bucket *bucket_for(key_type key); ExpansionPolicy _expansion_policy{DEFAULT_EXPANSION_POLICY}; ///< When to expand the table. size_t _expansion_limit{DEFAULT_EXPANSION_LIMIT}; ///< Limit value for expansion. // noncopyable IntrusiveHashMap(const IntrusiveHashMap &) = delete; IntrusiveHashMap &operator=(const IntrusiveHashMap &) = delete; // Hash table size prime list. static constexpr std::array<size_t, 29> PRIME = {{1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909}}; }; template <typename H> auto IntrusiveHashMap<H>::Bucket::Linkage::next_ptr(Bucket *b) -> Bucket *& { return b->_link._next; } template <typename H> auto IntrusiveHashMap<H>::Bucket::Linkage::prev_ptr(Bucket *b) -> Bucket *& { return b->_link._prev; } // This is designed so that if the bucket is empty, then @c nullptr is returned, which will immediately terminate // a search loop on an empty bucket because that will start with a nullptr candidate, matching the limit. template <typename H> auto IntrusiveHashMap<H>::Bucket::limit() const -> value_type * { Bucket *n{_link._next}; return n ? n->_v : nullptr; }; template <typename H> void IntrusiveHashMap<H>::Bucket::clear() { _v = nullptr; _count = 0; _mixed_p = false; // These can be left set during an expansion, when the bucket did have elements before but not // after. Therefore make sure they are cleared. _link._next = _link._prev = nullptr; } template <typename H> bool IntrusiveHashMap<H>::Bucket::contains(value_type *v) const { value_type *x = _v; value_type *limit = this->limit(); while (x != limit && x != v) { x = H::next_ptr(x); } return x == v; } // --------------------- template <typename H> auto IntrusiveHashMap<H>::range::begin() const -> iterator const & { return super_type::first; } template <typename H> auto IntrusiveHashMap<H>::range::end() const -> iterator const & { return super_type::second; } template <typename H> auto IntrusiveHashMap<H>::const_range::begin() const -> const_iterator const & { return super_type::first; } template <typename H> auto IntrusiveHashMap<H>::const_range::end() const -> const_iterator const & { return super_type::second; } // --------------------- template <typename H> IntrusiveHashMap<H>::IntrusiveHashMap(size_t n) { if (n) { _table.resize(*std::lower_bound(PRIME.begin(), PRIME.end(), n)); } } template <typename H> auto IntrusiveHashMap<H>::bucket_for(key_type key) -> Bucket * { return &_table[H::hash_of(key) % _table.size()]; } template <typename H> auto IntrusiveHashMap<H>::begin() -> iterator { return _list.begin(); } template <typename H> auto IntrusiveHashMap<H>::begin() const -> const_iterator { return _list.begin(); } template <typename H> auto IntrusiveHashMap<H>::end() -> iterator { return _list.end(); } template <typename H> auto IntrusiveHashMap<H>::end() const -> const_iterator { return _list.end(); } template <typename H> auto IntrusiveHashMap<H>::clear() -> self_type & { for (auto &b : _table) { b.clear(); } // Clear container data. _list.clear(); _active_buckets.clear(); return *this; } template <typename H> auto IntrusiveHashMap<H>::find(key_type key) -> iterator { Bucket *b = this->bucket_for(key); value_type *v = b->_v; value_type *limit = b->limit(); while (v != limit && !H::equal(key, H::key_of(v))) { v = H::next_ptr(v); } return v == limit ? _list.end() : _list.iterator_for(v); } template <typename H> auto IntrusiveHashMap<H>::find(key_type key) const -> const_iterator { return const_cast<self_type *>(this)->find(key); } template <typename H> auto IntrusiveHashMap<H>::equal_range(key_type key) -> range { iterator first{this->find(key)}; iterator last{first}; iterator limit{this->end()}; while (last != limit && H::equal(key, H::key_of(&*last))) { ++last; } return range{first, last}; } template <typename H> auto IntrusiveHashMap<H>::equal_range(key_type key) const -> const_range { return const_cast<self_type *>(this)->equal_range(key); } template <typename H> auto IntrusiveHashMap<H>::iterator_for(const value_type *v) const -> const_iterator { return _list.iterator_for(v); } template <typename H> auto IntrusiveHashMap<H>::iterator_for(value_type *v) -> iterator { return _list.iterator_for(v); } template <typename H> auto IntrusiveHashMap<H>::find(value_type *v) -> iterator { Bucket *b = this->bucket_for(H::key_of(v)); return b->contains(v) ? _list.iterator_for(v) : this->end(); } template <typename H> auto IntrusiveHashMap<H>::find(value_type const *v) const -> const_iterator { return const_cast<self_type *>(this)->find(const_cast<value_type *>(v)); } template <typename H> void IntrusiveHashMap<H>::insert(value_type *v) { auto key = H::key_of(v); Bucket *bucket = this->bucket_for(key); value_type *spot = bucket->_v; bool mixed_p = false; // Found a different key in the bucket. if (nullptr == spot) { // currently empty bucket, set it and add to active list. _list.append(v); bucket->_v = v; _active_buckets.append(bucket); } else { value_type *limit = bucket->limit(); // First search the bucket to see if the key is already in it. while (spot != limit && !H::equal(key, H::key_of(spot))) { spot = H::next_ptr(spot); } if (spot != bucket->_v) { mixed_p = true; // found some other key, it's going to be mixed. } _list.insert_before(spot, v); if (spot == bucket->_v) { // added before the bucket start, update the start. bucket->_v = v; } bucket->_mixed_p = mixed_p; } ++bucket->_count; // auto expand if appropriate. if ((AVERAGE == _expansion_policy && (_list.count() / _table.size()) > _expansion_limit) || (MAXIMUM == _expansion_policy && bucket->_count > _expansion_limit && bucket->_mixed_p)) { this->expand(); } } template <typename H> auto IntrusiveHashMap<H>::erase(iterator const &loc) -> iterator { value_type *v = loc; iterator zret = ++(this->iterator_for(v)); // get around no const_iterator -> iterator. Bucket *b = this->bucket_for(H::key_of(v)); value_type *nv = H::next_ptr(v); value_type *limit = b->limit(); if (b->_v == v) { // removed first element in bucket, update bucket if (limit == nv) { // that was also the only element, deactivate bucket _active_buckets.erase(b); b->clear(); } else { b->_v = nv; --b->_count; } } _list.erase(loc); return zret; } template <typename H> bool IntrusiveHashMap<H>::erase(value_type *v) { auto loc = this->iterator_for(v); if (loc != this->end()) { this->erase(loc); return true; } return false; } template <typename H> auto IntrusiveHashMap<H>::erase(iterator const &start, iterator const &limit) -> iterator { auto spot{start}; Bucket *bucket{this->bucket_for(spot)}; while (spot != limit) { auto target = bucket; bucket = bucket->_link._next; // bump now to avoid forward iteration problems in case of bucket removal. value_type *v_limit = bucket ? bucket->_v : nullptr; while (spot != v_limit && spot != limit) { --(target->_count); ++spot; } if (target->_count == 0) { _active_buckets.erase(target); } } _list.erase(start, limit); return _list.iterator_for(limit); // convert from const_iterator back to iterator }; template <typename H> auto IntrusiveHashMap<H>::erase(range const &r) -> iterator { return this->erase(r.first, r.second); } namespace detail { // Make @c apply more convenient by allowing the function to take a reference type or pointer type to the container // elements. The pointer type is the base, plus a shim to convert from a reference type functor to a pointer pointer // type. The complex return type definition forces only one, but not both, to be valid for a particular functor. This // also must be done via free functions and not method overloads because the compiler forces a match up of method // definitions and declarations before any template instantiation. template <typename H, typename F> auto IntrusiveHashMapApply(IntrusiveHashMap<H> &map, F &&f) -> decltype(f(*static_cast<typename IntrusiveHashMap<H>::value_type *>(nullptr)), map) { return map.apply([&f](typename IntrusiveHashMap<H>::value_type *v) { return f(*v); }); } template <typename H, typename F> auto IntrusiveHashMapApply(IntrusiveHashMap<H> &map, F &&f) -> decltype(f(static_cast<typename IntrusiveHashMap<H>::value_type *>(nullptr)), map) { auto spot{map.begin()}; auto limit{map.end()}; while (spot != limit) { f(spot++); // post increment means @a spot is updated before @a f is applied. } return map; } } // namespace detail template <typename H> template <typename F> auto IntrusiveHashMap<H>::apply(F &&f) -> self_type & { return detail::IntrusiveHashMapApply(*this, f); }; template <typename H> void IntrusiveHashMap<H>::expand() { ExpansionPolicy org_expansion_policy = _expansion_policy; // save for restore. value_type *old = _list.head(); // save for repopulating. auto old_size = _table.size(); // Reset to empty state. this->clear(); _table.resize(*std::lower_bound(PRIME.begin(), PRIME.end(), old_size + 1)); _expansion_policy = MANUAL; // disable any auto expand while we're expanding. while (old) { value_type *v = old; old = H::next_ptr(old); this->insert(v); } // stashed array gets cleaned up when @a tmp goes out of scope. _expansion_policy = org_expansion_policy; // reset to original value. } template <typename H> size_t IntrusiveHashMap<H>::count() const { return _list.count(); } template <typename H> size_t IntrusiveHashMap<H>::bucket_count() const { return _table.size(); } template <typename H> auto IntrusiveHashMap<H>::set_expansion_policy(ExpansionPolicy policy) -> self_type & { _expansion_policy = policy; return *this; } template <typename H> auto IntrusiveHashMap<H>::get_expansion_policy() const -> ExpansionPolicy { return _expansion_policy; } template <typename H> auto IntrusiveHashMap<H>::set_expansion_limit(size_t n) -> self_type & { _expansion_limit = n; return *this; } template <typename H> size_t IntrusiveHashMap<H>::get_expansion_limit() const { return _expansion_limit; } /* ---------------------------------------------------------------------------------------------- */
30.93232
131
0.678187
[ "object", "vector" ]
39e898af29c326d3cb3069b7a97d70716d6ff039
4,876
c
C
src/html/html_title_element.c
zhuyadong/libdom
0772e819f42f51a3ae8b4b778a24efd43a083945
[ "MIT" ]
null
null
null
src/html/html_title_element.c
zhuyadong/libdom
0772e819f42f51a3ae8b4b778a24efd43a083945
[ "MIT" ]
null
null
null
src/html/html_title_element.c
zhuyadong/libdom
0772e819f42f51a3ae8b4b778a24efd43a083945
[ "MIT" ]
1
2019-01-25T15:12:55.000Z
2019-01-25T15:12:55.000Z
/* * This file is part of libdom. * Licensed under the MIT License, * http://www.opensource.org/licenses/mit-license.php * Copyright 2009 Bo Yang <struggleyb.nku.com> */ #include <assert.h> #include <stdlib.h> #include <dom/core/characterdata.h> #include <dom/core/text.h> #include "html/html_document.h" #include "html/html_title_element.h" #include "core/node.h" #include "utils/utils.h" static struct dom_element_protected_vtable _protect_vtable = { { DOM_NODE_PROTECT_VTABLE_HTML_TITLE_ELEMENT }, DOM_HTML_TITLE_ELEMENT_PROTECT_VTABLE }; /** * Create a dom_html_title_element object * * \param params The html element creation parameters * \param ele The returned element object * \return DOM_NO_ERR on success, appropriate dom_exception on failure. */ dom_exception _dom_html_title_element_create( struct dom_html_element_create_params *params, struct dom_html_title_element **ele) { struct dom_node_internal *node; *ele = malloc(sizeof(dom_html_title_element)); if (*ele == NULL) return DOM_NO_MEM_ERR; /* Set up vtables */ node = (struct dom_node_internal *) *ele; node->base.vtable = &_dom_html_element_vtable; node->vtable = &_protect_vtable; return _dom_html_title_element_initialise(params, *ele); } /** * Initialise a dom_html_title_element object * * \param params The html element creation parameters * \param ele The dom_html_title_element object * \return DOM_NO_ERR on success, appropriate dom_exception on failure. */ dom_exception _dom_html_title_element_initialise( struct dom_html_element_create_params *params, struct dom_html_title_element *ele) { return _dom_html_element_initialise(params, &ele->base); } /** * Finalise a dom_html_title_element object * * \param ele The dom_html_title_element object */ void _dom_html_title_element_finalise(struct dom_html_title_element *ele) { _dom_html_element_finalise(&ele->base); } /** * Destroy a dom_html_title_element object * * \param ele The dom_html_title_element object */ void _dom_html_title_element_destroy(struct dom_html_title_element *ele) { _dom_html_title_element_finalise(ele); free(ele); } /*------------------------------------------------------------------------*/ /* The protected virtual functions */ /* The virtual function used to parse attribute value, see src/core/element.c * for detail */ dom_exception _dom_html_title_element_parse_attribute(dom_element *ele, dom_string *name, dom_string *value, dom_string **parsed) { UNUSED(ele); UNUSED(name); dom_string_ref(value); *parsed = value; return DOM_NO_ERR; } /* The virtual destroy function, see src/core/node.c for detail */ void _dom_virtual_html_title_element_destroy(dom_node_internal *node) { _dom_html_title_element_destroy((struct dom_html_title_element *) node); } /* The virtual copy function, see src/core/node.c for detail */ dom_exception _dom_html_title_element_copy( dom_node_internal *old, dom_node_internal **copy) { dom_html_title_element *new_node; dom_exception err; new_node = malloc(sizeof(dom_html_title_element)); if (new_node == NULL) return DOM_NO_MEM_ERR; err = dom_html_title_element_copy_internal(old, new_node); if (err != DOM_NO_ERR) { free(new_node); return err; } *copy = (dom_node_internal *) new_node; return DOM_NO_ERR; } dom_exception _dom_html_title_element_copy_internal( dom_html_title_element *old, dom_html_title_element *new) { dom_exception err; err = dom_html_element_copy_internal(old, new); if (err != DOM_NO_ERR) { return err; } return DOM_NO_ERR; } /*-----------------------------------------------------------------------*/ /* Public APIs */ /** * Get the text of title * * \param ele The title element * \param text The returned text * \return DOM_NO_ERR on success, appropriated dom_exception on failure. */ dom_exception dom_html_title_element_get_text(dom_html_title_element *ele, dom_string **text) { dom_node_internal *node = (dom_node_internal *) ele; dom_node_internal *n = node->first_child; /* There should be only one child of title element */ assert(node->first_child == node->last_child); /* And it should be a text node */ assert(n->type == DOM_TEXT_NODE); return dom_characterdata_get_data(n, text); } /** * Set the text of title * * \param ele The title element * \param text The text data to be set * \return DOM_NO_ERR on success, appropriated dom_exception on failure. */ dom_exception dom_html_title_element_set_text(dom_html_title_element *ele, dom_string *text) { dom_node_internal *node = (dom_node_internal *) ele; dom_node_internal *n = node->first_child; /* There should be only one child of title element */ assert(node->first_child == node->last_child); /* And it should be a text node */ assert(n->type == DOM_TEXT_NODE); return dom_characterdata_set_data(n, text); }
25.395833
77
0.732363
[ "object" ]
39f07a7cbf85d9f02c4cf6d7d19fea765bfb658f
4,692
h
C
Apptentive/Apptentive/Engagement/Model/ApptentiveAppRelease.h
Dedgmz/apptentive-ios
601a909c44638a7eed45c8f8deefc3b60d1a9a42
[ "BSD-3-Clause" ]
null
null
null
Apptentive/Apptentive/Engagement/Model/ApptentiveAppRelease.h
Dedgmz/apptentive-ios
601a909c44638a7eed45c8f8deefc3b60d1a9a42
[ "BSD-3-Clause" ]
null
null
null
Apptentive/Apptentive/Engagement/Model/ApptentiveAppRelease.h
Dedgmz/apptentive-ios
601a909c44638a7eed45c8f8deefc3b60d1a9a42
[ "BSD-3-Clause" ]
null
null
null
// // ApptentiveAppRelease.h // Apptentive // // Created by Frank Schmitt on 11/15/16. // Copyright © 2016 Apptentive, Inc. All rights reserved. // #import "ApptentiveState.h" NS_ASSUME_NONNULL_BEGIN @class ApptentiveVersion; /** An `ApptentiveAppRelease` represents a release of an application that has integrated the Apptentive SDK. */ @interface ApptentiveAppRelease : ApptentiveState /** Indicates the type of app release. Will always be "ios". */ @property (readonly, strong, nonatomic) NSString *type; /** The bundle identifier of the app, e.g. com.example.MyApp */ @property (readonly, strong, nonatomic) NSString *bundleIdentifier; /** The version object corresponding to the value of the `CFBundleShortVersionString` key in the application's `Info.plist` file. */ @property (readonly, strong, nonatomic) ApptentiveVersion *version; /** The version object corresponding to the value of the `CFBundleVersion` key in the application's `Info.plist` file. */ @property (readonly, strong, nonatomic) ApptentiveVersion *build; /** Indicates whether the file specified by the application's `appStoreRecieptURL` contains data. */ @property (readonly, assign, nonatomic) BOOL hasAppStoreReceipt; /** Indicates whether the APPTENTIVE_DEBUG preprocessor directive is defined. */ @property (readonly, assign, nonatomic, getter=isDebugBuild) BOOL debugBuild; /** Indicates whether the developer has accessed the style sheet object. */ @property (readonly, assign, nonatomic, getter=isOverridingStyles) BOOL overridingStyles; /** Indicates whether the version has changed since the first release that included the Apptentive SDK. */ @property (readonly, assign, nonatomic, getter=isUpdateVersion) BOOL updateVersion; /** Indicates whether the build has changed since the first release that included the Apptentive SDK. */ @property (readonly, assign, nonatomic, getter=isUpdateBuild) BOOL updateBuild; /** Records the time at which the SDK was first installed as part of the app. */ @property (readonly, strong, nonatomic) NSDate *timeAtInstallTotal; /** Records the time at which the version changed to the current version. */ @property (readonly, strong, nonatomic) NSDate *timeAtInstallVersion; /** Records the time at which the build changed to the current build. */ @property (readonly, strong, nonatomic) NSDate *timeAtInstallBuild; /** The compiler used to compile the app. */ @property (readonly, strong, nonatomic) NSString *compiler; /** The build number of the platform for which the app was built. */ @property (readonly, strong, nonatomic) NSString *platformBuild; /** The name of the platform for which the app was built. */ @property (readonly, strong, nonatomic) NSString *platformName; /** The version of the platform for which the app was built. */ @property (readonly, strong, nonatomic) NSString *platformVersion; /** The (iOS) SDK build against which the app was linked. */ @property (readonly, strong, nonatomic) NSString *SDKBuild; /** The (iOS) SDK name against which the app was linked. */ @property (readonly, strong, nonatomic) NSString *SDKName; /** The Xcode version with which the app was built. */ @property (readonly, strong, nonatomic) NSString *Xcode; /** The Xcode build with which the app was built. */ @property (readonly, strong, nonatomic) NSString *XcodeBuild; /** Initializes an `ApptentiveAppRelease` object by inspecting the running app, primarily values in the app's `Info.plist` file. @return The new initialized app release object. */ - (instancetype)initWithCurrentAppRelease; #pragma mark - Mutation /** Records that the build of the current app release changed from the previous value. This will update the `timeAtInstallBuild` value and may update the `isUpdateBuild` value. */ - (void)resetBuild; /** Records that the version of the current app release changed from the previous value. This will update the `timeAtInstallVersion` value and may update the `isUpdateVersion` value. */ - (void)resetVersion; /** Records that the app developer has accessed the style sheet object. */ - (void)setOverridingStyles; /** Copies values from another app release object that can't be observed from the current state of the app. @param otherAppRelease The app release object to copy values from */ - (void)copyNonholonomicValuesFrom:(ApptentiveAppRelease *)otherAppRelease; /** Due to a bug some app release objects might be missing their timeAtInstall values. @param timeAtInstall The install time to fall back to if values are missing. */ - (void)updateMissingTimeAtInstallTo:(NSDate *)timeAtInstall; @end NS_ASSUME_NONNULL_END
24.4375
104
0.752344
[ "object" ]
39f81c0d939952e3f19ffd7c06595d4aabf097a5
3,826
c
C
d/islands/serakii/obj/legion_cassock.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
null
null
null
d/islands/serakii/obj/legion_cassock.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
null
null
null
d/islands/serakii/obj/legion_cassock.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
null
null
null
//legion cassocks - LoKi - 2021 #include <std.h> inherit "/std/armour"; string thread; void create() { ::create(); switch (random(3)){ case 0: //officer set_name("Pearl Legion officer cassock"); set_id(({"cassock", "white woven cassock", "officer cassock","Pearl Legion Officer cassock"})); set_short("%^C231%^Pea%^C228%^r%^C231%^l "+ "L%^C228%^e%^C231%^gion officer casso%^C229%^c%^C231%^k%^CRST%^"); set_obvious_short("%^C231%^e%^C228%^m%^C231%^"+ "br%^C249%^o%^C231%^id%^C228%^e%^C250%^r%^C231%^ed "+ "wh%^C228%^i%^C231%^te c%^C249%^a%^C231%^ss%^C228%^o%^C250%^c%^C231%^k%^CRST%^"); thread = "%^C229%^gold%^CRST%^"; set_item_bonus("influence", 10); break; case 1: // academician set_name("Pearl Legion academician cassock"); set_id(({"cassock", "white woven cassock", "academician cassock","Pearl Legion Academician cassock"})); set_short("%^C231%^Pea%^C111%^r%^C231%^l "+ "L%^C111%^e%^C231%^gion academician casso%^C111%^"+ "c%^C231%^k%^CRST%^"); set_obvious_short("%^C231%^e%^C111%^m%^C231%^b"+ "r%^C249%^o%^C231%^id%^C111%^e%^C250%^r%^C231%^ed "+ "wh%^C111%^i%^C231%^te c%^C249%^a%^C231%^ss%^C111%^"+ "o%^C250%^c%^C231%^k%^CRST%^"); thread = "%^C062%^blue%^CRST%^"; set_item_bonus("academics", 10); break; case 2: //inquisitor set_name("Pearl Legion inquisitor cassock"); set_id(({"cassock", "white woven cassock", "inquisitor cassock","Pearl Legion Magus cassock"})); set_short("%^C231%^Pea%^C246%^r%^C231%^l L%^C247%^"+ "e%^C231%^gion inquisitor casso%^C247%^c%^C231%^"+ "k%^CRST%^"); set_obvious_short("%^C231%^e%^C250%^m%^C231%^b"+ "r%^C249%^o%^C231%^ide%^C250%^r%^C231%^ed white "+ "c%^C249%^a%^C231%^sso%^C250%^c%^C231%^k%^CRST%^"); thread = "%^C252%^silver%^CRST%^"; set_item_bonus("perception", 10); break; } set_long("%^C248%^This long %^C251%^cassock %^C248%^has been expertly "+ "stitched from %^C255%^fine white cotton%^C248%^ and is quite "+ "distinguished looking. Each panel of it though has also been "+ "%^C247%^reinforced %^C248%^so this is obviously more than just "+ "a simple garment. It runs all the way to the ground, but high "+ "enough to not run along the %^C095%^ground %^C248%^and get dirty. "+ "The %^C231%^white cloth%^C248%^ has been stitched with a "+thread+"%^C251%^ "+ "that creates an %^C111%^intricate design%^C248%^ of flowing %^C111%^waves "+ "%^C248%^that peak on the back of the garment where a detailed "+thread+"%^C251%^ "+ "embroidering of a %^C231%^sphere %^C248%^with a %^C241%^shield %^C248%^behind it.%^CRST%^\n"); set_lore("%^C110%^Let it be known this day that two hundred "+ "companies have destroyed their ledgers and the Legion of "+ "Pearl is formed in the Conclave. Long live the people of "+ "Serakii and death to the Hounds!\n- %^C093%^Inquisitor Baltsar "+ "Albrecht%^CRST%^: From the "+ "Legion Reformation"); set_weight(4); set_value(5000); set_type("clothing"); set_limbs(({"torso"})); set_property("enchantment",5); set_wear((:this_object(), "extra_wear":)); set_remove((:TO,"removeme":)); set_struck((:TO,"struck":)); } int extra_wear(){ return 1; } int removeme() { return 1; } int strike_fnc(int damage, object what, object who){ if(random(1000) < 100){ tell_room(environment(query_worn()),"%^C124%^"+ ""+ETOQCN+" %^C124%^turns as "+who->QCN+" %^C124%^strikes "+ "them, softening the blow!",({ETO,who})); tell_object(ETO,"%^C124%^You turn as "+who->QCN+" %^C124%^strikes "+ "you, it hurts, but you're saved from the worst of it!"); tell_object(who,"%^C124%^"+ETOQCN+" %^C124%^turns as you hit them!"); return (damage/3); } }
37.145631
109
0.603241
[ "object" ]
39fdc06530f09b3eae5ac37b651b7b8e96e1bbf3
3,142
h
C
logging/include/anchor/logging/logging.h
rideskip/anchor
fbd52aa2b049ba210619ab9e714fa43ce43f2081
[ "MIT" ]
53
2020-02-05T19:44:58.000Z
2022-03-11T20:59:17.000Z
logging/include/anchor/logging/logging.h
rideskip/anchor
fbd52aa2b049ba210619ab9e714fa43ce43f2081
[ "MIT" ]
3
2020-03-29T17:16:55.000Z
2022-01-09T20:31:46.000Z
logging/include/anchor/logging/logging.h
rideskip/anchor
fbd52aa2b049ba210619ab9e714fa43ce43f2081
[ "MIT" ]
13
2020-03-02T08:55:14.000Z
2022-03-19T07:40:24.000Z
// We explicitly don't use include guards as this file should not be included recursively. #include <inttypes.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif #ifdef _MSC_VER #define _LOGGING_FORMAT_ATTR #define _LOGGING_USED_ATTR #else #define _LOGGING_FORMAT_ATTR __attribute__((format(printf, 5, 6))) #define _LOGGING_USED_ATTR __attribute__((used)) #endif // The maximum length of a log message (not including extra formatting) #ifndef LOGGING_MAX_MSG_LENGTH #define LOGGING_MAX_MSG_LENGTH 128 #endif // The application's build scripts can define FILENAME to the name of the file without the full path in order to save code space #ifndef FILENAME #define FILENAME __FILE__ #endif // NOTE: LOGGING_MODULE_NAME can be defined before including this header in order to specify the module which the file belongs to typedef enum { LOGGING_LEVEL_DEFAULT = 0, // Used to represent the default level specified to logging_init() LOGGING_LEVEL_DEBUG, LOGGING_LEVEL_INFO, LOGGING_LEVEL_WARN, LOGGING_LEVEL_ERROR, } logging_level_t; typedef struct { // Write function which gets passed a fully-formatted log line void(*write_function)(const char* str); // Write function which gets passed the level and module name split out in addition to the fully-formatted log line void(*raw_write_function)(logging_level_t level, const char* module_name, const char* str); // A lock function which is called to make the logging library thread-safe void(*lock_function)(bool acquire); // A function which is called to get the current system time in milliseconds uint32_t(*time_ms_function)(void); // The default logging level logging_level_t default_level; } logging_init_t; // Initialize the logging library bool logging_init(const logging_init_t* init); // Internal type used to represent a logger typedef struct { uint8_t _private[sizeof(logging_level_t)]; const char* const module_prefix; } logging_logger_t; // Change the logging threshold for the current module #define LOG_SET_LEVEL(LEVEL) logging_module_set_level_impl(&_logging_logger, LEVEL) // Macros for logging at each level #define LOG_DEBUG(...) _LOG_LEVEL_IMPL(LOGGING_LEVEL_DEBUG, __VA_ARGS__) #define LOG_INFO(...) _LOG_LEVEL_IMPL(LOGGING_LEVEL_INFO, __VA_ARGS__) #define LOG_WARN(...) _LOG_LEVEL_IMPL(LOGGING_LEVEL_WARN, __VA_ARGS__) #define LOG_ERROR(...) _LOG_LEVEL_IMPL(LOGGING_LEVEL_ERROR, __VA_ARGS__) // Internal implementation macros / functions which are called via the macros above #define _LOG_LEVEL_IMPL(LEVEL, ...) logging_log_impl(&_logging_logger, LEVEL, FILENAME, __LINE__, __VA_ARGS__) void logging_log_impl(logging_logger_t* logger, logging_level_t level, const char* file, int line, const char* fmt, ...) _LOGGING_FORMAT_ATTR; void logging_set_level_impl(logging_logger_t* logger, logging_level_t level); // Per-file context object which we should create static logging_logger_t _logging_logger _LOGGING_USED_ATTR = { ._private = {0}, #ifdef LOGGING_MODULE_NAME .module_prefix = LOGGING_MODULE_NAME ":", #else .module_prefix = 0, #endif }; #ifdef __cplusplus } #endif
36.114943
142
0.781349
[ "object" ]
26027f638625609e5a7ec61a9e03555281392c4f
4,244
c
C
generational/test.c
mousycoder/gc_impl
988713e0231156b906d6f30ebcc35742dc1425cc
[ "Apache-2.0" ]
40
2020-03-16T14:09:46.000Z
2022-03-31T03:03:52.000Z
generational/test.c
mousycoder/gc_impl
988713e0231156b906d6f30ebcc35742dc1425cc
[ "Apache-2.0" ]
null
null
null
generational/test.c
mousycoder/gc_impl
988713e0231156b906d6f30ebcc35742dc1425cc
[ "Apache-2.0" ]
10
2020-04-01T08:11:04.000Z
2022-03-10T12:02:09.000Z
// // Created by jiangxin on 2020/3/15. // #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include "./gc.h" #define MAX_ROOTS 100 typedef struct dept { class_descriptor *class;//对象对应的类型 byte forwarded;//已拷贝标识 byte marked;//reachable标识 byte remembered;//已经记录在rs中的标识 object *forwarding;//目标位置 int age;//对象年龄 int id; } dept; typedef struct emp { class_descriptor *class;//对象对应的类型 byte forwarded;//已拷贝标识 byte marked;//reachable标识 byte remembered;//已经记录在rs中的标识 object *forwarding;//目标位置 int age;//对象年龄 int id; dept *dept; } emp; class_descriptor emp_object_class = { "emp_object", sizeof(struct emp), 1, (int[]) { offsetof(struct emp, dept) } }; class_descriptor dept_object_class = { "dept_object", sizeof(struct dept), /* size of string obj, not string */ 0, /* fields */ NULL }; /** * 测试新生代GC */ void test_minor_gc(){ gc_init(2000);//分配后,实际可用1936 emp *_emp1 = (emp *) gc_alloc(&emp_object_class); gc_add_root(_emp1); dept *_dept1 = (dept *) gc_alloc(&dept_object_class); //增加此引用会导致survivor容量不足,复制失败 gc_update_ptr((object *)_emp1,(object**)&_emp1->dept,(object *)_dept1); for (int i = 0; i < 6; ++i) { emp *temp_emp = (emp *) gc_alloc(&emp_object_class); } printf("即将新生代GC\n"); emp *temp_emp = (emp *) gc_alloc(&emp_object_class); gc_get_state(); } /** * 测试晋升 */ void test_promotion(){ gc_init(2000);//分配后,实际可用1936 emp *_emp1 = (emp *) gc_alloc(&emp_object_class); gc_add_root(_emp1); //触发3次新生代GC,然后emp1会晋升至老年代 for (int i = 0; i < 31; ++i) { emp *temp_emp = (emp *) gc_alloc(&emp_object_class); } printf("emp1晋升\n"); emp *temp_emp = (emp *) gc_alloc(&emp_object_class); gc_get_state(); } /** * 测试晋升引发的老年代GC */ void test_promotion_old_gc(){ gc_init(2000);//分配后,实际可用1936 for (int j = 0; j < 12; j++) { emp *_emp1 = (emp *) gc_alloc(&emp_object_class); _emp1->id = 666; gc_add_root(_emp1); //分配新对象,触发新生代GC for (int i = 0; i < 31; i++) { emp *temp_emp = (emp *) gc_alloc(&emp_object_class); } } printf("老年代GC\n"); emp *_emp1 = (emp *) gc_alloc(&emp_object_class); gc_add_root(_emp1); swap((void **)&_roots[0], (void **)(&_roots[--_rp])); //分配新对象,触发新生代GC for (int i = 0; i < 32; i++) { emp *temp_emp = (emp *) gc_alloc(&emp_object_class); } gc_get_state(); printf("FULL GC...\n"); _rp = 1; gc(); gc_get_state(); } /** * 测试跨代引用的回收 */ void test_cross_gen_ref_gc(){ gc_init(2000);//分配后,实际可用1936 emp *_emp1 = (emp *) gc_alloc(&emp_object_class); gc_add_root(_emp1); //触发3次新生代GC,然后emp1会晋升至老年代 for (int i = 0; i < 31; ++i) { emp *temp_emp = (emp *) gc_alloc(&emp_object_class); } printf("emp1晋升\n"); emp *temp_emp = (emp *) gc_alloc(&emp_object_class); dept *dept1 = (dept *) gc_alloc(&dept_object_class); //因为_emp1发生了晋升,所以此处的_emp1是复制前的对象,是一个过期的状态 //使用复制后的新_emp1对象 gc_update_ptr(_roots[0],(object **)&((emp*)_roots[0])->dept,(object*)dept1); printf("FULL GC...\n"); gc(); gc_get_state(); } /** * 测试因晋升导致的跨代引用的回收 */ void test_promotion_cross_gen_ref_gc(){ gc_init(2000);//分配后,实际可用1936 emp *_emp1 = (emp *) gc_alloc(&emp_object_class); gc_add_root(_emp1); //触发3次新生代GC,然后emp1会晋升至老年代 for (int i = 0; i < 31; ++i) { emp *temp_emp = (emp *) gc_alloc(&emp_object_class); } //在_emp1晋升前,增加_emp1->dept的引用,创建跨代引用 dept *dept1 = (dept *) gc_alloc(&dept_object_class); //因为_emp1发生了晋升,所以此处的_emp1是复制前的对象,是一个过期的状态 //使用复制后的新_emp1对象 gc_update_ptr(_roots[0],(object **)&((emp*)_roots[0])->dept,(object*)dept1); printf("emp1晋升\n"); //此时新生代内存不足,发生GC,_emp1已经经历3次GC,会晋升到老年代,但由于_dept还处于新生代,所以会在_rs中记录这条跨代引用 emp *temp_emp = (emp *) gc_alloc(&emp_object_class); printf("FULL GC...\n"); gc(); gc_get_state(); } int main(int argc, char *argv[]) { test_minor_gc(); // test_promotion(); // test_promotion_old_gc(); // test_cross_gen_ref_gc(); // test_promotion_cross_gen_ref_gc(); }
20.702439
80
0.598963
[ "object" ]
2602d954783f2419fc32f46f6e2cc1ad531e8eef
486
h
C
atom/app/manifests.h
torycl/electron
5252c898b4d179715bacf525efbdcb3696ed520b
[ "MIT" ]
1
2019-06-22T03:01:41.000Z
2019-06-22T03:01:41.000Z
atom/app/manifests.h
torycl/electron
5252c898b4d179715bacf525efbdcb3696ed520b
[ "MIT" ]
1
2021-09-02T20:36:59.000Z
2021-09-02T20:36:59.000Z
atom/app/manifests.h
torycl/electron
5252c898b4d179715bacf525efbdcb3696ed520b
[ "MIT" ]
1
2021-02-10T13:36:10.000Z
2021-02-10T13:36:10.000Z
// Copyright (c) 2019 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ATOM_APP_MANIFESTS_H_ #define ATOM_APP_MANIFESTS_H_ #include <vector> #include "services/service_manager/public/cpp/manifest.h" const service_manager::Manifest& GetElectronContentBrowserOverlayManifest(); const std::vector<service_manager::Manifest>& GetElectronBuiltinServiceManifests(); #endif // ATOM_APP_MANIFESTS_H_
28.588235
77
0.77572
[ "vector" ]
2602f196e698bc4bac98de133fd7fb852d34d523
3,659
h
C
sdk/msgapi/message_api.h
chwash/wwiv
0d67acdede788f8a4fd2b442e92caeb411552359
[ "Apache-2.0" ]
null
null
null
sdk/msgapi/message_api.h
chwash/wwiv
0d67acdede788f8a4fd2b442e92caeb411552359
[ "Apache-2.0" ]
null
null
null
sdk/msgapi/message_api.h
chwash/wwiv
0d67acdede788f8a4fd2b442e92caeb411552359
[ "Apache-2.0" ]
null
null
null
/**************************************************************************/ /* */ /* WWIV Version 5.x */ /* Copyright (C)2015-2022, WWIV Software Services */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, */ /* software distributed under the License is distributed on an */ /* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */ /* either express or implied. See the License for the specific */ /* language governing permissions and limitations under the License. */ /**************************************************************************/ #ifndef INCLUDED_SDK_MSGAPI_MESSAGE_API_H #define INCLUDED_SDK_MSGAPI_MESSAGE_API_H #include "sdk/msgapi/message_area.h" #include "sdk/net/net.h" #include "sdk/subxtr.h" #include <stdexcept> #include <string> #include <vector> namespace wwiv::sdk::msgapi { class MessageArea; enum class OverflowStrategy { delete_one, delete_all, delete_none }; struct MessageApiOptions { OverflowStrategy overflow_strategy = wwiv::sdk::msgapi::OverflowStrategy::delete_one; }; class bad_message_area : public ::std::runtime_error { public: explicit bad_message_area(const ::std::string& sub_filename) : ::std::runtime_error(sub_filename) {} }; class MessageApi { public: virtual ~MessageApi() = default; MessageApi( const MessageApiOptions& options, std::string root_directory, std::string subs_directory, std::string messages_directory, std::vector<net::Network> net_networks); /** Checks to see if the files for a subboard exist. */ [[nodiscard]] virtual bool Exist(const wwiv::sdk::subboard_t& sub) const = 0; /** Opens a message area, throwing bad_message_area if it does not exist. */ [[nodiscard]] virtual bool Create(const wwiv::sdk::subboard_t& sub, int subnum) = 0; /** Opens a message area, throwing bad_message_area if it does not exist. */ [[nodiscard]] virtual MessageArea* Open(const wwiv::sdk::subboard_t& sub, int subnum) = 0; /** Creates or Opens a message area. throwing bad_message_area if it exists but can not be opened.*/ [[nodiscard]] virtual MessageArea* CreateOrOpen(const wwiv::sdk::subboard_t& sub, int subnum); /** Deletes the message area identified by filename: name */ [[nodiscard]] virtual bool Remove(const std::string& name) = 0; [[nodiscard]] const std::vector<net::Network>& network() const { return net_networks_; } [[nodiscard]] std::string root_directory() const { return root_directory_; } [[nodiscard]] MessageApiOptions options() const { return options_; } // TODO(rushfan): Here's where we add hooks to the lastread system // so that message api's created inside the bbs will share *qsc with // the legacy code until it's all removed. protected: const MessageApiOptions options_; std::string root_directory_; std::string subs_directory_; std::string messages_directory_; std::vector<net::Network> net_networks_; }; } // namespace #endif
43.047059
102
0.600437
[ "vector" ]
260fbc9265f33c7967ab996f9a9875f7e3cb4015
4,324
h
C
chrome/browser/ui/views/select_file_dialog_extension.h
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:51:34.000Z
2018-02-15T03:11:54.000Z
chrome/browser/ui/views/select_file_dialog_extension.h
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
chrome/browser/ui/views/select_file_dialog_extension.h
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_SELECT_FILE_DIALOG_EXTENSION_H_ #define CHROME_BROWSER_UI_VIEWS_SELECT_FILE_DIALOG_EXTENSION_H_ #include <vector> #include "base/compiler_specific.h" #include "base/memory/ref_counted.h" #include "chrome/browser/ui/views/extensions/extension_dialog_observer.h" #include "ui/gfx/native_widget_types.h" // gfx::NativeWindow #include "ui/shell_dialogs/select_file_dialog.h" class ExtensionDialog; class Profile; namespace content { class RenderViewHost; class WebContents; } namespace ui { struct SelectedFileInfo; class SelectFilePolicy; } // Shows a dialog box for selecting a file or a folder, using the // file manager extension implementation. class SelectFileDialogExtension : public ui::SelectFileDialog, public ExtensionDialogObserver { public: // Opaque ID type for identifying the tab spawned each dialog, unique for // every WebContents. typedef const void* RoutingID; static RoutingID GetRoutingIDFromWebContents( const content::WebContents* web_contents); static SelectFileDialogExtension* Create( ui::SelectFileDialog::Listener* listener, ui::SelectFilePolicy* policy); // BaseShellDialog implementation. virtual bool IsRunning(gfx::NativeWindow owner_window) const OVERRIDE; virtual void ListenerDestroyed() OVERRIDE; // ExtensionDialog::Observer implementation. virtual void ExtensionDialogClosing(ExtensionDialog* dialog) OVERRIDE; virtual void ExtensionTerminated(ExtensionDialog* dialog) OVERRIDE; // Routes callback to appropriate SelectFileDialog::Listener based on the // owning |web_contents|. static void OnFileSelected(RoutingID routing_id, const ui::SelectedFileInfo& file, int index); static void OnMultiFilesSelected( RoutingID routing_id, const std::vector<ui::SelectedFileInfo>& files); static void OnFileSelectionCanceled(RoutingID routing_id); // For testing, so we can inject JavaScript into the contained view. content::RenderViewHost* GetRenderViewHost(); protected: // SelectFileDialog implementation. virtual void SelectFileImpl( Type type, const string16& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params) OVERRIDE; private: friend class SelectFileDialogExtensionBrowserTest; friend class SelectFileDialogExtensionTest; // Object is ref-counted, use Create(). explicit SelectFileDialogExtension(SelectFileDialog::Listener* listener, ui::SelectFilePolicy* policy); virtual ~SelectFileDialogExtension(); // Invokes the appropriate file selection callback on our listener. void NotifyListener(); // Adds this to the list of pending dialogs, used for testing. void AddPending(RoutingID routing_id); // Check if the list of pending dialogs contains dialog for |routing_id|. static bool PendingExists(RoutingID routing_id); // Returns true if the dialog has multiple file type choices. virtual bool HasMultipleFileTypeChoicesImpl() OVERRIDE; bool has_multiple_file_type_choices_; // Host for the extension that implements this dialog. scoped_refptr<ExtensionDialog> extension_dialog_; // ID of the tab that spawned this dialog, used to route callbacks. RoutingID routing_id_; // Pointer to the profile the dialog is running in. Profile* profile_; // The window that created the dialog. gfx::NativeWindow owner_window_; // We defer the callback into SelectFileDialog::Listener until the window // closes, to match the semantics of file selection on Windows and Mac. // These are the data passed to the listener. enum SelectionType { CANCEL = 0, SINGLE_FILE, MULTIPLE_FILES }; SelectionType selection_type_; std::vector<ui::SelectedFileInfo> selection_files_; int selection_index_; void* params_; DISALLOW_COPY_AND_ASSIGN(SelectFileDialogExtension); }; #endif // CHROME_BROWSER_UI_VIEWS_SELECT_FILE_DIALOG_EXTENSION_H_
33.261538
75
0.757863
[ "object", "vector" ]
2614c8ed28b0e74f1c7822ed4d97a9760040fab2
1,370
h
C
Game Engine/GameEngine/src/scene/component/model_matrix.h
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
Game Engine/GameEngine/src/scene/component/model_matrix.h
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
4
2018-12-24T11:16:53.000Z
2018-12-24T11:20:29.000Z
Game Engine/GameEngine/src/scene/component/model_matrix.h
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
#pragma once #include <glm/glm.hpp> #include "../game_object.h" #include "../../utils/detail.h" #include <glm/gtx/transform.hpp> template <> class component<struct component_model_matrix, game_object_data> : public component_base { private: glm::mat4 trs; glm::mat4 translation; glm::mat4 rotation; glm::mat4 scale; public: component(void) = default; auto update(f32 td, vec_dd<game_object> & objects) -> void override { auto & obj = objects[entity_index]; translation = glm::translate(obj->position); float y_axis_rot = detail::fequ(obj->direction.x, 0.0f) ? 0.00001f : -atan(obj->direction.z / obj->direction.x); rotation = glm::rotate(y_axis_rot, glm::vec3(0, 1, 0)); // rotation = detail::identity_matrix; scale = glm::scale(obj->scale); trs = translation * rotation * scale; } auto get_trs(void) -> glm::mat4 & { return trs; } auto get_translation(void) -> glm::mat4 & { return translation; } auto get_rotation(void) -> glm::mat4 & { return rotation; } auto get_scale(void) -> glm::mat4 & { return scale; } }; struct model_matrix_apply_func : apply_func { auto apply(class scene & dest, nlohmann::json::iterator & it, game_object & obj) -> void override { if (it.value()) { component<struct component_model_matrix, game_object_data> matrix_component; obj.add_component(matrix_component); } } };
20.447761
114
0.686131
[ "transform" ]
261ab3381284321577cbac8a2f31ab1fc2472f58
417
h
C
src/bullet.h
potedo/SDL2-SimpleShooter
a1bc9ecba08c7c214c0299cdd128b16a59931dd7
[ "MIT" ]
1
2022-02-12T08:15:25.000Z
2022-02-12T08:15:25.000Z
src/bullet.h
potedo/SDL2-SimpleShooter
a1bc9ecba08c7c214c0299cdd128b16a59931dd7
[ "MIT" ]
null
null
null
src/bullet.h
potedo/SDL2-SimpleShooter
a1bc9ecba08c7c214c0299cdd128b16a59931dd7
[ "MIT" ]
null
null
null
#ifndef BULLET_H #define BULLET_H #include "SDL.h" #include "SDL_image.h" #include <string> #include "object.h" constexpr int BULLET_WIDTH = 20; constexpr int BULLET_HEIGHT = 16; constexpr int BULLET_SPEED = 50; constexpr int BULLET_MIN_INTERVAL = 1; const std::string BULLET_IMAGEPATH = "../img/bullet/bullet.png"; class Bullet : public Object { public: Bullet(int x, int y, int speed); }; #endif // BULLET_H
19.857143
64
0.733813
[ "object" ]
261cea2ef771fd16b22b8de99986e69f52f7653d
3,556
h
C
DataFormats/Luminosity/interface/LumiDetails.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DataFormats/Luminosity/interface/LumiDetails.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DataFormats/Luminosity/interface/LumiDetails.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef DataFormats_Luminosity_LumiDetails_h #define DataFormats_Luminosity_LumiDetails_h /** \class LumiDetails * * * LumiDetails holds Details information: the lumi value, the error on this value, * its quality, and 2 beam intensities for each bunch crossing (BX) in a given * luminosity section (LS) * * \author Valerie Halyo, David Dagenhart, created June 7, 2007> * ************************************************************/ #include <utility> #include <vector> #include <string> #include <iosfwd> class LumiDetails { public: // If in the future additional algorithm names are added, // it is important that they be added at the end of the list. // The LumiDetails::algoNames function in LumiDetails.cc also // would need to be updated to keep the list of names in sync. enum Algos { kOCC1, kOCC2, kET, kPLT, kMaxNumAlgos }; typedef unsigned int AlgoType; typedef std::pair<std::vector<float>::const_iterator, std::vector<float>::const_iterator> ValueRange; typedef std::pair<std::vector<float>::const_iterator, std::vector<float>::const_iterator> ErrorRange; typedef std::pair<std::vector<short>::const_iterator, std::vector<short>::const_iterator> QualityRange; LumiDetails(); explicit LumiDetails(std::string const& lumiVersion); ~LumiDetails(); void setLumiVersion(std::string const& lumiVersion); std::string const& lumiVersion() const; bool isValid() const; // This will perform more efficiently if the calls to this // are in the same order as the Algos enumeration. It will // work properly even if they are not. void fill(AlgoType algo, std::vector<float> const& values, std::vector<float> const& errors, std::vector<short> const& qualities); void fillBeamIntensities(std::vector<float> const& beam1Intensities, std::vector<float> const& beam2Intensities); float lumiValue(AlgoType algo, unsigned int bx) const; float lumiError(AlgoType algo, unsigned int bx) const; short lumiQuality(AlgoType algo, unsigned int bx) const; float lumiBeam1Intensity(unsigned int bx) const; float lumiBeam2Intensity(unsigned int bx) const; ValueRange lumiValuesForAlgo(AlgoType algo) const; ErrorRange lumiErrorsForAlgo(AlgoType algo) const; QualityRange lumiQualitiesForAlgo(AlgoType algo) const; std::vector<float> const& lumiBeam1Intensities() const; std::vector<float> const& lumiBeam2Intensities() const; bool isProductEqual(LumiDetails const& lumiDetails) const; static std::vector<std::string> const& algoNames(); static std::vector<std::string> const& dipalgoNames(); private: void checkAlgo(AlgoType algo) const; void checkAlgoAndBX(AlgoType algo, unsigned int bx) const; static std::vector<std::string> const m_algoNames; std::string m_lumiVersion; /* m_algoToFirstIndex is 'kMaxNumAlgos' long. Each algorithm's numerical value from the enum Algos is used as the index into m_algoToFirstIndex to find the first entry into the m_all* vectors containing data for that algorithm. The entry beyond the last entry is found by using the numerical value + 1. If the first and last index are the same then there is no information recorded for that algorithm. */ std::vector<unsigned int> m_algoToFirstIndex; std::vector<float> m_allValues; std::vector<float> m_allErrors; std::vector<short> m_allQualities; std::vector<float> m_beam1Intensities; std::vector<float> m_beam2Intensities; }; std::ostream& operator<<(std::ostream& s, LumiDetails const& lumiDetails); #endif
37.829787
115
0.732283
[ "vector" ]
261f1ec414d9818e771b5bb4c0123319ad53df8a
6,625
c
C
c_src/cherly_nif.c
saleyn/cherly
b30a2f21d1721e5e3cad07336387191c026c54d8
[ "Beerware" ]
null
null
null
c_src/cherly_nif.c
saleyn/cherly
b30a2f21d1721e5e3cad07336387191c026c54d8
[ "Beerware" ]
null
null
null
c_src/cherly_nif.c
saleyn/cherly
b30a2f21d1721e5e3cad07336387191c026c54d8
[ "Beerware" ]
null
null
null
#include "erl_nif.h" #include <stdio.h> #include <string.h> #include "cherly.h" #include "common.h" #define CHERLY_RES_TYPE "cherly_res" static ERL_NIF_TERM cherly_nif_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cherly_nif_stop(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cherly_nif_get(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cherly_nif_put(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cherly_nif_remove(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cherly_nif_size(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM cherly_nif_items(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ErlNifFunc nif_funcs[] = { {"start", 1, cherly_nif_init}, {"stop", 1, cherly_nif_stop}, {"get" , 2, cherly_nif_get}, {"put" , 3, cherly_nif_put}, {"remove", 2, cherly_nif_remove}, {"size", 1, cherly_nif_size}, {"items" , 1, cherly_nif_items} }; static ERL_NIF_TERM atom_ok; static ERL_NIF_TERM atom_error; static ERL_NIF_TERM atom_oom; static ERL_NIF_TERM atom_not_found; /** * Initialize */ static ERL_NIF_TERM cherly_nif_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ErlNifUInt64 max_size; ERL_NIF_TERM term; ErlNifResourceType* pert; cherly_t* obj; if (argc < 1) { return enif_make_badarg(env); } if (!enif_get_uint64(env, argv[0], &max_size)) { return enif_make_badarg(env); } pert = (ErlNifResourceType*)enif_priv_data(env); obj = enif_alloc_resource(pert, sizeof(cherly_t)); term = enif_make_resource(env, obj); cherly_init(obj, 0, max_size); enif_release_resource(obj); return enif_make_tuple2(env, atom_ok, term); } /** * Stop */ static ERL_NIF_TERM cherly_nif_stop(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { cherly_t *obj; ErlNifResourceType* pert; if (argc < 1) { return enif_make_badarg(env); } pert = (ErlNifResourceType*)enif_priv_data(env); if (!enif_get_resource(env, argv[0], pert, (void**)&obj)) { return enif_make_badarg(env); } cherly_destroy(obj); return atom_ok; } /** * Retrieve an object from LRU-Storage */ static ERL_NIF_TERM cherly_nif_get(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { cherly_t *obj; int vallen; void* value; ErlNifResourceType* pert; ErlNifBinary keybin; ErlNifBinary bin; if (argc < 2) { return enif_make_badarg(env); } pert = (ErlNifResourceType*)enif_priv_data(env); if (!enif_get_resource(env, argv[0], pert, (void**)&obj)) { return enif_make_badarg(env); } if (!enif_inspect_binary(env, argv[1], &keybin)) { return enif_make_badarg(env); } if (keybin.size <= 0) { return enif_make_badarg(env); } value = cherly_get(obj, keybin.data, keybin.size, &vallen); if (value == NULL) { return atom_not_found; } if (!enif_alloc_binary(vallen, &bin)) { return enif_make_badarg(env); } memcpy(bin.data, value, vallen); return enif_make_tuple2(env, atom_ok, enif_make_binary(env, &bin)); } /** * Insert an object into LRU-Storage */ static ERL_NIF_TERM cherly_nif_put(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { cherly_t *obj; ErlNifResourceType* pert; ErlNifBinary keybin; ErlNifBinary bin; bool ret; if (argc < 3) { return enif_make_badarg(env); } pert = (ErlNifResourceType*)enif_priv_data(env); if (!enif_get_resource(env, argv[0], pert, (void**)&obj)) { return enif_make_badarg(env); } if (!enif_inspect_binary(env, argv[1], &keybin)) { return enif_make_badarg(env); } if (keybin.size <= 0) { return enif_make_badarg(env); } if (!enif_inspect_binary(env, argv[2], &bin)) { return enif_make_badarg(env); } ret = cherly_put(obj, keybin.data, keybin.size, bin.data, bin.size, NULL); return ret ? atom_ok : enif_make_tuple2(env, atom_error, atom_oom); } /** * Remove an object from LRU-Storage */ static ERL_NIF_TERM cherly_nif_remove(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { cherly_t *obj; ErlNifResourceType* pert; ErlNifBinary keybin; if (argc < 2) { return enif_make_badarg(env); } pert = (ErlNifResourceType*)enif_priv_data(env); if (!enif_get_resource(env, argv[0], pert, (void**)&obj)) { return enif_make_badarg(env); } if (!enif_inspect_binary(env, argv[1], &keybin)) { return enif_make_badarg(env); } if (keybin.size <= 0) { return enif_make_badarg(env); } cherly_remove(obj, keybin.data, keybin.size); return atom_ok; } /** * Retrieve summary of size of stored objects */ static ERL_NIF_TERM cherly_nif_size(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { cherly_t *obj; ErlNifResourceType* pert; ErlNifUInt64 size; if (argc < 1) { return enif_make_badarg(env); } pert = (ErlNifResourceType*)enif_priv_data(env); if (!enif_get_resource(env, argv[0], pert, (void**)&obj)) { return enif_make_badarg(env); } size = cherly_size(obj); return enif_make_tuple2(env, atom_ok, enif_make_uint64(env, size)); } /** * Retrieve total of objects */ static ERL_NIF_TERM cherly_nif_items(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { cherly_t *obj; ErlNifResourceType* pert; ErlNifUInt64 len; if (argc < 1) { return enif_make_badarg(env); } pert = (ErlNifResourceType*)enif_priv_data(env); if (!enif_get_resource(env, argv[0], pert, (void**)&obj)) { return enif_make_badarg(env); } len = cherly_items_length(obj); return enif_make_tuple2(env, atom_ok, enif_make_uint64(env, len)); } /** * When calling onload or uggrade */ static int onload(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) { ErlNifResourceFlags erf = ERL_NIF_RT_CREATE|ERL_NIF_RT_TAKEOVER; ErlNifResourceType* pert = enif_open_resource_type(env, NULL, CHERLY_RES_TYPE, NULL, erf, &erf); if (pert == NULL) { return 1; } *priv_data = (void*)pert; atom_ok = enif_make_atom(env, "ok"); atom_error = enif_make_atom(env, "error"); atom_oom = enif_make_atom(env, "out of memory"); atom_not_found = enif_make_atom(env, "not_found"); return 0; } /** * Onload */ int cherly_nif_onload(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) { return onload(env, priv_data, load_info); } /** * Upgrade */ int cherly_nif_upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info) { return onload(env, priv_data, load_info); } ERL_NIF_INIT(cherly, nif_funcs, cherly_nif_onload, NULL, cherly_nif_upgrade, NULL)
24.090909
104
0.700981
[ "object" ]
2621d26ea637668c0b6d7b0e74bd37870e9e65ed
15,278
h
C
BCC102/include/windows/sdk/InputScope.h
FarouDev/Projects-for-beginner-with-Cpp
1210457c122cb5da8f7c5a4a7386eb064e8b31b0
[ "MIT" ]
null
null
null
BCC102/include/windows/sdk/InputScope.h
FarouDev/Projects-for-beginner-with-Cpp
1210457c122cb5da8f7c5a4a7386eb064e8b31b0
[ "MIT" ]
null
null
null
BCC102/include/windows/sdk/InputScope.h
FarouDev/Projects-for-beginner-with-Cpp
1210457c122cb5da8f7c5a4a7386eb064e8b31b0
[ "MIT" ]
null
null
null
#pragma option push -b -a8 -pc -A- -w-pun /*P_O_Push*/ /* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 8.00.0611 */ /* @@MIDL_FILE_HEADING( ) */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif /* __RPCNDR_H_VERSION__ */ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __inputscope_h__ #define __inputscope_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __ITfInputScope_FWD_DEFINED__ #define __ITfInputScope_FWD_DEFINED__ typedef interface ITfInputScope ITfInputScope; #endif /* __ITfInputScope_FWD_DEFINED__ */ #ifndef __ITfInputScope2_FWD_DEFINED__ #define __ITfInputScope2_FWD_DEFINED__ typedef interface ITfInputScope2 ITfInputScope2; #endif /* __ITfInputScope2_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "ocidl.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_inputscope_0000_0000 */ /* [local] */ #include <winapifamily.h> //=--------------------------------------------------------------------------= // InputScope.h // InputScope declarations. //=--------------------------------------------------------------------------= // (C) Copyright 1995-2003 Microsoft Corporation. All Rights Reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR TFPLIED, INCLUDING BUT NOT LIMITED TO // THE TFPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. //=--------------------------------------------------------------------------= #ifndef INPUTSCOPE_DEFINED #define INPUTSCOPE_DEFINED #include <windows.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #pragma region Application Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) typedef /* [public][public] */ enum __MIDL___MIDL_itf_inputscope_0000_0000_0001 { IS_DEFAULT = 0, IS_URL = 1, IS_FILE_FULLFILEPATH = 2, IS_FILE_FILENAME = 3, IS_EMAIL_USERNAME = 4, IS_EMAIL_SMTPEMAILADDRESS = 5, IS_LOGINNAME = 6, IS_PERSONALNAME_FULLNAME = 7, IS_PERSONALNAME_PREFIX = 8, IS_PERSONALNAME_GIVENNAME = 9, IS_PERSONALNAME_MIDDLENAME = 10, IS_PERSONALNAME_SURNAME = 11, IS_PERSONALNAME_SUFFIX = 12, IS_ADDRESS_FULLPOSTALADDRESS = 13, IS_ADDRESS_POSTALCODE = 14, IS_ADDRESS_STREET = 15, IS_ADDRESS_STATEORPROVINCE = 16, IS_ADDRESS_CITY = 17, IS_ADDRESS_COUNTRYNAME = 18, IS_ADDRESS_COUNTRYSHORTNAME = 19, IS_CURRENCY_AMOUNTANDSYMBOL = 20, IS_CURRENCY_AMOUNT = 21, IS_DATE_FULLDATE = 22, IS_DATE_MONTH = 23, IS_DATE_DAY = 24, IS_DATE_YEAR = 25, IS_DATE_MONTHNAME = 26, IS_DATE_DAYNAME = 27, IS_DIGITS = 28, IS_NUMBER = 29, IS_ONECHAR = 30, IS_PASSWORD = 31, IS_TELEPHONE_FULLTELEPHONENUMBER = 32, IS_TELEPHONE_COUNTRYCODE = 33, IS_TELEPHONE_AREACODE = 34, IS_TELEPHONE_LOCALNUMBER = 35, IS_TIME_FULLTIME = 36, IS_TIME_HOUR = 37, IS_TIME_MINORSEC = 38, IS_NUMBER_FULLWIDTH = 39, IS_ALPHANUMERIC_HALFWIDTH = 40, IS_ALPHANUMERIC_FULLWIDTH = 41, IS_CURRENCY_CHINESE = 42, IS_BOPOMOFO = 43, IS_HIRAGANA = 44, IS_KATAKANA_HALFWIDTH = 45, IS_KATAKANA_FULLWIDTH = 46, IS_HANJA = 47, IS_HANGUL_HALFWIDTH = 48, IS_HANGUL_FULLWIDTH = 49, IS_SEARCH = 50, IS_FORMULA = 51, IS_SEARCH_INCREMENTAL = 52, IS_CHINESE_HALFWIDTH = 53, IS_CHINESE_FULLWIDTH = 54, IS_NATIVE_SCRIPT = 55, IS_YOMI = 56, IS_TEXT = 57, IS_CHAT = 58, IS_NAME_OR_PHONENUMBER = 59, IS_EMAILNAME_OR_ADDRESS = 60, IS_PRIVATE = 61, IS_MAPS = 62, IS_NUMERIC_PASSWORD = 63, IS_NUMERIC_PIN = 64, IS_ALPHANUMERIC_PIN = 65, IS_ALPHANUMERIC_PIN_SET = 66, IS_FORMULA_NUMBER = 67, IS_PHRASELIST = -1, IS_REGULAREXPRESSION = -2, IS_SRGS = -3, IS_XML = -4, IS_ENUMSTRING = -5 } InputScope; #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) */ #pragma endregion #pragma endregion #pragma region Desktop Family #pragma region Desktop Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) HRESULT WINAPI SetInputScope(HWND hwnd, InputScope inputscope); HRESULT WINAPI SetInputScopes(HWND hwnd, const InputScope *pInputScopes, UINT cInputScopes, _In_reads_(cPhrases) PWSTR *ppszPhraseList, UINT cPhrases, _In_opt_ PWSTR pszRegExp, _In_opt_ PWSTR pszSRGS); HRESULT WINAPI SetInputScopeXML(HWND hwnd, _In_opt_ PWSTR pszXML); HRESULT WINAPI SetInputScopes2(HWND hwnd, const InputScope *pInputScopes, UINT cInputScopes, IEnumString *pEnumString, _In_opt_ PWSTR pszRegExp, _In_opt_ PWSTR pszSRGS); #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #pragma endregion #pragma endregion #pragma region Application Family #pragma region Application Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) DEFINE_GUID(IID_ITfInputScope, 0xfde1eaee, 0x6924, 0x4cdf, 0x91, 0xe7, 0xda, 0x38, 0xcf, 0xf5, 0x55, 0x9d); DEFINE_GUID(IID_ITfInputScope2, 0x5731eaa0, 0x6bc2, 0x4681, 0xa5, 0x32, 0x92, 0xfb, 0xb7, 0x4d, 0x7c, 0x41); DEFINE_GUID(GUID_PROP_INPUTSCOPE, 0x1713dd5a, 0x68e7, 0x4a5b, 0x9a, 0xf6, 0x59, 0x2a, 0x59, 0x5c, 0x77, 0x8d); #ifdef __cplusplus } #endif /* __cplusplus */ extern RPC_IF_HANDLE __MIDL_itf_inputscope_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_inputscope_0000_0000_v0_0_s_ifspec; #ifndef __ITfInputScope_INTERFACE_DEFINED__ #define __ITfInputScope_INTERFACE_DEFINED__ /* interface ITfInputScope */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ITfInputScope; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("fde1eaee-6924-4cdf-91e7-da38cff5559d") ITfInputScope : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetInputScopes( /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*pcCount) InputScope **pprgInputScopes, /* [out] */ __RPC__out UINT *pcCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetPhrase( /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*pcCount) BSTR **ppbstrPhrases, /* [out] */ __RPC__out UINT *pcCount) = 0; virtual HRESULT STDMETHODCALLTYPE GetRegularExpression( /* [out] */ __RPC__deref_out_opt BSTR *pbstrRegExp) = 0; virtual HRESULT STDMETHODCALLTYPE GetSRGS( /* [out] */ __RPC__deref_out_opt BSTR *pbstrSRGS) = 0; virtual HRESULT STDMETHODCALLTYPE GetXML( /* [out] */ __RPC__deref_out_opt BSTR *pbstrXML) = 0; }; #else /* C style interface */ typedef struct ITfInputScopeVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ITfInputScope * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ITfInputScope * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ITfInputScope * This); HRESULT ( STDMETHODCALLTYPE *GetInputScopes )( __RPC__in ITfInputScope * This, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*pcCount) InputScope **pprgInputScopes, /* [out] */ __RPC__out UINT *pcCount); HRESULT ( STDMETHODCALLTYPE *GetPhrase )( __RPC__in ITfInputScope * This, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*pcCount) BSTR **ppbstrPhrases, /* [out] */ __RPC__out UINT *pcCount); HRESULT ( STDMETHODCALLTYPE *GetRegularExpression )( __RPC__in ITfInputScope * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrRegExp); HRESULT ( STDMETHODCALLTYPE *GetSRGS )( __RPC__in ITfInputScope * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrSRGS); HRESULT ( STDMETHODCALLTYPE *GetXML )( __RPC__in ITfInputScope * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrXML); END_INTERFACE } ITfInputScopeVtbl; interface ITfInputScope { CONST_VTBL struct ITfInputScopeVtbl *lpVtbl; }; #ifdef COBJMACROS #define ITfInputScope_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ITfInputScope_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ITfInputScope_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ITfInputScope_GetInputScopes(This,pprgInputScopes,pcCount) \ ( (This)->lpVtbl -> GetInputScopes(This,pprgInputScopes,pcCount) ) #define ITfInputScope_GetPhrase(This,ppbstrPhrases,pcCount) \ ( (This)->lpVtbl -> GetPhrase(This,ppbstrPhrases,pcCount) ) #define ITfInputScope_GetRegularExpression(This,pbstrRegExp) \ ( (This)->lpVtbl -> GetRegularExpression(This,pbstrRegExp) ) #define ITfInputScope_GetSRGS(This,pbstrSRGS) \ ( (This)->lpVtbl -> GetSRGS(This,pbstrSRGS) ) #define ITfInputScope_GetXML(This,pbstrXML) \ ( (This)->lpVtbl -> GetXML(This,pbstrXML) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ITfInputScope_INTERFACE_DEFINED__ */ #ifndef __ITfInputScope2_INTERFACE_DEFINED__ #define __ITfInputScope2_INTERFACE_DEFINED__ /* interface ITfInputScope2 */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ITfInputScope2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("5731eaa0-6bc2-4681-a532-92fbb74d7c41") ITfInputScope2 : public ITfInputScope { public: virtual HRESULT STDMETHODCALLTYPE EnumWordList( /* [out] */ __RPC__deref_out_opt IEnumString **ppEnumString) = 0; }; #else /* C style interface */ typedef struct ITfInputScope2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ITfInputScope2 * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ITfInputScope2 * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ITfInputScope2 * This); HRESULT ( STDMETHODCALLTYPE *GetInputScopes )( __RPC__in ITfInputScope2 * This, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*pcCount) InputScope **pprgInputScopes, /* [out] */ __RPC__out UINT *pcCount); HRESULT ( STDMETHODCALLTYPE *GetPhrase )( __RPC__in ITfInputScope2 * This, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*pcCount) BSTR **ppbstrPhrases, /* [out] */ __RPC__out UINT *pcCount); HRESULT ( STDMETHODCALLTYPE *GetRegularExpression )( __RPC__in ITfInputScope2 * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrRegExp); HRESULT ( STDMETHODCALLTYPE *GetSRGS )( __RPC__in ITfInputScope2 * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrSRGS); HRESULT ( STDMETHODCALLTYPE *GetXML )( __RPC__in ITfInputScope2 * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrXML); HRESULT ( STDMETHODCALLTYPE *EnumWordList )( __RPC__in ITfInputScope2 * This, /* [out] */ __RPC__deref_out_opt IEnumString **ppEnumString); END_INTERFACE } ITfInputScope2Vtbl; interface ITfInputScope2 { CONST_VTBL struct ITfInputScope2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define ITfInputScope2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ITfInputScope2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ITfInputScope2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ITfInputScope2_GetInputScopes(This,pprgInputScopes,pcCount) \ ( (This)->lpVtbl -> GetInputScopes(This,pprgInputScopes,pcCount) ) #define ITfInputScope2_GetPhrase(This,ppbstrPhrases,pcCount) \ ( (This)->lpVtbl -> GetPhrase(This,ppbstrPhrases,pcCount) ) #define ITfInputScope2_GetRegularExpression(This,pbstrRegExp) \ ( (This)->lpVtbl -> GetRegularExpression(This,pbstrRegExp) ) #define ITfInputScope2_GetSRGS(This,pbstrSRGS) \ ( (This)->lpVtbl -> GetSRGS(This,pbstrSRGS) ) #define ITfInputScope2_GetXML(This,pbstrXML) \ ( (This)->lpVtbl -> GetXML(This,pbstrXML) ) #define ITfInputScope2_EnumWordList(This,ppEnumString) \ ( (This)->lpVtbl -> EnumWordList(This,ppEnumString) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ITfInputScope2_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_inputscope_0000_0002 */ /* [local] */ #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) */ #pragma endregion #endif // INPUTSCOPE_DEFINED extern RPC_IF_HANDLE __MIDL_itf_inputscope_0000_0002_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_inputscope_0000_0002_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( __RPC__in unsigned long *, unsigned long , __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out BSTR * ); void __RPC_USER BSTR_UserFree( __RPC__in unsigned long *, __RPC__in BSTR * ); unsigned long __RPC_USER BSTR_UserSize64( __RPC__in unsigned long *, unsigned long , __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal64( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal64(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out BSTR * ); void __RPC_USER BSTR_UserFree64( __RPC__in unsigned long *, __RPC__in BSTR * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif #pragma option pop /*P_O_Pop*/
32.096639
201
0.666252
[ "object" ]
262211fb3e41bae66f96643c5c12e315f640c7f7
325
h
C
BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Channels/RendererContext/CullContext.h
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
1
2022-01-28T11:43:47.000Z
2022-01-28T11:43:47.000Z
BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Channels/RendererContext/CullContext.h
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Channels/RendererContext/CullContext.h
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
#pragma once namespace bv { namespace model { class CullContext { public: bool enabled; // true bool isCCWOrdered; // true public: CullContext (); CullContext * Clone () const; void SetContext ( const CullContext * ctx ); }; } //model } //bv
13
63
0.523077
[ "model" ]
2628763c08b4fd22c9943e3f646fff3c81014f86
8,705
h
C
src/rescoring/feature_function_grammar.h
nrc-cnrc/Portage-SMT-TAS
73f5a65de4adfa13008ea9a01758385c97526059
[ "MIT" ]
null
null
null
src/rescoring/feature_function_grammar.h
nrc-cnrc/Portage-SMT-TAS
73f5a65de4adfa13008ea9a01758385c97526059
[ "MIT" ]
null
null
null
src/rescoring/feature_function_grammar.h
nrc-cnrc/Portage-SMT-TAS
73f5a65de4adfa13008ea9a01758385c97526059
[ "MIT" ]
null
null
null
/** * @author Samuel Larkin * @file feature_function_grammar.h This is the grammar the parse feature * function when read a rescoring-model * * $Id$ * * Technologies langagieres interactives / Interactive Language Technologies * Inst. de technologie de l'information / Institute for Information Technology * Conseil national de recherches Canada / National Research Council Canada * Copyright 2005, 2006, Sa Majeste la Reine du Chef du Canada / * Copyright 2005, 2006, Her Majesty in Right of Canada */ #ifndef __FEATURE_FUNCTION_GRAMMAR_H__ #define __FEATURE_FUNCTION_GRAMMAR_H__ #include "portage_defs.h" #include "randomDistribution.h" #include "errors.h" #include <boost/version.hpp> #if BOOST_VERSION >= 103800 #include <boost/spirit/include/classic.hpp> #include <boost/spirit/include/classic_assign_actor.hpp> using namespace boost::spirit::classic; #else #include <boost/spirit.hpp> #include <boost/spirit/actor/assign_actor.hpp> using namespace boost::spirit; #endif #include <boost/bind.hpp> #include <string> namespace Portage { /// Grammar to parse feature function from a rescoring-model. class feature_function_grammar : public grammar<feature_function_grammar> { protected: // Only usefull within the class mutable double first; ///< tmp placeholder when creating a random distribution mutable double second; ///< tmp placeholder when creating a random distribution bool training; ///< when training substitue weight by default distn and warn public: // Must be accessible from outside mutable ptr_rnd_gen rnd; ///< The parsed random distribution object mutable std::string ff; ///< mutable std::string name, arg; ///< name and arguments of a feature function mutable double weight; /// Default constructor. feature_function_grammar(bool training) : first(0.0f) , second(0.0f) , training(training) , weight(0.0f) {} /// Resets the placeholders in the grammar in multiple usage scenarios. void clear() { debug("CLEARING"); rnd.reset(); ff.clear(); name.clear(); arg.clear(); weight = 0.0f; first = second = 0.0f; } /// Creates a uniform random distribution. /// Grammar's semantic action. void checkDistn(char const*, char const*) const{ debug("checking distribution"); if (rnd.get() == NULL) { std::cerr << "Invalid distribution" << std::endl; assert(false); } } /// Creates a uniform random distribution. /// Grammar's semantic action. void makeUniform(char const*, char const*) const{ debug("Creating uniform"); rnd = ptr_rnd_gen(new uniform(first, second)); } /// Creates a normal random distribution. /// Grammar's semantic action. void makeNormal(char const*, char const*) const{ debug("Creating normal"); rnd = ptr_rnd_gen(new normal(first, second)); } /// Creates the weight distribution. /// Grammar's semantic action. void makeWeight(double weight) const{ debug("Creating weight"); rnd = ptr_rnd_gen(new weight_distribution(weight)); } /// Creates the default random distribution which is a N(0.0,1.0). /// Grammar's semantic action. void makeDefault(char const*, char const*) const{ debug("Creating default"); rnd = ptr_rnd_gen(new normal(0.0f, 1.0f)); } /// Creates the default random distribution which is a N(0.0,1.0). /// Grammar's semantic action. void makeDefault(double) const{ makeDefault(NULL, NULL); } /// In training mode, when a weight is detect, warn the user. /// Grammar's semantic action. void warnDefault(double) const { if (training) { error(ETWarn, "Dropping weight and using default distribution for training"); makeDefault(NULL, NULL); } } /// Signals an error on missing weight in translation mode. /// In translating mode, the model MUST contain a weight for each feature function. void errorNoWeight(char const*, char const*) const { debug("Error, when translating you need weights"); error(ETFatal, "Translating requires feature function weights, check your rescoring model"); } /// Actual grammar's definiton template <typename ScannerT> struct definition { /// Default construtor. /// @param self the grammar object itself definition(feature_function_grammar const& self) { // Note: square braces are used to attach semantic action to a parsed // sequence of tokens. // Note: lexeme_d is to turn off white space skipping. // The grammar differs depending on training vs translating if (self.training) { // A weight can either be a normal distn or a uniform distn or a fix distn or be missing. weight = normal | uniform | fix | none; } else { // When translating, only a fix weight is allowed weight = fix | eps_p[bind(&feature_function_grammar::errorNoWeight, &self, _1, _2)]; } // none means no weight or distn and we will instanciate the default distn with a semantic action. none = eps_p [bind(&feature_function_grammar::makeDefault, &self, _1, _2)]; // A fix weight is represented by a real number. // We then want to assign the parsed value to the variable weight in self with a semantic action. // We then want to create the default distn with a semantic action. // We then want to warn the user that we've created a default distn if he's training with rescore_train. fix = real_p [assign_a(self.weight)] [bind(&feature_function_grammar::makeDefault, &self, _1)] [bind(&feature_function_grammar::warnDefault, &self, _1)]; // For a normal the user writes "N(mean, sigma)". // We then want to instanciate a normal distn with the provided mean and sigma with a semantic action. normal = ('N' >> values) [bind(&feature_function_grammar::makeNormal, &self, _1, _2)]; // For a uniform the user writes "U(min, max)". // We then want to instanciate a unifrom distn with the parsed min an max with a semantic action. uniform = ('U' >> values) [bind(&feature_function_grammar::makeUniform, &self, _1, _2)]; // value is the common part between the uniform and normal syntax which is "(real, real)". // We then want to assign the real values parsed to some temp variables with a semantic action. values = '(' >> real_p[assign_a(self.first)] >> ',' >> real_p[assign_a(self.second)] >> ')'; // The name of the feature function is composed of at least one alpha numeric caracter. // We then assign the feature's name to a variable called name with a semantic action. // lexeme_d means DO NOT skip white spaces for the rule inclosed in square braces // because this grammar expects the parser to eat the spaces for the rest. name = lexeme_d[(+alnum_p)][assign_a(self.name)]; // A feature may have some argument or not. // If it does, the argument starts with ':' and can contain any thing except spaces. // If an argument is present, we then want to assign it to a variable arg with a semantic action. // lexeme_d means DO NOT skip white spaces for the rule inclosed in square braces // because this grammar expects the parser to eat the spaces for the rest. arg = ':' >> lexeme_d[(+(~ch_p(' ')))][assign_a(self.arg)] | eps_p; // The overall rule for a feature function declaration in rescoring-model is: // a name, an argument that we assign to a variable ff with a semantic action // followed by a weight and for robustness, we attach a semantic action // to the weight which will make sure there is valid distn // instanciated. r = (name >> arg)[assign_a(self.ff)] >> weight[bind(&feature_function_grammar::checkDistn, &self, _1, _2)]; } /// Some rules placeholders rule<ScannerT> r, weight, normal, uniform, values, none, fix, name, arg; /// Default starting point. rule<ScannerT> const& start() const { return r; }; }; void debug(const char* const msg) const { #ifdef FF_GRAMMAR_DEBUG using namespace std; cerr << " FFG: " << msg << endl; #endif } }; // ends namespace feature_function_grammar }; // ends namespace Portage #endif // __FEATURE_FUNCTION_GRAMMAR_H__
40.300926
116
0.653762
[ "object", "model" ]
262e6c96a6369b9f5e9efbdd2fbdbd82e42d191c
2,700
h
C
cocos2dx_playground/Classes/step_rain_of_chaos_game_StageNode.h
R2Road/cocos2dx_playground
6e6f349b5c9fc702558fe8720ba9253a8ba00164
[ "Apache-2.0" ]
9
2020-06-11T17:09:44.000Z
2021-12-25T00:34:33.000Z
cocos2dx_playground/Classes/step_rain_of_chaos_game_StageNode.h
R2Road/cocos2dx_playground
6e6f349b5c9fc702558fe8720ba9253a8ba00164
[ "Apache-2.0" ]
9
2019-12-21T15:01:01.000Z
2020-12-05T15:42:43.000Z
cocos2dx_playground/Classes/step_rain_of_chaos_game_StageNode.h
R2Road/cocos2dx_playground
6e6f349b5c9fc702558fe8720ba9253a8ba00164
[ "Apache-2.0" ]
1
2020-09-07T01:32:16.000Z
2020-09-07T01:32:16.000Z
#pragma once #include <functional> #include <vector> #include "2d/CCNode.h" #include "step_mole_CircleCollisionComponentConfig.h" #include "step_rain_of_chaos_game_StageConfig.h" namespace step_mole { class CircleCollisionComponent; struct CircleCollisionComponentConfig; } namespace step_rain_of_chaos { namespace game { class BulletLifeComponent; using BulletManagerUp = std::unique_ptr<class BulletManager>; class StageNode : public cocos2d::Node { public: using BulletProcessExitCallback = std::function<void( int )>; using PlayerCollisionCallback = std::function<void()>; struct DebugConfig { bool bShowPivot = false; bool bShowLabel_StageArea = false; bool bShowGuide_BulletLifeArea = false; bool bShowGuide_BulletGenerateArea = false; }; private: StageNode( const StageConfig stage_config , const DebugConfig debug_config , const step_mole::CircleCollisionComponentConfig& circle_collision_component_config ); public: static StageNode* create( const StageConfig stage_config , const DebugConfig debug_config , const step_mole::CircleCollisionComponentConfig& circle_collision_component_config , const int bullet_count ); private: bool init( const int bullet_count ); cocos2d::Node* MakeBullet( const int index , const BulletProcessExitCallback& target_rest_callback , const step_mole::CircleCollisionComponentConfig& circle_collision_component_config , const bool bShowPivot ); void update4Collision( float dt ); public: void AddPlayer( cocos2d::Node* player_node ); void PlayerMoveRequest( const cocos2d::Vec2& move_vector ); void SetPlayerCollisionCallback( const PlayerCollisionCallback& player_collision_callback ) { mPlayerCollisionCallback = player_collision_callback; } void AddEnemy( cocos2d::Node* const enemy_node ); void RequestGenerateBullet( const int amount = 1 ); void RequestBulletAction( const cocos2d::Vec2 start_position, const cocos2d::Vec2 move_direction ); private: const StageConfig mStageConfig; const DebugConfig mDebugConfig; const step_mole::CircleCollisionComponentConfig mCircleCollisionComponentConfig; BulletManagerUp mBulletManager; std::vector<step_rain_of_chaos::game::BulletLifeComponent*> mBulletLifeComponentList; std::vector<step_mole::CircleCollisionComponent*> mCollisionComponentList; int mBulletCount; cocos2d::Node* mPlayerNode; step_mole::CircleCollisionComponent* mPlayerCircleCollisionComponent; PlayerCollisionCallback mPlayerCollisionCallback; cocos2d::Node* mEnemyNode; step_mole::CircleCollisionComponent* mEnemyCircleCollisionComponent; }; } }
29.032258
152
0.778148
[ "vector" ]
263d74005e7eafd82c13aa114ea23c97e13b9a83
2,416
h
C
common/WhirlyGlobeLib/include/GeographicLib.h
bacem86/WhirlyGlobe-1
79cf79d7e88e405cf476e638c17aa09bb79b06df
[ "Apache-2.0" ]
null
null
null
common/WhirlyGlobeLib/include/GeographicLib.h
bacem86/WhirlyGlobe-1
79cf79d7e88e405cf476e638c17aa09bb79b06df
[ "Apache-2.0" ]
null
null
null
common/WhirlyGlobeLib/include/GeographicLib.h
bacem86/WhirlyGlobe-1
79cf79d7e88e405cf476e638c17aa09bb79b06df
[ "Apache-2.0" ]
null
null
null
/* GeographicLib.h * WhirlyGlobeLib * * Created by Tim Sylvester on 1/14/22. * Copyright 2022 mousebird consulting * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GeographicLib_h #define GeographicLib_h #import "WhirlyVector.h" #import <tuple> namespace GeographicLib { class Geodesic; class Geocentric; } namespace WhirlyKit { namespace detail { // Generic geodesic initialized for WGS84 ellipsoid. // We assume this is thread-safe because we only read from it. extern const GeographicLib::Geodesic &wgs84Geodesic(); extern const GeographicLib::Geocentric &wgs84Geocentric(); } // Use an extra namespace to clarify that `Point3d`s are geocentric, not 3D Cartesian namespace Geocentric { extern bool checkIntersection( const Point3d &a, const Point3d &b, const Point3d &c, const Point3d &d); #if defined(GEOGRAPHICLIB_GEODESIC_HPP) extern bool checkIntersection( const Point3d &a, const Point3d &b, const Point3d &c, const Point3d &d, const GeographicLib::Geodesic &geo); #endif extern std::tuple<bool,Point3d> findIntersection( const Point3d &a, const Point3d &b, const Point3d &c, const Point3d &d); #if defined(GEOGRAPHICLIB_GEODESIC_HPP) extern std::tuple<bool,Point3d> findIntersection( const Point3d &a, const Point3d &b, const Point3d &c, const Point3d &d, const GeographicLib::Geodesic &geo); #endif extern double initialHeading(const Point3d &startPt, const Point3d &endPt); extern double finalHeading(const Point3d &startPt, const Point3d &endPt); extern Point3d orthoDirect(const Point3d &start, double azimuthRad, double distMeters); extern std::tuple<double,double,double> OrthoDist(const Point3d &gca, const Point3d &gcb, const Point3d &gcc); }} #if defined __cplusplus extern "C" { #endif #if defined __cplusplus } // extern "C" #endif #endif /* GeographicLib_h */
30.582278
110
0.735099
[ "3d" ]
26408a019340a7f755e2b2560ae07ca2349e42ce
5,737
h
C
src/C++/Mozilla/old_snapshots/dom-crypto/Key.h
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
src/C++/Mozilla/old_snapshots/dom-crypto/Key.h
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C++/Mozilla/old_snapshots/dom-crypto/Key.h
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et cindent: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_dom_Key_h #define mozilla_dom_Key_h #include "nsCycleCollectionParticipant.h" #include "nsWrapperCache.h" #include "nsIGlobalObject.h" #include "nsNSSShutDown.h" #include "pk11pub.h" #include "keyhi.h" #include "ScopedNSSTypes.h" #include "mozilla/dom/KeyAlgorithm.h" #include "mozilla/dom/CryptoBuffer.h" #include "js/StructuredClone.h" #include "js/TypeDecls.h" class nsIGlobalObject; namespace mozilla { namespace dom { /* The internal structure of keys is dictated by the need for cloning. We store everything besides the key data itself in a 32-bit bitmask, with the following structure (byte-aligned for simplicity, in order from least to most significant): Bits Usage 0 Extractable 1-7 [reserved] 8-15 KeyType 16-23 KeyUsage 24-31 [reserved] In the order of a hex value for a uint32_t 3 2 1 0 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |~~~~~~~~~~~~~~~| Usage | Type |~~~~~~~~~~~~~|E| +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Thus, internally, a key has the following fields: * uint32_t - flags for extractable, usage, type * KeyAlgorithm - the algorithm (which must serialize/deserialize itself) * The actual keys (which the Key must serialize) */ class Key MOZ_FINAL : public nsISupports, public nsWrapperCache, public nsNSSShutDownObject { public: NS_DECL_CYCLE_COLLECTING_ISUPPORTS NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Key) static const uint32_t CLEAR_EXTRACTABLE = 0xFFFFFFE; static const uint32_t EXTRACTABLE = 0x00000001; static const uint32_t CLEAR_TYPE = 0xFFFF00FF; static const uint32_t TYPE_MASK = 0x0000FF00; enum KeyType { UNKNOWN = 0x00000000, SECRET = 0x00000100, PUBLIC = 0x00000200, PRIVATE = 0x00000300 }; static const uint32_t CLEAR_USAGES = 0xFF00FFFF; static const uint32_t USAGES_MASK = 0x00FF0000; enum KeyUsage { ENCRYPT = 0x00010000, DECRYPT = 0x00020000, SIGN = 0x00040000, VERIFY = 0x00080000, DERIVEKEY = 0x00100000, DERIVEBITS = 0x00200000, WRAPKEY = 0x00400000, UNWRAPKEY = 0x00800000 }; Key(nsIGlobalObject* aWindow); ~Key(); nsIGlobalObject* GetParentObject() const { return mGlobal; } virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE; // WebIDL methods void GetType(nsString& aRetVal) const; bool Extractable() const; KeyAlgorithm* Algorithm() const; void GetUsages(nsTArray<nsString>& aRetVal) const; // The below methods are not exposed to JS, but C++ can use // them to manipulate the object KeyType GetKeyType() const; nsresult SetType(const nsString& aType); void SetType(KeyType aType); void SetExtractable(bool aExtractable); void SetAlgorithm(KeyAlgorithm* aAlgorithm); void ClearUsages(); nsresult AddUsage(const nsString& aUsage); nsresult AddUsageIntersecting(const nsString& aUsage, uint32_t aUsageMask); void AddUsage(KeyUsage aUsage); bool HasUsage(KeyUsage aUsage); bool HasUsageOtherThan(uint32_t aUsages); void SetSymKey(const CryptoBuffer& aSymKey); void SetPrivateKey(SECKEYPrivateKey* aPrivateKey); void SetPublicKey(SECKEYPublicKey* aPublicKey); // Accessors for the keys themselves // Note: GetPrivateKey and GetPublicKey return copies of the internal // key handles, which the caller must free with SECKEY_DestroyPrivateKey // or SECKEY_DestroyPublicKey. const CryptoBuffer& GetSymKey() const; SECKEYPrivateKey* GetPrivateKey() const; SECKEYPublicKey* GetPublicKey() const; // For nsNSSShutDownObject virtual void virtualDestroyNSSReference(); void destructorSafeDestroyNSSReference(); // Serialization and deserialization convenience methods // Note: // 1. The inputs aKeyData are non-const only because the NSS import // functions lack the const modifier. They should not be modified. // 2. All of the NSS key objects returned need to be freed by the caller. static SECKEYPrivateKey* PrivateKeyFromPkcs8(CryptoBuffer& aKeyData, const nsNSSShutDownPreventionLock& /*proofOfLock*/); static nsresult PrivateKeyToPkcs8(SECKEYPrivateKey* aPrivKey, CryptoBuffer& aRetVal, const nsNSSShutDownPreventionLock& /*proofOfLock*/); static SECKEYPublicKey* PublicKeyFromSpki(CryptoBuffer& aKeyData, const nsNSSShutDownPreventionLock& /*proofOfLock*/); static nsresult PublicKeyToSpki(SECKEYPublicKey* aPrivKey, CryptoBuffer& aRetVal, const nsNSSShutDownPreventionLock& /*proofOfLock*/); // Structured clone methods use these to clone keys bool WriteStructuredClone(JSStructuredCloneWriter* aWriter) const; bool ReadStructuredClone(JSStructuredCloneReader* aReader); private: nsRefPtr<nsIGlobalObject> mGlobal; uint32_t mAttributes; // see above nsRefPtr<KeyAlgorithm> mAlgorithm; // Only one key handle should be set, according to the KeyType CryptoBuffer mSymKey; ScopedSECKEYPrivateKey mPrivateKey; ScopedSECKEYPublicKey mPublicKey; }; } // namespace dom } // namespace mozilla #endif // mozilla_dom_Key_h
33.16185
99
0.687642
[ "object" ]
2646541bb57316882a9ae7a9c0da4822d796607b
2,539
h
C
ArduinoJson/JsonParser/JsonToken.h
ararog/WebSocketRails-Arduino
0a8f7c181533fc79be5d8f330c63030086bf8c84
[ "MIT" ]
1
2016-02-03T20:59:44.000Z
2016-02-03T20:59:44.000Z
ArduinoJson/JsonParser/JsonToken.h
ararog/WebSocketRails-Arduino
0a8f7c181533fc79be5d8f330c63030086bf8c84
[ "MIT" ]
null
null
null
ArduinoJson/JsonParser/JsonToken.h
ararog/WebSocketRails-Arduino
0a8f7c181533fc79be5d8f330c63030086bf8c84
[ "MIT" ]
null
null
null
/* * Arduino JSON library * Benoit Blanchon 2014 - MIT License */ #pragma once #include "jsmn.h" namespace ArduinoJson { namespace Parser { // A pointer to a JSON token class JsonToken { public: // Create a "null" pointer JsonToken() : token(0) { } // Create a pointer to the specified JSON token JsonToken(char* json, jsmntok_t* token) : json(json), token(token) { } // Get content of the JSON token char* getText() { json[token->end] = 0; return json + token->start; } // Get the number of children tokens int childrenCount() { return token->size; } // Get a pointer to the first child of the current token JsonToken firstChild() const { return JsonToken(json, token + 1); } // Get a pointer to the next sibling token (ie skiping the children tokens) JsonToken nextSibling() const; // Test equality bool operator!=(const JsonToken& other) const { return token != other.token; } // Tell if the pointer is "null" bool isValid() { return token != 0; } // Tell if the JSON token is a JSON object bool isObject() { return token != 0 && token->type == JSMN_OBJECT; } // Tell if the JSON token is a JSON array bool isArray() { return token != 0 && token->type == JSMN_ARRAY; } // Tell if the JSON token is a primitive bool isPrimitive() { return token != 0 && token->type == JSMN_PRIMITIVE; } // Tell if the JSON token is a string bool isString() { return token != 0 && token->type == JSMN_STRING; } // Explicit wait to create a "null" JsonToken static JsonToken null() { return JsonToken(); } private: char* json; jsmntok_t* token; }; } }
25.39
88
0.422607
[ "object" ]
2649b524af19596e9bd53ebc8e6ee70cd5c093bf
63,124
c
C
ProjectX/controls.c
ForsakenW/forsaken
f06e2b9031e96a9fd219ab1326ad4eacbab37d44
[ "MIT" ]
7
2015-06-21T13:01:03.000Z
2020-08-09T19:53:26.000Z
ProjectX/controls.c
ForsakenW/forsaken
f06e2b9031e96a9fd219ab1326ad4eacbab37d44
[ "MIT" ]
3
2015-06-26T01:35:18.000Z
2016-05-11T22:50:48.000Z
ProjectX/controls.c
ForsakenW/forsaken
f06e2b9031e96a9fd219ab1326ad4eacbab37d44
[ "MIT" ]
null
null
null
/* handle keyboard and mouse control */ #include <math.h> #include <dplay.h> #include <dplobby.h> #include "windows.h" #include "typedefs.h" #include "dinput.h" #include "config.h" #include "title.h" #include "controls.h" #include <stdio.h> #include "text.h" #include "d3dmain.h" #include "cdaudio.h" #include "main.h" #include "compobjects.h" #include "quat.h" #include "object.h" #include "mydplay.h" #include "primary.h" #include "secondary.h" #include "sfx.h" #include "d3dappi.h" #if 1 // TEMP!! - for testing looping SFX #include "sfx.h" #include "dplay.h" #include "compobjects.h" #include "quat.h" #include "object.h" #include "mydplay.h" #include "ships.h" extern GLOBALSHIP Ships[]; #endif extern BOOL AllowServer; extern MENU MENU_NEW_Battle; extern MENU *CurrentMenu; extern BOOL Cheated; extern BOOL WaitingToQuit; extern BOOL CheatsDisabled; extern BOOL MouseInput; extern BOOL JoystickInput; extern BYTE MyGameStatus; extern float framelag; extern float framelag2; extern float NitroFuel; extern USERCONFIG *player_config; extern int Num_Joysticks; extern float MaxMoveSpeed; extern float MoveAccell; extern float MoveDecell; extern float MaxTurboSpeed; extern float TurboAccell; extern float TurboDecell; extern float MaxTurnSpeed; extern float TurnAccell; extern float TurnDecell; extern float MaxRollSpeed; extern float RollAccell; extern float RollDecell; extern float MaxBankAngle; extern float BankAccell; extern float BankDecell; extern BOOL DebugInfo; extern int8 PrimaryToFireLookup[ MAXPRIMARYWEAPONS ]; extern BOOL PrimaryWeaponCheat; extern int8 SecondaryToFireLookup[ MAXSECONDARYWEAPONS ]; extern BOOL SecondaryWeaponCheat; extern BOOL GodMode; extern BOOL LevelSelectMode; extern int FontHeight; int NakedGirls( char *cheat ); /*------------------------------------------------------------------- Some Keyboard and Mouse Globals -------------------------------------------------------------------*/ #define MAX_KEYS (256) #define MOUSE_ZSTEP (120) #define MAX_MOUSE_DELTA_X (40.0F) #define MAX_MOUSE_DELTA_Y (40.0F) #define MouseXFactor ( 1.0F / ( MAX_MOUSE_DELTA_X * MAX_MOUSE_DELTA_X ) ) #define MouseYFactor ( -1.0F / ( MAX_MOUSE_DELTA_Y * MAX_MOUSE_DELTA_Y ) ) #define KEY_HELD( K ) ( KeyState[ new_input ][ K ] & 0x80 ) #define KEY_PRESSED( K ) ( !( KeyState[ old_input ][ K ] & 0x80) && ( KeyState[ new_input ][ K ] & 0x80 ) ) #define KEY_RELEASED( K ) ( ( KeyState[ old_input ][ K ] & 0x80) && !( KeyState[ new_input ][ K ] & 0x80 ) ) #define MOUSE_BUTTON_HELD( B ) ( MouseState[ new_input ].rgbButtons[ B ] & 0x80 ) #define MOUSE_BUTTON_PRESSED( B ) ( !( MouseState[ old_input ].rgbButtons[ B ] & 0x80 ) && ( MouseState[ new_input ].rgbButtons[ B ] & 0x80 ) ) #define MOUSE_BUTTON_RELEASED( B ) ( ( MouseState[ old_input ].rgbButtons[ B ] & 0x80 ) && !( MouseState[ new_input ].rgbButtons[ B ] & 0x80 ) ) #define MOUSE_WHEEL_UP() ( MouseState[ new_input ].lZ > 0 ) #define MOUSE_WHEEL_DOWN() ( MouseState[ new_input ].lZ < 0 ) #define MOUSE_WHEEL_UP_PRESSED() ( !( MouseState[ old_input ].lZ > 0 ) && ( MouseState[ new_input ].lZ > 0 ) ) #define MOUSE_WHEEL_UP_RELEASED() ( ( MouseState[ old_input ].lZ > 0 ) && !( MouseState[ new_input ].lZ > 0 ) ) #define MOUSE_WHEEL_DOWN_PRESSED() ( !( MouseState[ old_input ].lZ < 0 ) && ( MouseState[ new_input ].lZ < 0 ) ) #define MOUSE_WHEEL_DOWN_RELEASED() ( ( MouseState[ old_input ].lZ < 0 ) && !( MouseState[ new_input ].lZ < 0 ) ) #define JOYSTICK_BUTTON_HELD( J, B ) ( js[ new_input ][ J ].rgbButtons[ B ] & 0x80 ) #define JOYSTICK_BUTTON_PRESSED( J, B ) ( !( js[ old_input ][ J ].rgbButtons[ B ] & 0x80) && ( js[ new_input ][ J ].rgbButtons[ B ] & 0x80 ) ) #define JOYSTICK_BUTTON_RELEASED( J, B ) ( ( js[ old_input ][ J ].rgbButtons[ B ] & 0x80) && !( js[ new_input ][ J ].rgbButtons[ B ] & 0x80 ) ) #define JOYSTICK_POV_HELD( J, P, D ) ( js_pov[ new_input ][ J ][ P ][ D ] & 0x80 ) #define JOYSTICK_POV_PRESSED( J, P, D ) ( !( js_pov[ old_input ][ J ][ P ][ D ] & 0x80 ) && ( js_pov[ new_input ][ J ][ P ][ D ] & 0x80 ) ) #define JOYSTICK_POV_RELEASED( J, P, D ) ( ( js_pov[ old_input ][ J ][ P ][ D ] & 0x80 ) && !( js_pov[ new_input ][ J ][ P ][ D ] & 0x80 ) ) extern VIRTUALKEYMAP vkey_map[]; int GetPOVMask( DWORD pov ); BOOL CheatsEnabled = FALSE; DIDEVICEOBJECTDATA rgod[DINPUT_BUFFERSIZE]; /* Receives buffered data */ DWORD BufferedKey[ DINPUT_BUFFERSIZE ]; int16 NumKeysToProcess; #define TOTAL_JOYSTICK_ACTIONS 140 // 5 axis positions, 3 axis rotations, 4 POV hats and 128 buttons! #define TOTAL_JOYSTICK_AXIS 8 // 5 axis positions, 3 axis rotations DIJOYSTATE2 js[ INPUT_BUFFERS ][ MAX_JOYSTICKS ]; BYTE js_pov[ INPUT_BUFFERS ][ MAX_JOYSTICKS ][ MAX_JOYSTICK_POVS ][ MAX_POV_DIRECTIONS ]; JOYSTICKINFO JoystickInfo[MAX_JOYSTICKS]; extern LPDIRECTINPUTDEVICE lpdiMouse; extern LPDIRECTINPUTDEVICE lpdiKeyboard; extern LPDIRECTINPUTDEVICE lpdiBufferedKeyboard; extern LPDIRECTINPUTDEVICE2 lpdiJoystick[MAX_JOYSTICKS]; extern MENU MENU_QuickTextSend; extern MENU MENU_QuickTextSendWhisper; extern MENU MENU_NEW_StartSinglePlayer; BOOL flush_input = TRUE; static uint16 old_input = 0; uint16 new_input = 1; static DIMOUSESTATE MouseState[ INPUT_BUFFERS ]; static uint8 KeyState[ INPUT_BUFFERS ][ MAX_KEYS ]; char *ShipActionText[NUM_SHIP_ACTIONS] = { "No Action", "Rotate Up", "Rotate Down", "Rotate Left", "Rotate Right", "Roll Left", "Roll Right", "Slide Up", "Slide Down", "Slide Left", "Slide Right", "Move Forward", "Move Back", "Cruise Increase", "Cruise Decrease", "Nitro", "Fire Primary", "Fire Secondary", "Drop Mine", "Next Primary", "Prev Primary", "Next Secondary", "Prev Secondary", "Drop Primary", "Drop Secondary", "Drop Shield", "Drop Ammo", "Slide Mode", "Roll Mode", }; char *ShipAxisText[NUM_SHIP_AXIS_ACTIONS] = { "No Action", "Rotate Up/Down", "Rotate Left/Right", "Roll Left/Right", "Slide Up/Down", "Slide Left/Right", "Move Forward/Back", }; char *ShipAxisSeperateText[NUM_SHIP_AXIS_ACTIONS * 2] = { "No Action", "No Action", "Rotate Up", "Rotate Down", "Rotate Left", "Rotate Right", "Roll Left", "Roll Right", "Slide Up", "Slide Down", "Slide Left", "Slide Right", "Move Forward", "Move Back", }; char FlashText[ 128 ]; float FlashTextActive = 0.0F; BOOL FullRearView = FALSE; BOOL Headlights = FALSE; void FlashMenuText( char *text, float activetime, uint16 sfx ) { if( text ) { strcpy( FlashText, text ); FlashTextActive = activetime; if( sfx != 0xFF ) { PlaySfx( sfx, 1.0F ); } } } void ProcessMenuFlashText( void ) { if ( FlashTextActive > 0.0F ) { FlashTextActive -= framelag2; if ( FlashTextActive > 0.0F ) { CenterPrint4x5Text( FlashText , d3dappi.szClient.cy - FontHeight * 2, 2 ); } } } int EnableCheats( char *cheat ) { CheatsEnabled = TRUE; //AddMessageToQue( "cheat mode enabled" ); FlashMenuText( "cheat mode enabled", 120.0F, SFX_Secret ); Cheated = TRUE; return 1; } int JimBeam( char *cheat ) { //AddMessageToQue( cheat ); if( PrimaryWeaponCheat ) { PrimaryToFireLookup[ PULSAR ] = PULSAR; PrimaryToFireLookup[ TROJAX ] = TROJAX; PrimaryToFireLookup[ PYROLITE_RIFLE ] = PYROLITE_RIFLE; PrimaryToFireLookup[ TRANSPULSE_CANNON ] = TRANSPULSE_CANNON; PrimaryToFireLookup[ SUSS_GUN ] = SUSS_GUN; PrimaryToFireLookup[ LASER ] = LASER; PrimaryWeaponCheat = FALSE; FlashMenuText( "Beam me down", 120.0F, SFX_Secret ); } else { PrimaryWeaponCheat = TRUE; FlashMenuText( "Beam me up", 120.0F, SFX_Secret ); } return 1; } int Lumberjack( char *cheat ) { #if 0 static int line = 0; static char *msg[] = { "he's a lumberjack", "and he's okay,", "he works all night", "and he sleeps all day." }; FlashMenuText( msg[ line++ % ( sizeof( msg ) / sizeof( msg[ 0 ] ) ) ], 120.0F, SFX_Secret ); #else //AddMessageToQue( cheat ); if( SecondaryWeaponCheat ) { FlashMenuText( "...and he sleeps all day", 120.0F, SFX_Secret ); SecondaryToFireLookup[ MUGMISSILE ] = MUGMISSILE; SecondaryToFireLookup[ SOLARISMISSILE ] = SOLARISMISSILE; SecondaryToFireLookup[ THIEFMISSILE ] = THIEFMISSILE; SecondaryToFireLookup[ SCATTERMISSILE ] = SCATTERMISSILE; SecondaryToFireLookup[ GRAVGONMISSILE ] = GRAVGONMISSILE; SecondaryToFireLookup[ MULTIPLEMISSILE ] = MULTIPLEMISSILE; SecondaryToFireLookup[ TITANSTARMISSILE ] = TITANSTARMISSILE; SecondaryToFireLookup[ PURGEMINE ] = PURGEMINE; SecondaryToFireLookup[ PINEMINE ] = PINEMINE; SecondaryToFireLookup[ QUANTUMMINE ] = QUANTUMMINE; SecondaryToFireLookup[ SPIDERMINE ] = SPIDERMINE; // SecondaryToFireLookup[ PINEMISSILE ] = PINEMISSILE; // SecondaryToFireLookup[ TITANSTARSHRAPNEL ] = TITANSTARSHRAPNEL; // SecondaryToFireLookup[ ENEMYSPIRALMISSILE ] = ENEMYSPIRALMISSILE; // SecondaryToFireLookup[ ENEMYHOMINGMISSILE ] = ENEMYHOMINGMISSILE; // SecondaryToFireLookup[ ENEMYBLUEHOMINGMISSILE ] = ENEMYBLUEHOMINGMISSILE; // SecondaryToFireLookup[ ENEMYFIREBALL ] = ENEMYFIREBALL; // SecondaryToFireLookup[ ENEMYTENTACLE ] = ENEMYTENTACLE; // SecondaryToFireLookup[ ENEMYDEPTHCHARGE ] = ENEMYDEPTHCHARGE; SecondaryWeaponCheat = FALSE; } else { SecondaryWeaponCheat = TRUE; FlashMenuText( "He works all night...", 120.0F, SFX_Secret ); } #endif return 1; } int ToggleGodMode( char *cheat ) { if( !GodMode ) { GodMode = TRUE; FlashMenuText( "God mode enabled", 120.0F, SFX_Secret ); GivemeAllWeapons(); } else { FlashMenuText( "God mode disabled", 120.0F, SFX_Secret ); LoseAllWeapons(); GodMode = FALSE; } return 1; } int ToggleLevelSelectMode( char *cheat ) { if( !LevelSelectMode ) { LevelSelectMode = TRUE; //AddMessageToQue( "Level Select Mode Enabled" ); FlashMenuText( "Level select mode enabled", 120.0F, SFX_Secret ); } else { LevelSelectMode = FALSE; //AddMessageToQue( "Level Select Mode Disabled" ); FlashMenuText( "Level select mode disabled", 120.0F, SFX_Secret ); } InitInGameMenu( &MENU_InGame ); AllowLevelSelect( &MENU_NEW_StartSinglePlayer ); return 1; } int ToggleServer( char *cheat ) { if ( CurrentMenu == &MENU_NEW_Battle ) { if ( AllowServer ) FlashMenuText( "Cannot disable Server while in this menu", 120.0F, SFX_Secret ); else FlashMenuText( "Cannot enable Server while in this menu", 120.0F, SFX_Secret ); return 0; } if( !AllowServer ) { AllowServer = TRUE; FlashMenuText( "Server enabled", 120.0F, SFX_Secret ); } else { FlashMenuText( "Server disabled", 120.0F, SFX_Secret ); AllowServer = FALSE; } return 1; } #ifdef ABUSE_PAUL int FatPaul( char *cheat ) { static int n = 0; static char *msg[] = { "Yes he is...homing titans enabled", "and so is Adam, by the way", "both of them. very fat...", "...and very gay.", }; FlashMenuText( msg[ n ], 400.0F, SFX_Secret ); n++; if ( n >= ( sizeof( msg ) / sizeof( msg[ 0 ] ) ) ) n = 0; return 1; } #endif static struct { #if CHEATS_AS_PLAINTEXT unsigned char *cheatcode; #else unsigned char cheatcode[ 16 ]; #endif int (*cheatfunc)( char * ); BOOL allowmultiplayer; int next; } CheatTable[] = { #if CHEATS_AS_PLAINTEXT { "BUBBLES", EnableCheats, TRUE }, { "TITSOOT", NakedGirls, TRUE }, { "JIMBEAM", JimBeam, FALSE }, { "LUMBERJACK", Lumberjack, FALSE }, { "IAMZEUS", ToggleGodMode, FALSE }, { "FULLMONTY", ToggleLevelSelectMode, FALSE }, { "SERVER", ToggleServer, TRUE }, #else { { DIK_B, DIK_U, DIK_B, DIK_B, DIK_L, DIK_E, DIK_S, 0 }, EnableCheats, TRUE }, { { DIK_T, DIK_I, DIK_T, DIK_S, DIK_O, DIK_O, DIK_T, 0 }, NakedGirls, TRUE }, { { DIK_J, DIK_I, DIK_M, DIK_B, DIK_E, DIK_A, DIK_M, 0 }, JimBeam, FALSE }, { { DIK_L, DIK_U, DIK_M, DIK_B, DIK_E, DIK_R, DIK_J, DIK_A, DIK_C, DIK_K, 0 }, Lumberjack, FALSE }, { { DIK_I, DIK_A, DIK_M, DIK_Z, DIK_E, DIK_U, DIK_S, 0 }, ToggleGodMode, FALSE }, { { DIK_F, DIK_U, DIK_L, DIK_L, DIK_M, DIK_O, DIK_N, DIK_T, DIK_Y, 0 }, ToggleLevelSelectMode, FALSE }, { { DIK_S, DIK_E, DIK_R, DIK_V, DIK_E, DIK_R, 0 }, ToggleServer, TRUE }, #ifdef ABUSE_PAUL { { DIK_F, DIK_A, DIK_T, DIK_P, DIK_A, DIK_U, DIK_L, DIK_I, DIK_S, DIK_G, DIK_A, DIK_Y, 0 }, FatPaul, TRUE }, #endif #endif }; // NOTE: add any new cheats to DisableCheats function to ensure they are not active in multiplayer game VirtualKeycode asckey[ 256 ]; int ShipAxisLookup[NUM_SHIP_AXIS_ACTIONS] = { SHIPACTION_Nothing, SHIPACTION_RotateUp, SHIPACTION_RotateLeft, SHIPACTION_RollLeft, SHIPACTION_SlideUp, SHIPACTION_SlideLeft, SHIPACTION_MoveForward }; #if 0 // Test SFX stuff... VECTOR TestSfxPos; uint16 TestSfxGroup; extern GLOBALSHIP Ships[MAX_PLAYERS+1]; #endif char *JoystickPOVDirections[MAX_POV_DIRECTIONS] = { "Up", "Down", "Left", "Right" }; HRESULT SetDIDwordProperty(LPDIRECTINPUTDEVICE2 pdev, REFGUID guidProperty, DWORD dwObject, DWORD dwHow, DWORD dwValue); BOOL IsEqualGuid(GUID *lpguid1, GUID *lpguid2); void DebugPrintf( const char * format, ... ); #ifdef USEINLINE _inline #endif short key_pressed( USERKEY *k ) { int j; VirtualKeycode c; for ( j = 0; j < k->keys; j++ ) { c = k->key[ j ]; if ( KEY_ON_KEYBOARD( c ) ) { if ( KEY_PRESSED( c ) ) return 1; } else if ( KEY_ON_MOUSE( c ) ) { switch( c ) { case DIK_LBUTTON: case DIK_RBUTTON: case DIK_MBUTTON: case DIK_TBUTTON: if ( MOUSE_BUTTON_PRESSED( c - DIK_LBUTTON ) ) return 1; break; case DIK_WHEELUP: if ( MOUSE_WHEEL_UP_PRESSED() ) return 1; break; case DIK_WHEELDOWN: if ( MOUSE_WHEEL_DOWN_PRESSED() ) return 1; break; } } else if ( KEY_ON_JOYSTICK( c ) ) { int joystick; joystick = KEY_JOYSTICK( c ); if ( !JoystickInfo[ joystick ].connected ) continue; if ( KEY_ON_JOYSTICK_BUTTON( c ) ) { int button; button = KEY_JOYSTICK_BUTTON( c ); if ( JOYSTICK_BUTTON_PRESSED( joystick, button ) ) return 1; } else if ( KEY_ON_JOYSTICK_POV( c ) ) { int pov, dir; pov = KEY_JOYSTICK_POV( c ); dir = KEY_JOYSTICK_POVDIR( c ); if ( JOYSTICK_POV_PRESSED( joystick, pov, dir ) ) return 1; } } } return 0; } #ifdef USEINLINE _inline #endif short key_released( USERKEY *k ) { int j; VirtualKeycode c; for ( j = 0; j < k->keys; j++ ) { c = k->key[ j ]; if ( KEY_ON_KEYBOARD( c ) ) { if ( KEY_RELEASED( c ) ) return 1; } else if ( KEY_ON_MOUSE( c ) ) { switch( c ) { case DIK_LBUTTON: case DIK_RBUTTON: case DIK_MBUTTON: case DIK_TBUTTON: if ( MOUSE_BUTTON_RELEASED( c - DIK_LBUTTON ) ) return 1; break; case DIK_WHEELUP: if ( MOUSE_WHEEL_UP_RELEASED() ) return 1; break; case DIK_WHEELDOWN: if ( MOUSE_WHEEL_DOWN_RELEASED() ) return 1; break; } } else if ( KEY_ON_JOYSTICK( c ) ) { int joystick; joystick = KEY_JOYSTICK( c ); if ( !JoystickInfo[ joystick ].connected ) continue; if ( KEY_ON_JOYSTICK_BUTTON( c ) ) { int button; button = KEY_JOYSTICK_BUTTON( c ); if ( JOYSTICK_BUTTON_RELEASED( joystick, button ) ) return 1; } else if ( KEY_ON_JOYSTICK_POV( c ) ) { int pov, dir; pov = KEY_JOYSTICK_POV( c ); dir = KEY_JOYSTICK_POVDIR( c ); if ( JOYSTICK_POV_RELEASED( joystick, pov, dir ) ) return 1; } } } return 0; } #ifdef USEINLINE _inline #endif short key_held( USERKEY *k ) { int j; VirtualKeycode c; for ( j = 0; j < k->keys; j++ ) { c = k->key[ j ]; if ( KEY_ON_KEYBOARD( c ) ) { if ( KEY_HELD( c ) ) return 1; } else if ( KEY_ON_MOUSE( c ) ) { switch( c ) { case DIK_LBUTTON: case DIK_RBUTTON: case DIK_MBUTTON: case DIK_TBUTTON: if ( MOUSE_BUTTON_HELD( c - DIK_LBUTTON ) ) return 1; break; case DIK_WHEELUP: if ( MOUSE_WHEEL_UP() ) return 1; break; case DIK_WHEELDOWN: if ( MOUSE_WHEEL_DOWN() ) return 1; break; } } else if ( KEY_ON_JOYSTICK( c ) ) { int joystick; joystick = KEY_JOYSTICK( c ); if ( !JoystickInfo[ joystick ].connected ) continue; if ( KEY_ON_JOYSTICK_BUTTON( c ) ) { int button; button = KEY_JOYSTICK_BUTTON( c ); if ( JOYSTICK_BUTTON_HELD( joystick, button ) ) return 1; } else if ( KEY_ON_JOYSTICK_POV( c ) ) { int pov, dir; pov = KEY_JOYSTICK_POV( c ); dir = KEY_JOYSTICK_POVDIR( c ); if ( JOYSTICK_POV_HELD( joystick, pov, dir ) ) return 1; } } } return 0; } static void InitAscKey( void ) { int j, k; char *keyword; for ( j = 0; j < 256; j++ ) { asckey[ j ] = 0; } for ( k = 0; vkey_map[ k ].keyword; k++ ) { keyword = vkey_map[ k ].keyword; if ( strstr( keyword, "DIK_" ) == keyword && strlen( keyword ) == 5 && !asckey[ keyword[ 4 ] ] ) { asckey[ keyword[ 4 ] ] = vkey_map[ k ].keycode; } } } void DisableCheats( void ) { CheatsEnabled = FALSE; DebugInfo = FALSE; // used to indicate cheats disabled for multiplayer game... CheatsDisabled = TRUE; if( PrimaryWeaponCheat ) JimBeam( NULL ); if( SecondaryWeaponCheat ) Lumberjack( NULL ); if( GodMode ) ToggleGodMode( NULL ); /* no need to disable level select mode if( LevelSelectMode ) ToggleLevelSelectMode( NULL ); */ } void CheckCheats( VirtualKeycode key ) { int j, i; int cheats; unsigned char ch; #if CHEATS_AS_PLAINTEXT static int init = 0; #endif #if CHEATS_AS_PLAINTEXT if ( !init ) { InitAscKey(); init = 1; } #endif cheats = sizeof( CheatTable ) / sizeof( CheatTable[ 0 ] ); if ( key ) { for ( j = 0; j < cheats; j++ ) { ch = CheatTable[ j ].cheatcode[ CheatTable[ j ].next ]; #if CHEATS_AS_PLAINTEXT if ( key == asckey[ ch ] ) #else if ( key == ch ) #endif { CheatTable[ j ].next++; if ( !CheatTable[ j ].cheatcode[ CheatTable[ j ].next ] ) { if ( ( MyGameStatus != STATUS_Normal ) || ( CheatTable[ j ].allowmultiplayer ) ) { if ( CheatTable[ j ].cheatfunc && ( CheatsEnabled || !j ) ) { CheatTable[ j ].cheatfunc( CheatTable[ j ].cheatcode ); // reset all cheats... for( i = 0; i < cheats; i++ ) { CheatTable[ i ].next = 0; } break; } } CheatTable[ j ].next = 0; } } else { CheatTable[ j ].next = 0; } } } } static void ReadKeyboard( int dup_last ) { int j; if ( dup_last ) { for ( j = 0; j < MAX_KEYS; j++ ) KeyState[ new_input ][ j ] = KeyState[ old_input ][ j ]; } else if( !lpdiKeyboard || IDirectInputDevice_GetDeviceState( lpdiKeyboard, sizeof( KeyState[ 0 ] ), KeyState[ new_input ] ) != DI_OK || flush_input ) { // failed to read the keyboard for ( j = 0; j < MAX_KEYS; j++ ) KeyState[ new_input ][ j ] = 0; } } void ReadBufferedKeyboard( void ) { uint16 i; if (lpdiBufferedKeyboard) { DWORD cod; HRESULT hr; DIDEVICEOBJECTDATA keyinfo; again:; cod = DINPUT_BUFFERSIZE; hr = lpdiBufferedKeyboard->lpVtbl->GetDeviceData(lpdiBufferedKeyboard, sizeof(DIDEVICEOBJECTDATA), rgod, &cod, 0); if (hr != DI_OK) { /* << insert recovery code here if you need any >> */ if (hr == DIERR_INPUTLOST) { hr = IDirectInputDevice_Acquire(lpdiBufferedKeyboard); if (SUCCEEDED(hr)) { goto again; } } } /* * In order for it to be worth our while to parse the * buffer elements, the GetDeviceData must have succeeded, * and we must have received some data at all. */ /* if (SUCCEEDED(hr) && cod > 0) { keyinfo = rgod[0]; if (keyinfo.dwData & 0x80) // only set for key down BufferedKey = keyinfo.dwOfs; else BufferedKey = 0; } else BufferedKey = 0; */ NumKeysToProcess = 0; if ( SUCCEEDED ( hr ) ) { for ( i = 0; i < cod; i++ ) { keyinfo = rgod[ i ]; if ( keyinfo.dwData & 0x80 ) { BufferedKey[ NumKeysToProcess++ ] = keyinfo.dwOfs; } } } } } static void ReadMouse( int dup_last ) { int j; HRESULT hr; if ( !MouseInput ) goto fail; if (lpdiMouse) { if ( dup_last ) { MouseState[ new_input ] = MouseState[ old_input ]; if ( MOUSE_WHEEL_UP() ) MouseState[ new_input ].lZ--; if ( MOUSE_WHEEL_DOWN() ) MouseState[ new_input ].lZ++; }else { hr = IDirectInputDevice_GetDeviceState( lpdiMouse, sizeof(DIMOUSESTATE), &MouseState[ new_input ] ); switch (hr) { case DI_OK: #if 1 if ( MouseState[ new_input ].lZ > 0 ) MouseState[ new_input ].lZ = 1; else if ( MouseState[ new_input ].lZ < 0 ) MouseState[ new_input ].lZ = -1; #else MouseState[ new_input ].lZ /= MOUSE_ZSTEP; #endif break; case DIERR_INPUTLOST: // re-aquire mouse hr = IDirectInputDevice_Acquire(lpdiMouse); goto fail; default: goto fail; } } }else goto fail; return; fail: // failed to read the mouse MouseState[ new_input ].lX = 0; MouseState[ new_input ].lY = 0; MouseState[ new_input ].lZ = 0; for ( j = 0; j < 4; j++ ) MouseState[ new_input ].rgbButtons[ j ] = 0; } int CurrentPolledJoystick = 0; float framelagfix = 0.0F; void ReadInput( void ) { int i; if ( WaitingToQuit ) return; old_input = new_input; new_input++; if ( new_input >= INPUT_BUFFERS ) new_input = 0; framelagfix -= framelag2; if( framelagfix <= 0.0F ) { ReadMouse( 0 ); framelagfix = 2.0F; } else { ReadMouse( 1 ); } ReadKeyboard( 0 ); #if 0 CurrentPolledJoystick++; if (CurrentPolledJoystick > (Num_Joysticks - 1)) CurrentPolledJoystick = 0; while (!JoystickInfo[CurrentPolledJoystick].assigned) { CurrentPolledJoystick++; if (CurrentPolledJoystick > (Num_Joysticks - 1)) CurrentPolledJoystick = 0; } PollJoystick( CurrentPolledJoystick ); #endif for (i = 0; i < Num_Joysticks; i++) { if (JoystickInfo[i].connected) PollJoystick(i); } flush_input = FALSE; } void control_ship( USERCONFIG *conf, SHIPCONTROL *ctrl ) { int j, joystick; float mouse_dx; float mouse_dy; float pitch_sign; float turn_sign; float MaxMove, MaxTurbo, MaxTurn, MaxRoll, MaxBank; ctrl->pitch = 0.0F; ctrl->yaw = 0.0F; ctrl->roll = 0.0F; ctrl->bank = 0.0F; ctrl->right = 0.0F; ctrl->up = 0.0F; ctrl->forward = 0.0F; ctrl->cruise_control = 0; ctrl->turbo = 0; ctrl->fire_primary = 0; ctrl->fire_secondary = 0; ctrl->fire_mine = 0; ctrl->select_primary = 0; ctrl->select_secondary = 0; ctrl->select_next_primary = 0; ctrl->select_prev_primary = 0; ctrl->select_next_secondary = 0; ctrl->select_prev_secondary = 0; ctrl->drop_primary = 0; ctrl->drop_secondary = 0; ctrl->drop_shield = 0; ctrl->drop_ammo = 0; if ( !conf ) return; // bail if no config supplied #ifdef MULTIPLE_READINPUTS ReadInput(); #endif #ifndef SELF_PLAY if ( CurrentMenu ) return; // disable bike controls if using menus mouse_dx = MouseState[ new_input ].lX * conf->mouse_x_sensitivity * 4.0F; mouse_dy = MouseState[ new_input ].lY * conf->mouse_y_sensitivity * 4.0F; #if 0 if ( mouse_dx < -MAX_MOUSE_DELTA_X ) mouse_dx = -MAX_MOUSE_DELTA_X; else if ( mouse_dx > MAX_MOUSE_DELTA_X ) mouse_dx = MAX_MOUSE_DELTA_X; if ( mouse_dy < -MAX_MOUSE_DELTA_Y ) mouse_dy = -MAX_MOUSE_DELTA_Y; else if ( mouse_dy > MAX_MOUSE_DELTA_Y ) mouse_dy = MAX_MOUSE_DELTA_Y; #endif // mouse_dx = mouse_dx * MouseXFactor; // mouse_dy = mouse_dy * MouseYFactor; mouse_dx = mouse_dx * (float) fabs( mouse_dx ) * MouseXFactor; mouse_dy = mouse_dy * (float) fabs( mouse_dy ) * MouseYFactor; if ( mouse_dx < -framelag ) mouse_dx = -framelag; if ( mouse_dx > framelag ) mouse_dx = framelag; if ( mouse_dy < -framelag ) mouse_dy = -framelag; if ( mouse_dy > framelag ) mouse_dy = framelag; pitch_sign = ( conf->invert_pitch ) ? -1.0F : 1.0F; turn_sign = ( conf->invert_turn ) ? -1.0F : 1.0F; if ( key_held( &conf->full_rear_view ) ) FullRearView = TRUE; else FullRearView = FALSE; if ( key_pressed( &conf->headlights ) ) Headlights = !Headlights; ctrl->slide_mode = key_held( &conf->move ); ctrl->roll_mode = key_held( &conf->roll ); if ( ctrl->slide_mode ) { if ( key_held( &conf->left ) ) { ctrl->right -= MoveAccell * MaxMoveSpeed * framelag; } if ( key_held( &conf->right ) ) { ctrl->right += MoveAccell * MaxMoveSpeed * framelag; } if ( mouse_dx != 0.0F ) { ctrl->right += MoveAccell * MaxMoveSpeed * mouse_dx; } if ( key_held( &conf->up ) ) { ctrl->up += MoveAccell * MaxMoveSpeed * framelag; } if ( key_held( &conf->down ) ) { ctrl->up -= MoveAccell * MaxMoveSpeed * framelag; } if ( mouse_dy != 0.0F ) { ctrl->up += MoveAccell * MaxMoveSpeed * mouse_dy; } } else { if ( ctrl->roll_mode ) { if ( key_held( &conf->left ) ) { ctrl->roll += RollAccell * MaxRollSpeed * framelag; } if ( key_held( &conf->right ) ) { ctrl->roll -= RollAccell * MaxRollSpeed * framelag; } if ( mouse_dx != 0.0F ) { ctrl->roll -= RollAccell * MaxRollSpeed* mouse_dx; } } else { if ( key_held( &conf->left ) ) { ctrl->yaw -= TurnAccell * MaxTurnSpeed * framelag; ctrl->bank += BankAccell * MaxBankAngle * framelag; } if ( key_held( &conf->right ) ) { ctrl->yaw += TurnAccell * MaxTurnSpeed * framelag; ctrl->bank -= BankAccell * MaxBankAngle * framelag; } if ( mouse_dx != 0.0F ) { ctrl->yaw += TurnAccell * MaxTurnSpeed * mouse_dx * turn_sign; ctrl->bank -= BankAccell * MaxBankAngle * mouse_dx * turn_sign; } } if ( key_held( &conf->down ) ) { ctrl->pitch -= TurnAccell * MaxTurnSpeed * framelag; } if ( key_held( &conf->up ) ) { ctrl->pitch += TurnAccell * MaxTurnSpeed * framelag; } if ( mouse_dy != 0.0F ) { ctrl->pitch += TurnAccell * MaxTurnSpeed * pitch_sign * mouse_dy ; } } if ( key_held( &conf->move_left ) ) { ctrl->right -= MoveAccell * MaxMoveSpeed * framelag; } if ( key_held( &conf->move_right ) ) { ctrl->right += MoveAccell * MaxMoveSpeed * framelag; } if ( key_held( &conf->move_down ) ) { ctrl->up -= MoveAccell * MaxMoveSpeed * framelag; } if ( key_held( &conf->move_up ) ) { ctrl->up += MoveAccell * MaxMoveSpeed * framelag; } if ( key_held( &conf->roll_left ) ) { ctrl->roll += RollAccell * MaxRollSpeed * framelag; } if ( key_held( &conf->roll_right ) ) { ctrl->roll -= RollAccell * MaxRollSpeed * framelag; } if( NitroFuel && ( key_pressed ( &conf->turbo ) ) ) { PlaySfx( SFX_NitroStart, 0.66F ); } ctrl->turbo = key_held( &conf->turbo ); if ( ctrl->turbo ) { if ( NitroFuel > 0.0F ) { ctrl->forward += TurboAccell * MaxTurboSpeed * framelag; } else { ctrl->forward += MoveAccell * MaxMoveSpeed * framelag; } } else if ( key_held( &conf->move_forward ) ) { ctrl->forward += MoveAccell * MaxMoveSpeed * framelag; } if ( key_held( &conf->move_backward ) ) { ctrl->forward -= MoveAccell * MaxMoveSpeed * framelag; } if ( key_pressed( &conf->cruise_faster ) ) ctrl->cruise_control++; if ( key_pressed( &conf->cruise_slower ) ) ctrl->cruise_control--; ctrl->fire_primary = key_held( &conf->fire_primary ); ctrl->fire_secondary = key_held( &conf->fire_secondary ); ctrl->fire_mine = key_pressed( &conf->fire_mine ); ctrl->select_next_primary = key_pressed( &conf->select_next_primary ); ctrl->select_prev_primary = key_pressed( &conf->select_prev_primary ); ctrl->select_next_secondary = key_pressed( &conf->select_next_secondary ); ctrl->select_prev_secondary = key_pressed( &conf->select_prev_secondary ); ctrl->drop_primary = key_pressed( &conf->drop_primary ); ctrl->drop_secondary = key_pressed( &conf->drop_secondary ); ctrl->drop_shield = key_pressed( &conf->drop_shield ); ctrl->drop_ammo = key_pressed( &conf->drop_ammo ); ctrl->select_primary = 0; for ( j = 0; j < MAX_PRIMARY_WEAPONS; j++ ) { if ( key_pressed( &conf->select_primary[ j ] ) ) { ctrl->select_primary = j + 1; } } ctrl->select_secondary = 0; for ( j = 0; j < MAX_SECONDARY_WEAPONS; j++ ) { if ( key_pressed( &conf->select_secondary[ j ] ) ) { ctrl->select_secondary = j + 1; } } if ( ( IsKeyHeld( DIK_LCONTROL ) || IsKeyHeld( DIK_RCONTROL ) ) && ( key_pressed( &conf->send_msg ) ) && MyGameStatus == STATUS_Normal ) { MenuRestart( &MENU_QuickTextSendWhisper ); }else if ( ( key_pressed( &conf->send_msg ) ) && MyGameStatus == STATUS_Normal ) { MenuRestart( &MENU_QuickTextSend ); } #ifdef PLAYER_SPEECH_TAUNTS if( key_pressed( &conf->send_speech ) ) { PlaySpecificBikerSpeech( SFX_BIKER_TN, Ships[ WhoIAm ].Object.Group, &Ships[WhoIAm].Object.Pos, 0.0F, player_config->bike, -1, FALSE ); // don't update if( MyGameStatus == STATUS_Normal ) { SendGameMessage(MSG_TEXTMSG, 0, 0, TEXTMSGTYPE_SpeechTaunt, 0); } } #endif for (joystick = 0; joystick < Num_Joysticks; joystick++) { if (JoystickInfo[joystick].connected && JoystickInfo[joystick].assigned) ReadJoystickInput(ctrl, joystick); } MaxMove = MoveAccell * MaxMoveSpeed * framelag; MaxTurbo = TurboAccell * MaxTurboSpeed * framelag; MaxTurn = TurnAccell * MaxTurnSpeed * framelag; MaxRoll = RollAccell * MaxRollSpeed * framelag; MaxBank = BankAccell * MaxBankAngle * framelag; CLAMP( ctrl->pitch, MaxTurn ); CLAMP( ctrl->yaw, MaxTurn ); CLAMP( ctrl->roll, MaxRoll ); CLAMP( ctrl->bank, MaxBank ); CLAMP( ctrl->right, MaxMove ); CLAMP( ctrl->up, MaxMove ); if ( ctrl->turbo && NitroFuel > 0.0F ) { if ( ctrl->forward > MaxTurbo ) ctrl->forward = MaxTurbo; else if ( ctrl->forward < -MaxMove ) ctrl->forward = -MaxMove; } else { CLAMP( ctrl->forward, MaxMove ); } #endif // !SELF_PLAY } int AnyKeyPressed( void ) { int k; static VirtualKeycode null_key[] = { #if 0 DIK_ESCAPE, DIK_F1, DIK_F2, DIK_F3, DIK_F4, DIK_F5, DIK_F6, DIK_F7, DIK_F8, DIK_F9, DIK_F10, DIK_F11, DIK_F12, DIK_F13, DIK_F14, DIK_F15, #endif (VirtualKeycode) -1, }; #ifdef MULTIPLE_READINPUTS ReadInput(); #endif if ( CurrentMenu ) return 0; for ( k = 0; null_key[ k ] != (VirtualKeycode) -1; k++ ) { if ( KEY_PRESSED( null_key[ k ] ) ) return 0; } for ( k = 0; k < MAX_KEYS; k++ ) { if ( KEY_PRESSED( k ) ) return 1; } for ( k = 0; k < MAX_MOUSE_BUTTONS; k++ ) { if ( MOUSE_BUTTON_PRESSED( k ) ) return 1; } if( IsAnyJoystickButtonPressed() ) { return 1; } return 0; } int AnyKeyReleased( void ) { int k; static VirtualKeycode null_key[] = { DIK_ESCAPE, DIK_F1, DIK_F2, DIK_F3, DIK_F4, DIK_F5, DIK_F6, DIK_F7, DIK_F8, DIK_F9, DIK_F10, DIK_F11, DIK_F12, DIK_F13, DIK_F14, DIK_F15, (VirtualKeycode) -1, }; #ifdef MULTIPLE_READINPUTS ReadInput(); #endif if ( CurrentMenu ) return 0; for ( k = 0; null_key[ k ] != (VirtualKeycode) -1; k++ ) { if ( KEY_RELEASED( null_key[ k ] ) ) return 0; } for ( k = 0; k < MAX_KEYS; k++ ) { if ( KEY_RELEASED( k ) ) return 1; } for ( k = 0; k < MAX_MOUSE_BUTTONS; k++ ) { if ( MOUSE_BUTTON_RELEASED( k ) ) return 1; } if( IsAnyJoystickButtonReleased() ) { return 1; } return 0; } int IsKeyPressed( int di_keycode ) { switch( di_keycode ) { case DIK_LBUTTON: if ( MOUSE_BUTTON_PRESSED( 0 ) ) return 1; break; case DIK_RBUTTON: if ( MOUSE_BUTTON_PRESSED( 1 ) ) return 1; break; case DIK_MBUTTON: if ( MOUSE_BUTTON_PRESSED( 2 ) ) return 1; break; default: if ( KEY_PRESSED( di_keycode ) ) return 1; } return 0; } int IsKeyHeld( int di_keycode ) { switch( di_keycode ) { case DIK_LBUTTON: if ( MOUSE_BUTTON_HELD( 0 ) ) return 1; break; case DIK_RBUTTON: if ( MOUSE_BUTTON_HELD( 1 ) ) return 1; break; case DIK_MBUTTON: if ( MOUSE_BUTTON_HELD( 2 ) ) return 1; break; case DIK_WHEELUP: if ( MOUSE_WHEEL_UP() ) return 1; break; case DIK_WHEELDOWN: if ( MOUSE_WHEEL_DOWN() ) return 1; break; default: if ( KEY_HELD( di_keycode ) ) return 1; } return 0; } int CheckMouse( void ) { int k; int key; key = 0; for ( k = 0; k < MAX_MOUSE_BUTTONS; k++ ) { if ( MOUSE_BUTTON_PRESSED( k ) ) { if ( !key ) key = DIK_LBUTTON + k; else return 0; } } if ( MOUSE_WHEEL_UP() ) { if ( !key ) key = DIK_WHEELUP; else return 0; } if ( MOUSE_WHEEL_DOWN() ) { if ( !key ) key = DIK_WHEELDOWN; else return 0; } return key; } int WhichKeyPressed( void ) { int k; int key; key = 0; for ( k = 0; k < MAX_KEYS; k++ ) { if ( KEY_PRESSED( k ) ) { if ( !key ) key = k; else return 0; } } for ( k = 0; k < Num_Joysticks; k++ ) { if ( JoystickInfo[ k ].connected ) { int b, p, d; for ( b = 0; b < JoystickInfo[ k ].NumButtons; b++ ) { if ( JOYSTICK_BUTTON_PRESSED( k, b ) ) { if ( !key ) key = JOYSTICK_BUTTON_KEYCODE( k, b ); else return 0; } } for ( p = 0; p < JoystickInfo[ k ].NumPOVs; p++ ) { for ( d = 0; d < MAX_POV_DIRECTIONS; d++ ) { if ( JOYSTICK_POV_PRESSED( k, p, d ) ) { if ( !key ) key = JOYSTICK_POVDIR_KEYCODE( k, p, d ); else return 0; } } } } } return key; } int WhichMousePressed( void ) { int k; int key; key = 0; for ( k = 0; k < MAX_MOUSE_BUTTONS; k++ ) { if ( MOUSE_BUTTON_PRESSED( k ) ) { if ( !key ) key = DIK_LBUTTON + k; else return 0; } } if ( MOUSE_WHEEL_UP_PRESSED() ) { if ( !key ) key = DIK_WHEELUP; else return 0; } if ( MOUSE_WHEEL_DOWN_PRESSED() ) { if ( !key ) key = DIK_WHEELDOWN; else return 0; } return key; } int WhichJoystickPressed( void ) { int k; int key; key = 0; for ( k = 0; k < Num_Joysticks; k++ ) { if ( JoystickInfo[ k ].connected ) { int b, p, d; for ( b = 0; b < JoystickInfo[ k ].NumButtons; b++ ) { if ( JOYSTICK_BUTTON_PRESSED( k, b ) ) { if ( !key ) key = JOYSTICK_BUTTON_KEYCODE( k, b ); else return 0; } } for ( p = 0; p < JoystickInfo[ k ].NumPOVs; p++ ) { for ( d = 0; d < MAX_POV_DIRECTIONS; d++ ) { if ( JOYSTICK_POV_PRESSED( k, p, d ) ) { if ( !key ) key = JOYSTICK_POVDIR_KEYCODE( k, p, d ); else return 0; } } } } } return key; } int WhichKeyHeld( void ) { int k; int key; key = 0; for ( k = 0; k < MAX_KEYS; k++ ) { if ( KEY_HELD( k ) ) { if ( !key ) key = k; else return 0; } } for ( k = 0; k < MAX_MOUSE_BUTTONS; k++ ) { if ( MOUSE_BUTTON_HELD( k ) ) { if ( !key ) key = DIK_LBUTTON + k; else return 0; } } if ( MOUSE_WHEEL_UP() ) { if ( !key ) key = DIK_WHEELUP; else return 0; } if ( MOUSE_WHEEL_DOWN() ) { if ( !key ) key = DIK_WHEELDOWN; else return 0; } return key; } void DoShipAction( SHIPCONTROL *ctrl, int Action, float amount ) { switch (Action) { case SHIPACTION_RotateUp: if ( ctrl->slide_mode ) { ctrl->up += MoveAccell * MaxMoveSpeed * amount; } else { ctrl->pitch += TurnAccell * MaxTurnSpeed * amount; } return; case SHIPACTION_RotateLeft: if ( ctrl->slide_mode ) { ctrl->right += MoveAccell * MaxMoveSpeed * amount; } else if ( ctrl->roll_mode ) { ctrl->roll -= RollAccell * MaxRollSpeed * amount; } else { ctrl->yaw += TurnAccell * MaxTurnSpeed * amount; ctrl->bank -= BankAccell * MaxBankAngle * amount; } return; case SHIPACTION_RollLeft: ctrl->roll -= RollAccell * MaxRollSpeed * amount; return; case SHIPACTION_SlideUp: ctrl->up -= MoveAccell * MaxMoveSpeed * amount; return; case SHIPACTION_SlideLeft: ctrl->right += MoveAccell * MaxMoveSpeed * amount; return; case SHIPACTION_MoveForward: ctrl->forward -= MoveAccell * MaxMoveSpeed * amount; return; } } /*-------------------------------------------------------------------------- | ReadJoystickInput | | Requests joystick data and performs any needed processing. | *-------------------------------------------------------------------------*/ BOOL PollJoystick( int joysticknum ) { HRESULT hRes, err; int i, j, povdir; if ( !JoystickInput ) { return TRUE; } if( !lpdiJoystick[joysticknum] ) return FALSE; // poll the joystick to read the current state hRes = IDirectInputDevice2_Poll(lpdiJoystick[joysticknum]); if(hRes != DI_OK) { switch (hRes) { case DIERR_INPUTLOST: { err = IDirectInputDevice2_Acquire(lpdiJoystick[joysticknum]); if (err != DI_OK) return FALSE; } break; default: return FALSE; } } // get data from the joystick hRes = IDirectInputDevice_GetDeviceState(lpdiJoystick[joysticknum], sizeof(DIJOYSTATE2), &js[ new_input ][joysticknum]); #if 1 if(hRes != DI_OK) { return FALSE; } #else if(hRes == DI_OK) { DebugPrintf("Joystick %d returned DI_OK\n",joysticknum); return TRUE; } switch (hRes) { case DIERR_INPUTLOST: DebugPrintf("Joystick %d returned DIERR_INPUTLOST\n",joysticknum); break; case DIERR_INVALIDPARAM: DebugPrintf("Joystick %d returned DIERR_INVALIDPARAM\n",joysticknum); break; case DIERR_NOTACQUIRED: DebugPrintf("Joystick %d returned DIERR_NOTACQUIRED\n",joysticknum); break; case DIERR_NOTINITIALIZED: DebugPrintf("Joystick %d returned DIERR_NOTINITIALIZED\n",joysticknum); break; case E_PENDING: DebugPrintf("Joystick %d returned E_PENDING\n",joysticknum); break; } #endif for (i = 0; i < JoystickInfo[joysticknum].NumPOVs; i++) { povdir = GetPOVMask( js[ new_input ][ joysticknum ].rgdwPOV[ i ] ); for (j = 0; j < MAX_POV_DIRECTIONS; j++) { js_pov[ new_input ][ joysticknum ][ i ][ j ] = ( povdir & ( 1 << j ) ) ? 0x80 : 0; } } return TRUE; } /*-------------------------------------------------------------------------- | | SetDIDwordProperty | | Set a DWORD property on a DirectInputDevice. | *-------------------------------------------------------------------------*/ HRESULT SetDIDwordProperty(LPDIRECTINPUTDEVICE2 pdev, REFGUID guidProperty, DWORD dwObject, DWORD dwHow, DWORD dwValue) { DIPROPDWORD dipdw; dipdw.diph.dwSize = sizeof(dipdw); dipdw.diph.dwHeaderSize = sizeof(dipdw.diph); dipdw.diph.dwObj = dwObject; dipdw.diph.dwHow = dwHow; dipdw.dwData = dwValue; return pdev->lpVtbl->SetProperty(pdev, guidProperty, &dipdw.diph); } void SetUpJoystickAxis(int joystick) { DIPROPRANGE diprg; BOOL DeadzoneNotSet = FALSE; int i; // set axis range to (-100 ... +100) // This lets us test against 0 to see which way the stick is pointed. diprg.diph.dwSize = sizeof(diprg); diprg.diph.dwHeaderSize = sizeof(diprg.diph); diprg.diph.dwHow = DIPH_BYOFFSET; diprg.lMin = -100; diprg.lMax = +100; DebugPrintf( "SetUpJoystickAxis: setting up %d axes for joystick #%d='%s'\n", JoystickInfo[ joystick ].NumAxis, joystick, JoystickInfo[ joystick ].Name ); if (JoystickInfo[joystick].Axis[AXIS_XAxis].exists) { DebugPrintf( "SetUpJoystickAxis: setting up X axis range=(%d,%d) for joystick #%d='%s'\n", diprg.lMin, diprg.lMax, joystick, JoystickInfo[ joystick ].Name ); diprg.diph.dwObj = DIJOFS_X; if(lpdiJoystick[joystick]->lpVtbl->SetProperty(lpdiJoystick[joystick], DIPROP_RANGE, &diprg.diph) != DI_OK) { JoystickInfo[joystick].Axis[AXIS_XAxis].exists = FALSE; // cannot set range, therefore do not allow axis DebugPrintf( "SetUpJoystickAxis: failed to set range for X axis\n" ); }else { // set dead zone // Units are ten thousandths, so multiply %age by 100. DebugPrintf( "SetUpJoystickAxis: setting up X axis deadzone=%d for joystick #%d='%s'\n", JoystickInfo[ joystick ].Axis[AXIS_XAxis].deadzone, joystick, JoystickInfo[ joystick ].Name ); if (SetDIDwordProperty(lpdiJoystick[joystick], DIPROP_DEADZONE, DIJOFS_X, DIPH_BYOFFSET, (DWORD)(JoystickInfo[joystick].Axis[AXIS_XAxis].deadzone * 100)) != DI_OK) { // cannot set deadzone - but just ignore for now... DeadzoneNotSet = TRUE; DebugPrintf( "SetUpJoystickAxis: failed to set deadzone for X axis\n" ); } } } if (JoystickInfo[joystick].Axis[AXIS_YAxis].exists) { DebugPrintf( "SetUpJoystickAxis: setting up Y axis range=(%d,%d) for joystick #%d='%s'\n", diprg.lMin, diprg.lMax, joystick, JoystickInfo[ joystick ].Name ); diprg.diph.dwObj = DIJOFS_Y; if(lpdiJoystick[joystick]->lpVtbl->SetProperty(lpdiJoystick[joystick], DIPROP_RANGE, &diprg.diph) != DI_OK) { JoystickInfo[joystick].Axis[AXIS_YAxis].exists = FALSE; // cannot set range, therefore do not allow axis DebugPrintf( "SetUpJoystickAxis: failed to set range for Y axis\n" ); }else { DebugPrintf( "SetUpJoystickAxis: setting up Y axis deadzone=%d for joystick #%d='%s'\n", JoystickInfo[ joystick ].Axis[AXIS_YAxis].deadzone, joystick, JoystickInfo[ joystick ].Name ); if (SetDIDwordProperty(lpdiJoystick[joystick], DIPROP_DEADZONE, DIJOFS_Y, DIPH_BYOFFSET, (DWORD)(JoystickInfo[joystick].Axis[AXIS_YAxis].deadzone * 100)) != DI_OK) { // cannot set deadzone - but just ignore for now... DeadzoneNotSet = TRUE; DebugPrintf( "SetUpJoystickAxis: failed to set deadzone for Y axis\n" ); } } } if (JoystickInfo[joystick].Axis[AXIS_ZAxis].exists) { DebugPrintf( "SetUpJoystickAxis: setting up Z axis range=(%d,%d) for joystick #%d='%s'\n", diprg.lMin, diprg.lMax, joystick, JoystickInfo[ joystick ].Name ); diprg.diph.dwObj = DIJOFS_Z; if(lpdiJoystick[joystick]->lpVtbl->SetProperty(lpdiJoystick[joystick], DIPROP_RANGE, &diprg.diph) != DI_OK) { JoystickInfo[joystick].Axis[AXIS_ZAxis].exists = FALSE; // cannot set range, therefore do not allow axis DebugPrintf( "SetUpJoystickAxis: failed to set range for Z axis\n" ); }else { DebugPrintf( "SetUpJoystickAxis: setting up Z axis deadzone=%d for joystick #%d='%s'\n", JoystickInfo[ joystick ].Axis[AXIS_ZAxis].deadzone, joystick, JoystickInfo[ joystick ].Name ); if (SetDIDwordProperty(lpdiJoystick[joystick], DIPROP_DEADZONE, DIJOFS_Z, DIPH_BYOFFSET, (DWORD)(JoystickInfo[joystick].Axis[AXIS_ZAxis].deadzone * 100)) != DI_OK) { // cannot set deadzone - but just ignore for now... DeadzoneNotSet = TRUE; DebugPrintf( "SetUpJoystickAxis: failed to set deadzone for Z axis\n" ); } } } if (JoystickInfo[joystick].Axis[AXIS_RxAxis].exists) { DebugPrintf( "SetUpJoystickAxis: setting up Rx axis range=(%d,%d) for joystick #%d='%s'\n", diprg.lMin, diprg.lMax, joystick, JoystickInfo[ joystick ].Name ); diprg.diph.dwObj = DIJOFS_RX; if(lpdiJoystick[joystick]->lpVtbl->SetProperty(lpdiJoystick[joystick], DIPROP_RANGE, &diprg.diph) != DI_OK) { JoystickInfo[joystick].Axis[AXIS_RxAxis].exists = FALSE; // cannot set range, therefore do not allow axis DebugPrintf( "SetUpJoystickAxis: failed to set range for Rx axis\n" ); }else { DebugPrintf( "SetUpJoystickAxis: setting up Rx axis deadzone=%d for joystick #%d='%s'\n", JoystickInfo[ joystick ].Axis[AXIS_RxAxis].deadzone, joystick, JoystickInfo[ joystick ].Name ); if (SetDIDwordProperty(lpdiJoystick[joystick], DIPROP_DEADZONE, DIJOFS_RX, DIPH_BYOFFSET, (DWORD)(JoystickInfo[joystick].Axis[AXIS_RxAxis].deadzone * 100)) != DI_OK) { // cannot set deadzone - but just ignore for now... DeadzoneNotSet = TRUE; DebugPrintf( "SetUpJoystickAxis: failed to set deadzone for Rx axis\n" ); } } } if (JoystickInfo[joystick].Axis[AXIS_RyAxis].exists) { DebugPrintf( "SetUpJoystickAxis: setting up Ry axis range=(%d,%d) for joystick #%d='%s'\n", diprg.lMin, diprg.lMax, joystick, JoystickInfo[ joystick ].Name ); diprg.diph.dwObj = DIJOFS_RY; if(lpdiJoystick[joystick]->lpVtbl->SetProperty(lpdiJoystick[joystick], DIPROP_RANGE, &diprg.diph) != DI_OK) { JoystickInfo[joystick].Axis[AXIS_RyAxis].exists = FALSE; // cannot set range, therefore do not allow axis DebugPrintf( "SetUpJoystickAxis: failed to set range for Ry axis\n" ); }else { DebugPrintf( "SetUpJoystickAxis: setting up Ry axis deadzone=%d for joystick #%d='%s'\n", JoystickInfo[ joystick ].Axis[AXIS_RyAxis].deadzone, joystick, JoystickInfo[ joystick ].Name ); if (SetDIDwordProperty(lpdiJoystick[joystick], DIPROP_DEADZONE, DIJOFS_RY, DIPH_BYOFFSET, (DWORD)(JoystickInfo[joystick].Axis[AXIS_RyAxis].deadzone * 100)) != DI_OK) { // cannot set deadzone - but just ignore for now... DeadzoneNotSet = TRUE; DebugPrintf( "SetUpJoystickAxis: failed to set deadzone for Ry axis\n" ); } } } if (JoystickInfo[joystick].Axis[AXIS_RzAxis].exists) { DebugPrintf( "SetUpJoystickAxis: setting up Rz axis range=(%d,%d) for joystick #%d='%s'\n", diprg.lMin, diprg.lMax, joystick, JoystickInfo[ joystick ].Name ); diprg.diph.dwObj = DIJOFS_RZ; if(lpdiJoystick[joystick]->lpVtbl->SetProperty(lpdiJoystick[joystick], DIPROP_RANGE, &diprg.diph) != DI_OK) { JoystickInfo[joystick].Axis[AXIS_RzAxis].exists = FALSE; // cannot set range, therefore do not allow axis DebugPrintf( "SetUpJoystickAxis: failed to set range for Rz axis\n" ); }else { DebugPrintf( "SetUpJoystickAxis: setting up Rz axis deadzone=%d for joystick #%d='%s'\n", JoystickInfo[ joystick ].Axis[AXIS_RzAxis].deadzone, joystick, JoystickInfo[ joystick ].Name ); if (SetDIDwordProperty(lpdiJoystick[joystick], DIPROP_DEADZONE, DIJOFS_RZ, DIPH_BYOFFSET, (DWORD)(JoystickInfo[joystick].Axis[AXIS_RzAxis].deadzone * 100)) != DI_OK) { // cannot set deadzone - but just ignore for now... DeadzoneNotSet = TRUE; DebugPrintf( "SetUpJoystickAxis: failed to set deadzone for Rz axis\n" ); } } } for (i = 0; i < 2; i++) { if (JoystickInfo[joystick].Axis[AXIS_SliderAxis0 + i].exists) { DebugPrintf( "SetUpJoystickAxis: setting up Slider%d range=(%d,%d) for joystick #%d='%s'\n", i, diprg.lMin, diprg.lMax, joystick, JoystickInfo[ joystick ].Name ); diprg.diph.dwObj = DIJOFS_SLIDER(i); if(lpdiJoystick[joystick]->lpVtbl->SetProperty(lpdiJoystick[joystick], DIPROP_RANGE, &diprg.diph) != DI_OK) { JoystickInfo[joystick].Axis[AXIS_SliderAxis0 + i].exists = FALSE; // cannot set range, therefore do not allow axis DebugPrintf( "SetUpJoystickAxis: failed to set range for Slider%d axis\n", i ); }else { DebugPrintf( "SetUpJoystickAxis: setting up Slider%d deadzone=%d for joystick #%d='%s'\n", i, JoystickInfo[ joystick ].Axis[AXIS_SliderAxis0 + i].deadzone, joystick, JoystickInfo[ joystick ].Name ); if (SetDIDwordProperty(lpdiJoystick[joystick], DIPROP_DEADZONE, DIJOFS_SLIDER(i), DIPH_BYOFFSET, (DWORD)(JoystickInfo[joystick].Axis[AXIS_SliderAxis0 + i].deadzone * 100)) != DI_OK) { // cannot set deadzone - but just ignore for now... DeadzoneNotSet = TRUE; DebugPrintf( "SetUpJoystickAxis: failed to set deadzone for Slider%d axis\n", i ); } } } } // could do something about unset deadzones here... if (DeadzoneNotSet) DeadzoneNotSet = FALSE; } #define POV_UP 0 #define POV_RIGHT 9000 #define POV_DOWN 18000 #define POV_LEFT 27000 #define POV_RANGE 36000 #define POV_HALFRANGE 18000 #define POV_TOLERANCE 6750 // this gives 45 deg for each of 8 compass directions int GetPOVMask( DWORD pov ) { static DWORD POVDir[ MAX_POV_DIRECTIONS ] = { POV_UP, POV_DOWN, POV_LEFT, POV_RIGHT }; int mask; int dir; int dpov; mask = 0; if ( pov != 0xFFFF && pov != 0xFFFFFFFF ) { for ( dir = 0; dir < MAX_POV_DIRECTIONS; dir++ ) { dpov = abs( pov - POVDir[ dir ] ); if ( dpov > POV_HALFRANGE ) dpov = POV_RANGE - dpov; if ( dpov <= POV_TOLERANCE ) mask |= ( 1 << dir ); } } return mask; } int GetPOVDirection( DIJOYSTATE2 *data, int POVNum ) { int dir; if (!((data->rgdwPOV[POVNum] == 65535) || (data->rgdwPOV[POVNum] == -1))) { dir = POV_Centre; if( data->rgdwPOV[POVNum] > 27000 || data->rgdwPOV[POVNum] < 9000 ) // up { dir |= POV_Up; } if( data->rgdwPOV[POVNum] > 9000 && data->rgdwPOV[POVNum] < 27000 ) // down { dir |= POV_Down; } if( data->rgdwPOV[POVNum] < 18000 && data->rgdwPOV[POVNum] > 0 ) // right { dir |= POV_Right; } if( data->rgdwPOV[POVNum] > 18000 ) // left { dir |= POV_Left; } return dir; }else return POV_Centre; } // returns the position of the least sig. bit... int BitPos (int flag) { int i = 0; int mask = 1; if (flag == 0) return 0; while (!(mask & flag)) { flag >>= 1; i++; } return i; } // returns TRUE if it is OK to repeat the given ship action static BOOL RepeatShipActionOK ( int action ) { switch (action) { case SHIPACTION_RotateUp: case SHIPACTION_RotateDown: case SHIPACTION_RotateLeft: case SHIPACTION_RotateRight: case SHIPACTION_RollLeft: case SHIPACTION_RollRight: case SHIPACTION_SlideUp: case SHIPACTION_SlideDown: case SHIPACTION_SlideLeft: case SHIPACTION_SlideRight: case SHIPACTION_MoveForward: case SHIPACTION_MoveBack: case SHIPACTION_Turbo: case SHIPACTION_FirePrimary: case SHIPACTION_FireSecondary: return TRUE; default: return FALSE; } } void ReadJoystickInput(SHIPCONTROL *ctrl, int joysticknum) { #ifndef SELF_PLAY int ShipAction, axis; float amount; LONG *axisptr[MAX_JOYSTICK_AXIS] = { &js[ new_input ][joysticknum].lX, &js[ new_input ][joysticknum].lY, &js[ new_input ][joysticknum].lZ, &js[ new_input ][joysticknum].lRx, &js[ new_input ][joysticknum].lRy, &js[ new_input ][joysticknum].lRz, &js[ new_input ][joysticknum].rglSlider[0], &js[ new_input ][joysticknum].rglSlider[1] }; JOYSTICKAXIS *joyaxis; if ( !JoystickInput ) { return; } if( !lpdiJoystick[joysticknum] ) return; for (axis = 0; axis < MAX_JOYSTICK_AXIS; axis++) { if ((JoystickInfo[joysticknum].Axis[axis].exists) && (*axisptr[axis])) { joyaxis = &JoystickInfo[ joysticknum ].Axis[ axis ]; ShipAction = joyaxis->action; if ( ShipAction != SHIPACTION_Nothing ) { amount = (float) *axisptr[ axis ] * joyaxis->sensitivity; if ( joyaxis->fine ) amount *= (float) fabs( amount ); if ( joyaxis->inverted ) amount = -amount; DoShipAction( ctrl, ShipAction, framelag * amount ); } } } #endif } /*------------------------------------------------------------------- Procedure : Check if any buttons of a specific joystick are : pressed Input : int Joystick Number Output : BOOL TRUE/FALSE -------------------------------------------------------------------*/ BOOL IsJoystickButtonPressed( int joysticknum ) { int i; if( !lpdiJoystick[joysticknum] ) return( FALSE ); for( i = 0; i < JoystickInfo[joysticknum].NumButtons; i++) { if ( JOYSTICK_BUTTON_PRESSED( joysticknum, i ) ) { return( TRUE ); } } return( FALSE ); } /*------------------------------------------------------------------- Procedure : Check if any buttons of a specific joystick are : released Input : int Joystick Number Output : BOOL TRUE/FALSE -------------------------------------------------------------------*/ BOOL IsJoystickButtonReleased( int joysticknum ) { int i; if( !lpdiJoystick[joysticknum] ) return( FALSE ); for( i = 0; i < JoystickInfo[joysticknum].NumButtons; i++) { if ( JOYSTICK_BUTTON_RELEASED( joysticknum, i ) ) { return( TRUE ); } } return( FALSE ); } /*------------------------------------------------------------------- Procedure : Check if any buttons of a any connected joystick : are pressed Input : Nothing Output : BOOL TRUE/FALSE -------------------------------------------------------------------*/ BOOL IsAnyJoystickButtonPressed( void ) { int joystick; for (joystick = 0; joystick < Num_Joysticks; joystick++) { if( IsJoystickButtonPressed( joystick ) ) { return( TRUE ); } } return( FALSE ); } /*------------------------------------------------------------------- Procedure : Check if any buttons of a any connected joystick : are released Input : Nothing Output : BOOL TRUE/FALSE -------------------------------------------------------------------*/ BOOL IsAnyJoystickButtonReleased( void ) { int joystick; for (joystick = 0; joystick < Num_Joysticks; joystick++) { if( IsJoystickButtonReleased( joystick ) ) { return( TRUE ); } } return( FALSE ); }
28.218149
197
0.530701
[ "object", "vector" ]
264ecefa0f518209fe558d0e1d251ba692671ca2
2,171
h
C
source/userial/owproto.h
mieskolainen/deltaBox-NILM
ef5ffa91164a420c4a9ee689a338425547fdbdb1
[ "MIT" ]
57
2015-10-26T12:10:19.000Z
2022-01-11T19:29:02.000Z
source/userial/owproto.h
mieskolainen/deltaBox-NILM
ef5ffa91164a420c4a9ee689a338425547fdbdb1
[ "MIT" ]
24
2016-12-31T12:42:18.000Z
2021-05-15T17:11:28.000Z
source/userial/owproto.h
mieskolainen/deltaBox-NILM
ef5ffa91164a420c4a9ee689a338425547fdbdb1
[ "MIT" ]
15
2016-05-14T19:19:12.000Z
2021-04-27T16:16:34.000Z
/* Prototypes for userial driver functions */ /* From other low level userial files */ SMALLINT owAccess(int); #ifndef OWUSB SMALLINT owAcquire(int,char *); #else SMALLINT owAcquire(int,char *, char *); #endif /* OWUSB */ void owSerialNum(int,uchar *,SMALLINT); SMALLINT owWriteBytePower(int,SMALLINT); SMALLINT owWriteByte(int,SMALLINT); SMALLINT owReadByte(int); SMALLINT owLevel(int,SMALLINT); void msDelay(int); SMALLINT owBlock(int,SMALLINT,uchar *,SMALLINT); SMALLINT owTouchReset(int); #ifndef OWUSB void owRelease(int); #else void owRelease(int, char *); #endif /* OWUSB */ SMALLINT owFirst(int,SMALLINT,SMALLINT); SMALLINT owNext(int,SMALLINT,SMALLINT); /* From owerr.c */ int owGetErrorNum(void); void owClearError(void); int owHasErrors(void); #ifdef DEBUG void owRaiseError(int,int,char*); #else void owRaiseError(int); #endif #ifndef SMALL_MEMORY_TARGET void owPrintErrorMsg(FILE *); void owPrintErrorMsgStd(); char *owGetErrorMsg(int); #endif /* From ioutil.c */ int EnterString(char *, char *, int, int); int EnterNum(char *, int, long *, long, long); int EnterHex(char *, int, ulong *); int ToHex(char ch); int getkeystroke(void); int key_abort(void); void ExitProg(char *, int); int getData(uchar*, int, SMALLINT); void PrintHex(uchar*, int); void PrintChars(uchar*, int); void PrintSerialNum(uchar*); /* From crcutil.c */ void setcrc16(int,ushort); ushort docrc16(int,ushort); void setcrc8(int,uchar); uchar docrc8(int,uchar); /* From swt1f.c */ int SetSwitch1F(int,uchar *,int,int,uchar *,int); int SwitchStateToString1F(int, char *); int FindBranchDevice(int,uchar *,uchar BranchSN[][8],int,int); int owBranchFirst(int,uchar *,int,int); int owBranchNext(int,uchar *,int,int); /* From cnt1d.c */ SMALLINT ReadCounter(int,int,ulong *); /* From ad26.c */ double Get_Temperature(int portnum); float Volt_Reading(int portnum, int vdd, int *cad); int PIO_Reading(int portnum, int pionum /* TS ignored so far */ ); /* From XXXlnk.c */ SMALLINT owTouchBit(int,SMALLINT); SMALLINT owSpeed(int,SMALLINT); SMALLINT owTouchByte(int portnum, SMALLINT sendbyte); SMALLINT owProgramPulse(int portnum);
24.122222
66
0.723169
[ "cad" ]
265f65538c46e203e6a81eaee53a7304db8d8ac0
4,773
h
C
RedvsBlue/Dijkstra.h
JSeneque/AIE_AI_Project
f84530e4f5febf0ba2a321e1672251f6791585f9
[ "MIT" ]
null
null
null
RedvsBlue/Dijkstra.h
JSeneque/AIE_AI_Project
f84530e4f5febf0ba2a321e1672251f6791585f9
[ "MIT" ]
null
null
null
RedvsBlue/Dijkstra.h
JSeneque/AIE_AI_Project
f84530e4f5febf0ba2a321e1672251f6791585f9
[ "MIT" ]
null
null
null
#pragma once #include <unordered_set> #include "Graph.h" #include <vector> #include <algorithm> std::list<const Node*> ShowMovementArea(Node* startNode) { // validate the passed node if (!startNode) { throw std::runtime_error("Null nodes passed in!"); } // initialise the starting node startNode->runningCost = 0.0f; startNode->parent = nullptr; // create temporary lists for storing nodes that are visiting/visited //std::vector<Node*> openList; //std::unordered_set<const Node*> closedList; std::list<Node*> openList; std::list<const Node*> closedList; // add the start node to the open list openList.push_back(startNode); // process while the open list is not empty while (!openList.empty()) { // let the current node be the first item in the open list Node* currentNode = openList.front(); // remove the current node from the open list openList.erase(openList.begin()); // add current node to the closed list closedList.push_back(currentNode); // for all the connections in the current node out to the destination for (auto& edge : currentNode->outgoingEdges) { // check the destination is not in the closed list if (std::find(closedList.begin(), closedList.end(), edge.destination) == closedList.end()) { // calculate the score and update its parent float runningCost = currentNode->runningCost + edge.weight; // check the destination is not in the open list if (std::find(openList.begin(), openList.end(), edge.destination) == openList.end()) { edge.destination->runningCost = runningCost; edge.destination->parent = currentNode; openList.push_back(edge.destination); } else if (runningCost < edge.destination->runningCost) { edge.destination->runningCost = runningCost; edge.destination->parent = currentNode; } } } } return closedList; } std::list<const Node*> DijkstraSearch(Node* startNode, Node* endNode) { // validate the passed nodes if (!startNode || !endNode) { throw std::runtime_error("Null nodes passed in!"); } if (startNode == endNode) { return std::list<const Node*>(); } // initialise the starting node startNode->runningCost = 0.0f; startNode->parent = nullptr; // create temporary lists for storing nodes that are visiting/visited std::vector<Node*> openList; std::unordered_set<const Node*> closedList; // add the start node to the open list openList.push_back(startNode); // process while the open list is not empty while (!openList.empty()) { // sorting by auto sortNodes = [](const Node* a, const Node* b) { return a->runningCost < b->runningCost; }; // sort open list by the node gScore (running cost) std::sort(openList.begin(), openList.end(), sortNodes); // let the current node be the first item in the open list Node* currentNode = openList.front(); // if the current node is the end node then exit loop if (currentNode == endNode) break; // remove the current node from the open list openList.erase(openList.begin()); // add current node to the closed list closedList.insert(currentNode); // for all the connections in the current node out to the destination for (auto& edge : currentNode->outgoingEdges) { // check the destination is not in the closed list if (std::find(closedList.begin(), closedList.end(), edge.destination) == closedList.end()) { // calculate the score and update its parent float runningCost = currentNode->runningCost + edge.weight; // check the destination is not in the open list if (std::find(openList.begin(), openList.end(), edge.destination) == openList.end()) { edge.destination->runningCost = runningCost; edge.destination->parent = currentNode; openList.push_back(edge.destination); } else if ( runningCost < edge.destination->runningCost) { edge.destination->runningCost = runningCost; edge.destination->parent = currentNode; } } } } // create a path in reverse from the end node to the start node std::list<const Node*> path; Node* current_Node = endNode; if (!endNode->parent) return path; while (current_Node) { path.push_front(current_Node); current_Node = current_Node->parent; } return path; } std::list<const Node*> BreadthFirstSearch(Node* startNode) { // validate the passed node if (!startNode) { throw std::runtime_error("Null nodes passed in!"); } // initialise the starting node startNode->runningCost = 0.0f; startNode->parent = nullptr; std::list<Node*> openList; std::list<const Node*> closedList; // add the start node to the open list openList.push_back(startNode); // process while the open list is not empty while (!openList.empty()) { } return closedList; }
25.66129
94
0.694741
[ "vector" ]
2662ce79b5295c6d84a5a3d397a8b0fe9ee8840c
251
h
C
Arrt/View/ModelEditor/MaterialEditor/MaterialsList.h
AleksandarTomicMs2/azure-remote-rendering-asset-tool
c3962231e02af6ff90c2867f51e7a3b20af8c592
[ "MIT" ]
42
2020-06-12T19:10:52.000Z
2022-03-04T02:20:59.000Z
Arrt/View/ModelEditor/MaterialEditor/MaterialsList.h
AleksandarTomicMs2/azure-remote-rendering-asset-tool
c3962231e02af6ff90c2867f51e7a3b20af8c592
[ "MIT" ]
91
2020-06-12T12:10:46.000Z
2022-03-02T13:46:00.000Z
Arrt/View/ModelEditor/MaterialEditor/MaterialsList.h
AleksandarTomicMs2/azure-remote-rendering-asset-tool
c3962231e02af6ff90c2867f51e7a3b20af8c592
[ "MIT" ]
10
2020-07-29T21:19:14.000Z
2021-09-22T11:48:27.000Z
#pragma once #include <QWidget> class ModelEditorModel; // Panel used to show a list of materials in a ModelEditorModel class MaterialListView : public QWidget { public: MaterialListView(ModelEditorModel* model, QWidget* parent = nullptr); };
17.928571
73
0.76494
[ "model" ]
26707a78faabbdc586aee79dfc675c922932c52a
1,689
h
C
Code/Editor/Util/XmlArchive.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Editor/Util/XmlArchive.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Editor/Util/XmlArchive.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ // Description : Stores XML in MFC archive. #ifndef CRYINCLUDE_EDITOR_UTIL_XMLARCHIVE_H #define CRYINCLUDE_EDITOR_UTIL_XMLARCHIVE_H #pragma once #include "NamedData.h" #include "EditorUtils.h" class CPakFile; /*! * CXmlArcive used to stores XML in MFC archive. */ class CXmlArchive { public: XmlNodeRef root; CNamedData* pNamedData; bool bLoading; bool bOwnNamedData; CXmlArchive() { bLoading = false; bOwnNamedData = true; pNamedData = new CNamedData; }; explicit CXmlArchive(const QString& xmlRoot) { bLoading = false; bOwnNamedData = true; pNamedData = new CNamedData; root = XmlHelpers::CreateXmlNode(xmlRoot.toUtf8().data()); }; ~CXmlArchive() { if (bOwnNamedData) { delete pNamedData; } }; CXmlArchive(const CXmlArchive& ar) { *this = ar; } CXmlArchive& operator=(const CXmlArchive& ar) { root = ar.root; pNamedData = ar.pNamedData; bLoading = ar.bLoading; bOwnNamedData = false; return *this; } bool Load(const QString& file); void Save(const QString& file); //! Save XML Archive to pak file. //! @return true if saved. bool SaveToPak(const QString& levelPath, CPakFile& pakFile); bool LoadFromPak(const QString& levelPath, CPakFile& pakFile); }; #endif // CRYINCLUDE_EDITOR_UTIL_XMLARCHIVE_H
23.136986
158
0.636471
[ "3d" ]
267384a077c0d9dbc7955b31122699be17193020
4,167
h
C
NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/csrc/cuda/nhwc.h
mengkai94/training_results_v0.6
43dc3e250f8da47b5f8833197d74cb8cf1004fc9
[ "Apache-2.0" ]
180
2018-09-20T07:27:40.000Z
2022-03-19T07:55:42.000Z
NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/csrc/cuda/nhwc.h
mengkai94/training_results_v0.6
43dc3e250f8da47b5f8833197d74cb8cf1004fc9
[ "Apache-2.0" ]
80
2018-09-26T18:55:56.000Z
2022-02-10T02:03:26.000Z
NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/csrc/cuda/nhwc.h
mengkai94/training_results_v0.6
43dc3e250f8da47b5f8833197d74cb8cf1004fc9
[ "Apache-2.0" ]
72
2018-08-30T00:49:15.000Z
2022-02-15T23:22:40.000Z
/** * Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <torch/extension.h> #ifndef _nhwc_h_ #define _nhwc_h_ namespace at { namespace native { namespace nhwc { // NHWC conv // fprop (X, W) -> Y at::Tensor cudnnNhwcToNchw(const at::Tensor& input); at::Tensor cudnnNchwToNhwc(const at::Tensor& input); at::Tensor cudnn_convolution_nhwc( const at::Tensor& input_t, const at::Tensor& weight_t, std::vector<long> padding, std::vector<long> stride, std::vector<long> dilation, int64_t groups, bool benchmark, bool deterministic); // fprop (X, W, b) -> Y at::Tensor cudnn_convolution_with_bias_nhwc( const at::Tensor& input_t, const at::Tensor& weight_t, const at::Tensor& bias_t, std::vector<long> padding, std::vector<long> stride, std::vector<long> dilation, int64_t groups, bool benchmark, bool deterministic); // bprop (X, dY, W) -> (dX, dW) std::tuple<at::Tensor,at::Tensor> cudnn_convolution_backward_nhwc( const at::Tensor& input, const at::Tensor& grad_output_t, const at::Tensor& weight, std::vector<long> padding, std::vector<long> stride, std::vector<long> dilation, int64_t groups, bool benchmark, bool deterministic, std::array<bool,2> output_mask); // bprop (X, dY, W) -> (dX, dW, db) std::tuple<at::Tensor,at::Tensor,at::Tensor> cudnn_convolution_backward_with_bias_nhwc( const at::Tensor& input, const at::Tensor& grad_output_t, const at::Tensor& weight, std::vector<long> padding, std::vector<long> stride, std::vector<long> dilation, int64_t groups, bool benchmark, bool deterministic, std::array<bool,3> output_mask); std::tuple<at::Tensor,at::Tensor,at::Tensor> cudnn_convolution_transpose_backward_with_bias_nhwc( const at::Tensor& input, const at::Tensor& grad_output_t, const at::Tensor& weight, std::vector<long> padding, std::vector<long> output_padding, std::vector<long> stride, std::vector<long> dilation, int64_t groups, bool benchmark, bool deterministic, std::array<bool,3> output_mask); std::tuple<at::Tensor,at::Tensor> cudnn_convolution_transpose_backward_nhwc( const at::Tensor& input, const at::Tensor& grad_output_t, const at::Tensor& weight, std::vector<long> padding, std::vector<long> output_padding, std::vector<long> stride, std::vector<long> dilation, int64_t groups, bool benchmark, bool deterministic, std::array<bool,3> output_mask); at::Tensor cudnn_convolution_transpose_nhwc( const at::Tensor& input_t, const at::Tensor& weight_t, std::vector<long> padding, std::vector<long> output_padding, std::vector<long> stride, std::vector<long> dilation, int64_t groups, bool benchmark, bool deterministic); at::Tensor cudnn_convolution_transpose_with_bias_nhwc( const at::Tensor& input_t, const at::Tensor& weight_t, const at::Tensor& bias_t, std::vector<long> padding, std::vector<long> output_padding, std::vector<long> stride, std::vector<long> dilation, int64_t groups, bool benchmark, bool deterministic); }}} // NHWC MaxPool at::Tensor max_pool_nhwc_fwd( const at::Tensor& x, const int kernel, const int stride, const int padding, const int dilation); at::Tensor max_pool_nhwc_bwd(const at::Tensor& x, const at::Tensor& y, const at::Tensor& grad_y, const int kernel, const int stride, const int padding, const int dilation); #endif
50.817073
134
0.687545
[ "vector" ]
b7dbf5237d3480cd9670911da4204919ffb33269
14,082
h
C
Tudat/Mathematics/BasicMathematics/leastSquaresEstimation.h
ViktorJordanov/tudat
069ceeab8f12405c356e19f50d6df037914df85c
[ "BSD-3-Clause" ]
null
null
null
Tudat/Mathematics/BasicMathematics/leastSquaresEstimation.h
ViktorJordanov/tudat
069ceeab8f12405c356e19f50d6df037914df85c
[ "BSD-3-Clause" ]
null
null
null
Tudat/Mathematics/BasicMathematics/leastSquaresEstimation.h
ViktorJordanov/tudat
069ceeab8f12405c356e19f50d6df037914df85c
[ "BSD-3-Clause" ]
null
null
null
<<<<<<< HEAD /* Copyright (c) 2010-2018, Delft University of Technology ======= /* Copyright (c) 2010-2019, Delft University of Technology >>>>>>> origin/master * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. * * References: * Madsen, K., Nielsen, H., and Tingleff, O., Methods for Non-Linear Least Squares Problems, 2nd ed., * Technical University of Denmark, Faculty of Informatics and Mathematical Modelling, April 2004. */ #ifndef TUDAT_LEASTSQUARESESTIMATION_H #define TUDAT_LEASTSQUARESESTIMATION_H #include <map> #include <Eigen/Core> #include <Eigen/SVD> #include <boost/function.hpp> namespace tudat { namespace linear_algebra { //! Function to get condition number of matrix (using SVD decomposition) /*! * Function to get condition number of matrix (using SVD decomposition) * \param informationMatrix Matrix for which condition number is to be computed * \return Condition number of matrix */ double getConditionNumberOfInformationMatrix( const Eigen::MatrixXd informationMatrix ); //! Function to get condition number of matrix from SVD decomposition /*! * Function to get condition number of matrix from SVD decomposition * \param singularValueDecomposition SVD decomposition of matrix * \return Condition number of matrix */ double getConditionNumberOfDecomposedMatrix( const Eigen::JacobiSVD< Eigen::MatrixXd >& singularValueDecomposition ); //! Solve system of equations with SVD decomposition, checking condition number in the process /*! * Solve system of equations with SVD decomposition, checking condition number in the process. This function solves * A*x = b for the vector x. * \param matrixToInvert Matrix A that is to be inverted to solve the equation * \param rightHandSideVector Vector on the righthandside of the matrix equation that is to be solved * \param checkConditionNumber Boolean to denote whether the condition number is checked when estimating (warning is printed * when value exceeds maximumAllowedConditionNumber) * \param maximumAllowedConditionNumber Maximum value of the condition number of the covariance matrix that is allowed * (warning printed when exceeded) * \return Solution x of matrix equation A*x=b */ Eigen::VectorXd solveSystemOfEquationsWithSvd( const Eigen::MatrixXd matrixToInvert, const Eigen::VectorXd rightHandSideVector, const bool checkConditionNumber = 1, const double maximumAllowedConditionNumber = 1.0E-8 ); //! Function to multiply information matrix by diagonal weights matrix /*! * Function to multiply information matrix by diagonal weights matrix * \param informationMatrix Matrix containing partial derivatives of observations (rows) w.r.t. estimated parameters * (columns) * \param diagonalOfWeightMatrix Diagonal of observation weights matrix (assumes all weights to be uncorrelated) * \return informationMatrix, premultiplied by square matrix with diagonalOfWeightMatrix as diagonal elements */ Eigen::MatrixXd multiplyInformationMatrixByDiagonalWeightMatrix( const Eigen::MatrixXd& informationMatrix, const Eigen::VectorXd& diagonalOfWeightMatrix ); //! Function to compute inverse of covariance matrix at current iteration, including influence of a priori information /*! * Function to compute inverse of covariance matrix at current iteration, including influence of a priori information * \param informationMatrix Matrix containing partial derivatives of observations (rows) w.r.t. estimated parameters * (columns) * \param diagonalOfWeightMatrix Diagonal of observation weights matrix (assumes all weights to be uncorrelated) * \param inverseOfAPrioriCovarianceMatrix Inverse of a priori covariance matrix * (warning printed when exceeded) * \return Inverse of covariance matrix at current iteration */ Eigen::MatrixXd calculateInverseOfUpdatedCovarianceMatrix( const Eigen::MatrixXd& informationMatrix, const Eigen::VectorXd& diagonalOfWeightMatrix, const Eigen::MatrixXd& inverseOfAPrioriCovarianceMatrix ); //! Function to compute inverse of covariance matrix at current iteration /*! * Function to compute inverse of covariance matrix at current iteration * \param informationMatrix Matrix containing partial derivatives of observations (rows) w.r.t. estimated parameters * (columns) * \param diagonalOfWeightMatrix Diagonal of observation weights matrix (assumes all weights to be uncorrelated) * \return Inverse of covariance matrix at current iteration */ Eigen::MatrixXd calculateInverseOfUpdatedCovarianceMatrix( const Eigen::MatrixXd& informationMatrix, const Eigen::VectorXd& diagonalOfWeightMatrix ); //! Function to perform an iteration least squares estimation from information matrix, weights and residuals and a priori //! information /*! * Function to perform an iteration least squares estimation from information matrix, weights and residuals and a priori * information, as is typically done in orbit determination. This function also takes an inverse if the a priori covariance * matrix to constrain/stabilize the inversion. * \param informationMatrix Matrix containing partial derivatives of observations (rows) w.r.t. estimated parameters * (columns) * \param observationResiduals Difference between measured and simulated observations * \param diagonalOfWeightMatrix Diagonal of observation weights matrix (assumes all weights to be uncorrelated) * \param inverseOfAPrioriCovarianceMatrix Inverse of a priori covariance matrix * (warning printed when exceeded) * \param checkConditionNumber Boolean to denote whether the condition number is checked when estimating (warning is printed * when value exceeds maximumAllowedConditionNumber) * \param maximumAllowedConditionNumber Maximum value of the condition number of the covariance matrix that is allowed * \param constraintMultiplier Multiplier for estimated parameter that defines linear constraint * \param constraintRightHandside Right-hand side estimation linear constraint * \return Pair containing: (first: parameter adjustment, second: inverse covariance) */ std::pair< Eigen::VectorXd, Eigen::MatrixXd > performLeastSquaresAdjustmentFromInformationMatrix( const Eigen::MatrixXd& informationMatrix, const Eigen::VectorXd& observationResiduals, const Eigen::VectorXd& diagonalOfWeightMatrix, const Eigen::MatrixXd& inverseOfAPrioriCovarianceMatrix, const bool checkConditionNumber = 1, const double maximumAllowedConditionNumber = 1.0E8, const Eigen::MatrixXd& constraintMultiplier = Eigen::MatrixXd( 0, 0 ), const Eigen::VectorXd& constraintRightHandside = Eigen::VectorXd( 0 ) ); //! Function to perform an iteration of least squares estimation from information matrix, weights and residuals /*! * Function to perform an iteration of least squares estimation from information matrix, weights and residuals, as is * typically done in orbit determination * \param informationMatrix Matrix containing partial derivatives of observations (rows) w.r.t. estimated parameters * (columns) * \param observationResiduals Difference between measured and simulated observations * \param diagonalOfWeightMatrix Diagonal of observation weights matrix (assumes all weights to be uncorrelated) * \param checkConditionNumber Boolean to denote whether the condition number is checked when estimating (warning is printed * when value exceeds maximumAllowedConditionNumber) * \param maximumAllowedConditionNumber Maximum value of the condition number of the covariance matrix that is allowed * (warning printed when exceeded) * \return Pair containing: (first: parameter adjustment, second: inverse covariance) */ std::pair< Eigen::VectorXd, Eigen::MatrixXd > performLeastSquaresAdjustmentFromInformationMatrix( const Eigen::MatrixXd& informationMatrix, const Eigen::VectorXd& observationResiduals, const Eigen::VectorXd& diagonalOfWeightMatrix, const bool checkConditionNumber = 1, const double maximumAllowedConditionNumber = 1.0E8 ); //! Function to perform an iteration of least squares estimation from information matrix and residuals /*! * Function to perform an iteration of least squares estimation from information matrix and residuals, with all weights * fixed to 1.0. * \param informationMatrix Matrix containing partial derivatives of observations (rows) w.r.t. estimated parameters * (columns) * \param observationResiduals Difference between measured and simulated observations * \param checkConditionNumber Boolean to denote whether the condition number is checked when estimating (warning is printed * when value exceeds maximumAllowedConditionNumber) * \param maximumAllowedConditionNumber Maximum value of the condition number of the covariance matrix that is allowed * (warning printed when exceeded) * \return Pair containing: (first: parameter adjustment, second: inverse covariance) */ std::pair< Eigen::VectorXd, Eigen::MatrixXd > performLeastSquaresAdjustmentFromInformationMatrix( const Eigen::MatrixXd& informationMatrix, const Eigen::VectorXd& observationResiduals, const bool checkConditionNumber = 1, const double maximumAllowedConditionNumber = 1.0E8 ); //! Function to fit a univariate polynomial through a set of data /*! * Function to fit a univariate polynomial through a set of data. User must provide independent variables and observations * (dependent variables), as well as a list of polynomial powers for which the coefficients are to be estimated. * \param independentValues Independent variables of input data (e.g. time for observations as a function fo time). This * variable becomes the polynomial argument. * \param dependentValues Observations through which the polynomial is to be fitted, with entries defined at the * corresponding entries of independentValues * \param polynomialPowers List of powers of indepent variables for which coefficients are to be estimated. * \return Coefficients of the polynomial powers, as estimated from the input data (in same order as polynomialPowers). */ Eigen::VectorXd getLeastSquaresPolynomialFit( const Eigen::VectorXd& independentValues, const Eigen::VectorXd& dependentValues, const std::vector< double >& polynomialPowers ); //! Function to fit a univariate polynomial through a set of data /*! * Function to fit a univariate polynomial through a set of data. User must provide independent variables and observations * (dependent variables), as well as a list of polynomial powers for which the coefficients are to be estimated. * \param independentDependentValueMap Map with key: independent variables of input data (e.g. time for observations as a * function fo time), this variable becomes the polynomial argument. Map value: Observations through which the polynomial * is to be fitted. * \param polynomialPowers List of powers of indepent variables for which coefficients are to be estimated. * \return Coefficients of the polynomial powers, as estimated from the input data (in same order as polynomialPowers). */ std::vector< double > getLeastSquaresPolynomialFit( const std::map< double, double >& independentDependentValueMap, const std::vector< double >& polynomialPowers ); //! Function to perform a non-linear least squares estimation with the Levenberg-Marquardt method. /*! * Function to perform a non-linear least squares estimation. The non-linear least squares method is an iterative * process, which uses the information from the actual and estimated observations, to estimate the model parameters, with * the aid of a design matrix. The initial estimate of the model parameters is updated every iteration with the result of the * least squares equation. The iterative process is halted whenever the norm of the update is below the user-provided * threshold or when the maximum number of iterations is reached. The method used in this application is the Levenberg-Marquardt * method, which uses a damping parameter \f$ \lambda \f$ to make the iterative process more stable and accurate. * The reference for this implementation is (Madsen, K., et al.). * \param observationAndJacobianFunctions Function returning a pair of expected observations and Jacobian of the * observation function w.r.t. the model parameters (i.e., the design matrix), where the input is the current estimate * of the model parameters. * \param initialEstimate Initial estimate of the model parameters. * \param actualObservations Vector containing the actual observations that need to be fitted by the model. * \param initialScaling Double denoting the multiplicative factor to determine the damping parameter during the first iteration. * \param convergenceTolerance Double denoting the convergence criterion for the norm of the update vector. * \param maximumNumberOfIterations Integer denoting the maximum number of iterations. * \return Optimal value of the model parameters that minimize the least squares error between expected and actual observations. */ Eigen::VectorXd nonLinearLeastSquaresFit( const std::function< std::pair< Eigen::VectorXd, Eigen::MatrixXd >( const Eigen::VectorXd& ) >& observationAndJacobianFunctions, const Eigen::VectorXd& initialEstimate, const Eigen::VectorXd& actualObservations, const double initialScaling = 1.0e-6, const double convergenceTolerance = 1.0e-8, const unsigned int maximumNumberOfIterations = 25 ); } // namespace linear_algebra } // namespace tudat #endif // TUDAT_LEASTSQUARESESTIMATION_H
59.923404
136
0.7756
[ "vector", "model" ]
b7dcb0e959b2cc574ed822f97f05835f6aa82ed7
19,065
h
C
cls/include/tencentcloud/cls/v20201016/model/ConfigExtraInfo.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
cls/include/tencentcloud/cls/v20201016/model/ConfigExtraInfo.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
cls/include/tencentcloud/cls/v20201016/model/ConfigExtraInfo.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_CLS_V20201016_MODEL_CONFIGEXTRAINFO_H_ #define TENCENTCLOUD_CLS_V20201016_MODEL_CONFIGEXTRAINFO_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/cls/v20201016/model/HostFileInfo.h> #include <tencentcloud/cls/v20201016/model/ContainerFileInfo.h> #include <tencentcloud/cls/v20201016/model/ContainerStdoutInfo.h> #include <tencentcloud/cls/v20201016/model/ExtractRuleInfo.h> #include <tencentcloud/cls/v20201016/model/ExcludePathInfo.h> namespace TencentCloud { namespace Cls { namespace V20201016 { namespace Model { /** * 特殊采集规则配置信息 */ class ConfigExtraInfo : public AbstractModel { public: ConfigExtraInfo(); ~ConfigExtraInfo() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取采集规则扩展配置ID * @return ConfigExtraId 采集规则扩展配置ID */ std::string GetConfigExtraId() const; /** * 设置采集规则扩展配置ID * @param ConfigExtraId 采集规则扩展配置ID */ void SetConfigExtraId(const std::string& _configExtraId); /** * 判断参数 ConfigExtraId 是否已赋值 * @return ConfigExtraId 是否已赋值 */ bool ConfigExtraIdHasBeenSet() const; /** * 获取采集规则名称 * @return Name 采集规则名称 */ std::string GetName() const; /** * 设置采集规则名称 * @param Name 采集规则名称 */ void SetName(const std::string& _name); /** * 判断参数 Name 是否已赋值 * @return Name 是否已赋值 */ bool NameHasBeenSet() const; /** * 获取日志主题ID * @return TopicId 日志主题ID */ std::string GetTopicId() const; /** * 设置日志主题ID * @param TopicId 日志主题ID */ void SetTopicId(const std::string& _topicId); /** * 判断参数 TopicId 是否已赋值 * @return TopicId 是否已赋值 */ bool TopicIdHasBeenSet() const; /** * 获取类型:container_stdout、container_file、host_file * @return Type 类型:container_stdout、container_file、host_file */ std::string GetType() const; /** * 设置类型:container_stdout、container_file、host_file * @param Type 类型:container_stdout、container_file、host_file */ void SetType(const std::string& _type); /** * 判断参数 Type 是否已赋值 * @return Type 是否已赋值 */ bool TypeHasBeenSet() const; /** * 获取节点文件配置信息 注意:此字段可能返回 null,表示取不到有效值。 * @return HostFile 节点文件配置信息 注意:此字段可能返回 null,表示取不到有效值。 */ HostFileInfo GetHostFile() const; /** * 设置节点文件配置信息 注意:此字段可能返回 null,表示取不到有效值。 * @param HostFile 节点文件配置信息 注意:此字段可能返回 null,表示取不到有效值。 */ void SetHostFile(const HostFileInfo& _hostFile); /** * 判断参数 HostFile 是否已赋值 * @return HostFile 是否已赋值 */ bool HostFileHasBeenSet() const; /** * 获取容器文件路径信息 注意:此字段可能返回 null,表示取不到有效值。 * @return ContainerFile 容器文件路径信息 注意:此字段可能返回 null,表示取不到有效值。 */ ContainerFileInfo GetContainerFile() const; /** * 设置容器文件路径信息 注意:此字段可能返回 null,表示取不到有效值。 * @param ContainerFile 容器文件路径信息 注意:此字段可能返回 null,表示取不到有效值。 */ void SetContainerFile(const ContainerFileInfo& _containerFile); /** * 判断参数 ContainerFile 是否已赋值 * @return ContainerFile 是否已赋值 */ bool ContainerFileHasBeenSet() const; /** * 获取容器标准输出信息 注意:此字段可能返回 null,表示取不到有效值。 * @return ContainerStdout 容器标准输出信息 注意:此字段可能返回 null,表示取不到有效值。 */ ContainerStdoutInfo GetContainerStdout() const; /** * 设置容器标准输出信息 注意:此字段可能返回 null,表示取不到有效值。 * @param ContainerStdout 容器标准输出信息 注意:此字段可能返回 null,表示取不到有效值。 */ void SetContainerStdout(const ContainerStdoutInfo& _containerStdout); /** * 判断参数 ContainerStdout 是否已赋值 * @return ContainerStdout 是否已赋值 */ bool ContainerStdoutHasBeenSet() const; /** * 获取日志格式化方式 注意:此字段可能返回 null,表示取不到有效值。 * @return LogFormat 日志格式化方式 注意:此字段可能返回 null,表示取不到有效值。 */ std::string GetLogFormat() const; /** * 设置日志格式化方式 注意:此字段可能返回 null,表示取不到有效值。 * @param LogFormat 日志格式化方式 注意:此字段可能返回 null,表示取不到有效值。 */ void SetLogFormat(const std::string& _logFormat); /** * 判断参数 LogFormat 是否已赋值 * @return LogFormat 是否已赋值 */ bool LogFormatHasBeenSet() const; /** * 获取采集的日志类型,json_log代表json格式日志,delimiter_log代表分隔符格式日志,minimalist_log代表极简日志,multiline_log代表多行日志,fullregex_log代表完整正则,默认为minimalist_log 注意:此字段可能返回 null,表示取不到有效值。 * @return LogType 采集的日志类型,json_log代表json格式日志,delimiter_log代表分隔符格式日志,minimalist_log代表极简日志,multiline_log代表多行日志,fullregex_log代表完整正则,默认为minimalist_log 注意:此字段可能返回 null,表示取不到有效值。 */ std::string GetLogType() const; /** * 设置采集的日志类型,json_log代表json格式日志,delimiter_log代表分隔符格式日志,minimalist_log代表极简日志,multiline_log代表多行日志,fullregex_log代表完整正则,默认为minimalist_log 注意:此字段可能返回 null,表示取不到有效值。 * @param LogType 采集的日志类型,json_log代表json格式日志,delimiter_log代表分隔符格式日志,minimalist_log代表极简日志,multiline_log代表多行日志,fullregex_log代表完整正则,默认为minimalist_log 注意:此字段可能返回 null,表示取不到有效值。 */ void SetLogType(const std::string& _logType); /** * 判断参数 LogType 是否已赋值 * @return LogType 是否已赋值 */ bool LogTypeHasBeenSet() const; /** * 获取提取规则,如果设置了ExtractRule,则必须设置LogType 注意:此字段可能返回 null,表示取不到有效值。 * @return ExtractRule 提取规则,如果设置了ExtractRule,则必须设置LogType 注意:此字段可能返回 null,表示取不到有效值。 */ ExtractRuleInfo GetExtractRule() const; /** * 设置提取规则,如果设置了ExtractRule,则必须设置LogType 注意:此字段可能返回 null,表示取不到有效值。 * @param ExtractRule 提取规则,如果设置了ExtractRule,则必须设置LogType 注意:此字段可能返回 null,表示取不到有效值。 */ void SetExtractRule(const ExtractRuleInfo& _extractRule); /** * 判断参数 ExtractRule 是否已赋值 * @return ExtractRule 是否已赋值 */ bool ExtractRuleHasBeenSet() const; /** * 获取采集黑名单路径列表 注意:此字段可能返回 null,表示取不到有效值。 * @return ExcludePaths 采集黑名单路径列表 注意:此字段可能返回 null,表示取不到有效值。 */ std::vector<ExcludePathInfo> GetExcludePaths() const; /** * 设置采集黑名单路径列表 注意:此字段可能返回 null,表示取不到有效值。 * @param ExcludePaths 采集黑名单路径列表 注意:此字段可能返回 null,表示取不到有效值。 */ void SetExcludePaths(const std::vector<ExcludePathInfo>& _excludePaths); /** * 判断参数 ExcludePaths 是否已赋值 * @return ExcludePaths 是否已赋值 */ bool ExcludePathsHasBeenSet() const; /** * 获取更新时间 * @return UpdateTime 更新时间 */ std::string GetUpdateTime() const; /** * 设置更新时间 * @param UpdateTime 更新时间 */ void SetUpdateTime(const std::string& _updateTime); /** * 判断参数 UpdateTime 是否已赋值 * @return UpdateTime 是否已赋值 */ bool UpdateTimeHasBeenSet() const; /** * 获取创建时间 * @return CreateTime 创建时间 */ std::string GetCreateTime() const; /** * 设置创建时间 * @param CreateTime 创建时间 */ void SetCreateTime(const std::string& _createTime); /** * 判断参数 CreateTime 是否已赋值 * @return CreateTime 是否已赋值 */ bool CreateTimeHasBeenSet() const; /** * 获取用户自定义解析字符串 注意:此字段可能返回 null,表示取不到有效值。 * @return UserDefineRule 用户自定义解析字符串 注意:此字段可能返回 null,表示取不到有效值。 */ std::string GetUserDefineRule() const; /** * 设置用户自定义解析字符串 注意:此字段可能返回 null,表示取不到有效值。 * @param UserDefineRule 用户自定义解析字符串 注意:此字段可能返回 null,表示取不到有效值。 */ void SetUserDefineRule(const std::string& _userDefineRule); /** * 判断参数 UserDefineRule 是否已赋值 * @return UserDefineRule 是否已赋值 */ bool UserDefineRuleHasBeenSet() const; /** * 获取机器组ID * @return GroupId 机器组ID */ std::string GetGroupId() const; /** * 设置机器组ID * @param GroupId 机器组ID */ void SetGroupId(const std::string& _groupId); /** * 判断参数 GroupId 是否已赋值 * @return GroupId 是否已赋值 */ bool GroupIdHasBeenSet() const; /** * 获取自建采集配置标 注意:此字段可能返回 null,表示取不到有效值。 * @return ConfigFlag 自建采集配置标 注意:此字段可能返回 null,表示取不到有效值。 */ std::string GetConfigFlag() const; /** * 设置自建采集配置标 注意:此字段可能返回 null,表示取不到有效值。 * @param ConfigFlag 自建采集配置标 注意:此字段可能返回 null,表示取不到有效值。 */ void SetConfigFlag(const std::string& _configFlag); /** * 判断参数 ConfigFlag 是否已赋值 * @return ConfigFlag 是否已赋值 */ bool ConfigFlagHasBeenSet() const; /** * 获取日志集ID 注意:此字段可能返回 null,表示取不到有效值。 * @return LogsetId 日志集ID 注意:此字段可能返回 null,表示取不到有效值。 */ std::string GetLogsetId() const; /** * 设置日志集ID 注意:此字段可能返回 null,表示取不到有效值。 * @param LogsetId 日志集ID 注意:此字段可能返回 null,表示取不到有效值。 */ void SetLogsetId(const std::string& _logsetId); /** * 判断参数 LogsetId 是否已赋值 * @return LogsetId 是否已赋值 */ bool LogsetIdHasBeenSet() const; /** * 获取日志集name 注意:此字段可能返回 null,表示取不到有效值。 * @return LogsetName 日志集name 注意:此字段可能返回 null,表示取不到有效值。 */ std::string GetLogsetName() const; /** * 设置日志集name 注意:此字段可能返回 null,表示取不到有效值。 * @param LogsetName 日志集name 注意:此字段可能返回 null,表示取不到有效值。 */ void SetLogsetName(const std::string& _logsetName); /** * 判断参数 LogsetName 是否已赋值 * @return LogsetName 是否已赋值 */ bool LogsetNameHasBeenSet() const; /** * 获取日志主题name 注意:此字段可能返回 null,表示取不到有效值。 * @return TopicName 日志主题name 注意:此字段可能返回 null,表示取不到有效值。 */ std::string GetTopicName() const; /** * 设置日志主题name 注意:此字段可能返回 null,表示取不到有效值。 * @param TopicName 日志主题name 注意:此字段可能返回 null,表示取不到有效值。 */ void SetTopicName(const std::string& _topicName); /** * 判断参数 TopicName 是否已赋值 * @return TopicName 是否已赋值 */ bool TopicNameHasBeenSet() const; private: /** * 采集规则扩展配置ID */ std::string m_configExtraId; bool m_configExtraIdHasBeenSet; /** * 采集规则名称 */ std::string m_name; bool m_nameHasBeenSet; /** * 日志主题ID */ std::string m_topicId; bool m_topicIdHasBeenSet; /** * 类型:container_stdout、container_file、host_file */ std::string m_type; bool m_typeHasBeenSet; /** * 节点文件配置信息 注意:此字段可能返回 null,表示取不到有效值。 */ HostFileInfo m_hostFile; bool m_hostFileHasBeenSet; /** * 容器文件路径信息 注意:此字段可能返回 null,表示取不到有效值。 */ ContainerFileInfo m_containerFile; bool m_containerFileHasBeenSet; /** * 容器标准输出信息 注意:此字段可能返回 null,表示取不到有效值。 */ ContainerStdoutInfo m_containerStdout; bool m_containerStdoutHasBeenSet; /** * 日志格式化方式 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_logFormat; bool m_logFormatHasBeenSet; /** * 采集的日志类型,json_log代表json格式日志,delimiter_log代表分隔符格式日志,minimalist_log代表极简日志,multiline_log代表多行日志,fullregex_log代表完整正则,默认为minimalist_log 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_logType; bool m_logTypeHasBeenSet; /** * 提取规则,如果设置了ExtractRule,则必须设置LogType 注意:此字段可能返回 null,表示取不到有效值。 */ ExtractRuleInfo m_extractRule; bool m_extractRuleHasBeenSet; /** * 采集黑名单路径列表 注意:此字段可能返回 null,表示取不到有效值。 */ std::vector<ExcludePathInfo> m_excludePaths; bool m_excludePathsHasBeenSet; /** * 更新时间 */ std::string m_updateTime; bool m_updateTimeHasBeenSet; /** * 创建时间 */ std::string m_createTime; bool m_createTimeHasBeenSet; /** * 用户自定义解析字符串 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_userDefineRule; bool m_userDefineRuleHasBeenSet; /** * 机器组ID */ std::string m_groupId; bool m_groupIdHasBeenSet; /** * 自建采集配置标 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_configFlag; bool m_configFlagHasBeenSet; /** * 日志集ID 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_logsetId; bool m_logsetIdHasBeenSet; /** * 日志集name 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_logsetName; bool m_logsetNameHasBeenSet; /** * 日志主题name 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_topicName; bool m_topicNameHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CLS_V20201016_MODEL_CONFIGEXTRAINFO_H_
32.927461
167
0.442329
[ "vector", "model" ]
b7e24626ba18586b5ba54576b90f3a97d0b860e3
10,810
h
C
libs/multicam_mapper.h
Hsarham/automatic-ar
b49495572e9ceb24c805449fd398126685384de5
[ "BSD-2-Clause" ]
22
2018-06-16T17:57:11.000Z
2022-03-22T02:05:40.000Z
libs/multicam_mapper.h
Hsarham/automatic-ar
b49495572e9ceb24c805449fd398126685384de5
[ "BSD-2-Clause" ]
2
2019-07-10T18:47:15.000Z
2019-08-06T04:38:05.000Z
libs/multicam_mapper.h
Hsarham/automatic-ar
b49495572e9ceb24c805449fd398126685384de5
[ "BSD-2-Clause" ]
4
2018-06-08T10:06:01.000Z
2020-08-18T14:14:10.000Z
#ifndef OPTIMIZER_H #define OPTIMIZER_H #include <vector> #include <map> #include <opencv2/core.hpp> #include <set> #include <aruco/aruco.h> #include "sparselevmarq.h" #include "cam_config.h" #include "initializer.h" #include "pointcloud_drawer.h" class MultiCamMapper { public: MultiCamMapper(size_t root_c, const std::map<int, cv::Mat> &T_to_root_cam, size_t root_m, const std::map<int, cv::Mat> &T_to_root_marker, const std::map<int, cv::Mat> &obj_transforms, const std::map<int, std::map<int, std::vector<aruco::Marker>>> &fcm, float m_size, std::vector<CamConfig> &cam_confs); MultiCamMapper(Initializer &); MultiCamMapper(); void init(size_t root_c, const std::map<int, cv::Mat> &T_to_root_cam, size_t root_m, const std::map<int, cv::Mat> &T_to_root_marker, const std::map<int, cv::Mat> &object_poses, const std::map<int, std::map<int, std::vector<aruco::Marker> > > &fcm, float m_size, const std::vector<CamConfig> &cam_confs); void init(const std::map<int, cv::Mat> &object_poses, const std::map<int, std::map<int, std::vector<aruco::Marker>>> &fcm); void error_function( const typename ucoslam::SparseLevMarq<double>::eVector &input, typename ucoslam::SparseLevMarq<double>::eVector &error); void error_function_cams( const typename ucoslam::SparseLevMarq<double>::eVector &input, typename ucoslam::SparseLevMarq<double>::eVector &error); void error_function_markers( const typename ucoslam::SparseLevMarq<double>::eVector &input, typename ucoslam::SparseLevMarq<double>::eVector &error); void error_function_object_poses( const typename ucoslam::SparseLevMarq<double>::eVector &input, typename ucoslam::SparseLevMarq<double>::eVector &error); void error_function_tracking(const ucoslam::SparseLevMarq<double>::eVector &input, ucoslam::SparseLevMarq<double>::eVector &error); void serialize_frame_cam_markers(std::ofstream &ofile); void deserialize_frame_cam_markers(std::ifstream &ifile); void overlay_coords(cv::Mat img, cv::Mat to_ref_cam, float size, int cam_id); void overlay_markers(cv::Mat &img, int frame_id, int camera_id); static std::vector<int> read_subseqs(std::string path); void set_optmize_flag_cam_poses(bool); void set_optmize_flag_marker_poses(bool); void set_optmize_flag_object_poses(bool); void set_optmize_flag_cam_intrinsics(bool); void set_with_huber(bool); void optCallBack(const ucoslam::SparseLevMarq<double>::eVector &v); float hubberDelta=2.5; void solve(); void track(); bool write_solution_file(std::string path); bool read_solution_file(std::string path); typename ucoslam::SparseLevMarq<double>::eVector io_vec; void write_text_solution_file(std::string text_path); void visualize_sequence(std::string path="", size_t num_total_frames=0); static void draw_3d_line_points(cv::Mat start, cv::Mat end, int steps, cv::Scalar color, pointcloud_t &point_cloud, cv::Scalar end_color=cv::Scalar(-1,-1,-1)); static void visualize_camera(int cam_num, const cv::Mat cam_mat, cv::Mat T, const cv::Size im_size,double Z, pointcloud_t &point_cloud); static void visualize_cameras(const std::vector<CamConfig> &cam_confs, const std::vector<cv::Mat> &transforms_to_root_cam, const std::vector<int> &index2id, float Z, pointcloud_t &point_cloud_cameras); static void visualize_marker(int marker_id,const cv::Mat T,float marker_size,pointcloud_t& point_cloud); static void visualize_markers(const std::vector<cv::Mat> &transforms_to_root_marker, const std::vector<int> index2id, float marker_size, pointcloud_t &point_cloud_markers, cv::Mat T); void visualize_cameras(pointcloud_t &point_cloud_cameras, float Z=0.1); void visualize_markers(pointcloud_t &point_cloud_markers, const cv::Mat T=cv::Mat::eye(4,4,CV_64FC1)); static int read_stereo_calib(std::string path, std::map<int,std::map<int,cv::Mat>> &transforms); static void write_stereo_calib(std::string path, const std::map<int,std::map<int,cv::Mat>> &transforms, int root_cam_id); static void read_ground_truth(std::string path, std::map<size_t,cv::Mat>& poses); static void write_ground_truth(std::string path, const std::map<size_t,cv::Mat>& poses); static void write_detections_file(std::string path, std::vector<std::vector<std::vector<aruco::Marker>>> &seq); size_t get_root_cam(); size_t get_root_marker(); double get_marker_size(); std::vector<cv::Size> get_image_sizes(); struct Config{ bool optimize_cam_poses=true; bool optimize_object_poses=true; bool optimize_marker_poses=true; bool optimize_cam_intrinsics=true; Config(){} }; void set_config(Config &conf); size_t get_num_vars(const Config& conf); struct MatArray{ std::vector<cv::Mat> v; std::map <int,int> m; std::vector<int> id; void resize(size_t new_size){ v.resize(new_size); id.resize(new_size); } MatArray &operator=(const std::map<int,cv::Mat> &ma){ v.resize(ma.size()); id.resize(ma.size()); size_t index=0; for(auto it=ma.begin();it != ma.end(); it++){ m[it->first]=index; id[index]=it->first; it->second.convertTo(v[index++],CV_64FC1); } return *this; } MatArray &operator=(const MatArray &ma){ m=ma.m; id=ma.id; v.resize(ma.v.size()); for(size_t i=0;i<ma.v.size();i++) ma.v[i].convertTo(v[i],CV_64FC1); return *this; } cv::Mat &operator[](size_t i){ return v[m[i]]; } const cv::Mat &operator[](size_t i) const{ return v[m.at(i)]; } void init(MatArray &ma){ m=ma.m; id=ma.id; v.resize(ma.v.size()); } MatArray(MatArray &ma){ m=ma.m; id=ma.id; v.resize(ma.v.size()); for(size_t i=0;i<ma.v.size();i++) ma.v[i].convertTo(v[i],CV_64FC1); } MatArray(){} }; struct MatArrays{ MatArray object_to_global; MatArray transforms_to_root_marker; MatArray transforms_to_root_cam; MatArray transforms_to_local_cam; MatArray cam_mats; MatArray dist_coeffs; void init(MatArrays &ma, Config &conf){ if(conf.optimize_cam_poses){ transforms_to_root_cam.init(ma.transforms_to_root_cam); transforms_to_local_cam.init(ma.transforms_to_local_cam); } if(conf.optimize_marker_poses) transforms_to_root_marker.init(ma.transforms_to_root_marker); if(conf.optimize_object_poses) object_to_global.init(ma.object_to_global); if(conf.optimize_cam_intrinsics){ cam_mats.init(ma.cam_mats); dist_coeffs.init(ma.dist_coeffs); } } MatArrays(const MatArrays &ma, const Config &conf=Config()){ if(conf.optimize_cam_poses){ transforms_to_root_cam=ma.transforms_to_root_cam; transforms_to_local_cam=ma.transforms_to_local_cam; } if(conf.optimize_marker_poses) transforms_to_root_marker=ma.transforms_to_root_marker; if(conf.optimize_object_poses) object_to_global=ma.object_to_global; if(conf.optimize_cam_intrinsics){ cam_mats=ma.cam_mats; dist_coeffs=ma.dist_coeffs; } } MatArrays(){} }; MatArrays get_mat_arrays(); private: bool with_huber=false; MatArrays mat_arrays; enum param_type{camera, marker, object, intrinsics}; Config config; double J_delta=0.001; double marker_size; std::set<int> cam_ids; size_t root_cam, root_marker, num_cameras, num_markers, num_frames, num_point_xys, num_vars=0; std::map<int, int> marker_id2index, marker_index2id; std::vector<cv::Point3f> marker_points_3d; std::map<int,cv::Mat> marker_object_points_3d_mats; cv::Mat marker_points_3d_mat; std::vector<double> point_projection_deviation; std::map<int, std::map<int, std::vector<aruco::Marker>>> frame_cam_markers; std::map<int, std::map<int, std::map<int, std::pair<aruco::Marker,size_t>>>> cam_marker_frame,marker_cam_frame,frame_cam_marker; std::vector<cv::Size> image_sizes; std::vector<CamConfig> cam_configs; void init_marker_points_3d(); void remove_distortions(); void transformation_mat2vec(const cv::Mat mat, size_t &vec_index); void vec2transformation_mat(size_t &vec_index, const typename ucoslam::SparseLevMarq<double>::eVector &vec, cv::Mat& mat); size_t fill_io_vec_cams(size_t vec_index=0); size_t fill_io_vec_markers(size_t vec_index=0); size_t fill_io_vec_object_poses(size_t vec_index=0); size_t fill_io_vec_cam_intrinsics(size_t vec_index=0); size_t intrinsics_vec2mats(const ucoslam::SparseLevMarq<double>::eVector &eVec, MatArrays &ma, size_t vec_index=0); size_t object_poses_vec2mats(const ucoslam::SparseLevMarq<double>::eVector &eVec, MatArrays& ma, size_t vec_index=0); size_t cams_vec2mats(const typename ucoslam::SparseLevMarq<double>::eVector &eVec, MatArrays &ma, size_t vec_index=0); size_t markers_vec2mats(const typename ucoslam::SparseLevMarq<double>::eVector &eVec, MatArrays &ma, size_t vec_index=0); void eval_curr_solution(MatArrays &ma, typename ucoslam::SparseLevMarq<double>::eVector &error); void init_io_vec_object_poses(); void fill_iteration_arrays(); void project_marker(const MatArrays &ma, size_t frame_num, size_t marker_index, size_t cam_index, std::vector<cv::Point2f> &points_2d); void eVec2Mats(const typename ucoslam::SparseLevMarq<double>::eVector &eVec, MatArrays &ma); void mats2eVec(const Config &conf); void mats2eVec(); void project_points(); void run(); void obtain_marker_derivs(const MatArrays &ma_a, const MatArrays &ma_s, const aruco::Marker& marker, Eigen::SparseMatrix<double> &J, size_t frame_index, size_t marker_index, size_t cam_index, size_t error_vec_ind, size_t param_index, std::vector<Eigen::Triplet<double>> &elems); void obtain_transformation_derivs(const MatArrays &ma, const ucoslam::SparseLevMarq<double>::eVector &input, param_type transform_type, size_t transform_index, size_t param_offset, Eigen::SparseMatrix<double> &J, std::vector<Eigen::Triplet<double>> &elems); void jacobian_function(const ucoslam::SparseLevMarq<double>::eVector &input, Eigen::SparseMatrix<double> &J); ucoslam::SparseLevMarq<double> solver; }; #endif // OPTIMIZER_H
45.420168
307
0.685199
[ "object", "vector" ]
b7e8d69d234a9869f023207a5880a859fd93749d
1,583
h
C
src/w_menuentry.h
Masrik-Dahir/xfigx-3.1.1
40ec5d16e2f7ec4a3e84940fbf6a96c7b1890645
[ "MIT" ]
null
null
null
src/w_menuentry.h
Masrik-Dahir/xfigx-3.1.1
40ec5d16e2f7ec4a3e84940fbf6a96c7b1890645
[ "MIT" ]
null
null
null
src/w_menuentry.h
Masrik-Dahir/xfigx-3.1.1
40ec5d16e2f7ec4a3e84940fbf6a96c7b1890645
[ "MIT" ]
null
null
null
/* * FIG : Facility for Interactive Generation of figures * Copyright (c) 1989-2007 by Brian V. Smith * * Any party obtaining a copy of these files is granted, free of charge, a * full and unrestricted irrevocable, world-wide, paid up, royalty-free, * nonexclusive right and license to deal in this software and documentation * files (the "Software"), including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense and/or sell copies of * the Software, and to permit persons who receive copies from any such * party to do so, with the only requirement being that the above copyright * and this permission notice remain intact. * */ /* w_menuentry.h - Public Header file for subclassed BSB Menu Entry object This adds the underline resource to underline one character of the label */ #ifndef _FigSmeBSB_h #define _FigSmeBSB_h #ifdef XAW3D #include <X11/Xaw3d/Sme.h> #else #include <X11/Xaw/Sme.h> #endif #ifdef XAW3D1_5E #include <X11/Xaw3d/SmeBSB.h> #else #include "SmeBSB.h" #endif /**************************************************************** * * FigSmeBSB object * ****************************************************************/ /* FigBSB Menu Entry Resources: Name Class RepType Default Value ---- ----- ------- ------------- underline Index int -1 */ typedef struct _FigSmeBSBClassRec *FigSmeBSBObjectClass; typedef struct _FigSmeBSBRec *FigSmeBSBObject; extern WidgetClass figSmeBSBObjectClass; #define XtNunderline "underline" #endif /* Fig_SmeBSB_h */
26.830508
77
0.658876
[ "object" ]
b7f8e0e1f01aac40a243566114c9565a522af6ef
4,805
h
C
src/engine/profiler.h
IIMarch/mxnet
64c35f2d41f5bad3f9cbf4d4fda9cf3bf3dadb4b
[ "Apache-2.0" ]
4
2017-11-17T07:28:09.000Z
2019-07-23T06:24:16.000Z
src/engine/profiler.h
IIMarch/mxnet
64c35f2d41f5bad3f9cbf4d4fda9cf3bf3dadb4b
[ "Apache-2.0" ]
1
2022-02-28T21:23:12.000Z
2022-03-03T18:33:42.000Z
src/engine/profiler.h
IIMarch/mxnet
64c35f2d41f5bad3f9cbf4d4fda9cf3bf3dadb4b
[ "Apache-2.0" ]
2
2019-06-12T12:40:20.000Z
2020-11-03T14:33:14.000Z
/* * 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. */ /*! * \file profiler.h * \brief implements profiler */ #ifndef MXNET_ENGINE_PROFILER_H_ #define MXNET_ENGINE_PROFILER_H_ #include <vector> #include <string> #include <mutex> #include <memory> namespace mxnet { namespace engine { /*! * \brief Operation execution statistics */ struct OprExecStat { /*! \brief operation name */ char opr_name[32]; /*! * \brief operation execution start relative timestamp * time unit is microsecond (10^-6 s) */ uint64_t opr_start_rel_micros; /*! * \brief operation execution end relative timestamp * time unit is microsecond (10^-6 s) */ uint64_t opr_end_rel_micros; /*! \brief id of thread which operation run on */ uint32_t thread_id; /*! * \brief device type * CPU: 1, GPU: 2, CPUPinned: 3 */ uint32_t dev_type; /*! \brief device id */ uint32_t dev_id; }; /*! * \brief Device statistics */ struct DevStat { /*! \brief device name */ std::string dev_name; /*! \brief operation execution statistics on this device */ std::vector<OprExecStat*> opr_exec_stats; /*! \brief internal mutex of the execution state */ std::mutex m_; }; /*! * \brief profiler that records the operation execution information * and saves the profile statistics. */ class Profiler { public: enum ProfilerMode { kOnlySymbolic = 0, kAllOperator = 1 }; enum ProfilerState { kNotRunning = 0, kRunning = 1 }; /*! \brief set state of profiler */ void SetState(ProfilerState state); /*! \return state of profiler */ inline ProfilerState GetState() const { return this->state_; } /*! \brief set configure of profiler */ void SetConfig(ProfilerMode mode, std::string output_filename); /*! \return mode of profiler */ inline ProfilerMode GetMode() const { return this->mode_; } /*! \return whether the profiler is enabled to output */ inline bool IsEnableOutput() const { return this->enable_output_; } /*! \brief dump the profile file */ void DumpProfile(); /*! \return the profiler init time, time unit is microsecond (10^-6) s */ inline uint64_t GetInitTime() const { return init_time_; } /*! \brief add one operation execution record in * corresponding device statistics */ OprExecStat* AddOprStat(int dev_type, uint32_t dev_id); /*! \return Profiler singleton */ static Profiler* Get(); protected: /*! \brief make constructor protected. */ Profiler(); private: /*! \brief generate device information following chrome profile file format */ void EmitPid(std::ostream *os, const std::string& name, uint32_t pid); /*! \brief generate event information following chrome profile file format */ void EmitEvent(std::ostream *os, const std::string& name, const std::string& category, const std::string& ph, uint64_t ts, uint32_t pid, uint32_t tid); /*! \brief Profiler instance */ static Profiler* instance_; /*! \brief internal mutex of the profiler */ std::mutex m_; /*! \brief indicate whether the profiler is running */ ProfilerState state_; /*! \brief once running, enable profiler to output */ bool enable_output_; /*! \brief indicate what operator the profiler will record */ ProfilerMode mode_; /*! \brief filename to output profile file */ std::string filename_; /*! \brief profile statistics consist of multiple device statistics */ DevStat* profile_stat; /*! \brief cpu number on the machine */ unsigned int cpu_num_; /*! \brief gpu number on the machine */ unsigned int gpu_num_; /*! \brief the profiler init time */ uint64_t init_time_; }; /*! \return current clock time, time unit is microsecond (10^-6 s) */ inline uint64_t NowInUsec(); /*! \brief set operation execution start timestamp */ void SetOprStart(OprExecStat* opr_stat); /*! \brief set operation execution end timestamp */ void SetOprEnd(OprExecStat* opr_stat); } // namespace engine } // namespace mxnet #endif // MXNET_ENGINE_PROFILER_H_
30.03125
80
0.694901
[ "vector" ]
b7fd1f136fa151ebead9678f7af228bdc0248c45
1,708
h
C
nlp-automl/include/alibabacloud/nlp-automl/model/PredictMTModelRequest.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
nlp-automl/include/alibabacloud/nlp-automl/model/PredictMTModelRequest.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
nlp-automl/include/alibabacloud/nlp-automl/model/PredictMTModelRequest.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_NLP_AUTOML_MODEL_PREDICTMTMODELREQUEST_H_ #define ALIBABACLOUD_NLP_AUTOML_MODEL_PREDICTMTMODELREQUEST_H_ #include <string> #include <vector> #include <alibabacloud/core/RpcServiceRequest.h> #include <alibabacloud/nlp-automl/Nlp_automlExport.h> namespace AlibabaCloud { namespace Nlp_automl { namespace Model { class ALIBABACLOUD_NLP_AUTOML_EXPORT PredictMTModelRequest : public RpcServiceRequest { public: PredictMTModelRequest(); ~PredictMTModelRequest(); std::string getProduct()const; void setProduct(const std::string& product); std::string getModelId()const; void setModelId(const std::string& modelId); std::string getContent()const; void setContent(const std::string& content); std::string getModelVersion()const; void setModelVersion(const std::string& modelVersion); private: std::string product_; std::string modelId_; std::string content_; std::string modelVersion_; }; } } } #endif // !ALIBABACLOUD_NLP_AUTOML_MODEL_PREDICTMTMODELREQUEST_H_
29.964912
88
0.740632
[ "vector", "model" ]
4d0d6b003d99c1074c0222c84fe3291289a78e9d
989
h
C
Ancestor/src/Platform/OpenGL/OpenGLBuffer.h
AlerHugu3s/Ancestor
4ec1e693438d94f25f7eb4d7ef8a57e67a518c0d
[ "Apache-2.0" ]
null
null
null
Ancestor/src/Platform/OpenGL/OpenGLBuffer.h
AlerHugu3s/Ancestor
4ec1e693438d94f25f7eb4d7ef8a57e67a518c0d
[ "Apache-2.0" ]
null
null
null
Ancestor/src/Platform/OpenGL/OpenGLBuffer.h
AlerHugu3s/Ancestor
4ec1e693438d94f25f7eb4d7ef8a57e67a518c0d
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Ancestor/Renderer/Buffer.h" namespace Ancestor { class OpenGLVertexBuffer : public VertexBuffer { public: OpenGLVertexBuffer(float* vertices, uint32_t size); OpenGLVertexBuffer(std::vector<Vertex> vertices); virtual ~OpenGLVertexBuffer() override; virtual void Bind() const override; virtual void UnBind() const override; virtual BufferLayout& GetLayout() override { return m_Layout; } virtual void SetLayout(const BufferLayout& layout) override { m_Layout = layout; } private: uint32_t m_RendererID; BufferLayout m_Layout; }; class OpenGLIndexBuffer : public IndexBuffer { public: OpenGLIndexBuffer(uint32_t* indices, uint32_t size); OpenGLIndexBuffer(std::vector<uint32_t> indices); virtual~OpenGLIndexBuffer() override; virtual void Bind() const override; virtual void UnBind() const override; virtual uint32_t GetCount() const override { return m_Count; } private: uint32_t m_RendererID; uint32_t m_Count; }; }
25.358974
84
0.760364
[ "vector" ]
4d13436677c6a025cd10103e7b3a97ae9f933a6a
10,022
h
C
VisIt/interfaces/datatypes.h
QuocAnh90/Uintah_Aalto
802c236c331b7eb705d408c352969037e4c5b153
[ "MIT" ]
3
2020-06-10T08:21:31.000Z
2020-06-23T18:33:16.000Z
VisIt/interfaces/datatypes.h
QuocAnh90/Uintah_Aalto
802c236c331b7eb705d408c352969037e4c5b153
[ "MIT" ]
null
null
null
VisIt/interfaces/datatypes.h
QuocAnh90/Uintah_Aalto
802c236c331b7eb705d408c352969037e4c5b153
[ "MIT" ]
2
2019-12-30T05:48:30.000Z
2020-02-12T16:24:16.000Z
/* * The MIT License * * Copyright (c) 1997-2019 The University of Utah * * 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. */ /* * datatypes.h: Datatypes for the interface between Uintah and VisIt. * * Written by: * Scientific Computing and Imaging Institute * University of Utah * April 2018 * */ #ifndef UINTAH_VISIT_INTERFACES_DATATYPES_H #define UINTAH_VISIT_INTERFACES_DATATYPES_H #include <string> #include <sstream> #include <vector> #include <iostream> #include <climits> typedef enum loadExtraGeometry { NO_EXTRA_GEOMETRY = 0, CELLS = 1, PATCHES = 2, } LoadExtraGeometry; typedef enum loadVariables { LOAD_ALL_VARIABLES = 0, LOAD_OUTPUT_VARIABLES = 1, LOAD_CHECKPOINT_VARIABLES = 2, } LoadVariables; class PatchInfo { public: // GridType enum GridType { UNKNOWN=-1, CC, NC, SFCX, SFCY, SFCZ, NEIGHBORS, PATCH }; // str2GridType static GridType str2GridType(const std::string &type) { if (type.find("SFCX") != std::string::npos) return SFCX; if (type.find("SFCY") != std::string::npos) return SFCY; if (type.find("SFCZ") != std::string::npos) return SFCZ; if (type.find("CC") != std::string::npos) return CC; if (type.find("NC") != std::string::npos) return NC; if (type.find("NEIGHBORS") != std::string::npos) return NEIGHBORS; if (type.find("Patch") != std::string::npos) return PATCH; return UNKNOWN; } // getBounds void getBounds(int low[3], int high[3], const std::string &typestr) const { GridType type = str2GridType(typestr); getLow(low, type); getHigh(high, type); } // getLow void getLow(int low[3], GridType type) const { switch (type) { case CC: low[0] = cc_low[0]; low[1] = cc_low[1]; low[2] = cc_low[2]; break; case NC: low[0] = nc_low[0]; low[1] = nc_low[1]; low[2] = nc_low[2]; break; case SFCX: low[0] = sfcx_low[0]; low[1] = sfcx_low[1]; low[2] = sfcx_low[2]; break; case SFCY: low[0] = sfcy_low[0]; low[1] = sfcy_low[1]; low[2] = sfcy_low[2]; break; case SFCZ: low[0] = sfcz_low[0]; low[1] = sfcz_low[1]; low[2] = sfcz_low[2]; break; case NEIGHBORS: low[0] = neighbors_low[0]; low[1] = neighbors_low[1]; low[2] = neighbors_low[2]; break; case PATCH: low[0] = patch_id; low[1] = patch_id; low[2] = patch_id; break; default: low[0] = low[1] = low[2] = -1000000; } } // getHigh void getHigh(int high[3], GridType type) const { switch (type) { case CC: high[0] = cc_high[0]; high[1] = cc_high[1]; high[2] = cc_high[2]; break; case NC: high[0] = nc_high[0]; high[1] = nc_high[1]; high[2] = nc_high[2]; break; case SFCX: high[0] = sfcx_high[0]; high[1] = sfcx_high[1]; high[2] = sfcx_high[2]; break; case SFCY: high[0] = sfcy_high[0]; high[1] = sfcy_high[1]; high[2] = sfcy_high[2]; break; case SFCZ: high[0] = sfcz_high[0]; high[1] = sfcz_high[1]; high[2] = sfcz_high[2]; break; case NEIGHBORS: high[0] = neighbors_high[0]; high[1] = neighbors_high[1]; high[2] = neighbors_high[2]; break; case PATCH: high[0] = patch_id + 1; high[1] = patch_id + 1; high[2] = patch_id + 1; break; default: high[0] = high[1] = high[2] = -1000000; } } // getProcId int getProcId() const { return proc_id; } // setProcId void setProcId(const int new_proc_id) { proc_id = new_proc_id; } // getPatchId int getPatchId() const { return patch_id; } // setPatchId void setPatchId(const int new_patch_id) { patch_id = new_patch_id; } // setBounds bool setBounds(const int low[3], const int high[3], const std::string &typestr) { GridType type = str2GridType(typestr); switch (type) { case CC: cc_low[0] = low[0]; cc_low[1] = low[1]; cc_low[2] = low[2]; cc_high[0] = high[0]; cc_high[1] = high[1]; cc_high[2] = high[2]; break; case NC: nc_low[0] = low[0]; nc_low[1] = low[1]; nc_low[2] = low[2]; nc_high[0] = high[0]; nc_high[1] = high[1]; nc_high[2] = high[2]; break; case SFCX: sfcx_low[0] = low[0]; sfcx_low[1] = low[1]; sfcx_low[2] = low[2]; sfcx_high[0] = high[0]; sfcx_high[1] = high[1]; sfcx_high[2] = high[2]; break; case SFCY: sfcy_low[0] = low[0]; sfcy_low[1] = low[1]; sfcy_low[2] = low[2]; sfcy_high[0] = high[0]; sfcy_high[1] = high[1]; sfcy_high[2] = high[2]; break; case SFCZ: sfcz_low[0] = low[0]; sfcz_low[1] = low[1]; sfcz_low[2] = low[2]; sfcz_high[0] = high[0]; sfcz_high[1] = high[1]; sfcz_high[2] = high[2]; break; case NEIGHBORS: neighbors_low[0] = low[0]; neighbors_low[1] = low[1]; neighbors_low[2] = low[2]; neighbors_high[0] = high[0]; neighbors_high[1] = high[1]; neighbors_high[2] = high[2]; break; default: return false; } return true; } // toString std::string toString() const { std::ostringstream str; str<<"PatchID: "<<patch_id<<std::endl; str<<"CC: <"<<cc_low[0]<<","<<cc_low[1]<<","<<cc_low[2]<<"> to <"<<cc_high[0]<<","<<cc_high[1]<<","<<cc_high[2]<<">"<<std::endl; str<<"NC: <"<<nc_low[0]<<","<<nc_low[1]<<","<<nc_low[2]<<"> to <"<<nc_high[0]<<","<<nc_high[1]<<","<<nc_high[2]<<">"<<std::endl; str<<"SFCX: <"<<sfcx_low[0]<<","<<sfcx_low[1]<<","<<sfcx_low[2]<<"> to <"<<sfcx_high[0]<<","<<sfcx_high[1]<<","<<sfcx_high[2]<<">"<<std::endl; str<<"SFCY: <"<<sfcy_low[0]<<","<<sfcy_low[1]<<","<<sfcy_low[2]<<"> to <"<<sfcy_high[0]<<","<<sfcy_high[1]<<","<<sfcy_high[2]<<">"<<std::endl; str<<"SFCZ: <"<<sfcz_low[0]<<","<<sfcz_low[1]<<","<<sfcz_low[2]<<"> to <"<<sfcz_high[0]<<","<<sfcz_high[1]<<","<<sfcz_high[2]<<">"<<std::endl; str<<"NEIGHBORS: <"<<neighbors_low[0]<<","<<neighbors_low[1]<<","<<neighbors_low[2]<<"> to <"<<neighbors_high[0]<<","<<neighbors_high[1]<<","<<neighbors_high[2]<<">"<<std::endl; return str.str(); } private: // cell centered indices int cc_low[3]; int cc_high[3]; // node centered indices int nc_low[3]; int nc_high[3]; // sfcx indices int sfcx_low[3]; int sfcx_high[3]; // sfcy centered indices int sfcy_low[3]; int sfcy_high[3]; // sfcz centered indices int sfcz_low[3]; int sfcz_high[3]; // neighbors int neighbors_low[3]; int neighbors_high[3]; int patch_id; int proc_id; }; class LevelInfo { public: std::vector<PatchInfo> patchInfo; int refinementRatio[3]; double spacing[3]; double anchor[3]; int periodic[3]; // The extents are the same for all meshes void getExtents(double box_min[3], double box_max[3]) const { int low[3], high[3]; getBounds(low, high, "CC_Mesh"); box_min[0] = anchor[0] + low[0] * spacing[0]; box_min[1] = anchor[1] + low[1] * spacing[1]; box_min[2] = anchor[2] + low[2] * spacing[2]; box_max[0] = anchor[0] + high[0] * spacing[0]; box_max[1] = anchor[1] + high[1] * spacing[1]; box_max[2] = anchor[2] + high[2] * spacing[2]; } // Get the bounds for a specific patch of a given mesh. If the // patch_id = -1 query all patches. void getBounds(int low[3], int high[3], const std::string meshName, int patch_id = -1) const { if (patch_id == -1) { // Query limits of all patches low[0] = low[1] = low[2] = INT_MAX; high[0] = high[1] = high[2] = INT_MIN; int plow[3], phigh[3]; for (int i=0; i<(int)patchInfo.size(); i++) { patchInfo[i].getBounds(plow, phigh, meshName); for (int j=0; j<3; j++) { low[j] = std::min(low[j], plow[j]); high[j] = std::max(high[j],phigh[j]); } } } else { // Query limits of one patch const PatchInfo &patch = patchInfo[patch_id]; patch.getBounds(low, high, meshName); } } }; class VariableInfo { public: std::string name; std::string type; std::vector<int> materials; }; class TimeStepInfo { public: std::vector<LevelInfo> levelInfo; std::vector<VariableInfo> varInfo; }; class GridDataRaw { public: // Low and high indexes of the data that was read. They SHOULD // match what is expected, but may not if there is a boundary // layer for the variable. int num; int low[3]; int high[3]; int components; double *data; }; class ParticleDataRaw { public: int num; int components; double *data; }; #endif // UINTAH_DATATYPES_H
23.581176
181
0.574137
[ "mesh", "vector" ]
4d2096316766a79405fc792ebc1e6d468bfb9be9
90,822
h
C
tsc/tsc-new-parser/node_factory.h
SamuraiCrow/TypeScriptCompiler
11a5379f3ffe145e61611c463e43d39ec7ea8522
[ "MIT" ]
171
2021-02-17T19:01:41.000Z
2022-03-31T09:00:24.000Z
tsc/tsc-new-parser/node_factory.h
SamuraiCrow/TypeScriptCompiler
11a5379f3ffe145e61611c463e43d39ec7ea8522
[ "MIT" ]
12
2021-09-04T14:16:00.000Z
2022-03-29T15:46:42.000Z
tsc/tsc-new-parser/node_factory.h
SamuraiCrow/TypeScriptCompiler
11a5379f3ffe145e61611c463e43d39ec7ea8522
[ "MIT" ]
6
2021-09-30T07:30:01.000Z
2022-01-19T21:04:57.000Z
#ifndef NODEFACTORY_H #define NODEFACTORY_H #include "node_test.h" #include "parenthesizer_rules.h" #include "parser_fwd_types.h" #include "scanner.h" #include "utilities.h" namespace ts { class NodeFactory { Scanner *scanner; Scanner rawTextScanner; ParenthesizerRules parenthesizerRules; NodeFactoryFlags flags; NodeCreateCallbackFunc createNodeCallback; public: NodeFactory(ts::Scanner *scanner, NodeFactoryFlags nodeFactoryFlags, NodeCreateCallbackFunc createNodeCallback) : scanner(scanner), rawTextScanner(ScriptTarget::Latest, /*skipTrivia*/ false, LanguageVariant::Standard), parenthesizerRules(this), flags(nodeFactoryFlags), createNodeCallback(createNodeCallback) { } NodeFactory(NodeFactoryFlags nodeFactoryFlags) : scanner(nullptr), rawTextScanner(ScriptTarget::Latest, /*skipTrivia*/ false, LanguageVariant::Standard), parenthesizerRules(this), flags(nodeFactoryFlags), createNodeCallback((NodeCreateCallbackFunc)[](Node){}) { } auto NoParenthesizerRules() -> boolean; template <typename T> auto update(T updated, T original) -> T { if (!!(flags & NodeFactoryFlags::NoOriginalNode)) { return updateWithoutOriginal(updated, original); } return updateWithOriginal(updated, original); } template <typename T> auto updateWithoutOriginal(T updated, T original) -> T { if (updated != original) { setTextRange(updated, original); } return updated; } template <typename T> auto updateWithOriginal(T updated, T original) -> T { if (updated != original) { setOriginalNode(updated, original); setTextRange(updated, original); } return updated; } inline auto asName(Identifier name) -> Identifier { return name; } template <typename T> inline auto asNodeArray(NodeArray<T> array) -> NodeArray<T> { return createNodeArray(array); } inline auto asExpression(Expression value) -> Expression { return value; } inline auto asToken(Node value) -> Node { return value; } auto mergeEmitNode(/*EmitNode*/ Node sourceEmitNode, /*EmitNode*/ Node destEmitNode) -> /* EmitNode */ Node { // TODO: finish it return destEmitNode; } template <typename T> auto setOriginalNode(T node, Node original) -> T { node->original = original; if (original) { // TODO: review it // auto emitNode = original->emitNode; // if (emitNode) node->emitNode = mergeEmitNode(emitNode, node->emitNode); } return node; } template <typename T> inline auto asEmbeddedStatement(T statement) -> T { return statement && isNotEmittedStatement(statement) ? setTextRange(setOriginalNode(createEmptyStatement(), statement), statement).template as<Statement>() : statement; } auto propagateIdentifierNameFlags(Identifier node) -> TransformFlags; auto propagateAssignmentPatternFlags(Node node) -> TransformFlags; auto getTransformFlagsSubtreeExclusions(SyntaxKind kind) -> TransformFlags; auto propagatePropertyNameFlagsOfChild(PropertyName node, TransformFlags transformFlags) -> TransformFlags; auto propagateChildFlags(Node child) -> TransformFlags; template <typename T> auto aggregateChildrenFlags(NodeArray<T> children) -> void { auto subtreeFlags = TransformFlags::None; for (auto &child : children) { subtreeFlags |= propagateChildFlags(child); } children->transformFlags = subtreeFlags; } template <typename T> auto propagateChildrenFlags(NodeArray<T> children) -> TransformFlags { return !!children ? children->transformFlags : TransformFlags::None; } auto getCookedText(SyntaxKind kind, string rawText) -> std::pair<string, boolean>; template <typename T, typename D = typename T::data> auto createBaseNode(SyntaxKind kind) { auto newNode = T(D()); newNode->_kind = kind; createNodeCallback(newNode); return newNode; } template <typename T> auto createBaseToken(SyntaxKind kind) { return createBaseNode<T>(kind); } template <typename T> auto createBaseLiteral(SyntaxKind kind, string text) { auto node = createBaseNode<T>(kind); node->text = text; return node; } // auto createNodeArray(Node elements = undefined, boolean hasTrailingComma = false) -> Node; template <typename T> auto createNodeArray(NodeArray<T> elements, boolean hasTrailingComma = false) -> NodeArray<T> { setTextRangePosEnd(elements, -1, -1); elements.hasTrailingComma = !!hasTrailingComma; aggregateChildrenFlags(elements); Debug::attachNodeArrayDebugInfo(elements); return elements; } template <typename T = Node> auto createToken(SyntaxKind token) -> T { Debug::_assert(token >= SyntaxKind::FirstToken && token <= SyntaxKind::LastToken, S("Invalid token")); Debug::_assert(token <= SyntaxKind::FirstTemplateToken || token >= SyntaxKind::LastTemplateToken, S("Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals.")); Debug::_assert(token <= SyntaxKind::FirstLiteralToken || token >= SyntaxKind::LastLiteralToken, S("Invalid token. Use 'createLiteralLikeNode' to create literals.")); Debug::_assert(token != SyntaxKind::Identifier, S("Invalid token. Use 'createIdentifier' to create identifiers")); // auto node = createBaseTokenNode<Token<TKind>>(token); auto node = createBaseNode<T>(token); auto transformFlags = TransformFlags::None; switch (token) { case SyntaxKind::AsyncKeyword: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) transformFlags = TransformFlags::ContainsES2017 | TransformFlags::ContainsES2018; break; case SyntaxKind::PublicKeyword: case SyntaxKind::PrivateKeyword: case SyntaxKind::ProtectedKeyword: case SyntaxKind::ReadonlyKeyword: case SyntaxKind::AbstractKeyword: case SyntaxKind::DeclareKeyword: case SyntaxKind::ConstKeyword: case SyntaxKind::AnyKeyword: case SyntaxKind::NumberKeyword: case SyntaxKind::BigIntKeyword: case SyntaxKind::NeverKeyword: case SyntaxKind::ObjectKeyword: case SyntaxKind::StringKeyword: case SyntaxKind::BooleanKeyword: case SyntaxKind::SymbolKeyword: case SyntaxKind::VoidKeyword: case SyntaxKind::UnknownKeyword: case SyntaxKind::UndefinedKeyword: // `undefined` is an Identifier in the expression case. transformFlags = TransformFlags::ContainsTypeScript; break; case SyntaxKind::StaticKeyword: case SyntaxKind::SuperKeyword: transformFlags = TransformFlags::ContainsES2015; break; case SyntaxKind::ThisKeyword: // 'this' indicates a lexical 'this' transformFlags = TransformFlags::ContainsLexicalThis; break; } if (!!transformFlags) { node->transformFlags |= transformFlags; } return node; } template <typename T> auto createJSDocPrimaryTypeWorker(SyntaxKind kind) { return createBaseNode<T>(kind); } template <typename T> auto createJSDocUnaryTypeWorker(SyntaxKind kind, decltype(T()->type) type) -> T { auto node = createBaseNode<T>(kind); node->type = type; return node; } template <typename T> auto createBaseJSDocTag(SyntaxKind kind, Identifier tagName, string comment) { auto node = createBaseNode<T>(kind); node->tagName = tagName; node->comment = comment; return node; } auto static getDefaultTagNameForKind(SyntaxKind kind) -> string; template <typename T> auto createJSDocSimpleTagWorker(SyntaxKind kind, Identifier tagName, string comment) { auto node = createBaseJSDocTag<T>(kind, tagName ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment); return node; } template <typename T> auto createJSDocTypeLikeTagWorker(SyntaxKind kind, Identifier tagName, JSDocTypeExpression typeExpression, string comment) { auto node = createBaseJSDocTag<T>(kind, tagName ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment); node->typeExpression = typeExpression; return node; } template <typename T> auto createBaseDeclaration(SyntaxKind kind, DecoratorsArray decorators, ModifiersArray modifiers) { auto node = createBaseNode<T>(kind); node->decorators = asNodeArray(decorators); node->modifiers = asNodeArray(modifiers); node->transformFlags |= propagateChildrenFlags(node->decorators) | propagateChildrenFlags(node->modifiers); // NOTE: The following properties are commonly set by the binder and are added here to // ensure declarations have a stable shape. node->symbol = undefined; // initialized by binder node->localSymbol = undefined; // initialized by binder node->locals.clear(); // initialized by binder node->nextContainer = undefined; // initialized by binder return node; } template <typename T> auto createBaseNamedDeclaration(SyntaxKind kind, DecoratorsArray decorators, ModifiersArray modifiers, Identifier name) -> T { auto node = createBaseDeclaration<T>(kind, decorators, modifiers); name = asName(name); node->name = name; // The PropertyName of a member is allowed to be `await`. // We don't need to exclude `await` for type signatures since types // don't propagate child flags. if (name) { switch ((SyntaxKind)node) { case SyntaxKind::MethodDeclaration: case SyntaxKind::GetAccessor: case SyntaxKind::SetAccessor: case SyntaxKind::PropertyDeclaration: case SyntaxKind::PropertyAssignment: if (isIdentifier(name)) { node->transformFlags |= propagateIdentifierNameFlags(name); break; } // fall through default: node->transformFlags |= propagateChildFlags(name); break; } } return node; } template <typename T> auto createBaseBindingLikeDeclaration(SyntaxKind kind, DecoratorsArray decorators, ModifiersArray modifiers, BindingName name, Expression initializer) -> T { auto node = createBaseNamedDeclaration<T>(kind, decorators, modifiers, name); node->initializer = initializer; node->transformFlags |= propagateChildFlags(node->initializer); return node; } template <typename T> auto createBaseVariableLikeDeclaration(SyntaxKind kind, DecoratorsArray decorators, ModifiersArray modifiers, BindingName name, TypeNode type, Expression initializer) -> T { auto node = createBaseBindingLikeDeclaration<T>(kind, decorators, modifiers, name, initializer); node->type = type; node->transformFlags |= propagateChildFlags(type); if (type) node->transformFlags |= TransformFlags::ContainsTypeScript; return node; } template <typename T> auto createBaseGenericNamedDeclaration(SyntaxKind kind, DecoratorsArray decorators, ModifiersArray modifiers, PropertyName name, NodeArray<TypeParameterDeclaration> typeParameters) { auto node = createBaseNamedDeclaration<T>(kind, decorators, modifiers, name); node->typeParameters = asNodeArray(typeParameters); node->transformFlags |= propagateChildrenFlags(node->typeParameters); if (!typeParameters.empty()) node->transformFlags |= TransformFlags::ContainsTypeScript; return node; } template <typename T> auto createBaseSignatureDeclaration(SyntaxKind kind, DecoratorsArray decorators, ModifiersArray modifiers, PropertyName name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type) { auto node = createBaseGenericNamedDeclaration<T>(kind, decorators, modifiers, name, typeParameters); node->parameters = createNodeArray(parameters); node->type = type; node->transformFlags |= propagateChildrenFlags(node->parameters) | propagateChildFlags(node->type); if (type) node->transformFlags |= TransformFlags::ContainsTypeScript; return node; } template <typename T> auto createBaseFunctionLikeDeclaration(SyntaxKind kind, DecoratorsArray decorators, ModifiersArray modifiers, PropertyName name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) { auto node = createBaseSignatureDeclaration<T>(kind, decorators, modifiers, name, typeParameters, parameters, type); node->body = body; node->transformFlags |= propagateChildFlags(node->body) & ~TransformFlags::ContainsPossibleTopLevelAwait; if (!body) node->transformFlags |= TransformFlags::ContainsTypeScript; return node; } template <typename T> auto createBaseExpression(SyntaxKind kind) { auto node = createBaseNode<T>(kind); // the following properties are commonly set by the checker/binder return node; } template <typename T> auto createBaseInterfaceOrClassLikeDeclaration(SyntaxKind kind, DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses) { auto node = createBaseGenericNamedDeclaration<T>(kind, decorators, modifiers, name, typeParameters); node->heritageClauses = asNodeArray(heritageClauses); node->transformFlags |= propagateChildrenFlags(node->heritageClauses); return node; } template <typename T> auto createBaseClassLikeDeclaration(SyntaxKind kind, DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<ClassElement> members) { auto node = createBaseInterfaceOrClassLikeDeclaration<T>(kind, decorators, modifiers, name, typeParameters, heritageClauses); node->members = createNodeArray(members); node->transformFlags |= propagateChildrenFlags(node->members); return node; } // // Literals // auto createNumericLiteral(string value, TokenFlags numericLiteralFlags = TokenFlags::None) -> NumericLiteral; // auto createNumericLiteral(number value, TokenFlags numericLiteralFlags = TokenFlags::None) -> NumericLiteral; auto createBigIntLiteral(string value) -> BigIntLiteral; // auto createBigIntLiteral(PseudoBigInt value) -> BigIntLiteral; auto createBaseStringLiteral(string text, boolean isSingleQuote = false) -> StringLiteral; /* @internal*/ auto createStringLiteral(string text, boolean isSingleQuote = false, boolean hasExtendedUnicodeEscape = false) -> StringLiteral; // eslint-disable-line @typescript-eslint/unified-signatures // auto createStringLiteralFromNode(PropertyNameLiteral sourceNode, boolean isSingleQuote = false) -> StringLiteral; auto createRegularExpressionLiteral(string text) -> RegularExpressionLiteral; // // Identifiers // auto createBaseIdentifier(string text, SyntaxKind originalKeywordKind = SyntaxKind::Unknown); /* @internal */ auto createIdentifier(string text, NodeArray</*TypeNode | TypeParameterDeclaration*/ Node> typeArguments = undefined, SyntaxKind originalKeywordKind = SyntaxKind::Unknown) -> Identifier; // eslint-disable-line @typescript-eslint/unified-signatures ///* @internal */ auto updateIdentifier(Identifier node, NodeArray</*TypeNode | TypeParameterDeclaration*/Node> /// typeArguments) -> Identifier; /** * Create a unique temporary variable. * @param recordTempVariable An optional callback used to record the temporary variable name. This * should usually be a reference to `hoistVariableDeclaration` from a `TransformationContext`, but * can be `undefined` if you plan to record the temporary variable manually. * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes * during emit so that the variable can be referenced in a nested function body. This is an alternative to * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. */ // auto createTempVariable(std::function<void(Identifier)> recordTempVariable, boolean reservedInNestedScopes = false) -> Identifier; /** * Create a unique temporary variable for use in a loop. * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes * during emit so that the variable can be referenced in a nested function body. This is an alternative to * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. */ // auto createLoopVariable(boolean reservedInNestedScopes = false) -> Identifier; // /** Create a unique name based on the supplied text. */ // auto createUniqueName(string text, GeneratedIdentifierFlags flags = (GeneratedIdentifierFlags)0) -> Identifier; // /** Create a unique name generated for a node. */ // auto getGeneratedNameForNode(Node node, GeneratedIdentifierFlags flags = (GeneratedIdentifierFlags)0) -> Identifier; auto createPrivateIdentifier(string text) -> PrivateIdentifier; // // // // Punctuation // // // // // // Reserved words // // // auto createSuper() -> SuperExpression; // auto createThis() -> ThisExpression; // auto createNull() -> NullLiteral; // auto createTrue() -> TrueLiteral; // auto createFalse() -> FalseLiteral; // // // // Modifiers // // // template <typename T/*extends ModifierSyntaxKind*/> auto createModifier(SyntaxKind kind) -> Node; // auto createModifiersFromModifierFlags(ModifierFlags flags) -> ModifiersArray; // // // // Names // // // auto createQualifiedName(EntityName left, string right) -> QualifiedName; auto createQualifiedName(EntityName left, Identifier right) -> QualifiedName; // auto updateQualifiedName(QualifiedName node, EntityName left, Identifier right) -> QualifiedName; auto createComputedPropertyName(Expression expression) -> ComputedPropertyName; // auto updateComputedPropertyName(ComputedPropertyName node, Expression expression) -> ComputedPropertyName; // // // // Signature elements // // // auto createTypeParameterDeclaration(string name, TypeNode constraint = undefined, TypeNode defaultType = undefined) -> // TypeParameterDeclaration; auto createTypeParameterDeclaration(Identifier name, TypeNode constraint = undefined, TypeNode defaultType = undefined) -> TypeParameterDeclaration; // auto updateTypeParameterDeclaration(TypeParameterDeclaration node, Identifier name, TypeNode constraint, TypeNode defaultType) -> // TypeParameterDeclaration; // auto createParameterDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, DotDotDotToken dotDotDotToken, string name, // QuestionToken questionToken = undefined, TypeNode type = undefined, Expression initializer = undefined) -> ParameterDeclaration; auto createParameterDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, DotDotDotToken dotDotDotToken, BindingName name, QuestionToken questionToken = undefined, TypeNode type = undefined, Expression initializer = undefined) -> ParameterDeclaration; // auto updateParameterDeclaration(ParameterDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, DotDotDotToken // dotDotDotToken, string name, QuestionToken questionToken, TypeNode type, Expression initializer) -> ParameterDeclaration; auto // updateParameterDeclaration(ParameterDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, DotDotDotToken // dotDotDotToken, BindingName name, QuestionToken questionToken, TypeNode type, Expression initializer) -> ParameterDeclaration; auto createDecorator(Expression expression) -> Decorator; // auto updateDecorator(Decorator node, Expression expression) -> Decorator; // // // // Type Elements // // // auto createPropertySignature(ModifiersArray modifiers, string name, QuestionToken questionToken, TypeNode type) -> PropertySignature; auto createPropertySignature(ModifiersArray modifiers, PropertyName name, QuestionToken questionToken, TypeNode type) -> PropertySignature; // auto updatePropertySignature(PropertySignature node, ModifiersArray modifiers, PropertyName name, QuestionToken questionToken, // TypeNode type) -> PropertySignature; auto createPropertyDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, string // name, Node questionOrExclamationToken, TypeNode type, Expression initializer) -> PropertyDeclaration; auto createPropertyDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, PropertyName name, Node questionOrExclamationToken, TypeNode type, Expression initializer) -> PropertyDeclaration; // auto updatePropertyDeclaration(PropertyDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, string name, Node // questionOrExclamationToken, TypeNode type, Expression initializer) -> PropertyDeclaration; auto // updatePropertyDeclaration(PropertyDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, PropertyName name, Node // questionOrExclamationToken, TypeNode type, Expression initializer) -> PropertyDeclaration; // auto createMethodSignature(ModifiersArray modifiers, string name, QuestionToken questionToken, NodeArray<TypeParameterDeclaration> // typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> MethodSignature; auto createMethodSignature(ModifiersArray modifiers, PropertyName name, QuestionToken questionToken, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> MethodSignature; // auto updateMethodSignature(MethodSignature node, ModifiersArray modifiers, PropertyName name, QuestionToken questionToken, // NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> MethodSignature; // auto createMethodDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, AsteriskToken asteriskToken, string name, // QuestionToken questionToken, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode // type, Block body) -> MethodDeclaration; auto createMethodDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, AsteriskToken asteriskToken, PropertyName name, QuestionToken questionToken, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) -> MethodDeclaration; // auto updateMethodDeclaration(MethodDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, AsteriskToken // asteriskToken, PropertyName name, QuestionToken questionToken, NodeArray<TypeParameterDeclaration> typeParameters, // NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) -> MethodDeclaration; auto createConstructorDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, NodeArray<ParameterDeclaration> parameters, Block body) -> ConstructorDeclaration; // auto updateConstructorDeclaration(ConstructorDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, // NodeArray<ParameterDeclaration> parameters, Block body) -> ConstructorDeclaration; auto createGetAccessorDeclaration(DecoratorsArray // decorators, ModifiersArray modifiers, string name, NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) -> // GetAccessorDeclaration; auto createGetAccessorDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, PropertyName name, NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) -> GetAccessorDeclaration; // auto updateGetAccessorDeclaration(GetAccessorDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, PropertyName // name, NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) -> GetAccessorDeclaration; auto // createSetAccessorDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, string name, NodeArray<ParameterDeclaration> // parameters, Block body) -> SetAccessorDeclaration; auto createSetAccessorDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, PropertyName name, NodeArray<ParameterDeclaration> parameters, Block body) -> SetAccessorDeclaration; // auto updateSetAccessorDeclaration(SetAccessorDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, PropertyName // name, NodeArray<ParameterDeclaration> parameters, Block body) -> SetAccessorDeclaration; auto createCallSignature(NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> CallSignatureDeclaration; // auto updateCallSignature(CallSignatureDeclaration node, NodeArray<TypeParameterDeclaration> typeParameters, // NodeArray<ParameterDeclaration> parameters, TypeNode type) -> CallSignatureDeclaration; auto createConstructSignature(NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> ConstructSignatureDeclaration; // auto updateConstructSignature(ConstructSignatureDeclaration node, NodeArray<TypeParameterDeclaration> typeParameters, // NodeArray<ParameterDeclaration> parameters, TypeNode type) -> ConstructSignatureDeclaration; auto createIndexSignature(DecoratorsArray decorators, ModifiersArray modifiers, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> IndexSignatureDeclaration; // auto updateIndexSignature(IndexSignatureDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, // NodeArray<ParameterDeclaration> parameters, TypeNode type) -> IndexSignatureDeclaration; auto createTemplateLiteralTypeSpan(TypeNode type, Node literal) -> TemplateLiteralTypeSpan; // auto updateTemplateLiteralTypeSpan(TemplateLiteralTypeSpan node, TypeNode type, Node literal) -> TemplateLiteralTypeSpan; // // // // Types // // // auto createKeywordTypeNode(SyntaxKind kind) -> Node; // auto createTypePredicateNode(AssertsKeyword assertsModifier, string parameterName, TypeNode type) -> TypePredicateNode; auto createTypePredicateNode(AssertsKeyword assertsModifier, Node parameterName, TypeNode type) -> TypePredicateNode; // auto updateTypePredicateNode(TypePredicateNode node, AssertsKeyword assertsModifier, Node parameterName, TypeNode type) -> // TypePredicateNode; auto createTypeReferenceNode(string typeName, NodeArray<TypeNode> typeArguments = undefined) -> TypeReferenceNode; auto createTypeReferenceNode(EntityName typeName, NodeArray<TypeNode> typeArguments = undefined) -> TypeReferenceNode; // auto updateTypeReferenceNode(TypeReferenceNode node, EntityName typeName, NodeArray<TypeNode> typeArguments) -> TypeReferenceNode; auto createFunctionTypeNode(NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> FunctionTypeNode; // auto updateFunctionTypeNode(FunctionTypeNode node, NodeArray<TypeParameterDeclaration> typeParameters, // NodeArray<ParameterDeclaration> parameters, TypeNode type) -> FunctionTypeNode; auto createConstructorTypeNode(ModifiersArray modifiers, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> ConstructorTypeNode; // /** @deprecated */ // auto createConstructorTypeNode(NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, // TypeNode type) -> ConstructorTypeNode; auto updateConstructorTypeNode(ConstructorTypeNode node, ModifiersArray modifiers, // NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> // ConstructorTypeNode; // /** @deprecated */ // auto updateConstructorTypeNode(ConstructorTypeNode node, NodeArray<TypeParameterDeclaration> typeParameters, // NodeArray<ParameterDeclaration> parameters, TypeNode type) -> ConstructorTypeNode; auto createTypeQueryNode(EntityName exprName) -> TypeQueryNode; // auto updateTypeQueryNode(TypeQueryNode node, EntityName exprName) -> TypeQueryNode; auto createTypeLiteralNode(NodeArray<TypeElement> members) -> TypeLiteralNode; // auto updateTypeLiteralNode(TypeLiteralNode node, NodeArray<TypeElement> members) -> TypeLiteralNode; auto createArrayTypeNode(TypeNode elementType) -> ArrayTypeNode; // auto updateArrayTypeNode(ArrayTypeNode node, TypeNode elementType) -> ArrayTypeNode; auto createTupleTypeNode(NodeArray</*TypeNode | NamedTupleMember*/ Node> elements) -> TupleTypeNode; // auto updateTupleTypeNode(TupleTypeNode node, NodeArray</*TypeNode | NamedTupleMember*/Node> elements) -> TupleTypeNode; auto createNamedTupleMember(DotDotDotToken dotDotDotToken, Identifier name, QuestionToken questionToken, TypeNode type) -> NamedTupleMember; // auto updateNamedTupleMember(NamedTupleMember node, DotDotDotToken dotDotDotToken, Identifier name, QuestionToken questionToken, // TypeNode type) -> NamedTupleMember; auto createOptionalTypeNode(TypeNode type) -> OptionalTypeNode; // auto updateOptionalTypeNode(OptionalTypeNode node, TypeNode type) -> OptionalTypeNode; auto createRestTypeNode(TypeNode type) -> RestTypeNode; // auto updateRestTypeNode(RestTypeNode node, TypeNode type) -> RestTypeNode; auto createUnionTypeNode(NodeArray<TypeNode> types) -> UnionTypeNode; // auto updateUnionTypeNode(UnionTypeNode node, NodeArray<TypeNode> types) -> UnionTypeNode; auto createIntersectionTypeNode(NodeArray<TypeNode> types) -> IntersectionTypeNode; // auto updateIntersectionTypeNode(IntersectionTypeNode node, NodeArray<TypeNode> types) -> IntersectionTypeNode; auto createConditionalTypeNode(TypeNode checkType, TypeNode extendsType, TypeNode trueType, TypeNode falseType) -> ConditionalTypeNode; // auto updateConditionalTypeNode(ConditionalTypeNode node, TypeNode checkType, TypeNode extendsType, TypeNode trueType, TypeNode // falseType) -> ConditionalTypeNode; auto createInferTypeNode(TypeParameterDeclaration typeParameter) -> InferTypeNode; // auto updateInferTypeNode(InferTypeNode node, TypeParameterDeclaration typeParameter) -> InferTypeNode; auto createImportTypeNode(TypeNode argument, EntityName qualifier = undefined, NodeArray<TypeNode> typeArguments = undefined, boolean isTypeOf = false) -> ImportTypeNode; // auto updateImportTypeNode(ImportTypeNode node, TypeNode argument, EntityName qualifier, NodeArray<TypeNode> typeArguments, boolean // isTypeOf = false) -> ImportTypeNode; auto createParenthesizedType(TypeNode type) -> ParenthesizedTypeNode; // auto updateParenthesizedType(ParenthesizedTypeNode node, TypeNode type) -> ParenthesizedTypeNode; auto createThisTypeNode() -> ThisTypeNode; auto createTypeOperatorNode(SyntaxKind kind, TypeNode type) -> TypeOperatorNode; // auto updateTypeOperatorNode(TypeOperatorNode node, TypeNode type) -> TypeOperatorNode; auto createIndexedAccessTypeNode(TypeNode objectType, TypeNode indexType) -> IndexedAccessTypeNode; // auto updateIndexedAccessTypeNode(IndexedAccessTypeNode node, TypeNode objectType, TypeNode indexType) -> IndexedAccessTypeNode; auto createMappedTypeNode(Node readonlyToken, TypeParameterDeclaration typeParameter, TypeNode nameType, Node questionToken, TypeNode type) -> MappedTypeNode; // auto updateMappedTypeNode(MappedTypeNode node, Node token, TypeParameterDeclaration typeParameter, TypeNode nameType, Node // questionToken, TypeNode type) -> MappedTypeNode; auto createLiteralTypeNode(LiteralTypeNode literal) -> LiteralTypeNode; // auto updateLiteralTypeNode(LiteralTypeNode node, LiteralTypeNode literal) -> LiteralTypeNode; auto createTemplateLiteralType(TemplateHead head, NodeArray<TemplateLiteralTypeSpan> templateSpans) -> TemplateLiteralTypeNode; // auto updateTemplateLiteralType(TemplateLiteralTypeNode node, TemplateHead head, NodeArray<TemplateLiteralTypeSpan> templateSpans) -> // TemplateLiteralTypeNode; // // // // Binding Patterns // // auto createObjectBindingPattern(NodeArray<BindingElement> elements) -> ObjectBindingPattern; // auto updateObjectBindingPattern(ObjectBindingPattern node, NodeArray<BindingElement> elements) -> ObjectBindingPattern; auto createArrayBindingPattern(NodeArray<ArrayBindingElement> elements) -> ArrayBindingPattern; // auto updateArrayBindingPattern(ArrayBindingPattern node, NodeArray<ArrayBindingElement> elements) -> ArrayBindingPattern; // auto createBindingElement(DotDotDotToken dotDotDotToken, string propertyName, string name, Expression initializer = undefined) -> // BindingElement; auto createBindingElement(DotDotDotToken dotDotDotToken, PropertyName propertyName, BindingName name, Expression initializer = undefined) -> BindingElement; // auto updateBindingElement(BindingElement node, DotDotDotToken dotDotDotToken, PropertyName propertyName, BindingName name, Expression // initializer) -> BindingElement; // // // // Expression // // auto createArrayLiteralExpression(NodeArray<Expression> elements = undefined, boolean multiLine = false) -> ArrayLiteralExpression; // auto updateArrayLiteralExpression(ArrayLiteralExpression node, NodeArray<Expression> elements) -> ArrayLiteralExpression; auto createObjectLiteralExpression(NodeArray<ObjectLiteralElementLike> properties = undefined, boolean multiLine = false) -> ObjectLiteralExpression; // auto updateObjectLiteralExpression(ObjectLiteralExpression node, NodeArray<ObjectLiteralElementLike> properties) -> // ObjectLiteralExpression; auto createPropertyAccessExpression(Expression expression, string name) -> PropertyAccessExpression; auto createPropertyAccessExpression(Expression expression, MemberName name) -> PropertyAccessExpression; // auto updatePropertyAccessExpression(PropertyAccessExpression node, Expression expression, MemberName name) -> // PropertyAccessExpression; auto createPropertyAccessChain(Expression expression, QuestionDotToken questionDotToken, string name) -> // PropertyAccessChain; auto createPropertyAccessChain(Expression expression, QuestionDotToken questionDotToken, MemberName name) -> PropertyAccessChain; // auto updatePropertyAccessChain(PropertyAccessChain node, Expression expression, QuestionDotToken questionDotToken, MemberName name) // -> PropertyAccessChain; auto createElementAccessExpression(Expression expression, number index) -> ElementAccessExpression; auto createElementAccessExpression(Expression expression, Expression index) -> ElementAccessExpression; // auto updateElementAccessExpression(ElementAccessExpression node, Expression expression, Expression argumentExpression) -> // ElementAccessExpression; auto createElementAccessChain(Expression expression, QuestionDotToken questionDotToken, number index) -> // ElementAccessChain; auto createElementAccessChain(Expression expression, QuestionDotToken questionDotToken, Expression index) -> ElementAccessChain; // auto updateElementAccessChain(ElementAccessChain node, Expression expression, QuestionDotToken questionDotToken, Expression // argumentExpression) -> ElementAccessChain; auto createCallExpression(Expression expression, NodeArray<TypeNode> typeArguments, NodeArray<Expression> argumentsArray) -> CallExpression; auto updateCallExpression(CallExpression node, Expression expression, NodeArray<TypeNode> typeArguments, NodeArray<Expression> argumentsArray) -> CallExpression; auto createCallChain(Expression expression, QuestionDotToken questionDotToken, NodeArray<TypeNode> typeArguments, NodeArray<Expression> argumentsArray) -> CallChain; // auto updateCallChain(CallChain node, Expression expression, QuestionDotToken questionDotToken, NodeArray<TypeNode> typeArguments, // NodeArray<Expression> argumentsArray) -> CallChain; auto createNewExpression(Expression expression, NodeArray<TypeNode> typeArguments, NodeArray<Expression> argumentsArray) -> NewExpression; // auto updateNewExpression(NewExpression node, Expression expression, NodeArray<TypeNode> typeArguments, NodeArray<Expression> // argumentsArray) -> NewExpression; auto createTaggedTemplateExpression(Expression tag, NodeArray<TypeNode> typeArguments, TemplateLiteral _template) -> TaggedTemplateExpression; // auto updateTaggedTemplateExpression(TaggedTemplateExpression node, Expression tag, NodeArray<TypeNode> typeArguments, TemplateLiteral // _template) -> TaggedTemplateExpression; auto createTypeAssertion(TypeNode type, Expression expression) -> TypeAssertion; // auto updateTypeAssertion(TypeAssertion node, TypeNode type, Expression expression) -> TypeAssertion; auto createParenthesizedExpression(Expression expression) -> ParenthesizedExpression; // auto updateParenthesizedExpression(ParenthesizedExpression node, Expression expression) -> ParenthesizedExpression; // auto createFunctionExpression(ModifiersArray modifiers, AsteriskToken asteriskToken, string name, NodeArray<TypeParameterDeclaration> // typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) -> FunctionExpression; auto createFunctionExpression(ModifiersArray modifiers, AsteriskToken asteriskToken, Identifier name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) -> FunctionExpression; // auto updateFunctionExpression(FunctionExpression node, ModifiersArray modifiers, AsteriskToken asteriskToken, Identifier name, // NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) -> // FunctionExpression; auto createArrowFunction(ModifiersArray modifiers, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type, EqualsGreaterThanToken equalsGreaterThanToken, ConciseBody body) -> ArrowFunction; // auto updateArrowFunction(ArrowFunction node, ModifiersArray modifiers, NodeArray<TypeParameterDeclaration> typeParameters, // NodeArray<ParameterDeclaration> parameters, TypeNode type, EqualsGreaterThanToken equalsGreaterThanToken, ConciseBody body) -> // ArrowFunction; auto createDeleteExpression(Expression expression) -> DeleteExpression; // auto updateDeleteExpression(DeleteExpression node, Expression expression) -> DeleteExpression; auto createTypeOfExpression(Expression expression) -> TypeOfExpression; // auto updateTypeOfExpression(TypeOfExpression node, Expression expression) -> TypeOfExpression; auto createVoidExpression(Expression expression) -> VoidExpression; // auto updateVoidExpression(VoidExpression node, Expression expression) -> VoidExpression; auto createAwaitExpression(Expression expression) -> AwaitExpression; // auto updateAwaitExpression(AwaitExpression node, Expression expression) -> AwaitExpression; auto createPrefixUnaryExpression(PrefixUnaryOperator _operator, Expression operand) -> PrefixUnaryExpression; // auto updatePrefixUnaryExpression(PrefixUnaryExpression node, Expression operand) -> PrefixUnaryExpression; auto createPostfixUnaryExpression(Expression operand, PostfixUnaryOperator _operator) -> PostfixUnaryExpression; // auto updatePostfixUnaryExpression(PostfixUnaryExpression node, Expression operand) -> PostfixUnaryExpression; auto createBinaryExpression(Expression left, Node _operator, Expression right) -> BinaryExpression; // auto updateBinaryExpression(BinaryExpression node, Expression left, Node _operator, Expression right) -> BinaryExpression; auto createConditionalExpression(Expression condition, QuestionToken questionToken, Expression whenTrue, ColonToken colonToken, Expression whenFalse) -> ConditionalExpression; // auto updateConditionalExpression(ConditionalExpression node, Expression condition, QuestionToken questionToken, Expression whenTrue, // ColonToken colonToken, Expression whenFalse) -> ConditionalExpression; auto createTemplateExpression(TemplateHead head, NodeArray<TemplateSpan> templateSpans) -> TemplateExpression; // auto updateTemplateExpression(TemplateExpression node, TemplateHead head, NodeArray<TemplateSpan> templateSpans) -> // TemplateExpression; auto createTemplateHead(string text, string rawText = string(), TokenFlags templateFlags = TokenFlags::None) -> TemplateHead; auto createTemplateMiddle(string text, string rawText = string(), TokenFlags templateFlags = TokenFlags::None) -> TemplateMiddle; auto createTemplateTail(string text, string rawText = string(), TokenFlags templateFlags = TokenFlags::None) -> TemplateTail; auto createNoSubstitutionTemplateLiteral(string text, string rawText = string(), TokenFlags templateFlags = TokenFlags::None) -> NoSubstitutionTemplateLiteral; /* @internal */ auto createLiteralLikeNode(SyntaxKind kind, string text) -> LiteralLikeNode; /* @internal */ auto createTemplateLiteralLikeNodeChecked(SyntaxKind kind, string text, string rawText = string(), TokenFlags templateFlags = TokenFlags::None) -> TemplateLiteralLikeNode; /* @internal */ auto createTemplateLiteralLikeNode(SyntaxKind kind, string text, string rawText = string(), TokenFlags templateFlags = TokenFlags::None) -> TemplateLiteralLikeNode; auto createYieldExpression(AsteriskToken asteriskToken, Expression expression) -> YieldExpression; // auto updateYieldExpression(YieldExpression node, AsteriskToken asteriskToken, Expression expression) -> YieldExpression; auto createSpreadElement(Expression expression) -> SpreadElement; // auto updateSpreadElement(SpreadElement node, Expression expression) -> SpreadElement; // auto createClassExpression(DecoratorsArray decorators, ModifiersArray modifiers, string name, NodeArray<TypeParameterDeclaration> // typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<ClassElement> members) -> ClassExpression; auto createClassExpression(DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<ClassElement> members) -> ClassExpression; // auto updateClassExpression(ClassExpression node, DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, // NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<ClassElement> members) -> // ClassExpression; auto createOmittedExpression() -> OmittedExpression; auto createExpressionWithTypeArguments(Expression expression, NodeArray<TypeNode> typeArguments) -> ExpressionWithTypeArguments; // auto updateExpressionWithTypeArguments(ExpressionWithTypeArguments node, Expression expression, NodeArray<TypeNode> typeArguments) -> // ExpressionWithTypeArguments; auto createAsExpression(Expression expression, TypeNode type) -> AsExpression; // auto updateAsExpression(AsExpression node, Expression expression, TypeNode type) -> AsExpression; auto createNonNullExpression(Expression expression) -> NonNullExpression; // auto updateNonNullExpression(NonNullExpression node, Expression expression) -> NonNullExpression; auto createNonNullChain(Expression expression) -> NonNullChain; // auto updateNonNullChain(NonNullChain node, Expression expression) -> NonNullChain; auto createMetaProperty(SyntaxKind keywordToken, Identifier name) -> MetaProperty; // auto updateMetaProperty(MetaProperty node, Identifier name) -> MetaProperty; // // // // Misc // // auto createTemplateSpan(Expression expression, Node literal) -> TemplateSpan; // auto updateTemplateSpan(TemplateSpan node, Expression expression, Node literal) -> TemplateSpan; auto createSemicolonClassElement() -> SemicolonClassElement; // // // // Element // // auto createBlock(NodeArray<Statement> statements, boolean multiLine = false) -> Block; // auto updateBlock(Block node, NodeArray<Statement> statements) -> Block; // auto createVariableStatement(ModifiersArray modifiers, NodeArray<VariableDeclaration> declarationList) -> VariableStatement; auto createVariableStatement(ModifiersArray modifiers, VariableDeclarationList declarationList) -> VariableStatement; // auto updateVariableStatement(VariableStatement node, ModifiersArray modifiers, VariableDeclarationList declarationList) -> // VariableStatement; auto createEmptyStatement() -> EmptyStatement; auto createExpressionStatement(Expression expression) -> ExpressionStatement; // auto updateExpressionStatement(ExpressionStatement node, Expression expression) -> ExpressionStatement; auto createIfStatement(Expression expression, Statement thenStatement, Statement elseStatement = undefined) -> IfStatement; // auto updateIfStatement(IfStatement node, Expression expression, Statement thenStatement, Statement elseStatement) -> IfStatement; auto createDoStatement(Statement statement, Expression expression) -> DoStatement; // auto updateDoStatement(DoStatement node, Statement statement, Expression expression) -> DoStatement; auto createWhileStatement(Expression expression, Statement statement) -> WhileStatement; // auto updateWhileStatement(WhileStatement node, Expression expression, Statement statement) -> WhileStatement; auto createForStatement(ForInitializer initializer, Expression condition, Expression incrementor, Statement statement) -> ForStatement; // auto updateForStatement(ForStatement node, ForInitializer initializer, Expression condition, Expression incrementor, Statement // statement) -> ForStatement; auto createForInStatement(ForInitializer initializer, Expression expression, Statement statement) -> ForInStatement; // auto updateForInStatement(ForInStatement node, ForInitializer initializer, Expression expression, Statement statement) -> // ForInStatement; auto createForOfStatement(AwaitKeyword awaitModifier, ForInitializer initializer, Expression expression, Statement statement) -> ForOfStatement; // auto updateForOfStatement(ForOfStatement node, AwaitKeyword awaitModifier, ForInitializer initializer, Expression expression, // Statement statement) -> ForOfStatement; auto createContinueStatement(Identifier label = undefined) -> ContinueStatement; // auto createContinueStatement(string label) -> ContinueStatement; // auto updateContinueStatement(ContinueStatement node, Identifier label) -> ContinueStatement; // auto createBreakStatement(string label) -> BreakStatement; auto createBreakStatement(Identifier label = undefined) -> BreakStatement; // auto updateBreakStatement(BreakStatement node, Identifier label) -> BreakStatement; auto createReturnStatement(Expression expression = undefined) -> ReturnStatement; // auto updateReturnStatement(ReturnStatement node, Expression expression) -> ReturnStatement; auto createWithStatement(Expression expression, Statement statement) -> WithStatement; // auto updateWithStatement(WithStatement node, Expression expression, Statement statement) -> WithStatement; auto createSwitchStatement(Expression expression, CaseBlock caseBlock) -> SwitchStatement; // auto updateSwitchStatement(SwitchStatement node, Expression expression, CaseBlock caseBlock) -> SwitchStatement; // auto createLabeledStatement(string label, Statement statement) -> LabeledStatement; auto createLabeledStatement(Identifier label, Statement statement) -> LabeledStatement; // auto updateLabeledStatement(LabeledStatement node, Identifier label, Statement statement) -> LabeledStatement; auto createThrowStatement(Expression expression) -> ThrowStatement; // auto updateThrowStatement(ThrowStatement node, Expression expression) -> ThrowStatement; auto createTryStatement(Block tryBlock, CatchClause catchClause, Block finallyBlock) -> TryStatement; // auto updateTryStatement(TryStatement node, Block tryBlock, CatchClause catchClause, Block finallyBlock) -> TryStatement; auto createDebuggerStatement() -> DebuggerStatement; // auto createVariableDeclaration(string name, ExclamationToken exclamationToken = undefined, TypeNode type = undefined, Expression // initializer = undefined) -> VariableDeclaration; auto createVariableDeclaration(BindingName name, ExclamationToken exclamationToken = undefined, TypeNode type = undefined, Expression initializer = undefined) -> VariableDeclaration; // auto updateVariableDeclaration(VariableDeclaration node, BindingName name, ExclamationToken exclamationToken, TypeNode type, // Expression initializer) -> VariableDeclaration; auto createVariableDeclarationList(NodeArray<VariableDeclaration> declarations, NodeFlags flags = (NodeFlags)0) -> VariableDeclarationList; // auto updateVariableDeclarationList(VariableDeclarationList node, NodeArray<VariableDeclaration> declarations) -> // VariableDeclarationList; auto createFunctionDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, AsteriskToken // asteriskToken, string name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode // type, Block body) -> FunctionDeclaration; auto createFunctionDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, AsteriskToken asteriskToken, Identifier name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, TypeNode type, Block body) -> FunctionDeclaration; // auto updateFunctionDeclaration(FunctionDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, AsteriskToken // asteriskToken, Identifier name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<ParameterDeclaration> parameters, // TypeNode type, Block body) -> FunctionDeclaration; auto createClassDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, // string name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<ClassElement> // members) -> ClassDeclaration; auto createClassDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<ClassElement> members) -> ClassDeclaration; // auto updateClassDeclaration(ClassDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, // NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<ClassElement> members) -> // ClassDeclaration; auto createInterfaceDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, string name, // NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<TypeElement> members) -> // InterfaceDeclaration; auto createInterfaceDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<TypeElement> members) -> InterfaceDeclaration; // auto updateInterfaceDeclaration(InterfaceDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, // NodeArray<TypeParameterDeclaration> typeParameters, NodeArray<HeritageClause> heritageClauses, NodeArray<TypeElement> members) -> // InterfaceDeclaration; auto createTypeAliasDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, string name, // NodeArray<TypeParameterDeclaration> typeParameters, TypeNode type) -> TypeAliasDeclaration; auto createTypeAliasDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, NodeArray<TypeParameterDeclaration> typeParameters, TypeNode type) -> TypeAliasDeclaration; // auto updateTypeAliasDeclaration(TypeAliasDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, // NodeArray<TypeParameterDeclaration> typeParameters, TypeNode type) -> TypeAliasDeclaration; auto // createEnumDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, string name, NodeArray<EnumMember> members) -> // EnumDeclaration; auto createEnumDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, NodeArray<EnumMember> members) -> EnumDeclaration; // auto updateEnumDeclaration(EnumDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, Identifier name, // NodeArray<EnumMember> members) -> EnumDeclaration; auto createModuleDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, ModuleName name, ModuleBody body, NodeFlags flags = (NodeFlags)0) -> ModuleDeclaration; // auto updateModuleDeclaration(ModuleDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, ModuleName name, // ModuleBody body) -> ModuleDeclaration; auto createModuleBlock(NodeArray<Statement> statements) -> ModuleBlock; // auto updateModuleBlock(ModuleBlock node, NodeArray<Statement> statements) -> ModuleBlock; auto createCaseBlock(NodeArray<CaseOrDefaultClause> clauses) -> CaseBlock; // auto updateCaseBlock(CaseBlock node, NodeArray<CaseOrDefaultClause> clauses) -> CaseBlock; // auto createNamespaceExportDeclaration(string name) -> NamespaceExportDeclaration; auto createNamespaceExportDeclaration(Identifier name) -> NamespaceExportDeclaration; // auto updateNamespaceExportDeclaration(NamespaceExportDeclaration node, Identifier name) -> NamespaceExportDeclaration; // auto createImportEqualsDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, boolean isTypeOnly, string name, // ModuleReference moduleReference) -> ImportEqualsDeclaration; auto createImportEqualsDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, boolean isTypeOnly, Identifier name, ModuleReference moduleReference) -> ImportEqualsDeclaration; // auto updateImportEqualsDeclaration(ImportEqualsDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, boolean // isTypeOnly, Identifier name, ModuleReference moduleReference) -> ImportEqualsDeclaration; auto createImportDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, ImportClause importClause, Expression moduleSpecifier) -> ImportDeclaration; // auto updateImportDeclaration(ImportDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, ImportClause importClause, // Expression moduleSpecifier) -> ImportDeclaration; auto createImportClause(boolean isTypeOnly, Identifier name, NamedImportBindings namedBindings) -> ImportClause; // auto updateImportClause(ImportClause node, boolean isTypeOnly, Identifier name, NamedImportBindings namedBindings) -> ImportClause; auto createNamespaceImport(Identifier name) -> NamespaceImport; // auto updateNamespaceImport(NamespaceImport node, Identifier name) -> NamespaceImport; auto createNamespaceExport(Identifier name) -> NamespaceExport; // auto updateNamespaceExport(NamespaceExport node, Identifier name) -> NamespaceExport; auto createNamedImports(NodeArray<ImportSpecifier> elements) -> NamedImports; // auto updateNamedImports(NamedImports node, NodeArray<ImportSpecifier> elements) -> NamedImports; auto createImportSpecifier(Identifier propertyName, Identifier name) -> ImportSpecifier; // auto updateImportSpecifier(ImportSpecifier node, Identifier propertyName, Identifier name) -> ImportSpecifier; auto createExportAssignment(DecoratorsArray decorators, ModifiersArray modifiers, boolean isExportEquals, Expression expression) -> ExportAssignment; // auto updateExportAssignment(ExportAssignment node, DecoratorsArray decorators, ModifiersArray modifiers, Expression expression) -> // ExportAssignment; auto createExportDeclaration(DecoratorsArray decorators, ModifiersArray modifiers, boolean isTypeOnly, NamedExportBindings exportClause, Expression moduleSpecifier = undefined) -> ExportDeclaration; // auto updateExportDeclaration(ExportDeclaration node, DecoratorsArray decorators, ModifiersArray modifiers, boolean isTypeOnly, // NamedExportBindings exportClause, Expression moduleSpecifier) -> ExportDeclaration; auto createNamedExports(NodeArray<ExportSpecifier> elements) -> NamedExports; // auto updateNamedExports(NamedExports node, NodeArray<ExportSpecifier> elements) -> NamedExports; // auto createExportSpecifier(string propertyName, string name) -> ExportSpecifier; auto createExportSpecifier(Identifier propertyName, Identifier name) -> ExportSpecifier; // auto updateExportSpecifier(ExportSpecifier node, Identifier propertyName, Identifier name) -> ExportSpecifier; /* @internal*/ auto createMissingDeclaration() -> MissingDeclaration; // // // // Module references // // auto createExternalModuleReference(Expression expression) -> ExternalModuleReference; // auto updateExternalModuleReference(ExternalModuleReference node, Expression expression) -> ExternalModuleReference; // // // // JSDoc // // auto getDefaultTagName(JSDocTag node) -> Identifier; auto createJSDocAllType() -> JSDocAllType; auto createJSDocUnknownType() -> JSDocUnknownType; auto createJSDocNonNullableType(TypeNode type) -> JSDocNonNullableType; // auto updateJSDocNonNullableType(JSDocNonNullableType node, TypeNode type) -> JSDocNonNullableType; auto createJSDocNullableType(TypeNode type) -> JSDocNullableType; // auto updateJSDocNullableType(JSDocNullableType node, TypeNode type) -> JSDocNullableType; auto createJSDocOptionalType(TypeNode type) -> JSDocOptionalType; // auto updateJSDocOptionalType(JSDocOptionalType node, TypeNode type) -> JSDocOptionalType; auto createJSDocFunctionType(NodeArray<ParameterDeclaration> parameters, TypeNode type) -> JSDocFunctionType; // auto updateJSDocFunctionType(JSDocFunctionType node, NodeArray<ParameterDeclaration> parameters, TypeNode type) -> JSDocFunctionType; auto createJSDocVariadicType(TypeNode type) -> JSDocVariadicType; // auto updateJSDocVariadicType(JSDocVariadicType node, TypeNode type) -> JSDocVariadicType; auto createJSDocNamepathType(TypeNode type) -> JSDocNamepathType; // auto updateJSDocNamepathType(JSDocNamepathType node, TypeNode type) -> JSDocNamepathType; auto createJSDocTypeExpression(TypeNode type) -> JSDocTypeExpression; // auto updateJSDocTypeExpression(JSDocTypeExpression node, TypeNode type) -> JSDocTypeExpression; auto createJSDocNameReference(EntityName name) -> JSDocNameReference; // auto updateJSDocNameReference(JSDocNameReference node, EntityName name) -> JSDocNameReference; auto createJSDocTypeLiteral(NodeArray<JSDocPropertyLikeTag> jsDocPropertyTags = undefined, boolean isArrayType = false) -> JSDocTypeLiteral; // auto updateJSDocTypeLiteral(JSDocTypeLiteral node, NodeArray<JSDocPropertyLikeTag> jsDocPropertyTags, boolean isArrayType) -> // JSDocTypeLiteral; auto createJSDocSignature(NodeArray<JSDocTemplateTag> typeParameters, NodeArray<JSDocParameterTag> parameters, JSDocReturnTag type = undefined) -> JSDocSignature; // auto updateJSDocSignature(JSDocSignature node, NodeArray<JSDocTemplateTag> typeParameters, NodeArray<JSDocParameterTag> parameters, // JSDocReturnTag type) -> JSDocSignature; auto createJSDocTemplateTag(Identifier tagName, JSDocTypeExpression constraint, NodeArray<TypeParameterDeclaration> typeParameters, string comment = string()) -> JSDocTemplateTag; // auto updateJSDocTemplateTag(JSDocTemplateTag node, Identifier tagName, JSDocTypeExpression constraint, // NodeArray<TypeParameterDeclaration> typeParameters, string comment) -> JSDocTemplateTag; auto createJSDocTypedefTag(Identifier tagName, /*JSDocTypeExpression | JSDocTypeLiteral*/ Node typeExpression = undefined, /*Identifier | JSDocNamespaceDeclaration*/ Node fullName = undefined, string comment = string()) -> JSDocTypedefTag; // auto updateJSDocTypedefTag(JSDocTypedefTag node, Identifier tagName, /*JSDocTypeExpression | JSDocTypeLiteral*/Node typeExpression, // /*Identifier | JSDocNamespaceDeclaration*/Node fullName, string comment) -> JSDocTypedefTag; auto createJSDocParameterTag(Identifier tagName, EntityName name, boolean isBracketed, JSDocTypeExpression typeExpression = undefined, boolean isNameFirst = false, string comment = string()) -> JSDocParameterTag; // auto updateJSDocParameterTag(JSDocParameterTag node, Identifier tagName, EntityName name, boolean isBracketed, JSDocTypeExpression // typeExpression, boolean isNameFirst, string comment) -> JSDocParameterTag; auto createJSDocPropertyTag(Identifier tagName, EntityName name, boolean isBracketed, JSDocTypeExpression typeExpression = undefined, boolean isNameFirst = false, string comment = string()) -> JSDocPropertyTag; // auto updateJSDocPropertyTag(JSDocPropertyTag node, Identifier tagName, EntityName name, boolean isBracketed, JSDocTypeExpression // typeExpression, boolean isNameFirst, string comment) -> JSDocPropertyTag; auto createJSDocTypeTag(Identifier tagName, JSDocTypeExpression typeExpression, string comment = string()) -> JSDocTypeTag; // auto updateJSDocTypeTag(JSDocTypeTag node, Identifier tagName, JSDocTypeExpression typeExpression, string comment) -> JSDocTypeTag; auto createJSDocSeeTag(Identifier tagName, JSDocNameReference nameExpression, string comment = string()) -> JSDocSeeTag; // auto updateJSDocSeeTag(JSDocSeeTag node, Identifier tagName, JSDocNameReference nameExpression, string comment = string()) -> // JSDocSeeTag; auto createJSDocReturnTag(Identifier tagName, JSDocTypeExpression typeExpression = undefined, string comment = string()) -> JSDocReturnTag; // auto updateJSDocReturnTag(JSDocReturnTag node, Identifier tagName, JSDocTypeExpression typeExpression, string comment) -> // JSDocReturnTag; auto createJSDocThisTag(Identifier tagName, JSDocTypeExpression typeExpression, string comment = string()) -> JSDocThisTag; // auto updateJSDocThisTag(JSDocThisTag node, Identifier tagName, JSDocTypeExpression typeExpression, string comment) -> JSDocThisTag; auto createJSDocEnumTag(Identifier tagName, JSDocTypeExpression typeExpression, string comment = string()) -> JSDocEnumTag; // auto updateJSDocEnumTag(JSDocEnumTag node, Identifier tagName, JSDocTypeExpression typeExpression, string comment) -> JSDocEnumTag; auto createJSDocCallbackTag(Identifier tagName, JSDocSignature typeExpression, /*Identifier | JSDocNamespaceDeclaration*/ Node fullName, string comment = string()) -> JSDocCallbackTag; // auto updateJSDocCallbackTag(JSDocCallbackTag node, Identifier tagName, JSDocSignature typeExpression, /*Identifier | // JSDocNamespaceDeclaration*/Node fullName, string comment) -> JSDocCallbackTag; auto createJSDocAugmentsTag(Identifier tagName, JSDocAugmentsTag className, string comment = string()) -> JSDocAugmentsTag; // auto updateJSDocAugmentsTag(JSDocAugmentsTag node, Identifier tagName, JSDocAugmentsTag className, string comment) -> // JSDocAugmentsTag; auto createJSDocImplementsTag(Identifier tagName, JSDocImplementsTag className, string comment = string()) -> JSDocImplementsTag; // auto updateJSDocImplementsTag(JSDocImplementsTag node, Identifier tagName, JSDocImplementsTag className, string comment) -> // JSDocImplementsTag; auto createJSDocAuthorTag(Identifier tagName, string comment = string()) -> JSDocAuthorTag; // auto updateJSDocAuthorTag(JSDocAuthorTag node, Identifier tagName, string comment) -> JSDocAuthorTag; auto createJSDocClassTag(Identifier tagName, string comment = string()) -> JSDocClassTag; // auto updateJSDocClassTag(JSDocClassTag node, Identifier tagName, string comment) -> JSDocClassTag; auto createJSDocPublicTag(Identifier tagName, string comment = string()) -> JSDocPublicTag; // auto updateJSDocPublicTag(JSDocPublicTag node, Identifier tagName, string comment) -> JSDocPublicTag; auto createJSDocPrivateTag(Identifier tagName, string comment = string()) -> JSDocPrivateTag; // auto updateJSDocPrivateTag(JSDocPrivateTag node, Identifier tagName, string comment) -> JSDocPrivateTag; auto createJSDocProtectedTag(Identifier tagName, string comment = string()) -> JSDocProtectedTag; // auto updateJSDocProtectedTag(JSDocProtectedTag node, Identifier tagName, string comment) -> JSDocProtectedTag; auto createJSDocReadonlyTag(Identifier tagName, string comment = string()) -> JSDocReadonlyTag; // auto updateJSDocReadonlyTag(JSDocReadonlyTag node, Identifier tagName, string comment) -> JSDocReadonlyTag; auto createJSDocUnknownTag(Identifier tagName, string comment = string()) -> JSDocUnknownTag; // auto updateJSDocUnknownTag(JSDocUnknownTag node, Identifier tagName, string comment) -> JSDocUnknownTag; auto createJSDocDeprecatedTag(Identifier tagName, string comment = string()) -> JSDocDeprecatedTag; // auto updateJSDocDeprecatedTag(JSDocDeprecatedTag node, Identifier tagName, string comment = string()) -> JSDocDeprecatedTag; auto createJSDocComment(string comment = string(), NodeArray<JSDocTag> tags = undefined) -> JSDoc; // auto updateJSDocComment(JSDoc node, string comment, NodeArray<JSDocTag> tags) -> JSDoc; // // // // JSX // // auto createJsxElement(JsxOpeningElement openingElement, NodeArray<JsxChild> children, JsxClosingElement closingElement) -> JsxElement; // auto updateJsxElement(JsxElement node, JsxOpeningElement openingElement, NodeArray<JsxChild> children, JsxClosingElement // closingElement) -> JsxElement; auto createJsxSelfClosingElement(JsxTagNameExpression tagName, NodeArray<TypeNode> typeArguments, JsxAttributes attributes) -> JsxSelfClosingElement; // auto updateJsxSelfClosingElement(JsxSelfClosingElement node, JsxTagNameExpression tagName, NodeArray<TypeNode> typeArguments, // JsxAttributes attributes) -> JsxSelfClosingElement; auto createJsxOpeningElement(JsxTagNameExpression tagName, NodeArray<TypeNode> typeArguments, JsxAttributes attributes) -> JsxOpeningElement; // auto updateJsxOpeningElement(JsxOpeningElement node, JsxTagNameExpression tagName, NodeArray<TypeNode> typeArguments, JsxAttributes // attributes) -> JsxOpeningElement; auto createJsxClosingElement(JsxTagNameExpression tagName) -> JsxClosingElement; // auto updateJsxClosingElement(JsxClosingElement node, JsxTagNameExpression tagName) -> JsxClosingElement; auto createJsxFragment(JsxOpeningFragment openingFragment, NodeArray<JsxChild> children, JsxClosingFragment closingFragment) -> JsxFragment; auto createJsxText(string text, boolean containsOnlyTriviaWhiteSpaces = false) -> JsxText; // auto updateJsxText(JsxText node, string text, boolean containsOnlyTriviaWhiteSpaces = false) -> JsxText; auto createJsxOpeningFragment() -> JsxOpeningFragment; auto createJsxJsxClosingFragment() -> JsxClosingFragment; // auto updateJsxFragment(JsxFragment node, JsxOpeningFragment openingFragment, NodeArray<JsxChild> children, JsxClosingFragment // closingFragment) -> JsxFragment; auto createJsxAttribute(Identifier name, /*StringLiteral | JsxExpression*/ Node initializer) -> JsxAttribute; // auto updateJsxAttribute(JsxAttribute node, Identifier name, /*StringLiteral | JsxExpression*/Node initializer) -> JsxAttribute; auto createJsxAttributes(NodeArray<JsxAttributeLike> properties) -> JsxAttributes; // auto updateJsxAttributes(JsxAttributes node, NodeArray<JsxAttributeLike> properties) -> JsxAttributes; auto createJsxSpreadAttribute(Expression expression) -> JsxSpreadAttribute; // auto updateJsxSpreadAttribute(JsxSpreadAttribute node, Expression expression) -> JsxSpreadAttribute; auto createJsxExpression(DotDotDotToken dotDotDotToken, Expression expression) -> JsxExpression; // auto updateJsxExpression(JsxExpression node, Expression expression) -> JsxExpression; // // // // Clauses // // auto createCaseClause(Expression expression, NodeArray<Statement> statements) -> CaseClause; // auto updateCaseClause(CaseClause node, Expression expression, NodeArray<Statement> statements) -> CaseClause; auto createDefaultClause(NodeArray<Statement> statements) -> DefaultClause; // auto updateDefaultClause(DefaultClause node, NodeArray<Statement> statements) -> DefaultClause; auto createHeritageClause(/*HeritageClause*/ SyntaxKind token, NodeArray<ExpressionWithTypeArguments> types) -> HeritageClause; // auto updateHeritageClause(HeritageClause node, NodeArray<ExpressionWithTypeArguments> types) -> HeritageClause; // auto createCatchClause(string variableDeclaration, Block block) -> CatchClause; auto createCatchClause(VariableDeclaration variableDeclaration, Block block) -> CatchClause; // auto updateCatchClause(CatchClause node, VariableDeclaration variableDeclaration, Block block) -> CatchClause; // // // // Property assignments // // // auto createPropertyAssignment(string name, Expression initializer) -> PropertyAssignment; auto createPropertyAssignment(PropertyName name, Expression initializer) -> PropertyAssignment; // auto updatePropertyAssignment(PropertyAssignment node, PropertyName name, Expression initializer) -> PropertyAssignment; // auto createShorthandPropertyAssignment(string name, Expression objectAssignmentInitializer = undefined) -> // ShorthandPropertyAssignment; auto createShorthandPropertyAssignment(Identifier name, Expression objectAssignmentInitializer = undefined) -> ShorthandPropertyAssignment; // auto updateShorthandPropertyAssignment(ShorthandPropertyAssignment node, Identifier name, Expression objectAssignmentInitializer) -> // ShorthandPropertyAssignment; auto createSpreadAssignment(Expression expression) -> SpreadAssignment; // auto updateSpreadAssignment(SpreadAssignment node, Expression expression) -> SpreadAssignment; // // // // Enum // // // auto createEnumMember(string name, Expression initializer = undefined) -> EnumMember; auto createEnumMember(PropertyName name, Expression initializer = undefined) -> EnumMember; // auto updateEnumMember(EnumMember node, PropertyName name, Expression initializer) -> EnumMember; // // // // Top-level nodes // // auto createSourceFile(NodeArray<Statement> statements, EndOfFileToken endOfFileToken, NodeFlags flags) -> SourceFile; auto cloneSourceFileWithChanges(SourceFile node, NodeArray<Statement> statements, boolean isDeclarationFile, NodeArray<FileReference> referencedFiles, NodeArray<FileReference> typeReferences, boolean hasNoDefaultLib, NodeArray<FileReference> libReferences) -> SourceFile; auto updateSourceFile(SourceFile node, NodeArray<Statement> statements, boolean isDeclarationFile = false, NodeArray<FileReference> referencedFiles = undefined, NodeArray<FileReference> typeReferences = undefined, boolean hasNoDefaultLib = false, NodeArray<FileReference> libReferences = undefined) -> SourceFile; // /* @internal */ auto createUnparsedSource(NodeArray<UnparsedPrologue> prologues, NodeArray<UnparsedSyntheticReference> // syntheticReferences, NodeArray<UnparsedSourceText> texts) -> UnparsedSource; // /* @internal */ auto createUnparsedPrologue(string data = string()) -> UnparsedPrologue; // /* @internal */ auto createUnparsedPrepend(string data, NodeArray<UnparsedSourceText> texts) -> UnparsedPrepend; // /* @internal */ auto createUnparsedTextLike(string data, boolean internal) -> UnparsedTextLike; // /* @internal */ auto createUnparsedSyntheticReference(/*BundleFileHasNoDefaultLib | BundleFileReference*/Node section) -> // UnparsedSyntheticReference; // /* @internal */ auto createInputFiles() -> InputFiles; // // // // Synthetic Nodes // // // /* @internal */ auto createSyntheticExpression(SignatureFlags type, boolean isSpread = false, /*NamedTupleMember | // ParameterDeclaration*/Node tupleNameSource = undefined) -> SyntheticExpression; // /* @internal */ auto createSyntaxList(NodeArray<Node> children) -> SyntaxList; // // // // Transformation nodes // // // auto createNotEmittedStatement(Node original) -> NotEmittedStatement; // /* @internal */ auto createEndOfDeclarationMarker(Node original) -> EndOfDeclarationMarker; // /* @internal */ auto createMergeDeclarationMarker(Node original) -> MergeDeclarationMarker; // auto createPartiallyEmittedExpression(Expression expression, Node original = undefined) -> PartiallyEmittedExpression; // auto updatePartiallyEmittedExpression(PartiallyEmittedExpression node, Expression expression) -> PartiallyEmittedExpression; // /* @internal */ auto createSyntheticReferenceExpression(Expression expression, Expression thisArg) -> SyntheticReferenceExpression; // /* @internal */ auto updateSyntheticReferenceExpression(SyntheticReferenceExpression node, Expression expression, Expression thisArg) // -> SyntheticReferenceExpression; auto createCommaListExpression(NodeArray<Expression> elements) -> CommaListExpression; auto // updateCommaListExpression(CommaListExpression node, NodeArray<Expression> elements) -> CommaListExpression; auto // createBundle(NodeArray<SourceFile> sourceFiles, NodeArray</*UnparsedSource | InputFiles*/Node> prepends = undefined) -> Bundle; auto // updateBundle(Bundle node, NodeArray<SourceFile> sourceFiles, NodeArray</*UnparsedSource | InputFiles*/Node> prepends = undefined) -> // Bundle; // // // // Common operators // // // auto createComma(Expression left, Expression right) -> BinaryExpression; // auto createAssignment(Expression left, Expression right) -> /*DestructuringAssignment | AssignmentExpression<EqualsToken>*/Node; // auto createLogicalOr(Expression left, Expression right) -> BinaryExpression; // auto createLogicalAnd(Expression left, Expression right) -> BinaryExpression; // auto createBitwiseOr(Expression left, Expression right) -> BinaryExpression; // auto createBitwiseXor(Expression left, Expression right) -> BinaryExpression; // auto createBitwiseAnd(Expression left, Expression right) -> BinaryExpression; // auto createStrictEquality(Expression left, Expression right) -> BinaryExpression; // auto createStrictInequality(Expression left, Expression right) -> BinaryExpression; // auto createEquality(Expression left, Expression right) -> BinaryExpression; // auto createInequality(Expression left, Expression right) -> BinaryExpression; // auto createLessThan(Expression left, Expression right) -> BinaryExpression; // auto createLessThanEquals(Expression left, Expression right) -> BinaryExpression; // auto createGreaterThan(Expression left, Expression right) -> BinaryExpression; // auto createGreaterThanEquals(Expression left, Expression right) -> BinaryExpression; // auto createLeftShift(Expression left, Expression right) -> BinaryExpression; // auto createRightShift(Expression left, Expression right) -> BinaryExpression; // auto createUnsignedRightShift(Expression left, Expression right) -> BinaryExpression; // auto createAdd(Expression left, Expression right) -> BinaryExpression; // auto createSubtract(Expression left, Expression right) -> BinaryExpression; // auto createMultiply(Expression left, Expression right) -> BinaryExpression; // auto createDivide(Expression left, Expression right) -> BinaryExpression; // auto createModulo(Expression left, Expression right) -> BinaryExpression; // auto createExponent(Expression left, Expression right) -> BinaryExpression; // auto createPrefixPlus(Expression operand) -> PrefixUnaryExpression; // auto createPrefixMinus(Expression operand) -> PrefixUnaryExpression; // auto createPrefixIncrement(Expression operand) -> PrefixUnaryExpression; // auto createPrefixDecrement(Expression operand) -> PrefixUnaryExpression; // auto createBitwiseNot(Expression operand) -> PrefixUnaryExpression; // auto createLogicalNot(Expression operand) -> PrefixUnaryExpression; // auto createPostfixIncrement(Expression operand) -> PostfixUnaryExpression; // auto createPostfixDecrement(Expression operand) -> PostfixUnaryExpression; // // // // Compound Nodes // // // auto createImmediatelyInvokedFunctionExpression(NodeArray<Statement> statements) -> CallExpression; // auto createImmediatelyInvokedFunctionExpression(NodeArray<Statement> statements, ParameterDeclaration param, Expression paramValue) // -> CallExpression; auto createImmediatelyInvokedArrowFunction(NodeArray<Statement> statements) -> CallExpression; auto // createImmediatelyInvokedArrowFunction(NodeArray<Statement> statements, ParameterDeclaration param, Expression paramValue) -> // CallExpression; // auto createVoidZero() -> VoidExpression; // auto createExportDefault(Expression expression) -> ExportAssignment; // auto createExternalModuleExport(Identifier exportName) -> ExportDeclaration; // /* @internal */ auto createTypeCheck(Expression value, string tag) -> Expression; // /* @internal */ auto createMethodCall(Expression object, string methodName, NodeArray<Expression> argumentsList) -> CallExpression; // /* @internal */ auto createMethodCall(Expression object, Identifier methodName, NodeArray<Expression> argumentsList) -> // CallExpression; // /* @internal */ auto createGlobalMethodCall(string globalObjectName, string globalMethodName, NodeArray<Expression> argumentsList) -> // CallExpression; // /* @internal */ auto createFunctionBindCall(Expression target, Expression thisArg, NodeArray<Expression> argumentsList) -> // CallExpression; // /* @internal */ auto createFunctionCallCall(Expression target, Expression thisArg, NodeArray<Expression> argumentsList) -> // CallExpression; // /* @internal */ auto createFunctionApplyCall(Expression target, Expression thisArg, Expression argumentsExpression) -> // CallExpression; // /* @internal */ auto createObjectDefinePropertyCall(Expression target, string propertyName, Expression attributes) -> CallExpression; // /* @internal */ auto createObjectDefinePropertyCall(Expression target, Expression propertyName, Expression attributes) -> // CallExpression; // /* @internal */ auto createPropertyDescriptor(PropertyDescriptorAttributes attributes, boolean singleLine = false) -> // ObjectLiteralExpression; // /* @internal */ auto createArraySliceCall(Expression array, number start) -> CallExpression; // /* @internal */ auto createArraySliceCall(Expression array, Expression start = undefined) -> CallExpression; // /* @internal */ auto createArrayConcatCall(Expression array, NodeArray<Expression> values) -> CallExpression; // /* @internal */ auto createCallBinding(Expression expression, std::function<void(Identifier)> recordTempVariable, ScriptTarget // languageVersion = (ScriptTarget)0, boolean cacheIdentifiers = false) -> CallBinding; // /* @internal */ auto inlineExpressions(NodeArray<Expression> expressions) -> Expression; // /** // * Gets the internal name of a declaration. This is primarily used for declarations that can be // * referred to by name in the body of an ES5 class function body. An internal name will *never* // * be prefixed with an module or namespace export modifier like "exports." when emitted as an // * expression. An internal name will also *never* be renamed due to a collision with a block // * scoped variable. // * // * @param node The declaration. // * @param allowComments A value indicating whether comments may be emitted for the name. // * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. // */ // /* @internal */ auto getInternalName(Declaration node, boolean allowComments = false, boolean allowSourceMaps = false) -> Identifier; // /** // * Gets the local name of a declaration. This is primarily used for declarations that can be // * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A // * local name will *never* be prefixed with an module or namespace export modifier like // * "exports." when emitted as an expression. // * // * @param node The declaration. // * @param allowComments A value indicating whether comments may be emitted for the name. // * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. // */ // /* @internal */ auto getLocalName(Declaration node, boolean allowComments = false, boolean allowSourceMaps = false) -> Identifier; // /** // * Gets the export name of a declaration. This is primarily used for declarations that can be // * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An // * export name will *always* be prefixed with a module or namespace export modifier like // * `"exports."` when emitted as an expression if the name points to an exported symbol. // * // * @param node The declaration. // * @param allowComments A value indicating whether comments may be emitted for the name. // * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. // */ // /* @internal */ auto getExportName(Declaration node, boolean allowComments = false, boolean allowSourceMaps = false) -> Identifier; // /** // * Gets the name of a declaration for use in declarations. // * // * @param node The declaration. // * @param allowComments A value indicating whether comments may be emitted for the name. // * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. // */ // /* @internal */ auto getDeclarationName(Declaration node, boolean allowComments = false, boolean allowSourceMaps = false) -> // Identifier; // /** // * Gets a namespace-qualified name for use in expressions. // * // * @param ns The namespace identifier. // * @param name The name. // * @param allowComments A value indicating whether comments may be emitted for the name. // * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. // */ // /* @internal */ auto getNamespaceMemberName(Identifier ns, Identifier name, boolean allowComments = false, boolean allowSourceMaps = // false) -> PropertyAccessExpression; // /** // * Gets the exported name of a declaration for use in expressions. // * // * An exported name will *always* be prefixed with an module or namespace export modifier like // * "exports." if the name points to an exported symbol. // * // * @param ns The namespace identifier. // * @param node The declaration. // * @param allowComments A value indicating whether comments may be emitted for the name. // * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. // */ // /* @internal */ auto getExternalModuleOrNamespaceExportName(Identifier ns, Declaration node, boolean allowComments = false, boolean // allowSourceMaps = false) -> /*Identifier | PropertyAccessExpression*/Node; // // // // Utilities // // // auto restoreOuterExpressions(Expression outerExpression, Expression innerExpression, OuterExpressionKinds kinds = // OuterExpressionKinds::None) -> Expression; // /* @internal */ auto restoreEnclosingLabel(Statement node, LabeledStatement outermostLabeledStatement, // std::function<void(LabeledStatement)> afterRestoreLabelCallback = nullptr) -> Statement; // /* @internal */ auto createUseStrictPrologue() -> PrologueDirective; // /** // * Copies any necessary standard and custom prologue-directives into target array. // * @param source origin statements array // * @param target result statements array // * @param ensureUseStrict boolean determining whether the function need to add prologue-directives // * @param visitor Optional callback used to visit any custom prologue directives. // */ // /* @internal */ auto copyPrologue(NodeArray<Statement> source, Push<Statement> target, boolean ensureUseStrict = false, // std::function<VisitResult<Node>(Node)> visitor = nullptr) -> number; // /** // * Copies only the standard (string-expression) prologue-directives into the target statement-array. // * @param source origin statements array // * @param target result statements array // * @param ensureUseStrict boolean determining whether the function need to add prologue-directives // */ // /* @internal */ auto copyStandardPrologue(NodeArray<Statement> source, Push<Statement> target, boolean ensureUseStrict = false) -> // number; // /** // * Copies only the custom prologue-directives into target statement-array. // * @param source origin statements array // * @param target result statements array // * @param statementOffset The offset at which to begin the copy. // * @param visitor Optional callback used to visit any custom prologue directives. // */ // /* @internal */ auto copyCustomPrologue(NodeArray<Statement> source, Push<Statement> target, number statementOffset, // std::function<VisitResult<Node>(Node)> visitor = nullptr, std::function<boolean(Node)> filter = nullptr) -> number; // /* @internal */ auto ensureUseStrict(NodeArray<Statement> statements) -> NodeArray<Statement>; // /* @internal */ auto liftToBlock(NodeArray<Node> nodes) -> Statement; // /** // * Merges generated lexical declarations into a new statement list. // */ // /* @internal */ auto mergeLexicalEnvironment(NodeArray<Statement> statements, NodeArray<Statement> declarations) -> // NodeArray<Statement>; // /** // * Creates a shallow, memberwise clone of a node. // * - The result will have its `original` pointer set to `node`. // * - The result will have its `pos` and `end` set to `-1`. // * - *DO NOT USE THIS* if a more appropriate function is available. // */ // /* @internal */ template <typename T/*extends Node*/> auto cloneNode(T node) -> T; // /* @internal */ template <typename T/*extends HasModifiers*/> auto updateModifiers(T node, ModifierFlags modifiers) -> T; // /* @internal */ template <typename T/*extends HasModifiers*/> auto updateModifiers(T node, ModifiersArray modifiers) -> T; }; } // namespace ts #endif // NODEFACTORY_H
68.700454
140
0.74493
[ "object", "shape" ]
4d24743b9d04ddf8c2463b93b9e98be4c6bcfdd1
1,643
h
C
IHakulaShare/IHakulaShare/third/AGCommon.framework/Headers/CMLoadingView.h
wayde191/IHakulaShare
b6c28c7b1106d2c8de8c26f6b81c6ebb0e90d0d3
[ "MIT" ]
1
2019-03-28T15:13:27.000Z
2019-03-28T15:13:27.000Z
SDKs/Share&Login/Core/AGCommon.framework/Headers/CMLoadingView.h
huangxinping/AccessoriesComponents
e3e0ad6a7caf0aee827a7bc3256c5ff891f1f49e
[ "Apache-2.0" ]
2
2016-04-11T03:28:09.000Z
2016-04-11T03:28:18.000Z
SDKs/Share&Login/Core/AGCommon.framework/Headers/CMLoadingView.h
huangxinping/AccessoriesComponents
e3e0ad6a7caf0aee827a7bc3256c5ff891f1f49e
[ "Apache-2.0" ]
1
2020-12-31T08:24:32.000Z
2020-12-31T08:24:32.000Z
///#begin zh-cn // // Created by ShareSDK.cn on 13-1-14. // 官网地址:http://www.ShareSDK.cn // 技术支持邮箱:support@sharesdk.cn // 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复) // 商务QQ:4006852216 // Copyright (c) 2013年 ShareSDK.cn. All rights reserved. // ///#end ///#begin en // // Created by ShareSDK.cn on 13-1-14. // Website:http://www.ShareSDK.cn // Support E-mail:support@sharesdk.cn // WeChat ID:ShareSDK (If publish a new version, we will be push the updates content of version to you. If you have any questions about the ShareSDK, you can get in touch through the WeChat with us, we will respond within 24 hours) // Business QQ:4006852216 // Copyright (c) 2013年 ShareSDK.cn. All rights reserved. // ///#end #import <UIKit/UIKit.h> ///#begin zh-cn /** * @brief 加载视图 */ ///#end ///#begin en /** * @brief Loading View. */ ///#end @interface CMLoadingView : UIView { UIView *_backgroundView; UIActivityIndicatorView *_indicatorView; UILabel *_label; BOOL _needLayout; } ///#begin zh-cn /** * @brief 提示信息 */ ///#end ///#begin en /** * @brief Message content. */ ///#end @property (nonatomic,copy) NSString *text; ///#begin zh-cn /** * @brief 显示 */ ///#end ///#begin en /** * @brief Display. */ ///#end - (void)show; ///#begin zh-cn /** * @brief 显示到指定视图中 * * @param view 视图 */ ///#end ///#begin en /** * @brief Display to the specified view * * @param view View object. */ ///#end - (void)showInView:(UIView *)view; ///#begin zh-cn /** * @brief 隐藏 */ ///#end ///#begin en /** * @brief hide view. */ ///#end - (void)hide; @end
16.938144
234
0.629945
[ "object" ]
4d27af8dea029a4d4f422b4b976071f3cd6b9eca
1,844
h
C
src/Element.h
JoseAntFer/MeshProjector
ad42d9be44fa04663a795e785ff0a22e67182287
[ "MIT" ]
2
2020-02-25T12:22:44.000Z
2021-06-02T13:09:28.000Z
src/Element.h
JoseAntFer/MeshProjector
ad42d9be44fa04663a795e785ff0a22e67182287
[ "MIT" ]
null
null
null
src/Element.h
JoseAntFer/MeshProjector
ad42d9be44fa04663a795e785ff0a22e67182287
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2019 Jose Antonio Fernandez Fernandez 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. */ #pragma once #include <vector> #include <memory> #include "Array.h" #include "Mesh.h" #include "PointIt.h" #include "Matrix.h" #include "Vector.h" template<unsigned int nsd> class Element { public: /* Methods */ Element(); ~Element(); void prepareProjection(Mesh &mesh, unsigned int elem_i); bool projectIfInside(Mesh &in_mesh, unsigned int elem_i, Array<double> &out_mxyz, Array<double> &in_data, Array<double> &out_data, PointIt &node_it); void project(Mesh &in_mesh, unsigned int elem_i, Array<double> &out_mxyz, Array<double> &in_data, Array<double> &out_data, PointIt &node_it); bool hasIndex(unsigned int elem_i); /* Members */ Matrix<nsd> TinvT; PointIt origin_it; unsigned int elem_i = -1; };
35.461538
153
0.759219
[ "mesh", "vector" ]
6459b1f409e61c00b2177af3176800879f8131dc
66,618
c
C
src/resource-manager.c
ymj-uos/tpm2-abrmd
d8e6fda5bfbc820d91c4b63a2a4cc95dc8f04143
[ "BSD-2-Clause" ]
74
2018-01-30T09:07:08.000Z
2022-03-09T10:33:21.000Z
src/resource-manager.c
ymj-uos/tpm2-abrmd
d8e6fda5bfbc820d91c4b63a2a4cc95dc8f04143
[ "BSD-2-Clause" ]
405
2018-01-31T00:37:47.000Z
2022-03-24T16:13:15.000Z
src/resource-manager.c
ymj-uos/tpm2-abrmd
d8e6fda5bfbc820d91c4b63a2a4cc95dc8f04143
[ "BSD-2-Clause" ]
76
2018-02-08T18:17:13.000Z
2022-03-17T19:40:51.000Z
/* SPDX-License-Identifier: BSD-2-Clause */ /* * Copyright (c) 2017, Intel Corporation * All rights reserved. */ #include <errno.h> #include <inttypes.h> #include <string.h> #include <glib.h> #include <tss2/tss2_mu.h> #include "connection.h" #include "connection-manager.h" #include "control-message.h" #include "logging.h" #include "message-queue.h" #include "resource-manager-session.h" #include "resource-manager.h" #include "sink-interface.h" #include "source-interface.h" #include "tabrmd.h" #include "tpm2-header.h" #include "tpm2-command.h" #include "tpm2-response.h" #include "util.h" #define MAX_ABANDONED 4 static void resource_manager_sink_interface_init (gpointer g_iface); static void resource_manager_source_interface_init (gpointer g_iface); G_DEFINE_TYPE_WITH_CODE ( ResourceManager, resource_manager, TYPE_THREAD, G_IMPLEMENT_INTERFACE (TYPE_SINK, resource_manager_sink_interface_init); G_IMPLEMENT_INTERFACE (TYPE_SOURCE, resource_manager_source_interface_init); ); enum { PROP_0, PROP_QUEUE_IN, PROP_SINK, PROP_TPM2, PROP_SESSION_LIST, N_PROPERTIES }; static GParamSpec *obj_properties [N_PROPERTIES] = { NULL, }; /* * This is a helper function that does everything required to convert * a virtual handle to a physical one in a Tpm2Command object. * - load the context from the provided HandleMapEntry * - store the newly assigned TPM handle (physical handle) in the entry * - set this handle in the comamnd at the position indicated by * 'handle_number' (0-based index) */ TSS2_RC resource_manager_virt_to_phys (ResourceManager *resmgr, Tpm2Command *command, HandleMapEntry *entry, guint8 handle_number) { TPM2_HANDLE phandle = 0; TPMS_CONTEXT *context; TSS2_RC rc = TSS2_RC_SUCCESS; context = handle_map_entry_get_context (entry); if (handle_map_entry_get_phandle(entry)) { phandle = handle_map_entry_get_phandle(entry); g_debug ("remembered phandle: 0x%" PRIx32, phandle); tpm2_command_set_handle (command, phandle, handle_number); return TSS2_RC_SUCCESS; } rc = tpm2_context_load (resmgr->tpm2, context, &phandle); g_debug ("loaded phandle: 0x%" PRIx32, phandle); if (rc == TSS2_RC_SUCCESS) { handle_map_entry_set_phandle (entry, phandle); tpm2_command_set_handle (command, phandle, handle_number); } else { g_warning ("Failed to load context: 0x%" PRIx32, rc); } return rc; } TSS2_RC resource_manager_load_transient (ResourceManager *resmgr, Tpm2Command *command, GSList **entry_slist, TPM2_HANDLE handle, guint8 handle_index) { HandleMap *map; HandleMapEntry *entry; Connection *connection; TSS2_RC rc = TSS2_RC_SUCCESS; g_debug ("processing TPM2_HT_TRANSIENT: 0x%" PRIx32, handle); connection = tpm2_command_get_connection (command); map = connection_get_trans_map (connection); g_object_unref (connection); g_debug ("handle 0x%" PRIx32 " is virtual TPM2_HT_TRANSIENT, " "loading", handle); /* we don't unref the entry since we're adding it to the entry_slist below */ entry = handle_map_vlookup (map, handle); if (entry) { g_debug ("mapped virtual handle 0x%" PRIx32 " to entry", handle); } else { g_warning ("No HandleMapEntry for vhandle: 0x%" PRIx32, handle); goto out; } rc = resource_manager_virt_to_phys (resmgr, command, entry, handle_index); if (rc != TSS2_RC_SUCCESS) { goto out; } *entry_slist = g_slist_prepend (*entry_slist, entry); out: g_object_unref (map); return rc; } /* * This structure is used by the regap_session_callback to allow the * response code from the callbacks to be passed to the caller. */ typedef struct { ResourceManager *resmgr; gboolean ret; } regap_session_data_t; /* * This is a version of the 'regap_session' function with the with the * appropriate prototype for use with GList 'foreach' iterator. */ void regap_session_callback (gpointer data_entry, gpointer data_user) { regap_session_data_t *data = (regap_session_data_t*)data_user; SessionEntry *entry = SESSION_ENTRY (data_entry); g_debug ("%s: SessionEntry", __func__); if (data->ret == TRUE) { data->ret = regap_session (data->resmgr, entry); } else { g_critical ("%s: previous attempt to regap failed, skipping" " SessionEntry", __func__); } } /* * This function is a handler for response codes that we may get from the * TPM in response to commands. It may result in addtional commands being * sent to the TPM so use it with caution. */ gboolean handle_rc (ResourceManager *resmgr, TSS2_RC rc) { regap_session_data_t data = { .resmgr = resmgr, .ret = TRUE, }; gboolean ret; g_debug ("%s: handling RC 0x%" PRIx32, __func__, rc); switch (rc) { case TPM2_RC_CONTEXT_GAP: g_debug ("%s: handling TPM2_RC_CONTEXT_GAP", __func__); session_list_foreach (resmgr->session_list, regap_session_callback, &data); ret = data.ret; break; default: g_debug ("%s: Unable to recover gracefully from RC 0x%" PRIx32, __func__, rc); ret = TRUE; break; } return ret; }/* * This is a somewhat generic function used to load session contexts into * the TPM2 device. The ResourceManager uses this function when loading * sessions in the handle or auth area of a command. It will refuse to load * sessions that: * - aren't tracked by the ResourceManager (must have SessionEntry in * SessionList) * - that were last saved by the client instead of the RM * - aren't owned by the Connection object associated with the Tpm2Command */ TSS2_RC resource_manager_load_session_from_handle (ResourceManager *resmgr, Connection *command_conn, TPM2_HANDLE handle, gboolean will_flush) { Connection *entry_conn = NULL; SessionEntry *session_entry = NULL; Tpm2Response *response = NULL; SessionEntryStateEnum session_entry_state; TSS2_RC rc = TSS2_RC_SUCCESS; session_entry = session_list_lookup_handle (resmgr->session_list, handle); if (session_entry == NULL) { g_debug ("no session with handle 0x%08" PRIx32 " known to " "ResourceManager.", handle); goto out; } g_debug ("%s: mapped session handle 0x%08" PRIx32 " to " "SessionEntry", __func__, handle); entry_conn = session_entry_get_connection (session_entry); if (command_conn != entry_conn) { g_warning ("%s: Connection from Tpm2Command and SessionEntry do not " "match. Refusing to load.", __func__); goto out; } session_entry_state = session_entry_get_state (session_entry); if (session_entry_state != SESSION_ENTRY_SAVED_RM) { g_warning ("%s: Handle in handle area references SessionEntry " "for session in state \"%s\". Must be in state: " "SESSION_ENTRY_SAVED_RM for us manage it, ignoring.", __func__, session_entry_state_to_str (session_entry_state)); goto out; } response = load_session (resmgr, session_entry); rc = tpm2_response_get_code (response); if (rc != TSS2_RC_SUCCESS) { if (handle_rc (resmgr, rc) != TRUE) { g_warning ("Failed to load context for session with handle " "0x%08" PRIx32 " RC: 0x%" PRIx32, handle, rc); flush_session (resmgr, session_entry); goto out; } response = load_session (resmgr, session_entry); rc = tpm2_response_get_code (response); if (rc != TSS2_RC_SUCCESS) { flush_session (resmgr, session_entry); goto out; } } if (will_flush) { g_debug ("%s: will_flush: removing SessionEntry from SessionList", __func__); session_list_remove (resmgr->session_list, session_entry); } out: g_clear_object (&entry_conn); g_clear_object (&response); g_clear_object (&session_entry); return rc; } typedef struct { ResourceManager *resmgr; Tpm2Command *command; } auth_callback_data_t; void resource_manager_load_auth_callback (gpointer auth_offset_ptr, gpointer user_data) { Connection *connection = NULL; TPM2_HANDLE handle; auth_callback_data_t *data = (auth_callback_data_t*)user_data; TPMA_SESSION attrs; gboolean will_flush = TRUE; size_t auth_offset = *(size_t*)auth_offset_ptr; handle = tpm2_command_get_auth_handle (data->command, auth_offset); switch (handle >> TPM2_HR_SHIFT) { case TPM2_HT_HMAC_SESSION: case TPM2_HT_POLICY_SESSION: attrs = tpm2_command_get_auth_attrs (data->command, auth_offset); if (attrs & TPMA_SESSION_CONTINUESESSION) { will_flush = FALSE; } connection = tpm2_command_get_connection (data->command); resource_manager_load_session_from_handle (data->resmgr, connection, handle, will_flush); break; default: g_debug ("not loading object with handle: 0x%08" PRIx32 " from " "command auth area: not a session", handle); break; } g_clear_object (&connection); } /* * This function operates on the provided command. It iterates over each * handle in the commands handle area. For each relevant handle it loads * the related context and fixes up the handles in the command. */ TSS2_RC resource_manager_load_handles (ResourceManager *resmgr, Tpm2Command *command, GSList **loaded_transients) { Connection *connection = NULL; TSS2_RC rc = TSS2_RC_SUCCESS; TPM2_HANDLE handles[TPM2_COMMAND_MAX_HANDLES] = { 0, }; size_t i, handle_count = TPM2_COMMAND_MAX_HANDLES; gboolean handle_ret; g_debug ("%s", __func__); if (!resmgr || !command) { g_warning ("%s: received NULL parameter.", __func__); return RM_RC (TSS2_BASE_RC_GENERAL_FAILURE); } handle_ret = tpm2_command_get_handles (command, handles, &handle_count); if (handle_ret == FALSE) { g_error ("Unable to get handles from command"); } g_debug ("%s: for %zu handles in command handle area", __func__, handle_count); for (i = 0; i < handle_count; ++i) { switch (handles [i] >> TPM2_HR_SHIFT) { case TPM2_HT_TRANSIENT: g_debug ("processing TPM2_HT_TRANSIENT: 0x%" PRIx32, handles [i]); rc = resource_manager_load_transient (resmgr, command, loaded_transients, handles [i], i); break; case TPM2_HT_HMAC_SESSION: case TPM2_HT_POLICY_SESSION: g_debug ("processing TPM2_HT_HMAC_SESSION or " "TPM2_HT_POLICY_SESSION: 0x%" PRIx32, handles [i]); connection = tpm2_command_get_connection (command); rc = resource_manager_load_session_from_handle (resmgr, connection, handles [i], FALSE); break; default: break; } } g_debug ("%s: end", __func__); g_clear_object (&connection); return rc; } /* * Remove the context associated with the provided HandleMapEntry * from the TPM. Only handles in the TRANSIENT range will be flushed. * Any entry with a context that's flushed will have the physical handle * to 0. */ void resource_manager_flushsave_context (gpointer data_entry, gpointer data_resmgr) { ResourceManager *resmgr = RESOURCE_MANAGER (data_resmgr); HandleMapEntry *entry = HANDLE_MAP_ENTRY (data_entry); TPMS_CONTEXT *context; TPM2_HANDLE phandle; TSS2_RC rc = TSS2_RC_SUCCESS; g_debug ("%s: for entry", __func__); if (resmgr == NULL || entry == NULL) g_error ("%s: passed NULL parameter", __func__); phandle = handle_map_entry_get_phandle (entry); g_debug ("%s: phandle: 0x%" PRIx32, __func__, phandle); switch (phandle >> TPM2_HR_SHIFT) { case TPM2_HT_TRANSIENT: if (!handle_map_entry_get_phandle (entry)) { g_debug ("phandle for vhandle 0x%" PRIx32 " was already flushed.", handle_map_entry_get_vhandle (entry)); break; } g_debug ("%s: handle is transient, saving context", __func__); context = handle_map_entry_get_context (entry); rc = tpm2_context_saveflush (resmgr->tpm2, phandle, context); if (rc == TSS2_RC_SUCCESS) { handle_map_entry_set_phandle (entry, 0); } else { g_warning ("%s: tpm2_context_saveflush failed for " "handle: 0x%" PRIx32 " rc: 0x%" PRIx32, __func__, phandle, rc); } break; default: break; } } /* * Remove the context associated with the provided SessionEntry from the * TPM. Only session objects should be saved by this function. */ void save_session_callback (gpointer data_entry, gpointer data_resmgr) { ResourceManager *resmgr = RESOURCE_MANAGER (data_resmgr); SessionEntry *entry = SESSION_ENTRY (data_entry); Tpm2Response *resp = NULL; TSS2_RC rc; g_debug ("%s: SessionEntry", __func__); if (session_entry_get_state (entry) != SESSION_ENTRY_LOADED) { g_debug ("%s: cannot save SessionEntry, not loaded", __func__); return; } resp = save_session (resmgr, entry); rc = tpm2_response_get_code (resp); if (rc != TSS2_RC_SUCCESS) { if (handle_rc (resmgr, rc) != TRUE) { g_warning ("%s: Failed to save SessionEntry", __func__); flush_session (resmgr, entry); goto out; } resp = save_session (resmgr, entry); if (tpm2_response_get_code (resp) != TSS2_RC_SUCCESS) { g_critical ("%s: failed to save SessionEntry, flushing", __func__); flush_session (resmgr, entry); } } out: g_clear_object (&resp); return; } static void dump_command (Tpm2Command *command) { g_assert (command != NULL); g_debug ("Tpm2Command"); g_debug_bytes (tpm2_command_get_buffer (command), tpm2_command_get_size (command), 16, 4); g_debug_tpma_cc (tpm2_command_get_attributes (command)); } static void dump_response (Tpm2Response *response) { g_assert (response != NULL); g_debug ("Tpm2Response"); g_debug_bytes (tpm2_response_get_buffer (response), tpm2_response_get_size (response), 16, 4); g_debug_tpma_cc (tpm2_response_get_attributes (response)); } /* * This function performs the special processing required when a client * attempts to save a session context. In short: handling the context gap / * contextCounter roll over is the only reason we have to get involved. To do * this we must be able to load and save every active session from oldest to * newest. This is discussed in detail in section 30.5 from part 1 of the TPM2 * spec. * * The recommended algorithm for doing this is documented in one of the TSS2 specs. */ Tpm2Response* resource_manager_save_context_session (ResourceManager *resmgr, Tpm2Command *command) { Connection *conn_cmd = NULL, *conn_entry = NULL; SessionEntry *entry = NULL; Tpm2Response *response = NULL; TPM2_HANDLE handle = 0; handle = tpm2_command_get_handle (command, 0); g_debug ("save_context for session handle: 0x%" PRIx32, handle); entry = session_list_lookup_handle (resmgr->session_list, handle); if (entry == NULL) { g_warning ("Client attempting to save unknown session."); goto out; } /* the lookup function should check this for us? */ conn_cmd = tpm2_command_get_connection (command); conn_entry = session_entry_get_connection (entry); if (conn_cmd != conn_entry) { g_warning ("%s: session belongs to a different connection", __func__); goto out; } session_entry_set_state (entry, SESSION_ENTRY_SAVED_CLIENT); response = tpm2_response_new_context_save (conn_cmd, entry); g_debug ("%s: Tpm2Response from TPM2_ContextSave", __func__); g_debug_bytes (tpm2_response_get_buffer (response), tpm2_response_get_size (response), 16, 4); out: g_clear_object (&conn_cmd); g_clear_object (&conn_entry); g_clear_object (&entry); return response; } /* * This function performs the special processing associated with the * TPM2_ContextSave command. How much we can "virtualize of this command * depends on the parameters / handle type as well as how much work we * actually *want* to do. * * Transient objects that are tracked by the RM require no special handling. * It's possible that the whole of this command could be virtualized: When a * command is received all transient objects have been saved and flushed. The * saved context held by the RM could very well be returned to the caller * with no interaction with the TPM. This would however require that the RM * marshal the context object into the response buffer. This is less easy * than it should be and so we suffer the inefficiency to keep the RM code * more simple. Simple in this case means no special handling. * * Session objects are handled much in the same way with a specific caveat: * A session can be either loaded or saved. Unlike a transient object saving * it changes its state. And so for the caller to save the context it must * be loaded first. This is exactly what we do for transient objects, but * knowing that the caller wants to save the context we also know that the RM * can't have a saved copy as well. And so we must load the context and * destroy the mapping maintained by the RM. Since this function is called * after the session contexts are loaded we just need to drop the mapping. */ Tpm2Response* resource_manager_save_context (ResourceManager *resmgr, Tpm2Command *command) { TPM2_HANDLE handle = tpm2_command_get_handle (command, 0); g_debug ("%s", __func__); switch (handle >> TPM2_HR_SHIFT) { case TPM2_HT_HMAC_SESSION: case TPM2_HT_POLICY_SESSION: return resource_manager_save_context_session (resmgr, command); default: g_debug ("save_context: not virtualizing TPM2_CC_ContextSave for " "handles: 0x%08" PRIx32, handle); break; } return NULL; } /* * This function performs the special processing required when handling a * TPM2_CC_ContextLoad command: * - First we look at the TPMS_CONTEXT provided in the command body. If we've * never see the context then we do nothing and let the command be processed * in its current form. If the context is valid and the TPM loads it the * ResourceManager will intercept the response and begin tracking the * session. * - Second we check to be sure the session can be loaded by the connection * over which we received the command. This requires that it's either: * - the same connection associated with the SessionEntry * or * - that the SessionEntry has been abandoned * - If the access control check pacsses we return the handle to the caller * in a Tpm2Response that we craft. */ Tpm2Response* resource_manager_load_context_session (ResourceManager *resmgr, Tpm2Command *command) { Connection *conn_cmd = NULL, *conn_entry = NULL; SessionEntry *entry = NULL; Tpm2Response *response = NULL; g_debug ("%s", __func__); entry = session_list_lookup_context_client (resmgr->session_list, &tpm2_command_get_buffer (command) [TPM_HEADER_SIZE], tpm2_command_get_size (command) - TPM_HEADER_SIZE); if (entry == NULL) { g_debug ("%s: Tpm2Command contains unknown TPMS_CONTEXT.", __func__); goto out; } conn_cmd = tpm2_command_get_connection (command); conn_entry = session_entry_get_connection (entry); if (conn_cmd != conn_entry) { if (!session_list_claim (resmgr->session_list, entry, conn_cmd)) { goto out; } } session_entry_set_state (entry, SESSION_ENTRY_SAVED_RM); g_debug ("%s: SessionEntry context savedHandle: 0x%08" PRIx32, __func__, session_entry_get_handle (entry)); response = tpm2_response_new_context_load (conn_cmd, entry); out: g_debug ("%s: returning Tpm2Response", __func__); g_clear_object (&conn_cmd); g_clear_object (&conn_entry); g_clear_object (&entry); return response; } /* * This function performs the special processing associated with the * TPM2_ContextLoad command. */ Tpm2Response* resource_manager_load_context (ResourceManager *resmgr, Tpm2Command *command) { /* why all the marshalling */ uint8_t *buf = tpm2_command_get_buffer (command); TPMS_CONTEXT tpms_context; TSS2_RC rc; size_t offset = TPM_HEADER_SIZE; /* Need to be able to get handle from Tpm2Command */ rc = Tss2_MU_TPMS_CONTEXT_Unmarshal (buf, tpm2_command_get_size (command), &offset, &tpms_context); if (rc != TSS2_RC_SUCCESS) { g_warning ("%s: Failed to unmarshal TPMS_CONTEXT from Tpm2Command, " "rc: 0x%" PRIx32, __func__, rc); /* Generate Tpm2Response with "appropriate" RC */ } switch (tpms_context.savedHandle >> TPM2_HR_SHIFT) { case TPM2_HT_HMAC_SESSION: case TPM2_HT_POLICY_SESSION: return resource_manager_load_context_session (resmgr, command); default: g_debug ("%s: not virtualizing TPM2_ContextLoad for " "handles: 0x%08" PRIx32, __func__, tpms_context.savedHandle); break; } return NULL; } /* * This function performs the special processing associated with the * TPM2_FlushContext command. How much we can "virtualize" of this command * depends on the parameters / handle type. * * Transient objects that are tracked by the RM (stored in the transient * HandleMap in the Connection object) then we can simply delete the mapping * since transient objects are always saved / flushed after each command is * processed. So for this handle type we just delete the mapping, create a * Tpm2Response object and return it to the caller. * * Session objects are not so simple. Sessions cannot be flushed after each * use. The TPM will only allow us to save the context as it must maintain * some internal tracking information. So when the caller wishes to flush a * session context we must remove the entry tracking the mapping between * session and connection from the session_slist (if any exists). The comman * must then be passed to the TPM as well. We return NULL here to let the * caller know. */ Tpm2Response* resource_manager_flush_context (ResourceManager *resmgr, Tpm2Command *command) { Connection *connection; HandleMap *map; HandleMapEntry *entry; Tpm2Response *response = NULL; TPM2_HANDLE handle; TPM2_HT handle_type; TSS2_RC rc; if (tpm2_command_get_code (command) != TPM2_CC_FlushContext) { g_warning ("resource_manager_flush_context with wrong command"); return NULL; } rc = tpm2_command_get_flush_handle (command, &handle); if (rc != TSS2_RC_SUCCESS) { connection = tpm2_command_get_connection (command); response = tpm2_response_new_rc (connection, rc); g_object_unref (connection); goto out; } g_debug ("resource_manager_flush_context handle: 0x%" PRIx32, handle); handle_type = handle >> TPM2_HR_SHIFT; switch (handle_type) { case TPM2_HT_TRANSIENT: g_debug ("handle is TPM2_HT_TRANSIENT, virtualizing"); connection = tpm2_command_get_connection (command); map = connection_get_trans_map (connection); entry = handle_map_vlookup (map, handle); if (entry != NULL) { handle_map_remove (map, handle); g_object_unref (entry); rc = TSS2_RC_SUCCESS; } else { /* * If the handle doesn't map to a HandleMapEntry then it's not one * that we're managing and so we can't flush it. Return an error * indicating that error is related to a handle, that it's a parameter * and that it's the first parameter. */ rc = RM_RC (TPM2_RC_HANDLE + TPM2_RC_P + TPM2_RC_1); } g_object_unref (map); response = tpm2_response_new_rc (connection, rc); g_object_unref (connection); break; case TPM2_HT_HMAC_SESSION: case TPM2_HT_POLICY_SESSION: g_debug ("%s: handle 0x%08" PRIx32 "is a session, removing from " "SessionList", __func__, handle); session_list_remove_handle (resmgr->session_list, handle); break; } out: return response; } /* * Ensure that executing the provided command will not exceed any of the * per-connection quotas enforced by the RM. This is currently limited to * transient objects and sessions. */ TSS2_RC resource_manager_quota_check (ResourceManager *resmgr, Tpm2Command *command) { HandleMap *handle_map = NULL; Connection *connection = NULL; TSS2_RC rc = TSS2_RC_SUCCESS; switch (tpm2_command_get_code (command)) { /* These commands load transient objects. */ case TPM2_CC_CreatePrimary: case TPM2_CC_Load: case TPM2_CC_LoadExternal: connection = tpm2_command_get_connection (command); handle_map = connection_get_trans_map (connection); if (handle_map_is_full (handle_map)) { g_info ("%s: Connection has exceeded transient object limit", __func__); rc = TSS2_RESMGR_RC_OBJECT_MEMORY; } break; /* These commands create sessions. */ case TPM2_CC_StartAuthSession: connection = tpm2_command_get_connection (command); if (session_list_is_full (resmgr->session_list, connection)) { g_info ("%s: Connectionhas exceeded session limit", __func__); rc = TSS2_RESMGR_RC_SESSION_MEMORY; } break; } g_clear_object (&connection); g_clear_object (&handle_map); return rc; } /* * This is a callback function invoked by the GSList foreach function. It is * called when the object associated with a HandleMapEntry is no longer valid * (usually when it is flushed) and the HandleMap shouldn't be tracking it. */ void remove_entry_from_handle_map (gpointer data_entry, gpointer data_connection) { HandleMapEntry *entry = HANDLE_MAP_ENTRY (data_entry); Connection *connection = CONNECTION (data_connection); HandleMap *map = connection_get_trans_map (connection); TPM2_HANDLE handle = handle_map_entry_get_vhandle (entry); TPM2_HT handle_type = 0; handle_type = handle >> TPM2_HR_SHIFT; g_debug ("remove_entry_from_handle_map"); switch (handle_type) { case TPM2_HT_TRANSIENT: g_debug ("%s: entry is transient, removing from map", __func__); handle_map_remove (map, handle); break; default: g_debug ("%s: entry not transient, leaving entry alone", __func__); break; } } /* * This function handles the required post-processing on the HandleMapEntry * objects in the GSList that represent objects loaded into the TPM as part of * executing a command. */ void post_process_loaded_transients (ResourceManager *resmgr, GSList **transient_slist, Connection *connection, TPMA_CC command_attrs) { /* if flushed bit is clear we need to flush & save contexts */ if (!(command_attrs & TPMA_CC_FLUSHED)) { g_debug ("flushsave_context for %" PRIu32 " entries", g_slist_length (*transient_slist)); g_slist_foreach (*transient_slist, resource_manager_flushsave_context, resmgr); } else { /* * if flushed bit is set the transient object entry has been flushed * and so we just remove it */ g_debug ("TPMA_CC flushed bit set"); g_slist_foreach (*transient_slist, remove_entry_from_handle_map, connection); } g_slist_free_full (*transient_slist, g_object_unref); } /* * This structure is used to keep state while iterating over a list of * TPM2_HANDLES. * 'cap_data' : this parameter is used to collect the list of handles that * we want as well as the number of handles in the structure * 'max_count' : is the maximum number of handles to return * 'more_data' : once max_count handles have been collected this variable * tells the caller whether additional handles would have been returned had * max_count been larger * 'start_handle': is the numerically smallest handle that should be collected * into cap_data. */ typedef struct { TPMS_CAPABILITY_DATA *cap_data; size_t max_count; gboolean more_data; TPM2_HANDLE start_handle; } vhandle_iterator_state_t; /* * This callback function is invoked as part of iterating over a list of * handles. The first parameter is an entry from the collection being * traversed. The second is a reference to a vhandle_iterator_state_t * structure. * This structure is used to maintain state while iterating over the * collection. */ void vhandle_iterator_callback (gpointer entry, gpointer data) { TPM2_HANDLE vhandle = (uintptr_t)entry; vhandle_iterator_state_t *state = (vhandle_iterator_state_t*)data; TPMS_CAPABILITY_DATA *cap_data = state->cap_data; /* if vhandle is numerically smaller than the start value just return */ if (vhandle < state->start_handle) { return; } g_debug ("vhandle_iterator_callback with max_count: %zu and count: %" PRIu32, state->max_count, cap_data->data.handles.count); /* if we've collected max_count handles set 'more_data' and return */ if (!(cap_data->data.handles.count < state->max_count)) { state->more_data = TRUE; return; } cap_data->data.handles.handle [cap_data->data.handles.count] = vhandle; ++cap_data->data.handles.count; } /* * This is a GCompareFunc used to sort a list of TPM2_HANDLES. */ int handle_compare (gconstpointer a, gconstpointer b) { TPM2_HANDLE handle_a = (uintptr_t)a; TPM2_HANDLE handle_b = (uintptr_t)b; if (handle_a < handle_b) { return -1; } else if (handle_a > handle_b) { return 1; } else { return 0; } } /* * The get_cap_transient function populates a TPMS_CAPABILITY_DATA structure * with the handles in the provided HandleMap 'map'. The 'prop' parameter * is the lowest numerical handle to return. The 'count' parameter is the * maximum number of handles to return in the capability data structure. * Returns: * TRUE when more handles are present * FALSE when there are no more handles */ gboolean get_cap_handles (HandleMap *map, TPM2_HANDLE prop, UINT32 count, TPMS_CAPABILITY_DATA *cap_data) { GList *vhandle_list; vhandle_iterator_state_t state = { .cap_data = cap_data, .max_count = count, .more_data = FALSE, .start_handle = prop, }; cap_data->capability = TPM2_CAP_HANDLES; cap_data->data.handles.count = 0; vhandle_list = handle_map_get_keys (map); vhandle_list = g_list_sort (vhandle_list, handle_compare); g_list_foreach (vhandle_list, vhandle_iterator_callback, &state); g_debug ("iterating over %" PRIu32 " vhandles from g_list_foreach", cap_data->data.handles.count); size_t i; for (i = 0; i < cap_data->data.handles.count; ++i) { g_debug (" vhandle: 0x%" PRIx32, cap_data->data.handles.handle [i]); } return state.more_data; } /* * These macros are used to set fields in a Tpm2Response buffer that we * create in response to the TPM2 GetCapability command. They are very * specifically tailored and should not be used elsewhere. */ #define YES_NO_OFFSET TPM_HEADER_SIZE #define YES_NO_SET(buffer, value) \ (*(TPMI_YES_NO*)(buffer + YES_NO_OFFSET) = value) #define CAP_OFFSET (TPM_HEADER_SIZE + sizeof (TPMI_YES_NO)) #define CAP_SET(buffer, value) \ (*(TPM2_CAP*)(buffer + CAP_OFFSET) = htobe32 (value)) #define HANDLE_COUNT_OFFSET (CAP_OFFSET + sizeof (TPM2_CAP)) #define HANDLE_COUNT_SET(buffer, value) \ (*(UINT32*)(buffer + HANDLE_COUNT_OFFSET) = htobe32 (value)) #define HANDLE_OFFSET (HANDLE_COUNT_OFFSET + sizeof (UINT32)) #define HANDLE_INDEX(i) (sizeof (TPM2_HANDLE) * i) #define HANDLE_SET(buffer, i, value) \ (*(TPM2_HANDLE*)(buffer + HANDLE_OFFSET + HANDLE_INDEX (i)) = \ htobe32 (value)) #define CAP_RESP_SIZE(value) \ (TPM_HEADER_SIZE + \ sizeof (TPMI_YES_NO) + \ sizeof ((value)->capability) + \ sizeof ((value)->data.handles.count) + \ ((value)->data.handles.count * \ sizeof ((value)->data.handles.handle [0]))) /* * This function is used to build a response buffer that contains the provided * TPMS_CAPABILITY_DATA and TPMI_YES_NO. These are the two response parameters * to the TPM2_GetCapability function. * The 'cap_data' parameter *must* have the TPMU_CAPABILITY union populated * with the TPM2_CAP_HANDLES selector. */ uint8_t* build_cap_handles_response (TPMS_CAPABILITY_DATA *cap_data, TPMI_YES_NO more_data) { size_t i; uint8_t *buf; buf = calloc (1, CAP_RESP_SIZE (cap_data)); if (buf == NULL) { tabrmd_critical ("failed to allocate buffer for handle capability " "response"); } set_response_tag (buf, TPM2_ST_NO_SESSIONS); set_response_size (buf, CAP_RESP_SIZE (cap_data)); set_response_code (buf, TSS2_RC_SUCCESS); YES_NO_SET (buf, more_data); CAP_SET (buf, cap_data->capability); HANDLE_COUNT_SET (buf, cap_data->data.handles.count); for (i = 0; i < cap_data->data.handles.count; ++i) { HANDLE_SET (buf, i, cap_data->data.handles.handle [i]); } return buf; } /* * In cases where the GetCapability command isn't fully virtualized we may * need to perform some 'post processing' of the results returned from the * TPM2 device. Specifically, in the case of the TPM2_PT_CONTEXT_GAP_MAX * property, we overrite the value in the response body. This function * manually unmarshals the response, iterates over the values modifying * them if necessary and then marshals them back into the Tpm2Response. */ TSS2_RC get_cap_post_process (Tpm2Response *resp) { g_assert (resp != NULL); g_assert (tpm2_response_get_code (resp) == TSS2_RC_SUCCESS); TPMS_CAPABILITY_DATA cap_data = { .capability = 0 }; TSS2_RC rc; uint8_t *buf = tpm2_response_get_buffer (resp); size_t buf_size = tpm2_response_get_size (resp); size_t offset = TPM_HEADER_SIZE + sizeof (TPMI_YES_NO); size_t i; rc = Tss2_MU_TPMS_CAPABILITY_DATA_Unmarshal (buf, buf_size, &offset, &cap_data); if (rc != TSS2_RC_SUCCESS) { g_warning ("%s: Failed to unmarshal TPMS_CAPABILITY_DATA", __func__); return rc; } g_debug ("%s: capability 0x%" PRIx32, __func__, cap_data.capability); switch (cap_data.capability) { case TPM2_CAP_TPM_PROPERTIES: for (i = 0; i < cap_data.data.tpmProperties.count; ++i) { g_debug ("%s: property 0x%" PRIx32 ", value 0x%" PRIx32, __func__, cap_data.data.tpmProperties.tpmProperty [i].property, cap_data.data.tpmProperties.tpmProperty [i].value); switch (cap_data.data.tpmProperties.tpmProperty [i].property) { case TPM2_PT_CONTEXT_GAP_MAX: g_debug ("%s: changing TPM2_PT_CONTEXT_GAP_MAX, from 0x%" PRIx32 " to UINT32_MAX: 0x%" PRIx32, __func__, cap_data.data.tpmProperties.tpmProperty [i].value, UINT32_MAX); cap_data.data.tpmProperties.tpmProperty [i].value = UINT32_MAX; break; default: break; } } break; default: break; } offset = TPM_HEADER_SIZE + sizeof (TPMI_YES_NO); rc = Tss2_MU_TPMS_CAPABILITY_DATA_Marshal (&cap_data, buf, buf_size, &offset); if (rc != TSS2_RC_SUCCESS) { g_warning ("%s: Failed to unmarshal TPMS_CAPABILITY_DATA", __func__); return rc; } return rc; } /* * This function takes a Tpm2Command and the associated connection object * as parameters. The Tpm2Command *must* have the 'code' attribute set to * TPM2_CC_GetCapability. If it's a GetCapability command that we * "virtualize" then we'll build a Tpm2Response object and return it. If * not, then we send the command to the TPM2 device and perform whatever * post-processing is necessary. */ Tpm2Response* get_cap_gen_response (ResourceManager *resmgr, Tpm2Command *command) { TPM2_CAP cap = tpm2_command_get_cap (command); UINT32 prop = tpm2_command_get_prop (command); UINT32 prop_count = tpm2_command_get_prop_count (command); TPM2_HT handle_type; TSS2_RC rc = TSS2_RC_SUCCESS; Connection *connection = NULL; HandleMap *map; TPMS_CAPABILITY_DATA cap_data = { .capability = cap }; gboolean more_data = FALSE; uint8_t *resp_buf; Tpm2Response *response = NULL; g_debug ("processing TPM2_CC_GetCapability with cap: 0x%" PRIx32 " prop: 0x%" PRIx32 " prop_count: 0x%" PRIx32, cap, prop, prop_count); switch (cap) { case TPM2_CAP_HANDLES: handle_type = prop >> TPM2_HR_SHIFT; switch (handle_type) { case TPM2_HT_TRANSIENT: g_debug ("%s: TPM2_CAP_HANDLES && TPM2_HT_TRANSIENT", __func__); connection = tpm2_command_get_connection (command); map = connection_get_trans_map (connection); more_data = get_cap_handles (map, prop, prop_count, &cap_data); g_object_unref (map); resp_buf = build_cap_handles_response (&cap_data, more_data); response = tpm2_response_new (connection, resp_buf, CAP_RESP_SIZE (&cap_data), tpm2_command_get_attributes (command)); break; default: g_debug ("%s: TPM2_CAP_HANDLES not virtualized for handle type: " "0x%" PRIx32, __func__, handle_type); break; } break; default: g_debug ("%s: cap 0x%" PRIx32 " not handled", __func__, cap); break; } if (response == NULL) { response = tpm2_send_command (resmgr->tpm2, command, &rc); if (response != NULL && rc == TSS2_RC_SUCCESS) { get_cap_post_process (response); } } g_clear_object (&connection); return response; } /* * If the provided command is something that the ResourceManager "virtualizes" * then this function will do so and return a Tpm2Response object that will be * returned to the same connection. If the command isn't something that we * virtualize then we just return NULL. * * NOTE: Both the ContextSave and ContextLoad commands, when sent by clients, * do not result in the command being executed by the TPM. This makes * handling the context gap unnecessary for these commands. */ Tpm2Response* command_special_processing (ResourceManager *resmgr, Tpm2Command *command) { Tpm2Response *response = NULL; switch (tpm2_command_get_code (command)) { case TPM2_CC_FlushContext: g_debug ("processing TPM2_CC_FlushContext"); response = resource_manager_flush_context (resmgr, command); break; case TPM2_CC_ContextSave: g_debug ("processing TPM2_CC_ContextSave"); response = resource_manager_save_context (resmgr, command); break; case TPM2_CC_ContextLoad: g_debug ("%s: processing TPM2_CC_ContextLoad", __func__); response = resource_manager_load_context (resmgr, command); break; case TPM2_CC_GetCapability: g_debug ("processing TPM2_CC_GetCapability"); response = get_cap_gen_response (resmgr, command); break; default: break; } return response; } /* * This function creates a mapping from the transient physical to a virtual * handle in the provided response object. This mapping is then added to * the transient HandleMap for the associated connection, as well as the * list of currently loaded transient objects. */ void create_context_mapping_transient (ResourceManager *resmgr, Tpm2Response *response, GSList **loaded_transient_slist) { HandleMap *handle_map; HandleMapEntry *handle_entry; TPM2_HANDLE phandle, vhandle; Connection *connection; UNUSED_PARAM(resmgr); g_debug ("create_context_mapping_transient"); phandle = tpm2_response_get_handle (response); g_debug (" physical handle: 0x%08" PRIx32, phandle); connection = tpm2_response_get_connection (response); handle_map = connection_get_trans_map (connection); g_object_unref (connection); vhandle = handle_map_next_vhandle (handle_map); if (vhandle == 0) { g_error ("vhandle rolled over!"); } g_debug (" vhandle:0x%08" PRIx32, vhandle); handle_entry = handle_map_entry_new (phandle, vhandle); if (handle_entry == NULL) { g_warning ("failed to create new HandleMapEntry for handle 0x%" PRIx32, phandle); } *loaded_transient_slist = g_slist_prepend (*loaded_transient_slist, handle_entry); handle_map_insert (handle_map, vhandle, handle_entry); g_object_unref (handle_map); tpm2_response_set_handle (response, vhandle); } /* * This function after a Tpm2Command is sent to the TPM and: * - we receive a Tpm2Response object with a handle in the response buffers * handle area * - the handle is a session handle * Since there's a handle in the response handle area the caller is being * returned a new handle after a context was successfully created or loaded. * So we know that the response is to one of two possible commands: * - a session being loaded by a call to LoadContext * - a session was newly created by a call to StartAuthSession * We differentiate between these two situations as follows: * - A call to 'LoadContext' implies that the session already exists and so * it must already be in the session_list. * - If it's in the session_list *AND NOT* in the abandoned_session_queue * then the caller is just loading a context they already own and so we * set the session state to SAVED_RM and add the session to the list of * loaded sessions. * - If it's *NOT* in the session_list *AND* in the abandoned_session_queue * then the caller is loading a context saved by a different connection * and so we make the current connection the owner of the session, set * the session state to SAVED_RM and add the session to the list of loaded * sessions. * - A call to 'StartAuthSession' will return a handle for a session object * that is not in either the session_list or the abandoned_session_queue. * In this case we just create a new SessionEntry and add it to the * session_list and the list of loaded sessions. * NOTE: If the response doesn't indicate 'success' then we just ignore it * since there's nothing useful that we can do. */ void create_context_mapping_session (ResourceManager *resmgr, Tpm2Response *response, TPM2_HANDLE handle) { SessionEntry *entry = NULL; Connection *conn_resp = NULL, *conn_entry = NULL; entry = session_list_lookup_handle (resmgr->session_list, handle); conn_resp = tpm2_response_get_connection (response); if (entry != NULL) { g_debug ("%s: got SessionEntry that's in the SessionList", __func__); conn_entry = session_entry_get_connection (entry); if (conn_resp != conn_entry) { g_warning ("%s: connections do not match!", __func__); } } else { g_debug ("%s: handle is a session, creating entry for SessionList " "and SessionList", __func__); entry = session_entry_new (conn_resp, handle); session_entry_set_state (entry, SESSION_ENTRY_LOADED); session_list_insert (resmgr->session_list, entry); } g_clear_object (&conn_resp); g_clear_object (&conn_entry); g_clear_object (&entry); } /* * Each Tpm2Response object can have at most one handle in it. * This function assumes that the handle in the parameter Tpm2Response * object is the handle assigned by the TPM. Depending on the type of the * handle we do to possible things: * For TPM2_HT_TRANSIENT handles we create a new virtual handle and * allocates a new HandleMapEntry to map the virtual handle to a * TPMS_CONTEXT structure when processing future commands associated * with the same connection. This HandleMapEntry is inserted into the * handle map for the connection. It is also added to the list of loaded * transient objects so that it can be saved / flushed by the typical code * path. * For TPM2_HT_HMAC_SESSION or TPM2_HT_POLICY_SESSION handles we create a * new session_entry_t object, populate the connection field with the * connection associated with the response object, and set the savedHandle * field. We then add this entry to the list of sessions we're tracking * (session_slist) and the list of loaded sessions (loaded_session_slist). */ void resource_manager_create_context_mapping (ResourceManager *resmgr, Tpm2Response *response, GSList **loaded_transient_slist) { TPM2_HANDLE handle; g_debug ("%s", __func__); if (!tpm2_response_has_handle (response)) { g_debug ("response has no handles"); return; } handle = tpm2_response_get_handle (response); switch (handle >> TPM2_HR_SHIFT) { case TPM2_HT_TRANSIENT: create_context_mapping_transient (resmgr, response, loaded_transient_slist); break; case TPM2_HT_HMAC_SESSION: case TPM2_HT_POLICY_SESSION: create_context_mapping_session (resmgr, response, handle); break; default: g_debug (" not creating context for handle: 0x%08" PRIx32, handle); break; } } Tpm2Response* send_command_handle_rc (ResourceManager *resmgr, Tpm2Command *cmd) { regap_session_data_t data = { .resmgr = resmgr, .ret = TRUE, }; Tpm2Response *resp = NULL; TSS2_RC rc; /* Send command and create response object. */ resp = tpm2_send_command (resmgr->tpm2, cmd, &rc); rc = tpm2_response_get_code (resp); if (rc == TPM2_RC_CONTEXT_GAP) { g_debug ("%s: handling TPM2_RC_CONTEXT_GAP", __func__); session_list_foreach (resmgr->session_list, regap_session_callback, &data); g_clear_object (&resp); resp = tpm2_send_command (resmgr->tpm2, cmd, &rc); } return resp; } /** * This function is invoked in response to the receipt of a Tpm2Command. * This is the place where we send the command buffer out to the TPM * through the Tpm2 which will eventually get it to the TPM for us. * The Tpm2 will send us back a Tpm2Response that we send back to * the client by way of our Sink object. The flow is roughly: * - Receive the Tpm2Command as a parameter * - Load all virtualized objects required by the command. * - Send the Tpm2Command out through the Tpm2. * - Receive the response from the Tpm2. * - Virtualize the new objects created by the command & referenced in the * response. * - Enqueue the response back out to the processing pipeline through the * Sink object. * - Flush all objects loaded for the command or as part of executing the * command.. */ void resource_manager_process_tpm2_command (ResourceManager *resmgr, Tpm2Command *command) { Connection *connection; Tpm2Response *response; TSS2_RC rc = TSS2_RC_SUCCESS; GSList *transient_slist = NULL; TPMA_CC command_attrs; command_attrs = tpm2_command_get_attributes (command); g_debug ("%s", __func__); dump_command (command); connection = tpm2_command_get_connection (command); /* If executing the command would exceed a per connection quota */ rc = resource_manager_quota_check (resmgr, command); if (rc != TSS2_RC_SUCCESS) { response = tpm2_response_new_rc (connection, rc); goto send_response; } /* Do command-specific processing. */ response = command_special_processing (resmgr, command); if (response != NULL) { goto send_response; } /* Load objects associated with the handles in the command handle area. */ if (tpm2_command_get_handle_count (command) > 0) { resource_manager_load_handles (resmgr, command, &transient_slist); } /* Load objets associated with the authorizations in the command. */ if (tpm2_command_has_auths (command)) { g_info ("%s, Processing auths for command", __func__); auth_callback_data_t auth_callback_data = { .resmgr = resmgr, .command = command, }; tpm2_command_foreach_auth (command, resource_manager_load_auth_callback, &auth_callback_data); } /* Send command and create response object. */ response = send_command_handle_rc (resmgr, command); dump_response (response); /* transform virtualized handles in Tpm2Response if necessary */ resource_manager_create_context_mapping (resmgr, response, &transient_slist); send_response: sink_enqueue (resmgr->sink, G_OBJECT (response)); g_object_unref (response); /* save contexts that were previously loaded */ session_list_foreach (resmgr->session_list, save_session_callback, resmgr); post_process_loaded_transients (resmgr, &transient_slist, connection, command_attrs); g_object_unref (connection); return; } /* * Return FALSE to terminate main thread. */ gboolean resource_manager_process_control (ResourceManager *resmgr, ControlMessage *msg) { ControlCode code = control_message_get_code (msg); Connection *conn; g_debug ("%s", __func__); switch (code) { case CHECK_CANCEL: sink_enqueue (resmgr->sink, G_OBJECT (msg)); return FALSE; case CONNECTION_REMOVED: conn = CONNECTION (control_message_get_object (msg)); g_debug ("%s: received CONNECTION_REMOVED message for connection", __func__); resource_manager_remove_connection (resmgr, conn); sink_enqueue (resmgr->sink, G_OBJECT (msg)); return TRUE; default: g_warning ("%s: Unknown control code: %d ... ignoring", __func__, code); return TRUE; } } /** * This function acts as a thread. It simply: * - Blocks on the in_queue. Then wakes up and * - Dequeues a message from the in_queue. * - Processes the message (depending on TYPE) * - Does it all over again. */ gpointer resource_manager_thread (gpointer data) { ResourceManager *resmgr = RESOURCE_MANAGER (data); GObject *obj = NULL; gboolean done = FALSE; g_debug ("resource_manager_thread start"); while (!done) { obj = message_queue_dequeue (resmgr->in_queue); g_debug ("%s: message_queue_dequeue got obj", __func__); if (obj == NULL) { g_debug ("%s: dequeued a null object", __func__); break; } if (IS_TPM2_COMMAND (obj)) { resource_manager_process_tpm2_command (resmgr, TPM2_COMMAND (obj)); } else if (IS_CONTROL_MESSAGE (obj)) { gboolean ret = resource_manager_process_control (resmgr, CONTROL_MESSAGE (obj)); if (ret == FALSE) { done = TRUE; } } g_object_unref (obj); } return NULL; } static void resource_manager_unblock (Thread *self) { ControlMessage *msg; ResourceManager *resmgr = RESOURCE_MANAGER (self); if (resmgr == NULL) g_error ("resource_manager_cancel passed NULL ResourceManager"); msg = control_message_new (CHECK_CANCEL); g_debug ("%s: enqueuing ControlMessage", __func__); message_queue_enqueue (resmgr->in_queue, G_OBJECT (msg)); g_object_unref (msg); } /** * Implement the 'enqueue' function from the Sink interface. This is how * new messages / commands get into the Tpm2. */ void resource_manager_enqueue (Sink *sink, GObject *obj) { ResourceManager *resmgr = RESOURCE_MANAGER (sink); g_debug ("%s", __func__); message_queue_enqueue (resmgr->in_queue, obj); } /** * Implement the 'add_sink' function from the SourceInterface. This adds a * reference to an object that implements the SinkInterface to this objects * internal structure. We pass it data. */ void resource_manager_add_sink (Source *self, Sink *sink) { ResourceManager *resmgr = RESOURCE_MANAGER (self); GValue value = G_VALUE_INIT; g_debug ("%s", __func__); g_value_init (&value, G_TYPE_OBJECT); g_value_set_object (&value, sink); g_object_set_property (G_OBJECT (resmgr), "sink", &value); g_value_unset (&value); } /** * GObject property setter. */ static void resource_manager_set_property (GObject *object, guint property_id, GValue const *value, GParamSpec *pspec) { ResourceManager *resmgr = RESOURCE_MANAGER (object); g_debug ("%s", __func__); switch (property_id) { case PROP_QUEUE_IN: resmgr->in_queue = g_value_get_object (value); break; case PROP_SINK: if (resmgr->sink != NULL) { g_warning (" sink already set"); break; } resmgr->sink = SINK (g_value_get_object (value)); g_object_ref (resmgr->sink); break; case PROP_TPM2: if (resmgr->tpm2 != NULL) { g_warning (" tpm2 already set"); break; } resmgr->tpm2 = g_value_get_object (value); g_object_ref (resmgr->tpm2); break; case PROP_SESSION_LIST: resmgr->session_list = SESSION_LIST (g_value_dup_object (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } /** * GObject property getter. */ static void resource_manager_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { ResourceManager *resmgr = RESOURCE_MANAGER (object); g_debug ("%s", __func__); switch (property_id) { case PROP_QUEUE_IN: g_value_set_object (value, resmgr->in_queue); break; case PROP_SINK: g_value_set_object (value, resmgr->sink); break; case PROP_TPM2: g_value_set_object (value, resmgr->tpm2); break; case PROP_SESSION_LIST: g_value_set_object (value, resmgr->session_list); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } /** * Bring down the ResourceManager as gracefully as we can. */ static void resource_manager_dispose (GObject *obj) { ResourceManager *resmgr = RESOURCE_MANAGER (obj); Thread *thread = THREAD (obj); g_debug ("%s", __func__); if (resmgr == NULL) g_error ("%s: passed NULL parameter", __func__); if (thread->thread_id != 0) g_error ("%s: thread running, cancel thread first", __func__); g_clear_object (&resmgr->in_queue); g_clear_object (&resmgr->sink); g_clear_object (&resmgr->tpm2); g_clear_object (&resmgr->session_list); G_OBJECT_CLASS (resource_manager_parent_class)->dispose (obj); } static void resource_manager_init (ResourceManager *manager) { UNUSED_PARAM (manager); } /** * GObject class initialization function. This function boils down to: * - Setting up the parent class. * - Set dispose, property get/set. * - Install properties. */ static void resource_manager_class_init (ResourceManagerClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); ThreadClass *thread_class = THREAD_CLASS (klass); if (resource_manager_parent_class == NULL) resource_manager_parent_class = g_type_class_peek_parent (klass); object_class->dispose = resource_manager_dispose; object_class->get_property = resource_manager_get_property; object_class->set_property = resource_manager_set_property; thread_class->thread_run = resource_manager_thread; thread_class->thread_unblock = resource_manager_unblock; obj_properties [PROP_QUEUE_IN] = g_param_spec_object ("queue-in", "input queue", "Input queue for messages.", G_TYPE_OBJECT, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY); obj_properties [PROP_SINK] = g_param_spec_object ("sink", "Sink", "Reference to a Sink object that we pass messages to.", G_TYPE_OBJECT, G_PARAM_READWRITE); obj_properties [PROP_TPM2] = g_param_spec_object ("tpm2", "Tpm2 object", "Object used to communicate with TPM2", TYPE_TPM2, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY); obj_properties [PROP_SESSION_LIST] = g_param_spec_object ("session-list", "SessionList object", "Data structure to hold session tracking data", TYPE_SESSION_LIST, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY); g_object_class_install_properties (object_class, N_PROPERTIES, obj_properties); } /** * Boilerplate code to register functions with the SourceInterface. */ static void resource_manager_source_interface_init (gpointer g_iface) { SourceInterface *source = (SourceInterface*)g_iface; source->add_sink = resource_manager_add_sink; } /** * Boilerplate code to register function with the SinkInterface. */ static void resource_manager_sink_interface_init (gpointer g_iface) { SinkInterface *sink = (SinkInterface*)g_iface; sink->enqueue = resource_manager_enqueue; } /* * A callback function implementing the PruneFunc type for use with the * session_list_prune_abaonded function. */ gboolean flush_session_callback (SessionEntry *entry, gpointer data) { return flush_session (RESOURCE_MANAGER (data), entry); } /* * This structure is used to pass required data into the * connection_close_session_callback function. */ typedef struct { Connection *connection; ResourceManager *resource_manager; } connection_close_data_t; /* * This is a callback function invoked foreach SessionEntry in the SessionList * when a client Connection is closed. As it iterates over each SessionEntry, * it identifies sessions associated with the connection being closed and, * performs some task depending on its state. * * If session is in state SESSION_ENTRY_SAVED_CLIENT: * - take a reference to the SessionEntry * - remove SessionEntry from session list * - change state to SESSION_ENTRY_SAVED_CLIENT_CLOSED * - "prune" other abandoned sessions * - add SessionEntry to queue of abandoned sessions * If session is in state SESSION_ENTRY_SAVED_RM: * - flush session from TPM * - remove SessionEntry from session list * If session is in any other state * - panic */ void connection_close_session_callback (gpointer data, gpointer user_data) { SessionEntry *session_entry = SESSION_ENTRY (data); SessionEntryStateEnum session_state = session_entry_get_state (session_entry); connection_close_data_t *callback_data = (connection_close_data_t*)user_data; Connection *connection = callback_data->connection; ResourceManager *resource_manager = callback_data->resource_manager; TPM2_HANDLE handle; TSS2_RC rc; g_debug ("%s", __func__); if (session_entry->connection != connection) { g_debug ("%s: connection mismatch", __func__); return; } handle = session_entry_get_handle (session_entry); g_debug ("%s: SessionEntry is in state %s", __func__, session_entry_state_to_str (session_state)); switch (session_state) { case SESSION_ENTRY_SAVED_CLIENT: g_debug ("%s: abandoning.", __func__); session_list_abandon_handle (resource_manager->session_list, connection, handle); session_list_prune_abandoned (resource_manager->session_list, flush_session_callback, resource_manager); break; case SESSION_ENTRY_SAVED_RM: g_debug ("%s: flushing.", __func__); rc = tpm2_context_flush (resource_manager->tpm2, handle); if (rc != TSS2_RC_SUCCESS) { g_warning ("%s: failed to flush context", __func__); } session_list_remove (resource_manager->session_list, session_entry); break; default: /* This is a situation that should never happen */ g_error ("%s: Connection closed with session in unexpected state: %s", __func__, session_entry_state_to_str (session_state)); break; } } /* * This function is invoked when a connection is removed from the * ConnectionManager. This is if how we know a connection has been closed. * When a connection is removed, we need to remove all associated sessions * from the TPM. */ void resource_manager_remove_connection (ResourceManager *resource_manager, Connection *connection) { connection_close_data_t connection_close_data = { .connection = connection, .resource_manager = resource_manager, }; g_info ("%s: flushing session contexts", __func__); session_list_foreach (resource_manager->session_list, connection_close_session_callback, &connection_close_data); g_debug ("%s: done", __func__); } /** * Create new ResourceManager object. */ ResourceManager* resource_manager_new (Tpm2 *tpm2, SessionList *session_list) { if (tpm2 == NULL) g_error ("resource_manager_new passed NULL Tpm2"); MessageQueue *queue = message_queue_new (); return RESOURCE_MANAGER (g_object_new (TYPE_RESOURCE_MANAGER, "queue-in", queue, "tpm2", tpm2, "session-list", session_list, NULL)); }
37.808173
101
0.637095
[ "object", "transform" ]
645dbc81b35c81b50c3ad9cce393976d714a8de4
11,275
h
C
applications/physbam/physbam-lib/Public_Library/PhysBAM_Geometry/Grids_Dyadic_Advection_Collidable/ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_DYADIC.h
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
PhysBAM/Public_Library/PhysBAM_Geometry/Grids_Dyadic_Advection_Collidable/ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_DYADIC.h
uwgraphics/PhysicsBasedModeling-Core
dbc65b8e93b1a3d69fcc82aba06d28dc6c0adb8b
[ "BSD-3-Clause" ]
null
null
null
PhysBAM/Public_Library/PhysBAM_Geometry/Grids_Dyadic_Advection_Collidable/ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_DYADIC.h
uwgraphics/PhysicsBasedModeling-Core
dbc65b8e93b1a3d69fcc82aba06d28dc6c0adb8b
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2004-2006, Ron Fedkiw, Geoffrey Irving, Frank Losasso, Andrew Selle, Tamar Shinar. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_DYADIC //##################################################################### #ifndef COMPILE_WITHOUT_DYADIC_SUPPORT #ifndef __ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_DYADIC__ #define __ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_DYADIC__ #include <PhysBAM_Tools/Advection/ADVECTION.h> #include <PhysBAM_Tools/Grids_Dyadic/DYADIC_GRID_ITERATOR_CELL.h> #include <PhysBAM_Tools/Grids_Dyadic_Interpolation/AVERAGING_DYADIC.h> #include <PhysBAM_Tools/Grids_Dyadic_Interpolation/LINEAR_INTERPOLATION_DYADIC_HELPER.h> #include <PhysBAM_Geometry/Grids_Dyadic_Interpolation_Collidable/AVERAGING_COLLIDABLE_DYADIC.h> #include <PhysBAM_Geometry/Grids_Dyadic_Interpolation_Collidable/FACE_LOOKUP_COLLIDABLE_DYADIC.h> #include <PhysBAM_Geometry/Grids_Dyadic_Interpolation_Collidable/LINEAR_INTERPOLATION_COLLIDABLE_CELL_DYADIC.h> namespace PhysBAM{ template<class T_GRID,class T2,class T_FACE_LOOKUP> // T_FACE_LOOKUP=FACE_LOOKUP_COLLIDABLE_DYADIC<T_GRID> class ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_DYADIC:public ADVECTION<T_GRID,T2,T_FACE_LOOKUP> { typedef typename T_GRID::VECTOR_T TV;typedef typename TV::SCALAR T; typedef typename T_GRID::VECTOR_INT T_VECTOR_INT; typedef typename COLLISION_GEOMETRY_COLLECTION_POLICY<T_GRID>::GRID_BASED_COLLISION_GEOMETRY T_GRID_BASED_COLLISION_GEOMETRY;typedef typename T_GRID::CELL T_CELL; typedef typename INTERPOLATION_POLICY<T_GRID>::LINEAR_INTERPOLATION_HELPER T_LINEAR_INTERPOLATION_DYADIC_HELPER;typedef typename T_GRID::UNIFORM_GRID T_UNIFORM_GRID; typedef typename BOUNDARY_POLICY<T_GRID>::BOUNDARY_SCALAR T_BOUNDARY;typedef typename REBIND<T_BOUNDARY,T2>::TYPE T_BOUNDARY_T2; public: const T_GRID_BASED_COLLISION_GEOMETRY& body_list; ARRAY<bool> &cell_valid_points_current,&cell_valid_points_next; T2 cell_crossover_replacement_value; bool extrapolate_to_revalidate_interpolation; private: LINEAR_INTERPOLATION_COLLIDABLE_CELL_DYADIC<T_GRID,T2> linear_interpolation_collidable; LINEAR_INTERPOLATION_DYADIC<T_GRID,T2,typename T_FACE_LOOKUP::NESTED_LOOKUP> linear_interpolation; AVERAGING_DYADIC<T_GRID,typename T_FACE_LOOKUP::NESTED_LOOKUP> velocity_averaging; AVERAGING_COLLIDABLE_DYADIC<T_GRID,T_FACE_LOOKUP> velocity_averaging_collidable; public: ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_DYADIC(const T_GRID_BASED_COLLISION_GEOMETRY& body_list_input,ARRAY<bool>& cell_valid_points_current_input,ARRAY<bool>& cell_valid_points_next_input, const T2& default_cell_replacement_value_input,const bool extrapolate_to_revalidate_interpolation_input) :body_list(body_list_input),cell_valid_points_current(cell_valid_points_current_input),cell_valid_points_next(cell_valid_points_next_input), cell_crossover_replacement_value(default_cell_replacement_value_input),extrapolate_to_revalidate_interpolation(extrapolate_to_revalidate_interpolation_input), linear_interpolation_collidable(body_list,&cell_valid_points_current,cell_crossover_replacement_value,extrapolate_to_revalidate_interpolation), velocity_averaging_collidable(body_list,0) {} virtual ~ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_DYADIC() {} void Update_Advection_Equation_Cell_Lookup(const T_GRID& grid,ARRAY<T2>& Z,const ARRAY<T2>& Z_ghost, const T_FACE_LOOKUP& face_velocities,T_BOUNDARY_T2& boundary,const T dt,const T time, const ARRAY<T2>* Z_min_ghost,const ARRAY<T2>* Z_max_ghost,ARRAY<T2>* Z_min,ARRAY<T2>* Z_max) {assert(!Z_min && !Z_max); ARRAY<T2> Z_node_ghost(grid.number_of_nodes,false);T_LINEAR_INTERPOLATION_DYADIC_HELPER::Interpolate_From_Cells_To_Nodes(grid,Z_ghost,Z_node_ghost); for(DYADIC_GRID_ITERATOR_CELL<T_GRID> iterator(grid,0);iterator.Valid();iterator.Next()){int cell=iterator.Cell_Index(); if(!body_list.Swept_Occupied_Cell_Center(cell)){ TV sample_location=iterator.Location()-dt*velocity_averaging.Face_To_Cell_Vector(grid,iterator.Cell_Pointer(),face_velocities.Nested()); Z(cell)=linear_interpolation.From_Close_Cell_Cell(grid,iterator.Cell_Pointer(),Z_ghost,&Z_node_ghost,sample_location); cell_valid_points_next(cell)=true;} else{ TV grid_point_location=iterator.Location(),length_and_direction=-dt*velocity_averaging_collidable.Face_To_Cell_Vector(grid,iterator.Cell_Pointer(),face_velocities), interpolation_point=grid_point_location+length_and_direction; if(body_list.Latest_Cell_Crossover(cell,dt)){cell_valid_points_next(cell)=false;Z(cell)=linear_interpolation_collidable.default_cell_replacement_value;} else{ RAY<TV> backtrace_ray;COLLISION_GEOMETRY_ID body_id; if(RAY<TV>::Create_Non_Degenerate_Ray(grid_point_location,length_and_direction,backtrace_ray) && body_list.Closest_Non_Intersecting_Point_Of_Any_Body(backtrace_ray,body_id)) interpolation_point=backtrace_ray.Point(backtrace_ray.t_max); T_CELL* base_cell=grid.Base_Cell_By_Neighbor_Path(iterator.Cell_Pointer(),interpolation_point);assert(base_cell); BLOCK_DYADIC<T_GRID> block(grid,base_cell); Z(cell)=linear_interpolation_collidable.From_Block_Cell(grid,block,Z_ghost,interpolation_point,cell_valid_points_next(cell));}}} ARRAY<bool>::Exchange_Arrays(cell_valid_points_current,cell_valid_points_next);} private: void Get_Face_Values(const T_GRID& grid,T_CELL* cell,const ARRAY<bool>& cell_valid_points_current,const ARRAY<VECTOR<bool,T_GRID::dimension> >& cell_neighbors_visible, ARRAY<T_CELL*>& face_neighbors,const bool revalidate,ARRAY<T2>& values,T2& sum,T& weights,const T2& default_value) {ARRAY<VECTOR<T_CELL*,T_GRID::number_of_neighbors_per_cell> >& cell_neighbors=grid.Neighbors(); for(int axis=1;axis<=T_GRID::dimension;axis++){ T_CELL* min_neighbor=cell_neighbors(cell->Cell())(2*axis-1),*max_neighbor=cell_neighbors(cell->Cell())(2*axis); if(min_neighbor){ if(min_neighbor->Depth_Of_This_Cell()==grid.maximum_depth && cell_neighbors_visible(min_neighbor->Cell())(axis)){ if(cell_valid_points_current(min_neighbor->Cell())){sum+=min_neighbor->Face_Size()*values(min_neighbor->Cell());weights+=min_neighbor->Face_Size();} else{sum+=min_neighbor->Face_Size()*default_value;weights+=min_neighbor->Face_Size();}} else{ face_neighbors.Remove_All(); cell->Get_All_Face_Neighbors(1,face_neighbors,&grid); for(int n=1;n<=face_neighbors.m;n++){ if(cell_valid_points_current(face_neighbors(n)->Cell())){sum+=face_neighbors(n)->Face_Size()*values(face_neighbors(n)->Cell());weights+=face_neighbors(n)->Face_Size();} else if(revalidate){sum+=face_neighbors(n)->Face_Size()*default_value;weights+=face_neighbors(n)->Face_Size();}}}} if(max_neighbor){ if(max_neighbor->Depth_Of_This_Cell()==grid.maximum_depth && cell_neighbors_visible(cell->Cell())(axis)){ if(cell_valid_points_current(max_neighbor->Cell())){sum+=max_neighbor->Face_Size()*values(max_neighbor->Cell());weights+=max_neighbor->Face_Size();} else{sum+=max_neighbor->Face_Size()*default_value;weights+=max_neighbor->Face_Size();}} else{ face_neighbors.Remove_All(); cell->Get_All_Face_Neighbors(1,face_neighbors,&grid); for(int n=1;n<=face_neighbors.m;n++){ if(cell_valid_points_current(face_neighbors(n)->Cell())){sum+=face_neighbors(n)->Face_Size()*values(face_neighbors(n)->Cell());weights+=face_neighbors(n)->Face_Size();} else if(revalidate){sum+=face_neighbors(n)->Face_Size()*default_value;weights+=face_neighbors(n)->Face_Size();}}}}}} public: void Average_To_Invalidated_Cells(const T_GRID& grid,const T2 default_value,ARRAY<T2>& values) {// average values collision aware in Gauss-Jacobi fashion bool done=false;ARRAY<PAIR<T_CELL*,bool> > invalid_indices; // index and bool true if entry has been validated on iteration for(DYADIC_GRID_ITERATOR_CELL<T_GRID> iterator(grid);iterator.Valid();iterator.Next()) if(!cell_valid_points_current(iterator.Cell_Index())) invalid_indices.Append(PAIR<T_CELL*,bool>(iterator.Cell_Pointer(),false)); for(DYADIC_GRID_ITERATOR_CELL<T_GRID> iterator(grid,3,T_UNIFORM_GRID::GHOST_REGION);iterator.Valid();iterator.Next()) cell_valid_points_current(iterator.Cell_Index())=false; ARRAY<T_CELL*> face_neighbors; const ARRAY<VECTOR<bool,T_GRID::dimension> >& cell_neighbors_visible=body_list.cell_neighbors_visible; while(!done){ done=true; for(int k=1;k<=invalid_indices.m;k++){ T_CELL* cell=invalid_indices(k).x; T2 sum=T2();T weights=0; Get_Face_Values(grid,invalid_indices(k).x,cell_valid_points_current,cell_neighbors_visible,face_neighbors,false,values,sum,weights,default_value); if(weights>0){values(cell->Cell())=sum/weights;invalid_indices(k).y=true;done=false;}} if(!done) for(int k=invalid_indices.m;k>=1;k--) if(invalid_indices(k).y){cell_valid_points_current(invalid_indices(k).x->Cell())=true;invalid_indices.Remove_Index_Lazy(k);}} // keep a copy of currently valid nodes (used for phi so we can revalidate the remaining nodes again after collision aware fast marching) // but important to initialize ghost nodes to true since currently cell_valid_points_current has them set to false cell_valid_points_next=cell_valid_points_current; for(DYADIC_GRID_ITERATOR_CELL<T_GRID> iterator(grid,3,T_UNIFORM_GRID::GHOST_REGION);iterator.Valid();iterator.Next()) cell_valid_points_next(iterator.Cell_Index())=true; // average values collision aware in Gauss-Jacobi fashion (here we replace non-visible values with special values defined by Compute_Revalidation_Value()) done=false; while(!done){ done=true; for(int k=1;k<=invalid_indices.m;k++){ T_CELL* cell=invalid_indices(k).x; T2 sum=T2();T weights=0; Get_Face_Values(grid,invalid_indices(k).x,cell_valid_points_current,cell_neighbors_visible,face_neighbors,true,values,sum,weights,default_value); if(weights>0){values(cell->Cell())=sum/weights;invalid_indices(k).y=true;done=false;} else values(cell->Cell())=default_value;} if(!done) for(int k=invalid_indices.m;k>=1;k--) if(invalid_indices(k).y){cell_valid_points_current(invalid_indices(k).x->Cell())=true;invalid_indices.Remove_Index_Lazy(k);}} for(DYADIC_GRID_ITERATOR_CELL<T_GRID> iterator(grid,3,T_UNIFORM_GRID::GHOST_REGION);iterator.Valid();iterator.Next()) cell_valid_points_current(iterator.Cell_Index())=true;} //##################################################################### }; } #endif #endif
79.964539
195
0.749623
[ "vector" ]
64695ed48d57ff051ab584922a33b8e36ef5ab0c
5,178
h
C
include/retdec/bin2llvmir/optimizations/phi2seq/phi2seq.h
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
521
2019-03-29T15:44:08.000Z
2022-03-22T09:46:19.000Z
include/retdec/bin2llvmir/optimizations/phi2seq/phi2seq.h
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
30
2019-06-04T17:00:49.000Z
2021-09-08T20:44:19.000Z
include/retdec/bin2llvmir/optimizations/phi2seq/phi2seq.h
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
99
2019-03-29T16:04:13.000Z
2022-03-28T16:59:34.000Z
/** * @file include/retdec/bin2llvmir/optimizations/phi2seq/phi2seq.h * @brief Solves parallel processing of PHI nodes. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #ifndef RETDEC_BIN2LLVMIR_OPTIMIZATIONS_PHI2SEQ_PHI2SEQ_H #define RETDEC_BIN2LLVMIR_OPTIMIZATIONS_PHI2SEQ_PHI2SEQ_H #include <vector> #include <llvm/IR/IRBuilder.h> #include <llvm/Pass.h> #include "retdec/bin2llvmir/analyses/var_depend_analysis.h" namespace retdec { namespace bin2llvmir { /** * @brief Optimization that solves the problem of parallel processing of PHI * nodes. * * @pre The <em>Assign names to anonymous instructions</em> * (<tt>-instnamer</tt>) pass has to be run before this optimization. This * optimization automatically runs it. * * This optimization is needed because PHI nodes in a single block in LLVM IR * are executed in parallel basic block but our output languages like C or * Python are sequential. Hence, we need to transform the parallel processing to * equivalent sequential processing. * * We can divide this problem into two sub-problems. The first sub-problem * represents the dependency of variables like this: * @code * .bb * %A = phi i32 [ %D, %bb1 ], [ 10, %0 ] * %B = phi i32 [ %A, %bb1 ], [ 66, %0 ] * @endcode * If we look at this example with sequential processing, to variable A was * assigned the value of variable D and this value was assigned in B which is * not equivalent with parallel processing. The solution is to order PHI nodes * to a correct sequential order which is equivalent with parallel processing * like this: * @code * %B = phi i32 [ %A, %bb1 ], [ 66, %0 ] * %A = phi i32 [ %D, %bb1 ], [ 10, %0 ] * @endcode * * The second sub-problem that we need to solve is when we have a cycle * dependency of variables in PHI nodes. For example: * @code * .bb: * %A = phi i32 [ %B, %bb1 ], [ 1, %0 ] * %B = phi i32 [ %C, %bb1 ], [ 2, %0 ] * %C = phi i32 [ %A, %bb1 ], [ 3, %0 ] * @endcode * All PHI nodes are performed in parallel but we need for the back-end an * equivalent sequential processing. A solution is to create new PHI nodes in a * new basic block an update the dependencies. Something like this: * @code * .bb.phi2seq.pre: * %C.phi2seq.tmp = [ %C, %bb1 ] * br label %.bb * * .bb: * %A = phi i32 [ %B, %.bb.phi2seq.pre ], [ 1, %0 ] * %B = phi i32 [ %C.phi2seq.tmp, %.bb.phi2seq.pre ], [ 2, %0 ] * %C = phi i32 [ %A, %.bb.phi2seq.pre ], [ 3, %0 ] * @endcode * * This optimization solves both of these sub-problems, thus making sequential * processing of PHI nodes possible. */ class PHI2Seq: public llvm::FunctionPass { public: PHI2Seq(); virtual ~PHI2Seq() override; static const char *getName() { return NAME; } virtual bool runOnFunction(llvm::Function &func) override; virtual void getAnalysisUsage(llvm::AnalysisUsage &au) const override; public: static char ID; private: /// Name of the optimization. static const char *NAME; /** * @brief Structure for PHI node on which we substitute values. */ struct PHINodeToSubs { /** * @brief Constructs a new @c PHINodeToSubs. * * @param[in] phiNodeToSubs PHI node to substitute. * @param[in] oldValue Old value that will be substituted. * @param[in] newValue New value to substitute. */ PHINodeToSubs(llvm::PHINode *phiNodeToSubs, llvm::Value *oldValue, llvm::Value *newValue): phiNodeToSubs(phiNodeToSubs), oldValue(oldValue), newValue(newValue) {} /// PHI node to substitute. llvm::PHINode *phiNodeToSubs; /// Old value that will be substituted. llvm::Value *oldValue; /// New value to to substitute. llvm::Value *newValue; }; /// Vector of @c PHINodeToSubs. using PHINodeToSubsVec = std::vector<PHINodeToSubs>; private: llvm::BasicBlock &createPreBBAndSolveConnection( const VarDependAnalysis::BBVecOfPHINodes &bbWithPHINodesVec, llvm::BasicBlock &currBB); void createTmpPHINodes(llvm::IRBuilder<> &builder, const VarDependAnalysis::BBVecOfPHINodes &bbWithPHINodesVec); void initVarDependAnalysis(llvm::BasicBlock &bb); void iteratePHINodesAndInitVarDependAnalysis(llvm::BasicBlock &bb); void iterateIncValuesAndInitVarDependAnalysis(llvm::PHINode &phiNode); void orderDependentPHINodes(llvm::BasicBlock &bb, const VarDependAnalysis::PHINodeVec &nonCyclesDependResult); void orderDependentPHINodesAndSolveCycles(llvm::BasicBlock &bb); void replaceValueForPHINode(llvm::PHINode &phiNodeToUpdate, llvm::Value &oldValue, llvm::Value &newValue, llvm::BasicBlock &pred); void solveCycleVarDependency(llvm::BasicBlock &bb, const VarDependAnalysis::StringBBVecOfPHINodesMap &cyclesDetectResult); void updateBBTermInstr(llvm::BasicBlock &bbToUpdate, llvm::BasicBlock &oldSucc, llvm::BasicBlock &newSucc); void updateBBWithCycle(llvm::BasicBlock &bb, llvm::BasicBlock &oldBB, llvm:: BasicBlock &newBB); void updatePredecessorsInPHINodes(llvm::BasicBlock &bb, llvm::BasicBlock &oldBB, llvm::BasicBlock &newBB); private: /// PHI nodes dependency analysis. VarDependAnalysis varDependAnalysis; /// Vector of PHI nodes on which are substitute values. PHINodeToSubsVec phiNodeToSubsVec; }; } // namespace bin2llvmir } // namespace retdec #endif
33.406452
79
0.725956
[ "vector", "transform" ]
646b52895c865116f93aeb163630b796a201c742
15,953
h
C
clients/ios/Obsolete/OldPhotoManager.h
sleepingAnt/viewfinder
9caf4e75faa8070d85f605c91d4cfb52c4674588
[ "Apache-2.0" ]
645
2015-01-03T02:03:59.000Z
2021-12-03T08:43:16.000Z
clients/ios/Obsolete/OldPhotoManager.h
hoowang/viewfinder
9caf4e75faa8070d85f605c91d4cfb52c4674588
[ "Apache-2.0" ]
null
null
null
clients/ios/Obsolete/OldPhotoManager.h
hoowang/viewfinder
9caf4e75faa8070d85f605c91d4cfb52c4674588
[ "Apache-2.0" ]
222
2015-01-07T05:00:52.000Z
2021-12-06T09:54:26.000Z
// Copyright 2012 Viewfinder. All rights reserved. // Author: Peter Mattis. #ifndef VIEWFINDER_PHOTO_MANAGER_H #define VIEWFINDER_PHOTO_MANAGER_H #import <set> #import <tr1/unordered_map> #import <tr1/unordered_set> #import <vector> #import <stdint.h> #import "AssetsManager.h" #import "AsyncState.h" #import "DB.h" #import "Callback.h" #import "Image.h" #import "PhotoMetadata.pb.h" #import "ValueUtils.h" #import "WallTime.h" class AppState; class Breadcrumb; class EpisodeUpdate; class GetMetadataResponse; class MetadataUploadResponse; class PhotoStorage; class PhotoUpdate; class PlacemarkHistogram; class QueryUpdatesResponse; class ShareResponse; @class CIDetector; typedef std::tr1::unordered_set<string> ServerIdSet; bool HasAssetKey(const PhotoId& id); string GetAssetKey(const PhotoId& id); bool DecodeServerId(const string& server_id, uint64_t* device_id, uint64_t* device_local_id); class PhotoManager { public: struct EpisodeData; struct PhotoData { PhotoData() : priority(-1), timestamp(0), location(NULL), placemark(NULL), episode(NULL) { } int priority; WallTime timestamp; PhotoMetadata metadata; const Location* location; const Placemark* placemark; EpisodeData* episode; }; typedef std::vector<PhotoData*> PhotoVec; struct EpisodeData { EpisodeData() : location(NULL), placemark(NULL) { } EpisodeMetadata metadata; const Location* location; const Placemark* placemark; PhotoVec photos; }; enum PhotoType { THUMBNAIL = PhotoMetadata::THUMBNAIL, MEDIUM = PhotoMetadata::MEDIUM, FULL = PhotoMetadata::FULL, ORIGINAL = PhotoMetadata::ORIGINAL, }; struct PhotoUpload { PhotoUpload(PhotoData* p = NULL) : photo(p) { } PhotoData* photo; PhotoType type; string url; string path; string md5; }; struct PhotoDownload { PhotoId id; PhotoType type; string path; string url; }; struct MetadataUpload { std::vector<PhotoData*> photos; }; struct ShareUpload { PhotoVec photos; vector<ContactMetadata> contacts; }; struct UnshareUpload { PhotoVec photos; }; struct DeleteUpload { PhotoVec photos; }; private: struct PhotoByTimestamp { bool operator()(const PhotoData* a, const PhotoData* b) const { if (a->metadata.timestamp() != b->metadata.timestamp()) { return a->metadata.timestamp() > b->metadata.timestamp(); } // Distinguish identical timestamps using the local id. This makes // ordering predictable for tests. return a->metadata.id().local_id() < b->metadata.id().local_id(); } }; struct PhotoQueueCompare { bool operator()(const PhotoData* a, const PhotoData* b) const { if (a->priority != b->priority) { return a->priority > b->priority; } // Within a priority, sort on timestamp. if (a->timestamp != b->timestamp) { return a->timestamp > b->timestamp; } // Distinguish identical timestamps using the local id. This makes // ordering predictable for tests. return a->metadata.id().local_id() < b->metadata.id().local_id(); } }; struct LocationHash { size_t operator()(const Location& l) const { return static_cast<size_t>( 1e6 * (l.latitude() + l.longitude()) + l.accuracy()); } }; struct LocationEq { bool operator()(const Location& a, const Location& b) const { return a.latitude() == b.latitude() && a.longitude() == b.longitude() && a.accuracy() == b.accuracy(); } }; struct PlacemarkHash { std::tr1::hash<string> h; size_t operator()(const Placemark& p) const { return h(p.iso_country_code()) + h(p.country()) + h(p.state()) + h(p.postal_code()) + h(p.locality()) + h(p.sublocality()) + h(p.thoroughfare()) + h(p.subthoroughfare()); } }; struct PlacemarkEq { bool operator()(const Placemark& a, const Placemark& b) const { return a.iso_country_code() == b.iso_country_code() && a.country() == b.country() && a.state() == b.state() && a.postal_code() == b.postal_code() && a.locality() == b.locality() && a.sublocality() == b.sublocality() && a.thoroughfare() == b.thoroughfare() && a.subthoroughfare() == b.subthoroughfare(); } }; public: typedef std::tr1::unordered_map<int64_t, PhotoData> PhotoMap; typedef std::tr1::unordered_map<string, PhotoData*> ServerPhotoMap; typedef std::tr1::unordered_set<PhotoData*> PhotoSet; typedef std::tr1::unordered_map<int64_t, string> PhotoURLMap; typedef std::set<PhotoData*, PhotoQueueCompare> PhotoQueue; typedef std::tr1::unordered_map<PhotoData*, Image> PhotoDetectQueue; typedef std::tr1::unordered_set<EpisodeData*> EpisodeSet; typedef std::tr1::unordered_map<int64_t, EpisodeData> EpisodeMap; typedef std::tr1::unordered_map<string, EpisodeData*> ServerEpisodeMap; typedef std::tr1::unordered_map< Location, const Placemark*, LocationHash, LocationEq> LocationMap; typedef std::tr1::unordered_set< Placemark, PlacemarkHash, PlacemarkEq> PlacemarkSet; typedef CallbackSet1<bool> GeocodeCallbackSet; typedef std::tr1::unordered_map< const Location*, GeocodeCallbackSet*> GeocodeCallbackMap; typedef CallbackSet1<int> DownloadCallbackSet; typedef std::tr1::unordered_map< int64_t, DownloadCallbackSet*> DownloadCallbackMap; public: class Env { public: virtual ~Env() { } virtual void AssetForKey(const string& key, ALAssetsLibraryAssetForURLResultBlock result, ALAssetsLibraryAccessFailureBlock failure) = 0; virtual void TryDeleteAsset(const string& key) = 0; virtual void NetworkDispatch() = 0; virtual bool ReverseGeocode( const Location* l, void (^completion)(const Placemark*)) = 0; virtual CallbackSet* assets_scan_end() = 0; virtual AssetScanProgress* assets_scan_progress() = 0; virtual CallbackSet* auth_changed() = 0; virtual CallbackSet* network_changed() = 0; virtual CallbackSet* network_ready() = 0; virtual CallbackSet* settings_changed() = 0; virtual bool assets_scanning() = 0; virtual bool assets_full_scan() = 0; virtual bool cloud_storage() = 0; virtual const Breadcrumb* last_breadcrumb() = 0; virtual bool logged_in() = 0; virtual bool network_up() = 0; virtual bool network_wifi() = 0; virtual const string& photo_dir() = 0; virtual bool store_originals() = 0; virtual int64_t user_id() = 0; virtual DB* db() = 0; virtual PhotoStorage* photo_storage() = 0; virtual PlacemarkHistogram* placemark_histogram() = 0; }; public: PhotoManager(AppState* state); PhotoManager(Env* env); ~PhotoManager(); void EnsureInit(); void MemoryStats(); int64_t NewViewfinderPhoto(const PhotoMetadata& m, NSData* data); int64_t NewAssetPhoto(ALAsset* asset, const string& asset_key, bool complete_on_main_thread); void SetDeviceId(int64_t device_id); // Process query updates, adding any photos and episodes that we don't have // to the retrieval queue. void ProcessQueryUpdates(const QueryUpdatesResponse& r); // Process the retrieval of photo and episode metadata. void ProcessGetMetadata(const GetMetadataResponse& r); // Commit the current metadata upload. void CommitQueuedMetadataUpload(const MetadataUploadResponse& r); // Commit the current photo upload. void CommitQueuedPhotoUpload(bool error); // Commit the current photo download. void CommitQueuedPhotoDownload(int64_t photo_id, const string& md5, bool retry); // Commit the current share upload. void CommitQueuedShareUpload(); // Commit the current unshare upload. void CommitQueuedUnshareUpload(); // Commit the current delete upload. void CommitQueuedDeleteUpload(); // Add the specified contacts to the share list for the specified photos. void SharePhotos(const vector<int64_t>& photo_ids, const vector<ContactMetadata>& contacts); // Unshare the specified photos. void UnsharePhotos(const vector<int64_t>& photo_ids); // Delete the specified photos. void DeletePhotos(const vector<int64_t>& photo_ids); void DeletePhoto(int64_t photo_id, DB::Batch* updates); // Asynchronously load a thumbnail/photo. These methods return their result // on the done() block, but must be called from the main thread. void LoadLocalThumbnail(int64_t photo_id, Image* image, void (^done)()); void LoadLocalPhoto(int64_t photo_id, CGSize size, Image* image, void (^done)()); void LoadNetworkThumbnail(int64_t photo_id, Image* image, void (^done)()); void LoadNetworkPhoto(int64_t photo_id, CGSize size, Image* image, void (^done)()); bool NeedsReverseGeocode(int64_t photo_id); bool ReverseGeocode(int64_t photo_id, void (^completion)(bool success)); bool FormatLocation(int64_t photo_id, bool short_location, string* s); bool DistanceToLocation(int64_t photo_id, double* distance); const Placemark* GetPlacemark(int64_t photo_id); WallTime GetTimestamp(int64_t photo_id); int64_t device_id() const { return device_id_; } CallbackSet* geocode() { return &geocode_; } CallbackSet* queue() { return &queue_; } CallbackSet* update() { return &update_; } const PhotoMap& photos() const { return photo_map_; } const EpisodeMap& episodes() const { return episode_map_; } int num_photos() const { return photo_map_.size(); } int num_queued_photos() const { return queued_photos_.size(); } int num_queued_uploads() const { return queued_uploads_.size(); } int num_queued_downloads() const { return queued_downloads_.size(); } int num_queued_shares() const { return queued_shares_.size(); } int num_episodes() const { return episode_map_.size(); } const MetadataUpload* queued_metadata_upload() const { return queued_metadata_upload_.get(); } const PhotoUpload* queued_photo_upload() const { return queued_photo_upload_.get(); } const PhotoDownload* queued_photo_download() { return queued_photo_download_.get(); } const ShareUpload* queued_share_upload() const { return queued_share_upload_.get(); } const UnshareUpload* queued_unshare_upload() const { return queued_unshare_upload_.get(); } const DeleteUpload* queued_delete_upload() const { return queued_delete_upload_.get(); } const string& query_updates_key() const { return query_updates_key_; } const ServerIdSet& update_photo_ids() const { return update_photo_ids_; } const ServerIdSet& update_episode_ids() const { return update_episode_ids_; } private: void CommonInit(); void GarbageCollectAssets(); PhotoData* NewPhoto(const PhotoMetadata& p, bool owned, DB::Batch* updates); EpisodeData* NewEpisode(DB::Batch* updates); void CommitDeletePhoto(PhotoData* p, DB::Batch* updates); void DeleteEmptyEpisode(EpisodeData* e, DB::Batch* updates); bool LoadEpisode(EpisodeData* e, const EpisodeId& id); void AddPhoto(PhotoData* p, DB::Batch* updates); void AddPhoto(const Slice& key, const Slice& value, bool reset_errors); void AddPhotoToEpisode(PhotoData* p, DB::Batch* updates); void AddPhotoToExistingEpisode(PhotoData* p, EpisodeData* e, DB::Batch* updates); void RemovePhotoFromEpisode(PhotoData* p, DB::Batch* updates); EpisodeData* MatchPhotoToEpisode(PhotoData* p); bool ShouldAddPhotoToEpisode(PhotoData* p) const; bool ShouldDelete(PhotoData* p) const; void InternPhotoLocation(PhotoData* p); void InternEpisodeLocation(EpisodeData* e); void QuarantinePhoto(PhotoData* p); void LoadViewfinderPhotoError(PhotoData* p, const string& filename, void (^done)(bool error)); void LoadAssetPhotoError(PhotoData* p, int types, void (^done)(bool error)); void UploadPhotoError(PhotoData* p, int types); void DownloadPhotoError(PhotoData* p, int types); void WaitForDownload(int64_t photo_id, PhotoType type, void (^done)()); void NotifyDownload(int64_t photo_id, int types); void MergePhotoUpdate(const PhotoUpdate& u, bool queue_update, DB::Batch* updates); void MergePhotoUpdate(PhotoData* p, const PhotoUpdate& u, DB::Batch* updates, bool dirty); bool MergePhotoMetadata(PhotoData* p, const PhotoMetadata& m, DB::Batch* updates); void MergeEpisodeUpdate(const EpisodeUpdate& u, bool queue_update, DB::Batch* updates); bool MergeEpisodeMetadata(EpisodeData* e, const EpisodeMetadata& m); void OutputPhotoMetadata(PhotoData* p, DB::Batch* updates); void OutputEpisodeMetadata(EpisodeData* e, DB::Batch* updates); void ReprioritizePhotoQueue(); void UnqueuePhoto(PhotoData* p); void MaybeQueuePhoto(PhotoData* p); void MaybeQueueNetwork(); void MaybeQueueMetadataUpload(EpisodeData* e); void MaybeLoadImages(MetadataUpload* u, int index); bool MaybeLoadImageData(PhotoData* p, int size, void (^completion)(const string& path, const string& md5)); void MaybeReverseGeocode(MetadataUpload* u, int index); void MaybeQueuePhotoUpload(PhotoData* p); void MaybeQueuePhotoDownload(PhotoData* p); void MaybeQueueShareUpload(); void MaybeQueueUnshareUpload(); void MaybeQueueDeleteUpload(); bool MaybeLoadInternal(PhotoData* p, CGSize size, bool store_jpeg, NSData* __strong* jpeg_data, Image* image, void (^done)()); bool MaybeLoadViewfinder(PhotoData* p, CGSize size, bool store_jpeg, NSData* __strong* jpeg_data, Image* image, void (^done)(bool error)); bool MaybeLoadAsset(PhotoData* p, CGSize size, bool store_jpeg, NSData* __strong* jpeg_data, Image* image, void (^done)(bool error)); void MaybeWriteThumbnail(PhotoData* p, NSData* jpeg_data); void MaybeQueueDetect(PhotoData* p, const Image& image); void MaybeDetect(); void DetectFeatures(PhotoData* p, Image* image); private: ScopedPtr<Env> env_; ScopedPtr<AsyncState> async_; string photo_dir_; string photo_tmp_dir_; bool initialized_; int64_t device_id_; int64_t next_photo_id_; int64_t next_episode_id_; string query_updates_key_; PhotoMap photo_map_; ServerPhotoMap server_photo_map_; PhotoQueue queued_photos_; PhotoSet queued_uploads_; PhotoSet queued_downloads_; PhotoSet queued_shares_; PhotoDetectQueue queued_detects_; EpisodeMap episode_map_; ServerEpisodeMap server_episode_map_; LocationMap locations_; PlacemarkSet placemarks_; GeocodeCallbackMap geocode_callback_map_; DownloadCallbackMap download_callback_map_; PhotoURLMap thumbnail_get_urls_; PhotoURLMap thumbnail_put_urls_; PhotoURLMap medium_get_urls_; PhotoURLMap medium_put_urls_; PhotoURLMap full_get_urls_; PhotoURLMap full_put_urls_; PhotoURLMap original_get_urls_; PhotoURLMap original_put_urls_; CallbackSet geocode_; CallbackSet queue_; CallbackSet update_; WallTime last_load_time_; ScopedPtr<MetadataUpload> queued_metadata_upload_; ScopedPtr<PhotoUpload> queued_photo_upload_; ScopedPtr<PhotoDownload> queued_photo_download_; ScopedPtr<ShareUpload> queued_share_upload_; ScopedPtr<UnshareUpload> queued_unshare_upload_; ScopedPtr<DeleteUpload> queued_delete_upload_; bool queue_in_progress_; WallTime queue_start_time_; PhotoData* detect_in_progress_; ServerIdSet update_photo_ids_; ServerIdSet update_episode_ids_; CIDetector* face_detector_; }; #endif // VIEWFINDER_PHOTO_MANAGER_H
34.530303
83
0.697549
[ "vector" ]
646cec5bcc9b6dc27f00da35e8d8a1e2174ae4df
4,719
h
C
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dlockabletexture.h
txlos/wpf
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
[ "MIT" ]
5,937
2018-12-04T16:32:50.000Z
2022-03-31T09:48:37.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dlockabletexture.h
txlos/wpf
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
[ "MIT" ]
4,151
2018-12-04T16:38:19.000Z
2022-03-31T18:41:14.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dlockabletexture.h
txlos/wpf
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
[ "MIT" ]
1,084
2018-12-04T16:24:21.000Z
2022-03-30T13:52:03.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------------- // // // $TAG ENGR // $Module: win_mil_graphics_text // $Keywords: // // $Description: // Contains lockable D3D texture class declaration and the stack based lock // helper class // // Contains also CD3DLockableTexturePair class declaration and stack based // lock helper class for it. // // $ENDTAG // //------------------------------------------------------------------------------ MtExtern(CD3DLockableTexture); MtExtern(D3DResource_LockableTexture); class CD3DTexture; class CD3DLockableTexture : public CD3DTexture { protected: DECLARE_METERHEAP_ALLOC(ProcessHeap, Mt(CD3DLockableTexture)); public: DEFINE_RESOURCE_REF_COUNT_BASE static HRESULT Create( __inout_ecount(1) CD3DResourceManager *pResourceManager, __in_ecount(1) IDirect3DTexture9 *pD3DTexture, __deref_out_ecount(1) CD3DLockableTexture **ppD3DLockableTexture ); // Only call this method if you are certain that we have a system memory // texture. HRESULT LockRect( __out_ecount(1) D3DLOCKED_RECT* pLockedRect, __in_ecount(1) CONST RECT* pRect, DWORD dwFlags ); HRESULT UnlockRect(); HRESULT AddDirtyRect( __in_ecount(1) const RECT &rc ); protected: CD3DLockableTexture(); ~CD3DLockableTexture(); HRESULT Init( __inout_ecount(1) CD3DResourceManager *pResourceManager, __in_ecount(1) IDirect3DTexture9 *pD3DTexture ); #if PERFMETER virtual PERFMETERTAG GetPerfMeterTag() const { return Mt(D3DResource_LockableTexture); } #endif }; //+----------------------------------------------------------------------------- // // Class: // CD3DLockableTexturePair // // Synopsis: // Holds one or two lockable textures. Normally, only the main one is used; // the second is involved only for text rendering in clear type mode. // Clear type requires 6 components per texel: three colors and three // alphas (separate alpha for each color component). As far as DX allows // only four components, we store alphas separately in m_pAuxTexture, while // m_pMainTexture stores colors. // //------------------------------------------------------------------------------ class CD3DLockableTexturePair { public: CD3DLockableTexturePair(); ~CD3DLockableTexturePair(); VOID InitMain( __in_ecount(1) CD3DLockableTexture *pTexture ); VOID InitAux( __in_ecount(1) CD3DLockableTexture *pTexture ); HRESULT Draw( __in_ecount(1) CD3DDeviceLevel1 *pDevice, __in_ecount(1) const MilPointAndSizeL &rc, bool fUseAux ); private: friend class CD3DLockableTexturePairLock; CD3DLockableTexture *m_pTextureMain; CD3DLockableTexture *m_pTextureAux; }; //+----------------------------------------------------------------------------- // // Class: // CD3DLockableTexturePairLock // // Synopsis: // The helper class for CD3DLockableTexturePair locking/unlocking. This is // short-term life time object supposed to live in stack frame. // //------------------------------------------------------------------------------ class CD3DLockableTexturePairLock { public: CD3DLockableTexturePairLock( __in_ecount(1) const CD3DLockableTexturePair* pTexturePair ) : m_texturePair(*pTexturePair) { m_fMainLocked = false; m_fAuxLocked = false; } struct LockData { BYTE *pMainBits; BYTE *pAuxBits; INT uPitch; #if DBG_ANALYSIS UINT m_uDbgAnalysisLockedWidth; UINT m_uDbgAnalysisLockedHeight; #endif }; HRESULT Lock( UINT uWidth, UINT uHeight, __out_ecount(1) LockData &lockData, bool fUseAux = false ); ~CD3DLockableTexturePairLock() { if (m_fMainLocked) { IGNORE_HR(m_texturePair.m_pTextureMain->UnlockRect()); } if (m_fAuxLocked) { IGNORE_HR(m_texturePair.m_pTextureAux->UnlockRect()); } } private: static HRESULT LockOne( __in_ecount(1) CD3DLockableTexture* pTexture, UINT uWidth, UINT uHeight, __out_ecount(1) D3DLOCKED_RECT* pD3DLockedRect ); private: CD3DLockableTexturePair const& m_texturePair; bool m_fMainLocked; bool m_fAuxLocked; };
25.646739
80
0.59822
[ "object" ]
647298851c9d75320f1d3c6fefe963780db2f958
1,699
h
C
Physics3D/geometry/shapeClass.h
ThePhysicsGuys/Physics3D
ac621163f353fd3b765756c99e1fe1407b916752
[ "MIT" ]
175
2018-11-27T15:29:35.000Z
2022-03-24T19:33:54.000Z
Physics3D/geometry/shapeClass.h
ThePhysicsGuys/Physics3D
ac621163f353fd3b765756c99e1fe1407b916752
[ "MIT" ]
5
2020-07-14T11:14:10.000Z
2022-03-15T16:16:07.000Z
Physics3D/geometry/shapeClass.h
ThePhysicsGuys/Physics3D
ac621163f353fd3b765756c99e1fe1407b916752
[ "MIT" ]
19
2020-02-26T13:20:48.000Z
2022-02-24T05:45:06.000Z
#pragma once #include "../math/linalg/vec.h" #include "../math/linalg/mat.h" #include "../math/rotation.h" #include "../math/boundingBox.h" #include "genericCollidable.h" #include "scalableInertialMatrix.h" namespace P3D { class Polyhedron; // a ShapeClass is defined as a shape with dimentions -1..1 in all axes. All functions work on scaled versions of the shape. // examples include: // Sphere of radius=1 // Cube of 2x2x2 // Custom polygon of 2x2x2 class ShapeClass : public GenericCollidable { public: const double volume; const Vec3 centerOfMass; const ScalableInertialMatrix inertia; const int intersectionClassID; ShapeClass(double volume, Vec3 centerOfMass, ScalableInertialMatrix inertia, int intersectionClassID); virtual bool containsPoint(Vec3 point) const = 0; virtual double getIntersectionDistance(Vec3 origin, Vec3 direction) const = 0; virtual BoundingBox getBounds(const Rotation& referenceFrame, const DiagonalMat3& scale) const = 0; virtual double getScaledMaxRadius(DiagonalMat3 scale) const; virtual double getScaledMaxRadiusSq(DiagonalMat3 scale) const = 0; /* This must return a valid Vec3f on the surface of the shape, even for 0,0,0 Does not need to take account of NaN or infinities in the input argument */ virtual Vec3f furthestInDirection(const Vec3f& direction) const = 0; virtual Polyhedron asPolyhedron() const = 0; // these functions determine the relations between the axes, for example, for Sphere, all axes must be equal virtual void setScaleX(double newX, DiagonalMat3& scale) const; virtual void setScaleY(double newY, DiagonalMat3& scale) const; virtual void setScaleZ(double newZ, DiagonalMat3& scale) const; }; };
35.395833
125
0.770453
[ "shape" ]
647aefa32b0fae0de63850cd97d3374e27ed20e3
1,148
h
C
Search/SearchLib/internal/pattern/ConstructorDeclarationPattern.h
kuafuwang/JCDT
2b009ea887b4816303fed9e6e1dc104a90c67d16
[ "MIT" ]
1
2021-04-17T01:55:27.000Z
2021-04-17T01:55:27.000Z
Search/SearchLib/internal/pattern/ConstructorDeclarationPattern.h
kuafuwang/JCDT
2b009ea887b4816303fed9e6e1dc104a90c67d16
[ "MIT" ]
null
null
null
Search/SearchLib/internal/pattern/ConstructorDeclarationPattern.h
kuafuwang/JCDT
2b009ea887b4816303fed9e6e1dc104a90c67d16
[ "MIT" ]
1
2022-02-18T12:02:00.000Z
2022-02-18T12:02:00.000Z
#ifndef ConstructorDeclarationPattern_JIKES_SERACH_INCLUDE #define ConstructorDeclarationPattern_JIKES_SERACH_INCLUDE #include "MethodDeclarationPattern.h" namespace Jikes { // Open namespace Jikes block namespace Search{ class ConstructorDeclarationPattern:public MethodDeclarationPattern { public: ConstructorDeclarationPattern(std::wstring declaringSimpleName, int _matchMode, bool _isCaseSensitive, std::wstring declaringQualification, std::vector<std::wstring>* parameterQualifications, std::vector<std::wstring>* parameterSimpleNames); /** * @see SearchPattern#matchesBinary(Object, Object) */ bool matchesBinary(std::pair<void*, BinaryInfoType>& binaryInfo, std::pair<const ConstantPool*, CPClassInfo*>& class_data); /** * @see SearchPattern#matchLevel(AstNode, bool) */ int matchLevel(Ast* node, bool resolve); /** * @see SearchPattern#matchLevel(Binding) */ int matchLevel(Symbol* binding); }; }// Close namespace Search block } // Close namespace Jikes block #endif
30.210526
126
0.687282
[ "object", "vector" ]
6481a12eaa2e09b80d08c73b8d237d20ccfbe92f
26,053
h
C
src/irelic.h
rodriguescr/libfastlib
b89172ae727cd36f84d0d02359ce635eb11b8472
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/irelic.h
rodriguescr/libfastlib
b89172ae727cd36f84d0d02359ce635eb11b8472
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/irelic.h
rodriguescr/libfastlib
b89172ae727cd36f84d0d02359ce635eb11b8472
[ "BSD-3-Clause-LBNL" ]
null
null
null
//File: $Id$ // Author: John Wu <John.Wu at ACM.org> // Lawrence Berkeley National Laboratory // Copyright (c) 2000-2017 the Regents of the University of California #ifndef IBIS_IRELIC_H #define IBIS_IRELIC_H ///@file /// Define ibis::relic and its derived classes ///@verbatim /// relic -> skive, fade, bylt (pack), zona (zone), fuzz /// fade -> sbiad, sapid ///@endverbatim /// #if defined(_WIN32) && defined(_MSC_VER) #pragma warning(disable:4786) // some identifier longer than 256 characters #endif #include "index.h" /// The basic bitmap index. It generates one bitmap for each distinct /// value. class ibis::relic : public ibis::index { public: virtual ~relic() {clear();}; relic(const relic&); relic(const ibis::column* c, const char* f = 0); relic(const ibis::column* c, uint32_t popu, uint32_t ntpl=0); relic(const ibis::column* c, uint32_t card, array_t<uint32_t>& ints); relic(const ibis::column* c, ibis::fileManager::storage* st, size_t start = 8); relic(const ibis::column* c, uint32_t nb, double *keys, int64_t *offs); relic(const ibis::column* c, uint32_t nb, double *keys, int64_t *offs, uint32_t *bms); relic(const ibis::column* c, uint32_t nb, double *keys, int64_t *offs, void *bms, FastBitReadBitmaps rd); virtual index* dup() const; virtual void print(std::ostream& out) const; virtual void serialSizes(uint64_t&, uint64_t&, uint64_t&) const; virtual int write(ibis::array_t<double> &, ibis::array_t<int64_t> &, ibis::array_t<uint32_t> &) const; virtual int write(const char* dt) const; virtual int read(const char* idxfile); virtual int read(ibis::fileManager::storage* st); virtual long append(const char* dt, const char* df, uint32_t nnew); virtual long select(const ibis::qContinuousRange&, void*) const; virtual long select(const ibis::qContinuousRange&, void*, ibis::bitvector&) const; using ibis::index::estimate; using ibis::index::estimateCost; virtual long evaluate(const ibis::qContinuousRange& expr, ibis::bitvector& hits) const; virtual long evaluate(const ibis::qDiscreteRange& expr, ibis::bitvector& hits) const; virtual void estimate(const ibis::qContinuousRange& expr, ibis::bitvector& lower, ibis::bitvector& upper) const { (void) evaluate(expr, lower); upper.clear(); } virtual uint32_t estimate(const ibis::qContinuousRange& expr) const; /// This class and its derived classes should produce exact answers, /// therefore no undecidable rows. virtual float undecidable(const ibis::qContinuousRange &, ibis::bitvector &iffy) const { iffy.clear(); return 0.0; } virtual void estimate(const ibis::qDiscreteRange& expr, ibis::bitvector& lower, ibis::bitvector& upper) const { evaluate(expr, lower); upper.clear(); } virtual uint32_t estimate(const ibis::qDiscreteRange&) const; virtual float undecidable(const ibis::qDiscreteRange&, ibis::bitvector& iffy) const { iffy.clear(); return 0.0; } virtual double estimateCost(const ibis::qContinuousRange& expr) const; virtual double estimateCost(const ibis::qDiscreteRange& expr) const; /// Estimate the pairs for the range join operator. Only records that /// are masked are evaluated. virtual void estimate(const ibis::relic& idx2, const ibis::deprecatedJoin& expr, const ibis::bitvector& mask, ibis::bitvector64& lower, ibis::bitvector64& upper) const; virtual void estimate(const ibis::relic& idx2, const ibis::deprecatedJoin& expr, const ibis::bitvector& mask, const ibis::qRange* const range1, const ibis::qRange* const range2, ibis::bitvector64& lower, ibis::bitvector64& upper) const; /// Estimate an upper bound for the number of pairs produced from /// marked records. virtual int64_t estimate(const ibis::relic& idx2, const ibis::deprecatedJoin& expr, const ibis::bitvector& mask) const; virtual int64_t estimate(const ibis::relic& idx2, const ibis::deprecatedJoin& expr, const ibis::bitvector& mask, const ibis::qRange* const range1, const ibis::qRange* const range2) const; virtual INDEX_TYPE type() const {return RELIC;} virtual const char* name() const {return "basic";} // bin boundaries and counts of each bin virtual void binBoundaries(std::vector<double>& b) const; virtual void binWeights(std::vector<uint32_t>& b) const; virtual long getCumulativeDistribution(std::vector<double>& bds, std::vector<uint32_t>& cts) const; virtual long getDistribution(std::vector<double>& bds, std::vector<uint32_t>& cts) const; virtual double getMin() const {return (vals.empty()?DBL_MAX:vals[0]);} virtual double getMax() const {return (vals.empty()?-DBL_MAX:vals.back());} virtual double getSum() const; virtual void speedTest(std::ostream& out) const; long append(const ibis::relic& tail); long append(const array_t<uint32_t>& ind); array_t<uint32_t>* keys(const ibis::bitvector& mask) const; /// A single value with known positions. template <typename T> struct valpos { /// The value. T val; /// The index set representing the positions with the given value. bitvector::indexSet ind; /// The current index value inside the index set. If the index set /// is a range, this is the actual position (RID), otherwise the /// positions()[j] holds the position (RID). bitvector::word_t j; /// Default constrtuctor. valpos<T>() : val(0), j(0) {} /// Specifying the values. valpos<T>(const T v, const bitvector& b) : val(v), ind(b.firstIndexSet()), j(0) { if (ind.nIndices() > 0 && ind.isRange()) j = *(ind.indices()); } /// Current position (RID). bitvector::word_t position() const { if (ind.isRange()) return j; else return ind.indices()[j]; } /// Move to the next row. void next() { ++ j; if (ind.isRange()) { if (j >= ind.indices()[1]) { ++ ind; if (ind.nIndices() > 0 && ind.isRange()) j = ind.indices()[0]; else j = 0; } } else if (j >= ind.nIndices()) { ++ ind; if (ind.nIndices() > 0 && ind.isRange()) j = ind.indices()[0]; else j = 0; } } }; // valpos /// The comparator used to build a min-heap based on positions. template<typename T> struct comparevalpos { bool operator()(const valpos<T>* x, const valpos<T>* y) { return (x->position() > y->position()); } }; // comparevalpos void construct(const char* f = 0); template <typename E> void construct(const array_t<E>& arr); void locate(const ibis::qContinuousRange& expr, uint32_t& hit0, uint32_t& hit1) const; protected: // protected member variables array_t<double> vals; // protected member functions int write32(int fdes) const; int write64(int fdes) const; uint32_t locate(const double& val) const; // a dummy constructor relic() : ibis::index() {} // free current resources, re-initialized all member variables virtual void clear(); virtual double computeSum() const; virtual size_t getSerialSize() const throw(); long mergeValues(uint32_t, uint32_t, void*) const; template <typename T> static long mergeValuesT(const array_t<T>& vs, const array_t<const bitvector*>& ps, array_t<T>& res); template <typename T> struct mappedValues; private: // private member functions int64_t equiJoin(const ibis::relic& idx2, const ibis::bitvector& mask, ibis::bitvector64& hits) const; int64_t deprecatedJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const double& delta, ibis::bitvector64& hits) const; int64_t compJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const ibis::math::term& delta, ibis::bitvector64& hits) const; int64_t equiJoin(const ibis::relic& idx2, const ibis::bitvector& mask) const; int64_t deprecatedJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const double& delta) const; int64_t compJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const ibis::math::term& delta) const; int64_t equiJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const ibis::qRange* const range1, const ibis::qRange* const range2, ibis::bitvector64& hits) const; int64_t deprecatedJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const ibis::qRange* const range1, const ibis::qRange* const range2, const double& delta, ibis::bitvector64& hits) const; /// Can not make good use of range restrictions when the distance /// function in the join expression is an arbitrary function. int64_t compJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const ibis::qRange* const range1, const ibis::qRange* const range2, const ibis::math::term& delta, ibis::bitvector64& hits) const { return compJoin(idx2, mask, delta, hits); } int64_t equiJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const ibis::qRange* const range1, const ibis::qRange* const range2) const; int64_t deprecatedJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const ibis::qRange* const range1, const ibis::qRange* const range2, const double& delta) const; /// Can not make good use of range restrictions when the distance /// function in the join expression is an arbitrary function. int64_t compJoin(const ibis::relic& idx2, const ibis::bitvector& mask, const ibis::qRange* const range1, const ibis::qRange* const range2, const ibis::math::term& delta) const { return compJoin(idx2, mask, delta); } relic& operator=(const relic&); }; // ibis::relic /// The binary encoded index with recoding of keyvalues. /// /// @note The work skive is the Danish for slice. This is a weired version /// of the bit-sliced index because it encodes the keyvalues to be between /// 0 and cnts.size()-1. The alternative version ibis::slice will use bit /// slices more strictly. class ibis::skive : public ibis::relic { public: virtual ~skive(); skive(const ibis::column* c = 0, const char* f = 0); skive(const ibis::column* c, ibis::fileManager::storage* st, size_t start = 8); virtual int write(const char* dt) const; virtual void print(std::ostream& out) const; virtual int read(const char* idxfile); virtual int read(ibis::fileManager::storage* st); virtual long append(const char* dt, const char* df, uint32_t nnew); virtual long select(const ibis::qContinuousRange&, void*) const { return -1;} virtual long select(const ibis::qContinuousRange&, void*, ibis::bitvector&) const { return -1;} using ibis::relic::estimate; using ibis::relic::estimateCost; virtual long evaluate(const ibis::qContinuousRange& expr, ibis::bitvector& hits) const; virtual long evaluate(const ibis::qDiscreteRange& expr, ibis::bitvector& hits) const; virtual void estimate(const ibis::qContinuousRange& expr, ibis::bitvector& lower, ibis::bitvector& upper) const; virtual uint32_t estimate(const ibis::qContinuousRange& expr) const; virtual INDEX_TYPE type() const {return SKIVE;} virtual const char* name() const {return "binary-encoded";} // number of records in each bin virtual void binWeights(std::vector<uint32_t>& b) const; virtual double getSum() const; virtual void speedTest(std::ostream& out) const; virtual double estimateCost(const ibis::qContinuousRange&) const { double ret; if (offset64.size() > bits.size()) ret = offset64.back(); else if (offset32.size() > bits.size()) ret = offset32.back(); else ret = 0.0; return ret; } virtual double estimateCost(const ibis::qDiscreteRange& expr) const { double ret; if (offset64.size() > bits.size()) ret = offset64.back(); else if (offset32.size() > bits.size()) ret = offset32.back(); else ret = 0.0; return ret; } protected: virtual void clear(); virtual size_t getSerialSize() const throw(); array_t<uint32_t> cnts; // the counts for each distinct value int write32(int fdes) const; int write64(int fdes) const; void evalGE(ibis::bitvector& res, uint32_t b) const; void evalEQ(ibis::bitvector& res, uint32_t b) const; private: skive(const skive&); skive& operator=(const skive&); // private member functions void construct1(const char* f = 0); // uses more temporary storage void construct2(const char* f = 0); // passes through data twice void setBit(const uint32_t i, const double val); }; // ibis::skive /// The bit-sliced index. This version strictly slices the binary bits of /// the incoming values. It also supports operations on bit slices. class ibis::slice : public ibis::skive { public: virtual ~slice(); slice(const ibis::column* c = 0, const char* f = 0); slice(const ibis::column* c, ibis::fileManager::storage* st, size_t start = 8); virtual INDEX_TYPE type() const {return SLICE;} virtual const char* name() const {return "bit-slice";} virtual int write(const char* dt) const; virtual void print(std::ostream& out) const; virtual long append(const char* dt, const char* df, uint32_t nnew); static bool isSuitable(const column&, const char*); private: slice(const slice&); slice& operator=(const slice&); // private member functions int construct(const char* f = 0); // passes through data twice template <typename T> int constructT(const char*); }; // ibis::slice /// The multicomponent range-encoded index. Defined by Chan and Ioannidis /// (SIGMOD 98). class ibis::fade : public ibis::relic { public: virtual ~fade() {clear();}; fade(const ibis::column* c = 0, const char* f = 0, const uint32_t nbase = 2); fade(const ibis::column* c, ibis::fileManager::storage* st, size_t start = 8); virtual int write(const char* dt) const; virtual void print(std::ostream& out) const; virtual int read(const char* idxfile); virtual int read(ibis::fileManager::storage* st); virtual long append(const char* dt, const char* df, uint32_t nnew); virtual long select(const ibis::qContinuousRange&, void*) const { return -1;} virtual long select(const ibis::qContinuousRange&, void*, ibis::bitvector&) const { return -1;} using ibis::relic::estimate; using ibis::relic::estimateCost; virtual long evaluate(const ibis::qContinuousRange& expr, ibis::bitvector& hits) const; virtual long evaluate(const ibis::qDiscreteRange& expr, ibis::bitvector& hits) const; virtual uint32_t estimate(const ibis::qContinuousRange& expr) const; virtual INDEX_TYPE type() const {return FADE;} virtual const char* name() const {return "multi-level range";} virtual void speedTest(std::ostream& out) const; // number of records in each bin virtual void binWeights(std::vector<uint32_t>& b) const; virtual double getSum() const; virtual double estimateCost(const ibis::qContinuousRange& expr) const; //virtual double estimateCost(const ibis::qDiscreteRange& expr) const; protected: // protected member variables array_t<uint32_t> cnts; // the counts for each distinct value array_t<uint32_t> bases;// the values of the bases used // protected member functions to be used by derived classes int write32(int fdes) const; int write64(int fdes) const; virtual void clear(); virtual size_t getSerialSize() const throw(); private: // private member functions void setBit(const uint32_t i, const double val); void construct1(const char* f = 0, const uint32_t nbase = 2); void construct2(const char* f = 0, const uint32_t nbase = 2); void evalEQ(ibis::bitvector& res, uint32_t b) const; void evalLE(ibis::bitvector& res, uint32_t b) const; void evalLL(ibis::bitvector& res, uint32_t b0, uint32_t b1) const; fade(const fade&); fade& operator=(const fade&); }; // ibis::fade /// The multicomponent interval encoded index. Defined by Chan and /// Ioannidis (SIGMOD 99). class ibis::sbiad : public ibis::fade { public: virtual ~sbiad() {clear();}; sbiad(const ibis::column* c = 0, const char* f = 0, const uint32_t nbase = 2); sbiad(const ibis::column* c, ibis::fileManager::storage* st, size_t start = 8); virtual int write(const char* dt) const; virtual void print(std::ostream& out) const; virtual long append(const char* dt, const char* df, uint32_t nnew); virtual long evaluate(const ibis::qContinuousRange& expr, ibis::bitvector& hits) const; virtual long evaluate(const ibis::qDiscreteRange& expr, ibis::bitvector& hits) const; virtual INDEX_TYPE type() const {return SBIAD;} virtual const char* name() const {return "multi-level interval";} virtual void speedTest(std::ostream& out) const; //virtual double estimateCost(const ibis::qContinuousRange& expr) const; //virtual double estimateCost(const ibis::qDiscreteRange& expr) const; private: // private member functions void setBit(const uint32_t i, const double val); void construct1(const char* f = 0, const uint32_t nbase = 2); void construct2(const char* f = 0, const uint32_t nbase = 2); void evalEQ(ibis::bitvector& res, uint32_t b) const; void evalLE(ibis::bitvector& res, uint32_t b) const; void evalLL(ibis::bitvector& res, uint32_t b0, uint32_t b1) const; sbiad(const sbiad&); sbiad& operator=(const sbiad&); }; // ibis::sbiad /// The multicomponent equality encoded index. class ibis::sapid : public ibis::fade { public: virtual ~sapid() {clear();}; sapid(const ibis::column* c = 0, const char* f = 0, const uint32_t nbase = 2); sapid(const ibis::column* c, ibis::fileManager::storage* st, size_t start = 8); virtual int write(const char* dt) const; virtual void print(std::ostream& out) const; virtual long append(const char* dt, const char* df, uint32_t nnew); virtual long evaluate(const ibis::qContinuousRange& expr, ibis::bitvector& hits) const; virtual long evaluate(const ibis::qDiscreteRange& expr, ibis::bitvector& hits) const; virtual INDEX_TYPE type() const {return SAPID;} virtual const char* name() const {return "multi-level equality";} virtual void speedTest(std::ostream& out) const; //virtual double estimateCost(const ibis::qContinuousRange& expr) const; //virtual double estimateCost(const ibis::qDiscreteRange& expr) const; private: // private member functions void setBit(const uint32_t i, const double val); void construct1(const char* f = 0, const uint32_t nbase = 2); void construct2(const char* f = 0, const uint32_t nbase = 2); void addBits_(uint32_t ib, uint32_t ie, ibis::bitvector& res) const; void evalEQ(ibis::bitvector& res, uint32_t b) const; void evalLE(ibis::bitvector& res, uint32_t b) const; void evalLL(ibis::bitvector& res, uint32_t b0, uint32_t b1) const; sapid(const sapid&); sapid& operator=(const sapid&); }; // ibis::sapid /// The precise version of two-level interval-equality index. /// /// @note In fuzzy classification / clustering, many interval equality /// conditions are used. Hence the crazy name. class ibis::fuzz : public ibis::relic { public: virtual ~fuzz() {clear();}; fuzz(const ibis::column* c = 0, const char* f = 0); fuzz(const ibis::column* c, ibis::fileManager::storage* st, size_t start = 8); virtual int write(const char* dt) const; virtual void print(std::ostream& out) const; virtual int read(const char* idxfile); virtual int read(ibis::fileManager::storage* st); virtual long append(const char* dt, const char* df, uint32_t nnew); using ibis::relic::evaluate; using ibis::relic::estimate; using ibis::relic::estimateCost; virtual long evaluate(const ibis::qContinuousRange& expr, ibis::bitvector& hits) const; virtual uint32_t estimate(const ibis::qContinuousRange& expr) const; virtual double estimateCost(const ibis::qContinuousRange& expr) const; virtual INDEX_TYPE type() const {return FUZZ;} virtual const char* name() const {return "interval-equality";} protected: virtual void clear(); virtual size_t getSerialSize() const throw(); private: /// The fine level is stored in ibis::relic, the parent class, only /// the coarse bins are stored here. The coarse bins use integer bin /// boundaries; these integers are indices to the array vals and bits. mutable array_t<bitvector*> cbits; array_t<uint32_t> cbounds; mutable array_t<int32_t> coffset32; mutable array_t<int64_t> coffset64; void coarsen(); // given fine level, add coarse level void activateCoarse() const; // activate all coarse level bitmaps void activateCoarse(uint32_t i) const; // activate one bitmap void activateCoarse(uint32_t i, uint32_t j) const; int writeCoarse32(int fdes) const; int writeCoarse64(int fdes) const; int readCoarse(const char *fn); void clearCoarse(); /// Estimate the cost of answer a range query [lo, hi). long coarseEstimate(uint32_t lo, uint32_t hi) const; /// Evaluate the range condition [lo, hi) and place the result in @c res. long coarseEvaluate(uint32_t lo, uint32_t hi, ibis::bitvector& res) const; fuzz(const fuzz&); fuzz& operator=(const fuzz&); }; // ibis::fuzz /// The precise version of the two-level range-equality index. /// /// @note Bylt is Danish word for pack, the name of the binned version of /// the two-level range-equality code. class ibis::bylt : public ibis::relic { public: virtual ~bylt() {clear();}; bylt(const ibis::column* c = 0, const char* f = 0); bylt(const ibis::column* c, ibis::fileManager::storage* st, size_t start = 8); virtual int write(const char* dt) const; virtual void print(std::ostream& out) const; virtual int read(const char* idxfile); virtual int read(ibis::fileManager::storage* st); virtual long append(const char* dt, const char* df, uint32_t nnew); using ibis::relic::evaluate; using ibis::relic::estimate; using ibis::relic::estimateCost; virtual long evaluate(const ibis::qContinuousRange& expr, ibis::bitvector& hits) const; virtual uint32_t estimate(const ibis::qContinuousRange& expr) const; virtual double estimateCost(const ibis::qContinuousRange& expr) const; virtual INDEX_TYPE type() const {return BYLT;} virtual const char* name() const {return "range-equality";} protected: virtual void clear(); virtual size_t getSerialSize() const throw(); private: // the fine level is stored in ibis::relic, the parent class, only the // coarse bins are stored here. The coarse bins use integer bin // boundaries; these integers are indices to the array vals and bits. mutable array_t<bitvector*> cbits; array_t<uint32_t> cbounds; mutable array_t<int32_t> coffset32; mutable array_t<int64_t> coffset64; void coarsen(); // given fine level, add coarse level void activateCoarse() const; // activate all coarse level bitmaps void activateCoarse(uint32_t i) const; // activate one bitmap void activateCoarse(uint32_t i, uint32_t j) const; int writeCoarse32(int fdes) const; int writeCoarse64(int fdes) const; int readCoarse(const char *fn); bylt(const bylt&); bylt& operator=(const bylt&); }; // ibis::bylt /// The precise version of the two-level equality-equality index. /// /// @note Zona is Italian word for zone, the name of the binned version of /// the two-level equality-equality code. class ibis::zona : public ibis::relic { public: virtual ~zona() {clear();}; zona(const ibis::column* c = 0, const char* f = 0); zona(const ibis::column* c, ibis::fileManager::storage* st, size_t start = 8); virtual int write(const char* dt) const; virtual void print(std::ostream& out) const; virtual int read(const char* idxfile); virtual int read(ibis::fileManager::storage* st); virtual long append(const char* dt, const char* df, uint32_t nnew); using ibis::relic::evaluate; using ibis::relic::estimate; using ibis::relic::estimateCost; virtual long evaluate(const ibis::qContinuousRange& expr, ibis::bitvector& hits) const; virtual uint32_t estimate(const ibis::qContinuousRange& expr) const; virtual double estimateCost(const ibis::qContinuousRange& expr) const; virtual INDEX_TYPE type() const {return ZONA;} virtual const char* name() const {return "equality-equality";} protected: virtual void clear(); virtual size_t getSerialSize() const throw(); private: // the fine level is stored in ibis::relic, the parent class, only the // coarse bins are stored here. The coarse bins use integer bin // boundaries; these integers are indices to the array vals and bits. mutable array_t<bitvector*> cbits; array_t<uint32_t> cbounds; mutable array_t<int32_t> coffset32; mutable array_t<int64_t> coffset64; void coarsen(); // given fine level, add coarse level void activateCoarse() const; // activate all coarse level bitmaps void activateCoarse(uint32_t i) const; // activate one bitmap void activateCoarse(uint32_t i, uint32_t j) const; int writeCoarse32(int fdes) const; int writeCoarse64(int fdes) const; int readCoarse(const char *fn); zona(const zona&); zona& operator=(const zona&); }; // ibis::zona /// A struct to hold a set of values and their positions. The values are /// held in a heap according to their first positions. template <typename T> struct ibis::relic::mappedValues { }; // ibis::relic::mappedValues #endif // IBIS_IRELIC_H
36.539972
80
0.681611
[ "vector" ]
6483d33675db17dd83cdedae8328185d048b3cb9
3,469
c
C
tools/3gpp_vad/src/g_code.c
xiangxyq/kaldi_rt_decoder
9f4006e2ffb0d69edc111fda2f1bedc2e3969d44
[ "Apache-2.0" ]
5
2021-09-03T02:16:00.000Z
2022-02-22T12:06:58.000Z
tools/3gpp_vad/src/g_code.c
xiangxyq/kaldi_rt_decoder
9f4006e2ffb0d69edc111fda2f1bedc2e3969d44
[ "Apache-2.0" ]
1
2022-02-25T06:26:35.000Z
2022-02-25T06:26:35.000Z
tools/3gpp_vad/src/g_code.c
xiangxyq/kaldi_rt_decoder
9f4006e2ffb0d69edc111fda2f1bedc2e3969d44
[ "Apache-2.0" ]
5
2021-09-08T03:42:25.000Z
2022-01-27T08:05:50.000Z
/* ******************************************************************************** * * GSM AMR-NB speech codec R98 Version 7.6.0 December 12, 2001 * R99 Version 3.3.0 * REL-4 Version 4.1.0 * ******************************************************************************** * * File : g_code.c * Purpose : Compute the innovative codebook gain. * ******************************************************************************** */ /* ******************************************************************************** * MODULE INCLUDE FILE AND VERSION ID ******************************************************************************** */ #include "g_code.h" const char g_code_id[] = "@(#)$Id $" g_code_h; /* ******************************************************************************** * INCLUDE FILES ******************************************************************************** */ #include "typedef.h" #include "basic_op.h" #include "count.h" #include "cnst.h" /* ******************************************************************************** * LOCAL VARIABLES AND TABLES ******************************************************************************** */ /* ******************************************************************************** * PUBLIC PROGRAM CODE ******************************************************************************** */ /************************************************************************* * * FUNCTION: G_code * * PURPOSE: Compute the innovative codebook gain. * * DESCRIPTION: * The innovative codebook gain is given by * * g = <x[], y[]> / <y[], y[]> * * where x[] is the target vector, y[] is the filtered innovative * codevector, and <> denotes dot product. * *************************************************************************/ Word16 G_code ( /* out : Gain of innovation code */ Word16 xn2[], /* in : target vector */ Word16 y2[] /* in : filtered innovation vector */ ) { Word16 i; Word16 xy, yy, exp_xy, exp_yy, gain; Word16 scal_y2[L_SUBFR]; Word32 s; /* Scale down Y[] by 2 to avoid overflow */ for (i = 0; i < L_SUBFR; i++) { scal_y2[i] = shr (y2[i], 1); move16 (); } /* Compute scalar product <X[],Y[]> */ s = 1L; move32 (); /* Avoid case of all zeros */ for (i = 0; i < L_SUBFR; i++) { s = L_mac (s, xn2[i], scal_y2[i]); } exp_xy = norm_l (s); xy = extract_h (L_shl (s, exp_xy)); /* If (xy < 0) gain = 0 */ test (); if (xy <= 0) return ((Word16) 0); /* Compute scalar product <Y[],Y[]> */ s = 0L; move32 (); for (i = 0; i < L_SUBFR; i++) { s = L_mac (s, scal_y2[i], scal_y2[i]); } exp_yy = norm_l (s); yy = extract_h (L_shl (s, exp_yy)); /* compute gain = xy/yy */ xy = shr (xy, 1); /* Be sure xy < yy */ gain = div_s (xy, yy); /* Denormalization of division */ i = add (exp_xy, 5); /* 15-1+9-18 = 5 */ i = sub (i, exp_yy); gain = shl (shr (gain, i), 1); /* Q0 -> Q1 */ return (gain); }
30.165217
80
0.311905
[ "vector" ]
64872c51eb6a7ed1aae40c154ff6ede7cbfda5a4
4,551
h
C
starter-stack/Lib/rcsc/coach/coach_audio_sensor.h
InsperDynamics/Soccer-Simulation-2D
a548d576ca4ab2a8f797810f5e23875c45cef73f
[ "Apache-2.0" ]
null
null
null
starter-stack/Lib/rcsc/coach/coach_audio_sensor.h
InsperDynamics/Soccer-Simulation-2D
a548d576ca4ab2a8f797810f5e23875c45cef73f
[ "Apache-2.0" ]
null
null
null
starter-stack/Lib/rcsc/coach/coach_audio_sensor.h
InsperDynamics/Soccer-Simulation-2D
a548d576ca4ab2a8f797810f5e23875c45cef73f
[ "Apache-2.0" ]
null
null
null
// -*-c++-*- /*! \file coach_audio_sensor.h \brief audio message analyzer for coach Header File */ /* *Copyright: Copyright (C) Hidehisa Akiyama This code 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 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *EndCopyright: */ ///////////////////////////////////////////////////////////////////// #ifndef RCSC_COACH_COACH_AUDIO_SENSOR_H #define RCSC_COACH_COACH_AUDIO_SENSOR_H #include <rcsc/common/audio_message.h> #include <rcsc/game_time.h> #include <rcsc/types.h> #include <rcsc/geom/vector_2d.h> #include <boost/shared_ptr.hpp> #include <string> #include <map> #include <list> namespace rcsc { class SayMessageParser; /*-------------------------------------------------------------------*/ /*! \class CoachAudioSensor \brief players' communication message handler class */ class CoachAudioSensor { private: //! typedef of the say message parser container typedef std::map< char, boost::shared_ptr< SayMessageParser > > ParserMap; //! my team name std::string M_team_name; //! teammate message parsers ParserMap M_say_message_parsers; //! last time that teammate message is heard GameTime M_teammate_message_time; //! last heard message data from teammate players std::list< HearMessage > M_teammate_messages; //! last time that teammate message is heard GameTime M_opponent_message_time; //! last heard message data from opponent players std::list< HearMessage > M_opponent_messages; //! last time when freeform message form trainer is heard GameTime M_trainer_message_time; //! last received aural message from trainer std::string M_trainer_message; public: /*! \brief init member variables by default value */ CoachAudioSensor(); /*! \brief set our team name \param team_name team name string */ void setTeamName( const std::string & team_name ); /*! \brief add new player message parer. \param parser shared_ptr of player message parser instance */ void addParser( boost::shared_ptr< SayMessageParser > parser ); /*! \brief remove registered parser object \param header say message header character */ void removeParser( const char header ); /*! \brief analyze other player's audio message \param msg raw server message \param current game time when message is received */ void parsePlayerMessage( const char * msg, const GameTime & current ); /*! \brief analyze trainer's audio message \param msg raw server message \param current game time when message is received */ void parseTrainerMessage( const char * msg, const GameTime & current ); /*! \brief get time when teammate message is received \return const referncd to the game time */ const GameTime & teammateMessageTime() const { return M_teammate_message_time; } /*! \brief get the last received teammate messages \return const reference to the message object container */ const std::list< HearMessage > & teammateMessages() const { return M_teammate_messages; } /*! \brief get the time when last freeform message is received \return game time variable */ const GameTime & trainerMessageTime() const { return M_trainer_message_time; } /*! \brief get the last received trainer message info \return const reference to the message object instance */ const std::string & trainerMessage() const { return M_trainer_message; } private: /* \brief analyze message from teammate \param message message object from teammate */ void parseTeammateMessage( const HearMessage & message ); }; } #endif
25.567416
78
0.657658
[ "object" ]
648d5a6b387de9f16d9ef9b86780ec491b31434f
715
h
C
src/random_projection.h
mlverse/cuda.ml
54fc9575e271b6a94c8650bea1887bb7ffa2b333
[ "MIT" ]
12
2021-10-05T15:34:55.000Z
2021-12-28T14:50:44.000Z
src/random_projection.h
mlverse/cuml4r
54fc9575e271b6a94c8650bea1887bb7ffa2b333
[ "MIT" ]
39
2021-07-12T13:12:52.000Z
2021-08-24T14:18:05.000Z
src/random_projection.h
mlverse/cuda.ml
54fc9575e271b6a94c8650bea1887bb7ffa2b333
[ "MIT" ]
1
2021-11-06T02:28:04.000Z
2021-11-06T02:28:04.000Z
#pragma once #include <Rcpp.h> #ifdef HAS_CUML namespace cuml4r { size_t rproj_johnson_lindenstrauss_min_dim(size_t const n_samples, double const eps); SEXP rproj_fit(int const n_samples, int const n_features, int const n_components, double const eps, bool const gaussian_method, double const density, int const random_state); Rcpp::NumericMatrix rproj_transform(SEXP rproj_ctx_xptr, Rcpp::NumericMatrix const& input); Rcpp::List rproj_get_state(SEXP model); SEXP rproj_set_state(Rcpp::List const& model_state); } // namespace cuml4r #else #include "warn_cuml_missing.h" #endif
23.064516
70
0.657343
[ "model" ]
648dff87ab9b07df170464b2fba9026053e78a2d
4,038
h
C
rlclientlib/serialization/json_serializer.h
orenmichaely/reinforcement_learning
1a1570641255fdcd03a33996986aa58f3c0c58e2
[ "MIT" ]
null
null
null
rlclientlib/serialization/json_serializer.h
orenmichaely/reinforcement_learning
1a1570641255fdcd03a33996986aa58f3c0c58e2
[ "MIT" ]
null
null
null
rlclientlib/serialization/json_serializer.h
orenmichaely/reinforcement_learning
1a1570641255fdcd03a33996986aa58f3c0c58e2
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "ranking_event.h" #include "data_buffer.h" #include "logger/message_type.h" #include "api_status.h" #include "utility/data_buffer_streambuf.h" #include "utility/config_helper.h" namespace reinforcement_learning { namespace logger { template<typename T> struct json_event_serializer; template <> struct json_event_serializer<ranking_event> { static int serialize(ranking_event& evt, std::ostream& buffer, api_status* status) { // Add version and eventId buffer << R"({"Version":"1","EventId":")" << evt.get_event_id() << R"(")"; if (evt.get_defered_action()) { buffer << R"(,"DeferredAction":true)"; } // Add action ids buffer << R"(,"a":[)"; auto delimiter = ""; for (auto const& action_id : evt.get_action_ids()) { buffer << delimiter << action_id + 1; delimiter = ","; } // Add context const char* context = reinterpret_cast<const char*>(&(evt.get_context()[0])); //std::string context(evt.get_context().begin(), evt.get_context().end()) buffer << R"(],"c":)" << context << R"(,"p":[)"; // Add probabilities delimiter = ""; for (auto const& probability : evt.get_probabilities()) { buffer << delimiter << probability + 1; delimiter = ","; } //add model id buffer << R"(],"VWState":{"m":")" << evt.get_model_id() << R"("})"; if (evt.get_pass_prob() < 1) { buffer << R"(,"pdrop":)" << (1 - evt.get_pass_prob()); } buffer << R"(})"; return error_code::success; } }; template<> struct json_event_serializer<outcome_event> { static int serialize(outcome_event& evt, std::ostream& buffer, api_status* status) { switch (evt.get_outcome_type()) { case outcome_event::outcome_type_string: buffer << R"({"EventId":")" << evt.get_event_id() << R"(","v":)" << evt.get_outcome() << R"(})"; break; case outcome_event::outcome_type_numeric: buffer << R"({"EventId":")" << evt.get_event_id() << R"(","v":)" << evt.get_numeric_outcome() << R"(})"; break; case outcome_event::outcome_type_action_taken: buffer << R"({"EventId":")" << evt.get_event_id() << R"(","ActionTaken":true})"; break; default: { RETURN_ERROR(nullptr, status, serialize_unknown_outcome_type); } } return error_code::success; } }; template <typename event_t> struct json_collection_serializer { using serializer_t = json_event_serializer<event_t>; using buffer_t = utility::data_buffer; using streambuf_t = utility::data_buffer_streambuf; using shared_state_t = int; static int message_id() { return 0; } json_collection_serializer(buffer_t& buffer, const char* content_encoding) : _buffer(buffer), _streambuf{&_buffer}, _ostream{&_streambuf} { _ostream << std::unitbuf; } json_collection_serializer(buffer_t& buffer, const char* content_encoding, int /*dummy*/) : json_collection_serializer(buffer, content_encoding) {} int add(event_t& evt, api_status* status=nullptr) { RETURN_IF_FAIL(serializer_t::serialize(evt, _ostream, status)); _ostream << "\n"; return error_code::success; } uint64_t size() const { return _buffer.body_filled_size(); } void reset() { _buffer.reset(); } int finalize(api_status* status) { _streambuf.finalize(); return error_code::success; } int finalize(api_status* status, uint64_t original_event_count) { return finalize(status); } buffer_t& _buffer; streambuf_t _streambuf; std::ostream _ostream; }; template<> inline int json_collection_serializer<outcome_event>::message_id() { return message_type::json_outcome_event_collection; } template<> inline int json_collection_serializer<ranking_event>::message_id() { return message_type::json_ranking_event_collection; } }}
30.360902
151
0.626795
[ "vector", "model" ]
649deba7d954056890936e5ec18d99d141bdbad6
11,407
h
C
FEMLib/FEInterface.h
febiosoftware/FEBioStudio
324d76b069a60e99328500b9b25eb79cf5a019e8
[ "MIT" ]
27
2020-06-25T06:34:52.000Z
2022-03-11T08:58:57.000Z
FEMLib/FEInterface.h
febiosoftware/FEBioStudio
324d76b069a60e99328500b9b25eb79cf5a019e8
[ "MIT" ]
42
2020-06-15T18:40:57.000Z
2022-03-24T05:38:54.000Z
FEMLib/FEInterface.h
febiosoftware/FEBioStudio
324d76b069a60e99328500b9b25eb79cf5a019e8
[ "MIT" ]
12
2020-06-27T13:58:57.000Z
2022-03-24T05:39:10.000Z
#pragma once #include "FEStepComponent.h" #include "MeshTools/FEItemListBuilder.h" #include "MeshTools/GMaterial.h" #include <list> //using namespace std; using std::list; //----------------------------------------------------------------------------- // Base class for contact interfaces class FEInterface : public FEStepComponent { public: FEInterface(int ntype, FEModel* ps, int nstep); virtual ~FEInterface(); int Type() { return m_ntype; } protected: void SaveList(FEItemListBuilder* pitem, OArchive& ar); FEItemListBuilder* LoadList(IArchive& ar); protected: FEModel* m_ps; int m_ntype; }; //----------------------------------------------------------------------------- //! This class is the base class for interfaces that only require one //! surface definition (e.g. rigid interface, rigid wall interface) class FESoloInterface : public FEInterface { public: FESoloInterface(int ntype, FEModel* ps, int nstep); ~FESoloInterface(); FEItemListBuilder* GetItemList() { return m_pItem; } void SetItemList(FEItemListBuilder* pi) { m_pItem = pi; } void Save(OArchive& ar); void Load(IArchive& ar); protected: FEItemListBuilder* m_pItem; // list of items that define interface }; //----------------------------------------------------------------------------- //! This class is the base class for interfaces that require two surfaces //! class FEPairedInterface : public FEInterface { public: FEPairedInterface(int ntype, FEModel* ps, int nstep); ~FEPairedInterface(); void SetPrimarySurface(FEItemListBuilder* pg) { m_surf1 = pg; } void SetSecondarySurface(FEItemListBuilder* pg) { m_surf2 = pg; } FEItemListBuilder* GetPrimarySurface() { return m_surf1; } FEItemListBuilder* GetSecondarySurface() { return m_surf2; } FEItemListBuilder* GetItemList(int index) { return (index == 0 ? GetPrimarySurface() : GetSecondarySurface()); } void SetItemList(int index, FEItemListBuilder* itemList) { (index == 0 ? SetPrimarySurface(itemList) : SetSecondarySurface(itemList)); } void SwapPrimarySecondary(); void Save(OArchive& ar); void Load(IArchive& ar); public: FEItemListBuilder* m_surf1; // primary surface item list FEItemListBuilder* m_surf2; // secondary syurface item list }; //----------------------------------------------------------------------------- // This class implements the rigid node and facets interface // class FERigidInterface : public FESoloInterface { public: FERigidInterface(FEModel* ps, int nstep = 0); FERigidInterface(FEModel* ps, GMaterial* pm, FEItemListBuilder* pi, int nstep = 0); GMaterial* GetRigidBody() { return m_pmat; } void SetRigidBody(GMaterial* pm) { m_pmat = pm; } void Save(OArchive& ar); void Load(IArchive& ar); protected: GMaterial* m_pmat; // pointer to rigid material }; //----------------------------------------------------------------------------- // This class implements the rigid wall interface // class FERigidWallInterface : public FESoloInterface { public: enum { LAUGON, ALTOL, PENALTY, PA, PB, PC, PD, OFFSET }; public: FERigidWallInterface(FEModel* ps, int nstep = 0); ~FERigidWallInterface(){} FELoadCurve* GetLoadCurve() { return GetParamLC(OFFSET); } void GetPlaneEquation(double a[4]); }; //----------------------------------------------------------------------------- // This class implements the rigid sphere contact interface // class FERigidSphereInterface : public FESoloInterface { public: enum { LAUGON, ALTOL, PENALTY, RADIUS, CENTER, UX, UY, UZ}; public: FERigidSphereInterface(FEModel* ps, int nstep = 0); ~FERigidSphereInterface(){} FELoadCurve* GetLoadCurve(int i); double Radius(); vec3d Center(); }; //----------------------------------------------------------------------------- // This class implements the sliding contact interface // NOTE: This class is now obsolete. It was deprecated since it does not map nicely to an FEBio contact interface // It was replaced by the FESlidingWithGapsInterface and FEFacetOnFacetInterface. class FESlidingInterface : public FEPairedInterface { public: enum {LAUGON, ALTOL, PENALTY, TWOPASS, AUTOPEN, MU, EPSF, STOL, NTYPE, MINAUG, MAXAUG, GAPTOL, SEGUP }; public: FESlidingInterface(FEModel* ps, int nstep = 0); ~FESlidingInterface() {} }; //----------------------------------------------------------------------------- class FESlidingWithGapsInterface : public FEPairedInterface { public: enum { LAUGON, ALTOL, PENALTY, TWOPASS, AUTOPEN, MU, EPSF, STOL, MINAUG, MAXAUG, GAPTOL, SEGUP }; public: FESlidingWithGapsInterface(FEModel* ps, int nstep = 0); ~FESlidingWithGapsInterface() {} }; //----------------------------------------------------------------------------- class FEFacetOnFacetInterface : public FEPairedInterface { public: enum { LAUGON, ALTOL, PENALTY, TWOPASS, AUTOPEN, MU, EPSF, STOL, MINAUG, MAXAUG, GAPTOL, SEGUP, SEARCH_RADIUS }; public: FEFacetOnFacetInterface(FEModel* ps, int nstep = 0); ~FEFacetOnFacetInterface() {} }; //----------------------------------------------------------------------------- // This class implements the tied contact interface // class FETiedInterface : public FEPairedInterface { public: enum { LAUGON, ALTOL, PENALTY, MINAUG, MAXAUG }; public: FETiedInterface(FEModel* ps, int nstep = 0); ~FETiedInterface(){} }; //----------------------------------------------------------------------------- // This class implements the facet-on-facet tied contact interface // class FEF2FTiedInterface : public FEPairedInterface { public: enum { LAUGON, ALTOL, PENALTY, MINAUG, MAXAUG }; public: FEF2FTiedInterface(FEModel* ps, int nstep = 0); ~FEF2FTiedInterface(){} }; //----------------------------------------------------------------------------- // This class implements the sticky contact interface // class FEStickyInterface : public FEPairedInterface { public: enum { LAUGON, ALTOL, PENALTY, MINAUG, MAXAUG }; public: FEStickyInterface(FEModel* ps, int nstep = 0); ~FEStickyInterface(){} }; //----------------------------------------------------------------------------- // This class implements a periodic boundary constraint class FEPeriodicBoundary : public FEPairedInterface { public: enum { LAUGON, ALTOL, PENALTY, TWOPASS }; public: FEPeriodicBoundary(FEModel* ps, int nstep = 0); ~FEPeriodicBoundary(){} }; //----------------------------------------------------------------------------- // Biphasic-solid contact class FEPoroContact : public FEPairedInterface { public: enum {LAUGON, ALTOL, PENALTY, TWOPASS, AUTOPEN, PRESSPEN, SYMMETRIC, SEARCHRAD }; public: FEPoroContact(FEModel* ps, int nstep = 0); }; //----------------------------------------------------------------------------- class FEPoroSoluteContact : public FEPairedInterface { public: enum {LAUGON, ALTOL, PENALTY, TWOPASS, AUTOPEN, PRESSPEN, SYMMETRIC, CONCPEN, AMBPRESS, AMBCONC, SEARCHRAD }; public: FEPoroSoluteContact(FEModel* ps, int nstep = 0); }; //----------------------------------------------------------------------------- class FEMultiphasicContact : public FEPairedInterface { public: enum {LAUGON, ALTOL, PENALTY, TWOPASS, AUTOPEN, PRESSPEN, SYMMETRIC, CONCPEN, AMBPRESS, AMBCONC, SEARCHRAD }; public: FEMultiphasicContact(FEModel* ps, int nstep = 0); }; //----------------------------------------------------------------------------- class FETensionCompressionInterface : public FEPairedInterface { public: enum { LAUGON, ALTOL, GAPTOL, PENALTY, AUTOPEN, TWOPASS, SEARCHTOL, SYMMETRIC, SEARCHRAD, NSEGUP, BTENSION, MINAUG, MAXAUG, FRICCOEFF, AUGSMOOTH, BNODERELOC, BFLIPMASTER, BFLIPSLAVE, KNMULT }; public: FETensionCompressionInterface(FEModel* ps, int nstep = 0); }; //----------------------------------------------------------------------------- class FETiedBiphasicInterface : public FEPairedInterface { public: enum {LAUGON, ALTOL, GAPTOL, PTOL, PENALTY, AUTOPEN, TWOPASS, KNMULT, SEARCHTOL, PRS_PENALTY, SYMMETRIC, SEARCHRAD}; public: FETiedBiphasicInterface(FEModel* ps, int nstep = 0); }; //----------------------------------------------------------------------------- class FETiedMultiphasicInterface : public FEPairedInterface { public: enum { LAUGON, ALTOL, GAPTOL, PTOL, CTOL, PENALTY, AUTOPEN, TWOPASS, KNMULT, SEARCHTOL, PRS_PENALTY, SYMMETRIC, SEARCHRAD }; public: FETiedMultiphasicInterface(FEModel* ps, int nstep = 0); }; //----------------------------------------------------------------------------- class FETiedElasticInterface : public FEPairedInterface { public: enum { LAUGON, ALTOL, GAPTOL, PTOL, PENALTY, AUTOPEN, TWOPASS, KNMULT, SEARCHTOL, PRS_PENALTY, SYMMETRIC, SEARCHRAD }; public: FETiedElasticInterface(FEModel* ps, int nstep = 0); }; //----------------------------------------------------------------------------- class FEContactPotentialInterface : public FEPairedInterface { public: enum { KC, POWER, RIN, ROUT, WTOL }; public: FEContactPotentialInterface(FEModel* ps, int nstep = 0); }; //----------------------------------------------------------------------------- class FEGapHeatFluxInterface : public FEPairedInterface { public: FEGapHeatFluxInterface(FEModel* ps, int nstep = 0); }; //----------------------------------------------------------------------------- // This class implements a rigid joint // class FERigidJoint : public FEInterface { public: enum {TOL, PENALTY, RJ}; public: FERigidJoint(FEModel* ps, int nstep = 0); void Save(OArchive& ar); void Load(IArchive& ar); public: GMaterial* m_pbodyA; // rigid body a GMaterial* m_pbodyB; // rigid body b }; //----------------------------------------------------------------------------- // This class implements a spring-tied interface, that is, an interface // where the nodes of one surface are connected with springs to the other // surface. class FESpringTiedInterface : public FEPairedInterface { public: enum { ECONST }; public: FESpringTiedInterface(FEModel* ps, int nstep = 0); double SpringConstant() const; void BuildSpringList(vector<pair<int, int> >& L); }; //----------------------------------------------------------------------------- // This class implements a linear constraint // TODO: Figure out a way to integrate this class FELinearConstraintSet : public FSObject { public: // a linear constraint defined via LCDOFs class LinearConstraint { public: // linear constraint dof class DOF { public: DOF() { node = -1; bc = 0; s = 0.0; } public: int node; int bc; double s; }; public: LinearConstraint(){} LinearConstraint(const LinearConstraint& LC) { m_dof = LC.m_dof; } LinearConstraint& operator = (const LinearConstraint& LC) { m_dof = LC.m_dof; return (*this); } public: vector<DOF> m_dof; }; public: FELinearConstraintSet(); FELinearConstraintSet(const FELinearConstraintSet& lcs); FELinearConstraintSet& operator = (const FELinearConstraintSet& lcs); public: double m_atol; double m_penalty; int m_nmaxaug; public: vector<LinearConstraint> m_set; };
28.446384
138
0.58429
[ "vector", "solid" ]