repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
TwoFlyLiu/ecanspy3
ecanspy3/can/UsbCanUtil.h
<gh_stars>1-10 #pragma once #include "ECanVci.H" #include <QObject> /*! * \brief 设备类型,对于测试软件就是使用USBCAN了 */ #define USB_CAN_DEVICE_TYPE (USBCAN1) #define USB_CAN_DEVICE_INDEX (0) /*! * \brief 默认的VCI_CAN初始化设置 */ #define DEFAULT_VCI_INIT_CONFIG {0x00000000, 0xffffffff, 0, 0x00, 0, 0x1c, 0x00} /*! * \brief 辅助宏,当USB CAN没有被打开的时候,直接返回 */ #define USB_CAN_NOT_OPENED_RETURN() \ if(!UsbCanUtil::GetInstance().IsOpened()) { \ return; \ } /*! * \brief 辅助宏,当USB CAN没有被打开的时候,直接返回某个值 */ #define USB_CAN_NOT_OPENED_RETURN_VALUE(val) \ if(!UsbCanUtil::GetInstance().IsOpened()) { \ return val; \ } /*! * \brief 常量,当返回ERR_CAN_NOT_OPENED,就表示USB CAN没有被打开 */ #define ERR_CAN_NOT_OPENED (-1) #include <QMap> #include <QString> #define USB_CAN_BAURATE_5KBPS QObject::tr("5KBPS") #define USB_CAN_BAURATE_10KBPS QObject::tr("10KBPS") #define USB_CAN_BAURATE_20KBPS QObject::tr("20KBPS") #define USB_CAN_BAURATE_40KBPS QObject::tr("40KBPS") #define USB_CAN_BAURATE_80KBPS QObject::tr("80KBPS") #define USB_CAN_BAURATE_100KBPS QObject::tr("100KBPS") #define USB_CAN_BAURATE_125KBPS QObject::tr("125KBPS") #define USB_CAN_BAURATE_200KBPS QObject::tr("200KBPS") #define USB_CAN_BAURATE_250KBPS QObject::tr("250KBPS") #define USB_CAN_BAURATE_400KBPS QObject::tr("400KBPS") #define USB_CAN_BAURATE_500KBPS QObject::tr("500KBPS") #define USB_CAN_BAURATE_666KBPS QObject::tr("666KBPS") #define USB_CAN_BAURATE_800KBPS QObject::tr("800KBPS") #define USB_CAN_BAURATE_1000KBPS QObject::tr("1000KBPS") #define USB_CAN_BAURATE_DEFAULT USB_CAN_BAURATE_500KBPS /*! * \brief VCI_CAN的一个辅助封装类 */ class UsbCanUtil : public QObject { Q_OBJECT public: enum { MAX_DEV_IND = 10, }; /*! * \brief The Baurate enum 波特率 */ enum Baurate{ BAURATE_5KBPS = 0xBFFF, BAURATE_10KBPS = 0x311C, BAURATE_20KBPS = 0x181C, BAURATE_40KBPS = 0x87FF, BAURATE_80KBPS = 0x83FF, BAURATE_100KBSP = 0x041C, BAURATE_125KBPS = 0x031C, BAURATE_200KBPS = 0x81FA, BAURATE_250KBPS = 0x011C, BAURATE_400KBPS = 0x80FA, BAURATE_500KBPS = 0x001C, BAURATE_666KBPS = 0x80B6, BAURATE_800KBPS = 0x0016, BAURATE_1000KBPS = 0x0014, BAURATE_DEFAULT = BAURATE_500KBPS, }; /*! * \brief 析构器 */ ~UsbCanUtil(void); /*! * \brief 单利模式在c/c++中就相当于使用全局变量 * * 总之要想获取UsbCanUtil就直接使用UsbCanUtil::GetInstance()就行 */ static UsbCanUtil& GetInstance(); /*! * \brief getBaurate 获取波特率 * \retval 波特率 */ QString GetBaurate() const; /*! * \brief addBaurate 添加波特率 * \param name 波特率名称 * \param baurate 波特率值 */ void AddBaurate(QString name, Baurate baurate); /*! * \brief getSupportedBaurate 获取支持的波特率 * \retval 支持的波特率列表 */ QList<QString> GetSupportedBaurateList(); /*! * \brief setBaurate 设置波特率 * \param baurate 波特率,可以是: * + USB_CAN_BAURATE_5KBPS * + USB_CAN_BAURATE_10KBPS * + USB_CAN_BAURATE_20KBPS * + USB_CAN_BAURATE_40KBPS * + USB_CAN_BAURATE_80KBPS * + USB_CAN_BAURATE_100KBPS * + USB_CAN_BAURATE_125KBPS * + USB_CAN_BAURATE_200KBPS * + USB_CAN_BAURATE_250KBPS * + USB_CAN_BAURATE_400KBPS * + USB_CAN_BAURATE_500KBPS * + USB_CAN_BAURATE_666KBPS * + USB_CAN_BAURATE_800KBPS * + USB_CAN_BAURATE_1000KBPS */ void SetBaurate(QString baurate); /*! * \brief ReadCANStatus 读取CAN状态 * \param can_status 接收CAN状态 * \retval 成功与否 */ bool ReadCANStatus(P_CAN_STATUS can_status); /*! * \brief 打开指定的VCI_CAN设备 * * \param [in] device_type 设备类型,对于我们测试项目直接使用DEVICE_TYPE宏就可以,使用的是USB CAN * \param [in] init 打开VCI_CAN后要进行的配置,如果为NULL,那么默认的值就是使用DEFAULT_VCI_INIT_CONFIG * \retval 返回成功与否 */ BOOL Open(DWORD device_type, INIT_CONFIG *init = NULL); /*! * \brief 关闭已经打开的CAN设备 */ ULONG Close(); /*! * \brief 获取CAN设备是否打开 */ BOOL IsOpened() const; /*! * \brief 使用CAN设备来发送数据 * \param [in] can_obj 表示要发送的对象 * \retval 返回STATUS_OK表示发送成功,否则表示发送失败 */ ULONG Send(CAN_OBJ & can_obj); /*! * \brief 使用CAN设备来发送多组报文 * \param [in] can_objs 要发送can报文的首地址 * \param [in] obj_len CAN报文的数目 */ ULONG Send(CAN_OBJ *can_objs, UINT obj_len); /*! * \brief 接收数据 * \param [in] can_obj 表示要发送的对象指针 * \param [in] obj_len 表示can_obj指针具有包含几个VCI_CAN_OBJ * \param [in] wait_time * \retval 返回值<=0表示发送失败,否则发送成功 */ DWORD Receive(CAN_OBJ *can_obj, UINT obj_len = 1, INT wait_time = INT(0)); // 档接收失败的时候,使用此函数可以获取错误消息 /*! * \brief 读取错误信息 * \param [out] err_info 用来读取具体的错误信息 * \retval */ DWORD ReadErrorInfo(ERR_INFO &error_info); signals: void openCan(); void closeCan(); private: UsbCanUtil(); //!< 单利模式的固定模式,禁止其他类直接构造这个对象 void initBaurateMap(); BOOL opened_; //!< 保存CAN设备是否被打开的状态 DWORD dev_ind_; //!< CAN设备索引,对于新版ECAN DLL非常重要 DWORD dev_type_; //!< 设备类型 INIT_CONFIG init_config_; //!< 初始化配置 QMap<QString, Baurate> baurateMap; //!< 管理波特率 QList<QString> supportedBaurateList; //!< 支持的波特率列表 QString baurate; BOOL OpenDevice(UINT max_dev_ind); //!< 用来打开可以可选的CAN设备,最多尝试max_dev_ind此 };
TwoFlyLiu/ecanspy3
ecanspy3/send/signalwidget.h
#ifndef SIGNALWIDGET_H #define SIGNALWIDGET_H #include "base/titletableviewwidget.h" #include "send/signaltablemodel.h" #include "can/UsbCanUtil.h" class SignalWidget : public TitleTableViewWidget { Q_OBJECT public: explicit SignalWidget(QWidget *parent = nullptr); void initModel(); void setAllButtons(); void setRowButtons(int row); void setAllPhyDelegate(); signals: void updateMessageData(Message *msg); public slots: void setMessage(Message *msg, CAN_OBJ *obj); void onIncButton(); void onDecButton(); void modelDataChanged(QModelIndex, QModelIndex); protected: SignalTableModel *model; }; #endif // SIGNALWIDGET_H
TwoFlyLiu/ecanspy3
ecanspy3/send/signaltableviewphysicalvaluedelegate.h
<reponame>TwoFlyLiu/ecanspy3 #ifndef COMBOBOXDELEGATE_H #define COMBOBOXDELEGATE_H #include <QItemDelegate> #include <dbc4cpp/parser.h> class SignalTableViewPhysicalValueDelegate : public QItemDelegate { public: SignalTableViewPhysicalValueDelegate(QObject *parent=nullptr); // QAbstractItemDelegate interface public: QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; protected: QWidget *createComboBoxEditor(QWidget *parent, Signal *signal) const; QWidget *createDoubleSpinBoxEditor(QWidget *parent, Signal *signal) const; int calucSignalFactor(Signal *signal) const; }; #endif // COMBOBOXDELEGATE_H
TwoFlyLiu/ecanspy3
ecanspy3/diag/diagwidget.h
<reponame>TwoFlyLiu/ecanspy3 #ifndef DIAGWIDGET_H #define DIAGWIDGET_H #include <QWidget> class DiagWidget : public QWidget { public: DiagWidget(QWidget *parent); }; #endif // DIAGWIDGET_H
TwoFlyLiu/ecanspy3
ecanspy3/can/Core - 副本.h
<filename>ecanspy3/can/Core - 副本.h #pragma once #include <vector> #include <map> #include "ECanVci.H" #include <QObject> #include <QTimer> ///////////////////////////////////////////////////////////////////////////////////////// // 周期性发送报文 //////////////////////////////////////////////////////////////////////////////////////// // 这个类当需要调用的时候调用, // 当前用于,当报文发送完毕的时候,调用 class MessageTxCallback { public: MessageTxCallback(BOOL need_called = FALSE) : need_called_(need_called) {} void NeedCalled() { need_called_ = TRUE; } void Call() { if (need_called_) { need_called_ = FALSE; OnCall(); } } virtual void OnCall() = 0; protected: BOOL need_called_; }; //MessageTxCallback管理类 class MessageTxCallbackManager { public: void AddMessageTxCallback(MessageTxCallback *callback) { callbacks_.push_back(callback); } void Call() { for (auto iter = callbacks_.begin(); iter != callbacks_.end(); ++iter) { if ((*iter) != NULL) { (*iter)->Call(); } } } static MessageTxCallbackManager& GetInstance() { static MessageTxCallbackManager inst; return inst; } protected: std::vector<MessageTxCallback*> callbacks_; }; enum TestMode { TEST_MODE_NORMAL = 0, /*普通测试模式*/ TEST_MODE_PRESS /*压力测试模式*/ }; // 发送报文基类 class MessageTx { public: MessageTx(UINT id, UINT len); void SetCallback(MessageTxCallback *callback) { callbacks_.push_back(callback); MessageTxCallbackManager::GetInstance().AddMessageTxCallback(callback); } void SetNormalTestMode(); void SetPressTestMode(); TestMode GetTestMode() const; void PreTransmit(); protected: void Transmit(); public: CAN_OBJ can_obj_; CAN_OBJ press_can_obj_; CAN_OBJ *cur_can_obj_; std::vector<MessageTxCallback *>callbacks_; TestMode mode_; }; class MessagePeriodTx : public MessageTx { public: MessagePeriodTx(UINT id, UINT len, UINT period, UINT offset); void OnElapsed(UINT elapsed); void Start(); void Stop(); UINT GetPeriod() const { return period_; } void SetPeriod(UINT period) { period_ = period; } protected: UINT period_; UINT tick_count_; int offset_; BOOL started_; }; class MessagePeriodTxMgr { public: static MessagePeriodTxMgr& GetInstance(); void AddMessagePeriodTx(UINT id, UINT len, UINT period, UINT offset); void OnElapsed(UINT elapsed); void Start(); void Start(UINT can_id); void Stop(); void Stop(UINT can_id); void AddCallback(UINT can_id, MessageTxCallback *callback); BYTE* GetCanData(UINT can_id) { auto iter = message_period_txs_.find(can_id); if (iter != message_period_txs_.end()) { return iter->second.can_obj_.Data; } return NULL; } CAN_OBJ* GetCanObj(UINT can_id) { auto iter = message_period_txs_.find(can_id); if (iter != message_period_txs_.end()) { return &iter->second.can_obj_; } return NULL; } BOOL IsStarted() const { return started_; } void clear() { message_period_txs_.clear(); } void SetNormalTestMode(); void SetPressTestMode(); TestMode GetTestMode() const { return mode_; } std::vector<UINT> GetAllCanIds() const { std::vector<UINT> ids; for (auto iter = message_period_txs_.begin(); iter != message_period_txs_.end(); ++iter) { ids.push_back(iter->first); } return ids; } protected: std::map<UINT, MessagePeriodTx> message_period_txs_; BOOL started_; private: MessagePeriodTxMgr() : started_(FALSE), mode_(TEST_MODE_NORMAL) {} TestMode mode_; public: BOOL SetCanPeriod(UINT id, UINT period); BOOL GetCanPeriod(UINT id, UINT & period); }; class QTimerMessagePeriodTxMgr : public QObject { Q_OBJECT public: enum { MULTI_MEDIA_MESSAGE_PERIOD = 10, }; static QTimerMessagePeriodTxMgr &GetInstance() { static QTimerMessagePeriodTxMgr instance(MULTI_MEDIA_MESSAGE_PERIOD); return instance; } ~QTimerMessagePeriodTxMgr() { //Q_ASSERT(already_destroyed_ && "MultiMedia Must Destroyed"); if (timer_) { delete timer_; timer_ = NULL; } } operator bool() const { return (TRUE != already_destroyed_); } void Start() { message_period_tx_mgr_.Start(); } void Start(UINT can_id) { message_period_tx_mgr_.Start(can_id); } void Stop() { message_period_tx_mgr_.Stop(); } void Stop(UINT can_id) { message_period_tx_mgr_.Stop(can_id); } void Close() { Stop(); destroyed_ = TRUE; } protected: void Init(UINT period, UINT res); protected slots: void OnTimer(); private: UINT timer_res_; UINT timer_id_; BOOL destroyed_; BOOL already_destroyed_; UINT period_; QTimer *timer_; MessagePeriodTxMgr &message_period_tx_mgr_; private: QTimerMessagePeriodTxMgr(UINT period, UINT timer_res=1) : message_period_tx_mgr_(MessagePeriodTxMgr::GetInstance()) { Init(period, timer_res); } }; struct RxMessageListener { virtual void OnMessageChanged(const CAN_OBJ &message) = 0; virtual ~RxMessageListener() {} }; class RxMessageDispatcher { public: ~RxMessageDispatcher(); void AddRxMessageListener(RxMessageListener *listener, BOOL auto_delete); void RemoveRxMessageListener(RxMessageListener *listener); void Dispatch(const CAN_OBJ &message); static RxMessageDispatcher& GetInstance() { static RxMessageDispatcher instance; return instance; } protected: std::map<RxMessageListener*, BOOL> items_; }; class RxMessageFilter { public: enum { FILTER_BIT_VALUE = 0, }; enum EndianKind{ INTEL_LSB = 0, INTEL_MSB, MOTOROLA_LSB, MOTOROLA_MSB }; struct FilterRange { UINT start_pos; UINT len; EndianKind kind; }; void AddFilterRange(UINT start_pos, UINT len, EndianKind kind); void Filter(CAN_OBJ &obj); protected: void doFilter(CAN_OBJ &obj, UINT start_pos, UINT len, EndianKind kind); void doIntelLsbFilter(CAN_OBJ &obj, UINT start_pos, UINT len); void doIntelMsbFilter(CAN_OBJ &obj, UINT start_pos, UINT len); void doMotorolaLsbFilter(CAN_OBJ &obj, UINT start_pos, UINT len); void doMotorolaMsbFilter(CAN_OBJ &obj, UINT start_pos, UINT len); protected: std::vector<FilterRange> filter_ranges_; }; class RxMessageFilterManager { public: ~RxMessageFilterManager(); void AddRxMessageFilter(UINT can_id, RxMessageFilter *filter); void RemoveRxMessageFilter(UINT can_id); void Filter(CAN_OBJ &obj); static RxMessageFilterManager& GetInstance() { static RxMessageFilterManager instance; return instance; } protected: std::map<UINT, RxMessageFilter*> filters_; }; #define BEGIN_RX_MESSAGE_FILTER(__can_id) {\ auto can_id = __can_id;\ auto *filter = new RxMessageFilter;\ RxMessageFilterManager::GetInstance().AddRxMessageFilter(can_id, filter); #define RX_MESSAGE_FILTER_ITEM(start_pos, len, kind)\ filter->AddFilterRange(start_pos, len, RxMessageFilter::kind); #define END_RX_MESSAGE_FILTER() } class RxMessageMonitor { public: RxMessageMonitor(); static RxMessageMonitor& GetInstance() { static RxMessageMonitor instance; return instance; } void Receive(CAN_OBJ &obj); void DispatchObj(const CAN_OBJ &obj); void Reset(); protected: RxMessageDispatcher &dispatcher_; RxMessageFilterManager &filter_; std::map<UINT, CAN_OBJ> objs_; };
TwoFlyLiu/ecanspy3
dbc4cpp/entities.h
#ifndef ENTITIES_H #define ENTITIES_H #include "dbc4cpp_global.h" #include <QSet> #include <QMap> #include <QStringList> BEGIN_DBC4CPP_NAMESPACE static QString EMPTY_STRING; /*! * \brief Version类,代表DBC文件中的版本号 */ class Version { public: Version(const QString &version=""); /*! * \brief get 获取版本号 * \retval 版本号 */ const QString &get() const; /*! * \brief set 设置版本号 * \param version 要设置的版本号 */ void set(const QString &version); private: QString version; //!< 保存当前DBC文件中解析到的版本号 }; /*! * \brief NS类,代表DBC文件中的NS(New Symbol) */ class NS { public: NS(const QSet<QString> &set=QSet<QString>()); /*! * \brief addNewSymbol 添加新的Symbol到NewSymbol集合中 * \param newSymbol 新的NewSymbol */ void addNewSymbol(const QString &newSymbol); /*! * \brief reset 清空NewSymbol集合中的所有元素 */ void reset(); /*! * \brief getNewSymbolSet 获取当前的NewSymbol集合 * \return 当前的NewSymbol集合 */ const QSet<QString> &getNewSymbolSet() const; private: QSet<QString> newSymboSet; //!< NewSymbol集合 }; /*! * \brief BS类表示DBC文件中位时间参数信息 */ class BS { public: BS(quint32 baurate=0, quint32 btr1=0, quint32 btr2=0); /*! * \brief getBaurate 获取总线波特率值 * \retval 总线波特率值 */ quint32 getBaurate() const; /*! * \brief setBaurate 设置总线波特率 * \param baurate 要设置的总线波特率 */ void setBaurate(quint32 baurate); /*! * \brief getBTR1 获取BTR1寄存器的值 * \retval BTR1寄存器的值 */ quint32 getBTR1() const; /*! * \brief setBTR1 设置BTR1寄存器的值 * \param btr1 要设置BTR1寄存器的值 */ void setBTR1(quint32 btr1); /*! * \brief getBTR2 获取BTR2寄存器的值 * \retval BTR2寄存器的值 */ quint32 getBTR2() const; /*! * \brief setBTR2 设置BTR2寄存器的值 * \param btr2 要设置的BTR2寄存器的值 */ void setBTR2(quint32 btr2); private: quint32 baurate; //!< 保存总线波特率 quint32 btr1; //!< 保存BTR1寄存器的值 quint32 btr2; //!< 保存BTR2寄存器的值 }; /*! * \brief Commenter类代表DBC文件中的CM_节点 */ class Commenter { public: /*! * \brief getComment 获取注释 * \retval 注释 */ const QString &getComment() const { return this->comment; } /*! * \brief setComment 设置注释 * \param comment 要设置的注释 */ void setComment(const QString &comment) { this->comment = comment; } protected: QString comment; //!< 注释 }; /*! * \brief AdditionalAttribute类表示附加属性 */ class AdditionalAttribute { public: enum ValueType { VALUE_TYPE_INT=0, //!< 整形类型 VALUE_TYPE_HEX, //!< HEX类型 VALUE_TYPE_FLOAT, //!< 浮点类型 VALUE_TYPE_STRING, //!< 字符串类型 VALUE_TYPE_ENUM //!< 枚举类型 }; ValueType getValueType() const { return this->valueType; } void setIntRange(qint32 minimum, qint32 maximum) { this->value.intVal.minimum = minimum; this->value.intVal.maximum = maximum; this->valueType = VALUE_TYPE_INT; } bool getIntRange(qint32 &minimum, qint32 &maximum) const { if (VALUE_TYPE_INT == this->valueType) { minimum = this->value.intVal.minimum; maximum = this->value.intVal.maximum; return true; } return false; } void setIntValue(qint32 value) { if (VALUE_TYPE_INT == this->valueType) { this->value.intVal.setValue(value); } } qint32 getIntValue() const { if (VALUE_TYPE_INT == this->valueType) { return this->value.intVal.getValue(); } return -1; } void setHexRange(qint32 minimum, qint32 maximum) { this->valueType = VALUE_TYPE_HEX; this->value.hexVal.minimum = minimum; this->value.hexVal.maximum = maximum; } bool getHexRange(qint32 &minimum, qint32 &maximum) const { if (VALUE_TYPE_HEX == this->valueType) { minimum = this->value.hexVal.minimum; maximum = this->value.hexVal.maximum; return true; } return false; } void setHexValue(qint32 value) { if (VALUE_TYPE_HEX == this->valueType) { this->value.hexVal.setValue(value); } } qint32 getHexValue() const { if (VALUE_TYPE_HEX == this->valueType) { return this->value.hexVal.getValue(); } return -1; } QString getHexString() const { if (VALUE_TYPE_HEX == this->valueType) { return this->value.hexVal.getHexValue(); } return ""; } void setFloatRange(double minimum, double maximum) { this->valueType = VALUE_TYPE_FLOAT; this->value.floatVal.minimum = minimum; this->value.floatVal.maximum = maximum; } bool getFloatRange(double &minimum, double &maximum) const { if (VALUE_TYPE_FLOAT == this->valueType) { minimum = this->value.floatVal.minimum; maximum = this->value.floatVal.maximum; return true; } return false; } void setFloatValue(double value) { if (VALUE_TYPE_FLOAT == this->valueType) { this->value.floatVal.setValue(value); } } double getFloatValue() const { if (VALUE_TYPE_FLOAT == this->valueType) { return this->value.floatVal.getValue(); } return -1; } void setStringType() { this->valueType = VALUE_TYPE_STRING; } const QString &getStringValue() const { if (VALUE_TYPE_STRING == this->valueType) { return this->strVal.getValue(); } return EMPTY_STRING; } void setStringValue(const QString &str) { if (VALUE_TYPE_STRING == this->valueType) { this->strVal.setValue(str); } } void setEnumType() { this->valueType = VALUE_TYPE_ENUM; } void addEnumValue(const QString &value) { if (VALUE_TYPE_ENUM == this->valueType) { this->enumVal.addEnumValue(value); } } const QString &getEnumValue(qint32 index) const { if (VALUE_TYPE_ENUM == this->valueType) { return this->enumVal.getEnumValue(index); } return EMPTY_STRING; } qint32 getEnumIndex(const QString &value) const { if (VALUE_TYPE_ENUM == this->valueType) { return this->enumVal.getEnumIndex(value); } return -1; } void setEnumValue(qint32 index) { if (VALUE_TYPE_ENUM == this->valueType) { this->enumVal.setValue(index); } } void setEnumValue(const QString &index) { if (VALUE_TYPE_ENUM == this->valueType) { this->enumVal.setValue(index); } } qint32 getEnumValue() const { if (VALUE_TYPE_ENUM == this->valueType) { return this->enumVal.getValue(); } return -1; } const QString &getEnumStringValue() const { if (VALUE_TYPE_ENUM == this->valueType) { return this->enumVal.getEnumValue(getEnumValue()); } return EMPTY_STRING; } QStringList getEnumValues() const { if (VALUE_TYPE_ENUM == this->valueType) { return this->enumVal.getEnumValues(); } return QStringList(); } void setValue(qint32 value) { switch (this->valueType) { case VALUE_TYPE_ENUM: this->enumVal.setValue(value); break; case VALUE_TYPE_HEX: this->value.hexVal.setValue(value); break; case VALUE_TYPE_INT: this->value.intVal.setValue(value); break; default: break; } } void setValue(const QString &value) { switch (this->valueType) { case VALUE_TYPE_ENUM: this->enumVal.setValue(value); break; case VALUE_TYPE_STRING: this->strVal.setValue(value); break; default: break; } } void setValue(double value) { switch (this->valueType) { case VALUE_TYPE_FLOAT: this->value.floatVal.setValue(value); break; default: break; } } private: template <typename T> struct RangeValue { T minimum; T maximum; T value; void setValue(T value) { if (value >= minimum && value <= maximum) { this->value = value; } } T getValue() const { return this->value; } }; // 执行数值 struct IntValue : public RangeValue<qint32> {}; // HEX数据 struct HexValue : public IntValue { QString getHexValue() const { return QString("%1").arg(this->value, 0, 16); } }; // Float数值 struct FloatValue : public RangeValue<double> {}; // 字符串值 struct StringValue { QString value; void setValue(const QString &value) { this->value = value; } const QString &getValue() const { return this->value; } }; // 枚举类型值 struct EnumValue { typedef QStringList EnumValueTable; EnumValue() : valueIndex(-1) {} /*! * \brief addEnumValue 添加枚举类型值 * \param value 要添加的枚举类型值 */ void addEnumValue(const QString &value) { this->valueTable.push_back(value); } /*! * \brief getEnumValue 获取指定索引位置上的枚举值 * \param index 指定索引位置 * \retval 指定索引位置上的枚举值 */ const QString &getEnumValue(qint32 index) const { if (index < valueTable.size()) { return valueTable.at(index); } return EMPTY_STRING; } /*! * \brief setValue 设置枚举值 * \param value 要设置的枚举值 */ void setValue(const QString &value) { valueIndex = getEnumIndex(value); } /*! * \brief setValue 设置枚举值 * \param index 要设置的索引 */ void setValue(qint32 index) { if (index < valueTable.size()) { valueIndex = index; } } /*! * \brief getValue 获取枚举值 * \retval 枚举值 */ qint32 getValue() const { return valueIndex; } /*! * \brief getEnumIndex 获取指定枚举值对应的索引 * \param value 指定枚举值 * \retval 指定枚举值对应的索引 */ qint32 getEnumIndex(const QString &value) const { return valueTable.indexOf(value); } /*! * \brief getEnumValues 获取enum内的所有值 * \retval enum内的所有值 */ const EnumValueTable& getEnumValues() const { return this->valueTable; } EnumValueTable valueTable; int valueIndex; }; ValueType valueType; //!< 存储值类型 union { IntValue intVal; HexValue hexVal; FloatValue floatVal; } value; //!< 存储对应的值 StringValue strVal; EnumValue enumVal; }; class AdditionalAttributeTable { public: typedef QMap<QString, AdditionalAttribute> AdditionalAttributeMap; void addAdditionalAttribute(const QString &name, const AdditionalAttribute &attr) { table.insert(name, attr); } void removeAdditionalAttribute(const QString &name) { table.remove(name); } AdditionalAttribute* getAdditionalAttribute(const QString &name) { auto iter = table.find(name); if (iter != table.end()) { return &iter.value(); } return NULL; } const AdditionalAttribute* getAdditionalAttribute(const QString &name) const { auto iter = table.find(name); if (iter != table.end()) { return &iter.value(); } return NULL; } const AdditionalAttributeMap& getAdditionalAttributeMap() const { return table; } protected: AdditionalAttributeMap table; }; /*! * \brief ValueDescription 作为Val和ValTable的基类存在,主要复位维护数据 */ class ValueDescription { public: typedef QMap<qint32, QString> ValueDescTable; //!< 表示对应值描述对应的表类型 /*! * \brief addValueDesc 添加值描述 * \param value 要添加的值 * \param desc 对应的值描述 */ void addValueDesc(qint32 value, const QString &desc) { valueDescTable.insert(value, desc); } /*! * \brief removeValueDesc 移除指定的值描述 * \param value 要移除的值 */ void removeValueDesc(qint32 value) { valueDescTable.remove(value); } /*! * \brief getValueDescTable 获取值描述表 * \retval 描述表 */ const ValueDescTable & getValueDescTable() const { return valueDescTable; } protected: ValueDescTable valueDescTable; }; /*! * \brief ValTable类对应DBC文件中的VAL_TABLE_节点 */ class ValTable : public ValueDescription { public: /*! * \brief setName 设置值表名 * \param name 要设置的值表名 */ void setName(const QString &name) { this->name = name; } /*! * \brief getName 返回值表名 * \retval 值表名 */ const QString &getName() const { return this->name; } private: QString name; //!< 用来保存值表名 }; /*! * \brief Signal类,定义DBC文件中的SG_节点和VAL_节点 */ class Signal : public Commenter, public ValueDescription { public: enum MultiplexerIndType { MULTIPLEXER_IND_TYPE_SWITCH=0, //!< 多路复用指示开关类型 MULTIPLEXER_IND_TYPE_VALUE, //!< 多路复用指示值类型 MULTIPLEXER_IND_TYPE_NONE //!< 多路复用指示空类型 }; enum ByteOrderType { BYTE_ORDER_TYPE_MOTOROLA=0, //!< 摩托罗拉字节序(大端) BYTE_ORDER_TYPE_INTEL //!< 英特尔字节序(小端) }; enum ValueType { VALUE_TYPE_UNSIGNED='+', //!< 无符号类型 VALUE_TYPE_SIGNED='-' //!< 有符号类型 }; enum ExternalValueType { EXTERNAL_VALUE_TYPE_SIGNED_UNSIGNED=0, //!< 有符号或者无符号类型 EXTERNAL_VALUE_TYPE_32_BIT_IEEE_FLOAT, //!< 32位浮点数 EXTERNAL_VALUE_TYPE_64_BIT_IEEE_DOUBLE //!< 64位双精度 }; /*! * \brief getName 获取信号名 * \retval 信号名 */ const QString &getName() const { return sigName; } /*! * \brief setName 设置信号名 * \param sigName 要设置的信号名 */ void setName(const QString &sigName) { this->sigName = sigName; } /*! * \brief getMultiplexerIndicatorType 获取多路复用指示类型 * \retval 多路复用指示类型 */ MultiplexerIndType getMultiplexerIndicatorType() const { return this->multiplexerIndType; } /*! * \brief setMultiplexerIndicatorType 设置多路复用指示类型 * \param multiplexerIndType 要设置的多路复用指示类型 */ void setMultiplexerIndicatorType(MultiplexerIndType multiplexerIndType) { this->multiplexerIndType = multiplexerIndType; } /*! * \brief getMultiplexerIndicatorValue 获取多路复用指示值 * \retval 多路复用指示值 */ qint32 getMultiplexerIndicatorValue() const { return this->multiplexerIndValue; } /*! * \brief setMultiplexerIndicatorValue 设置多路复用指示值 * \param value 要设置的多路复用指示值 */ void setMultiplexerIndicatorValue(quint32 value) { this->multiplexerIndValue = value; } /*! * \brief getStartBit 获取起始位 * \retval 起始位 */ qint32 getStartBit() const { return this->startBit; } /*! * \brief setStartBit * \param startBit */ void setStartBit(qint32 startBit) { this->startBit = startBit; } /*! * \brief getBitLen 获取信号位长度 * \retval 信号位长度 */ qint32 getBitLen() const { return this->bitLen; } /*! * \brief setBitLen 设置信号位长度 * \param bitLen 要设置的信号位长度 */ void setBitLen(qint32 bitLen) { this->bitLen = bitLen; } /*! * \brief getByteOrder 获取字节序 * \retval 字节序 */ ByteOrderType getByteOrder() const { return this->byteOrder; } /*! * \brief setByteOrder 设置字节序 * \param byteOrder 要设置的字节序 */ void setByteOrder(ByteOrderType byteOrder) { this->byteOrder = byteOrder; } /*! * \brief getValueType 获取值类型 * \retval 值类型 */ ValueType getValueType() const { return this->valueType; } /*! * \brief setValueType 设置值类型 * \param valueType 要设置的值类型 */ void setValueType(ValueType valueType) { this->valueType = valueType; } /*! * \brief getExternalValueType 获取外部值类型 * \retval 外部值类型 */ ExternalValueType getExternalValueType() const { return this->externValueType; } /*! * \brief setExternalValueType 设置外部值类型 * \param externValueType 要设置的外部值类型 */ void setExternalValueType(ExternalValueType externValueType) { this->externValueType = externValueType; } /*! * \brief getFactor 获取精度 * \retval 精度 */ double getFactor() const { return factor; } /*! * \brief setFactor 设置精度 * \param factor 要设置的精度 */ void setFactor(double factor) { this->factor = factor; } /*! * \brief getOffset 获取偏移值 * \retval 偏移值 */ double getOffset() const { return offset; } /*! * \brief setOffset 设置偏移值 * \param offset 要设置的偏移值 */ void setOffset(double offset) { this->offset = offset; } /*! * \brief getMinimum 获取最小值(物理值) * \retval 最小值(物理值) */ double getMinimum() const { return this->minimum; } /*! * \brief setMinimum 设置最小值(物理值) * \param minimum 要设置的最小值(物理值) */ void setMinimum(double minimum) { this->minimum = minimum; } /*! * \brief getMaximum 获取最大值(物理值) * \retval 最大值(物理值) */ double getMaximum() const { return this->maximum; } /*! * \brief setMaximum 设置最大值(物理值) * \param maximum 要设置的最大值(物理值) */ void setMaximum(double maximum) { this->maximum = maximum; } /*! * \brief getUnit 获取单位 * \retval 单位 */ const QString &getUnit() const { return this->unit; } /*! * \brief setUnit 设置单位 * \param unit 要设置的单位 */ void setUnit(const QString &unit) { this->unit = unit; } /*! * \brief addReceiver 添加接收者 * \param receiver 要添加的接收者 */ void addReceiver(const QString &receiver) { receiverSet.insert(receiver); } /*! * \brief resetReceiverSet 清空所有接收者 */ void resetReceiverSet() { receiverSet.clear(); } /*! * \brief getReceiverSet 获取接收者集合 * \retval 接收者集合 */ QSet<QString> getReceiverSet() const { return receiverSet; } private: QString sigName; //!< 保存信号名称 MultiplexerIndType multiplexerIndType; //!< 多路复用指示类型 quint32 multiplexerIndValue; //!< 多路复用指示值 qint32 startBit; //!< 起始位 qint32 bitLen; //!< 信号的位长度 ByteOrderType byteOrder; //!< 字节序 ValueType valueType; //!< 值类型 ExternalValueType externValueType; //!< 外部值类型 double factor; //!< 精度 double offset; //!< 偏移值 double minimum; //!< 最小值 double maximum; //!< 最大值 QString unit; //!< 单位 QSet<QString> receiverSet; //!< 集合 }; class Message : public Commenter { public: typedef QMap<QString, Signal*> SignalTable; ~Message() { resetSignalList(); } /*! * \brief getName 获取报文名称 * \retval 报文名称 */ const QString &getName() const { return this->name; } /*! * \brief setName 设置报文名称 * \param name 要设置的报文名称 */ void setName(const QString &name) { this->name = name; } /*! * \brief getId 获取报文ID * \retval 报文ID */ quint32 getId() const { return this->id; } /*! * \brief setId 设置报文ID * \param id 要设置的报文ID */ void setId(quint32 id) { this->id = id; } /*! * \brief addTransmitter 添加发送者 * \param transmitter 要添加的发送者 */ void addTransmitter(const QString &transmitter) { transmitterSet.insert(transmitter); } /*! * \brief resetTransmitterSet 清空发送者集合 */ void resetTransmitterSet() { transmitterSet.clear(); } /*! * \brief getTransmitterSet 返回发送者集合 * \retval 发送者集合 */ const QSet<QString>& getTransmitterSet() const { return transmitterSet; } /*! * \brief getTransmitter 获取发送者名称 * \retval 发送者名称 */ QString getTransmitter() { auto iter = transmitterSet.begin(); if (iter != transmitterSet.end()) { return *iter; } return QString(""); } /*! * \brief setByteLen 设置报文数据长度 * \param byteLen 要设置的报文数据长度 */ void setByteLen(qint32 byteLen) { this->byteLen = byteLen; } /*! * \brief getByteLen 获取报文字节长度 * \retval 报文字节长度 */ qint32 getByteLen() const { return this->byteLen; } /*! * \brief addSignal 添加信号到列表中 * \param signal 要添加的信号 */ void addSignal(Signal *signal) { if (signal != NULL) { signalList.insert(signal->getName(), signal); } } /*! * \brief removeSignal 移除指定名称的信号 * \param name 要移除信号的名称 */ void removeSignal(const QString &name) { auto iter = signalList.find(name); if (iter != signalList.end()) { delete iter.value(); iter.value() = NULL; signalList.erase(iter); } } /*! * \brief getSignal 获取指定名称的信号 * \param name 指定的信号名称 * \retval 指定名称的信号 */ Signal* getSignal(const QString &name) { auto iter = signalList.find(name); if (iter != signalList.end()) { return iter.value(); } return NULL; } /*! * \brief resetSignalList 清空信号列表 */ void resetSignalList() { for (auto iter = signalList.begin(); iter != signalList.end(); ++iter) { delete iter.value(); iter.value() = NULL; } signalList.clear(); } /*! * \brief getSignalList 获取信号列表 * \retval 信号列表 */ const SignalTable &getSignalList() const { return this->signalList; } private: QString name; //!< 报文名称 quint32 id; //!< 报文id QSet<QString> transmitterSet; //!< 发送者集合 qint32 byteLen; //!< 报文数据长度 SignalTable signalList; //!< 信号列表 }; /*! * \brief The Node class 网络节点,对应DBC文件中的BU_ */ class Node : public Commenter { public: ~Node() { clearMsgMap(this->txMsgMap); } /*! * \brief clearMsgMap 清除指定的MsgMap * \param msgMap 要清除的msgMap */ void clearMsgMap(QMap<qint32, Message*> &msgMap) { for (auto iter = msgMap.begin(); iter != msgMap.end(); ++iter) { delete iter.value(); } msgMap.clear(); } /*! * \brief setName 设置节点名称 * \param name 节点名称 */ void setName(const QString &name) { this->name = name; } /*! * \brief getName 获取节点名称 * \return 节点名称 */ const QString &getName() const { return this->name; } /*! * \brief addTxMsg 添加发送报文 * \param msg 要添加的发送报文 */ void addTxMsg(Message *msg) { Message *oldMsg = NULL; auto iter = this->txMsgMap.find(msg->getId()); if (iter != this->txMsgMap.end()) { oldMsg = iter.value(); } if (oldMsg != msg) { delete oldMsg; this->txMsgMap.insert(msg->getId(), msg); } } /*! * \brief removeTxMsg 移除发送报文 * \param id 要移除的报文ID */ void removeTxMsg(qint32 id) { auto iter = this->txMsgMap.find(id); if (iter != this->txMsgMap.end()) { delete iter.value(); this->txMsgMap.remove(id); } } /*! * \brief getTxMsgMap 获取发送报文Map * \retval 发送报文Map */ const QMap<qint32, Message*> &getTxMsgMap() const { return this->txMsgMap; } /*! * \brief getTxMsg 报文报文id来查找此报文的发送报文 * \param id 报文id * \return 指定id的发送报文 */ Message* getTxMsg(qint32 id) { auto iter = txMsgMap.find(id); if (iter != txMsgMap.end()) { return iter.value(); } return NULL; } private: QString name; //!< 节点名称 QMap<qint32, Message*> txMsgMap; //!< 发送报文Map }; /*! * \brief EVBase类是所有环境变量类的基类类型 */ class EVBase { public: enum ClassType { CLASS_TYPE_BASE_TYPE, CLASS_TYPE_DATA_TYPE }; virtual ~EVBase() {} /*! * \brief getClassType 由子类实现,获取类类型 * \retval 类类型 */ virtual ClassType getClassType() const = 0; /*! * \brief setName 设置环境变量名称 * \param name 环境变量名称 */ void setName(const QString &name) { this->name = name; } /*! * \brief getName 获取环境变量名称 * \retval 环境变量名称 */ const QString &getName() const { return this->name; } private: QString name; //!< 环境变量名称 }; /*! * \brief EV 类对应dbc文件中的EV_节点,它只表示基本类型的环境变量 */ class EV : public EVBase, public Commenter , public ValueDescription { public: enum EnvVarType { ENV_VAR_TYPE_INTEGER=0, //!< 表示变量值是整形 ENV_VAR_TYPE_FLOAT, //!< 表示变量值是浮点类型 ENV_VAR_TYPE_STRING //!< 表示变量值是字符串类型 }; enum AccessType { ACCESS_TYPE_UNRESTRICTED=0, //!< 没有限制 ACCESS_TYPE_READ, //!< 读 ACCESS_TYPE_WRITE, //!< 写 ACCESS_TYPE_READ_WRITE //!< 读写 }; ~EV() {} ClassType getClassType() const override { return CLASS_TYPE_BASE_TYPE; } /*! * \brief getEnvVarType 获取环境变量值类型 * \retval 环境变量值类型 */ EnvVarType getEnvVarType() const { return envVarType; } /*! * \brief setEnvVarType 设置环境变量类型 * \param envVarType 要设置的环境变量类型 */ void setEnvVarType(EnvVarType envVarType) { this->envVarType = envVarType; } /*! * \brief getMinimum 获取最小值 * \retval 最小值 */ double getMinimum() const { return minimum; } /*! * \brief setMinimum 设置最小值 * \param minimum 要设置的最小值 */ void setMinimum(double minimum) { this->minimum = minimum; } /*! * \brief getMaximum 获取最大值 * \retval 最大值 */ double getMaximum() const { return this->maximum; } /*! * \brief setMaximum 设置最大值 * \param maximum 要设置的最大值 */ void setMaximum(double maximum) { this->maximum = maximum; } /*! * \brief getUnit 获取单位 * \retval 单位 */ const QString &getUnit() const { return this->unit; } /*! * \brief setUnit 设置单位 * \param unit 要设置的单位 */ void setUnit(const QString &unit) { this->unit = unit; } /*! * \brief getInitValue 获取初始值 * \return 初始值 */ double getInitValue() const { return this->initValue; } /*! * \brief setInitValue 设置初始值 * \param initValue 要设置的初始值 */ void setInitValue(double initValue) { this->initValue = initValue; } /*! * \brief getEvId 获取要设置的环境id * \retval 要设置的环境id */ quint32 getEvId() const { return this->evId; } /*! * \brief setEvId 设置环境id * \param evId 要设置的环境id */ void setEvId(quint32 evId) { this->evId = evId; } /*! * \brief getAccessType 返回访问类型 * \retval 访问类型 */ AccessType getAccessType() const { return this->accessType; } /*! * \brief setAccessType 设置访问类型 * \param accessType 要设置的访问类型 */ void setAccessType(AccessType accessType) { this->accessType = accessType; } /*! * \brief addAccessNode 添加访问节点名称 * \param name 访问节点名称 */ void addAccessNode(const QString &name) { accessNodeList.push_back(name); } /*! * \brief removeAccessNode 移除指定名称的访问节点 * \param name 要移除的访问节点名称 */ void removeAccessNode(const QString &name) { auto index = accessNodeList.indexOf(name); if (index != -1) { accessNodeList.removeAt(index); } } /*! * \brief getAllAccessNode 获取所有访问节点 * \retval 所有访问节点 */ const QStringList &getAllAccessNode() const { return accessNodeList; } /*! * \brief getIntValue 获取整形值 * \retval 整形值 */ qint32 getIntValue() const { if (ENV_VAR_TYPE_INTEGER == envVarType) { return 0; } return value.intVal; } /*! * \brief setIntValue 设置整型值 * \param intVal 要设置的整型值 */ void setIntValue(qint32 intVal) { this->envVarType = ENV_VAR_TYPE_INTEGER; this->value.intVal = intVal; } /*! * \brief getFloatVal 或是浮点类型值 * \retval 浮点类型值 */ float getFloatVal() const { if (ENV_VAR_TYPE_FLOAT == envVarType) { return 0.0; } return this->value.floatVal; } /*! * \brief setFloatVal 设置浮点类型值 * \param floatVal 浮点类型值 */ void setFloatVal(float floatVal) { this->envVarType = ENV_VAR_TYPE_FLOAT; this->value.floatVal = floatVal; } /*! * \brief getStrVal 获取字符串类型值 * \retval 字符串类型值 */ QString getStrVal() const { if (ENV_VAR_TYPE_STRING == envVarType) { return ""; } return this->strVal; } /*! * \brief setStrVal 设置字符串类型值 * \param strVal 要设置的字符串值 */ void setStrVal(const QString strVal) { this->envVarType = ENV_VAR_TYPE_STRING; this->strVal = strVal; } private: EnvVarType envVarType; //!< 表示基本的变量值类型 double minimum; //!< 最小值 double maximum; //!< 最大值 QString unit; //!< 单位 double initValue; //!< 初始值 quint32 evId; //!< 环境变量id AccessType accessType; //!< 访问类型 QStringList accessNodeList; //!< 访问节点列表 union { qint32 intVal; float floatVal; } value; //!< 存储对应的值 QString strVal; }; /*! * \brief EnvVarData类表示dbc文件中的ENVAR_DATA_节点,这个类数据以二进制格式存储 */ class EnvVarData : public EVBase { public: typedef QList<quint8> ValueType; ClassType getClassType() const override { return CLASS_TYPE_DATA_TYPE; } /*! * \brief getDataSize 获取数据尺寸 * \retval 数据尺寸 */ qint32 getDataSize() const { return value.size(); } /*! * \brief setDataSize 设置数据尺寸 * \param newDataSize 要设置的数据尺寸 */ void setDataSize(qint32 newDataSize) { qint32 oldDataSize = getDataSize(); if (oldDataSize < newDataSize) { //要添加 for (; oldDataSize < newDataSize; ++oldDataSize) { value.push_back(0); } } else if (newDataSize < oldDataSize) { //要减少 for (; newDataSize < oldDataSize; ++newDataSize) { value.pop_back(); } } } /*! * \brief getValue 或是值,可以直接获取或者修改这个值 * \retval 值 */ ValueType &getValue() { return value; } private: ValueType value; //!< 值类型 }; /*! * \brief Document类代表整个DBC文件 */ class Document { public: /*! * \brief ForEachNewSymbolFn 是foreachAllNewSymbols方法的回调函数类型 * \param arg 是附加参数,此参数由foreachAllNewSymbols方法的第二个参数决定 * \param newSymbol 当前的新标签(New Symbol)的名称 */ typedef bool (*ForEachNewSymbolFn)(void* arg, const QString &newSymbol); typedef QMap<QString, Node*> NodeMap; //!< (网络)节点列表 typedef QMap<QString, ValTable*> ValueTableMap; typedef QMap<QString, EV*> EVMap; typedef QMap<QString, EnvVarData*> EVDataMap; typedef QMap<qint32, AdditionalAttributeTable> DefaultAttrTblMap; typedef QMap<QString, AdditionalAttributeTable> NodeAttrTblMap; typedef QMap<QString, AdditionalAttributeTable> EVAttrTblMap; typedef QMap<qint32, AdditionalAttributeTable> MsgAttrTblMap; typedef QMap<Signal*, AdditionalAttributeTable> SigAttrTablMap; enum ObjectType { OBJECT_TYPE_BU = 0, OBJECT_TYPE_BO, OBJECT_TYPE_SG, OBJECT_TYPE_EV, OBJECT_TYPE_GL //!< 全局 }; Document(); ~Document(); /*! * \brief getVersion 获取版本号 * \retval 版本号 */ const QString &getVersion() const { return version.get(); } /*! * \brief setVersion 设置版本号 * \param version 要设置的版本号 */ void setVersion(const QString &version) { this->version.set(version); } /*! * \brief addNewSymbol 添加新标签(NewSymbol) * \param newSymbol 要新建的新标签(NewSymbol) */ void addNewSymbol(const QString &newSymbol) { ns.addNewSymbol(newSymbol); } /*! * \brief foreachAllNewSymbols 遍历所有的新标签(NewSymbol) * \param fn 回调函数 */ void foreachAllNewSymbols(ForEachNewSymbolFn fn, void *arg); /*! * \brief getNS 获取所有New Symbol * \retval 所有New Symbol */ const QSet<QString> &getNS() const; /*! * \brief setBS 设置位定时参数 * \param baurate 波特率 * \param btr1 BTR1寄存器的值 * \param btr2 BTR2寄存器的值 */ void setBS(quint32 baurate, quint32 btr1, quint32 btr2); /*! * \brief getBS 获取位定时参数 * \param [out] baurate 接收波特率值 * \param [out] btr1 接收BTR1寄存器的值 * \param [out] btr2 接收BTR2寄存器的值 */ void getBS(quint32 &baurate, quint32 &btr1, quint32 &btr2); /*! * \brief addNode 添加(网络)节点 * \param node 要添加的(网络)节点 */ void addNode(Node *node); /*! * \brief removeNode 移除节点 * \param nodeName 要移除的节点名称 */ void removeNode(const QString &nodeName); /*! * \brief removeNode 移除节点,要移除的节点 * \param node 要移除的节点 */ void removeNode(Node *node); /*! * \brief removeAllNode 移除所有节点 */ void removeAllNode(); /*! * \brief getNode 获取指定名称节点 * \param nodeName 要获取的节点名称 * \retval 执行名称的节点 */ Node* getNode(const QString &nodeName); /*! * \brief getNodeMap 获取所有节点 * \retval 所有节点 */ const NodeMap &getNodeMap() const { return this->nodeMap; } /*! * \brief getBU 获取所有节点名称 * \retval 所有节点名称 */ QList<QString> getBU(); /*! * \brief getAllNodeNames 获取所有节点名称,同能同getBU * \retval 所有节点名称 */ QList<QString> getAllNodeNames() { return getBU(); } /*! * \brief addValueTable 添加ValueTable * \param valTable 要添加的ValueTable */ void addValueTable(ValTable *valTable); /*! * \brief removeValueTable 移除ValueTable * \param name 要移除的ValueTable名称 */ void removeValueTable(const QString &name); /*! * \brief removeAllValueTable 移除所有的ValueTable */ void removeAllValueTable(); /*! * \brief getValueTable 获取指定名称的ValueTable * \param name 指定的名称 * \retval 指定名称的ValueTable */ ValTable *getValueTable(const QString &name); /*! * \brief getValueTableMap 获取所有的ValueTable * \retval 所有的ValueTable */ const ValueTableMap &getValueTableMap() const { return this->valueTableMap; } /*! * \brief getMessage 根据报文id来获取指定指定报文 * \param msgId 报文id * \retval 指定id的报文 */ Message *getMessage(qint32 msgId); /*! * \brief getSignal 获取指定报文中的指定信号名的信号 * \param msgId 报文id * \param sigName 信号名 * \retval 指定报文中的指定信号名的信号 */ Signal *getSignal(qint32 msgId, const QString &sigName); /*! * \brief addEV 添加环境变量 * \param ev 要添加环境变量 */ void addEV(EV * ev) { if (ev != NULL) { evMap.insert(ev->getName(), ev); } } /*! * \brief removeEV 移除指定名称的环境变量 * \param name 要移除的环境变量的名称 */ void removeEV(const QString &name) { auto iter = evMap.find(name); if (iter != evMap.end()) { delete iter.value(); iter.value() = NULL; evMap.erase(iter); } } /*! * \brief removeAllEV 移除所有基本类型环境变量 */ void removeAllEV() { for (auto iter = evMap.begin(); iter != evMap.end(); ++iter) { delete iter.value(); iter.value() = NULL; } evMap.clear(); } /*! * \brief getEV 获取指定名称的环境变量 * \param evName 指定的环境变量名称 * \return 取指定名称的环境变量 */ EV *getEV(const QString &evName) { auto iter = evMap.find(evName); if (iter != evMap.end()) { return iter.value(); } return NULL; } /*! * \brief getEVMap 获取所有环境变量 * \retval 所有环境变量 */ const EVMap& getEVMap() const { return evMap; } /*! * \brief addEVData 添加二进制值类型的环境变量 * \param evData 要添加的二进制值类型的环境变量 */ void addEVData(EnvVarData *evData) { if (evData != NULL) { evDataMap.insert(evData->getName(), evData); } } /*! * \brief removeEVData 移除指定名称的二进制值环境变量 * \param name 要移除的变量的名称 */ void removeEVData(const QString &name) { auto iter = evDataMap.find(name); if (iter != evDataMap.end()) { delete iter.value(); iter.value() = NULL; evDataMap.erase(iter); } } /*! * \brief removeAllEVData 移除所有的二进制环境变量 */ void removeAllEVData() { for (auto iter = evDataMap.begin(); iter != evDataMap.end(); ++iter) { delete iter.value(); iter.value() = NULL; } evDataMap.clear(); } /*! * \brief getEVData 获取指定名称的二进制值环境变量 * \param name 变量名称 * \retval 指定名称的二进制值环境变量 */ EnvVarData* getEVData(const QString &name) { auto iter = evDataMap.find(name); if (iter != evDataMap.end()) { return iter.value(); } return NULL; } /*! * \brief addObjectAttribute 添加默认属性定义 * \param objectType 对象类型, 实际上值为:Document::ObjectType枚举类型中的值 * \param attrName 属性名称 * \param attr 属性值 */ void addObjectAttribute(int objectType, const QString &attrName, const AdditionalAttribute &attr) { auto iter = defaultAttrTblMap.find(objectType); if (iter != defaultAttrTblMap.end()) { iter.value().addAdditionalAttribute(attrName, attr); } else { AdditionalAttributeTable tbl; tbl.addAdditionalAttribute(attrName, attr); defaultAttrTblMap.insert(objectType, tbl); } } /*! * \brief getAllObjectAttrPrototypes 获取所有对象属性原型 * \retval 所有对象属性原型 */ const DefaultAttrTblMap &getAllObjectAttrPrototypes() const { return defaultAttrTblMap; } /*! * \brief getAllObjectAttrDefaultValues 获取所有对象属性默认值 * \retval 所有对象属性默认值 */ const DefaultAttrTblMap &getAllObjectAttrDefaultValues() const { return defaultAttrTblMap; } /*! * \brief getAllNodeAttrValues 获取所有节点属性值 * \retval 所有节点属性值 */ const NodeAttrTblMap &getAllNodeAttrValues() const { return this->nodeAttrTblMap; } /*! * \brief getAllMsgAttrValues 获取所有报文属性值 * \retval 所有报文属性值 */ const MsgAttrTblMap &getAllMsgAttrValues() const { return this->msgAttrTblMap; } /*! * \brief getMsgAttribute 获取报文属性 * \param attrName 属性名称 * \param msgId 报文id * \retval 报文属性 */ const AdditionalAttribute* getMsgAttribute(quint32 msgId, const QString &attrName) const; /*! * \brief getAllSigAttrValues 获取所有信号属性值 * \retval 所有信号属性值 */ const SigAttrTablMap &getAllSigAttrValues() const { return this->sigAttrTblMap; } /*! * \brief getAllEvAttrValues 获取所有环境变量属性值 * \retval 所有环境变量属性值 */ const EVAttrTblMap &getAllEvAttrValues() const { return this->evAttrTblMap; } /*! * \brief setDefaultAttributeIntValue 设置默认属性整形值 * \param attrName 属性名称 * \param value 属性值 */ void setDefaultAttributeIntValue(const QString &attrName, qint32 value); /*! * \brief setDefaultAttributeHexValue 设置默认属性HEX值 * \param attrName 属性名称 * \param value 属性值 */ void setDefaultAttributeHexValue(const QString &attrName, qint32 value); /*! * \brief setDefaultAttributeFloatValue 设置默认属性浮点值 * \param attrName 属性名称 * \param value 属性值 */ void setDefaultAttributeFloatValue(const QString &attrName, double value); /*! * \brief setDefaultAttributeStringValue 设置默认属性字符串值 * \param attrName 属性名称 * \param value 属性值 */ void setDefaultAttributeStringValue(const QString &attrName, const QString &value); /*! * \brief setDefaultAttributeStringValue 设置默认属性枚举值 * \param attrName 属性名称 * \param value 属性值 */ void setDefaultAttributeEnumValue(const QString &attrName, const QString &value); template <typename T> void setNodeAttributeValue(const QString &nodeName, const QString &attrName, const T &value); template <typename T> void setMsgAttributeValue(qint32 msgId, const QString &attrName, const T &value); template <typename T> void setSigAttributeValue(qint32 msgId, const QString &sigName, const QString &attrName, const T &value); template <typename T> void setEvAttributeValue(const QString &varName, const QString &attrName, const T &value); template <typename T> void setGblAttributeValue(const QString &attrName, const T &value); /*! * \brief getMsgCount 获取所有报文数据 * \retval 所有报文数据 */ qint32 getMsgCount() const { return msgList.size(); } /*! * \brief GetMsgList 获取所有报文 * \retval 所有报文 */ const QList<Message*> &GetMsgList() const { return msgList; } /*! * \brief onParseDone 解析器解析完成的时候,需要调用一次 */ void onParseDone(); private: Version version; //!< 版本号 NS ns; //!< 所有NS(New Symbol) BS bs; //!< 位定时参数 NodeMap nodeMap; //!< 所有节点 ValueTableMap valueTableMap; //!< 值表 EVMap evMap; //!< 基本类型环境变量 EVDataMap evDataMap; //!< 二进制值类型环境变量 DefaultAttrTblMap defaultAttrTblMap; //!< 默认值表(也起类型值表的功能) NodeAttrTblMap nodeAttrTblMap; //!< 所有网络节点的属性表 EVAttrTblMap evAttrTblMap; //!< 所有环境变量的属性表 MsgAttrTblMap msgAttrTblMap; //!< 所有报文的属性表 SigAttrTablMap sigAttrTblMap; //!< 所有信号的属性表 QList<Message*> msgList; //!< 保存所有报文 }; template <typename T> void Document::setNodeAttributeValue(const QString &nodeName, const QString &attrName, const T &value) { auto tblIter = nodeAttrTblMap.find(nodeName); if (tblIter != nodeAttrTblMap.end()) { auto &tbl = tblIter.value(); auto attrVal = tbl.getAdditionalAttribute(attrName); if (attrVal != NULL) { attrVal->setValue(value); } else { auto iter = defaultAttrTblMap.find(OBJECT_TYPE_BU); if (iter != defaultAttrTblMap.end()) { AdditionalAttribute *defaultAttr = iter.value().getAdditionalAttribute(attrName); if (defaultAttr) { AdditionalAttribute attr = *defaultAttr; attr.setValue(value); tbl.addAdditionalAttribute(attrName, attr); } } } } else { auto iter = defaultAttrTblMap.find(OBJECT_TYPE_BU); if (iter != defaultAttrTblMap.end()) { AdditionalAttribute *defaultAttr = iter.value().getAdditionalAttribute(attrName); if (defaultAttr) { AdditionalAttributeTable tbl; AdditionalAttribute attr = *defaultAttr; attr.setValue(value); tbl.addAdditionalAttribute(attrName, attr); nodeAttrTblMap.insert(nodeName, tbl); } } } } template<typename T> void Document::setMsgAttributeValue(qint32 msgId, const QString &attrName, const T &value) { auto tblIter = msgAttrTblMap.find(msgId); if (tblIter != msgAttrTblMap.end()) { auto &tbl = tblIter.value(); auto attrVal = tbl.getAdditionalAttribute(attrName); if (attrVal != NULL) { attrVal->setValue(value); } else { auto iter = defaultAttrTblMap.find(OBJECT_TYPE_BO); if (iter != defaultAttrTblMap.end()) { AdditionalAttribute *defaultAttr = iter.value().getAdditionalAttribute(attrName); if (defaultAttr) { AdditionalAttribute attr = *defaultAttr; attr.setValue(value); tbl.addAdditionalAttribute(attrName, attr); } } } } else { auto iter = defaultAttrTblMap.find(OBJECT_TYPE_BO); if (iter != defaultAttrTblMap.end()) { AdditionalAttribute *defaultAttr = iter.value().getAdditionalAttribute(attrName); if (defaultAttr) { AdditionalAttributeTable tbl; AdditionalAttribute attr = *defaultAttr; attr.setValue(value); tbl.addAdditionalAttribute(attrName, attr); msgAttrTblMap.insert(msgId, tbl); } } } } template<typename T> void Document::setSigAttributeValue(qint32 msgId, const QString &sigName, const QString &attrName, const T &value) { Signal *signal = getSignal(msgId, sigName); if (NULL == signal) return; auto tblIter = sigAttrTblMap.find(signal); if (tblIter != sigAttrTblMap.end()) { auto &tbl = tblIter.value(); auto attrVal = tbl.getAdditionalAttribute(attrName); if (attrVal != NULL) { attrVal->setValue(value); } else { auto iter = defaultAttrTblMap.find(OBJECT_TYPE_SG); if (iter != defaultAttrTblMap.end()) { AdditionalAttribute *defaultAttr = iter.value().getAdditionalAttribute(attrName); if (defaultAttr) { AdditionalAttribute attr = *defaultAttr; attr.setValue(value); tbl.addAdditionalAttribute(attrName, attr); } } } } else { auto iter = defaultAttrTblMap.find(OBJECT_TYPE_SG); if (iter != defaultAttrTblMap.end()) { AdditionalAttribute *defaultAttr = iter.value().getAdditionalAttribute(attrName); if (defaultAttr) { AdditionalAttributeTable tbl; AdditionalAttribute attr = *defaultAttr; attr.setValue(value); tbl.addAdditionalAttribute(attrName, attr); sigAttrTblMap.insert(signal, tbl); } } } } template<typename T> void Document::setEvAttributeValue(const QString &varName, const QString &attrName, const T &value) { auto tblIter = evAttrTblMap.find(varName); if (tblIter != evAttrTblMap.end()) { auto &tbl = tblIter.value(); auto attrVal = tbl.getAdditionalAttribute(attrName); if (attrVal != NULL) { attrVal->setValue(value); } else { auto iter = defaultAttrTblMap.find(OBJECT_TYPE_EV); if (iter != defaultAttrTblMap.end()) { AdditionalAttribute *defaultAttr = iter.value().getAdditionalAttribute(attrName); if (defaultAttr) { AdditionalAttribute attr = *defaultAttr; attr.setValue(value); tbl.addAdditionalAttribute(attrName, attr); } } } } else { auto iter = defaultAttrTblMap.find(OBJECT_TYPE_EV); if (iter != defaultAttrTblMap.end()) { AdditionalAttribute *defaultAttr = iter.value().getAdditionalAttribute(attrName); if (defaultAttr) { AdditionalAttributeTable tbl; AdditionalAttribute attr = *defaultAttr; attr.setValue(value); tbl.addAdditionalAttribute(attrName, attr); evAttrTblMap.insert(varName, tbl); } } } } template<typename T> void Document::setGblAttributeValue(const QString &attrName, const T &value) { auto iter = defaultAttrTblMap.find(OBJECT_TYPE_GL); if (iter != defaultAttrTblMap.end()) { auto &tbl = iter.value(); auto attrVal = tbl.getAdditionalAttribute(attrName); if (attrVal != NULL) { attrVal->setValue(value); } } } END_DBC4CPP_NAMESPACE #endif // ENTITIES_H
TwoFlyLiu/ecanspy3
ecanspy3/receive/receivemessagefilterproxymodel.h
#ifndef RECEIVEMESSAGEFILTERPROXYMODEL_H #define RECEIVEMESSAGEFILTERPROXYMODEL_H #include <QSortFilterProxyModel> #include <QList> #include "filtertablemodel.h" class ReceiveMessageFilterProxyModel : public QSortFilterProxyModel { Q_OBJECT public: ReceiveMessageFilterProxyModel(QObject *parent=nullptr); void setFilterList(QList<FilterTableModel::Entity> * filterList); void refilter(); // QSortFilterProxyModel interface protected: bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; private: QList<FilterTableModel::Entity> *filterList; }; #endif // RECEIVEMESSAGEFILTERPROXYMODEL_H
TwoFlyLiu/ecanspy3
ecanspy3/utils/scrollingfile.h
#ifndef SCROLLINGFILE_H #define SCROLLINGFILE_H #include <QFile> class ScrollingFile { public: enum { DEFAULT_SINGILE_FILE_COUNT = 40 * 1024 * 1024 //!< 单位字节 }; enum FileNameRule { FILE_NAME_RULE_ID_INC = 0, //!< 以ID递增方式 }; ScrollingFile(QString filePath, int maxFileSize = DEFAULT_SINGILE_FILE_COUNT, FileNameRule rule = FILE_NAME_RULE_ID_INC); ~ScrollingFile(); qint64 write(const char *data, qint64 maxSize); qint64 write(const char *data); qint64 write(const QByteArray &byteArray); void close(); void flush(); void setMaxFileSize(int maxFileSize) { this->maxFileSize = maxFileSize; } int getMaxFileSize() const { return this->maxFileSize; } void setFileNameRule(FileNameRule rule) { this->rule = rule; } FileNameRule getFileNameRule() const { return this->rule; } protected: void generateNextFile(); QString generateNextFileName(); private: QFile *file = nullptr; QString fileName; QString extName; QString dirName; FileNameRule rule; int maxFileSize; int id = 0; }; #endif // SCROLLINGFILE_H
algisb/vkRend
src/DbgPrint.h
<reponame>algisb/vkRend #pragma once #include <stdarg.h> #define ENABLE_DBG_PRINT #ifdef ENABLE_DBG_PRINT #define dbgPrint(_str, ...)\ {\ printf(_str, ##__VA_ARGS__);\ } #else #define dbgPrint(_str, ...) #endif
algisb/vkRend
src/VkWrapper.h
#pragma once #include <vector> #include <vulkan/vulkan.h> struct SDL_Window; class VkWrapper { public: const std::vector<const char*> validationLayers = { "VK_LAYER_KHRONOS_validation" }; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; #endif VkWrapper(); ~VkWrapper(); void init(SDL_Window* window); void deinit(); private: VkInstance instance; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; void createInstance(SDL_Window* window); bool checkValidationLayerSupport(); void pickPhysicalDevice(); bool isDeviceSuitable(VkPhysicalDevice device); struct QueueFamilyIndices { QueueFamilyIndices() = default; ~QueueFamilyIndices() { if(graphicsFamily != nullptr) { delete graphicsFamily; } } bool isComplete() { return graphicsFamily != nullptr; } uint32_t* graphicsFamily = nullptr; }; QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device); };
devium/redis-devium
protocol/redis.h
#pragma once #include <string> #include <vector> #include <cstdint> #include <boost/variant.hpp> #include "reader.h" #include "writer.h" #include "configs.h" struct RedisError { explicit RedisError(const std::string& msg) : msg(msg) {} std::string msg; }; struct RedisNull {}; struct RedisBulkString { explicit RedisBulkString(const std::string& str) : container(str) {} std::string container; }; typedef boost::make_recursive_variant< RedisNull , int64_t , std::string , RedisBulkString , RedisError , std::vector<boost::recursive_variant_> >::type RedisValue; enum FirstChar { INT_CHAR = ':', STRING_CHAR = '+', BULK_STRING_CHAR = '$', ERROR_CHAR = '-', ARRAY_CHAR = '*' }; void WriteRedisValue(Writer* w, const RedisValue& value); void ReadRedisValue(Reader* r, RedisValue* value);
devium/redis-devium
server/HashTable.h
<reponame>devium/redis-devium<gh_stars>0 #pragma once #include <unordered_map> #include <protocol/redis.h> typedef std::unordered_map<std::string, RedisValue> RedisHashTable; class HashTable { private: RedisHashTable table_; public: HashTable(); HashTable(RedisHashTable hashTable); RedisHashTable * getTable(); };
devium/redis-devium
server/Cmd.h
#pragma once #include <protocol/redis.h> #include "HashTable.h" #include "configs.h" class Cmd { protected: cmd name_; HashTable* redisHashTable_; public: Cmd(cmd name, HashTable * hashTable); cmd getName(); }; class Setter : public Cmd { public: Setter(HashTable * hashTable); using Cmd::getName; RedisValue exec(RedisValue& args); }; class Getter : public Cmd { public: Getter(HashTable * hashTable); using Cmd::getName; RedisValue exec(RedisValue& args); };
devium/redis-devium
configs.h
#pragma once constexpr size_t MAX_STRING_SIZE_ = 1024 * 1024; constexpr size_t MAX_STRING_LEN_ = 1 << 15; enum cmd {SET, GET}; enum RedisType { REDIS_NULL, REDIS_INT, REDIS_STRING, REDIS_BULK_STRING, REDIS_ERROR, REDIS_ARRAY };
devium/redis-devium
server/Listener.h
<gh_stars>0 #pragma once #include <memory> #include <stdlib.h> #include <netinet/in.h> #include <tclDecls.h> #include <sys/errno.h> #include "Socket.h" class Listener { private: int socketDescriptor_; int port_; const int max_port_ = 1 << 16 - 1; const int min_port_ = 0; void bindSocket(); void setSocketOptions(); public: Listener(int port); std::unique_ptr<Socket> accept(); void listenSocket(int amountOfConnections); ~Listener(); };
devium/redis-devium
protocol/reader.h
<reponame>devium/redis-devium #pragma once #include <vector> #include <string> #include <stdexcept> #include "configs.h" class Reader { public: explicit Reader(size_t bufferSize) : buffer_(bufferSize) {} char readChar(); std::string readLine(); std::string readRaw(size_t len); int64_t readInt(); protected: std::vector<char> buffer_; size_t end_ = 0, rpos_ = 0; virtual void readMore() = 0; }; class StringReader : public Reader { public: explicit StringReader(size_t bufferSize = 1024) : Reader(bufferSize) {} std::string input; virtual void readMore() override; };
devium/redis-devium
server/Server.h
<gh_stars>0 #pragma once #include <gtest/gtest.h> class Server { public: Server(); void listen(); void serve(int maxAccept = -1); virtual void handle(int conn) = 0; };
devium/redis-devium
server/Socket.h
<filename>server/Socket.h #pragma once #include <unistd.h> #include <string> class Socket { private: int socketDescriptor_; public: Socket(int socketDescriptor); ~Socket(); int getSocketDescriptor(); std::string readData(size_t size); void writeData(std::string data); };
devium/redis-devium
protocol/writer.h
<filename>protocol/writer.h #pragma once #include <vector> #include <string> class Writer { public: explicit Writer(size_t bufferSize) : buffer_(bufferSize) {} void writeString(const std::string &s); void writeRaw(const char *s, size_t len); void writeInt(int64_t i); void writeChar(char c); void writeCrlf(); virtual void flush() = 0; virtual void checkBuffer() = 0; protected: std::vector<char> buffer_; int wpos_ = 0; }; class StringWriter : public Writer { public: explicit StringWriter(size_t bufferSize = 1024) : Writer(bufferSize) {} std::string result; virtual void flush() override; virtual void checkBuffer() override; };
yksz/cpp-logger
src/loggerconf.h
#pragma once namespace logger { /** * Configure a logger with a configuration file. * If the filename is nullptr, return without doing anything. * * The following is the configurable key/value list. * |key |value | * |:--------------------------|:--------------------------------------------| * |level |TRACE, DEBUG, INFO, WARN, ERROR or FATAL | * |logger |console or file | * |logger.console.output |stdout or stderr | * |logger.file.filename |A output filename | * |logger.file.maxFileSize |1-LONG_MAX [bytes] (1 MB if size <= 0) | * |logger.file.maxBackupFiles |0-255 | * * @param[in] filename The name of the configuration file * @return true upon success or false on error */ bool Configure(const char* filename); } // namespace logger
yksz/cpp-logger
src/logger.h
<filename>src/logger.h #pragma once #include <cstdint> #include <cstdio> #include <cstring> #if defined(_WIN32) || defined(_WIN64) #define __FILENAME__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__) #else #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) #endif // defined(_WIN32) || defined(_WIN64) #define LOG_TRACE(fmt, ...) logger::Log(logger::LogLevel_TRACE, __FILENAME__, __LINE__, fmt, ##__VA_ARGS__) #define LOG_DEBUG(fmt, ...) logger::Log(logger::LogLevel_DEBUG, __FILENAME__, __LINE__, fmt, ##__VA_ARGS__) #define LOG_INFO(fmt, ...) logger::Log(logger::LogLevel_INFO , __FILENAME__, __LINE__, fmt, ##__VA_ARGS__) #define LOG_WARN(fmt, ...) logger::Log(logger::LogLevel_WARN , __FILENAME__, __LINE__, fmt, ##__VA_ARGS__) #define LOG_ERROR(fmt, ...) logger::Log(logger::LogLevel_ERROR, __FILENAME__, __LINE__, fmt, ##__VA_ARGS__) #define LOG_FATAL(fmt, ...) logger::Log(logger::LogLevel_FATAL, __FILENAME__, __LINE__, fmt, ##__VA_ARGS__) namespace logger { enum LogLevel : uint8_t { LogLevel_TRACE, LogLevel_DEBUG, LogLevel_INFO, LogLevel_WARN, LogLevel_ERROR, LogLevel_FATAL, }; bool InitConsoleLogger(FILE* output = stdout); bool InitFileLogger(const char* filename, int64_t maxFileSize, uint8_t maxBackupFiles); void SetLevel(LogLevel level); LogLevel GetLevel(); bool IsEnabled(LogLevel level); void Log(LogLevel level, const char* file, uint32_t line, const char* fmt, ...); } // namespace logger
bolero-MURAKAMI/KTL
projects/msvc11/functor/ktl_rc_version.h
<reponame>bolero-MURAKAMI/KTL /*============================================================================= Copyright (c) 2010-3015 <NAME> https://github.com/bolero-MURAKAMI/KTL Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef PROJECTS_KTL_RC_VERSION_H #define PROJECTS_KTL_RC_VERSION_H #define KTL_RC_PROJECT_NAME "functor" #define KTL_RC_MODULE_NAME "Functor" #define KTL_RC_VERSION 0,2,14,0 #define KTL_RC_TARGET "KiriKiri 2.32rev2 core" #define KTL_RC_COMPILER "Microsoft Visual C++ version 11.0" #define KTL_RC_USELIB_0 "Windows SDK 7.1" #define KTL_RC_USELIB_1 "Boost 1.59" #endif // #ifndef PROJECTS_KTL_RC_VERSION_H
bolero-MURAKAMI/KTL
ktl/rc/version.h
/*============================================================================= Copyright (c) 2010-2015 <NAME> https://github.com/bolero-MURAKAMI/KTL Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef KTL_RC_VERSION_H #define KTL_RC_VERSION_H #include <WinVer.h> #ifndef KTL_RC_PROJECT_NAME # error Requires: define KTL_RC_PROJECT_NAME #endif // #ifndef KTL_RC_PROJECT_NAME #ifndef KTL_RC_MODULE_NAME # error Requires: define KTL_RC_MODULE_NAME #endif // #ifndef KTL_RC_MODULE_NAME #ifndef KTL_RC_VERSION # define KTL_RC_VERSION 0,0,0,0 #endif // #ifndef KTL_RC_VERSION #define KTL_FULL_PROJECT_NAME "ktl_" KTL_RC_PROJECT_NAME #define KTL_FULL_MODULE_NAME "KTL." KTL_RC_MODULE_NAME #ifdef NDEBUG # define KTL_COMMENTS_BUILD "(Release)" #else #define KTL_COMMENTS_BUILD "(Debug)" #endif #if defined(KTL_RC_TARGET) # define KTL_COMMENTS_TARGET "(" KTL_RC_TARGET ")" #else # define KTL_COMMENTS_TARGET "(Unknown)" #endif #if defined(KTL_RC_COMPILER) # define KTL_COMMENTS_COMPILER "(" KTL_RC_COMPILER ")" #else # define KTL_COMMENTS_COMPILER "(Unknown)" #endif #if defined(KTL_RC_USELIB_0) # define KTL_COMMENTS_USELIB_0 "(" KTL_RC_USELIB_0 ")" #else # define KTL_COMMENTS_USELIB_0 "" #endif #if defined(KTL_RC_USELIB_1) # define KTL_COMMENTS_USELIB_1 "(" KTL_RC_USELIB_1 ")" #else # define KTL_COMMENTS_USELIB_1 "" #endif #if defined(KTL_RC_USELIB_2) # define KTL_COMMENTS_USELIB_2 "(" KTL_RC_USELIB_2 ")" #else # define KTL_COMMENTS_USELIB_2 "" #endif #if defined(KTL_RC_USELIB_3) # define KTL_COMMENTS_USELIB_3 "(" KTL_RC_USELIB_3 ")" #else # define KTL_COMMENTS_USELIB_3 "" #endif #if defined(KTL_RC_USELIB_4) # define KTL_COMMENTS_USELIB_4 "(" KTL_RC_USELIB_4 ")" #else # define KTL_COMMENTS_USELIB_4 "" #endif #if defined(KTL_RC_USELIB_5) # define KTL_COMMENTS_USELIB_5 "(" KTL_RC_USELIB_5 ")" #else # define KTL_COMMENTS_USELIB_5 "" #endif #if defined(KTL_RC_USELIB_6) # define KTL_COMMENTS_USELIB_6 "(" KTL_RC_USELIB_6 ")" #else # define KTL_COMMENTS_USELIB_6 "" #endif #if defined(KTL_RC_USELIB_7) # define KTL_COMMENTS_USELIB_7 "(" KTL_RC_USELIB_7 ")" #else # define KTL_COMMENTS_USELIB_7 "" #endif #if defined(KTL_RC_USELIB_8) # define KTL_COMMENTS_USELIB_8 "(" KTL_RC_USELIB_8 ")" #else # define KTL_COMMENTS_USELIB_8 "" #endif #if defined(KTL_RC_USELIB_9) # define KTL_COMMENTS_USELIB_9 "(" KTL_RC_USELIB_9 ")" #else # define KTL_COMMENTS_USELIB_9 "" #endif #define KTL_COMMENTS_LIBRARIES KTL_COMMENTS_USELIB_0 \ KTL_COMMENTS_USELIB_1 \ KTL_COMMENTS_USELIB_2 \ KTL_COMMENTS_USELIB_3 \ KTL_COMMENTS_USELIB_4 \ KTL_COMMENTS_USELIB_5 \ KTL_COMMENTS_USELIB_6 \ KTL_COMMENTS_USELIB_7 \ KTL_COMMENTS_USELIB_8 \ KTL_COMMENTS_USELIB_9 #define KTL_STRINGIZE_I(TEXT) #TEXT #define KTL_STRINGIZE(TEXT) KTL_STRINGIZE_I(TEXT) #define KTL_FILEVERSION KTL_RC_VERSION #define KTL_PRODUCTVERSION KTL_RC_VERSION #define KTL_FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #ifdef NDEBUG #define KTL_FILEFLAGS (0x0L | VS_FF_PRERELEASE) #else #define KTL_FILEFLAGS (0x0L | VS_FF_PRERELEASE | VS_FF_DEBUG) #endif #define KTL_FILEOS VOS_NT_WINDOWS32 #define KTL_FILETYPE VFT_DLL #define KTL_FILESUBTYPE VFT2_UNKNOWN #define KTL_COMMENTS KTL_FULL_MODULE_NAME \ " " KTL_STRINGIZE(KTL_RC_VERSION) "\n" \ " " KTL_COMMENTS_BUILD "\n" \ " / Target: " KTL_COMMENTS_TARGET "\n" \ " / Compiler: " KTL_COMMENTS_COMPILER "\n" \ " / Libraries: " KTL_COMMENTS_LIBRARIES "\n" \ "\0" #define KTL_COMPANY_NAME "<NAME>\0" #define KTL_FILE_DESCRIPTION KTL_FULL_MODULE_NAME " (KiriKiri Plug-in DLL)\0" #define KTL_FILE_VERSION KTL_STRINGIZE(KTL_RC_VERSION) "\0" #define KTL_INTERNAL_NAME KTL_FULL_PROJECT_NAME "\0" #define KTL_LEGAL_COPYRIGHT "Copyright (C) 2009-2015 <NAME>.\0" #define KTL_LEGAL_TRADEMARKS "\0" #ifdef NDEBUG # define KTL_ORIGINAL_FILENAME KTL_FULL_PROJECT_NAME ".dll\0" #else # define KTL_ORIGINAL_FILENAME KTL_FULL_PROJECT_NAME "-d.dll\0" #endif #define KTL_PRODUCT_NAME KTL_FULL_MODULE_NAME "\0" #define KTL_PRODUCT_VERSION KTL_STRINGIZE(KTL_RC_VERSION) "\0" #define KTL_PRIVATE_BUILD "\0" #define KTL_SPECIAL_BUILD "\0" #endif // #ifndef KTL_RC_VERSION_H
Jmin17/Random-Class-C-
Random.h
<gh_stars>0 #pragma once #ifndef RANDOM_CLASS #define RANDOM_CLASS #include <random> #include <memory> class Random { public: Random(); Random(int minIntVal, int maxIntVal); int nextInt(); int nextInt(int minVal, int maxVal); void setIntRange(int minVal, int maxVal); double nextDouble(); void setDoubleRange(double minVal, double maxVal); private: static std::random_device seeder; static std::shared_ptr<std::mt19937> engine; std::shared_ptr<std::uniform_int_distribution <int>> disInt; std::shared_ptr<std::uniform_real_distribution <double>> disReal; }; #endif
iYeso/TextureTangram
TextureTangram/Core/Build-in Layouts/1+N/TangramOnePlusLayoutComponent.h
<reponame>iYeso/TextureTangram<gh_stars>1-10 // Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "TangramLayoutComponent.h" /** 1+N 布局 */ @interface TangramOnePlusLayoutComponent : TangramLayoutComponent @property (nonatomic, copy) NSArray *rowPartitions; ///< 右方的行高比例;最终的高度是左边的item定的 @property (nonatomic) double aspectRatio; ///< 整体宽高比 /** //TODO:设定宽度比例,内容是百分比的数字。下面的1,2,3,4,5 指代第N个组件,具体可看样例图组件上的数字。三个组件时:1:2;四个组件:1:2:3:4;五个组件时:1:2:3:4:5 */ @property (nonatomic, copy) NSArray *cols; @end
iYeso/TextureTangram
TextureTangram/Core/Build-in Layouts/Inline Layout/Base/TangramInlineLayoutComponent.h
// // TangramInlineLayoutComponent.h // TextureTangram // // Created by 廖超龙 on 2018/8/23. // Copyright © 2018年 ZZinKin. All rights reserved. // #import "TangramLayoutComponent.h" #import "TangramInlineCellInfo.h" @interface TangramInlineLayoutComponent : TangramLayoutComponent @property (nonatomic) CGRect inlineCellFrame; @property (nonatomic, strong, nonnull) TangramInlineCellInfo *inlineModel; ///自动初始化一个inlineModel - (nonnull Class)inlineNodeClass; @end
iYeso/TextureTangram
TextureTangram/Core/Build-in Layouts/Grid Layout/TangramGridLayoutComponet.h
// Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "TangramLayoutComponent.h" @interface TangramGridLayoutComponet : TangramLayoutComponent @property (nonatomic) NSUInteger maximumColumn; ///< 最大列数,默认1 @property (nonatomic) double rowAspectRatio; ///< 每一行宽高比; 对应aspectRatio @property (nonatomic) CGFloat verticalInterItemsSpace; ///< 垂直方向每个组件的间距;vGap @property (nonatomic) CGFloat horizontalInterItemsSpace; ///< 垂直方向每个组件的距离; hGap ///每列的百分比,如果是N列,可以只写Array中只写N-1项,最后一项会自动填充,如果加一起大于100,就按照填写的来算;示例: ["30","30"] 或 [30",30] @property (nonatomic) NSArray<NSNumber *> *columnPartitions; @end
iYeso/TextureTangram
TextureTangram/Core/Data Source Helper/TangramDefaultDataSourceHelper.h
// // TangramDefaultDataSourceHelper.h // TextureTangram // // Created by 廖超龙 on 2018/10/19. // Copyright © 2018年 ZZinKin. All rights reserved. // #import "TangramLayoutComponent.h" @interface TangramDefaultDataSourceHelper : NSObject /** 根据json数据创建TangramLayoutComponent数组 @param contents json转化的数组,需要去null处理 */ - (NSMutableArray<TangramLayoutComponent *> *)layoutComponentsForContents:(NSArray *)contents; @end
iYeso/TextureTangram
TextureTangram/Utils/NSTimer+Compatible.h
// Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> @interface NSTimer (SmartUtils) #if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_10_0 + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block ; + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block; #endif /** @param shouldUseProxy 使用代理转发,避免循环引用 @param runloopMode runloop模式 */ + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo useProxy:(BOOL)shouldUseProxy runloopMode:(NSRunLoopMode)runloopMode; - (void)tan_pause; - (void)tan_resume; - (void)tan_resumeAfterTimeInterval:(NSTimeInterval)interval; @end
iYeso/TextureTangram
TextureTangram/Demo/Hardcoded Demo/DemoViewController.h
// // DemoViewController.h // TextureTangram // // Created by cello on 2018/8/23. // Copyright © 2018年 ZZinKin. All rights reserved. // #import <AsyncDisplayKit/AsyncDisplayKit.h> @interface DemoViewController : ASViewController @end
iYeso/TextureTangram
TextureTangram/Core/Build-in Layouts/Inline Layout/Carousel(Banner)/TangramPageControl.h
/// Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <AsyncDisplayKit/AsyncDisplayKit.h> @interface TangramPageControl : ASDisplayNode /** 创建一个页码指示器的实例 @param imageURL 正常状态的图片地址(后面拼接比例) @param highlightedImageURL 高亮状态的图片地址(后面拼接比例) @param interItemSpace pageCtrl标识点之间的间距 @param itemCount 标识点的数目 */ - (instancetype)initWithItemImageURL:(NSString *)imageURL highlightedImageURL:(NSString *)highlightedImageURL interItemSpace:(CGFloat)interItemSpace itemCount:(NSUInteger)itemCount; @property (nonatomic) NSInteger currentIndex; @end
iYeso/TextureTangram
TextureTangram/Core/Base/TangramLayoutComponent.h
// Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> #import "TangramComponentDescriptor.h" #import <AsyncDisplayKit/ASSectionContext.h> NS_ASSUME_NONNULL_BEGIN /** 类似tableView header吸顶、footer吸底的效果 */ typedef NS_ENUM(NSUInteger, TangramLayoutComponentPinnedType) { TangramLayoutComponentPinnedTypeNone = 0, ///< 正常布局 TangramLayoutComponentPinnedTypeTop, ///< 吸顶;目前只支持一个吸顶布局 TangramLayoutComponentPinnedTypeBottom, ///< 吸底,目前没有实现 }; /** 对应tangram的内置布局;类似collectionView的section 添加一种layout类型需要继承它 */ @interface TangramLayoutComponent : NSObject <ASSectionContext> @property CGPoint layoutOrigin; ///< 布局的起点 @property CGFloat width; ///< 布局宽度 @property CGFloat height; ///< 整个布局的高度;调用computeLayoutsWithOrigin会改变此属性 @property (nonatomic) BOOL isInlineLayout; ///<是否为内联布局 @property (nonatomic) UIEdgeInsets margin; ///< layout的外边距会控制background、header的范围; margin @property (nonatomic) UIEdgeInsets insets; ///< layout的内边距,控制items与header、footer之间的边距;对应padding @property (nonatomic) BOOL isFloatingLayout; ///< 是否为固定布局/浮动布局; 不应该放到TangramCollectionViewLayout里面参与布局计算 @property (nonatomic) TangramLayoutComponentPinnedType pinnedType; ///< 是否有吸顶/吸底效果 @property (nonatomic) CGFloat fixHeight; ///< 设置大于0的值,调用height只能获取到fixHeight /// 整个layout的头部描述信息,布局在items上方,不能为空 @property (nonatomic, strong, nonnull) TangramComponentDescriptor *headerInfo; /// 整个layout尾部信息,布局在items下方,不能为空 @property (nonatomic, strong, nonnull) TangramComponentDescriptor *footerInfo; /// 背景图片地址 @property (nonatomic, strong, nullable) NSString *backgroundImageURL; /// 背景颜色 @property (nonatomic, strong, nullable) UIColor *backgroundColor; /// 布局项,对应cell @property (nonatomic, strong, nonnull) NSArray<TangramComponentDescriptor*> *itemInfos; @property (nonatomic) UIEdgeInsets edgeInsets; ///< 整个layout的边距;需要注意附近的layout也可能会设置 /** * Custom name of this section, for debugging only. */ @property (nonatomic, copy, nullable) NSString *sectionName; @property (nonatomic, weak, nullable) ASCollectionView *collectionView; /** 重写此方法重新计算布局;得到的高度信息会缓存到height属性 */ - (void)computeLayoutsWithOrigin:(CGPoint)origin width:(CGFloat)width; @end NS_ASSUME_NONNULL_END
iYeso/TextureTangram
TextureTangram/Utils/NSArray+TangramParse.h
// // NSArray+TangramParse.h // TextureTangram // // Created by 廖超龙 on 2018/10/19. // Copyright © 2018年 ZZinKin. All rights reserved. // #import <UIKit/UIKit.h> @interface NSArray (TangramParse) - (UIEdgeInsets)parseInsets; /** 递归地移除所有的属性 @return 一个新的NSArray对象 */ - (NSArray *)tan_removeNullValues; @end
iYeso/TextureTangram
TextureTangram/Utils/TANWeakProxy.h
<gh_stars>1-10 // Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> @interface TANWeakProxy : NSProxy /** The proxy target. */ @property (nonatomic, weak, readonly) id target; /** Creates a new weak proxy for target. @param target Target object. @return A new proxy object. */ - (instancetype)initWithTarget:(id)target; /** Creates a new weak proxy for target. @param target Target object. @return A new proxy object. */ + (instancetype)proxyWithTarget:(id)target; @end
iYeso/TextureTangram
TextureTangram/Utils/NSDictionary+TangramParse.h
<reponame>iYeso/TextureTangram<filename>TextureTangram/Utils/NSDictionary+TangramParse.h<gh_stars>1-10 // // NSDictionary+TangramParse.h // TextureTangram // // Created by 廖超龙 on 2018/10/19. // Copyright © 2018年 ZZinKin. All rights reserved. // #import <Foundation/Foundation.h> @interface NSDictionary (TangramParse) /** 递归地移除所有的属性 @return 一个新的NSDictionary对象 */ - (NSDictionary *)tan_removeNullValues; @end
iYeso/TextureTangram
TextureTangram/Utils/NSObject+SafeKVO.h
<reponame>iYeso/TextureTangram // // NSObject+SafeKVO.h // TextureTangram // // Created by 廖超龙 on 2018/10/18. // Copyright © 2018年 ZZinKin. All rights reserved. // #import <Foundation/Foundation.h> @interface NSObject (SafeKVO) /** Registers a block to receive KVO notifications for the specified key-path relative to the receiver. @discussion The block and block captured objects are retained. Call `removeObserverBlocksForKeyPath:` or `removeObserverBlocks` to release. @param keyPath The key path, relative to the receiver, of the property to observe. This value must not be nil. @param block The block to register for KVO notifications. */ - (void)tan_addObserverBlockForKeyPath:(NSString*)keyPath block:(void (^)(id _Nonnull obj, id _Nonnull oldVal, id _Nonnull newVal))block; /** Stops all blocks (associated by `addObserverBlockForKeyPath:block:`) from receiving change notifications for the property specified by a given key-path relative to the receiver, and release these blocks. @param keyPath A key-path, relative to the receiver, for which blocks is registered to receive KVO change notifications. */ - (void)tan_removeObserverBlocksForKeyPath:(NSString*)keyPath; /** Stops all blocks (associated by `addObserverBlockForKeyPath:block:`) from receiving change notifications, and release these blocks. */ - (void)tan_removeObserverBlocks; @end
iYeso/TextureTangram
TextureTangram/Core/Base/TangramComponentDescriptor.h
<gh_stars>1-10 // Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> /** 一个实体控件(如卡片、header、footer)的描述信息;不能看作一个Model,实际上它与控件是一一对应的 类似于UICollectionViewLayoutAttributes */ @interface TangramComponentDescriptor: NSObject @property UIEdgeInsets insets; ///< 内边距 @property (strong) NSString *type; ///< UI组件的类型 @property CGRect frame; ///< 布局的frame,未完成布局之前,使用此属性会不准确 @property CGFloat width; ///< 控件的宽度,第一次布局的时候会设置这个属性。 @property CGFloat expectedHeight; - (Class)nodeClass; ///< 对应的控件类名;默认TangramItemNode - (CGFloat)computeHeightWithWidth:(CGFloat)width; ///< 自计算高度;会影响expectedHeight属性 @end
iYeso/TextureTangram
TextureTangram/Core/Base/TangramCollectionViewLayout.h
<filename>TextureTangram/Core/Base/TangramCollectionViewLayout.h<gh_stars>1-10 // Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> #import "TangramLayoutComponent.h" #import <AsyncDisplayKit/AsyncDisplayKit.h> extern NSString *const TangramCollectionViewBackgroundDecoratedKind; extern NSString *const TangramCollectionViewSupplementaryKindHeader; extern NSString *const TangramCollectionViewSupplementaryKindFooter; /// 要是写自定义layout,直接调用 self.collectionView.delegate 来获取布局大小等等信息; /// collectionNode 会使用 rangeController和DataController进行优化(但是有限)。先看看用flowlayout实现效果如何 @interface TangramCollectionViewLayout : UICollectionViewLayout @property (nonatomic) CGFloat cacheHeight; @property (nonatomic, strong) NSArray<TangramLayoutComponent *> *layoutComponents; @property (nonatomic, weak) ASCollectionNode *collectionNode; @property (nonatomic, strong) ASDisplayNode *stickyNode; @property (nonatomic, strong, readonly) NSNumber *stickyIndex; //@property (nonatomic, strong) NSMutableDictionary *cellAttributes; //@property (nonatomic, strong) NSMutableDictionary *supplementaryViewAttributes; //@property (nonatomic, strong) NSMutableDictionary *decoratedViewAttributes; - (void)layouStickyNode; @end
iYeso/TextureTangram
TextureTangram/Core/Build-in Layouts/Inline Layout/Carousel(Banner)/TangramCarouselInlineLayoutComponent.h
/// Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <AsyncDisplayKit/AsyncDisplayKit.h> #import "TangramInlineLayoutComponent.h" #import "TangramPageControl.h" /// 滚动图布局 @interface TangramCarouselInlineLayoutComponent : TangramInlineLayoutComponent <ASPagerDataSource, ASPagerDelegate> @property (nonatomic, weak) ASPagerNode *pageNode; @property (nonatomic, weak) TangramPageControl *pageControl; /** 页之间的间距 */ @property (nonatomic) CGFloat horizontalInterItemsSpace; /** 内部 View 的宽高比,宽度按满屏幕根据ratio计算高度, 建议设置此属性,可预先占位,避免 Banner 有一个高度撑开的过程 */ @property (nonatomic) CGFloat itemRatio; /** 内部 View 宽度占总屏幕宽度的比例,如内部 View 宽度为 120,屏幕宽为750, 则此值是 120/750=0.16 */ @property (nonatomic) CGFloat pageRatio; /** 自动滚动的间隔,单位毫秒,填写数字大于0就开始自动滚动,默认值0 */ @property (nonatomic) NSInteger autoScroll; /** 指示器选中状态的图片,必须带图片宽高比后缀 */ @property (nonatomic, copy) NSString *indicatorImg1; /**ß 指示器未被选中状态的图片,必须带图片宽高比后缀 */ @property (nonatomic, copy) NSString *indicatorImg2; /** 指示器位置,居中居左还是居右; "left"/"right"/"center" */ @property (nonatomic, copy) NSString *indicatorGravity; /** 指示器位置,在内部还是在外部; 默认内部,暂不支持外部; "inside"/"outside" */ @property (nonatomic, copy) NSString *indicatorPosition; /** 单独指定每一帧的自动滚动的间隔,单位毫秒,key从0开始计数; 与autoScroll配合使用,当未在此声明某一帧的停留时间的时候, 使用autoScroll指定的间隔,否则使用此处声明的间隔时间(暂时不支持) */ @property (nonatomic, strong) NSDictionary *specialInterval; /** 是否为无限滚动 */ @property (nonatomic) BOOL infinite; /** 每个之间的指示器间距 */ @property (nonatomic) CGFloat indicatorGap; /** 指示器相对于布局底端的间距 */ @property (nonatomic) CGFloat indicatorMargin; /** 指示器高度(暂时不支持,似乎没必要) */ @property (nonatomic) CGFloat indicatorHeight; /** 最左边一帧距离布局左边的间距 */ @property (nonatomic) CGFloat scrollMarginLeft; /** 最右边一帧距离布局右边的间距 */ @property (nonatomic) CGFloat scrollMarginRight; /** 横向每一帧之间的间距 (暂不支持) */ @property (nonatomic) CGFloat hGap; @end
iYeso/TextureTangram
TextureTangram/Core/Build-in Layouts/Waterflow Layout/TangramWaterFlowLayoutComponent.h
<filename>TextureTangram/Core/Build-in Layouts/Waterflow Layout/TangramWaterFlowLayoutComponent.h // Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "TangramLayoutComponent.h" @interface TangramWaterFlowLayoutComponent : TangramLayoutComponent @property (nonatomic) NSUInteger maximumColumn; ///< 最大列数,默认1 @property (nonatomic) CGFloat verticalInterItemsSpace; ///< 垂直方向每个组件的间距;vGap @property (nonatomic) CGFloat horizontalInterItemsSpace; ///< 垂直方向每个组件的距离; hGap @end
iYeso/TextureTangram
TextureTangram/Core/Build-in Layouts/TangramBuildInLayout.h
<gh_stars>1-10 // // TangramBuildInLayout.h // TextureTangram // // Created by 廖超龙 on 2018/10/19. // Copyright © 2018年 ZZinKin. All rights reserved. // #import "TangramGridLayoutComponet.h" #import "TangramWaterFlowLayoutComponent.h" #import "TangramOnePlusLayoutComponent.h" #import "TangramCarouselInlineLayoutComponent.h" #import "TangramHorizontalInlineLayoutComponent.h"
iYeso/TextureTangram
TextureTangram/Core/Build-in Layouts/Inline Layout/Horizontal Scrollable/TangramHorizontalInlineLayoutComponent.h
// Copyright ZZinKin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <AsyncDisplayKit/AsyncDisplayKit.h> #import "TangramInlineLayoutComponent.h" #import "TangramInlineCellInfo.h" /// 内联布局,如banner、横向滑动等布局继承使用本布局 @interface TangramHorizontalInlineLayoutComponent : TangramInlineLayoutComponent < ASCollectionDataSource, ASCollectionDelegateFlowLayout> - (ASCellNodeBlock)nodeBlockWithModel:(TangramComponentDescriptor *)model; @property (nonatomic, weak) ASCollectionNode *collectionNode; /** 页面宽度,在iOS上配置了此参数,轮播布局的滚动会变为线性,不配置的话,就是一页一页的滚动,Android需要依赖此选型设置页面宽度 注意: 暂时不支持 */ @property (nonatomic) CGFloat pageWidth; @property (nonatomic) CGFloat pageHeight; ///< 页面高度 @property (nonatomic) BOOL hasIndicator; ///< 是否显示滚动指示 @property (nonatomic) CGFloat horizontalInterItemsSpace; ///< 垂直方向每个组件的距离; hGap @property (nonatomic) CGFloat scrollMarginLeft; ///< 最左边一帧距离布局左边的间距 @property (nonatomic) CGFloat scrollMarginRight; ///<最右边一帧距离布局右边的间距 @property (nonatomic, strong) UIColor *indicatorColor; ///<指示器选中颜色(iOS不支持) @property (nonatomic, strong) UIColor *defaultIndicatorColor; ///<指示器默认颜色(iOS不支持) @end
ModernBinary/ModernBinary
src/comp/core/convert.h
<gh_stars>10-100 #include <string> using namespace std; #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED string texttomb(string text); string mbtotext(string text); #endif
aapris/esp32-ble2mqtt
config.c
<gh_stars>1-10 #include "config.h" #include <mbedtls/md5.h> #include <esp_err.h> #include <esp_log.h> #include <esp_spiffs.h> #include <cJSON.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> /* Constants */ static const char *TAG = "Config"; static const char *config_file_name = "/spiffs/config.json"; static const char *config_update_file_name = "/spiffs/config.json.update"; static cJSON *config; /* Internal variables */ static char config_version[33]; /* BLE Configuration*/ static cJSON *config_ble_get_name_by_uuid(uint8_t is_service, const char *uuid, const char *field_name) { cJSON *ble = cJSON_GetObjectItemCaseSensitive(config, "ble"); cJSON *type = cJSON_GetObjectItemCaseSensitive(ble, is_service ? "services" : "characteristics"); cJSON *list = cJSON_GetObjectItemCaseSensitive(type, "definitions"); /* Check config.json for override values */ cJSON *obj = cJSON_GetObjectItemCaseSensitive(list, uuid); cJSON *field = cJSON_GetObjectItemCaseSensitive(obj, field_name); return field; } const char *config_ble_service_name_get(const char *uuid) { cJSON *name = config_ble_get_name_by_uuid(1, uuid, "name"); if (cJSON_IsString(name)) return name->valuestring; return NULL; } const char *config_ble_characteristic_name_get(const char *uuid) { cJSON *name = config_ble_get_name_by_uuid(0, uuid, "name"); if (cJSON_IsString(name)) return name->valuestring; return NULL; } const char **config_ble_characteristic_types_get(const char *uuid) { cJSON *types = config_ble_get_name_by_uuid(0, uuid, "types"); static char **ret = NULL; int i, size; if (ret) { free(ret); ret = NULL; } if (!cJSON_IsArray(types)) return NULL; size = cJSON_GetArraySize(types); ret = malloc(sizeof(char *) * (size + 1)); for (i = 0; i < size; i++) { cJSON *type = cJSON_GetArrayItem(types, i); ret[i] = type->valuestring; } ret[size] = NULL; return (const char **)ret; } int match_wildcard(const char *fmt, const char *str) { while(*fmt && (*fmt == *str || *fmt == '?')) { fmt++; str++; } return *fmt == *str || *fmt == '?'; } cJSON *json_find_in_array(cJSON *arr, const char *item) { cJSON *cur; if (!arr) return NULL; for (cur = arr->child; cur; cur = cur->next) { if (cJSON_IsString(cur) && match_wildcard(cur->valuestring, item)) return cur; } return NULL; } static uint8_t json_is_in_lists(cJSON *base, const char *item) { cJSON *whitelist = cJSON_GetObjectItemCaseSensitive(base, "whitelist"); cJSON *blacklist = cJSON_GetObjectItemCaseSensitive(base, "blacklist"); uint8_t action = whitelist ? 1 : 0; cJSON *list = whitelist ? : blacklist; /* No list was defined, accept all */ if (!list) return 1; return json_find_in_array(list, item) ? action : !action; } uint8_t config_ble_characteristic_should_include(const char *uuid) { cJSON *ble = cJSON_GetObjectItemCaseSensitive(config, "ble"); cJSON *characteristics = cJSON_GetObjectItemCaseSensitive(ble, "characteristics"); return json_is_in_lists(characteristics, uuid); } uint8_t config_ble_service_should_include(const char *uuid) { cJSON *ble = cJSON_GetObjectItemCaseSensitive(config, "ble"); cJSON *services = cJSON_GetObjectItemCaseSensitive(ble, "services"); return json_is_in_lists(services, uuid); } uint8_t config_ble_should_connect(const char *mac) { cJSON *ble = cJSON_GetObjectItemCaseSensitive(config, "ble"); return json_is_in_lists(ble, mac); } uint32_t config_ble_passkey_get(const char *mac) { cJSON *ble = cJSON_GetObjectItemCaseSensitive(config, "ble"); cJSON *passkeys = cJSON_GetObjectItemCaseSensitive(ble, "passkeys"); cJSON *key; if (!passkeys) return 0; for (key = passkeys->child; key; key = key->next) { if (cJSON_IsNumber(key) && match_wildcard(key->string, mac)) return key->valuedouble; } return 0; } /* MQTT Configuration*/ const char *config_mqtt_server_get(const char *param_name) { cJSON *mqtt = cJSON_GetObjectItemCaseSensitive(config, "mqtt"); cJSON *server = cJSON_GetObjectItemCaseSensitive(mqtt, "server"); cJSON *param = cJSON_GetObjectItemCaseSensitive(server, param_name); if (cJSON_IsString(param)) return param->valuestring; return NULL; } const char *config_mqtt_host_get(void) { return config_mqtt_server_get("host"); } uint16_t config_mqtt_port_get(void) { cJSON *mqtt = cJSON_GetObjectItemCaseSensitive(config, "mqtt"); cJSON *server = cJSON_GetObjectItemCaseSensitive(mqtt, "server"); cJSON *port = cJSON_GetObjectItemCaseSensitive(server, "port"); if (cJSON_IsNumber(port)) return port->valuedouble; return 1883; } const char *config_mqtt_client_id_get(void) { return config_mqtt_server_get("client_id"); } const char *config_mqtt_username_get(void) { return config_mqtt_server_get("username"); } const char *config_mqtt_password_get(void) { return config_mqtt_server_get("password"); } uint8_t config_mqtt_qos_get(void) { cJSON *mqtt = cJSON_GetObjectItemCaseSensitive(config, "mqtt"); cJSON *publish = cJSON_GetObjectItemCaseSensitive(mqtt, "publish"); cJSON *qos = cJSON_GetObjectItemCaseSensitive(publish, "qos"); if (cJSON_IsNumber(qos)) return qos->valuedouble; return 0; } uint8_t config_mqtt_retained_get(void) { cJSON *mqtt = cJSON_GetObjectItemCaseSensitive(config, "mqtt"); cJSON *publish = cJSON_GetObjectItemCaseSensitive(mqtt, "publish"); cJSON *retain = cJSON_GetObjectItemCaseSensitive(publish, "retain"); return cJSON_IsTrue(retain); } const char *config_mqtt_topics_get(const char *param_name, const char *def) { cJSON *mqtt = cJSON_GetObjectItemCaseSensitive(config, "mqtt"); cJSON *topics = cJSON_GetObjectItemCaseSensitive(mqtt, "topics"); cJSON *param = cJSON_GetObjectItemCaseSensitive(topics, param_name); if (cJSON_IsString(param)) return param->valuestring; return def; } const char *config_mqtt_prefix_get(void) { return config_mqtt_topics_get("prefix", ""); } const char *config_mqtt_get_suffix_get(void) { return config_mqtt_topics_get("get_suffix", "/Get"); } const char *config_mqtt_set_suffix_get(void) { return config_mqtt_topics_get("set_suffix", "/Set"); } /* WiFi Configuration */ const char *config_wifi_ssid_get(void) { cJSON *wifi = cJSON_GetObjectItemCaseSensitive(config, "wifi"); cJSON *ssid = cJSON_GetObjectItemCaseSensitive(wifi, "ssid"); if (cJSON_IsString(ssid)) return ssid->valuestring; return NULL; } const char *config_wifi_password_get(void) { cJSON *wifi = cJSON_GetObjectItemCaseSensitive(config, "wifi"); cJSON *password = cJSON_GetObjectItemCaseSensitive(wifi, "password"); if (cJSON_IsString(password)) return password->valuestring; return NULL; } /* Remote Logging Configuration */ const char *config_log_ip_get(void) { cJSON *log = cJSON_GetObjectItemCaseSensitive(config, "log"); cJSON *ip = cJSON_GetObjectItemCaseSensitive(log, "ip"); if (cJSON_IsString(ip)) return ip->valuestring; return NULL; } uint16_t config_log_port_get(void) { cJSON *log = cJSON_GetObjectItemCaseSensitive(config, "log"); cJSON *port = cJSON_GetObjectItemCaseSensitive(log, "port"); if (cJSON_IsNumber(port)) return port->valuedouble; return NULL; } /* Configuration Update */ int config_update_begin(config_update_handle_t *handle) { int fd; if ((fd = open(config_update_file_name, O_WRONLY | O_CREAT | O_TRUNC)) < 0) return -1; *handle = fd; return 0; } int config_update_write(config_update_handle_t handle, uint8_t *data, size_t len) { return write(handle, data, len) < 0; } int config_update_end(config_update_handle_t handle) { struct stat st; if (close(handle)) return -1; if (stat(config_update_file_name, &st)) return -1; if (st.st_size == 0) return -1; if (unlink(config_file_name)) return -1; if (rename(config_update_file_name, config_file_name)) return -1; return 0; } static char *read_file(const char *path) { int fd, len; struct stat st; char *buf, *p; if (stat(path, &st)) return NULL; if ((fd = open(path, O_RDONLY)) < 0) return NULL; if (!(buf = p = malloc(st.st_size + 1))) return NULL; while ((len = read(fd, p, 1024)) > 0) p += len; close(fd); if (len < 0) { free(buf); return NULL; } *p = '\0'; return buf; } static cJSON *load_json(const char *path) { char *p, *str = read_file(path); uint8_t i, hash[16]; cJSON *json; if (!str) return NULL; json = cJSON_Parse(str); /* Calculate MD5 hash as config version */ mbedtls_md5((unsigned char *)str, strlen(str), hash); for (i = 0, p = config_version; i < 16; i++) p += sprintf(p, "%02x", hash[i]); free(str); return json; } char *config_version_get(void) { return config_version; } int config_initialize(void) { ESP_LOGI(TAG, "Initializing configuration"); esp_vfs_spiffs_conf_t conf = { .base_path = "/spiffs", .partition_label = NULL, .max_files = 5, .format_if_mount_failed = true }; ESP_ERROR_CHECK(esp_vfs_spiffs_register(&conf)); /* Load config.json from SPIFFS */ if (!(config = load_json(config_file_name))) return -1; ESP_LOGI(TAG, "version: %s", config_version_get()); return 0; }
bennyyip/kaleidoscope-oxidized
example/fib.c
<reponame>bennyyip/kaleidoscope-oxidized<filename>example/fib.c<gh_stars>0 #include<stdio.h> double fib(double); double fibi(double); int main(int argc, const char **argv) { printf("%lf %lf", fib(10), fibi(20)); return 0; }
colinw7/CConcat
src/CConcatFind.h
<gh_stars>0 #ifndef CCONCAT_FIND_H #define CCONCAT_FIND_H #include <CConcatBase.h> #include <CGlob.h> #include <CRegExp.h> #include <vector> class CommentParser; class CConcatFind : public CConcatBase { public: typedef std::vector<std::string> Strings; public: CConcatFind(); ~CConcatFind(); //--- const std::string &filePattern() const { return filePattern_.str; } void setFilePattern(const std::string &s); //--- const std::string &pattern() const { return pattern_.str; } void setPattern(const std::string &s); bool isGlob() const { return pattern_.isGlob; } void setGlob(bool b) { pattern_.isGlob = b; } bool isRegExp() const { return pattern_.isRegExp; } void setRegExp(bool b) { pattern_.isRegExp = b; } bool isNoCase() const { return pattern_.noCase; } void setNoCase(bool b) { pattern_.noCase = b; } bool isMatchWord() const { return pattern_.matchWord; } void setMatchWord(bool b) { pattern_.matchWord = b; } //--- bool isList() const { return list_; } void setList(bool b) { list_ = b; } bool isShowFile() const { return showFile_; } void setShowFile(bool b) { showFile_ = b; } bool isNumber() const { return number_; } void setNumber(bool b) { number_ = b; } const Strings &extensions() const { return extensions_; } void setExtensions(const Strings &s) { extensions_ = s; } bool isMatchFile() const { return matchFile_; } void setMatchFile(bool b) { matchFile_ = b; } bool isMatchDir() const { return matchDir_; } void setMatchDir(bool b) { matchDir_ = b; } const std::string &root() const { return root_; } void setRoot(const std::string &s) { root_ = s; } bool isComment() const { return comment_; } void setComment(bool b) { comment_ = b; } bool isNoComment() const { return noComment_; } void setNoComment(bool b) { noComment_ = b; } bool exec(); bool checkMatch(int c); bool checkLine(const std::string &line) const; void addLineChar(char c); int getChar() const; private: const std::string &currentFile() const { return currentFile_; } void setCurrentFile(const std::string &s) { currentFile_ = s; } int currentLine() const { return currentLine_; } void setCurrentLine(int i) { currentLine_ = i; } bool checkPattern(const std::string &s) const; bool checkFilePattern(const std::string &s) const; std::string getDirName() const; const std::string &lpattern() const { return pattern_.lstr; } private: struct PatternData { std::string str; CGlob glob; CRegExp regexp; std::string lstr; bool isGlob { false }; bool isRegExp { false }; bool noCase { false }; bool matchWord { false }; }; static bool checkPatternData(const std::string &str, const PatternData &data); static bool isWord(const std::string &str, int pos, int len); static std::string toLower(const std::string &str); private: PatternData filePattern_; PatternData pattern_; bool list_ { false }; bool showFile_ { true }; bool number_ { false }; Strings extensions_; bool matchFile_ { false }; bool matchDir_ { false }; bool comment_ { false }; bool noComment_ { false }; std::string root_; uint bytesWritten_ { 0 }; std::string checkBuffer_; std::string currentFile_; int currentLine_ { 1 }; CommentParser* commentParser_ { nullptr }; FILE* fp_ { nullptr }; std::string line_; }; #endif
colinw7/CConcat
src/CConcatBase.h
<filename>src/CConcatBase.h #ifndef CCONCAT_BASE_H #define CCONCAT_BASE_H #include <string> #include <sys/types.h> class CConcatBase { public: CConcatBase(); const std::string &id() const { return id_; } void setId(const std::string &s) { id_ = s; } const std::string &filename() const { return filename_; } void setFilename(const std::string &s) { filename_ = s; } protected: bool readId(FILE *fp); const std::string &getDefId() const; protected: std::string id_; std::string filename_; uint checkPos_ { 0 }; }; #endif
colinw7/CConcat
src/CConcat.h
<gh_stars>0 #ifndef CCONCAT_H #define CCONCAT_H #include <CConcatBase.h> #include <vector> class CConcat : public CConcatBase { public: CConcat(); bool isSymlink() const { return symlink_; } void setSymlink(bool b) { symlink_ = b; } void addFile(const std::string &s) { files_.push_back(s); } uint getNumFiles() const { return files_.size(); } bool exec(); private: bool check_match(int c); private: bool symlink_ { true }; std::vector<std::string> files_; }; #endif
colinw7/CConcat
src/CConcatReplace.h
<filename>src/CConcatReplace.h #ifndef CCONCAT_REPLACE_H #define CCONCAT_REPLACE_H #include <CConcatBase.h> #include <vector> class CConcatReplace : public CConcatBase { public: typedef std::vector<std::string> Strings; public: CConcatReplace(); ~CConcatReplace(); const Strings &fromPatterns() const { return fromPatterns_; } void setFromPatterns(const Strings &strs); const Strings &toPatterns() const { return toPatterns_; } void setToPatterns(const Strings &strs); bool replaceFilename() const { return replaceFilename_; } void setReplaceFilename(bool b) { replaceFilename_ = b; } bool replaceContents() const { return replaceContents_; } void setReplaceContents(bool b) { replaceContents_ = b; } bool exec(); bool processLine(std::string &line) const; void addLineChar(char c); int getChar() const; private: const std::string &currentFile() const { return currentFile_; } void setCurrentFile(const std::string &s) { currentFile_ = s; } int currentLine() const { return currentLine_; } void setCurrentLine(int i) { currentLine_ = i; } bool checkMatch(int c); private: Strings fromPatterns_; Strings toPatterns_; bool replaceFilename_ { false }; bool replaceContents_ { false }; uint bytesWritten_ { 0 }; std::string checkBuffer_; std::string currentFile_; int currentLine_ { 1 }; FILE* fp_ { nullptr }; std::string line_; }; #endif
colinw7/CConcat
src/CUnconcat.h
#ifndef CUNCONCAT_H #define CUNCONCAT_H #include <CConcatBase.h> class CUnconcat : public CConcatBase { public: CUnconcat(); bool isTabulate() const { return tabulate_; } void setTabulate(bool b) { tabulate_ = b; } bool isCount() const { return count_; } void setCount(bool b) { count_ = b; } int fileNum() const { return fileNum_; } void setFileNum(int i) { fileNum_ = i; } bool exec(); bool check_match(FILE *fp, int c); private: uint bytesWritten_ { 0 }; std::string checkBuffer_; int fileNum_ { -1 }; bool tabulate_ { false }; bool count_ { false }; }; #endif
sayinala/Capstone
main/algorithms/NemhauserUllmannSolver.h
<filename>main/algorithms/NemhauserUllmannSolver.h #ifndef MAIN_ALGORITHMS_NEMHAUSERULLMANNSOLVER_H_ #define MAIN_ALGORITHMS_NEMHAUSERULLMANNSOLVER_H_ #include <string> #include <vector> #include "main/KnapSackSolver.h" /** * A PlotPoint represents a point in the worth vs. weight plot. * Therefore we need the worth, the need and the containing items. */ struct PlotPoint { double worth; double weight; std::vector<KnapSackItem*>* containingItems; }; /** * The NemhauserUllmannSolver extends the KnapSackSolver class and * implements the abstract method solve(). * * This algorithm is a sequential algorithm. The idea of this algorithm is * based on the plot worth vs. weight. Every possible combination represents a point in the plot. * For example a point could be consist of item1, item2 and item3. The point would be located at <br/> * x = w1 + w2 + w3, where w* is an abbreviation for weight of item* <br/> * y = p1 + p2 + p3, where p* is an abbreviation for profit (==worth) of item*<br/> * In this plot only the most upper points are interesting. They are called (Pareto-optimal). * During the construction we can omit a lot of points to check.<br/> * The rough algorithm is (implemented in solve-function): * * L_0 := [(0,0)] // A list with pareto optimal points. In the beginning only the point (0,0) is available <br/> * foreach item x in input do: <br/> * 1. Copy new items in L'_i<br/> * L'_i := L_i + x // This means create a new list L'_i with points equal to the list L_i and add to all points the current item x (weight and worth) * 2. Remove not pareto-optimal points in lists L_i and L'_i * 3. Merge both list sorted<br/> * L_{i+1} := sort_with_ascending_weight( L_i, L'_i )<br/> * * After adding of all items the optimal solution is at the end of list L_n where n is the number of input items. * * For more information see http://www-i1.informatik.rwth-aachen.de/~algorithmus/algo15.php */ class NemhauserUllmannSolver : public KnapSackSolver { public: static const std::string NAME; NemhauserUllmannSolver(std::string inputFilename, std::string outputFilename, int nrOfExecutions = 1); protected: void setUp(); void tearDown(); void solve(); private: void initPlotPointLists(); void deletePlotPointLists(); /** * Copies PlotPoint 'from' to 'to' only if 'from's weight does not exceed the maximal allowed weight * of our knapsack. * Returns true if the item was actually copied, otherwise false. */ bool copyPlotPointIfItFitsIntoKnapsack(PlotPoint* from, PlotPoint* to); /* * The PlotPoint lists represent the lists L_i, L'_i and L_{i+i}. * The names are numbered because the roles (L_*) will switch. * The items in the lists are ordered ascend by weight. */ PlotPoint* list0; PlotPoint* list1; PlotPoint* list2; const double knapsackCapacity; }; #endif /* MAIN_ALGORITHMS_NEMHAUSERULLMANNSOLVER_H_ */
sayinala/Capstone
main/algorithms/DynamicProgrammingParallelSolver.h
<reponame>sayinala/Capstone #ifndef MAIN_ALGORITHMS_DYNAMICPROGRAMMINGPARALLELSOLVER_H_ #define MAIN_ALGORITHMS_DYNAMICPROGRAMMINGPARALLELSOLVER_H_ #include <string> #include <vector> #include "util/MyMath.h" #include "main/KnapSackSolver.h" #include "main/algorithms/DynamicProgrammingSolver.h" // for IntegerItem struct /** * The DynamicProgrammingParallelSolver extends the KnapSackSolver class and * implements the abstract method solve(). * * It follows the same approach as the DynamicProgramminParallelSolver * (see DynamicProgrammingSolver.h) * but calculates the entries of each row in parallel. * * This version is only compatible to integer input values and can not handle floating point values. * To handle floating point values, we could multiply them (e.g. by 100) and parse them them to integer * but this delivers only a low accuracy and makes the problem / matrix to solve more complex. * To solve problems with floating point values we have implemented the algorithm of Nemhauser and Ullmann */ class DynamicProgrammingParallelSolver: public KnapSackSolver { public: /** * This threshold is used to determine whether the problem should be solved in parallel. * It is not necessary to start several threads and calculate the elements in parallel * when the number of elements of one row is lower than a certain threshold. * In this case it would take more time to start the threads than just solving the * problem sequentially. * * The number of elements per row is depending on the max capacity of the knapsack, * since there are as many columns as the value of the capacity. */ static const int PARALLEL_CAPACITY_THRESHOLD; static const int PARALLEL_ITEM_THRESHOLD; static const std::string NAME; DynamicProgrammingParallelSolver(std::string inputFilename, std::string outputFilename, int nrOfExecutions = 1); ~DynamicProgrammingParallelSolver(); protected: void setUp(); void tearDown(); /** * Solves every subproblem of the given knapsack problem including the knapsack problem itself. * Each entry of the table represents the best worth achievable by the specific sub problem. * The problems are being solved in a bottom-up manner. * We start by solving the lowest subproblem [1,1] and end up solving the main problem at [numOfItems, maxCapacity]. * * Why don't we start at [0,0] ? Because worths of row[0] and worths of column[0] stay 0. * This is because a knapsack with 0 capacity can not have any items and a knapsack with 0 items can not weigh anything (0 capacity = 0 items). * Thus the best worths of our base-problems (the sub problems at [i,0] for all [0 <= i < cols] and the sub problems at [0, c] for all [0 <= c < rows]) * stay 0. * * In this version the independent elements in each row are calculated in parallel. * Meaning: each row i has c elements where i = index of itemRows and c = index of weightColumns. * All c elements can be calculated in parallel, since they are independent from each other. * We can not calculate several rows or columns in parallel, since they are dependant from each other. */ void solve(); private: /**each row represents the number of items available for the specific sub problem*/ const int itemRows; /**each column represents the max capacity of the knapsack for the specific sub problem*/ const int weightColumns; /** * The result table. * Each row represents the number of items available for the specific sub problem * Each column represents the max capacity of the knapsack for the specific sub problem * * The upper left entry represents the optimal worth for the sub-problem [0,0] * (a knapsack that can choose among 0 items and has a capacity of 0). * * The lower right entry represents the optimal worth for the main-problem * (the knapsack that can choose among all available items and has the highest capacity possible). * * Example table: |[c:0]|[c:1]|[c:2]|[c:3]|[c:4]|[c:5] ----------------------------------------- [i:0]| 0 | 0 | 0 | 0 | 0 | 0 ----------------------------------------- [i:1]| 0 | 0 | 3 | 3 | 3 | 3 ----------------------------------------- [i:2]| 0 | 0 | 3 | 4 | 4 | 7 ----------------------------------------- [i:3]| 0 | 0 | 3 | 4 | 5 | 7 ----------------------------------------- [i:4]| 0 | 0 | 3 | 4 | 5 | 7 ----------------------------------------- * */ int** table; /** * Equals the itemlist (itempool) of the KnapSack, except that those items worths and weights are casted to int. * Thus we prevent explicit casting during solve */ IntegerItem* integerItems; /** * Determines items included in the optimal solution by * traversing the populated result table. * This happens top-down, meaning we start at the most lower right table entry. * This entry contains the optimal worths for the main knapsack problem. * By comparing the worths of specific sub problems we can determine if a * specific item is part of the optimal solution or not. * * If the optimal worths of entries of two rows * table[currItem][currWeight] and table[currItem-1][currWeight] * differ from each other, the item of the current row must be part of the solution. * We add the item and decrease the capacity by the weight of that item. * Thus, new sub problems with the new capacity will be checked until we checked all items. */ void backtrackItemsOfSolution(); /**prints the table to the console*/ void printTable(); }; #endif /* MAIN_ALGORITHMS_DYNAMICPROGRAMMINGPARALLELSOLVER_H_ */
sayinala/Capstone
util/io/KnapSackWriter.h
#ifndef IO_KNAPSACKWRITER_H_ #define IO_KNAPSACKWRITER_H_ #include <stdio.h> #include <iostream> #include <fstream> #include <assert.h> #include "main/KnapSack.h" /** * Helper class used to create an output file representing the solution of a solved * knapsack problem in a specific format. * * Example output file: * * ------------------------------ Capacity;400.0 item24;5 item69;2 Total weight;345.00 Total worth;333.00 * ------------------------------ * * Meaning: * - The max capacity was 400.0 * - item24 is included 5 times in the solution * - item69 is included 2 times in the solution * - The solution takes a weight of 345.00 * - The solution is worth 333.00 */ class KnapSackWriter { public: KnapSackWriter(std::string filename, int nrOfDistinctItems, double capacityOfKnapSack); virtual ~KnapSackWriter(); /** * Adds an entry to the item list to be written to file. * The exemplarsOfThisItem parameter specifies how often this item is included in the solution. */ void addItem(const KnapSackItem* item, int exemplarsOfThisItem); /** * Writes the knapsackwriter object to the specified output file. */ bool writeToFile(); private: std::string filename; double capacityOfKnapSack; double weight; double worth; int nrOfDistinctItems; KnapSackItem* items; int* exemplarsOfItems; int currPointerToFreeSpot; }; #endif /* IO_KNAPSACKWRITER_H_ */
sayinala/Capstone
main/algorithms/BruteForceSolver.h
<filename>main/algorithms/BruteForceSolver.h<gh_stars>1-10 #ifndef MAIN_ALGORITHMS_BRUTEFORCESOLVER_H_ #define MAIN_ALGORITHMS_BRUTEFORCESOLVER_H_ #include <string> #include <vector> #include "main/KnapSackSolver.h" /** * The BruteForceSolver extends the KnapSackSolver class and * implements the abstract method solve(). * * Solves the KnapSack-Problem with a brute force method by trying each possible combination of * KnapSack-objects. See solve() method of BruteForceSolver.cpp for more information. */ class BruteForceSolver : public KnapSackSolver { public: static const std::string NAME; BruteForceSolver(std::string inputFilename, std::string outputFilename, int nrOfExecutions = 1); protected: void setUp(); void tearDown(); void solve(); private: /** * CurrentCombination is a bit pattern which describes the current combination of items * which is being evaluated. It is modified during solve() and used to update bestCombination */ std::vector<char> currentCombination; /** * BestCombination is a bit pattern which describes the best combination of items that has * been determined during solve(). It is used to track the best combination over the process * of evaluation each combination and to fill itemsOfSolution during tearDown(). */ std::vector<char> bestCombination; /** * The number of possible knapsack item combinations. this is always 2^n where n is the number of available knapsack items. */ const unsigned long long int numOfCombinations; }; #endif /* MAIN_ALGORITHMS_BRUTEFORCESOLVER_H_ */
sayinala/Capstone
main/algorithms/DynamicProgrammingSolver.h
#ifndef MAIN_ALGORITHMS_DYNAMICPROGRAMMINGSOLVER_H_ #define MAIN_ALGORITHMS_DYNAMICPROGRAMMINGSOLVER_H_ #include <string> #include <vector> #include "util/MyMath.h" #include "main/KnapSackSolver.h" /** * The same struct as KnapSackItem but instead of having * double values for weight and worth we use int values. * This struct is used to prevent explicit casting during * solve of DynamicProgrammingSolver */ struct IntegerItem{ std::string* name; int weight; int worth; bool operator==(const IntegerItem& rhs){ return weight == rhs.weight && worth == rhs.worth && *name == *(rhs.name); } }; /** * The DynamicProgrammingSolver extends the KnapSackSolver class and * implements the abstract method solve(). * * Solves the KnapSack-Problem with the dynamic programming approach. * The main knapsack-problem is being solved in a bottom-up manner by solving * all sub-problems first. When the optimal worths of the base problems * are known, the worths of higher sub problems are calculated until * the worth of main problem is known. Afterwards the items belonging to the * calculated worth are added to the solutionlist. * * This version is only compatible to integer input values and can not handle floating point values. * To handle floating point values, we could multiply them (e.g. by 100) and parse them them to integer * but this delivers only a low accuracy and makes the problem / matrix to solve more complex. * To solve problems with floating point values we have implemented the algorithm of Nemhauser and Ullmann */ class DynamicProgrammingSolver : public KnapSackSolver { public: static const std::string NAME; DynamicProgrammingSolver(std::string inputFilename, std::string outputFilename, int nrOfExecutions = 1); ~DynamicProgrammingSolver(); protected: void setUp(); void tearDown(); /** * Solves every subproblem of the given knapsack problem including the knapsack problem itself. * Each entry of the table represents the best worth achievable by the specific sub problem. * The problems are being solved in a bottom-up manner. * We start by solving the lowest subproblem [1,1] and end up solving the main problem at [numOfItems, maxCapacity]. * * Why don't we start at [0,0] ? Because worths of row[0] and worths of column[0] stay 0. * This is because a knapsack with 0 capacity can not have any items and a knapsack with 0 items can not weigh anything (0 capacity = 0 items). * Thus the best worths of our base-problems (the sub problems at [i,0] for all [0 <= i < cols] and the sub problems at [0, c] for all [0 <= c < rows]) * stay 0. */ void solve(); private: /**each row represents the number of items available for the specific sub problem*/ const int itemRows; /**each column represents the max capacity of the knapsack for the specific sub problem*/ const int weightColumns; /** * The result table. * Each row represents the number of items available for the specific sub problem * Each column represents the max capacity of the knapsack for the specific sub problem * * The upper left entry represents the optimal worth for the sub-problem [0,0] * (a knapsack that can choose among 0 items and has a capacity of 0). * * The lower right entry represents the optimal worth for the main-problem * (the knapsack that can choose among all available items and has the highest capacity possible). * * Example table: |[c:0]|[c:1]|[c:2]|[c:3]|[c:4]|[c:5] ----------------------------------------- [i:0]| 0 | 0 | 0 | 0 | 0 | 0 ----------------------------------------- [i:1]| 0 | 0 | 3 | 3 | 3 | 3 ----------------------------------------- [i:2]| 0 | 0 | 3 | 4 | 4 | 7 ----------------------------------------- [i:3]| 0 | 0 | 3 | 4 | 5 | 7 ----------------------------------------- [i:4]| 0 | 0 | 3 | 4 | 5 | 7 ----------------------------------------- * */ int** table; /** * Equals the itemlist of the KnapSack, except that those items worths and weights are casted to int. * Thus we prevent explicit casting during solve */ IntegerItem* integerItems; /** * Determines items included in the optimal solution by * traversing the populated result table. * This happens top-down, meaning we start at the most lower right table entry. * This entry contains the optimal worths for the main knapsack problem. * By comparing the worths of specific sub problems we can determine if a * specific item is part of the optimal solution or not. * * If the optimal worths of entries of two rows * table[currItem][currWeight] and table[currItem-1][currWeight] * differ from each other, the item of the current row must be part of the solution. * We add the item and decrease the capacity by the weight of that item. * Thus, new sub problems with the new capacity will be checked until we checked all items. */ void backtrackItemsOfSolution(); /**prints the result table to the console*/ void printTable(); }; #endif /* MAIN_ALGORITHMS_DYNAMICPROGRAMMINGSOLVER_H_ */
sayinala/Capstone
main/algorithms/NemhauserUllmannParallelSolver.h
#ifndef MAIN_ALGORITHMS_NEMHAUSERULLMANNPARALLELSOLVER_H_ #define MAIN_ALGORITHMS_NEMHAUSERULLMANNPARALLELSOLVER_H_ #include <omp.h> #include <string> #include <vector> #include "main/KnapSackSolver.h" #include "main/algorithms/NemhauserUllmannSolver.h" /** * Based on NemhauserUllmannSolver but the method betterPointExists is parallelized here. */ class NemhauserUllmannParallelSolver : public KnapSackSolver { public: static const std::string NAME; NemhauserUllmannParallelSolver(std::string inputFilename, std::string outputFilename, int nrOfExecutions = 1); protected: void setUp(); void tearDown(); void solve(); private: void initPlotPointLists(); void deletePlotPointLists(); /** * Copies PlotPoint 'from' to 'to' only if 'from's weight does not exceed the maximal allowed weight * of our knapsack. * Returns true if the item was actually copied, otherwise false. */ bool copyPlotPointIfItFitsIntoKnapsack(PlotPoint* from, PlotPoint* to); /** * Checks whether a better point than 'ptToCheck' exists in 'list'. 'counter' is the number * of points in 'list'. * A better point means a point which is located in the upper left quarter, so a point with * lower weight but higher worth. */ bool betterPointExists(const PlotPoint* ptToCheck, const PlotPoint* list, const int counter); /** * Find PlotPoints which are not pareto-optimal and 'mark' them. Marking means here set the * worth to a negative value. Not pareto-optimal points are points which have other points in * their the upper left quarter, so points with lower weights but higher worths. * * Note, for the points from L_i we only need to check for better points in the list L'_i since * all points in the list are pareto-optimal. The same holds for points from L'_i accordingly. * * @param list1 * @param ctr1 The number of elements in list1 * @param list1 * @param ctr2 The number of elements in list2 */ void markAllNonOptimalPoints(PlotPoint* list1, const int ctr1, PlotPoint* list2, const int ctr2); /* * The PlotPoint lists represent the lists L_i, L'_i and L_{i+i}. * The names are numbered because the roles (L_*) will switch. * The items in the lists are ordered ascend by weight. */ PlotPoint* list0; PlotPoint* list1; PlotPoint* list2; const double knapsackCapacity; static const double NEG_VALUE_FOR_MARKING_NOT_OPTIMAL_POINTS; /** * Used in "parallel for" pragma. If we have only a few items then it is faster to run it on a single * thread. The threshold has to be determined. */ static const int THRESHOLD_OF_ITEMS_TO_PARALLELIZE; }; #endif /* MAIN_ALGORITHMS_NEMHAUSERULLMANNPARALLELSOLVER_H_ */
sayinala/Capstone
util/StringUtils.h
#ifndef UTIL_STRINGUTILS_H_ #define UTIL_STRINGUTILS_H_ #include <string> #include <algorithm> #include <functional> #include <cctype> #include <locale> #include <vector> #include <sstream> /** * Helper class which provides string helper functions */ class StringUtils { public: /** * Trims white spaces from the beginning of the given string */ static inline std::string& ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } /** * Trims white spaces from the end of the given string */ static inline std::string& rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } /** * Trims white spaces from the beginning and the end of the given string */ static inline std::string& trim(std::string &s) { return ltrim(rtrim(s)); } /** * Removes all spaces from the given string */ static inline std::string& removeAllSpaces(std::string &s) { std::string::iterator end_pos = std::remove(s.begin(), s.end(), ' '); s.erase(end_pos, s.end()); return s; } static std::vector<std::string> split(std::string str, char delimiter){ std::vector<std::string> internal; std::stringstream ss(str); std::string tok; while (std::getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } }; #endif /* UTIL_STRINGUTILS_H_ */
sayinala/Capstone
main/algorithms/DynamicProgrammingLowMemorySolver.h
#ifndef MAIN_ALGORITHMS_DYNAMICPROGRAMMINGLOWMEMORYSOLVER_H_ #define MAIN_ALGORITHMS_DYNAMICPROGRAMMINGLOWMEMORYSOLVER_H_ #include <string> #include <vector> #include <assert.h> #include "util/MyMath.h" #include "main/KnapSackSolver.h" #include "main/algorithms/DynamicProgrammingSolver.h" // for IntegerItem struct /** * The DynamicProgrammingLowMemorySolver extends the KnapSackSolver class and * implements the abstract method solve(). * * Solves the KnapSack-Problem with the dynamic programming approach (see DynamicProgrammingSolver). * But instead of storing the whole matrix / result table, this algorithm reduces the used storage * by only storing the currently needed data within two rows (instead of numOfItem rows). Instead of * having the whole table we just need one row which stores the previously calculated worths and uses * them to calculate the worths of the next iteration. * * This however causes some difficulty when trying to backtrack the items of the solution. * Before we could easily the stored result table to look up the items that were included in the solution. * Now that the table is gone, we need another approach to backtrack the picked items. * Therefore we use the Recursive-DP algorithm presented by Prof. <NAME> and Prof. <NAME> * in their book 'Knapsack Problems' (page 47). * * This version is only compatible to integer input values and can not handle floating point values. * To handle floating point values, we could multiply them (e.g. by 100) and parse them them to integer * but this delivers only a low accuracy and makes the problem / matrix to solve more complex. * To solve problems with floating point values we have implemented the algorithm of Nemhauser and Ullmann */ class DynamicProgrammingLowMemorySolver : public KnapSackSolver { public: static const std::string NAME; DynamicProgrammingLowMemorySolver(std::string inputFilename, std::string outputFilename, int nrOfExecutions = 1); ~DynamicProgrammingLowMemorySolver(); protected: void setUp(); void tearDown(); /** * Calls solveProblem(..) to determine the max worth of the given knapSack problem * and then uses determineItemsOfSolutionRecursively(..) to backtrack the packed items. */ void solve(); private: /** * Equals the itemlist (itempool) of the KnapSack, except that those items worths and weights are casted to int. * Thus we prevent explicit casting during solve */ IntegerItem* integerItems; /** * Used to store the packed items during the backtracking process. * In tearDown(), the items of this list are converted to KnapSackItems * and put into the original itemsOfSolution. This is done because the * conversion from integerItem to knapSackItem should not affect time measurement. */ std::vector<IntegerItem> integerItemsOfSolution; /** * Solves the given knapsack problem with the dynamic programming approach. * While solving, this algorithm only operates on the given solutionRow as data holder. * At the beginning the solutionRow will be initialized by zeros and then will be filled * for each item iteration. At the end it represents the last row of typical DP result table. * The last element of the solutionRow therefore represents the solution / max worth of the given * problem. * * Returns a pointer to the final solutionRow. */ int* solveProblem(IntegerItem* items, int itemsLength, int* solutionRow, int rowLength, int capacity); /** * Used to determine / backtrack the items that have been packed to achieve the given solution for * the given knapsack problem (items, capacity). This is needed since we do not store the solutions * of all sub problems within a table. * * This algorithm was introduced by <NAME> and <NAME> in their book 'Knapsack Problems' on page 47. * It is a recursive divide and conquer algorithm that divides the given itemlist in sublists until only one element is left * within the respective sublist, from which we know it must have been packed. Therefore it uses the solveProblem algorithm * several times (for each divided sublist). */ void determineItemsOfSolutionRecursively(IntegerItem* items, int numOfItems, int capacity, int solution); }; #endif /* MAIN_ALGORITHMS_DYNAMICPROGRAMMINGLOWMEMORYSOLVER_H_ */
sayinala/Capstone
util/io/KnapSackReader.h
#ifndef IO_KNAPSACKREADER_H_ #define IO_KNAPSACKREADER_H_ #include "main/KnapSack.h" #include "util/StringUtils.h" #include <cstdlib> #include <fstream> #include <string> /** * Helper class used to interpret knapsack problems from input files. * * Example File: * * ------------------------ * 10.0 4 2 * XXL blue Ox 3.0 2.00 * gray mouse 1.0 2.45 * ------------------------ * * Means: * Capacity = 10.0 * MaxNumPerItem = 4 * NumOfItems = 2 * Item 1: Name(XXL blue Ox), Weight(3.0), Worth(2.00) * Item 2: Name(gray mouse), Weight(1.0), Worth(2.45) * Itemnames are always STRLENGTH_ITEMNAME characters long * */ class KnapSackReader{ private: //Input file constraints static const int STRLENGTH_ITEMNAME = 13; KnapSackReader(); public: /** * Reads the knapsack problem file found at the given path and * creates a KnapSack object representing the read problem. * Returns the created knapsack. */ static KnapSack readKnapSackFrom(const char* fileName); }; #endif /* IO_KNAPSACKREADER_H_ */
sayinala/Capstone
util/io/StatisticsWriter.h
#ifndef IO_STATISTICSWRITER_H_ #define IO_STATISTICSWRITER_H_ #include <stdio.h> #include <iostream> #include <fstream> #include <vector> #include <cmath> /** * Helper class used to create an output file representing the statistics collected * while solving a knapsack problem in a KnapSackSolver * * Example output file: * * ------------------------------ Alogrithmus;Dynamic Programming Low Memory (Sequential) Anzahl Durchlaeufe;3 Durchschnittliche Laufzeit;2.1608 Quadratisches Mittel;0.0243 1;2.1265 2;2.1772 3;2.1788 * ------------------------------ * * Meaning: * - Alogrithmus = The name of the solver algorithm * - The problem was solved 3 times with this algorithm * - The average time to solve the problem was 2.1608s * - The root mean square for solving was 0.0243s * - The first solving took 2.1265s * - The second solving took 2.1772s * - The third solving took 2.1788s */ class StatisticsWriter { public: StatisticsWriter(std::string filename, std::string algorithmname); virtual ~StatisticsWriter(); /** * Adds a duration in seconds to the duration list. */ void addDuration(const double seconds); /** * Clears the list of durations, meaning it removes all entries from the list. */ void clearDurations(); /** * Writes the statistics to the specified output file. */ bool writeToFile(); private: /** * The path to the output file */ std::string filename; /** * The name of the algorithm that was measured while solving the problem */ std::string algorithmname; /** * The duration list represents the durations of the respective solve iterations. * There should be one measured duration for each time the problem was solved. * It serves as base for calculating the average needed time and the root mean square. */ std::vector<double> durations; /** * Calculates the average time needed to solve the problem and returns it. */ double calcAvg(); /** * Calculates the root mean square error among the collected durations and returns it. */ double calcRmsError(const double avg); }; #endif /* IO_STATISTICSWRITER_H_ */
sayinala/Capstone
test/TestData.h
<filename>test/TestData.h #ifndef TEST_DATA_H_ #define TEST_DATA_H_ /* Content of text file 15.0 4 5 XXL blue 0x 02.0 2.00 gray mouse 01.0 2.00 big green box 12.0 4.00 yellow daisy 04.0 10.00 salmon mousse 01.0 1.00 */ static const char* KNAPSACK_INPUT_FILE = "res/KnapSackItemsForUnittest.txt"; /* Content of text file. Same as above but with more whitespace. 15.0 4 5 XXL blue 0x 2.0 2.0 gray mouse 1.0 2.0 big green box 12.0 4.0 yellow daisy 4.0 10.0 salmon mousse 1.0 1.0 */ static const char* KNAPSACK_INPUT_FILE_FIRST_EXAMPLE = "res/firstFileExample.txt"; std::string* ITEM__NAME_1 = new std::string("XXL blue 0x"); const KnapSackItem TEST_ITEM_1 = {ITEM__NAME_1, 2.0, 2.0}; std::string* ITEM__NAME_2 = new std::string("gray mouse"); const KnapSackItem TEST_ITEM_2 = {ITEM__NAME_2, 1.0, 2.0}; std::string* ITEM__NAME_3 = new std::string("big green box"); const KnapSackItem TEST_ITEM_3 = {ITEM__NAME_3, 12.0, 4.0}; std::string* ITEM__NAME_4 = new std::string("yellow daisy"); const KnapSackItem TEST_ITEM_4 = {ITEM__NAME_4, 4.0, 10.0}; std::string* ITEM__NAME_5 = new std::string("salmon mousse"); const KnapSackItem TEST_ITEM_5 = {ITEM__NAME_5, 1.0, 1.0}; /* Expected Solution of KNAPSACK_INPUT_FILE_FIRST_EXAMPLE * ----------------------------------- * 3x gray mouse -> 3 weight, 6 worth * 3x yellow daisy -> 12 weight, 30 worth * ----------------------------------- * overall 15 weight and 36 worth */ const std::string ASSUMED_CONTENT_FILE_1[] {"Capacity;15.0", "gray mouse;3", "yellow daisy;3", "Total weight;15.00", "Total worth;36.00"}; /** * Same solution as ASSUMED_CONTENT_FILE_1 but inverses the order of the items. */ const std::string ASSUMED_CONTENT_FILE_1_DIFFERENT_ORDER_OF_ITEMS[] {"Capacity;15.0", "yellow daisy;3", "gray mouse;3", "Total weight;15.00", "Total worth;36.00"}; /** * Number of elements of ASSUMED_CONTENT_FILE_1[] and ASSUMED_CONTENT_FILE_1_DIFFERENT_ORDER_OF_ITEMS[] */ const int ASSUMED_CONTENT_LINES_FILE_1 = 5; /* Content of text file 15.0 1 6 XXL blue Ox 2.0 2.0 gray mouse 1.0 2.0 big green box 12.0 4.0 yellow daisy 4.0 10.0 salmon mousse 1.0 1.0 9780596521530 1.54 44.99 */ static const char* KNAPSACK_INPUT_FILE_SECOND_EXAMPLE = "res/secondFileExample.txt"; // Only one new item in this file. std::string* ITEM__NAME_6 = new std::string("9780596521530"); const KnapSackItem TEST_ITEM_6 = {ITEM__NAME_6, 1.54, 44.99}; /**Expected Solution of KNAPSACK_INPUT_FILE_SECOND_EXAMPLE The items to fit into the 15.0 knapsack are: 1 gray mouse 1 9780596521530 1 yellow daisy 1 salmon mousse 1 XXL blue Ox Total capacity used: 9.54 Total value: 59.99 */ const std::string ASSUMED_CONTENT_FILE_2[] {"Capacity;15.0", "XXL blue 0x;1", "gray mouse;1", "yellow daisy;1", "salmon mousse;1", "9780596521530;1", "Total weight;9.54", "Total worth;59.99"}; /** * Same solution as ASSUMED_CONTENT_FILE_2 but inverses the order of the items. */ const std::string ASSUMED_CONTENT_FILE_2_DIFFERENT_ORDER[] {"Capacity;15.0", "9780596521530;1", "yellow daisy;1", "XXL blue 0x;1", "gray mouse;1", "salmon mousse;1", "Total weight;9.54", "Total worth;59.99"}; /** * Number of elements of ASSUMED_CONTENT_FILE_2[] and ASSUMED_CONTENT_FILE_2_DIFFERENT_ORDER[] */ const int ASSUMED_CONTENT_LINES_FILE_2 = 8; /* Content of text file 645.0 7 8 EINS 153.0 232.0 ZWEI 54.0 73.0 DREI 191.0 201.0 VIERE 66.0 50.0 FUENF 239.0 141.0 SECHS 137.0 79.0 SIEBEN 148.0 48.0 ACHT 249.0 38.0 */ static const char* KNAPSACK_INPUT_FILE_THIRD_EXAMPLE = "res/thirdFileExample.txt"; std::string* ITEM__EINS = new std::string("EINS"); const KnapSackItem TEST_ITEM_EINS = {ITEM__EINS, 153.0, 232.0}; std::string* ITEM__ZWEI = new std::string("ZWEI"); const KnapSackItem TEST_ITEM_ZWEI = {ITEM__ZWEI, 54.0, 73.0}; std::string* ITEM__DREI = new std::string("DREI"); const KnapSackItem TEST_ITEM_DREI = {ITEM__DREI, 191.0, 201.0}; std::string* ITEM__VIERE = new std::string("VIERE"); const KnapSackItem TEST_ITEM_VIERE = {ITEM__VIERE, 66.0, 50.0}; std::string* ITEM__FUENF = new std::string("FUENF"); const KnapSackItem TEST_ITEM_FUENF = {ITEM__FUENF, 239.0, 141.0}; std::string* ITEM__SECHS = new std::string("SECHS"); const KnapSackItem TEST_ITEM_SECHS = {ITEM__SECHS, 137.0, 79.0}; std::string* ITEM__SIEBEN = new std::string("SIEBEN"); const KnapSackItem TEST_ITEM_SIEBEN = {ITEM__SIEBEN, 148.0, 48.0}; std::string* ITEM__ACHT = new std::string("ACHT"); const KnapSackItem TEST_ITEM_ACHT = {ITEM__ACHT, 249.0, 38.0}; /**Expected Solution of KNAPSACK_INPUT_FILE_THIRD_EXAMPLE The items to fit into the 645.0 knapsack are: 4x EINS Total capacity used: 612.00 Total value: 928.00 */ const std::string ASSUMED_CONTENT_FILE_3[] {"Capacity;645.0", "EINS;4", "Total weight;612.00", "Total worth;928.00"}; /** * Number of elements of ASSUMED_CONTENT_FILE_3[] */ const int ASSUMED_CONTENT_LINES_FILE_3 = 4; /* Content of text file 5.0 1 4 item_01 2.0 3.0 item_02 3.0 4.0 item_03 4.0 5.0 item_04 5.0 6.0 */ static const char* KNAPSACK_INPUT_FILE_DP_EXAMPLE = "res/dynamicProgrammingExample.txt"; std::string* ITEM__DP_01 = new std::string("item_01"); const KnapSackItem TEST_ITEM_DP_01 = {ITEM__DP_01, 2.0, 3.0}; std::string* ITEM__DP_02 = new std::string("item_02"); const KnapSackItem TEST_ITEM_DP_02 = {ITEM__DP_02, 3.0, 4.0}; std::string* ITEM__DP_03 = new std::string("item_03"); const KnapSackItem TEST_ITEM_DP_03 = {ITEM__DP_03, 4.0, 5.0}; std::string* ITEM__DP_04 = new std::string("item_04"); const KnapSackItem TEST_ITEM_DP_04 = {ITEM__DP_04, 5.0, 6.0}; /* Expected Solution * ----------------------------------- * 1x item_02 -> 3 weight, 4 worth * 1x item_01 -> 2 weight, 3 worth * ----------------------------------- * overall 5 weight and 7 worth */ const std::string ASSUMED_CONTENT_FILE_DP[] {"Capacity;5.0", "item_02;1", "item_01;1", "Total weight;5.00", "Total worth;7.00"}; /** * Same solution as ASSUMED_CONTENT_FILE_DP but inverses the order of the items. */ const std::string ASSUMED_CONTENT_FILE_DP_DIFFERENT_ORDER[] {"Capacity;5.0", "item_01;1", "item_02;1", "Total weight;5.00", "Total worth;7.00"}; /** * Number of elements of ASSUMED_CONTENT_FILE_DP[] and ASSUMED_CONTENT_FILE_DP_DIFFERENT_ORDER[] */ const int ASSUMED_CONTENT_LINES_FILE_DP = 5; /** * The file to where the test output is written to */ const char* TEST_OUTPUT_FILE = "outputForTesting.txt"; #endif /* TEST_DATA_H_ */
sayinala/Capstone
main/KnapSack.h
#ifndef MAIN_KNAPSACK_H_ #define MAIN_KNAPSACK_H_ #include <utility> #include <iostream> #include "util/MyMath.h" /** * Represents an item from the item pool of the knapsack */ struct KnapSackItem{ // using string pointer because of performance reasons. std::string* name; double weight; double worth; bool operator==(const KnapSackItem& rhs){ return MyMath::almostEqual(weight, rhs.weight) && MyMath::almostEqual(worth, rhs.worth) && *name == *(rhs.name); } }; class KnapSack{ private: /** * The maximum capacity the knapsack can take */ double capacity; /** * the number of items available in the item pool */ int numOfItems; /** * the item pool from which the items can be picked */ KnapSackItem* items; KnapSack(); public: /** * Initializes a knapSack object with _capacity as max capacity and allocates an array of knapsackitems of the size of _numOfItems on the heap. */ KnapSack(double _capacity, int _numOfItems); KnapSack(const KnapSack& other); ~KnapSack(); friend void swap(KnapSack& first, KnapSack& second); KnapSack& operator=(KnapSack other); double getCapacity() const; int getNumOfItems() const; KnapSackItem* getItems() const; }; std::ostream& operator<<(std::ostream &strm, const KnapSack &v); void swap(KnapSack& first, KnapSack& second); #endif /* MAIN_KNAPSACK_H_ */
sayinala/Capstone
util/TestUtils.h
<gh_stars>1-10 #ifndef UTIL_TESTUTILS_H_ #define UTIL_TESTUTILS_H_ /** * Helper class that provides methods for performing tests. */ class TestUtils { public: /** * Checks whether the file found at the given TEST_OUTPUT_FILE path matches the given ASSUMED_CONTENT. * Reads the file found at the given path and compares line for line with the elements of the ASSUMED_CONTET array. * Returns 0 if everything matches. * Returns -1 if a mismatch occured. */ static inline int checkOutput(const std::string ASSUMED_CONTENT[], const int ASSUMED_CONTENT_LENGTH, const char* TEST_OUTPUT_FILE) { // Read file std::ifstream ifile(TEST_OUTPUT_FILE); std::string strLine; //compare line for line int i = 0; bool matches = true; std::string wholeText; while (std::getline(ifile, strLine) && i<ASSUMED_CONTENT_LENGTH) { wholeText += strLine; if (ASSUMED_CONTENT[i].compare(strLine) != 0){ std::fprintf(stderr, "Mismatch \n'%s' (assumed) \nvs \n'%s' (read)\n", ASSUMED_CONTENT[i].c_str(), strLine.c_str()); matches = false; break; } i++; } if (matches) { // Delete file again std::remove(TEST_OUTPUT_FILE); return 0; } else { std::string assumedText; for (int i = 0; i < ASSUMED_CONTENT_LENGTH; i++){ assumedText += ASSUMED_CONTENT[i]; } std::fprintf(stderr, "Mismatch between written and assumed file content\nAssumed:\n%s\n\nActual:\n%s\n", assumedText.c_str(), wholeText.c_str()); return -1; } } }; #endif /* UTIL_TESTUTILS_H_ */
sayinala/Capstone
main/algorithms/NemhauserUllmannRLPParallelSolver.h
#ifndef MAIN_ALGORITHMS_NEMHAUSERULLMANNRLPPARALLELSOLVER_H_ #define MAIN_ALGORITHMS_NEMHAUSERULLMANNRLPPARALLELSOLVER_H_ #include <string> #include <vector> #include <cmath> #include <omp.h> #include "main/KnapSackSolver.h" // For PlotPoints #include "main/algorithms/NemhauserUllmannSolver.h" /** * This is parallelized version of NemhauserUllmannRLPSolver. * */ class NemhauserUllmannRLPParallelSolver : public KnapSackSolver { public: static const std::string NAME; NemhauserUllmannRLPParallelSolver(std::string inputFilename, std::string outputFilename, int nrOfExecutions = 1, bool sortInputItemsByWeights = true); protected: void setUp(); void tearDown(); void solve(); private: void initPlotPointLists(); void deletePlotPointLists(); /** * Copies PlotPoint 'from' to 'to' only if 'from's weight does not exceed the maximal allowed weight * of our knapsack. * Returns true if the item was actually copied, otherwise false. */ bool copyPlotPointIfItFitsIntoKnapsack(PlotPoint* from, PlotPoint* to); /** * Checks whether a better point than 'ptToCheck' exists in 'list'. 'counter' is the number * of points in 'list'. * A better point means a point which is located in the upper left quarter, so a point with * lower weight but higher worth. */ bool betterPointExists(PlotPoint* ptToCheck, PlotPoint* list, int counter); /** * Sort the list of input items in knapsack by weights descending. The first element at index 0 * will have the highest weight. The sort will take place on the list itself. */ void sortInputItems(); /** * Removes points which cannot contribute to the optimal solution. * Such a point is a point for which the worth summed with * remainingWorthOfInputItems is smaller than the worth of the point * with the highest weight, which is the last item in list. * The list will be modified in such a way that the items will be * shift to the left until no hopeless points exist. * * @return the number of detected and removed points */ int removeHopelessPoints(PlotPoint* list, int counter, const int& remainingWorthOfInputItems); /** * Find PlotPoints which are not pareto-optimal and 'mark' them. Marking means here set the * worth to a negative value. Not pareto-optimal points are points which have other points in * their the upper left quarter, so points with lower weights but higher worths. * * Note, for the points from L_i we only need to check for better points in the list L'_i since * all points in the list are pareto-optimal. The same holds for points from L'_i accordingly. * * @param list1 * @param ctr1 The number of elements in list1 * @param list1 * @param ctr2 The number of elements in list2 */ void markAllNonOptimalPoints(PlotPoint* list1, const int ctr1, PlotPoint* list2, const int ctr2); /* * The PlotPoint lists represent the lists L_i, L'_i and L_{i+i}. * The names are numbered because the roles (L_*) will switch. * The items in the lists are ordered ascend by weight. */ PlotPoint* list0; PlotPoint* list1; PlotPoint* list2; const double knapsackCapacity; const bool sortInputItemsByWeights; static const double NEG_VALUE_FOR_MARKING_NOT_OPTIMAL_POINTS; /** * Used in "parallel for" pragma. If we have only a few items then it is faster to run it on a single * thread. It depends also an the number of threads actually. * For simplicity we will just take a value which delivers the best runtimes tested on a single computer * with 4 cores. The best runtimes delivered 100 (from 1, 100, 500 and 1000) */ static const int THRESHOLD_OF_ITEMS_TO_PARALLELIZE; }; #endif /* MAIN_ALGORITHMS_NEMHAUSERULLMANNRLPPARALLELSOLVER_H_ */
sayinala/Capstone
util/MyMath.h
<gh_stars>1-10 #ifndef UTIL_MYMATH_H_ #define UTIL_MYMATH_H_ #include <cmath> /** * Helper class which provides mathematical helper functions */ class MyMath { public: /** * Range that two floating point numbers may differ to still be considered as equal */ static const double EPSILON; /** * Compares two floating point numbers and checks if they are equal within the constant EPSLION range */ static bool almostEqual(const double& a, const double& b) { return almostEqual(a, b, EPSILON); } /** * Compares two floating point numbers and checks if they are equal within the given epsilon range */ static bool almostEqual(const double& a, const double& b, const double& epsilon) { return std::abs(a-b) < epsilon; } }; #endif /* UTIL_MYMATH_H_ */
sayinala/Capstone
main/algorithms/NemhauserUllmannSolverRLP.h
#ifndef MAIN_ALGORITHMS_NEMHAUSERULLMANNSOLVER_RLP_H_ #define MAIN_ALGORITHMS_NEMHAUSERULLMANNSOLVER_RLP_H_ #include <string> #include <vector> #include "main/KnapSackSolver.h" // For PlotPoints #include "main/algorithms/NemhauserUllmannSolver.h" /** * This is an improvement of NemhauserUllmannSolver. * The suffix RLP means "remove lightest point". * The points which cannot reach the best point will be omitted. * */ class NemhauserUllmannSolverRLP : public KnapSackSolver { public: static const std::string NAME; NemhauserUllmannSolverRLP(std::string inputFilename, std::string outputFilename, int nrOfExecutions = 1, bool sortInputItemsByWeights = true); protected: void setUp(); void tearDown(); void solve(); private: void initPlotPointLists(); void deletePlotPointLists(); /** * Copies PlotPoint 'from' to 'to' only if 'from's weight does not exceed the maximal allowed weight * of our knapsack. * Returns true if the item was actually copied, otherwise false. */ bool copyPlotPointIfItFitsIntoKnapsack(PlotPoint* from, PlotPoint* to); /** * Checks whether a better point than 'ptToCheck' exists in 'list'. 'counter' is the number * of points in 'list'. * A better point means a point which is located in the upper left quarter, so a point with * lower weight but higher worth. */ bool betterPointExists(PlotPoint* ptToCheck, PlotPoint* list, int counter); /** * Sort the list of input items in knapsack by weights descending. The first element at index 0 * will have the highest weight. The sort will take place on the list itself. */ void sortInputItems(); /** * Removes points which cannot contribute to the optimal solution. * Such a point is a point for which the worth summed with * remainingWorthOfInputItems is smaller than the worth of the point * with the highest weight, which is the last item in list. * The list will be modified in such a way that the items will be * shift to the left until no hopeless points exist. * * @return the number of detected and removed points */ int removeHopelessPoints(PlotPoint* list, int counter, const int& remainingWorthOfInputItems); /* * The PlotPoint lists represent the lists L_i, L'_i and L_{i+i}. * The names are numbered because the roles (L_*) will switch. * The items in the lists are ordered ascend by weight. */ PlotPoint* list0; PlotPoint* list1; PlotPoint* list2; const double knapsackCapacity; const bool sortInputItemsByWeights; }; #endif /* MAIN_ALGORITHMS_NEMHAUSERULLMANNSOLVER_RLP_H_ */
jiayuehua/Cpp20
src/splitview.h
#pragma once // https://godbolt.org/z/7GjPzEGo1 #include <ranges> #include <algorithm> #include <string> #include <iostream> #include <span> using namespace std::ranges; template <contiguous_range V, forward_range Pattern> requires view<V> && view<Pattern> && std::indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, equal_to> class contig_split_view : public view_interface<contig_split_view<V, Pattern>> { public: contig_split_view() = default; contig_split_view(V base, Pattern pattern) : base_(base) , pattern_(pattern) { } template <contiguous_range R> requires std::constructible_from<V, views::all_t<R>> && std::constructible_from<Pattern, single_view<range_value_t<R>>> contig_split_view(R&& r, range_value_t<R> elem) : base_(std::views::all(std::forward<R>(r))) , pattern_(std::move(elem)) { } struct sentinel; struct as_sentinel_t { }; class iterator { private: using underlying = std::remove_reference_t< range_reference_t<V>>; friend sentinel; contig_split_view* parent = nullptr; iterator_t<V> cur = iterator_t<V>(); iterator_t<V> next = iterator_t<V>(); public: iterator() = default; iterator(contig_split_view* p) : parent(p) , cur(std::ranges::begin(p->base_)) , next(lookup_next()) { } iterator(as_sentinel_t, contig_split_view* p) : parent(p) , cur(std::ranges::end(p->base_)) , next() { } using iterator_category = std::forward_iterator_tag; struct reference : std::span<underlying> { using std::span<underlying>::span; operator std::string_view() const requires std::same_as<range_value_t<V>, char> { return {this->data(), this->size()}; } }; using value_type = reference; using difference_type = std::ptrdiff_t; bool operator==(iterator const& rhs) const { return cur == rhs.cur; } auto lookup_next() const -> iterator_t<V> { return std::ranges::search( subrange(cur, std::ranges::end(parent->base_)), parent->pattern_ ).begin(); } auto operator++() -> iterator& { cur = next; if (cur != std::ranges::end(parent->base_)) { cur += distance(parent->pattern_); next = lookup_next(); } return *this; } auto operator++(int) -> iterator { auto tmp = *this; ++*this; return tmp; } auto operator*() const -> reference { return {cur, next}; } }; struct sentinel { bool operator==(iterator const& rhs) const { return rhs.cur == sentinel; } sentinel_t<V> sentinel; }; auto begin() -> iterator { if (not cached_begin_) { cached_begin_.emplace(this); } return *cached_begin_; } auto end() -> sentinel { return {std::ranges::end(base_)}; } auto end() -> iterator requires common_range<V> { return {as_sentinel_t(), this}; } private: V base_ = V(); Pattern pattern_ = Pattern(); std::optional<iterator> cached_begin_; }; namespace std::ranges { template<contiguous_range V, forward_range Pattern> requires view<V> && view<Pattern> && indirectly_comparable<iterator_t<V>, iterator_t<Pattern>, equal_to> class split_view<V, Pattern> : public contig_split_view<V, Pattern> { using contig_split_view<V, Pattern>::contig_split_view; }; } struct zstring_sentinel { bool operator==(char const* p) const { return *p == '\0'; } }; struct zstring : view_interface<zstring> { char const* p = nullptr; zstring() = default; zstring(char const* p) : p(p) { } auto begin() const { return p; } auto end() const { return zstring_sentinel{}; } }; //int main() { // using namespace std::literals; // using V = contig_split_view<std::string_view, std::string_view>; // using It = V::iterator; // using S = V::sentinel; // static_assert(std::sentinel_for<S, It>); // static_assert(forward_range<V>); // static_assert(common_range<V>); // static_assert(view<V>); // static_assert(std::indirectly_readable<It>); // static_assert(std::forward_iterator<It>); // // V v = contig_split_view("127..0..0..1"sv, ".."sv); // std::ranges::begin(v); // // for (std::string_view sv : "127..0..0..1"sv | std::views::split(".."sv)) // { // std::cout << sv << '\n'; // } // // auto ip = "127.0.0.1"s; // auto parts = ip | std::views::split('.'); // auto as_vec = std::vector<std::string>(parts.begin(), parts.end()); // std::cout << as_vec.size() << '\n'; // // char const* words = "A quick brown fox"; // static_assert(view<zstring>); // for (std::string_view sv : zstring{words} | std::views::split(' ')) { // std::cout << sv << '\n'; // } // return 0; //}
jiayuehua/Cpp20
src/boolean.h
#pragma once #include <concepts> struct boolean { private: bool _val; public: constexpr boolean() noexcept = default; template<std::convertible_to<bool> T> explicit(!std::same_as<T, bool>) constexpr boolean(T b) noexcept : _val(b) {} template<std::constructible_from<bool> T> explicit(!std::same_as<bool, T>) constexpr operator T() const noexcept { return T(_val); } constexpr boolean operator!() const noexcept { return !_val; } constexpr boolean operator==(bool other) const noexcept { return bool(*this) == other; } constexpr boolean operator!=(bool other) const noexcept { return bool(*this) != other; } constexpr auto operator<=>(bool other) const noexcept { return bool(*this) <=> other; } };
jiayuehua/Cpp20
src/detect_expr.h
#pragma once //#include "https://raw.githubusercontent.com/PeterSommerlad/PSsimplesafeint/main/include/psssafeint.h""" #include <iostream> namespace compile_checks { //using namespace psssint; template<auto value> using consume_value = void; #define concat_line_impl(A, B) A##_##B #define concat_line(A, B) concat_line_impl(A, B) #define check_does_compile(NOT, FROM, oper) \ namespace concat_line(NOT##_test, __LINE__) \ { \ template<typename T, typename = void> \ constexpr bool \ expression_compiles = false; \ template<typename T> \ constexpr bool \ expression_compiles<T, consume_value<(T {} oper T{})>> = true; \ static_assert(NOT expression_compiles<FROM>, "should not compile: " #oper); \ }// namespace tag check_does_compile(not, int, /) check_does_compile(, int, +) }// namespace compile_checks #undef check_does_compile #undef concat_line_impl #undef concat_line
haikieu/Swift-Tool-Kit
ToolKit/ToolKit/ToolKit.h
<reponame>haikieu/Swift-Tool-Kit // // ToolKit.h // ToolKit // // Created by <NAME> on 1/28/18. // Copyright © 2018 <EMAIL>. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for ToolKit. FOUNDATION_EXPORT double ToolKitVersionNumber; //! Project version string for ToolKit. FOUNDATION_EXPORT const unsigned char ToolKitVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <ToolKit/PublicHeader.h>
haikieu/Swift-Tool-Kit
ToolKitUI/DevKitUI/DevKitUI.h
<reponame>haikieu/Swift-Tool-Kit // // ToolKitUI.h // ToolKitUI // // Created by <NAME> on 1/28/18. // Copyright © 2018 <EMAIL>. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for ToolKitUI. FOUNDATION_EXPORT double ToolKitUIVersionNumber; //! Project version string for ToolKitUI. FOUNDATION_EXPORT const unsigned char ToolKitUIVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <ToolKitUI/PublicHeader.h>
ybabs/dji-drone-planner
include/uav_agent/controllers/pid_alt.h
// Alternative implementation of PID controller from : https://github.com/pms67/PID #ifndef PID_CONTROLLER_H #define PID_CONTROLLER_H struct PIDControl { // Gains float Kp; float Ki; float Kd; /* LPF time constant derivative */ float tau; // Output limits float max_limit; float min_limit; // Sample Time float dt; float integrator; float prev_error; float differentiator; float prev_value; // output float output; }; void PIDInit(PIDControl * pid); float PIDUpdate(PIDControl *pid, float setpoint, float measurement); #endif
ybabs/dji-drone-planner
include/uav_agent/base/control.h
<filename>include/uav_agent/base/control.h #ifndef CONTROL_H #define CONTROL_H #include "uav_agent/base/base.h" class HLControl : public Base { public: HLControl(); bool takeoff(); bool M100Takeoff(); bool M100Land(); bool land(); void rth(); float computeTimeToLand(); bool takeoffLand(int task); private: float land_time; int motor_wait_time; int takeoff_timeout; float takeoff_altitude; }; #endif // if you dont listen to me and whatever i say // there will be consequences // random shit will start to show up like this in your code // but you wont be this lucky // cuz you wont be able find it // // Whuahahahahahahahahhahahahahahahahahahahahahaha // // _..--""````""--.._ // .' |\/| '. // / /`._ | | _.'\ \ // ; / \ | // | / \ | // ; / .-. .-. \ ; // \ |/ \.-. .-./ \| / // '._ \/ _.' // ''--..____..--'' // // whuahahahahahahahahahahahahahahahahahahahahaha
ybabs/dji-drone-planner
include/uav_agent/base/base.h
<filename>include/uav_agent/base/base.h #ifndef FLIGHT_BASE #define FLIGHT_BASE #include <ros/ros.h> #include <geometry_msgs/QuaternionStamped.h> #include <geometry_msgs/Vector3Stamped.h> #include <sensor_msgs/NavSatFix.h> #include <std_msgs/UInt8.h> #include <tf/tf.h> #include <sensor_msgs/Joy.h> #include <std_msgs/Float32.h> #include <djiosdk/dji_vehicle.hpp> #include <dji_sdk/dji_sdk_node.h> #include "dji_sdk/dji_sdk.h" #include <dji_sdk/DroneTaskControl.h> #include <dji_sdk/SDKControlAuthority.h> #include <dji_sdk/QueryDroneVersion.h> #include <dji_sdk/SetLocalPosRef.h> #include <dji_sdk/Activation.h> #include "uav_agent/utils/utils.h" struct UAV { typedef enum { M100 = 0, N3 = 1, A3 = 2, UNKNOWN = 2 } Type; }; class Base { public: Base(); ~Base(); void activate(); // activate UAV for SDK control bool obtainControl(); bool releaseControl(); void localPositionCallback(const geometry_msgs::PointStamped::ConstPtr &msg); void attitudeCallback(const geometry_msgs::QuaternionStamped::ConstPtr &msg); void flightStatusCallback(const std_msgs::UInt8::ConstPtr& msg); void displayModeCallback(const std_msgs::UInt8::ConstPtr& msg); void gpsCallback(const sensor_msgs::NavSatFix::ConstPtr& msg); void gpsHealthCallback(const std_msgs::UInt8::ConstPtr& msg); void altitudeCallback(const std_msgs::Float32::ConstPtr& msg); UAV::Type checkUAVType(); bool setLocalPosition(); void flightAnomalyCallback(const dji_sdk::FlightAnomaly::ConstPtr &msg); void velocityCallback(const geometry_msgs::Vector3Stamped::ConstPtr& msg); protected: ros::NodeHandle nh; ros::ServiceClient ctrl_authority_service; ros::ServiceClient drone_task_service; ros::ServiceClient query_version_service; ros::ServiceClient drone_activation_service; ros::ServiceClient set_local_pos_reference; ros::Subscriber gps_subscriber; ros::Subscriber gps_health_subscriber; ros::Subscriber flight_status_subscriber; ros::Subscriber altitude_subscriber; ros::Subscriber attitude_subscriber; ros::Subscriber local_position_subscriber; ros::Subscriber velocity_subscriber; geometry_msgs::Vector3Stamped velocity_data; geometry_msgs::Point current_local_position; sensor_msgs::NavSatFix current_gps_location; geometry_msgs::Quaternion current_drone_attitude; uint8_t flight_status; uint8_t display_mode; uint8_t gps_health; float altitude_above_takeoff; UAV::Type uav_model; ros::Time current_time; ros::Time prev_time; double dt; }; #endif
ybabs/dji-drone-planner
include/uav_agent/controllers/pid.h
<reponame>ybabs/dji-drone-planner #ifndef _PID_H_ #define _PID_H_ #include <ros/ros.h> struct pid { float current_effort; float target_effort; float prev_position; // to get rid of derivative kick float error; float prev_error; float Kp; float Ki; float Kd; float output; float integral; float max_effort; float min_effort; float sample_time; } ; class PIDController { public: PIDController(); void init(float kp, float ki, float kd, float max, float min); void reset(); float update(float setpoint, float current, float dt); private: pid pid_; int index; }; #endif
ybabs/dji-drone-planner
include/uav_agent/utils/utils.h
#include <cmath> #include <geometry_msgs/QuaternionStamped.h> #include <geometry_msgs/Vector3Stamped.h> #define PI (double) 3.141592653589793 #define C_EARTH (double)6378137.0 static double DegToRad(double degree) { return degree * (PI/180.0); } static double RadToDeg(double rad) { return rad * (180.0/PI); } static geometry_msgs::Vector3 toEulerAngle(geometry_msgs::Quaternion quat) { geometry_msgs::Vector3 ans; tf::Matrix3x3 R_FLU2ENU(tf::Quaternion(quat.x, quat.y, quat.z, quat.w)); R_FLU2ENU.getRPY(ans.x, ans.y, ans.z); return ans; }
ybabs/dji-drone-planner
include/uav_agent/base/planner.h
<filename>include/uav_agent/base/planner.h #ifndef PLANNER_H #define PLANNER_H #include <tuple> #include <Eigen/Dense> #include <Eigen/Geometry> #include <queue> #include "uav_agent/controllers/pid.h" #include "uav_agent/base/base.h" #include "uav_agent/base/control.h" #include "gcs/Action.h" #include "gcs/Waypoint.h" #include "gcs/Missionparameters.h" class HLControl; class PIDController; enum MissionState { IDLE = 0, NEW_WAYPOINT = 1, ARRIVED = 2, FINISHED = 3, RTH = 4 }; class Planner: public Base { public: Planner(); ~Planner(); void setWaypoint(sensor_msgs::NavSatFix new_waypoint); void fly(); void flyHome(); void setYawAngle(); void getLocalPositionOffset(geometry_msgs::Vector3 &deltaENU, sensor_msgs::NavSatFix &target, sensor_msgs::NavSatFix &origin); bool isMissionFinished(); bool reachedWaypoint(); void onWaypointReached(); void onMissionFinished(); void runMission(); void prepareFlightPlan(gcs::Waypoint waypoint); void appendFlightPlan(gcs::Waypoint waypoint); void droneControlSignal(double x, double y, double z, double yaw, bool use_yaw_rate = true, bool use_ground_frame = true); void setZOffset(double offset); Eigen::Vector3d getEffort(Eigen::Vector3d &target); Eigen::Vector2d getHorizontalEffort(Eigen::Vector2d &target); Eigen::Vector3d getHomeEffort(Eigen::Vector3d &target); Eigen::Vector3d setTargetVector(float target_x, float target_y, float target_z); Eigen::Vector3d setHomeTarget(float x, float y, float z); float setYaw(float yaw); void flightAnomalyCallback(const dji_sdk::FlightAnomaly::ConstPtr &msg); void missionParamCallback(const gcs::Missionparameters::ConstPtr &msg); void missionPauseCallback(const std_msgs::UInt8::ConstPtr& msg); void waypointCallback(const gcs::Waypoint::ConstPtr &msg); void missionActionCallback(const gcs::Action::ConstPtr &msg); double getPositionError(sensor_msgs::NavSatFix &origin, gcs::Waypoint &target); void computeLandingError(); private: HLControl control; PIDController pid_pos; PIDController pid_z; PIDController pid_yaw; int uav_state; // int alti_control; int waypoint_index; int waypoint_count; int uav_speed; int mission_end_action; int drone_action; int play_pause; Eigen::Vector3d target_position_vector; Eigen::Vector3d home_position_vector; float target_yaw_angle; float desired_yaw_angle; float current_yaw_angle; float z_offset_takeoff; float yaw_limit; float distance_to_setpoint; float xy_setpoint_dist; float home_target_norm; float home_distance; float target_norm; float hori_target_norm; int drone_version; int ctrl_flag; uint32_t flight_anomaly_data; float kp, ki, kd; float kp_z, ki_z, kd_z; float kp_y, ki_y, kd_y; float z_max = 5; float z_min = -4; float z_clamp_p; float z_clamp_n; double total_landing_error; sensor_msgs::NavSatFix start_gps_location; sensor_msgs::NavSatFix home_gps_location; sensor_msgs::NavSatFix home_start_gps_location; geometry_msgs::Point start_local_position; std::vector<gcs::Waypoint> flight_plan; ros::Subscriber param_subscriber; ros::Subscriber waypoint_subscriber; ros::Subscriber mission_pause_subscriber; ros::Subscriber mission_action_subscriber; ros::Subscriber flight_anomaly_subscriber; ros::Publisher daqrecord_publisher; bool waypoint_finished; bool yaw_flag; bool takeoff_result; bool rth_complete; uint8_t control_flag = (DJISDK::VERTICAL_VELOCITY | DJISDK::HORIZONTAL_VELOCITY | DJISDK::YAW_RATE | DJISDK::HORIZONTAL_GROUND | DJISDK::STABLE_ENABLE); ros::Publisher control_publisher; ros::Publisher error_publisher; }; #endif
Nero-Hu/speech
HMM/hmm.h
// // hmm.h // HMM // // Created by NeroHu on 3/5/15. // Copyright (c) 2015 hthu. All rights reserved. // #ifndef HMM_hmm_h #define HMM_hmm_h #include <vector> #include <iostream> #include <deque> typedef std::vector<int> ObsVector; typedef std::vector<float> RowVector; typedef std::deque<RowVector> Beta; typedef std::vector<RowVector> Table; class HMM { private: int _states; int _iter; void ComputeForward(ObsVector obs) { // Clear old values _alpha.clear(); _coef.clear(); for (int it = 0; it < obs.size(); it++) { RowVector alpha; float sum = 0.0; if( it == 0) { for (int i = 0; i < _states; i++) { alpha.push_back(_startProb[i] * _emissionProb[i][obs[it]]); sum += alpha[i]; } for (int i = 0; i < _states; i++) { alpha[i] /= sum; } _alpha.push_back(alpha); _coef.push_back(sum); continue; } for (int i = 0; i < _states; i++) { float score = 0.0; for (int j = 0; j < _states; j++) { score += _alpha[it-1][j] * _transitionProb[j][i] * _emissionProb[i][obs[it]]; } sum += score; alpha.push_back(score); } //Normalize alpha, and save coefficient for (int i =0; i < _states; i++) { alpha[i] /= sum; } _coef.push_back(sum); _alpha.push_back(alpha); } } void ComputeBackward(ObsVector obs) { _beta.clear(); for (int it = (int)obs.size() - 1 ; it >= 0 ; it--) { float coef = _coef[it]; RowVector beta; if( it == (int)obs.size() -1 ) { for (int i = 0; i < _states; i++) { beta.push_back(1.0/coef); } _beta.push_front(beta); continue; } for (int i = 0; i < _states; i++) { float score = 0.0; for (int j = 0; j < _states; j++) { score += _beta[0][j] * _transitionProb[i][j] * _emissionProb[j][obs[it+1]] / coef; } beta.push_back(score); } _beta.push_front(beta); } } void NormalizeTableByRow(Table *table) { for (Table::iterator it=table->begin(); it != table->end(); it++) { float sum = 0.0; for (RowVector::iterator row = it->begin(); row != it->end(); row++) { sum += *row; } for (RowVector::iterator row = it->begin(); row != it->end(); row++) { *row /= sum; } } } void doEM(ObsVector obs) { ComputeForward(obs); ComputeBackward(obs); Table gamma; //Save sum of state gamma as denominator RowVector stateGammaSum; stateGammaSum.resize(_states); Table sigma; sigma.resize(_states); //Compute gamma & Compute denominator for sigma for (int it = 0; it < (int)obs.size(); it++) { RowVector rowGamma; float sum = 0.0; for (int j = 0; j < _states; j++) { float albeta = _alpha[it][j] * _beta[it][j]; rowGamma.push_back(albeta); sum += albeta; } for (int j = 0; j < _states; j++) { rowGamma[j] /= sum; stateGammaSum[j] += rowGamma[j]; } gamma.push_back(rowGamma); float denom = 0.0; Table sigmaCount; if (it < (int)obs.size()-1) { for (int i = 0 ; i < _states; i++) { RowVector sigmaRow; for (int j = 0; j < _states; j++) { float sig = _alpha[it][i] * _transitionProb[i][j] * _beta[it+1][j] * _emissionProb[j][obs[it+1]]; denom += sig; sigmaRow.push_back(sig); } sigmaCount.push_back(sigmaRow); } for (int i = 0 ; i < _states; i++) { sigma[i].resize(_states); for (int j = 0; j < _states; j++) { sigma[i][j] += sigmaCount[i][j] / denom; } } } } //Re-estimate Transition probability for (int i = 0 ; i < _states; i++) { for (int j = 0; j < _states; j++) { _transitionProb[i][j] = sigma[i][j] / stateGammaSum[i]; } } NormalizeTableByRow(&_transitionProb); //Update start probability using gamma[0] _startProb = gamma[0]; //Update emission probability for (Table::iterator it = _emissionProb.begin(); it != _emissionProb.end(); it++) { std::fill(it->begin(), it->end(), 0.0); } for (int it = 0; it < (int)obs.size(); it++) { for (int i = 0; i < _states; i++) { _emissionProb[i][obs[it]] += gamma[it][i] / stateGammaSum[i]; } } } void printTable(Table t) { for (Table::iterator it = t.begin() ; it != t.end(); ++it){ for (RowVector::iterator r = it->begin(); r != it->end(); ++r) { std::cout << *r << ", " ; } std::cout << std::endl; } } public: Table _alpha, _transitionProb, _emissionProb; RowVector _coef, _startProb, _logProb; Beta _beta; HMM() { } HMM(RowVector startProb, Table transitionProb, Table emissionProb) { _startProb = startProb; _transitionProb = transitionProb; _emissionProb = emissionProb; _states = (int)_transitionProb.size(); _iter = 5; } void setIter(int iter) { _iter = iter; } void Train(ObsVector obs) { _alpha.reserve(obs.size()); for (int it = 0; it < _iter; it++ ) { std::cout.flush(); if ( it%20 == 0) { std::cout << '.' ; } doEM(obs); } std::cout << std::endl; } void printResult() { std::cout << "Transiton Probability=======" << std::endl; printTable(_transitionProb); std::cout << "Emission Probability=======" << std::endl; printTable(_emissionProb); } }; #endif
Nero-Hu/speech
recognizer/fenonic.h
<gh_stars>0 // // fenonic.h // recognizer // // Created by NeroHu on 3/6/15. // Copyright (c) 2015 hthu. All rights reserved. // #ifndef recognizer_fenonic_h #define recognizer_fenonic_h #include <iostream> #include <fstream> #include <unordered_map> #include <deque> #include <cmath> #include <set> #include "hmm.h" static const std::string LBLNAMES = "clsp.lblnames"; static const std::string TRNSCR = "clsp.trnscr"; static const std::string TRNWAV = "clsp.trnwav"; static const std::string TRNLBLS = "clsp.trnlbls"; static const std::string ENDPT = "clsp.endpts"; static const std::string DEVLBLS = "clsp.devlbls"; static const std::string DEVWAV = "clsp.devwav"; //Pair of one training src, like <wav file name, <vector<Labels>, <startLoc, endLoc>>> //e.g: <0005.wav, <HH, HM ..., >, <48,96>>> typedef std::pair<std::string, std::pair<StringVec, std::pair<int, int> > > TPair; //Training Map typedef std::map<std::string, std::vector<TPair> > TMap; //HMM Map typedef std::map<std::string, HMM> HMap; //baseform Map typedef std::unordered_map<std::string, StringVec> Baseform; class Fenonic { //Mapping the fenoms and their HMM HMap fenoMap; //Training pair <word, Vector<TPair> TMap trnPair; //Contrast system pair using 20-80 splits TMap cstTrnPair; TMap cstTstPair; //Baseform for words Baseform _baseform; //For current word baseform StringVec curBaseform; //For dev labels std::vector<StringVec> devLabelVec; StringVec devWavVec; bool _isContrast; //total frames float totalFrames; void ConstructData() { trnPair.clear(); cstTrnPair.clear(); cstTstPair.clear(); std::string delimiter = " "; std::ifstream trnscr, trnwav, trnlbls, trnEndpt, devLbls, devWav; std::string strScr, strWav, strLbls, strEndpt, strDevLbls, strDevWav; trnscr.open(TRNSCR); trnwav.open(TRNWAV); trnlbls.open(TRNLBLS); trnEndpt.open(ENDPT); devLbls.open(DEVLBLS); devWav.open(DEVWAV); //Trim first line trnscr >> strScr; trnwav >> strWav; std::getline(trnlbls,strLbls); trnEndpt >> strEndpt; std::getline(devLbls,strDevLbls); devWav >> strDevWav; //Load training data int i = 0; totalFrames = 0; for (i = 0;trnscr >> strScr && trnwav >> strWav && std::getline(trnlbls,strLbls); i++) { //If first time, make a new vector if (trnPair.find(strScr) == trnPair.end()) { std::vector<TPair> pair; StringVec fenem; size_t pos = 0; std::string token; for (int j = 0; (pos = strLbls.find(delimiter)) != std::string::npos; j++) { token = strLbls.substr(0, pos); fenem.push_back(token); strLbls.erase(0, pos + delimiter.length()); totalFrames += 1; } int start, end; trnEndpt >> start; trnEndpt >> end; pair.push_back(std::make_pair(strWav, std::make_pair(fenem, std::make_pair(start, end)))); trnPair.insert(std::make_pair(strScr, pair)); //Construct a baseform for each word StringVec base; base.push_back(SIL); for (int i = start; i < end-1; i++) { base.push_back(fenem[i]); } base.push_back(SIL); _baseform.insert(std::make_pair(strScr, base)); } //If key exists just push back else { StringVec fenem; size_t pos = 0; std::string token; for (int j = 0; (pos = strLbls.find(delimiter)) != std::string::npos; j++) { token = strLbls.substr(0, pos); fenem.push_back(token); strLbls.erase(0, pos + delimiter.length()); totalFrames += 1; } int start, end; trnEndpt >> start; trnEndpt >> end; //push back to existing vector trnPair.find(strScr)->second.push_back(std::make_pair(strWav, std::make_pair(fenem, std::make_pair(start, end)))); } } std::cout << "Load " << i << " lines of training data, with total " << totalFrames << " frames. " << std::endl; //Load dev data while (std::getline(devLbls,strDevLbls) && devWav >> strDevWav) { StringVec fenem; size_t pos = 0; std::string token; for (int j = 0; (pos = strDevLbls.find(delimiter)) != std::string::npos; j++) { token = strDevLbls.substr(0, pos); fenem.push_back(token); strDevLbls.erase(0, pos + delimiter.length()); } devLabelVec.push_back(fenem); devWavVec.push_back(strDevWav); } std::cout << "Load " << devLabelVec.size() << " lines of dev data" << std::endl; //Normal mode if (!_isContrast) { //Set train pair to be whole set cstTrnPair = trnPair; } //Contrast system else{ std::cout << "Using contrastive setting =============" << std::endl; std::cout << "Shuffle data into 2 parts..." << std::endl; std::set<int> keyList; for (TMap::iterator it = trnPair.begin(); it != trnPair.end(); it++) { keyList.clear(); std::string key = it->first; std::vector<TPair> pair = it->second; int range = (int)pair.size(); int trainLen = range * 4 / 5; std::vector<TPair> insertPair; while ((int)insertPair.size() < trainLen) { //random a number not in keyList set int loc = rand() % range; while (keyList.find(loc) != keyList.end()) { loc = rand() % range; } keyList.insert(loc); //Add this vector into cstTrnpair if (cstTrnPair.find(key) == cstTrnPair.end()) { insertPair.push_back(pair[loc]); } } //Insert train pair cstTrnPair.insert(std::make_pair(key, insertPair)); //Insert test pair, using left loc's insertPair.clear(); for (int i = 0; i < range; i++) { if (keyList.find(i) == keyList.end()) { insertPair.push_back(pair[i]); } } cstTstPair.insert(std::make_pair(key, insertPair)); } } } public: //alpha, beta for trellis std::vector<RowVec> _alpha; std::deque<ReRowVec> _beta; RowVec _coef; //total states for a trellis float sumStates; //Loglikelihood std::vector<float> _logProb; Fenonic(bool isContrast) { HIdxMap.clear(); std::ifstream infile; std::string data; infile.open(LBLNAMES); //Skip first line infile >> data; //Initialize map pair for fenoms and its corresponding HMM for (int i = 0 ; infile >> data; i++) { fenoMap.insert(std::make_pair(data, HMM(data,i))); HIdxMap.insert(std::make_pair(data, i)); } fenoMap.insert(std::make_pair(SIL, HMM(SIL,FENO_SIZE-1))); HIdxMap.insert(std::make_pair(SIL, FENO_SIZE-1)); //construct train pair _isContrast = isContrast; ConstructData(); } void Train() { _logProb.clear(); int insCount = 0; for (TMap::iterator it = cstTrnPair.begin(); it != cstTrnPair.end(); it++) { curBaseform = _baseform.find(it->first)->second; //For each word training instance for (std::vector<TPair>::iterator ins = it->second.begin(); ins != it->second.end(); ins++) { insCount++; if (insCount % 50 == 0) { std::cout << "." << std::flush; } //Clean alpha, beta and coefficient _alpha.clear(); _beta.clear(); _coef.clear(); //Put alpha0, set start state to be 1 RowVec alpha0; //Reset sum states for each instance sumStates = 0.0; for (StringVec::iterator fe = curBaseform.begin(); fe != curBaseform.end(); fe++) { for (int i = 0; i < fenoMap.find(*fe)->second._numOfStates; i++) { alpha0.push_back(1.0); sumStates += 1.0; } } //Uniform start probability for (RowVec::iterator a0 = alpha0.begin(); a0 != alpha0.end(); a0++) { *a0 /= sumStates; } _alpha.push_back(alpha0); CollectCounts(ins->second.first); } } //Update transition and emission probabilities for (Baseform::iterator base = _baseform.begin(); base != _baseform.end(); base++) { StringVec fenoms = base->second; //Could be duplicate update, but we don't reset counts here, so results will be fine for (StringVec::iterator fe = fenoms.begin(); fe != fenoms.end(); fe++) { fenoMap.find(*fe)->second.Update(); } } //Reset counts for (HMap::iterator fe = fenoMap.begin(); fe != fenoMap.end(); fe++) { //Reset counts fe->second.ResetCounts(); } } void CollectCounts(StringVec obs) { float logProb = 0.0; RowVec predAlpha = _alpha[0]; _coef.push_back(1.0); //Alpha and beta vector for each instance for (StringVec::iterator it = obs.begin(); it != obs.end(); it++) { RowVec alphaVec; //for baseform trellis, compute alpha int feLoc = 0; float sum = 0.0; for (StringVec::iterator fe = curBaseform.begin(); fe != curBaseform.end(); fe++) { HMM hmm = fenoMap.find(*fe)->second; hmm.ComputeForward(predAlpha, feLoc, &alphaVec, *it); feLoc += hmm._numOfStates; } //Normalize alpha for (RowVec::iterator a = alphaVec.begin(); a != alphaVec.end(); a++) { sum += *a; } for (RowVec::iterator a = alphaVec.begin(); a != alphaVec.end(); a++) { *a /= sum; } //Push to coefficient logProb += logf(sum); _coef.push_back(sum); predAlpha = alphaVec; _alpha.push_back(alphaVec); } _logProb.push_back(logProb); //Initialize beta with 1/coefficient ReRowVec successorBeta; RowVec lastAlpha = _alpha.back(); float coef = _coef.back(); for (RowVec::iterator la = lastAlpha.begin(); la != lastAlpha.end(); la++) { successorBeta.push_back(1.0/coef); } _beta.push_front(successorBeta); //Compute beta for (int i = (int)obs.size()-1; i >=0 ; i--) { ReRowVec betaVec; //for baseform trellis, compute beta int endLoc = sumStates-1; //Loop from back, since the beta from successor should be carried for (StringVec::reverse_iterator fe = curBaseform.rbegin(); fe != curBaseform.rend(); fe++) { HMM hmm = fenoMap.find(*fe)->second; hmm.ComputeBackwardAndColCounts(&_alpha[i], _coef[i], successorBeta, endLoc, &betaVec, obs[i]); endLoc -= hmm._numOfStates; } successorBeta = betaVec; _beta.push_front(betaVec); } } //Given a sequence of observation, find the most likely word //Return the most likely word std::string findMostLikelyWord(StringVec obs, std::string wav) { StringVec cur; //record each word and its prob with pair std::vector<float> sum; std::string maxWord; float maxProb = -INFINITY; for (Baseform::iterator it = _baseform.begin(); it != _baseform.end(); it++) { cur = it->second; //log prob float prob = 0.0; RowVec predAlpha; //Reset sum states for each instance sumStates = 0.0; for (StringVec::iterator fe = cur.begin(); fe != cur.end(); fe++) { for (int i = 0; i < fenoMap.find(*fe)->second._numOfStates; i++) { predAlpha.push_back(1.0); sumStates += 1.0; } } //Uniform start probability for (RowVec::iterator a0 = predAlpha.begin(); a0 != predAlpha.end(); a0++) { *a0 /= sumStates; } //Start compute forward for (StringVec::iterator it = obs.begin(); it != obs.end(); it++) { RowVec alphaVec; //for baseform trellis, compute alpha int feLoc = 0; float sum = 0.0; for (StringVec::iterator fe = cur.begin(); fe != cur.end(); fe++) { HMM hmm = fenoMap.find(*fe)->second; hmm.ComputeForward(predAlpha, feLoc, &alphaVec, *it); feLoc += hmm._numOfStates; } //Normalize alpha for (RowVec::iterator a = alphaVec.begin(); a != alphaVec.end(); a++) { sum += *a; } for (RowVec::iterator a = alphaVec.begin(); a != alphaVec.end(); a++) { *a /= sum; } predAlpha = alphaVec; //Rescale prob += logf(sum); } if (prob > maxProb) { maxProb = prob; maxWord = it->first; } //save all prob in the sum, and sum.push_back(prob); } //Output only when not in contrast mode if (!_isContrast) { float sumP = 0; //Compute confidence level through exp domain, set throw away threshold to be 20 for (std::vector<float>::iterator p = sum.begin(); p != sum.end(); p++) { if (*p - maxProb > -20) { sumP += exp(*p - maxProb); } } maxProb = 1.0/sumP; std::cout << "wav file: " << wav << ", predict word : " << maxWord << " with confidence " << maxProb << std::endl; } return maxWord; } //For each test label, find the maximum void Predict() { std::cout << "Start prediciting outputs on test data..." << std::endl; int i = 0; for (std::vector<StringVec>::iterator sv = devLabelVec.begin(); sv != devLabelVec.end(); sv++) { findMostLikelyWord(*sv, devWavVec[i]); i++; } } //Compute accuracy, used in contrast mode float ComputeAcc() { float acc = 0.0; float sum = 0.0; //For each word in std::cout << std::endl; for (TMap::iterator it = cstTstPair.begin(); it != cstTstPair.end(); it++) { for (std::vector<TPair>::iterator ins = it->second.begin(); ins != it->second.end(); ins++) { std::string result = findMostLikelyWord(ins->second.first, ""); if (result == it->first) { acc++; } sum++; if (int(sum) % 10 == 0) { //report progress std::cout << "Right prediction : " << acc << " out of total : " << sum << std::endl; } } } std::cout << "Right prediction : " << acc << " out of total : " << sum << std::endl; std::cout << "Accuracy : " << acc/sum << std::endl; return acc/sum; } void PrintLogLikelihood() { float sumP = 0.0; for (std::vector<float>::iterator log = _logProb.begin(); log != _logProb.end(); log++) { sumP += *log; } sumP /= totalFrames; std::cout << std::endl << "Log-prob : " << sumP << std::endl; } }; #endif
Nero-Hu/speech
recognizer/hmm.h
// // hmm.h // HMM // // Created by NeroHu on 3/5/15. // Copyright (c) 2015 hthu. All rights reserved. // #ifndef HMM_hmm_h #define HMM_hmm_h #include <vector> #include <map> #include <ctime> static const int FENO_SIZE = 257; static const std::string SIL = "<sil>"; static std::map<std::string, int> HIdxMap; //Row float vector typedef std::vector<float> RowVec; //Row vector has better performance that can loop from bottom typedef std::deque<float> ReRowVec; typedef std::vector<std::string> StringVec; class HMM { public: int _numOfStates; std::string _name; //2d array for transition probability float **_pProb, **_qProb, **_pCount, **_qCount; //3d array for emission probability float ***_eProb, ***_eCount; HMM() { } HMM(std::string name, int idx) { _name = name; //For sil HMM if (name == SIL) { _numOfStates = 7; //Construct SIL model //Initialize transition 2d array _pProb = new float*[_numOfStates]; _pCount =new float*[_numOfStates]; for (int i = 0; i<_numOfStates; i++) { _pProb[i] = new float[_numOfStates]; _pCount[i] = new float[_numOfStates]; for (int j = 0; j < _numOfStates; j++) { _pProb[i][j] = 0.0; _pCount[i][j] = 0.0; } } //Initialize null transition 2d array _qProb = new float*[_numOfStates]; _qCount = new float*[_numOfStates]; for (int i = 0; i<_numOfStates; i++) { _qProb[i] = new float[_numOfStates]; _qCount[i] = new float[_numOfStates]; for (int j = 0; j < _numOfStates; j++) { _qProb[i][j] = 0.0; _qCount[i][j] = 0.0; } } //Initialize emission 3d array _eProb = new float**[_numOfStates]; _eCount = new float**[_numOfStates]; for (int i = 0; i < _numOfStates; i++) { _eProb[i] = new float*[_numOfStates]; _eCount[i] = new float*[_numOfStates]; for (int j = 0; j < _numOfStates; j++) { _eProb[i][j] = new float[FENO_SIZE-1]; _eCount[i][j] = new float[FENO_SIZE-1]; for (int k = 0; k < FENO_SIZE-1; k++) { _eProb[i][j][k] = 1.0/256.0; _eCount[i][j][k] = 0.0; } } } //Set transition prob _pProb[0][1] = 0.5; _pProb[0][3] = 0.5; _pProb[1][1] = 0.5; _pProb[1][2] = 0.5; _pProb[2][2] = 0.5; _pProb[2][6] = 0.5; _pProb[3][4] = 0.5; _pProb[4][5] = 0.5; _pProb[5][6] = 0.5; //Set null prob _qProb[3][6] = 0.5; _qProb[4][6] = 0.5; _qProb[5][6] = 0.5; } //For regular baseform else{ _numOfStates = 2; //Initialize transition 2d array _pProb = new float*[_numOfStates]; _pCount = new float*[_numOfStates]; for (int i = 0; i<_numOfStates; i++) { _pProb[i] = new float[_numOfStates]; _pCount[i] = new float[_numOfStates]; for (int j = 0; j < _numOfStates; j++) { _pProb[i][j] = 0.0; _pCount[i][j] = 0.0; } } //Initialize null transition 2d array _qProb = new float*[_numOfStates]; _qCount = new float*[_numOfStates]; for (int i = 0; i<_numOfStates; i++) { _qProb[i] = new float[_numOfStates]; _qCount[i] = new float[_numOfStates]; for (int j = 0; j < _numOfStates; j++) { _qProb[i][j] = 0.0; _qCount[i][j] = 0.0; } } //Initialize emission 3d array _eProb = new float**[_numOfStates]; _eCount = new float**[_numOfStates]; for (int i = 0; i < _numOfStates; i++) { _eProb[i] = new float*[_numOfStates]; _eCount[i] = new float*[_numOfStates]; for (int j = 0; j < _numOfStates; j++) { _eProb[i][j] = new float[FENO_SIZE-1]; _eCount[i][j] = new float[FENO_SIZE-1]; for (int k = 0; k < FENO_SIZE-1; k++) { //Initialize emission prob if (k == idx) { _eProb[i][j][k] = 0.5; } else{ _eProb[i][j][k] = 0.5/255.0; } _eCount[i][j][k] = 0.0; } } } _pProb[0][0] = 0.1; _pProb[0][1] = 0.8; _qProb[0][1] = 0.1; } } // Arc based forward, return sum of alpha for normalization void ComputeForward(RowVec predAlpha, int startLoc, RowVec *alpha, std::string obs) { //Emit symbol index int idx = HIdxMap.find(obs)->second; float al = 0.0; //Carry the null transition from former element if (!alpha->empty()) { al = alpha->back(); } //First update non-null arc, j is source state, i is target state for (int i = 0; i < _numOfStates; i++) { for (int j = 0; j < _numOfStates; j++) { //State is 1 indexed if (_pProb[j][i] != 0) { al += predAlpha[startLoc+j] * _pProb[j][i] * _eProb[j][i][idx]; } //Only last states has null transition, so we can safely write this //Note at this time, the last number has not been pushed into alpha if (_qProb[j][i] != 0) { al += alpha->at(startLoc + j) * _qProb[j][i]; } } alpha->push_back(al); //Set al back to 0 al = 0.0; } } /* Arc based backward Notice that the last states will always have 0 for its beta Also, count the arcs at the same time */ void ComputeBackwardAndColCounts(RowVec *alpha,float coef, ReRowVec successorBeta, int endLoc, ReRowVec *beta, std::string obs) { //Emit symbol index int idx = HIdxMap.find(obs)->second; //beta that carried from successor float botBeta = 0.0; //First carry beta from successor beta if (!beta->empty()) { botBeta = beta->front(); } //0 if the last stage in large trellis beta->push_front(botBeta); float be = 0.0; //No need to care about the last states, since its not outgoing to any states //it's value is simply the carried from last beta for (int i = _numOfStates -2 ; i >=0 ; i--) { //i is the source state, j is the target state for (int j = 0; j < _numOfStates; j++) { if (_pProb[i][j] != 0) { float b = successorBeta[endLoc - (_numOfStates-j-1)] * _pProb[i][j] * _eProb[i][j][idx]; float c = alpha->at(endLoc - (_numOfStates - i - 1)) * b; be += b/coef; //Add counts for corresponding emission and transition _eCount[i][j][idx] += c; _pCount[i][j] += c; } if (_qProb[i][j] != 0) { be += _qProb[i][j] * botBeta; /*Note that the null transition always goes to the last state, so this is always calculated at last, so at this time, be equals the beta of the source state i, so we could use this beta to calculate the counts for null transition in the same stage from i -> j ***Need to multiply the coefficient back */ _qCount[i][j] += alpha->at(endLoc - (_numOfStates -i-1)) * _qProb[i][j] * botBeta * coef; } } beta->push_front(be); be = 0.0; } } //Update transition and emission probabilities void Update() { //Update for (int i = 0; i < _numOfStates; i++) { float denom = 0.0; for (int j = 0; j < _numOfStates; j++) { denom += _pCount[i][j] + _qCount[i][j]; if (_pCount[i][j] != 0) { float sumK = 0.0; //pcount can be non-accurate, so here compute sum again for (int k = 0; k < FENO_SIZE-1; k++) { sumK += _eCount[i][j][k]; } for (int k = 0; k < FENO_SIZE-1; k++) { _eProb[i][j][k] = _eCount[i][j][k] / sumK; } } } //Update prob for state i for (int j = 0; j < _numOfStates; j++) { if (denom != 0 ) { _pProb[i][j] = _pCount[i][j] / denom; _qProb[i][j] = _qCount[i][j] / denom; } } } } //Reset arc counts void ResetCounts() { for (int i = 0; i < _numOfStates; i++) { for (int j = 0; j < _numOfStates; j++) { _pCount[i][j] = 0; _qCount[i][j] = 0; for (int k = 0; k < FENO_SIZE-1; k++) { _eCount[i][j][k] = 0; } } } } //Simple output form void PrintHMM() { std::cout << "HMM for : " << _name << std::endl; std::cout << "Transition Probability ==== " << std::endl; for (int i = 0; i < _numOfStates; i++) { for (int j = 0; j< _numOfStates; j++) { std::cout << i << " -> " << j <<" " << _pProb[i][j] << " , "; } std::cout << std::endl; } std::cout << "Null Transition Probability ==== " << std::endl; for (int i = 0; i < _numOfStates; i++) { for (int j = 0; j< _numOfStates; j++) { std::cout << i << " -> " << j <<" " << _qProb[i][j] << " , "; } std::cout << std::endl; } std::cout << "Emission Probability ==== " << std::endl; for (int i = 0; i < _numOfStates; i++) { for (int j = 0; j< _numOfStates; j++) { for (int k = 0; k < FENO_SIZE-1; k++) { std::cout << i << " , " << j << "," << k << " : " << _eProb[i][j][k] << " , "; std::cout << HIdxMap.find(_name)->second << std::endl; } std::cout << std::endl; } std::cout << std::endl; } } void PrintCounts() { std::cout << "HMM for : " << _name << std::endl; std::cout << "Transition Counts ==== " << std::endl; for (int i = 0; i < _numOfStates; i++) { for (int j = 0; j< _numOfStates; j++) { if (_pCount[i][j] == 0) { continue; } std::cout << i << " -> " << j <<" " << _pCount[i][j] << " , "; } std::cout << std::endl; } std::cout << "Null Transition Counts ==== " << std::endl; for (int i = 0; i < _numOfStates; i++) { for (int j = 0; j< _numOfStates; j++) { if (_qCount[i][j] == 0) { continue; } std::cout << i << " -> " << j <<" " << _qCount[i][j] << " , "; } std::cout << std::endl; } std::cout << "Emission Counts ==== " << std::endl; for (int i = 0; i < _numOfStates; i++) { for (int j = 0; j< _numOfStates; j++) { for (int k = 0; k < FENO_SIZE-1; k++) { if (_eCount[i][j][k] == 0) { continue; } std::cout << i << " , " << j << "," << k << " : " << _eCount[i][j][k] << " , "; } std::cout << std::endl; } std::cout << std::endl; } } }; #endif
pablomiralles22/deiso-xv6
kernel/exec.c
#include "types.h" #include "param.h" #include "memlayout.h" #include "riscv.h" #include "spinlock.h" #include "proc.h" #include "defs.h" #include "elf.h" #include "vma.h" int exec(char *path, char **argv) { char *s, *last; int i, off; uint64 argc, sz = 0, sp, ustack[MAXARG], stackbase; struct elfhdr elf; struct inode *ip; struct proghdr ph; struct file *elf_file; pagetable_t pagetable = 0, oldpagetable; struct proc *p = myproc(); struct vma *vma = 0, *aux = 0, *old_vma = p->vma_start.next; // needed to restore in case of error begin_op(); if((ip = namei(path)) == 0){ end_op(); return -1; } ilock(ip); // Check ELF header if(readi(ip, 0, (uint64)&elf, 0, sizeof(elf)) != sizeof(elf)) goto bad; if(elf.magic != ELF_MAGIC) goto bad; if((pagetable = proc_pagetable(p)) == 0) goto bad; // Get file for VMAs if((elf_file = filealloc()) < 0) goto bad; elf_file->type = FD_INODE; elf_file->off = 0; elf_file->readable = 1; elf_file->writable = 0; elf_file->ref = 1; // avoid filedup panic elf_file->ip = ip; // Load program into memory. for(i=0, off=elf.phoff; i<elf.phnum; i++, off+=sizeof(ph)){ if(readi(ip, 0, (uint64)&ph, off, sizeof(ph)) != sizeof(ph)) goto bad; if(ph.type != ELF_PROG_LOAD) continue; if(ph.memsz < ph.filesz) goto bad; if(ph.vaddr + ph.memsz < ph.vaddr) goto bad; sz = ph.vaddr + ph.memsz; if((ph.vaddr % PGSIZE) != 0) goto bad; // Get VMA for segment int permission = 0; if(ph.flags & ELF_PROG_FLAG_WRITE) permission |= PROT_WRITE; if(ph.flags & ELF_PROG_FLAG_READ) permission |= PROT_READ; if(ph.flags & ELF_PROG_FLAG_EXEC) permission |= PROT_EXEC; aux = vma; if((vma = vma_alloc()) == 0) goto bad; _vma_init(vma, ph.vaddr, ph.memsz, ph.filesz, elf_file, ph.off, permission, MAP_PRIVATE, aux); } if(elf_file->ref <= 1) goto bad; else elf_file->ref--; // shouldn't have any problem with concurrency iunlock(ip); // don't deref inode on finish end_op(); ip = 0; // Allocate VMA for stack aux = vma; if((vma = vma_alloc()) == 0) goto bad; sz = PGROUNDUP(sz); sz += 2 * PGSIZE; sp = sz; stackbase = sp - PGSIZE; _vma_init(vma, stackbase, PGSIZE, 0, 0, 0, PROT_READ | PROT_WRITE, MAP_PRIVATE, aux); // Allocate VMA for heap aux = vma; if((vma = vma_alloc()) == 0) goto bad; _vma_init(vma, sz, 0, 0, 0, 0, PROT_READ | PROT_WRITE, MAP_PRIVATE, aux); // Need new vmas before writing to stack p->vma_start.next = vma; // Push argument strings, prepare rest of stack in ustack. for(argc = 0; argv[argc]; argc++) { if(argc >= MAXARG) goto bad; sp -= strlen(argv[argc]) + 1; sp -= sp % 16; // riscv sp must be 16-byte aligned if(sp < stackbase) goto bad; if(copyout(pagetable, sp, argv[argc], strlen(argv[argc]) + 1) < 0) goto bad; ustack[argc] = sp; } ustack[argc] = 0; /** printf("EXEC CALL from PID=%d\n", p->pid); */ /** for(struct vma *it = &p->vma_start; it != 0; it = it->next) { */ /** printf("VMA %p, [%p, %p]\n", it, it->start, it->start+it->length); */ /** } */ /** printf("----------\n"); */ // push the array of argv[] pointers. sp -= (argc+1) * sizeof(uint64); sp -= sp % 16; if(sp < stackbase) goto bad; if(copyout(pagetable, sp, (char *)ustack, (argc+1)*sizeof(uint64)) < 0) goto bad; // arguments to user main(argc, argv) // argc is returned via the system call return // value, which goes in a0. p->trapframe->a1 = sp; // Save program name for debugging. for(last=s=path; *s; s++) if(*s == '/') last = s+1; safestrcpy(p->name, last, sizeof(p->name)); // Commit to the user image. oldpagetable = p->pagetable; p->pagetable = pagetable; p->sz = sz; p->trapframe->epc = elf.entry; // initial program counter = main p->trapframe->sp = sp; // initial stack pointer for(struct vma *it = old_vma, *next; it != 0; it = next) { next = it->next; vma_free(oldpagetable, it); } proc_freepagetable(oldpagetable, 0); p->heap = vma; // set heap VMA // Stop lazy alloc por binary /** struct vma *it; */ /** for(it = vma; it->next != 0; it = it->next); */ /** allocrange(pagetable, vma->start, vma->length); */ return argc; // this ends up in a0, the first argument to main(argc, argv) bad: p->vma_start.next = old_vma; // undo change of VMAs if(pagetable) { for(struct vma *it = vma, *next; it != 0; it = next) { next = it->next; vma_free(pagetable, it); } proc_freepagetable(pagetable, 0); } if(ip){ iunlockput(ip); end_op(); } return -1; }
pablomiralles22/deiso-xv6
kernel/vma.c
#include "file.h" #include "defs.h" #include "vma.h" #include "proc.h" struct vma vma_list[NVMA]; struct vma *vma_alloc() { struct vma* vma; for(vma = vma_list; vma < &vma_list[NVMA]; vma++) { acquire(&vma->lock); if(vma->used == 0) return vma; release(&vma->lock); } return 0; panic("Out of VMAs"); } void vma_free_mem(pagetable_t pagetable, struct vma *vma, uint64 addr, uint64 length) { struct file *f = vma->file; int write = (vma->flags & MAP_SHARED) && vma->file; uint64 pos, file_pos, start, end, write_end; for(pos = PGROUNDDOWN(addr); pos < addr + length; pos += PGSIZE) { start = addr > pos ? addr : pos; end = pos + PGSIZE > addr + length ? addr + length : pos + PGSIZE; write_end = end > vma->start + vma->file_length ? vma->start + vma->file_length : end; file_pos = start - vma->start + vma->offset; if(is_page_mapped(pagetable, pos)) { if(write && write_end > start) { begin_op(); ilock(f->ip); writei(f->ip, 1, start, file_pos, write_end - start); iunlock(f->ip); end_op(); } if((start > pos && start > vma->start) || (end < pos+PGSIZE && end < vma->start + vma->length)) { // fill with junk, since we will not unmap uint64 pa = walkaddr(pagetable, start); memset((void *)(pa + (start - pos)), 0, end - start); // do not unmap if there is still part of the vma in the page continue; } uvmunmap(pagetable, pos, 1, 1); } } } void vma_free(pagetable_t pagetable, struct vma *vma) { vma_free_mem(pagetable, vma, vma->start, vma->length); if(vma->file != 0) fileclose(vma->file); vma->start = 0; vma->next = 0; vma->file = 0; vma->offset = 0; vma->permission = 0; vma->flags = 0; vma->length = 0; vma->file_length = 0; acquire(&vma->lock); vma->used = 0; release(&vma->lock); } // needs a's lock to be taken void vma_copy(struct vma *a, struct vma *b) { a->used = b->used; a->start = b->start; a->length = b->length; a->file_length = b->file_length; a->next = b->next; a->file = b->file; a->offset = b->offset; a->permission = b->permission; a->flags = b->flags; } // call with vma->lock acquired void vma_init(struct vma *vma, uint64 start, uint64 length, struct file *file, uint64 offset, int permission, int flags, struct vma *next) { _vma_init(vma, start, length, length, file, offset, permission, flags, next); } void _vma_init(struct vma *vma, uint64 start, uint64 length, uint64 file_length, struct file *file, uint64 offset, int permission, int flags, struct vma *next) { vma->used = 1; release(&vma->lock); if(file) filedup(file); vma->length = length; vma->start = start; vma->length = length; vma->file_length = file_length; vma->file = file; vma->offset = offset; vma->permission = permission; vma->flags = flags; vma->next = next; }
pablomiralles22/deiso-xv6
kernel/vma_flags.h
<reponame>pablomiralles22/deiso-xv6 #ifndef VMA_FLAGS_H #define VMA_FLAGS_H #define PROT_READ (0x1 << 0) #define PROT_WRITE (0x1 << 1) #define PROT_EXEC (0x1 << 2) #define MAP_SHARED (0x1 << 0) #define MAP_PRIVATE (0x1 << 1) #endif
pablomiralles22/deiso-xv6
user/lotterytest.c
<filename>user/lotterytest.c #include "../kernel/types.h" #include "../kernel/stat.h" #include "../kernel/pstat.h" #include "user.h" #define N_THREADS 5 #define X_SPIN 1e5 #define Y_SPIN 1e5 #define ITER_TOL 5 struct pstat ps; int pid[N_THREADS], ind[N_THREADS]; long long aux; long long spin() { unsigned x = 0; unsigned y = 0; while (x < X_SPIN) { y = 0; while (y < Y_SPIN) y++, aux++; x++; } return aux; } int main(int argc, char *argv[]) { int pid_aux; settickets((2*N_THREADS+1)*10); for(int i=0; i<N_THREADS; ++i) if ((pid_aux = fork()) == 0) { settickets((i+1) * 10); spin(); exit(0); } else pid[i] = pid_aux; getpinfo(&ps); for (int i = 0; i < NPROC; i++) if(ps.inuse[i]) for(int j = 0; j < N_THREADS; ++j) if(ps.pid[i] == pid[j]) ind[j] = i; int last_sum_ticks = 0; int cnt_iter_no_ticks = 0; for(;;) { getpinfo(&ps); int sum_ticks = 0; for (int j = 0; j < N_THREADS; ++j) if(ps.inuse[ind[j]] && ps.pid[ind[j]] == pid[j]) sum_ticks += ps.ticks[ind[j]]; if(sum_ticks <= last_sum_ticks) cnt_iter_no_ticks++; else cnt_iter_no_ticks = 0; if(cnt_iter_no_ticks >= ITER_TOL) break; last_sum_ticks = sum_ticks; for(int j=0; j<N_THREADS; ++j) printf("%d ", ps.ticks[ind[j]]); printf("\n"); sleep(2); } exit(0); }
pablomiralles22/deiso-xv6
kernel/pstat.h
#ifndef _PSTAT_H_ #define _PSTAT_H_ #include "param.h" struct pstat { int inuse[NPROC]; // whether this slot of the process table is in use (1 or 0) int tickets[NPROC]; // the number of tickets this process has int pid[NPROC]; // the PID of each process int ticks[NPROC]; // the number of ticks each process has accumulated }; #endif // _PSTAT_H_
pablomiralles22/deiso-xv6
kernel/sysproc.c
<reponame>pablomiralles22/deiso-xv6 #include "types.h" #include "riscv.h" #include "defs.h" #include "date.h" #include "param.h" #include "memlayout.h" #include "spinlock.h" #include "proc.h" #include "pstat.h" #include "vma.h" uint64 sys_exit(void) { int n; if(argint(0, &n) < 0) return -1; exit(n); return 0; // not reached } uint64 sys_getpid(void) { return myproc()->pid; } uint64 sys_fork(void) { return fork(); } uint64 sys_wait(void) { uint64 p; if(argaddr(0, &p) < 0) return -1; return wait(p); } uint64 sys_sbrk(void) { struct proc *p = myproc(); struct vma *heap = p->heap, *prev_heap; int n; uint64 addr; if(argint(0, &n) < 0) return -1; if(n < 0 && heap->length < (uint64)(-n)) return -1; // check not overtaking next vma if(n > 0) { for(prev_heap = &p->vma_start; prev_heap->next != heap; prev_heap = prev_heap->next); if(heap->start + heap->length + (uint64) n > prev_heap->start) return -1; } addr = heap->start + heap->length; if(n < 0) vma_free_mem(p->pagetable, heap, addr - (uint64)(-n), -n); heap->length += n; p->sz = heap->start + heap->length; return addr; } uint64 sys_sleep(void) { int n; uint ticks0; if(argint(0, &n) < 0) return -1; acquire(&tickslock); ticks0 = ticks; while(ticks - ticks0 < n){ if(myproc()->killed){ release(&tickslock); return -1; } sleep(&ticks, &tickslock); } release(&tickslock); return 0; } uint64 sys_kill(void) { int pid; if(argint(0, &pid) < 0) return -1; return kill(pid); } // return how many clock tick interrupts have occurred // since start. uint64 sys_uptime(void) { uint xticks; acquire(&tickslock); xticks = ticks; release(&tickslock); return xticks; } // stablish the number of tickets of the caller process uint64 sys_settickets(void) { int n; struct proc* p = myproc(); if(argint(0, &n) < 0 || n < MINTICKETS) return -1; acquire(&p->lock); acquire(&tickets_lock); total_tickets += n - p->tickets; p->tickets = n; release(&tickets_lock); release(&p->lock); return 0; } uint64 sys_getpinfo(void) { uint64 addr; struct pstat ps = { 0 }; if(argaddr(0, &addr) < 0) return -1; for(int i = 0; i < NPROC; ++i) { /* if(proc[i].state != UNUSED) { */ ps.inuse[i] = proc[i].state != UNUSED; ps.pid[i] = proc[i].pid; ps.tickets[i] = proc[i].tickets; ps.ticks[i] = proc[i].ticks; } if(copyout(myproc()->pagetable, addr, (char *) &ps, sizeof(struct pstat)) < 0) return -1; return 0; } uint64 sys_mmap(void) { struct proc *p = myproc(); struct file *f; uint64 addr; size_t length; int prot, flags, fd; off_t offset; if(argaddr(0, &addr) < 0) return -1; if(argaddr(1, &length) < 0) return -1; if(argint(2, &prot) < 0) return -1; if(argint(3, &flags) < 0) return -1; if(argint(4, &fd) < 0) return -1; if(argaddr(5, &offset) < 0) return -1; f = p->ofile[fd]; if(f == 0) return -1; if((prot & PROT_WRITE) && (flags & MAP_SHARED) && (!f->writable)) return -1; if((prot & PROT_READ) && (!f->readable)) return -1; struct vma *vma; struct vma *it = &p->vma_start; while(it->next != 0) { uint64 available_space = PGROUNDDOWN(it->start) - PGROUNDUP(it->next->start + it->next->length); if(available_space >= PGROUNDUP(length)) { if((vma = vma_alloc()) == 0) return -1; vma_init(vma, PGROUNDDOWN(it->start) - PGROUNDUP(length), length, f, offset, prot, flags, it->next); it->next = vma; return vma->start; } it = it->next; } return -1; } uint64 sys_munmap(void) { struct proc* p = myproc(); uint64 addr; size_t length; if(argaddr(0, &addr) < 0) return -1; if(argaddr(1, &length) < 0) return -1; struct vma *it = &p->vma_start; struct vma *prev = 0; for(; it->next != 0; prev = it, it = it->next) if(it->start <= addr && it->start + it->length >= addr + length) { // found VMA if(it->start == addr && it->length == length) { prev->next = it->next; vma_free(p->pagetable, it); return 0; } if(it->start == addr) { if(PGROUNDDOWN(length) != length) return -1; vma_free_mem(p->pagetable, it, addr, length); it->start = addr + length; it->offset += length; it->length -= length; } else if(it->start + it->length == addr + length) { vma_free_mem(p->pagetable, it, addr, length); it->length -= length; } else { printf("Hole in vma not supported. Range: %p - %p", addr, addr + length); return -1; } return 0; } printf("VMA not found. Range: %p - %p", addr, addr + length); return -1; }
pablomiralles22/deiso-xv6
kernel/types.h
<reponame>pablomiralles22/deiso-xv6 #ifndef TYPES_H #define TYPES_H typedef unsigned int uint; typedef unsigned short ushort; typedef unsigned char uchar; typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedef unsigned long uint64; typedef uint64 pde_t; # ifndef __size_t_defined typedef uint64 size_t; # endif # ifndef __off_t_defined typedef uint64 off_t; // TODO: should be signed? # endif #endif /* TYPES_H */
pablomiralles22/deiso-xv6
kernel/vma.h
<reponame>pablomiralles22/deiso-xv6<gh_stars>0 #ifndef VMA_H #define VMA_H #include "defs.h" #include "types.h" #include "file.h" #include "spinlock.h" #include "param.h" #include "vma_flags.h" struct vma { int used; uint64 start; uint64 length; uint64 file_length; struct file *file; uint64 offset; int permission; int flags; struct vma *next; struct spinlock lock; }; struct vma *vma_alloc(); void vma_free_mem(pagetable_t pagetable, struct vma *vma, uint64 addr, uint64 length); void vma_free(pagetable_t pagetable, struct vma *vma); void vma_copy(struct vma *a, struct vma *b); void vma_init(struct vma *vma, uint64 start, uint64 length, struct file *file, uint64 offset, int permission, int flags, struct vma *next); void _vma_init(struct vma *vma, uint64 start, uint64 length, uint64 file_length, struct file *file, uint64 offset, int permission, int flags, struct vma *next); #endif /* VMA_H */
ChristopherBilg/crb_shell
tests.c
<filename>tests.c<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include "parser.h" #include "standard.h" int main() { printf("Enter some input: "); char *test_input = read_input(); printf("Test Input: %s", test_input); char **parsed_input = parse_input(test_input); int parsed_input_size = count_arguments(parsed_input); for (int i=0; i<parsed_input_size; i++) printf("[%s] ", parsed_input[i]); printf("\n"); print_error(); int io_redirect = has_io_redirect(parsed_input); printf("I/O Redirect? %d\n", io_redirect); int io_redirect_position = find_io_redirect_position(parsed_input); printf("I/O Redirect Position: %d\n", io_redirect_position); return EXIT_SUCCESS; }
ChristopherBilg/crb_shell
standard.h
<gh_stars>0 #ifndef STANDARD_H #define STANDARD_H #define SHELLNAME "crb_shell$ " #define INPUT "<" #define DOUBLE_INPUT "<<" #define OUTPUT ">" #define DOUBLE_OUTPUT ">>" #define PIPE "|" #define BACKGROUND "&" void print_error(); int has_io_redirect(char **parsed_input); int find_io_redirect_position(char **parsed_input); #endif
ChristopherBilg/crb_shell
parser.c
#include <dirent.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "parser.h" #include "standard.h" // This function will read the input from the user and return it as a char* (array) char *read_input() { char *input = NULL; size_t input_buffer_size = 0; getline(&input, &input_buffer_size, stdin); return input; } // The will take the users input and parse it into individual // tokens, ie: the command, arguments, redirect, pipe, etc. char **parse_input(char *input) { int input_buffer_size = BUFFER_SIZE; int index = 0; char **all_segments = malloc(input_buffer_size * sizeof(char *)); char *current_segment; current_segment = strtok(input, DELIMITER); while (current_segment != NULL) { // Add the current segment to the array of all segments all_segments[index] = current_segment; index++; // Reallocate dynamic memory buffer if needed if (index >= input_buffer_size) { input_buffer_size *= 2; void *temp = realloc(all_segments, input_buffer_size * sizeof(char *)); if (temp == NULL) free(temp); all_segments = temp; } // Move the current segment to be the next segment with the same delim. current_segment = strtok(NULL, DELIMITER); } // NULL terminated all_segments[index] = NULL; return all_segments; } // Simple function to sum up the number of arguments given by // a parsed user's input. (including the command name) int count_arguments(char **parsed_input) { int counter = 0; for (int i=0; parsed_input[i] != NULL; i++) counter++; return counter; } // Runs the internal command: cd (change directory) int run_cd(char **parsed_input) { if (parsed_input[1] == NULL) { char buffer[BUFFER_SIZE]; if (getcwd(buffer, BUFFER_SIZE) == NULL) print_error(); printf("%s%s\n", SHELLNAME, buffer); } else if (chdir(parsed_input[1]) != 0) { print_error(); } return 1; } // Runs the internal command: clr (clear screen) int run_clr() { system("clear"); return 1; } // Runs the internal command: dir (list's the current directory contents) int run_dir(char **parsed_input) { DIR *d; if (parsed_input[1] == NULL) d = opendir("."); else d = opendir(parsed_input[1]); if (d == NULL) { print_error(); return 1; } struct dirent *dir; while ((dir = readdir(d)) != NULL) { printf("\t%s\n", dir->d_name); } return 1; } // Runs the internal command: environ (list's environment variables) int run_environ() { const char* env_variables[BUFFER_SIZE]; int size = 0; env_variables[size++] = "USER"; env_variables[size++] = getenv("USER"); env_variables[size++] = "HOME"; env_variables[size++] = getenv("HOME"); env_variables[size++] = "SHELL"; env_variables[size++] = getenv("SHELL"); env_variables[size++] = "OS"; env_variables[size++] = getenv("DESKTOP_SESSION"); env_variables[size++] = "PWD"; env_variables[size++] = getenv("PWD"); env_variables[size++] = "USERNAME"; env_variables[size++] = getenv("USERNAME"); env_variables[size++] = "LANG"; env_variables[size++] = getenv("LANG"); int index = 0; while (index < size) { printf("\t%s: %s\n", env_variables[index], env_variables[index+1]); index += 2; } return 1; } // Runs the internal command: echo (prints all arguments out) int run_echo(char **parsed_input) { int index = 1; while (parsed_input[index]) { printf("%s ", parsed_input[index]); index++; } printf("\n"); return 1; } // Runs the internal command: help // (gives the user a helpful guide to the crb_shell program) int run_help() { printf("crb_shell User Manual:\n"); printf(" Internal Commands:\n"); printf("\tcd <directory>: Change the directory to the given <directory>\n"); printf("\tclr: clear the screen\n"); printf("\tdir: list the contents of the current working directory\n"); printf("\tenviron: list some of the local system environment variables\n"); printf("\techo <arguments...>: print out to given arguments\n"); printf("\thelp: list helpful user information for the crb_shell program\n"); printf("\tpause: pause the shell until the 'enter' key is pressed\n"); printf("\tquit: quit the crb_shell program, and return to calling shell program\n"); printf(" External Commands:\n"); printf("\tAll external commands are supported.\n"); printf(" Input redirects: < or <<\n"); printf("\tUsage: com1 args... < filename: This will use the contents of filename as the input for com1.\n"); printf("\tUsage: com1 args... << filename: This will use the contents of filename as the input for com1.\n"); printf(" Output redirects: > or >>\n"); printf("\tUsage: com1 args... > filename: This will append the output of com1 to filename.\n"); printf("\tUsage: com1 args... >> filename: This will truncate the output of com1 to filename.\n"); printf(" Command piping: |\n"); printf("\tUsage: com1 args... | com2 args...: This will link the output of com1 to the input of com2.\n"); return 1; } // Runs the internal command: pause // (pauses the crb_shell until the 'enter' key is pressed) int run_pause() { printf("Press 'enter' to continue"); while (getchar() != '\n'); return 1; } // Runs the internal command: quit (quits the crb_shell program) int run_quit() { exit(EXIT_SUCCESS); return 0; }
ChristopherBilg/crb_shell
parser.h
<gh_stars>0 #ifndef PARSER_H #define PARSER_H #define BUFFER_SIZE 128 #define DELIMITER " \t\r\n\a" char *read_input(); char **parse_input(char *input); int count_arguments(char **parsed_input); int run_cd(char **parsed_input); int run_clr(); int run_dir(char **parsed_input); int run_environ(); int run_echo(char **parsed_input); int run_help(); int run_pause(); int run_quit(); #endif
ChristopherBilg/crb_shell
main.c
#include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/wait.h> #include <unistd.h> #include "main.h" #include "parser.h" #include "standard.h" #define LINE_SIZE 1024 // The main function that is called when the program is started int main(int argc, char **argv) { // Check for arguments (batch file) if (argc > 1) { FILE *file; if ((file = fopen(argv[1], "r")) == 0) { print_error(); return EXIT_FAILURE; } char line[LINE_SIZE]; while (1) { fgets(line, LINE_SIZE, file); if (feof(file)) break; int str_len = strlen(line); if (line[str_len-1] == '\n') line[str_len-1] = 0; printf("%s\"%s\"\n", SHELLNAME, line); char **args = parse_input(line); run_execution(args); } fclose(file); } // No batch file arguments else { int return_code; do { char *input; char **arguments; printf("%s", SHELLNAME); input = read_input(); arguments = parse_input(input); return_code = run_execution(arguments); } while (return_code != 0); return EXIT_SUCCESS; } } // Placeholders for internal commands and their associated functions (ORDER MATTERS) char *internal_commands[] = {"cd", "clr", "dir", "environ", "echo", "help", "pause", "quit"}; int (*internal_functions[]) (char**) = {&run_cd, &run_clr, &run_dir, &run_environ, &run_echo, &run_help, &run_pause, &run_quit}; int start_process(char **process_input, int input, int filedesc) { pid_t process_id; int background = 0; char process_name_to_run[strlen(process_input[0])]; memset(process_name_to_run, '\0', sizeof(process_name_to_run)); // Check for background process (background_) if (strcmp(process_input[count_arguments(process_input)-1], "&") == 0) { // Shorten the length of the process_input by one element off of the end process_input[count_arguments(process_input)-1] = NULL; background = 1; } strcpy(process_name_to_run, process_input[0]); process_id = fork(); if (process_id == 0) { // Child will run this if (background) { int devNull = open("/dev/null", O_WRONLY); dup2(devNull, STDOUT_FILENO); } else if (filedesc != -1) { if (input == 0) // output dup2(filedesc, 1); else dup2(filedesc, 0); } execvp(process_name_to_run, process_input); } else { // Parent will run this if (!background) wait(NULL); } return 1; } // Executes a given command (with arguments) by passing it to // the above start_process(...) function int run_execution(char **process_input) { // No command given, or NULL command if (process_input[0] == NULL) return 1; // Find position of io redirect if it exists int io_redirect = has_io_redirect(process_input); int io_redirect_location = find_io_redirect_position(process_input); // No io redirect if (io_redirect < 0 || io_redirect_location < 0) { // 8 is the number of internal commands to check for for (int i=0; i<8; i++) { if (strcmp(process_input[0], internal_commands[i]) == 0) return (*internal_functions[i])(process_input); } // If not an internal command, return here return start_process(process_input, -1, -1); } else { // There is an io redirect int process_input_length = count_arguments(process_input); // Make a copy of the arguments on the left of the io redirect int index1 = 0; char *left_side_arguments[io_redirect_location + 1]; for (index1=0; index1<io_redirect_location; index1++) left_side_arguments[index1] = process_input[index1]; left_side_arguments[index1++] = NULL; // NULL terminated // Make a copy of the arguments on the right of the io redirect int index2 = 0; char *right_side_arguments[process_input_length - io_redirect_location]; for (index2=0; process_input[index1] != NULL; index1++, index2++) right_side_arguments[index2] = process_input[index1]; right_side_arguments[index2] = NULL; // NULL terminated // Check for io redirects and run command if (io_redirect == 0) // < truncate return run_io_redirect(left_side_arguments, right_side_arguments, true, false); else if (io_redirect == 1) // << append return run_io_redirect(left_side_arguments, right_side_arguments, true, true); else if (io_redirect == 2) // > truncate return run_io_redirect(left_side_arguments, right_side_arguments, false, false); else if (io_redirect == 3) // >> append return run_io_redirect(left_side_arguments, right_side_arguments, false, true); else if (io_redirect == 4) // | pipe return run_io_pipe(left_side_arguments, right_side_arguments); } return 1; } // Takes in the parsed aguments for io redirects (input and output) // and then startts the program by passing the correct arguments // to the start_process(...) function. This is all after the correct // file descriptor is opened. int run_io_redirect(char **left_side_arguments, char **right_side_arguments, _Bool input, _Bool append) { int fd; int error = 1; // The IO redirect is an input (< or <<) if (input == true) { // Append the file contents if (append == true) { if ((fd = open(*right_side_arguments, O_CREAT | O_RDWR | O_APPEND)) < 0) { print_error(); return error; } return start_process(left_side_arguments, 1, fd); } // Truncate the file contents else { if ((fd = open(*right_side_arguments, O_CREAT | O_RDWR | O_TRUNC)) < 0) { print_error(); return error; } return start_process(left_side_arguments, 1, fd); } } // The IO redirect is an output (> or >>) else { // Append the file contents if (append == true) { if ((fd = open(*right_side_arguments, O_CREAT | O_RDWR | O_APPEND, S_IRWXU)) < 0) { print_error(); return error; } return start_process(left_side_arguments, 0, fd); } // Truncate the file contents else { if ((fd = open(*right_side_arguments, O_CREAT | O_RDWR | O_TRUNC, S_IRWXU)) < 0) { print_error(); return error; } return start_process(left_side_arguments, 0, fd); } } return 1; } // Handled the piping of multiple commands together by linking the output // of the first command to the input of the second command. // After this, the start_process(...) function is called to execute. int run_io_pipe(char **left_side_arguments, char **right_side_arguments) { int error = 1; int child_pid = fork(); if (child_pid < 0) { print_error(); return error; } else if (child_pid == 0) { // Inside the child process now int pipe_fds[2]; if (pipe(pipe_fds) != 0) { print_error(); return error; } int pipe_pid = fork(); if (pipe_pid < 0) { print_error(); return error; } else if (pipe_pid == 0) { // left side command arguments to be run close(STDOUT_FILENO); dup2(pipe_fds[1], 1); close(pipe_fds[0]); execvp(left_side_arguments[0], left_side_arguments); } else { // right side command arguments to be run close(STDIN_FILENO); dup2(pipe_fds[0], 0); close(pipe_fds[1]); execvp(right_side_arguments[0], right_side_arguments); } } else { // Inside the parent process still wait(NULL); } return 1; }
ChristopherBilg/crb_shell
standard.c
#include <stdio.h> #include <string.h> #include <unistd.h> #include "standard.h" // Standard error message to print whenever an error occurs // This is required by the project requirements. void print_error() { char error_message[30] = "An error has occurred\n"; write(STDERR_FILENO, error_message, strlen(error_message)); } // Returns an int representing the type of io redirect found // -1 error // 0 input // 1 double_input // 2 output // 3 double_output // 4 pipe int has_io_redirect(char **parsed_input) { if (parsed_input[0] == NULL) return -1; for (int i=0; parsed_input[i] != NULL; i++) { if (strcmp(parsed_input[i], INPUT) == 0) return 0; if (strcmp(parsed_input[i], DOUBLE_INPUT) == 0) return 1; if (strcmp(parsed_input[i], OUTPUT) == 0) return 2; if (strcmp(parsed_input[i], DOUBLE_OUTPUT) == 0) return 3; if (strcmp(parsed_input[i], PIPE) == 0) return 4; } return -1; } // Returns the position in the parsed_input array of the io redirect int find_io_redirect_position(char **parsed_input) { if (parsed_input[0] == NULL) return -1; for (int i=0; parsed_input[i] != NULL; i++) { if (strcmp(parsed_input[i], INPUT) == 0) return i; if (strcmp(parsed_input[i], DOUBLE_INPUT) == 0) return i; if (strcmp(parsed_input[i], OUTPUT) == 0) return i; if (strcmp(parsed_input[i], DOUBLE_OUTPUT) == 0) return i; if (strcmp(parsed_input[i], PIPE) == 0) return i; } return -1; }
ChristopherBilg/crb_shell
main.h
<reponame>ChristopherBilg/crb_shell #ifndef MAIN_H #define MAIN_H #include <stdbool.h> int main(); int start_process(char **process_input, int input, int filedesc); int run_execution(char **process_input); int run_io_redirect(char **left_side_arguments, char **right_side_arguments, _Bool input, _Bool append); int run_io_pipe(char **left_side_arguments, char **right_side_arguments); #endif
andrewparlane/fiuba6633_lab_de_sistemas_digitales
micro/assembler/lsd_asm.c
<reponame>andrewparlane/fiuba6633_lab_de_sistemas_digitales /************************************************************************** Copyright (c) 2013 <NAME> (<EMAIL>) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2. 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. ***************************************************************************/ #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> typedef struct link_s { char* name; unsigned int memPos; unsigned int line; struct link_s* next; } link_t; typedef link_t* linksList_t; typedef enum functionType_e { TYPE_ONE_OP = 0, TYPE_TWO_OP = 1 } functionType_t; typedef struct instruction_s { functionType_t type; char function[16]; char aOperand[16]; char bOperand[16]; unsigned int instructionNumber; unsigned int lineNumber; struct instruction_s* next; } instruction_t; typedef instruction_t* instructionList_t; typedef struct api_s { char* name; functionType_t type; unsigned char opcode; } api_t; api_t instructionName[] = { // Type two operands {"load", TYPE_TWO_OP,0x00}, {"store", TYPE_TWO_OP,0x01}, {"loadi", TYPE_TWO_OP,0x02}, {"storei",TYPE_TWO_OP,0x03}, {"add", TYPE_TWO_OP,0x40}, {"sub", TYPE_TWO_OP,0x41}, {"addc", TYPE_TWO_OP,0x42}, {"subc", TYPE_TWO_OP,0x43}, {"addi", TYPE_TWO_OP,0x44}, {"subi", TYPE_TWO_OP,0x45}, {"addic", TYPE_TWO_OP,0x46}, {"subic", TYPE_TWO_OP,0x47}, {"nor", TYPE_TWO_OP,0x80}, {"nand", TYPE_TWO_OP,0x81}, {"xor", TYPE_TWO_OP,0x82}, {"xnor", TYPE_TWO_OP,0x83}, {"nori", TYPE_TWO_OP,0x84}, {"nandi", TYPE_TWO_OP,0x85}, {"xori", TYPE_TWO_OP,0x86}, {"xnori", TYPE_TWO_OP,0x87}, // Type one operands {"jump", TYPE_ONE_OP,0xc0}, {"jz", TYPE_ONE_OP,0xc1}, {"jc", TYPE_ONE_OP,0xc2}, {"jn", TYPE_ONE_OP,0xc3}, }; int main (int argc, char * argv[]) { FILE * inputFile; FILE * outputFile; FILE * dumpFile; char str[1024]; char function[16]; char aOperand[16]; char bOperand[16]; int line; int operands; int instCount; int error; int i, j, k; unsigned int value; puts (""); puts ("#############################################################"); puts ("# #"); puts ("# Assembler Program #"); puts ("# #"); puts ("#############################################################"); puts ("# #"); puts ("# Version 1.0 #"); puts ("# Sep. 30, 2014 #"); puts ("# #"); puts ("#############################################################"); puts (""); puts (""); puts (""); linksList_t linksList = NULL; instructionList_t instructionsList; instructionsList = NULL; error = 0; instCount = 0; line = 0; if (argc!=3) { error = 1; puts ("ERROR: Bad input arguments."); puts (""); puts ("USAGE: ./lsdasm <inputFile> <outputFile>"); puts (""); puts (""); return 0; } if ((inputFile = fopen(argv[1],"r"))==NULL) { error = 1; printf ("ERROR 0: Invalid name for input file. Check it has access.\n"); puts (""); puts (""); return -1; } dumpFile = fopen ("code.lst","w"); outputFile = fopen (argv[2],"w"); while (fgets(str,1024,inputFile)!=NULL) { if (ferror(inputFile)) { printf ("ERROR 1: Wrong input file.\n"); puts (""); puts (""); return -1; } line++; int i,j=0; operands = 2; // Remove initial spaces and tabulators for (i=0;i<1024;++i) { if ((str[i]!='\t') && (str[i]!=' ')) { break; } } for (;i<1024;++i) { str[j++]=str[i]; // Remove everything after first ';' or ':' if (str[i]==';' || str[i]==':') { str[j++]='\n'; str[j]='\0'; break; } } // Remove all empty lines if (str[0]!='\n' && str[0]!='\r' && str[0]!='#') { // Check for ';' or "$xxxx:" at end of line for (i=0;i<1024;++i) { if (str[i]==';') { i=1024; } else if (str[i]==':') { i = 1024; if (str[0]!='$') { error = 1; printf ("ERROR 3: No \"$.....:\" found at end of line \"%d\".\n",line); } } else if (str[i]=='\n' || str[i]=='\r' || str[i]=='#' || str[i]=='\0'|| i==1023) { error = 1; printf ("ERROR 2: No ';' found at end of line \"%d\".\n",line); break; } } // Check for '$' at the beginning or for ' ' after function if (str[0]=='$') { operands = 0; } else { for (i=0;i<1024;++i) { if((str[i]==' ') || (str[i]=='\t')) { str[i] = '#'; instCount++; break; } if ((str[i]==';') || (str[i]=='\n') || str[i]=='\r' || (str[i]=='\0')) { error = 1; printf ("ERROR 4: No ' ' found before operands in line \"%d\".\n",line); break; } } j = i; for (;i<1024;++i) { if((str[i] != ' ') && (str[i] != '\t')) { str[j++] = str[i]; } } } // Extract function operands A and B or add link to list if (operands>0) { for (i=0,j=0;i<1024;++i) { if (str[i]!='#') { function[j++] = str[i]; } else { break; } } function[j] = '\0'; for (i++,j=0;i<1024;++i) { if (str[i]!=',' && str[i]!=';') { aOperand[j++] = str[i]; } else { break; } } aOperand[j] = '\0'; j = 0; if (str[i]==',') { for (i++,j=0;i<1024;++i) { if (str[i]!=';') { bOperand[j++] = str[i]; } else { break; } } bOperand[j] = '\0'; } else { bOperand[0] = '\0'; operands = 1; } if (operands==1) { fprintf (dumpFile,"0x%02x: \t%s\t%s;\n",(instCount-1)*2,function,aOperand); } else { fprintf (dumpFile,"0x%02x: \t%s\t%s, %s;\n",(instCount-1)*2,function,aOperand,bOperand); } } else { str[strlen(str)-2]='\0'; fprintf (dumpFile,"\n0x%02x: \t<%s>:\n",(instCount)*2,str); // Add to linksList link_t* aux = (link_t*) malloc(sizeof(link_t)); aux->name = (char*) malloc(strlen(str)*sizeof(char)); for (i=0;i<strlen(str);i++) { aux->name[i] = str[i]; } aux->memPos = instCount; aux->line = line; aux->next=NULL; if (linksList==NULL) { linksList = aux; } else { link_t * aux2 = linksList; while (aux2->next && (strcmp(aux2->name,str)!=0)) { aux2 = aux2->next; } if (strcmp(aux2->name,str)!=0) { aux2->next = aux; } else { error = 1; printf ("ERROR 5: Reference \"%s\" multiple defined: line %d\n first defined in line %d.\n",str,line,aux2->line); free (aux); } } } // Function and operands in lower case for (i=0;i<16;++i) { function[i] = (function[i]=='\n'||function[i]=='\r')?'\0':(char)tolower((int)function[i]); aOperand[i] = (aOperand[i]=='\n'||aOperand[i]=='\r')?'\0':(char)tolower((int)aOperand[i]); bOperand[i] = (bOperand[i]=='\n'||bOperand[i]=='\r')?'\0':(char)tolower((int)bOperand[i]); } // Add instruction to instructionsList if (operands != 0) { instruction_t * aux = (instruction_t*) malloc(sizeof(instruction_t)); aux->type = (operands==2) ? TYPE_TWO_OP : TYPE_ONE_OP; for (i=0;i<16;i++) { aux->function[i] = function[i]; aux->aOperand[i] = aOperand[i]; aux->bOperand[i] = bOperand[i]; } aux->instructionNumber = instCount - 1; aux->lineNumber = line; aux->next=NULL; if (instructionsList==NULL) { instructionsList = aux; } else { instructionList_t aux2 = instructionsList; while (aux2->next) { aux2 = aux2->next; } aux2->next = aux; } } } } // Code generation instruction_t * aux; aux = instructionsList; for (i=0;i<instCount;++i,aux=aux->next) { for (j=0;j<24;++j) { if (strcmp(aux->function,instructionName[j].name)==0) { break; } } if (instructionName[j].type!=aux->type) { error = 1; printf ("ERROR 13: Wrong operands count in function \"%s\": line %d.\n",aux->function,aux->lineNumber); } if (j==24) { error = 1; printf ("ERROR 6: Function not recognized in line %d: \"%s\".\n",aux->lineNumber,aux->function); } else { if (aux->type==TYPE_ONE_OP) { if (aux->aOperand[0]=='$') { // It is a label link_t * aux2 = linksList; while (aux2->next && (strcmp(aux2->name,aux->aOperand)!=0)) { aux2 = aux2->next; } if (strcmp(aux2->name,aux->aOperand)==0) { fprintf (outputFile,"%02x\n",(unsigned char)instructionName[j].opcode); fprintf (outputFile,"%02x\n",(unsigned char)((aux2->memPos-aux->instructionNumber-1)*2)); } else if (aux2->next==NULL) { error = 1; printf ("ERROR 7: Reference \"%s\" is not defined: line %d.\n",aux->aOperand,aux->lineNumber); } } else { // Not a label for (k=0;k<16;++k) { if ((!isdigit(aux->aOperand[k])) || aux->aOperand[k]=='\0') { break; } } if (k==16 || aux->aOperand[k]=='\0') { // No error value = (unsigned int) atoi(aux->aOperand); if (value<256) { fprintf (outputFile,"%02x\n",(unsigned char)instructionName[j].opcode); fprintf (outputFile,"%02x\n",(unsigned char)value); } else { error = 1; printf ("ERROR 9: Value \"%s\" is too big: line %d.\n",aux->aOperand,aux->lineNumber); } } else { // error error = 1; printf ("ERROR 8: Operand \"%s\" is not a number: line %d.\n",aux->aOperand,aux->lineNumber); } } } else { if (strcmp("a",aux->aOperand)!=0) { error = 1; printf ("ERROR 10: First operand is not \"a\": line %d.\n",aux->lineNumber); } for (k=0;k<16;++k) { if ((!isdigit(aux->bOperand[k])) || aux->bOperand[k]=='\0') { break; } } if (k==16 || aux->bOperand[k]=='\0') { // No error value = (unsigned int) atoi(aux->bOperand); if (value<256) { fprintf (outputFile,"%02x\n",(unsigned char)instructionName[j].opcode); fprintf (outputFile,"%02x\n",(unsigned char)value); } else { error = 1; printf ("ERROR 12: Value \"%s\" is too big: line %d.\n",aux->bOperand,aux->lineNumber); } } else { // Error error = 1; printf ("ERROR 11: Operand \"%s\" is not a number: line %d.\n",aux->bOperand,aux->lineNumber); } } } } if (instCount>128) { error = 1; printf ("ERROR 14: Code is too large. Just 128 instruccions are allowed.\n"); } else if (instCount<128) { while (instCount++<127) { fprintf (outputFile,"00\n00\n"); } fprintf (outputFile,"00\n00"); } fclose (inputFile); fclose (outputFile); fclose (dumpFile); if (error) { puts (""); puts ("Some errors founded!!!"); puts (""); puts (""); return 1; } else { puts (""); puts ("Compilation done!!!"); puts (""); puts (""); return 0; } }
gniezen/PicoPicoSynth
picopicosynth.c
<reponame>gniezen/PicoPicoSynth<filename>picopicosynth.c /** * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. * * SPDX-License-Identifier: BSD-3-Clause */ #include <stdio.h> #include <math.h> #include "bongo.h" #if PICO_ON_DEVICE #include "hardware/clocks.h" #include "hardware/structs/clocks.h" #endif #include "pico/stdlib.h" #include "pico/audio_pwm.h" //note -- will have to include this in the cmake file #include "hardware/gpio.h" #define SINE_WAVE_TABLE_LEN 2048 #define SAMPLES_PER_BUFFER 256 //There is definately a better way of storing all this //actually, this shouldn't be needed any more #define HIGHBEATFREQ 1.2 #define LOWBEATFREQ 4.8 #define BEATFREQ 15000 #define BEATNUM 8 //not sure this is being used correctly? #define SAMPLEFREQ 12050 //taken from the bongosamples header file -- should be stored in there really #define BONGOSAMPLES 9054 #define BUTTON_GPIO 1 //this gives a max echo of 1 second #define ECHOBUFFERLEN 22050 /**TODO # weird blip if there's echo on bongos and sine all at the same time. Not sure if running out of resources or something else. # would like to try with I2S maybe. #this may be fixed (ish) in the audio correction mode #should still try I2S # Defo needs flashing lights. Hook up some neoPixels and maybe buttons to control the sequencer ##getting some clicks and hisses -- could this be noise on the ground when doing a lot of processing? #fix saw / square wobbler blinps # add some effects ## echo (could also be used for chorus) ### needs a circular buffer ### or could just be a regular buffer that's kicked off on envelope & noenvelope ### or could just hold a separate posn_absolute (posn_echo) and echo_len and run some more inputs to the mixers. -- this won't work as it'll mess with the beat numbers, etc. # Also, can I pull the functions out into a separate file so they can be used elsewhere? # how to make it physical computing? ## neopixels that light up the beat number? ## take user input? Get a irq on a GPIO and use that to trigger certain sounds ### Done, but should it there be a bit more debouncing than a simple falling edge? ## use a potentiometer to control pitch / frequency? **/ static int16_t sine_wave_table[SINE_WAVE_TABLE_LEN]; static int16_t bongo_wave_table[BONGOSAMPLES]; static int16_t echo_table[ECHOBUFFERLEN]; static int16_t calc_samples[SAMPLES_PER_BUFFER]; uint32_t button_last_pressed = 0; uint32_t posn_absolute = 0; //currently documentation incomplete on this. Need to have a read over what various settings do when it's finished. struct audio_buffer_pool *init_audio() { static struct audio_format audio_format = { .format = AUDIO_BUFFER_FORMAT_PCM_S16, .sample_freq = 22050, .channel_count = 1, }; static struct audio_buffer_format producer_format = { .format = &audio_format, .sample_stride = 2 }; //this says there should be three buffers. struct audio_buffer_pool *producer_pool = audio_new_producer_pool(&producer_format, 3, SAMPLES_PER_BUFFER); // todo correct size bool __unused ok; const struct audio_format *output_format; output_format = audio_pwm_setup(&audio_format, -1, &default_mono_channel_config); //-1 is don't care about latency if (!output_format) { panic("MuAudio: Unable to open audio device.\n"); } ok = audio_pwm_default_connect(producer_pool, false); // the true dedicates core 1 to doing audio gubbins -- doesn't seem to work?. maybe need to enable multicore? --looking at source, it's not implemented yet assert(ok); audio_pwm_set_enabled(true); return producer_pool; } int16_t no_envelope(int16_t wave_table[], int table_len, float table_multiplier, int envelope_posn) { if((envelope_posn*table_multiplier) >= table_len) { return 0; } return wave_table[(int)(envelope_posn*table_multiplier)] ; } //note posn_virtual only works out-the-box with continuous waves. // can probably be made to work with samples, but will need a little thought. int16_t envelope(int16_t wave_table[], int table_len, float table_multiplier,float posn_virtual, int envelope_posn, int decay, int sustain, int release, int finish) { float attack_multiplier = 1; float sustain_multiplier = 0.5; float proportion = 0; //note finished if(envelope_posn > finish) {return 0;} //release else if(envelope_posn > release) { proportion = (1.0-(((float)envelope_posn - release) / ((float)finish - release))) * sustain_multiplier; } //sustain else if(envelope_posn > sustain) { proportion = sustain_multiplier; } //decay else if(envelope_posn > decay) { proportion = ( (1.0-(((float)envelope_posn - decay) / ((float)sustain - decay))) * ((float)attack_multiplier - sustain_multiplier)) + sustain_multiplier; } //attack else { proportion = ((float)envelope_posn / decay) * attack_multiplier; } return wave_table[(int)((float)posn_virtual*table_multiplier) % table_len ] * proportion; } int16_t mixer(int16_t inputs[], float volumes[], int size) { float output = 0; for(int i=0;i<size; i++) { output = output + inputs[i] * volumes[i]; } //clip if output too high if (output > 32766) { output = 32766; } if (output < -32766) { output = -32766; } return (int16_t)output; } //wildly overkill to calculate this every sample. This only needs to be calculated every beat int sequence( bool note_sequence[], int posn_absolute, int current_beat_num, int last_loop_posn) { // returns the length of time (in samples) since last played int last_played = 0; for( int i=0; i<BEATNUM;i++) { if (note_sequence[i] && i<= current_beat_num) { last_played = last_loop_posn + (i*BEATFREQ); } } //wrap around to previous bar if none in current bar if(last_played == 0) { for(int i=0; i<BEATNUM;i++) { if (note_sequence[i]) { last_played = last_loop_posn + (i*BEATFREQ) - (BEATFREQ*BEATNUM); } } } return posn_absolute - last_played; } void button_callback() { button_last_pressed = posn_absolute; } //a set of LFOs of basic waveforms. May be worth expanding these with a wave table. float square_wobbler(int wave_len,float vol, int posn_absolute){ return ((float)((int)(posn_absolute/wave_len) % 2) * vol); } float saw_wobbler(int wave_len,float vol, int posn_absolute){ return (((float)((posn_absolute) % wave_len)/wave_len) * vol); } float triangle_wobbler(int wave_len,float vol, int posn_absolute) { if (posn_absolute % (2*wave_len) < wave_len / 2) { return (((float)((posn_absolute) % wave_len)/wave_len) * vol); } else { ( (1.0-((float)((posn_absolute) % wave_len)/wave_len)) * vol); } } //very basic bitcrusher //only resolution reduction, not sample rate reduction //max is the number of sample levels you want, so not tied to integer bit rates int16_t bitcrush(int16_t input, int max, int new_max) { float reducer = max / new_max; return ((int)(input / reducer)) * reducer; } int16_t create_echo(int16_t input, int16_t buffer[], int buffer_len, int posn_absolute) { buffer[posn_absolute % buffer_len] = input; return input; } int16_t read_echo(int16_t buffer[], int buffer_len, int posn_absolute, int delay) { if (posn_absolute < delay) { return 0;} return buffer[(posn_absolute - delay) % buffer_len]; } int main() { //do we really need this? //does seem to work a little better set_sys_clock_48mhz(); //setup our button gpio_init(BUTTON_GPIO); gpio_set_dir(BUTTON_GPIO, GPIO_IN); gpio_pull_up(BUTTON_GPIO); //should there be any sort of debounce here? gpio_set_irq_enabled_with_callback(BUTTON_GPIO, GPIO_IRQ_EDGE_FALL, true, &button_callback); for (int i = 0; i < SINE_WAVE_TABLE_LEN; i++) { sine_wave_table[i] = 32767 * cosf(i * 2 * (float) (M_PI / SINE_WAVE_TABLE_LEN)); } for (int i = 0; i < BONGOSAMPLES; i++) { bongo_wave_table[i] = bongoSamples[i] * 256; //the sound sample web page is +/-1 128 so need to multiply this up :https://bitluni.net/wp-content/uploads/2018/03/WavetableEditor.html } struct audio_buffer_pool *ap = init_audio(); int beat_num = 0; float posn_low_sine = 0; int last_loop_posn = 0; bool bongo_sequence[] = {true, false, true, false, false, false, false, false}; bool low_sine_sequence[] = {true, false, false, true, false, false, false, false}; int16_t inputs[] = {0,0,0,0}; float volumes[] = {0.4,0.1,0.1,0.2}; int mixer_size = 4; int posn_echo = 0; enum audio_correction_mode m = audio_pwm_get_correction_mode(); m = fixed_dither; audio_pwm_set_correction_mode(m); while (true) { //there are three buffers, so presumably, this will get the next one rather than just using the same one over and over? //check this with Graham? struct audio_buffer *buffer = take_audio_buffer(ap, true); // is this the point the loop blocks waiting for free space? int16_t *samples = (int16_t *) buffer->buffer->bytes; for (uint i = 0; i < SAMPLES_PER_BUFFER; i++) { //if(posn_absolute > ECHOLEN) { posn_echo = posn_absolute - echo_len; } if (posn_absolute > (last_loop_posn + ((beat_num+1) * BEATFREQ))) { beat_num++; } if ( beat_num == BEATNUM ) { beat_num = 0; last_loop_posn = posn_absolute; } //track a 'virtual' position for the low_sine note. This allows us to use posn_absolute for beats & enveloping, but the virtual position for //wobbles additionally to give a tremello effect. //the alternative to this, I think, would be to feed the output into a buffer large enough to apply the tremello effect in there posn_low_sine = posn_low_sine + 1 + triangle_wobbler(2000,0.5,posn_absolute); //bongos inputs[0] = create_echo(no_envelope(bongo_wave_table, BONGOSAMPLES, 1, sequence(bongo_sequence, posn_absolute, beat_num, last_loop_posn)) , echo_table, ECHOBUFFERLEN, posn_absolute); // weird distorted sine wave inputs[1] = bitcrush(envelope(sine_wave_table, SINE_WAVE_TABLE_LEN, 24, posn_low_sine, sequence(low_sine_sequence, posn_absolute, beat_num, last_loop_posn), 5000, 10000, 15000, 40000),32768,8); //undistorted sound wave //inputs[1] = envelope(sine_wave_table, SINE_WAVE_TABLE_LEN, 8, posn_low_sine, sequence(low_sine_sequence, posn_absolute, beat_num, last_loop_posn), // 5000, 10000, 15000, 40000); // high pitched sine on button press /** inputs[2] = envelope(sine_wave_table, SINE_WAVE_TABLE_LEN, 32, posn_absolute, posn_absolute-button_last_pressed, 5000, 10000, 15000, 20000); **/ //echo of bongos inputs[3] = read_echo(echo_table, ECHOBUFFERLEN, posn_absolute, 2000); samples[i] = mixer (inputs, volumes, mixer_size); posn_absolute++; if (posn_absolute > 2000000000) { posn_absolute = 0;} // ugly hack. Should do something better --this will also break the sequencer -- only causes a problem after 2 1/2 hours, so could just leave it for now. } buffer->sample_count = buffer->max_sample_count; give_audio_buffer(ap, buffer); } return 0; }
kouxichao/ncnn
examples/print_data.h
#include <stdio.h> int print_data(ncnn::Mat &indata, int startrow, int num_print, char* name = NULL) { printf("%s(dim:%d,c:%d,h:%d,w:%d):\n", name, indata.dims, indata.c,indata.h,indata.w); int rows = num_print/indata.w; int len; for(size_t i = 0; i < rows + 1; i++) { printf("row_%d:\n", i); if(i == rows) len = num_print % indata.w; else len = indata.w; for(size_t j = 0; j < len; j++) { /* code */ printf("%d_%f\t", j, *((float*)indata.row(i+startrow) + j)); } printf("\n"); } // printf("\n"); }
kouxichao/ncnn
examples/crnn/text_recognization.h
<gh_stars>1-10 #ifndef TEXT_RECOGNIZATION_H #define TEXT_RECOGNIZATION_H typedef struct { //左上角开始顺时针点坐标 int x1; int y1; int x2; int y2; int x3; int y3; int x4; int y4; }DKSBox; typedef struct { //等待添加 bool lexicon; }DKSBoxTextRecognizationParam; char* minDistanceWord(char* result); void DKBoxTextRecognizationInit(); char* DKBoxTextRecognizationProcess(const char* rgbfilename, int iWidth, int iHeight, DKSBox box, DKSBoxTextRecognizationParam param); void DKBoxTextRecognizationEnd(); #endif
kouxichao/ncnn
src/layer/lstmcell.h
<filename>src/layer/lstmcell.h #ifndef LAYER_LSTMCell_H #define LAYER_LSTMCell_H #include "layer.h" namespace ncnn { class LSTMCell : public Layer { public: LSTMCell(); virtual int load_param(const ParamDict& pd); virtual int load_model(const ModelBin& mb); virtual int forward(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs, const Option& opt) const; public: // param int input_size; int hidden_size; // int num_output; // int weight_xc_data_size; // / int weight_hc_data_size; // model Mat weight_ih_data; Mat weight_hh_data; Mat bias_ih_data; Mat bias_hh_data; }; } // namespace ncnn #endif //LAYER_LSTMCell_H